File size: 8,833 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
"""Render the multi-seed robustness figure (paper fig 9).

Shows per-seed accuracy dots (jittered), mean bar, across-seed std whisker,
and the within-cell bootstrap CI as a shaded band — so a reviewer can see
two sources of uncertainty in one frame.

If fewer than 2 seeds have completed, we drop the std whisker (it's
meaningless with n=1) and annotate the figure so the reader knows.
"""

import argparse
import glob
import json
import os
import re
import sys
from typing import List, Tuple

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,
})

COLOR_BASE = "#B0B7C3"
COLOR_REST = "#2E7D32"


def _trace_correctness(trace: dict, golds: dict) -> float:
    """Return 1.0 if this trace's final answer matches gold, else 0.0.

    Prefers the diagnoser's `is_correct_final` label when present;
    otherwise falls back to math_verify on the raw inference output.
    This lets the figure read from `inference/` for seeds where
    `diagnosis/` hasn't been produced (e.g. multi-seed runs where only
    a single FP16 reference exists)."""
    if "is_correct_final" in trace:
        return 1.0 if trace.get("is_correct_final") else 0.0
    try:
        from eval_accuracy import extract_pred, _equiv
    except ImportError:
        return 0.0
    pred = extract_pred(trace)
    gold = trace.get("gold_answer") or golds.get(trace.get("problem_id", ""), "")
    return 1.0 if _equiv(pred, gold) else 0.0


def _find_per_seed_files(base_dir: str, benchmark: str) -> dict:
    """Return {seed: path} preferring inference/<f> over diagnosis/<f>.

    Multi-seed runs typically have full inference for every seed but only
    a single diagnosis run (since DTW-based step diagnosis needs a paired
    FP16 reference and we run only one). Mixing the two correctness
    judges across seeds produced bogus across-seed std (the diagnosis
    pipeline's `is_correct_final` is more permissive than the figure's
    fallback `_equiv` / math_verify path). Using inference for all seeds
    keeps the same judge across the comparison."""
    found: dict = {}
    for sub in ("inference", "diagnosis"):
        for fp in sorted(glob.glob(os.path.join(base_dir, sub, f"{benchmark}_run*.jsonl"))):
            m = re.search(r"run(\d+)\.jsonl$", fp)
            if not m:
                continue
            seed = int(m.group(1))
            found.setdefault(seed, fp)
    return found


def seed_accuracies(base_dir: str, benchmark: str, golds: dict) -> List[Tuple[int, float]]:
    out = []
    for seed, fp in sorted(_find_per_seed_files(base_dir, benchmark).items()):
        n, c = 0, 0.0
        with open(fp) as f:
            for line in f:
                t = json.loads(line)
                n += 1
                c += _trace_correctness(t, golds)
        if n > 0:
            out.append((seed, c / n))
    return out


