File size: 14,361 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
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
#!/usr/bin/env python
"""Downstream utility: difficulty-aware curation / targeted robustness eval.

Addresses the reviewer critique *"you motivate difficulty-aware curation and
targeted robustness evaluation, then never do either"*. The paper's downstream
promise is a *ranking* one: under a fixed inspection/eval budget ``k``, surface
the most fragile tasks near the top of a shortlist. This script runs exactly
that selection -> outcome experiment and shows whether the SCE predictions win
over the non-causal alternatives.

Protocol (per seed):
  1. Load the config's real labeled pairs, take the same stratified 70/30
     holdout split used everywhere else (``causal_difficulty.eval.reports._split``).
  2. Train the SCE (diff contrast head) on the train split, exactly as
     ``scripts/paper_supports_real.py`` does, and compute per-holdout-job
     predicted difficulty for each method:
       * SCE D^perp (ours, deconfounded)      -- cross-fitted residual of the
                                                 contrast head vs complexity
       * SCE D_avg contrast (ours)            -- mean predicted twin effect
       * Random                               -- budget-matched random ranking
       * Surface length                       -- input-length heuristic
       * Score-predictor                      -- single-tower Y(J) regressor
       * Amortized IRT difficulty             -- published amortized-eval rival
                                                 (only if a GSM8K model pool is
                                                 available for this config)
  3. For a grid of budgets ``k`` (both absolute and as a fraction of the
     holdout), take each method's top-k and report, against the *measured*
     causal difficulty ``tau`` (= ``d_obs``):
       * recall@k     -- fraction of all truly-fragile jobs captured in the top-k
       * precision@k  -- purity of the shortlist
       * captured tau -- mean measured ``d_obs`` over the selected top-k
                         (the fragility a downstream user actually inspects)
     A "truly fragile" job is ``d_obs > fragile_threshold`` (config value).

Metrics are averaged over ``--seeds`` (mean +/- std) so the win is reported
with honest seed variance -- the same standard the invariance study already
holds itself to.

Usage
-----
    python scripts/downstream_curation.py --config gsmic_adv_m9_4omini
    python scripts/downstream_curation.py --config gsmic_adv_m9_4omini \\
        --seeds 7 42 123 --budgets-frac 0.05 0.10 0.20 \\
        --pool data/gsm8k_model_pool.json
"""
from __future__ import annotations

import argparse
import json
import statistics
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
sys.path.insert(0, str(Path(__file__).resolve().parent))

import numpy as np

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


