File size: 7,026 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 | #!/usr/bin/env python
"""Downstream utility (top-k curation), redone on the repaired pi estimand.
The version in the paper (Appendix app:utility) predates the audit/estimand
repair: it ranks by the retracted D_avg on the *unaudited* single-dose
GSM-IC-Adv pairs (data/, not data_audited/), with the FrailTau ablation head
rather than the FrailPi headline predictor, at a single seed (7). This script
reruns the same recall@k curation experiment on the audited, pooled 5-dose
data, ranking by FrailPi's actual held-out predictions (loaded from the
dumped runs/new_audit/*/00_baseline/hf_finetune/predictions/*_text_probe_*.json
-- the exact run behind Table tab:c1, no retraining needed), against the
Surface-features(GBT) and Declared-complexity baselines already used
elsewhere in the paper, averaged over the same 5 seeds as everywhere else.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
import numpy as np
from causal_difficulty.eval.deconfound import cross_fitted_residual
from causal_difficulty.eval.estimands import build_job_targets
from causal_difficulty.eval.loading import load_pairs
from causal_difficulty.eval.splits import three_way_split
from causal_difficulty.features.surface import surface_baseline_predictions, surface_matrix
DATA_AUDITED = ROOT / "data_audited"
PRED_DIR = ROOT / "runs" / "new_audit"
SEEDS = [0, 1, 2, 3, 4]
VAL_FRAC = 0.15
TEST_FRAC = 0.30
BUDGETS_FRAC = [0.05, 0.10, 0.20, 0.50]
FRAGILE_THRESHOLD = 0.05
SUITES = {
"gsmic_adv": {
"files": [str(DATA_AUDITED / f"gsmic_adv_m{m}_4omini_labeled_pairs.jsonl") for m in (1, 3, 5, 7, 9)],
"pred_dir": PRED_DIR / "gsmic_adv_gpt4omini" / "00_baseline" / "hf_finetune" / "predictions",
"expected_fingerprint_seed0": "43f803e998314690",
},
"math_adv": {
"files": [str(DATA_AUDITED / f"math_adv_m{m}_4omini_labeled_pairs.jsonl") for m in (1, 3, 5, 7, 9)],
"pred_dir": PRED_DIR / "math_adv_gpt4omini" / "00_baseline" / "hf_finetune" / "predictions",
"expected_fingerprint_seed0": None, # not independently verified; checked via base_id-set match instead
},
}
def recall_at_k(pred: np.ndarray, target: np.ndarray, threshold: float, frac: float) -> float:
n = len(target)
k = max(1, int(round(frac * n)))
n_fragile = int((target > threshold).sum())
if n_fragile == 0:
return float("nan")
top = np.argsort(-np.asarray(pred))[:k]
return float((target[top] > threshold).sum()) / n_fragile
def run_suite(name: str, spec: dict) -> dict:
print(f"\n=== {name} ===")
pairs, _ = load_pairs(",".join(spec["files"]))
jobs = build_job_targets(pairs, solvable_only=True, min_obs=4)
job_by_id = {j.base_id: j for j in jobs}
print(f" {len(jobs)} solvable jobs")
methods = ("frail_pi", "frail_pi_dperp", "surface_gbt", "declared_complexity", "oracle")
per_seed = {m: {f: [] for f in BUDGETS_FRAC} for m in methods}
n_fragile_fracs = []
for seed in SEEDS:
strata = {j.base_id: j.break_rate for j in jobs}
split = three_way_split([j.base_id for j in jobs], seed=seed, val_frac=VAL_FRAC,
test_frac=TEST_FRAC, strata=strata)
exp_fp = spec.get("expected_fingerprint_seed0")
if seed == 0 and exp_fp:
status = "OK" if split.fingerprint == exp_fp else "MISMATCH"
print(f" seed 0 fingerprint {split.fingerprint} (expected {exp_fp}) [{status}]")
if status != "OK":
raise SystemExit("split fingerprint mismatch -- not the same holdout as Table tab:c1")
train_ids, test_ids = set(split.train_ids), set(split.test_ids)
tr = [j for j in jobs if j.base_id in train_ids]
te = [j for j in jobs if j.base_id in test_ids]
pred_path = spec["pred_dir"] / f"hf_finetune_text_probe_seed{seed}.json"
dumped = json.loads(pred_path.read_text())
dumped_ids = dumped["base_id"]
if set(dumped_ids) != test_ids:
raise SystemExit(f"{name} seed {seed}: dumped prediction base_id set does not match "
f"the recomputed test split -- not the same holdout, refusing to report.")
# reorder te/target to the dumped prediction order so arrays align
te_by_id = {j.base_id: j for j in te}
te_ordered = [te_by_id[b] for b in dumped_ids]
target = np.asarray(dumped["target_break_rate"], dtype=float)
frail_pi_pred = np.asarray(dumped["pred_break_rate"], dtype=float)
n_fragile_fracs.append(float((target > FRAGILE_THRESHOLD).mean()))
X_surf_tr = surface_matrix([j.base_text for j in tr])
X_surf_te = surface_matrix([j.base_text for j in te_ordered])
y_tr_rate = np.asarray([j.break_rate for j in tr])
surf_pred = surface_baseline_predictions(X_surf_tr, y_tr_rate, X_surf_te, seed=seed)
complexity_pred = np.asarray([j.complexity_score for j in te_ordered])
oracle_pred = target # tautological upper bound: rank by the truth itself
dperp_pred, _ = cross_fitted_residual(complexity_pred, frail_pi_pred, n_folds=5, seed=seed)
preds = {
"frail_pi": frail_pi_pred,
"frail_pi_dperp": dperp_pred,
"surface_gbt": surf_pred,
"declared_complexity": complexity_pred,
"oracle": oracle_pred,
}
for m, p in preds.items():
for f in BUDGETS_FRAC:
per_seed[m][f].append(recall_at_k(p, target, FRAGILE_THRESHOLD, f))
print(f" seed {seed}: n_test={len(te_ordered)} n_fragile={(target > FRAGILE_THRESHOLD).sum()} "
f"frail_pi@20%={recall_at_k(frail_pi_pred, target, FRAGILE_THRESHOLD, 0.20):.3f}")
summary = {"n_fragile_frac": {"mean": float(np.mean(n_fragile_fracs)),
"sd": float(np.std(n_fragile_fracs))}}
for m in methods:
summary[m] = {}
for f in BUDGETS_FRAC:
vals = np.asarray(per_seed[m][f], dtype=float)
summary[m][f] = {"mean": float(np.nanmean(vals)), "sd": float(np.nanstd(vals))}
return summary
def main() -> None:
out = {}
for name, spec in SUITES.items():
out[name] = run_suite(name, spec)
out_path = ROOT / "runs" / "new_audit" / "downstream_utility_pi.json"
out_path.write_text(json.dumps(out, indent=2))
print(f"\nWrote {out_path}")
for name, summary in out.items():
print(f"\n{name} (mean fragile frac {summary['n_fragile_frac']['mean']:.3f}):")
print(f" {'Method':<22}" + "".join(f" k={int(f*100)}%".ljust(14) for f in BUDGETS_FRAC))
for m in ("frail_pi", "frail_pi_dperp", "surface_gbt", "declared_complexity", "oracle"):
row = summary[m]
cells = "".join(f" {row[f]['mean']:.3f}±{row[f]['sd']:.3f}".ljust(14) for f in BUDGETS_FRAC)
print(f" {m:<22}{cells}")
if __name__ == "__main__":
main()
|