File size: 7,600 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 203 204 205 206 207 208 209 210 | """Render the baseline comparison figure (paper fig 7)."""
import argparse
import json
import os
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,
})
# Order matters: weakest → strongest reads left-to-right.
STRATEGIES = [
("random", "Random\n(no diagnosis)", "#B0B7C3"),
("failed_only", "Failed only\n(no type balancing)", "#F0A357"),
("silver_bullet", "Silver bullet\n(ours)", "#2E7D32"),
]
GREY_REF = "#999999"
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 _paired_p(base_out, rest_out, n_boot=5000):
common = sorted(set(base_out) & set(rest_out))
if not common:
return None
b = np.array([base_out[k] for k in common])
r = np.array([rest_out[k] for k in common])
rng = np.random.default_rng(0)
deltas = np.empty(n_boot)
for i in range(n_boot):
idx = rng.integers(0, len(common), size=len(common))
deltas[i] = r[idx].mean() - b[idx].mean()
return float(2 * min((deltas <= 0).mean(), (deltas >= 0).mean()))
def _load_outcomes(jsonl_path):
if not os.path.exists(jsonl_path):
return None
out = {}
with open(jsonl_path) as f:
for line in f:
t = json.loads(line)
out[t.get("problem_id")] = 1.0 if t.get("is_correct_final") else 0.0
return out
def _stars(p):
if p is None: return ""
if p < 0.001: return "***"
if p < 0.01: return "**"
if p < 0.05: return "*"
return ""
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--baseline-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()
base_out = _load_outcomes(os.path.join("results", "diagnosis",
args.quant, args.model,
f"{args.benchmark}_run0.jsonl"))
names, means, los, his, colors, stars = [], [], [], [], [], []
for strat_key, strat_label, color in STRATEGIES:
diag = os.path.join(args.baseline_root, strat_key, "diagnosis",
f"{args.benchmark}_run0.jsonl")
ci = _bootstrap(diag)
if ci is None:
continue
p = None
if base_out:
rest_out = _load_outcomes(diag)
if rest_out:
p = _paired_p(base_out, rest_out)
names.append(strat_label)
means.append(ci[0] * 100); los.append(ci[1] * 100); his.append(ci[2] * 100)
colors.append(color); stars.append(_stars(p))
if not names:
print("No baseline results found.")
return
# Reference levels.
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
fig, ax = plt.subplots(figsize=(5.3, 3.2), constrained_layout=True)
x = np.arange(len(names))
width = 0.5
# Shade the "quantization gap" region (baseline → FP16) in pale grey.
if base_acc is not None and fp16_acc is not None:
ax.axhspan(base_acc, fp16_acc, color="#EEEEEE", alpha=1.0, zorder=0)
for i, (m, lo, hi, c, s) in enumerate(zip(means, los, his, colors, stars)):
ax.bar(x[i], m, width, color=c, edgecolor="white", linewidth=0.9,
zorder=2)
# CI whisker
ax.plot([x[i], x[i]], [lo, hi], color="#333333", linewidth=1.0, zorder=3,
solid_capstyle="butt")
# Value label
ax.annotate(f"{m:.1f}", xy=(x[i], m), xytext=(0, 5),
textcoords="offset points", ha="center", va="bottom",
fontsize=9.5, color="#222", fontweight="bold")
# Significance star (offset above the value).
if s:
ax.annotate(s, xy=(x[i], hi), xytext=(0, 4),
textcoords="offset points", ha="center", va="bottom",
fontsize=11, color=c, fontweight="bold")
# Reference lines — labels anchored just OUTSIDE the right spine via
# axes fraction, so they sit clearly in the right-margin whitespace
# regardless of where bars end in data coordinates.
if base_acc is not None:
ax.axhline(base_acc, color=GREY_REF, linestyle=(0, (5, 3)),
linewidth=1.0, zorder=1)
ax.text(1.02, base_acc, f"Quantized\n{base_acc:.1f}%",
transform=ax.get_yaxis_transform(),
ha="left", va="center", fontsize=7.5, color=GREY_REF)
if fp16_acc is not None:
ax.axhline(fp16_acc, color="#333", linestyle=(0, (1, 2)),
linewidth=1.0, zorder=1)
ax.text(1.02, fp16_acc, f"FP16\n{fp16_acc:.1f}%",
transform=ax.get_yaxis_transform(),
ha="left", va="center", fontsize=7.5, color="#333")
ax.set_xticks(x)
ax.set_xticklabels(names)
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) if v is not None]
ax.set_ylim(min(ys) - 3, max(ys) + 5)
ax.set_xlim(-0.55, len(names) - 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")
# Footnote-size key for the stars.
fig.text(0.02, -0.03,
r"Paired-bootstrap $p$ vs. quantized baseline: $*$: $p<.05$ $**$: $p<.01$ $***$: $p<.001$",
ha="left", va="top", fontsize=7, color="#555")
os.makedirs(os.path.dirname(args.output), exist_ok=True)
fig.savefig(args.output)
plt.close(fig)
print(f" Paper fig 7 (baselines) saved: {args.output}")
if __name__ == "__main__":
main()
|