def _run_one_seed(cfg, config_name, seed, complexity_proxy, pool_path, threshold):
    """Train once and return {method: predicted difficulty over holdout}, plus
    the measured target and the fragile threshold for that split."""
    import torch

    from causal_difficulty.baselines import (
        AmortizedIRTBaseline, LengthBaseline, ScorePredictorBaseline)
    from causal_difficulty.encoders import build_encoder
    from causal_difficulty.eval.deconfound import cross_fitted_residual
    from causal_difficulty.eval.reports import _split
    from causal_difficulty.io_utils import read_labeled_pairs
    from causal_difficulty.models.train import build_sce, train
    from causal_difficulty.schemas import LabeledPair

    # _aggregate lives in the sibling script; reuse it verbatim so the job-level
    # aggregation (complexity proxy, twin_texts, d_avg/d_wc) matches the C1/C2 tables.
    from paper_supports_real import _aggregate

    pairs, pairs_path = read_labeled_pairs(cfg, config_name, LabeledPair)
    if not pairs:
        raise FileNotFoundError(f"No labeled pairs at {pairs_path}.")

    stratified = cfg.eval.get("stratified_split", False)
    holdout_frac = cfg.eval.get("holdout_frac", 0.3)
    train_pairs, hold_pairs = _split(pairs, holdout_frac, seed, stratified=stratified)
    train_agg = _aggregate(train_pairs, complexity_proxy=complexity_proxy)
    hold_agg = _aggregate(hold_pairs, complexity_proxy=complexity_proxy)
    train_ids = sorted(train_agg.keys())
    hold_ids = sorted(hold_agg.keys())

    base_texts_train = [train_agg[b].base_text for b in train_ids]
    base_texts_hold = [hold_agg[b].base_text for b in hold_ids]
    measured_avg_hold = np.array([hold_agg[b].d_avg for b in hold_ids])
    complexity_hold = np.array([hold_agg[b].complexity for b in hold_ids])
    twins_by_base_hold = {b: hold_agg[b].twin_texts for b in hold_ids}

    encoder = build_encoder(cfg)
    sce = build_sce(cfg, encoder, contrast_mode="diff")
    train(sce, train_pairs, cfg, stage="both",
          base_texts_pool=[p.base_text for p in train_pairs], seed=seed)
    sce.eval()

    def _job_contrast(ids, base_id_texts, twins_by_base):
        out = []
        with torch.no_grad():
            for b, btext in zip(ids, base_id_texts):
                twins = twins_by_base.get(b, [])
                if not twins:
                    out.append(0.0)
                    continue
                vals = sce.predict_contrast([btext] * len(twins), twins).cpu().numpy()
                out.append(float(np.mean(vals)))
        return np.array(out, dtype=float)

    sce_contrast_avg_hold = _job_contrast(hold_ids, base_texts_hold, twins_by_base_hold)
    # deconfounded prediction: cross-fitted residual of the contrast head vs C
    # (identical estimator to paper_supports_real.py --fix-leakage).
    d_perp_hat_hold, _ = cross_fitted_residual(
        complexity_hold, sce_contrast_avg_hold, n_folds=5, seed=seed)

    embed_fn = lambda ts: encoder.encode(ts)  # noqa: E731
    length_pred = LengthBaseline().fit(train_pairs).predict_job_difficulty(base_texts_hold)
    score_pred = (ScorePredictorBaseline(embed_fn).fit(train_pairs)
                  .predict_job_difficulty(base_texts_hold))

    methods = {
        "SCE D^perp (ours)": d_perp_hat_hold,
        "SCE D_avg contrast (ours)": sce_contrast_avg_hold,
        "Surface length": length_pred,
        "Score-predictor": score_pred,
    }

    if pool_path is not None and Path(pool_path).exists():
        try:
            from causal_difficulty.eval.gsmic_adv_deconf import build_b_j_map
            target_model = cfg.get("model", None) or cfg.eval.get("model", "gpt-4o-mini")
            b_j_map, _meta = build_b_j_map(
                [p.base_id for p in pairs], pool_path, target_model=target_model)
            if b_j_map:
                amort = (AmortizedIRTBaseline(embed_fn, b_j_map)
                         .fit(train_pairs))
                methods["Amortized IRT difficulty"] = amort.predict_job_difficulty(base_texts_hold)
        except Exception as exc:  # pool missing/misaligned -> skip cleanly
            print(f"  (amortized-IRT baseline skipped: {exc})")

    return methods, measured_avg_hold, float(threshold), pairs_path


def _curation_metrics(pred, measured, threshold, budgets_abs):
    from causal_difficulty.eval.metrics import precision_at_k, recall_at_k
    n = len(measured)
    rows = {}
    for k in budgets_abs:
        k = min(k, n)
        top = np.argsort(-np.asarray(pred))[:k]
        rows[k] = {
            "recall@k": recall_at_k(pred, measured, threshold, k),
            "precision@k": precision_at_k(pred, measured, threshold, k),
            "captured_tau": float(np.mean(measured[top])),
        }
    return rows


