File size: 11,864 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""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


# ---------------------------------------------------------------------------
# Style (matches make_paper_figures.py exactly)
# ---------------------------------------------------------------------------

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"


# ---------------------------------------------------------------------------
# Accuracy helpers
# ---------------------------------------------------------------------------

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

    # Load gold answers for the benchmark
    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


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

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()

    # Discover ablation runs on disk: n50, n100, n250, n500, ...
    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)
    # FP16 upper-bound via LaTeX-aware eval (math_verify + SymPy). See
    # scripts/eval_accuracy.py for the brace-balanced extractor that fixes
    # the old naive string-match approach.
    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)

    # ---------- Figure ----------
    fig, ax = plt.subplots(figsize=(4.5, 3.0), constrained_layout=True)

    method_color = METHOD_COLOR.get(args.quant, "#4E79A7")

    # Main curve: restored accuracy vs N (with CI whiskers).
    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]

    # Per-point 95% CI whiskers (vertical error bars). Using whiskers rather
    # than a fill_between band, because with only 4 discrete N values a band
    # looks watery — whiskers feel more decisive.
    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)

    # Quantized baseline reference line
    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.)")

    # FP16 reference — only draw if we actually computed it (>0).
    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")

    # X axis — log scale so small N values are well-spaced.
    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)

    # Y axis — zoom to the data range with a bit of padding. NOT anchored to 0,
    # because clustering all data in the top fifth of the panel is a classic
    # amateur Q1 tell.
    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)

    # Numeric labels BELOW each point so they don't collide with the corner tag.
    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)

    # Corner metadata tag placed OUTSIDE the axes so it never overlaps data.
    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)

    # "+X pp over baseline" callout — anchored to the first point (N=50),
    # offset UP and LEFT so the arrow doesn't cross the rising data line.
    # (The previous placement at the best point shot its arrow back across
    # the data in the middle of the figure.)
    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"))

    # Place legend OUTSIDE the plot (right side), so the reference lines
    # (FP16 dotted, Quantized dashed) don't run through the legend labels.
    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()