def bootstrap_ci(base_dir: str, benchmark: str, golds: dict, n_boot=5000):
    v = []
    for seed, fp in sorted(_find_per_seed_files(base_dir, benchmark).items()):
        with open(fp) as f:
            for line in f:
                t = json.loads(line)
                v.append(_trace_correctness(t, golds))
    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("--multiseed-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()

    try:
        from eval_accuracy import _load_gold
        golds = _load_gold(args.benchmark)
    except Exception:
        golds = {}

    cells = {}
    for cfg, color in [("base", COLOR_BASE), ("restored", COLOR_REST)]:
        base_dir = os.path.join(args.multiseed_root, cfg)
        seeds = seed_accuracies(base_dir, args.benchmark, golds)
        ci = bootstrap_ci(base_dir, args.benchmark, golds)
        if not seeds or ci is None:
            continue
        cells[cfg] = {"seeds": seeds, "ci": ci, "color": color}

    if not cells:
        print("No multi-seed diagnosis data found.")
        return

    n_seeds = max(len(v["seeds"]) for v in cells.values())

    fig, ax = plt.subplots(figsize=(4.6, 3.2), constrained_layout=True)

    xpos = {"base": 0, "restored": 1}
    xticks, xlabels = [], []

    for cfg, info in cells.items():
        x = xpos[cfg]
        xticks.append(x); xlabels.append(cfg.capitalize())
        seeds = info["seeds"]
        color = info["color"]

        accs = np.array([s[1] for s in seeds]) * 100
        mean = float(accs.mean())
        std  = float(accs.std(ddof=0)) if len(seeds) > 1 else 0.0
        boot_mean, lo, hi = (v * 100 for v in info["ci"])

        # Within-cell bootstrap CI as a shaded rectangle.
        ax.fill_between([x - 0.28, x + 0.28], [lo, lo], [hi, hi],
                        color=color, alpha=0.22, linewidth=0, zorder=1)

        # Mean bar (horizontal line across the cell width).
        ax.plot([x - 0.28, x + 0.28], [mean, mean], color=color,
                linewidth=2.6, solid_capstyle="butt", zorder=3)

        # Across-seed std whisker — only if we have >=2 seeds.
        if len(seeds) >= 2:
            ax.plot([x, x], [mean - std, mean + std],
                    color=color, linewidth=1.6, alpha=0.85, zorder=3)

        # Per-seed dots, lightly jittered in x.
        rng = np.random.default_rng(0)
        for j, (_seed, a) in enumerate(seeds):
            jx = x + rng.uniform(-0.10, 0.10)
            ax.scatter(jx, a * 100, s=36, color=color,
                       edgecolor="white", linewidth=1.0, zorder=4)

        # Label above the bar.
        if len(seeds) >= 2:
            label = f"{mean:.1f}  ±{std:.1f}"
        else:
            label = f"{mean:.1f}"
        ax.annotate(label, xy=(x, mean), xytext=(0, 18),
                    textcoords="offset points", ha="center", va="bottom",
                    fontsize=10, color=color, fontweight="bold")

    ax.set_xticks(xticks)
    ax.set_xticklabels(xlabels)
    ax.set_ylabel("Accuracy (%)")
    ax.yaxis.grid(True, linewidth=0.4, color="#DDDDDD")
    ax.set_axisbelow(True)

    all_y = []
    for info in cells.values():
        all_y.extend([s[1] * 100 for s in info["seeds"]])
        all_y.extend([info["ci"][1] * 100, info["ci"][2] * 100])
    ax.set_ylim(min(all_y) - 4, max(all_y) + 7)
    ax.set_xlim(-0.55, 1.55)

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

    # If only one seed ran, flag it so a reader doesn't misread ±0.0.
    if n_seeds < 2:
        fig.text(0.02, -0.03,
                 "Note: only 1 seed completed in this snapshot; resume "
                 "run_multi_seed.sh for full 3-seed variance.",
                 ha="left", va="top", fontsize=7, color="#C03A2B", style="italic")

    # Legend explaining what the visual elements mean.
    handles = [
        plt.Line2D([0], [0], marker="o", color="gray", markersize=6,
                   linestyle="", label="per-seed"),
        plt.Line2D([0], [0], color="gray", linewidth=2.4, label="mean"),
        plt.Line2D([0], [0], color="gray", linewidth=1.6, alpha=0.6,
                   label="±1 std (across seeds)"),
        plt.Rectangle((0, 0), 1, 1, color="gray", alpha=0.22,
                      label="95% CI (bootstrap over problems)"),
    ]
    ax.legend(handles=handles, loc="lower right", handlelength=1.6,
              handletextpad=0.5, borderpad=0.4, labelspacing=0.5)

    os.makedirs(os.path.dirname(args.output), exist_ok=True)
    fig.savefig(args.output)
    plt.close(fig)
    print(f"  Paper fig 9 (multi-seed) saved: {args.output}")


if __name__ == "__main__":
    main()