File size: 10,254 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
"""Bootstrap confidence intervals and paired significance tests.

Reads the per-problem diagnosed traces in results/diagnosis/ and, for each
(model, benchmark, quantization) cell, computes:

    - 95% bootstrap CIs for accuracy, average FFS, and ECR (5000 resamples).
    - A full SSR curve CI band (per-depth bootstrap).
    - For (base, restored) pairs: a paired bootstrap significance test on
      ΔAccuracy (uses the SAME sampled problem ids for base and restored in
      each resample, so the null cancels properly).

Emits one *_ci.json next to each existing *_metrics.json, plus one pair-level
*_sig.json per (model, benchmark, method) restoration comparison.

These are real, defensible uncertainty estimates given a SINGLE inference run:
they capture variance across problems, not variance across seeds. For a Q1
paper you want both — this script delivers the first half for free; the
seed-variance half requires re-running inference with NUM_RUNS>=3.
"""

from __future__ import annotations

import argparse
import glob
import json
import os
import re
from typing import Dict, List, Optional, Tuple

import numpy as np


BENCHMARKS = ("gsm8k", "math500", "gpqa")
QUANT_METHODS = ("awq_w4", "gptq_w4", "bnb_nf4_w4")


# ---------------------------------------------------------------------------
# Per-problem metric extraction
# ---------------------------------------------------------------------------

def first_failure_step(steps: List[dict]) -> Optional[int]:
    for s in steps:
        if s.get("is_correct") is False:
            return s.get("index")
    return None


def cascade_rate(steps: List[dict]) -> Optional[float]:
    """Fraction of steps AFTER the first failure that are also incorrect.
    Returns None for problems with no failure (so the aggregate only averages
    over problems that actually failed — matches aggregate_metrics.ecr)."""
    ffs = first_failure_step(steps)
    if ffs is None:
        return None
    tail = [s for s in steps if s.get("index", 0) > ffs]
    if not tail:
        return None
    return sum(1 for s in tail if s.get("is_correct") is False) / len(tail)


def survival_at_depth(steps: List[dict], depth: int) -> Optional[bool]:
    """True if all of steps[0..depth] are correct, None if the trace is shorter."""
    if len(steps) <= depth:
        return None
    return all(s.get("is_correct", True) for s in steps[: depth + 1])


def load_per_problem(jsonl_path: str) -> List[dict]:
    """Return a list of per-problem records with the fields bootstrapping needs."""
    out = []
    with open(jsonl_path) as f:
        for line in f:
            t = json.loads(line)
            steps = t.get("steps", []) or []
            out.append({
                "problem_id":  t.get("problem_id"),
                "is_correct":  bool(t.get("is_correct_final", False)),
                "ffs":         first_failure_step(steps),
                "ecr":         cascade_rate(steps),
                "step_correct": [s.get("is_correct", True) for s in steps],
            })
    return out


# ---------------------------------------------------------------------------
# Bootstrap utilities
# ---------------------------------------------------------------------------

def _ci(samples: np.ndarray, alpha: float = 0.05) -> Tuple[float, float]:
    lo, hi = np.percentile(samples, [100 * alpha / 2, 100 * (1 - alpha / 2)])
    return float(lo), float(hi)


def bootstrap_single(records: List[dict], n_boot: int = 5000,
                     rng: Optional[np.random.Generator] = None) -> dict:
    """Bootstrap accuracy, avg_ffs, ecr, and the SSR curve for one cell."""
    rng = rng or np.random.default_rng(0)
    n = len(records)
    if n == 0:
        return {}

    acc_vec = np.array([r["is_correct"] for r in records], dtype=float)
    ffs_vec = np.array([r["ffs"] if r["ffs"] is not None else np.nan for r in records], dtype=float)
    ecr_vec = np.array([r["ecr"] if r["ecr"] is not None else np.nan for r in records], dtype=float)

    # SSR per depth: for problems with enough steps, is the trace "alive" at depth d?
    max_depth = 30
    alive = np.full((n, max_depth), np.nan)
    for i, r in enumerate(records):
        steps = r["step_correct"]
        for d in range(max_depth):
            if d < len(steps):
                alive[i, d] = float(all(steps[: d + 1]))

    acc_samples = np.empty(n_boot)
    ffs_samples = np.empty(n_boot)
    ecr_samples = np.empty(n_boot)
    ssr_samples = np.full((n_boot, max_depth), np.nan)

    for b in range(n_boot):
        idx = rng.integers(0, n, size=n)
        acc_samples[b] = acc_vec[idx].mean()
        f = ffs_vec[idx]
        ffs_samples[b] = np.nanmean(f) if np.any(~np.isnan(f)) else np.nan
        e = ecr_vec[idx]
        ecr_samples[b] = np.nanmean(e) if np.any(~np.isnan(e)) else np.nan
        for d in range(max_depth):
            col = alive[idx, d]
            valid = ~np.isnan(col)
            if valid.any():
                ssr_samples[b, d] = col[valid].mean()

    def summarize(x):
        x = x[~np.isnan(x)]
        if x.size == 0:
            return None
        lo, hi = _ci(x)
        return {"mean": float(x.mean()), "ci_lo": lo, "ci_hi": hi}

    ssr_ci_lo = np.nanpercentile(ssr_samples, 2.5, axis=0)
    ssr_ci_hi = np.nanpercentile(ssr_samples, 97.5, axis=0)
    ssr_mean = np.nanmean(ssr_samples, axis=0)

    return {
        "n": int(n),
        "accuracy": summarize(acc_samples),
        "avg_ffs":  summarize(ffs_samples),
        "ecr":      summarize(ecr_samples),
        "ssr_curve_ci": {
            "mean":  [None if np.isnan(v) else float(v) for v in ssr_mean],
            "ci_lo": [None if np.isnan(v) else float(v) for v in ssr_ci_lo],
            "ci_hi": [None if np.isnan(v) else float(v) for v in ssr_ci_hi],
        },
    }


