File size: 8,202 Bytes
3ccaf5a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | """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" # deep red for the headline series
QLORA_C = "#2E7D32" # green for QLoRA comparator
FP16_C = "#333333" # dark grey
BASE_C = "#888888" # light grey
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
# ---------- Figure ----------
# Taller than the default to leave room for a 2-row legend below the
# x-axis without squeezing the headline plot.
fig, ax = plt.subplots(figsize=(5.8, 3.9))
# Shade the quantization gap: from quantized baseline up to FP16.
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")
# CI whiskers + markers + line for the prefix series.
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)
# Reference lines — drawn after the shading, before the headline series.
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}%)")
# Value labels above points (not below — below collides with lines/labels).
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")
# Callout — placed in the top-left empty space, above the headline line's
# rising arm, so it doesn't collide with the legend or the QLoRA ref line.
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:
# Anchor text at upper-left of the plot area (well away from the
# legend which sits lower-right below).
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)
# Y range — anchor so "gap" band is visible but headline series has room.
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)
# Quiet top-right metadata stamp (no inline title).
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")
# Legend as a dedicated strip below the x-axis label (not overlapping it).
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)
# Reserve bottom space explicitly so the legend doesn't crash into the
# x-axis label. Must be manual — constrained_layout doesn't know about
# a fig.legend added after axis creation.
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()
|