File size: 7,201 Bytes
a0d1de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Blend predictions from two or more fragility_report.py runs post hoc.

fragility_report.py's ``model`` row already beats
``same_features_joblevel_regression`` on the best backbone, so ensembling
with a job-level baseline on the *same* representation adds little. What's
untested is blending genuinely different representations (e.g. hf_finetune's
fine-tuned embedding + openai_embed's frozen one) that likely make different
errors on different jobs.

Requires each source run to have been produced with ``--dump-predictions``
(so ``<out-dir>/predictions/<featurizer>_<protocol>_seed<seed>.json`` exists)
using the *same* ``--dataset`` and ``--seeds`` for every source: splits are
deterministic in (dataset job ids, seed, break-rate strata) and independent of
featurizer, so two runs with matching dataset+seeds share test folds and can
be joined on ``base_id``.

Usage
-----
    python scripts/ensemble_fragility.py --seeds 0,1,2,3,4 \\
        --source "hf_finetune=outputs_fragility/gsmic_adv_hf_finetune/predictions/hf_finetune_text_probe_seed{seed}.json" \\
        --source "openai_embed=outputs_fragility/gsmic_adv_openai_embed/predictions/openai_embed_text_probe_seed{seed}.json" \\
        --out-dir outputs_fragility/gsmic_adv_ensemble_hf_finetune_openai
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np
from scipy.stats import rankdata, spearmanr

ROOT = Path(__file__).resolve().parents[1]


def _rho(a, b) -> float:
    a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
    ok = np.isfinite(a) & np.isfinite(b)
    if ok.sum() < 3 or np.std(a[ok]) < 1e-12 or np.std(b[ok]) < 1e-12:
        return float("nan")
    return float(spearmanr(a[ok], b[ok]).statistic)


def _mean_sd(vals: list[float]) -> tuple[float, float]:
    arr = np.asarray([v for v in vals if np.isfinite(v)], dtype=float)
    if len(arr) == 0:
        return float("nan"), float("nan")
    return float(arr.mean()), float(arr.std())


def _zscore(x: np.ndarray) -> np.ndarray:
    sd = x.std()
    return (x - x.mean()) / sd if sd > 1e-12 else x - x.mean()


def load_seed(sources: dict[str, str], seed: int) -> dict:
    """Load every source's prediction dump for one seed, joined on base_id."""
    per_source = {}
    for label, pattern in sources.items():
        path = Path(pattern.format(seed=seed))
        if not path.exists():
            raise SystemExit(
                f"missing prediction file for source '{label}' seed {seed}: {path}\n"
                f"(re-run fragility_report.py for that source with --dump-predictions "
                f"and matching --seeds)")
        per_source[label] = json.loads(path.read_text())

    ids_by_source = {label: d["base_id"] for label, d in per_source.items()}
    common = set(ids_by_source[next(iter(ids_by_source))])
    for label, ids in ids_by_source.items():
        common &= set(ids)
    if not common:
        raise SystemExit(
            f"seed {seed}: no base_id overlap across sources -- are they really the "
            f"same --dataset and --seeds?")
    common_sorted = sorted(common)
    n_total = len(ids_by_source[next(iter(ids_by_source))])
    if len(common) < n_total:
        print(f"  seed {seed}: {len(common)}/{n_total} test jobs shared across all "
              f"sources (rest dropped -- check --dataset/--seeds match)")

    preds: dict[str, np.ndarray] = {}
    target = None
    for label, d in per_source.items():
        idx = {bid: i for i, bid in enumerate(d["base_id"])}
        order = [idx[bid] for bid in common_sorted]
        preds[label] = np.asarray(d["pred_break_rate"])[order]
        tgt = np.asarray(d["target_break_rate"])[order]
        if target is None:
            target = tgt
        elif not np.allclose(target, tgt, atol=1e-6):
            raise SystemExit(
                f"seed {seed}: source '{label}' has a different target_break_rate for "
                f"shared base_ids -- sources were not trained on the same --dataset")
    return {"base_id": common_sorted, "target": target, "preds": preds}


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--source", action="append", required=True,
                    help="label=path_pattern, where the pattern contains a literal "
                         "'{seed}' placeholder. Give at least two.")
    ap.add_argument("--seeds", default="0,1,2,3,4")
    ap.add_argument("--out-dir", required=True)
    args = ap.parse_args()

    sources: dict[str, str] = {}
    for s in args.source:
        if "=" not in s:
            raise SystemExit(f"--source must be 'label=path_pattern', got: {s}")
        label, pattern = s.split("=", 1)
        sources[label] = pattern
    if len(sources) < 2:
        raise SystemExit("need at least two --source entries to ensemble")

    seeds = [int(s) for s in args.seeds.split(",")]
    labels = list(sources)
    per_seed_rows = []

    for seed in seeds:
        print(f"=== seed {seed} ===")
        data = load_seed(sources, seed)
        target = data["target"]
        row = {"seed": seed, "n_test": len(data["base_id"]), "individual": {}}
        for label in labels:
            row["individual"][label] = _rho(data["preds"][label], target)

        rank_stack = np.stack([rankdata(data["preds"][label]) for label in labels])
        mean_rank_pred = rank_stack.mean(axis=0)
        row["ensemble_mean_rank"] = _rho(mean_rank_pred, target)

        z_stack = np.stack([_zscore(data["preds"][label]) for label in labels])
        mean_z_pred = z_stack.mean(axis=0)
        row["ensemble_mean_z"] = _rho(mean_z_pred, target)

        print(f"  individual: " + ", ".join(f"{l}={row['individual'][l]:+.3f}" for l in labels))
        print(f"  ensemble(mean rank)={row['ensemble_mean_rank']:+.3f}  "
              f"ensemble(mean z)={row['ensemble_mean_z']:+.3f}")
        per_seed_rows.append(row)

    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    summary = {"sources": sources, "seeds": seeds, "per_seed": per_seed_rows, "aggregate": {}}
    lines = [
        "# Fragility ensemble", "",
        f"Sources: {', '.join(f'{l} ({p})' for l, p in sources.items())}", "",
        "| Method | break_rate rho (mean ± sd over seeds) |",
        "| --- | --- |",
    ]
    for label in labels:
        m, s = _mean_sd([r["individual"][label] for r in per_seed_rows])
        summary["aggregate"][label] = {"mean": m, "sd": s}
        lines.append(f"| {label} (individual) | {m:.3f} ± {s:.3f} |")
    for key, title in (("ensemble_mean_rank", "ensemble (mean rank)"),
                       ("ensemble_mean_z", "ensemble (mean z-score)")):
        m, s = _mean_sd([r[key] for r in per_seed_rows])
        summary["aggregate"][key] = {"mean": m, "sd": s}
        lines.append(f"| {title} | {m:.3f} ± {s:.3f} |")

    (out_dir / "summary.json").write_text(json.dumps(summary, indent=2))
    (out_dir / "report.md").write_text("\n".join(lines) + "\n")
    print(f"\nWrote {out_dir}/report.md and summary.json")


if __name__ == "__main__":
    main()