def paired_bootstrap_sig(base: List[dict], rest: List[dict],
                         n_boot: int = 5000,
                         rng: Optional[np.random.Generator] = None) -> dict:
    """Paired bootstrap on ΔAccuracy between base and restored.

    Problems are paired by problem_id. For each bootstrap resample we draw the
    SAME indices in both conditions, compute the delta, and accumulate. The
    two-sided p-value is 2 * min(P(Δ<=0), P(Δ>=0)).
    """
    rng = rng or np.random.default_rng(0)
    base_by_id = {r["problem_id"]: r for r in base}
    rest_by_id = {r["problem_id"]: r for r in rest}
    shared = sorted(set(base_by_id) & set(rest_by_id))
    if not shared:
        return {"n_pairs": 0}

    b_vec = np.array([base_by_id[pid]["is_correct"] for pid in shared], dtype=float)
    r_vec = np.array([rest_by_id[pid]["is_correct"] for pid in shared], dtype=float)

    n = len(shared)
    deltas = np.empty(n_boot)
    for i in range(n_boot):
        idx = rng.integers(0, n, size=n)
        deltas[i] = r_vec[idx].mean() - b_vec[idx].mean()

    observed = float(r_vec.mean() - b_vec.mean())
    p_two = 2 * min((deltas <= 0).mean(), (deltas >= 0).mean())
    lo, hi = _ci(deltas)
    return {
        "n_pairs": int(n),
        "delta_acc_observed": observed,
        "delta_acc_ci_lo": lo,
        "delta_acc_ci_hi": hi,
        "p_value": float(p_two),
    }


# ---------------------------------------------------------------------------
# CLI glue
# ---------------------------------------------------------------------------

def _discover_cells(diagnosis_dir: str):
    """Yield (model, benchmark, quant, jsonl_path) tuples for everything on disk."""
    for quant_dir in sorted(glob.glob(os.path.join(diagnosis_dir, "*"))):
        if not os.path.isdir(quant_dir):
            continue
        quant = os.path.basename(quant_dir)
        for model_dir in sorted(glob.glob(os.path.join(quant_dir, "*"))):
            if not os.path.isdir(model_dir):
                continue
            model = os.path.basename(model_dir)
            for jsonl in sorted(glob.glob(os.path.join(model_dir, "*_run0.jsonl"))):
                base = os.path.basename(jsonl)
                m = re.match(r"(.+)_run0\.jsonl$", base)
                if not m:
                    continue
                bench = m.group(1)
                if bench not in BENCHMARKS:
                    continue
                yield model, bench, quant, jsonl


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--diagnosis", default="results/diagnosis",
                        help="Root diagnosis dir (quant/model/<bench>_run0.jsonl)")
    parser.add_argument("--output", default="results/metrics",
                        help="Where to drop *_ci.json and *_sig.json")
    parser.add_argument("--n-boot", type=int, default=5000)
    parser.add_argument("--seed", type=int, default=0)
    args = parser.parse_args()

    os.makedirs(args.output, exist_ok=True)
    rng = np.random.default_rng(args.seed)

    # --- Phase A: single-cell CIs ------------------------------------------
    cells = list(_discover_cells(args.diagnosis))
    print(f"Found {len(cells)} diagnosis cells to bootstrap")

    per_problem_cache: Dict[Tuple[str, str, str], List[dict]] = {}
    for model, bench, quant, jsonl in cells:
        records = load_per_problem(jsonl)
        per_problem_cache[(model, bench, quant)] = records
        ci = bootstrap_single(records, n_boot=args.n_boot, rng=rng)
        out_path = os.path.join(args.output, f"{model}_{quant}_{bench}_run0_ci.json")
        with open(out_path, "w") as f:
            json.dump(ci, f, indent=2)
    print(f"  wrote {len(cells)} *_ci.json files")

    # --- Phase B: paired significance (base vs restored) --------------------
    n_sig = 0
    for (model, bench, quant), base_recs in per_problem_cache.items():
        if quant.endswith("_restored"):
            continue
        rest_recs = per_problem_cache.get((model, bench, quant + "_restored"))
        if not rest_recs:
            continue
        sig = paired_bootstrap_sig(base_recs, rest_recs, n_boot=args.n_boot, rng=rng)
        out_path = os.path.join(args.output, f"{model}_{quant}_{bench}_run0_sig.json")
        with open(out_path, "w") as f:
            json.dump(sig, f, indent=2)
        n_sig += 1
    print(f"  wrote {n_sig} *_sig.json files (paired base vs restored)")


if __name__ == "__main__":
    main()