def main() -> None:
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--config", default="gsmic_adv_m9_4omini")
    parser.add_argument("--seeds", nargs="+", type=int, default=[7, 42, 123])
    parser.add_argument("--complexity-proxy", default="y_base_mean",
                        help="Complexity proxy for the D^perp residualization "
                             "(default y_base_mean, matching the C2 headline).")
    parser.add_argument("--budgets-frac", nargs="+", type=float,
                        default=[0.05, 0.10, 0.20],
                        help="Budgets as a fraction of the holdout set.")
    parser.add_argument("--budgets-abs", nargs="+", type=int, default=[10, 25],
                        help="Absolute budgets k.")
    parser.add_argument("--n-random-repeats", type=int, default=200,
                        help="Random-ranking baseline is averaged over this many draws per seed.")
    parser.add_argument("--pool", default=str(ROOT / "data" / "gsm8k_model_pool.json"),
                        help="GSM8K model pool for the amortized-IRT baseline "
                             "(skipped if absent).")
    parser.add_argument("--fragile-threshold", type=float, default=None)
    parser.add_argument("--out-dir", default=None)
    args = parser.parse_args()

    from causal_difficulty.config import load_config
    from causal_difficulty.eval.metrics import precision_at_k, recall_at_k

    cfg = load_config(args.config)
    threshold = (args.fragile_threshold if args.fragile_threshold is not None
                 else cfg.eval.get("fragile_threshold", 0.05))
    out_dir = (Path(args.out_dir) if args.out_dir
               else ROOT / "outputs_real_supports" / f"{args.config}_curation")
    out_dir.mkdir(parents=True, exist_ok=True)

    print(f"Config           : {args.config}")
    print(f"Seeds            : {args.seeds}")
    print(f"Complexity proxy : {args.complexity_proxy}")
    print(f"Fragile threshold: {threshold}")

    # accumulate per-(method, k) metric lists across seeds
    per_seed_rows: list[dict] = []
    method_names: list[str] = []
    budgets_used: list[int] = []
    rng_master = np.random.RandomState(0)

    for seed in args.seeds:
        print(f"\n=== seed {seed} ===")
        methods, measured, thr, pairs_path = _run_one_seed(
            cfg, args.config, seed, args.complexity_proxy, args.pool, threshold)
        n_hold = len(measured)
        n_fragile = int((measured > thr).sum())
        print(f"  holdout jobs={n_hold}  truly-fragile={n_fragile}")

        budgets_abs = sorted(set(
            [max(1, int(round(f * n_hold))) for f in args.budgets_frac]
            + [k for k in args.budgets_abs if k <= n_hold]))
        budgets_used = budgets_abs

        seed_result: dict[str, dict] = {}
        for name, pred in methods.items():
            seed_result[name] = _curation_metrics(pred, measured, thr, budgets_abs)
        # random ranking, averaged over many draws
        rand_rows = {k: {"recall@k": [], "precision@k": [], "captured_tau": []}
                     for k in budgets_abs}
        for _ in range(args.n_random_repeats):
            rp = rng_master.rand(n_hold)
            for k in budgets_abs:
                top = np.argsort(-rp)[:k]
                rand_rows[k]["recall@k"].append(recall_at_k(rp, measured, thr, k))
                rand_rows[k]["precision@k"].append(precision_at_k(rp, measured, thr, k))
                rand_rows[k]["captured_tau"].append(float(np.mean(measured[top])))
        seed_result["Random"] = {
            k: {m: float(np.nanmean(v)) for m, v in d.items()}
            for k, d in rand_rows.items()}

        method_names = list(seed_result.keys())
        per_seed_rows.append({"seed": seed, "n_hold": n_hold,
                              "n_fragile": n_fragile, "results": seed_result})

    # aggregate mean +/- std across seeds
    agg: dict[str, dict] = {}
    for name in method_names:
        agg[name] = {}
        for k in budgets_used:
            for metric in ("recall@k", "precision@k", "captured_tau"):
                vals = [r["results"][name][k][metric]
                        for r in per_seed_rows if name in r["results"]
                        and k in r["results"][name]]
                vals = [v for v in vals if v is not None and not np.isnan(v)]
                agg[name].setdefault(k, {})[metric] = {
                    "mean": float(statistics.fmean(vals)) if vals else float("nan"),
                    "std": float(statistics.pstdev(vals)) if len(vals) > 1 else 0.0,
                }

    summary = {
        "config": args.config,
        "seeds": args.seeds,
        "complexity_proxy": args.complexity_proxy,
        "fragile_threshold": threshold,
        "budgets": budgets_used,
        "per_seed": per_seed_rows,
        "aggregate": agg,
    }
    (out_dir / "curation_summary.json").write_text(json.dumps(summary, indent=2),
                                                   encoding="utf-8")

    # markdown table: recall@k (primary) per method x budget, mean +/- std
    lines = [
        f"# Downstream difficulty-aware curation -- {args.config}",
        "",
        f"Seeds {args.seeds}; complexity proxy `{args.complexity_proxy}`; "
        f"fragile threshold `{threshold}` (truly fragile = measured "
        f"`d_obs > {threshold}`). Budgets `k` are top-of-shortlist sizes on the "
        f"holdout. Higher is better for every column. A method wins if, at a "
        f"fixed budget, it captures more of the fragile set (recall@k) and more "
        f"measured fragility (captured tau) than random/length/score-predictor.",
        "",
    ]
    for metric, title in (("recall@k", "Recall@k (fraction of fragile jobs captured)"),
                          ("captured_tau", "Captured tau (mean measured d_obs in top-k)"),
                          ("precision@k", "Precision@k (shortlist purity)")):
        lines += [f"## {title}", "",
                  "| Method | " + " | ".join(f"k={k}" for k in budgets_used) + " |",
                  "| --- | " + " | ".join("---" for _ in budgets_used) + " |"]
        for name in method_names:
            cells = []
            for k in budgets_used:
                s = agg[name][k][metric]
                cells.append(f"{s['mean']:.3f} ± {s['std']:.3f}")
            lines.append(f"| {name} | " + " | ".join(cells) + " |")
        lines.append("")
    (out_dir / "table_curation.md").write_text("\n".join(lines) + "\n", encoding="utf-8")

    print(f"\nWrote {out_dir / 'table_curation.md'}")
    print(f"Wrote {out_dir / 'curation_summary.json'}")


if __name__ == "__main__":
    main()