File size: 6,009 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
"""Multi-seed ensemble evaluation for GSM (or any small dataset).

Fixes the holdout split (split_seed) and trains the SCE model with N
different model-initialization/training seeds, then averages ex-ante
predictions before computing metrics.  This reduces variance on the
small (30-problem) holdout.

Usage:
    python scripts/ensemble_evaluate.py --config gsm --seeds 1 3 5 7 13 42
"""
from __future__ import annotations

import argparse
import json
import random
import sys
from pathlib import Path

import numpy as np
import torch

ROOT = Path(__file__).parent.parent
sys.path.insert(0, str(ROOT / "src"))

from causal_difficulty.config import load_config  # noqa: E402
from causal_difficulty.encoders import build_encoder  # noqa: E402
from causal_difficulty.eval import metrics  # noqa: E402
from causal_difficulty.eval.reports import _aggregate, _split  # noqa: E402
from causal_difficulty.baselines import (  # noqa: E402
    FrozenDistanceBaseline, LengthBaseline, ScorePredictorBaseline,
)
from causal_difficulty.io_utils import read_labeled_pairs  # noqa: E402
from causal_difficulty.models.train import build_sce, train  # noqa: E402
from causal_difficulty.schemas import LabeledPair  # noqa: E402


def _set_seed(seed: int) -> None:
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)


def run_single_seed(cfg, train_pairs, hold_ids, hold, base_texts, encoder,
                    seed: int, config_name: str):
    _set_seed(seed)
    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()
    with torch.no_grad():
        ex = sce.predict_ex_ante(base_texts).cpu().numpy()
        ex_ante = ex[:, 0]
        contrast = np.array([
            float(sce.predict_contrast(
                [hold[b].base_text] * len(hold[b].twin_texts),
                hold[b].twin_texts).mean())
            if hold[b].twin_texts else 0.0
            for b in hold_ids
        ])
    return ex_ante, contrast


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", default="gsm")
    parser.add_argument("--seeds", nargs="+", type=int, default=[1, 3, 5, 7, 13, 42])
    parser.add_argument("--split-seed", type=int, default=7,
                        help="Seed for train/holdout split (fixed across ensemble)")
    args = parser.parse_args()

    cfg = load_config(args.config)
    pairs, pairs_path = read_labeled_pairs(cfg, args.config, LabeledPair)

    train_pairs, hold_pairs = _split(
        pairs, cfg.eval.get("holdout_frac", 0.3), args.split_seed,
        stratified=cfg.eval.get("stratified_split", False),
    )
    hold = _aggregate(hold_pairs)
    hold_ids = sorted(hold.keys())
    base_texts = [hold[b].base_text for b in hold_ids]
    measured = np.array([hold[b].d_avg for b in hold_ids], dtype=float)
    complexity = np.array([hold[b].complexity for b in hold_ids], dtype=float)
    twins_by_base = {b: hold[b].twin_texts for b in hold_ids}
    threshold = cfg.eval.get("fragile_threshold", 0.15)

    encoder = build_encoder(cfg)
    embed_fn = lambda ts: encoder.encode(ts)  # noqa: E731

    print(f"Config: {args.config}  |  Seeds: {args.seeds}  |  Split seed: {args.split_seed}")
    print(f"Train: {len({p.base_id for p in train_pairs})} problems, "
          f"Holdout: {len(hold_ids)} problems")
    print(f"Holdout fragile (D_avg > {threshold}): "
          f"{sum(1 for d in measured if d > threshold)}/{len(measured)}")
    print()

    all_ex_ante = []
    all_contrast = []

    for seed in args.seeds:
        print(f"  Training seed={seed}...", flush=True)
        ex_ante, contrast = run_single_seed(
            cfg, train_pairs, hold_ids, hold, base_texts, encoder,
            seed=seed, config_name=args.config,
        )
        all_ex_ante.append(ex_ante)
        all_contrast.append(contrast)
        rho = metrics.spearman(ex_ante, measured)
        print(f"    seed={seed}  ex-ante ρ_S={rho:.3f}", flush=True)

    # Ensemble by averaging predictions
    ens_ex_ante = np.mean(all_ex_ante, axis=0)
    ens_contrast = np.mean(all_contrast, axis=0)

    # Baselines (deterministic)
    length_b = LengthBaseline().fit(train_pairs)
    score_b = ScorePredictorBaseline(embed_fn).fit(train_pairs)
    frozen_b = FrozenDistanceBaseline(embed_fn).fit(train_pairs)

    length_pred = length_b.predict_job_difficulty(base_texts)
    score_pred = score_b.predict_job_difficulty(base_texts)
    frozen_pred = frozen_b.predict_job_difficulty_from_twins(hold_ids, base_texts, twins_by_base)

    methods = {
        "Surface length": length_pred,
        "Correlational score-predictor": score_pred,
        "Frozen embedding distance": frozen_pred,
        f"SCE ex-ante ensemble ({len(args.seeds)} seeds)": ens_ex_ante,
        f"SCE contrast ensemble ({len(args.seeds)} seeds)": ens_contrast,
    }

    print()
    print(f"{'Method':<42} {'Spearman':>8} {'MAE':>7} {'AUROC':>7} {'NDCG@10':>8} {'|rho_C|':>8}")
    print("-" * 87)
    results = {}
    for name, pred in methods.items():
        m = metrics.all_metrics(np.asarray(pred), measured, threshold)
        m["deconfound_|rho_C|"] = metrics.deconfounding_probe(np.asarray(pred), complexity)
        results[name] = m
        print(f"{name:<42} {m['spearman']:>8.3f} {m['mae']:>7.3f} {m['auroc']:>7.3f} "
              f"{m['ndcg@10']:>8.3f} {m['deconfound_|rho_C|']:>8.3f}")

    # Save summary
    out_dir = Path(cfg.paths.outputs_dir) / "ensemble"
    out_dir.mkdir(parents=True, exist_ok=True)
    summary = {
        "config": args.config,
        "seeds": args.seeds,
        "split_seed": args.split_seed,
        "n_train": len({p.base_id for p in train_pairs}),
        "n_holdout": len(hold_ids),
        "results": results,
    }
    out_path = out_dir / f"{args.config}_ensemble.json"
    out_path.write_text(json.dumps(summary, indent=2))
    print(f"\nSaved to {out_path}")


if __name__ == "__main__":
    main()