| """Render the prompt-prefix injection figure (paper fig 10). |
| |
| This is the paper's new headline result: training-free prefix injection |
| beats training-based QLoRA restoration. The figure is designed to make |
| that claim read in under 2 seconds. |
| """ |
|
|
| import argparse |
| import glob |
| 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, |
| }) |
|
|
| PRIMARY = "#C03A2B" |
| QLORA_C = "#2E7D32" |
| FP16_C = "#333333" |
| BASE_C = "#888888" |
|
|
|
|
| def _bootstrap(jsonl_path, n_boot=5000): |
| if not os.path.exists(jsonl_path): |
| return None |
| v = [] |
| with open(jsonl_path) as f: |
| for line in f: |
| t = json.loads(line) |
| v.append(1.0 if t.get("is_correct_final") else 0.0) |
| if not v: |
| return None |
| v = np.array(v) |
| rng = np.random.default_rng(0) |
| s = np.empty(n_boot) |
| for i in range(n_boot): |
| idx = rng.integers(0, len(v), size=len(v)) |
| s[i] = v[idx].mean() |
| return float(v.mean()), float(np.percentile(s, 2.5)), float(np.percentile(s, 97.5)) |
|
|
|
|
| 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("--segmented", default="results/segmented") |
| parser.add_argument("--output", required=True) |
| args = parser.parse_args() |
|
|
| ks, means, los, his = [], [], [], [] |
| for entry in sorted(os.listdir(args.sweep_root)): |
| m = re.match(r"k(\d+)$", entry) |
| if not m: |
| continue |
| k = int(m.group(1)) |
| diag = os.path.join(args.sweep_root, entry, "diagnosis", f"{args.benchmark}_run0.jsonl") |
| ci = _bootstrap(diag) |
| if ci is None: |
| continue |
| ks.append(k); means.append(ci[0] * 100); los.append(ci[1] * 100); his.append(ci[2] * 100) |
|
|
| if not ks: |
| print("No prefix-injection data found.") |
| return |
|
|
| idx = np.argsort(ks) |
| ks = [ks[i] for i in idx]; means = [means[i] for i in idx] |
| los = [los[i] for i in idx]; his = [his[i] for i in idx] |
|
|
| base_path = os.path.join(args.metrics, f"{args.model}_{args.quant}_{args.benchmark}_run0_metrics.json") |
| base_acc = json.load(open(base_path))["accuracy"] * 100 if os.path.exists(base_path) else None |
|
|
| from eval_accuracy import accuracy as _lv_acc |
| fp16_jsonl = os.path.join(args.segmented, "fp16", args.model, f"{args.benchmark}_run0.jsonl") |
| fp16_v = _lv_acc(fp16_jsonl, args.benchmark) |
| fp16_acc = fp16_v * 100 if fp16_v else None |
|
|
| rest_path = os.path.join(args.metrics, f"{args.model}_{args.quant}_restored_{args.benchmark}_run0_metrics.json") |
| rest_acc = json.load(open(rest_path))["accuracy"] * 100 if os.path.exists(rest_path) else None |
|
|
| |
| |
| |
| fig, ax = plt.subplots(figsize=(5.8, 3.9)) |
|
|
| |
| if base_acc is not None and fp16_acc is not None: |
| ax.axhspan(base_acc, fp16_acc, color="#EDEDED", alpha=1.0, zorder=0, |
| label="_gap") |
|
|
| |
| for x, m, lo, hi in zip(ks, means, los, his): |
| ax.plot([x, x], [lo, hi], color=PRIMARY, linewidth=1.4, alpha=0.5, zorder=2, |
| solid_capstyle="butt") |
| ax.plot(ks, means, "-", color=PRIMARY, linewidth=2.4, zorder=3, |
| label="Prompt-prefix injection (ours, training-free)") |
| ax.plot(ks, means, "o", color=PRIMARY, markersize=7, |
| markeredgecolor="white", markeredgewidth=1.3, zorder=4) |
|
|
| |
| if base_acc is not None: |
| ax.axhline(base_acc, color=BASE_C, linestyle=(0, (5, 3)), linewidth=1.0, |
| zorder=1, label=f"Quantized baseline ({base_acc:.1f}%)") |
| if rest_acc is not None: |
| ax.axhline(rest_acc, color=QLORA_C, linestyle=(0, (3, 2)), linewidth=1.2, |
| zorder=1, label=f"QLoRA restored ({rest_acc:.1f}%)") |
| if fp16_acc is not None: |
| ax.axhline(fp16_acc, color=FP16_C, linestyle=(0, (1, 2)), linewidth=1.0, |
| zorder=1, label=f"FP16 ({fp16_acc:.1f}%)") |
|
|
| |
| for x, m, hi in zip(ks, means, his): |
| ax.annotate(f"{m:.1f}", xy=(x, m), xytext=(0, 10), |
| textcoords="offset points", ha="center", va="bottom", |
| fontsize=9, color=PRIMARY, fontweight="bold") |
|
|
| |
| |
| if rest_acc is not None: |
| crossover_k = None; crossover_m = None |
| for x, m in zip(ks, means): |
| if m >= rest_acc: |
| crossover_k = x; crossover_m = m |
| break |
| if crossover_k is not None: |
| |
| |
| ax.annotate( |
| "matches QLoRA here\n(zero training)", |
| xy=(crossover_k, crossover_m), |
| xytext=(0.02, 0.78), textcoords="axes fraction", |
| fontsize=8.5, color=QLORA_C, ha="left", va="top", |
| arrowprops=dict(arrowstyle="->", color=QLORA_C, lw=0.8, |
| shrinkA=2, shrinkB=4, |
| connectionstyle="arc3,rad=0.25"), |
| ) |
|
|
| ax.set_xticks(ks) |
| ax.set_xlabel(r"$k$ — number of FP16 reference steps injected into the prompt", labelpad=4) |
| ax.set_ylabel("Accuracy (%)") |
| ax.yaxis.grid(True, linewidth=0.4, color="#DDDDDD") |
| ax.set_axisbelow(True) |
|
|
| |
| ys = means + los + his + [v for v in (base_acc, fp16_acc, rest_acc) if v is not None] |
| ax.set_ylim(min(ys) - 3.5, max(ys) + 6) |
|
|
| |
| 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="#555555") |
|
|
| |
| handles, labels = ax.get_legend_handles_labels() |
| pairs = [(h, l) for h, l in zip(handles, labels) if l != "_gap"] |
| if pairs: |
| fig.legend([p[0] for p in pairs], [p[1] for p in pairs], |
| loc="lower center", bbox_to_anchor=(0.5, 0.01), |
| ncol=2, handlelength=2.4, handletextpad=0.6, |
| columnspacing=1.8, labelspacing=0.5) |
|
|
| |
| |
| |
| fig.subplots_adjust(bottom=0.28, top=0.92, left=0.12, right=0.97) |
|
|
| os.makedirs(os.path.dirname(args.output), exist_ok=True) |
| fig.savefig(args.output) |
| plt.close(fig) |
| print(f" Paper fig 10 (prefix injection) saved: {args.output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|