Download scripts/fragility_report.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 66.2 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/fragility_report.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/scripts/fragility_report.py
-
curl -L -o fragility_report.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/fragility_report.py
66.2 kB
#!/usr/bin/env python
"""Headline fragility-prediction results on the repaired estimand.
Everything the retracted numbers got wrong is closed off here by construction:
* the target is the conditional break rate on the **solvable stratum** (and its
dose-response parameters), not a ``max`` capped by base correctness;
* the split is **three-way** with a fingerprint, and the model is trained inside
this process on the train fold only -- there is no ``--checkpoint`` path that
could smuggle in weights fit on the test fold;
* epochs are chosen by **early stopping on the validation fold**, never on test;
* the ceiling is the **parametric-bootstrap** reliability, not Spearman-Brown on
an order statistic;
* every number is reported over several seeds with a spread;
* the surface-feature baseline and the measured-base-correctness reference are
reported alongside, so a headline that merely rediscovers length or solvability
is visible as such.
Two protocols are reported separately and never merged. ``text`` uses the
problem statement only. ``text_probe`` adds ex-ante probe features from repeated
samples of the *base* prompt (no twin is ever run), which requires model access
and is therefore a different claim.
Usage
-----
python scripts/fragility_report.py --dataset gsmic_adv --seeds 0,1,2
python scripts/fragility_report.py --dataset math_adv --featurizer tfidf_svd
python scripts/fragility_report.py --dataset gsmic_adv --protocol both \\
--probe-file outputs_probes/gsmic_adv/base_probes.json
"""
from __future__ import annotations
import argparse
import gc
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
import numpy as np
import torch
from scipy.stats import spearmanr
from causal_difficulty.baselines.bertpe import BERTPEBaseline
from causal_difficulty.baselines.pi_adapters import bertpe_job_pairs, vap3_twin_pairs
from causal_difficulty.baselines.vap3 import VAP3Baseline
from causal_difficulty.eval.deconfound import (
cross_fitted_residual,
explained_variance_drop,
null_head_negative_control,
orthogonality_diagnostics,
predict_m,
stratified_rank_correlation,
)
from causal_difficulty.eval.estimands import (
FAMILIES,
build_job_targets,
dose_from_operator,
)
from causal_difficulty.eval.loading import load_pairs
from causal_difficulty.eval.metrics import all_metrics, deconfounding_probe
from causal_difficulty.eval.reliability import parametric_reliability
from causal_difficulty.eval.splits import three_way_split
from causal_difficulty.features import probes as probe_feats
from causal_difficulty.features.surface import (
SURFACE_FEATURE_NAMES,
declared_proxy_scores,
out_of_fold_predictions,
surface_baseline_predictions,
surface_matrix,
)
from causal_difficulty.features.text import TextFeaturizer
from causal_difficulty.models.fragility import (
FragilityModel,
TrainConfig,
dose_response_from_grid,
expected_mean,
)
from causal_difficulty.models.fragility_encoder import (
EncoderFragilityModel,
EncoderTrainConfig,
)
ROOT = Path(__file__).resolve().parents[1]
# Backbones whose whole point is gradient-based adaptation to the break-
# probability objective: routed through EncoderFragilityModel (joint
# encoder+head training) instead of the precomputed-feature TextFeaturizer
# path every other --featurizer value uses. See fragility_encoder.py's
# module docstring for why a frozen/precomputed split doesn't make sense here.
TRAINABLE_ENCODER_BACKBONES = ("hf_lora", "hf_finetune")
def _origin(base_id: str) -> str:
"""``<dataset>-<index>`` -> ``<dataset>``, so a pooled ``--dataset`` spec
spanning multiple suites (e.g. every gsmic_adv_* and math_adv_* file in one
run) can still be scored per-suite, not just on the mixed pool."""
return base_id.rsplit("-", 1)[0]
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 _mean_sd_dict(dicts: list[dict[str, float]]) -> dict[str, dict[str, float]]:
"""Mean+-sd over seeds for every scalar key present in every dict in
``dicts`` (the ``metrics``/``orthogonality_*``/``r2_drop``/null-head-row
sub-dicts returned per seed by :mod:`eval.deconfound`)."""
keys = dicts[0].keys()
out: dict[str, dict[str, float]] = {}
for k in keys:
vals = [d[k] for d in dicts if isinstance(d.get(k), (int, float))]
m, s = _mean_sd(vals)
out[k] = {"mean": m, "sd": s}
return out
def _free_device_memory(device: str | None) -> None:
"""Best-effort release of a just-dropped model's device memory.
Purely a memory-management helper -- it only affects *when* memory is
reclaimed, never any computed value. Needed because torch's MPS/CUDA
caching allocators do not return memory to the shared pool just because
the Python object holding it was ``del``-ed; the caller must ``del`` the
model first (dropping its refcount to zero) and then call this so the
allocator actually frees it before the next model is instantiated.
"""
gc.collect()
if device == "mps" and torch.backends.mps.is_available():
torch.mps.empty_cache()
elif device == "cuda" and torch.cuda.is_available():
torch.cuda.empty_cache()
def _seed_cache_path(out_dir: Path, seed: int, proto: str) -> Path:
return out_dir / "seeds" / f"seed_{seed}" / f"{proto}.json"
def _load_seed_cache(path: Path) -> dict | None:
if path.is_file():
return json.loads(path.read_text())
return None
def _save_seed_cache(path: Path, res: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(res, indent=2))
def _collect_seed_results(out_dir: Path, proto: str, expected_seeds: list[int],
fresh: list[dict]) -> tuple[list[dict], list[int]]:
"""Merge in-memory results with on-disk per-seed caches; return missing."""
by_seed = {r["seed"]: r for r in fresh}
for seed in expected_seeds:
if seed in by_seed:
continue
cached = _load_seed_cache(_seed_cache_path(out_dir, seed, proto))
if cached is not None:
by_seed[seed] = cached
missing = [s for s in expected_seeds if s not in by_seed]
runs = [by_seed[s] for s in sorted(by_seed) if s in expected_seeds]
return runs, missing
def _aggregate_dperp_diagnostics(runs: list[dict]) -> dict:
"""Seed-aggregated tab:c2 diagnostic suite for the (pi, declared surface
proxy) pairing: same columns/controls ``paper_supports_real.py`` reports
for the D_avg/y_base_mean pairing, applied to this script's D^perp block."""
dperps = [r["dperp"] for r in runs]
null_heads = [d["null_head"] for d in dperps]
return {
"metrics": _mean_sd_dict([d["metrics"] for d in dperps]),
"orthogonality_target": _mean_sd_dict([d["orthogonality_target"] for d in dperps]),
"orthogonality_pred": _mean_sd_dict([d["orthogonality_pred"] for d in dperps]),
"r2_drop": _mean_sd_dict([d["r2_drop"] for d in dperps]),
"stratified_rank_weighted_spearman": dict(zip(
("mean", "sd"), _mean_sd([d["stratified_rank"]["weighted_mean_spearman"] for d in dperps]))),
"null_head_constant": _mean_sd_dict([nh["constant_head"] for nh in null_heads]),
"null_head_shuffled_mean": _mean_sd_dict([nh["shuffled_head_mean"] for nh in null_heads]),
"n_shuffle_repeats": null_heads[0]["n_repeats"],
}
def _fmt(v: float) -> str:
return "n/a" if v is None or not np.isfinite(v) else f"{v:.3f}"
def _dperp_diagnostics_lines(diag: dict) -> list[str]:
m, ot, op = diag["metrics"], diag["orthogonality_target"], diag["orthogonality_pred"]
r2, strat = diag["r2_drop"], diag["stratified_rank_weighted_spearman"]
ct, sh = diag["null_head_constant"], diag["null_head_shuffled_mean"]
lines = [
"",
"### D^perp C2 diagnostics (pi residualized against the declared surface proxy)",
"",
"Same tab:c2 columns as the D_avg/y_base_mean pairing, applied to this "
"script's repaired-estimand D^perp block, mean +/- sd over seeds.",
"",
"| Quantity | value |",
"| --- | --- |",
f"| Spearman(D^perp_hat, D^perp) | {_fmt(m['spearman']['mean'])} ± {_fmt(m['spearman']['sd'])} |",
f"| MAE | {_fmt(m['mae']['mean'])} ± {_fmt(m['mae']['sd'])} |",
f"| NDCG@10 | {_fmt(m['ndcg@10']['mean'])} ± {_fmt(m['ndcg@10']['sd'])} |",
f"| \\|rho_C\\| (pred vs proxy) | {_fmt(m['deconfound_|rho_C|']['mean'])} ± {_fmt(m['deconfound_|rho_C|']['sd'])} |",
f"| Corr(target, C) | {_fmt(ot['corr_D_perp_C']['mean'])} ± {_fmt(ot['corr_D_perp_C']['sd'])} |",
f"| Corr(pred, C) | {_fmt(op['corr_D_perp_C']['mean'])} ± {_fmt(op['corr_D_perp_C']['sd'])} |",
f"| Corr(pred, C^2) | {_fmt(op['corr_D_perp_C2']['mean'])} ± {_fmt(op['corr_D_perp_C2']['sd'])} |",
f"| R^2-drop (before -> after) | {_fmt(r2['r2_before']['mean'])} -> {_fmt(r2['r2_after']['mean'])} "
f"(drop {_fmt(r2['r2_drop']['mean'])}) |",
f"| Complexity-stratified weighted Spearman | {_fmt(strat['mean'])} ± {_fmt(strat['sd'])} |",
"",
"Shared-term controls (constant head / shuffled head, "
f"{diag['n_shuffle_repeats']} repeats, -m_pred(C) retained, scored "
"against the real D^perp target):",
"",
"| Row | rho_S | MAE | NDCG@10 | Corr(pred,C) | Corr(pred,C^2) |",
"| --- | --- | --- | --- | --- | --- |",
f"| constant head | {_fmt(ct['spearman']['mean'])} | {_fmt(ct['mae']['mean'])} | "
f"{_fmt(ct['ndcg@10']['mean'])} | {_fmt(ct['corr_c']['mean'])} | {_fmt(ct['corr_c2']['mean'])} |",
f"| shuffled head (mean) | {_fmt(sh['spearman']['mean'])} ± {_fmt(sh['spearman']['sd'])} | "
f"{_fmt(sh['mae']['mean'])} | {_fmt(sh['ndcg@10']['mean'])} | {_fmt(sh['corr_c']['mean'])} | "
f"{_fmt(sh['corr_c2']['mean'])} |",
"",
]
return lines
def build_features(
jobs,
train_ids: set[str],
*,
featurizer: str,
protocol: str,
probe_file: str | None,
dim: int,
seed: int,
hf_model: str | None = None,
device: str | None = None,
hf_batch_size: int | None = None,
cache_dir: str | None = None,
max_concurrency: int | None = None,
) -> tuple[np.ndarray, list[str], dict]:
"""Job feature matrix. Text representations are fit on the train fold only.
For a trainable-encoder backbone (``hf_lora``/``hf_finetune``) the text
block is intentionally omitted: those encoders adapt jointly with the
break-probability head inside ``EncoderFragilityModel.fit``, so there is
no fixed text representation to precompute here -- see
``TRAINABLE_ENCODER_BACKBONES``. The returned matrix then holds only the
static (surface + probe) features that model concatenates onto its own
per-step embeddings.
"""
texts = [j.base_text for j in jobs]
X_surface = surface_matrix(texts)
info: dict = {"featurizer": featurizer}
if featurizer in TRAINABLE_ENCODER_BACKBONES:
blocks = [X_surface]
names = list(SURFACE_FEATURE_NAMES)
else:
train_texts = [j.base_text for j in jobs if j.base_id in train_ids]
tf = TextFeaturizer(featurizer, dim=dim, seed=seed, model_name=hf_model,
device=device, batch_size=hf_batch_size,
cache_dir=cache_dir, max_concurrency=max_concurrency)
X_text = tf.fit_transform(train_texts, texts)
blocks = [X_text, X_surface]
names = [f"text_{i}" for i in range(X_text.shape[1])] + list(SURFACE_FEATURE_NAMES)
info["text_dim"] = int(X_text.shape[1])
if protocol == "text_measured":
# k actually-measured twins at the cheapest dose, withheld from every
# target in build_job_targets. This is not an ex-ante protocol: it buys
# a little measurement to rank the expensive full-family target.
n_probe = np.asarray([[float(j.n_probe_obs)] for j in jobs])
rate = np.asarray([[float(j.probe_break_rate)] for j in jobs])
# Laplace-smoothed logit of the small-sample rate: k=2 twins give rates
# in {0, .5, 1}, and the raw value sends 0 and 1 to infinity downstream.
smooth = (rate * n_probe + 0.5) / (n_probe + 1.0)
mean_dose = np.asarray([[float(j.probe_mean_dose)] for j in jobs])
blocks += [rate, smooth, np.log(smooth / (1.0 - smooth)), n_probe, mean_dose]
names += ["probe_break_rate", "probe_rate_smoothed",
"probe_rate_logit", "probe_n_obs", "probe_mean_dose"]
info["measured_probe_obs"] = float(np.mean([j.n_probe_obs for j in jobs]))
info["measured_probe_mean_dose"] = float(
np.nanmean([j.probe_mean_dose for j in jobs]))
if protocol == "text_probe":
X_free, free_names = probe_feats.probe_features_from_targets(jobs)
blocks.append(X_free)
names += list(free_names)
info["free_probes"] = list(free_names)
if probe_file:
X_s, s_names, covered = probe_feats.probe_features_from_samples(
jobs, probe_file)
if covered < 0.95 * len(jobs):
raise SystemExit(
f"probe file covers only {covered}/{len(jobs)} jobs; refusing to "
f"report a probe protocol on that coverage")
blocks.append(X_s)
names += list(s_names)
info["sampled_probes"] = list(s_names)
info["probe_coverage"] = covered
return np.hstack(blocks), names, info
def run_seed(
jobs,
*,
seed: int,
featurizer: str,
protocol: str,
probe_file: str | None,
dim: int,
cfg: TrainConfig,
val_frac: float,
test_frac: float,
encoder_cfg: EncoderTrainConfig | None = None,
hf_model: str | None = None,
device: str | None = None,
hf_batch_size: int | None = None,
cache_dir: str | None = None,
max_concurrency: int | None = None,
lora_r: int = 8,
lora_alpha: int = 16,
lora_dropout: float = 0.05,
include_bertpe_vap3: bool = False,
bertpe_epochs: int = 3,
vap3_epochs: int = 3,
bertpe_vap3_batch_size: int = 16,
predictions_out: Path | None = None,
n_shuffled_head_repeats: int = 100,
n_inits: int = 1,
encoder_max_length: int | None = None,
encoder_pooling: str = "mean",
encoder_base_dtype: str = "float32",
aux_train_jobs: dict | None = None,
checkpoint_dir: Path | None = None,
checkpoint_meta: dict | None = None,
) -> dict:
"""One complete train/select/test cycle at a single split seed."""
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)
train_ids, val_ids, test_ids = (set(split.train_ids), set(split.val_ids),
set(split.test_ids))
X, feat_names, finfo = build_features(
jobs, train_ids, featurizer=featurizer, protocol=protocol,
probe_file=probe_file, dim=dim, seed=seed, hf_model=hf_model,
device=device, hf_batch_size=hf_batch_size, cache_dir=cache_dir,
max_concurrency=max_concurrency)
job_index = {j.base_id: i for i, j in enumerate(jobs)}
tr = [j for j in jobs if j.base_id in train_ids]
va = [j for j in jobs if j.base_id in val_ids]
te = [j for j in jobs if j.base_id in test_ids]
doses = tuple(sorted({int(d) for j in jobs for d in j.doses}))
if aux_train_jobs and featurizer in TRAINABLE_ENCODER_BACKBONES:
# Extra supervision for the *train fold only*: swap each train job for
# its counterpart built from --aux-train-dataset (same base problem,
# more twins). Validation/test jobs and every reported target stay
# the --dataset ones, so the evaluation is unchanged.
tr = [aux_train_jobs.get(j.base_id, j) for j in tr]
if featurizer in TRAINABLE_ENCODER_BACKBONES:
from causal_difficulty.encoders import build_encoder_simple
# n_inits > 1: train that many independently initialized encoder+head
# models on the *same* split (init seed = seed + 1000*k; k=0 is the
# single-model run) and average their predicted probabilities. Each
# member is early-stopped on the validation fold as usual; the
# ensemble's own validation Spearman is recorded so model selection
# stays on the validation fold.
grids, rates_te, rates_tr, rates_va, histories = [], [], [], [], []
for k in range(max(1, n_inits)):
if k:
del model, encoder
_free_device_memory(device)
encoder = build_encoder_simple(
featurizer, model_name=hf_model, device=device,
max_length=encoder_max_length, pooling=encoder_pooling,
base_dtype=encoder_base_dtype,
lora_r=lora_r, lora_alpha=lora_alpha, lora_dropout=lora_dropout)
model = EncoderFragilityModel(
encoder, EncoderTrainConfig(**{**(encoder_cfg or EncoderTrainConfig()).__dict__,
"seed": seed + 1000 * k})).fit(
X, tr, va, job_index)
grids.append(model.predict_dose_grid(X, te, job_index, doses))
rates_te.append(model.predict_break_rate(X, te, job_index))
if checkpoint_dir is not None:
checkpoint_dir.mkdir(parents=True, exist_ok=True)
ckpt = model.checkpoint()
ckpt.update(checkpoint_meta or {})
ckpt.update({
"featurizer": featurizer, "hf_model": hf_model, "protocol": protocol,
"seed": seed, "init": k, "n_inits": max(1, n_inits),
"encoder_max_length": encoder_max_length,
"encoder_pooling": encoder_pooling, "lora_r": lora_r,
"encoder_base_dtype": encoder_base_dtype,
"lora_alpha": lora_alpha, "lora_dropout": lora_dropout,
"probe_file": probe_file, "feature_names": list(feat_names),
"split": {"train": sorted(train_ids), "val": sorted(val_ids),
"test": sorted(test_ids)},
"test_base_ids": [j.base_id for j in te],
"test_pred_break_rate": rates_te[-1].tolist(),
"val_spearman": model.history.best_val_spearman,
"test_spearman": _rho(rates_te[-1], np.asarray([j.break_rate for j in te])),
})
torch.save(ckpt, checkpoint_dir / f"{protocol}_seed{seed}_init{k}.pt")
rates_tr.append(model.predict_break_rate(X, tr, job_index))
rates_va.append(model.predict_break_rate(X, va, job_index))
histories.append(model.history.to_dict())
grid_te = np.mean(grids, axis=0)
pred_rate = np.mean(rates_te, axis=0)
pred_rate_tr = np.mean(rates_tr, axis=0)
model_history = histories[0]
if len(histories) > 1:
model_history = {
**histories[0],
"best_val_spearman": _rho(np.mean(rates_va, axis=0),
np.asarray([j.break_rate for j in va])),
"member_best_val_spearman": [h["best_val_spearman"] for h in histories],
"member_best_epochs": [h["best_epoch"] for h in histories],
"n_inits": len(histories),
}
else:
model = FragilityModel(TrainConfig(**{**cfg.__dict__, "seed": seed})).fit(
X, tr, va, job_index)
grid_te = model.predict_dose_grid(X, te, job_index, doses)
pred_rate = model.predict_break_rate(X, te, job_index)
pred_rate_tr = model.predict_break_rate(X, tr, job_index)
model_history = model.history.to_dict()
pred_a, pred_b = dose_response_from_grid(grid_te, doses)
pred_davg = expected_mean(pred_rate)
tgt = {
"break_rate": np.asarray([j.break_rate for j in te]),
"break_rate_shrunk": np.asarray([j.break_rate_shrunk for j in te]),
"a": np.asarray([j.a for j in te]),
"b": np.asarray([j.b for j in te]),
"d_avg": np.asarray([j.d_avg for j in te]),
}
pred = {
"break_rate": pred_rate,
"break_rate_shrunk": pred_rate,
"a": pred_a,
"b": pred_b,
"d_avg": pred_davg,
}
# --- reference rows ---------------------------------------------------
X_surf_all = surface_matrix([j.base_text for j in jobs])
idx_tr = np.asarray([job_index[j.base_id] for j in tr])
idx_te = np.asarray([job_index[j.base_id] for j in te])
y_tr_rate = np.asarray([j.break_rate for j in tr])
surf_pred = surface_baseline_predictions(
X_surf_all[idx_tr], y_tr_rate, X_surf_all[idx_te], seed=seed)
complexity_te = np.asarray([j.complexity_score for j in te])
ybase_te = np.asarray([j.y_base for j in te])
# Same inputs as the model, but regressing the job-level target directly
# instead of predicting per-observation break events. Isolates what the BCE
# reformulation contributes from what the representation contributes.
joblevel_pred = surface_baseline_predictions(X[idx_tr], y_tr_rate, X[idx_te],
seed=seed)
rows = {
"model": {k: _rho(pred[k], tgt[k]) for k in tgt},
"same_features_joblevel_regression": {k: _rho(joblevel_pred, tgt[k]) for k in tgt},
"surface_features": {k: _rho(surf_pred, tgt[k]) for k in tgt},
"declared_complexity_only": {k: _rho(complexity_te, tgt[k]) for k in tgt},
"measured_base_correctness": {k: _rho(ybase_te, tgt[k]) for k in tgt},
}
extra_preds = {
"model": pred_rate, "same_features_joblevel_regression": joblevel_pred,
"surface_features": surf_pred, "declared_complexity_only": complexity_te,
"measured_base_correctness": ybase_te,
}
# --- BERTPE/VAP3: re-implementations of two published sensitivity
# predictors, retargeted from D_wc (which S5.1's measurement audit shows is
# degenerate) to the repaired break rate pi -- see baselines/pi_adapters.py
# for exactly how. Expensive (both fine-tune bert-base-uncased), so opt-in.
bertpe_pred = vap3_pred = None
if include_bertpe_vap3:
# Memory management only (no effect on any computed number): the main
# model above is done contributing anything derived from its live
# torch parameters (its predictions are already extracted into numpy
# arrays, and `model_history` above already pulled the one attribute
# still needed later). BERTPE and VAP3 each instantiate their own
# full bert-base-uncased; on a unified-memory (MPS) device the three
# models' caching-allocator footprints stack rather than reusing
# freed space unless explicitly released, which OOM'd here in
# practice. Dropping the reference and emptying the allocator cache
# before the next model loads keeps peak memory to one model at a
# time instead of three.
if featurizer in TRAINABLE_ENCODER_BACKBONES:
del model, encoder
_free_device_memory(device)
bertpe = BERTPEBaseline(device=device, epochs=bertpe_epochs,
batch_size=bertpe_vap3_batch_size).fit(
bertpe_job_pairs(tr), target_attr="pi")
bertpe_pred = bertpe.predict_job_difficulty([j.base_text for j in te])
del bertpe
_free_device_memory(device)
vap3 = VAP3Baseline(device=device, epochs=vap3_epochs,
batch_size=bertpe_vap3_batch_size).fit(
vap3_twin_pairs(tr), target_attr="delta_mean")
twins_by_base = {j.base_id: list(j.twin_texts) for j in te}
vap3_pred = vap3.predict_job_difficulty_from_twins(
[j.base_id for j in te], [j.base_text for j in te], twins_by_base,
agg="mean")
del vap3
_free_device_memory(device)
rows["bertpe"] = {k: _rho(bertpe_pred, tgt[k]) for k in tgt}
rows["vap3"] = {k: _rho(vap3_pred, tgt[k]) for k in tgt}
extra_preds["bertpe"] = bertpe_pred
extra_preds["vap3"] = vap3_pred
# --- Extra metrics against the primary target (break rate / pi), for
# every row above: MAE, NDCG@10, AUROC (median-of-target fragile cutoff).
# Spearman is already in `rows`; this is the rest of Table tab:davg's
# column set, requested for the repaired estimand too.
fragile_threshold = float(np.median(tgt["break_rate"])) if len(tgt["break_rate"]) else 0.0
extra_metrics = {
name: all_metrics(p, tgt["break_rate"], fragile_threshold, k=10)
for name, p in extra_preds.items()
}
# --- Additive: same metric suite as above, but against d_avg instead of
# break_rate/pi -- matching Table tab:synth2's column semantics
# (paper_supports_synth2.py's _write_avg_table: all_metrics(pred,
# measured_avg_hold, threshold) + deconfounding_probe(pred,
# complexity_hold)), so a Synth-CD-2-FrailPi row can be reported with
# the identical column set as the existing Frail-tau rows. This block is
# purely additive: it does not read or modify any variable used by the
# existing `extra_metrics` / `rows` / `dperp` computations above.
davg_threshold = float(np.median(tgt["d_avg"])) if len(tgt["d_avg"]) else 0.0
davg_metrics = {
name: all_metrics(p, tgt["d_avg"], davg_threshold, k=10)
for name, p in extra_preds.items()
}
for name, p in extra_preds.items():
davg_metrics[name]["deconfound_|rho_C|"] = deconfounding_probe(p, complexity_te)
# --- D^perp: residualize against the declared surface proxy -----------
# The proxy is fit on train only, then frozen; the target side residualizes
# with that proxy across disjoint folds and the predictor side is cross-fitted
# within the test fold, so no fold contributes to its own residualization.
# c_tr must itself be out-of-fold: querying the train-fit proxy on its own
# training rows (as this used to do) returns in-sample, overfit values, and
# fitting predict_m's isotonic m(C) on that near-degenerate (c_tr, y_tr_rate)
# pair produces an m_hat that overshoots badly once applied to the honestly
# out-of-fold c_te -- manufacturing a large spurious negative Corr(target, C)
# that isn't present in the raw, uncontaminated data (see Appendix, C2 erratum).
c_tr = out_of_fold_predictions(X_surf_all[idx_tr], y_tr_rate, n_folds=5, seed=seed)
c_te = declared_proxy_scores(X_surf_all[idx_tr], y_tr_rate, X_surf_all[idx_te],
seed=seed)
dperp_target = tgt["break_rate"] - predict_m(c_tr, y_tr_rate, c_te)
dperp_pred, _ = cross_fitted_residual(c_te, pred_rate, n_folds=5, seed=seed)
dperp_surf, _ = cross_fitted_residual(c_te, surf_pred, n_folds=5, seed=seed)
dperp: dict = {
"model": _rho(dperp_pred, dperp_target),
"surface_features": _rho(dperp_surf, dperp_target),
"spearman_target_vs_proxy": _rho(tgt["break_rate"], c_te),
}
if include_bertpe_vap3:
dperp_bertpe, _ = cross_fitted_residual(c_te, bertpe_pred, n_folds=5, seed=seed)
dperp_vap3, _ = cross_fitted_residual(c_te, vap3_pred, n_folds=5, seed=seed)
dperp["bertpe"] = _rho(dperp_bertpe, dperp_target)
dperp["vap3"] = _rho(dperp_vap3, dperp_target)
# --- C2 diagnostics on this (pi, declared surface proxy) pairing --------
# Same tab:c2 columns/controls as paper_supports_real.py computes for the
# D_avg/y_base_mean pairing, applied here instead to the D^perp block
# above. `orthogonality_diagnostics` on the *target* checks the near-
# mechanical Corr(D^perp,C)~0 sanity check (Prop. orthogonality); the two
# non-vacuous diagnostics are `explained_variance_drop` (R^2-drop of the
# prediction on C, before vs after residualization) and
# `stratified_rank_correlation` (Spearman within narrow C strata, where
# the shared -m_hat(C) term is ~constant). `null_head_negative_control`
# replaces the head with something carrying zero genuine per-job signal
# and puts it through the identical fit-and-subtract mechanics. `fix_leakage`
# is left at its default (cross-fit m_pred within the holdout) because
# `dperp_pred` above is already computed that way (`cross_fitted_residual`
# on `c_te`, not a train-fold `predict_m`), so the control must match.
dperp_threshold = float(np.median(dperp_target)) if len(dperp_target) else 0.0
dperp_metrics = all_metrics(dperp_pred, dperp_target, dperp_threshold, k=10)
dperp_metrics["deconfound_|rho_C|"] = deconfounding_probe(dperp_pred, c_te)
dperp["metrics"] = dperp_metrics
dperp["orthogonality_target"] = orthogonality_diagnostics(dperp_target, c_te)
dperp["orthogonality_pred"] = orthogonality_diagnostics(dperp_pred, c_te)
dperp["r2_drop"] = explained_variance_drop(pred_rate, dperp_pred, c_te, seed=seed)
dperp["stratified_rank"] = stratified_rank_correlation(
dperp_pred, dperp_target, c_te, n_strata=5)
dperp["null_head"] = null_head_negative_control(
pred_rate_tr, pred_rate, c_tr, c_te, dperp_target,
n_shuffle_repeats=n_shuffled_head_repeats, seed=seed, fix_leakage=True)
rates_te = np.asarray([j.break_rate_shrunk for j in te])
counts_te = np.asarray([j.n_obs for j in te])
ceiling = parametric_reliability(rates_te, counts_te, agg="mean", seed=seed)
# --- per-origin breakdown: only informative when `--dataset` pooled more
# than one suite (see _origin); a single-suite run collapses to one group
# and this is skipped downstream rather than printed as a no-op.
origins = np.asarray([_origin(j.base_id) for j in te])
by_origin: dict[str, dict] = {}
for origin in sorted(set(origins)):
mask = origins == origin
if mask.sum() < 3:
continue
by_origin[origin] = {
"n_test": int(mask.sum()),
"break_rate": _rho(pred_rate[mask], tgt["break_rate"][mask]),
"a": _rho(pred_a[mask], tgt["a"][mask]),
"b": _rho(pred_b[mask], tgt["b"][mask]),
}
if predictions_out is not None:
predictions_out.parent.mkdir(parents=True, exist_ok=True)
predictions_out.write_text(json.dumps({
"seed": seed,
"base_id": [j.base_id for j in te],
"pred_break_rate": pred_rate.tolist(),
"target_break_rate": tgt["break_rate"].tolist(),
"target_break_rate_shrunk": tgt["break_rate_shrunk"].tolist(),
}, indent=2))
return {
"seed": seed,
"split": split.summary(),
"features": finfo,
"n_features": int(X.shape[1]),
"training": model_history,
"rows": rows,
"extra_metrics": extra_metrics,
"d_avg_metrics": davg_metrics,
"dperp": dperp,
"ceiling_break_rate": ceiling.to_dict(),
"by_origin": by_origin,
"target_stats": {
"test_break_rate_mean": float(np.mean(tgt["break_rate"])),
"test_break_rate_sd": float(np.std(tgt["break_rate"])),
"d_avg_sd": float(np.std(tgt["d_avg"])),
},
}
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--dataset", required=True,
help="dose family (gsmic_adv, math_adv) or comma-separated files")
ap.add_argument("--seeds", default="0,1,2")
ap.add_argument("--featurizer", default="hf_finetune",
help="Text representation. Default hf_finetune = Frail-pi with a fully "
"fine-tuned DeBERTa-v3-base encoder (use a GPU). For a fast CPU "
"smoke run use tfidf_svd.")
ap.add_argument("--text-dim", type=int, default=256)
ap.add_argument("--protocol", default="text",
choices=("text", "text_probe", "text_measured", "both", "all"))
ap.add_argument("--reserve-obs", type=int, default=0,
help="Withhold this many twins per job from every target and expose "
"them as features to the text_measured protocol (required by "
"it, ignored otherwise)")
ap.add_argument("--reserve-mode", default="spread",
choices=("spread", "cheapest_dose"),
help="spread: reserved twins sampled across all doses, i.e. a budget "
"of k twin evaluations spent anywhere. cheapest_dose: confined "
"to the lowest dose, cheaper per call but extrapolating in dose")
ap.add_argument("--probe-file", default=None)
ap.add_argument("--val-frac", type=float, default=0.15)
ap.add_argument("--test-frac", type=float, default=0.30)
ap.add_argument("--max-epochs", type=int, default=200)
ap.add_argument("--patience", type=int, default=15)
ap.add_argument("--hidden-dim", type=int, default=256)
ap.add_argument("--min-obs", type=int, default=4)
ap.add_argument("--restrict-to-probe-file", action="store_true",
help="keep only jobs present in --probe-file, so the text and "
"text_probe protocols are compared on identical jobs")
ap.add_argument("--out-dir", default=None)
ap.add_argument("--family", action="store_true", dest="use_family",
help="thread perturbation family into the break-probability head "
"(predict per-family x dose, compose analytically to pi) "
"instead of marginalizing over it. Adds family one-hot next "
"to the dose features; changes model rows (break_rate/a/b).")
ap.add_argument("--device", default=None,
help="cuda / cuda:0 / cpu, for --featurizer hf_frozen|hf_lora|"
"hf_finetune. Default: cuda if visible, else cpu. Restrict to "
"specific GPUs with CUDA_VISIBLE_DEVICES rather than this flag "
"(hf_frozen/hf_finetune auto-shard across every visible GPU via "
"nn.DataParallel; hf_lora runs on the first visible one).")
ap.add_argument("--hf-model", default=None,
help="HF model id for hf_frozen/hf_lora/hf_finetune. Defaults: "
"sentence-transformers/all-MiniLM-L6-v2 (hf_frozen), "
"BAAI/bge-small-en-v1.5 (hf_lora), microsoft/deberta-v3-base (hf_finetune)")
ap.add_argument("--hf-batch-size", type=int, default=None,
help="hf_frozen: encode() batch size. openai_embed: max API "
"batch size (default 512). Raise on a GPU / high-throughput box.")
ap.add_argument("--cache-dir", default=None,
help="openai_embed: on-disk embedding cache directory "
"(default: cache/<dataset>)")
ap.add_argument("--max-concurrency", type=int, default=None,
help="openai_embed: parallel API requests (default 64)")
ap.add_argument("--lora-r", type=int, default=8)
ap.add_argument("--lora-alpha", type=int, default=16)
ap.add_argument("--lora-dropout", type=float, default=0.05)
ap.add_argument("--jobs-per-batch", type=int, default=64,
help="hf_lora/hf_finetune only: unique job texts encoded per "
"optimizer step (each contributes ~90-100 dose observations)")
ap.add_argument("--encoder-microbatch", type=int, default=16,
help="hf_lora/hf_finetune only: sub-chunk size for the encoder "
"forward pass within a job-batch, gradient-accumulated so peak "
"activation memory depends on this, not --jobs-per-batch. Lower "
"this first if you hit CUDA OOM; bert-base-uncased full "
"fine-tuning needs a real GPU at any reasonable value.")
ap.add_argument("--encoder-lr", type=float, default=2e-5,
help="hf_lora/hf_finetune only: LR for the encoder's trainable "
"parameters (LoRA adapters, or the whole transformer)")
ap.add_argument("--head-lr", type=float, default=1e-3,
help="hf_lora/hf_finetune only: LR for the break-probability head")
ap.add_argument("--encoder-max-epochs", type=int, default=30,
help="hf_lora/hf_finetune only: separate (smaller) epoch budget from "
"--max-epochs, since every epoch here backprops through the "
"encoder -- see docs/gsmic_math_adv_rerun_instructions.md")
ap.add_argument("--encoder-patience", type=int, default=5)
ap.add_argument("--max-grad-norm", type=float, default=1.0,
help="hf_lora/hf_finetune only: clip joint encoder+head "
"gradients to this L2 norm (0 disables clipping)")
ap.add_argument("--lambda-contrast", type=float, default=0.0,
help="hf_lora/hf_finetune only: weight of an auxiliary within-job "
"contrast term added to the per-observation BCE loss (paper's "
"eq:loss contrast supervision, adapted to this single-tower model "
"-- there is no second embedding tower to difference here, so the "
"contrast is formed between two twins' *predicted* break "
"probabilities within the same job, Huber-penalized against their "
"*actual* break-indicator difference). 0.0 (default) reproduces "
"the plain BCE objective the paper describes for Frail-pi.")
ap.add_argument("--max-contrast-pairs-per-job", type=int, default=32,
help="Cap on how many random within-job twin pairs are sampled per "
"job per step for --lambda-contrast > 0.")
ap.add_argument("--contrast-huber-delta", type=float, default=0.1,
help="Huber loss delta for the --lambda-contrast term.")
ap.add_argument("--loss-mode", default="bce",
choices=("bce", "soft_rank", "reliability_weighted"),
help="hf_lora/hf_finetune only: training objective. 'bce' (default) "
"is the plain per-observation BCE. 'soft_rank' replaces it with "
"a differentiable Spearman surrogate on job-level aggregated "
"predictions (optimizes rank order directly, since val/test "
"selection is already Spearman). 'reliability_weighted' keeps "
"BCE but reweights each job's observations by an inverse-"
"variance weight from that job's own measured binomial SE.")
ap.add_argument("--rank-temperature", type=float, default=5.0,
help="--loss-mode soft_rank: temperature for the pairwise-sigmoid "
"soft-rank operator (lower = closer to hard ranks, higher "
"gradient noise).")
ap.add_argument("--reliability-eps", type=float, default=1e-3,
help="--loss-mode reliability_weighted: variance floor added before "
"inverting, so near-zero-variance jobs don't get unbounded weight.")
ap.add_argument("--encoder-lr-schedule", default="constant",
choices=("constant", "linear"),
help="hf_lora/hf_finetune only: 'linear' = linear warmup over "
"--encoder-warmup-frac of the max-epoch step budget, then linear "
"decay to 0. 'constant' (default) is the original recipe.")
ap.add_argument("--encoder-warmup-frac", type=float, default=0.0)
ap.add_argument("--layer-lr-decay", type=float, default=1.0,
help="hf_finetune only: layer-wise LR decay factor (<1 gives lower "
"layers smaller LRs); 1.0 (default) is a single encoder LR.")
ap.add_argument("--encoder-bf16", action="store_true",
help="hf_lora/hf_finetune only: bf16 autocast for the encoder forward.")
ap.add_argument("--encoder-max-length", type=int, default=None,
help="hf_finetune/hf_lora only: tokenizer max_length (default: "
"the backbone builder's default, 128 for hf_finetune).")
ap.add_argument("--encoder-pooling", default="mean", choices=("mean", "last"),
help="hf_lora only: 'last' = last non-pad token (decoder-LM "
"embedders); 'mean' (default) is the original mean pooling.")
ap.add_argument("--solution-file", default=None,
help="text_probe only, hf_lora/hf_finetune only: JSON {base_id: solver "
"solution} (scripts/build_solution_texts.py, from the base-probe "
"completions cache). The encoder then reads the base problem plus "
"that sampled solution; surface features still use the problem "
"alone. Raise --encoder-max-length (e.g. 512) with this.")
ap.add_argument("--aux-train-dataset", default=None,
help="hf_lora/hf_finetune only: labeled pairs (e.g. the pooled "
"multi-dose corpus) whose job targets replace the train-fold jobs "
"of --dataset (same base problems, more twins). Splits, "
"validation and test targets are those of --dataset.")
ap.add_argument("--save-checkpoint", action="store_true",
help="hf_lora/hf_finetune only: save every fitted model (head + "
"encoder weights in fp16 + feature/split metadata) to "
"<out-dir>/checkpoints/<protocol>_seed<k>_init<i>.pt; reload "
"with scripts/frailpi_predict_from_checkpoint.py")
ap.add_argument("--encoder-base-dtype", default="float32",
choices=("float32", "bfloat16"),
help="hf_lora only: dtype of the frozen base weights (bfloat16 lets "
"7-14B decoders fit); LoRA adapters always train in fp32.")
ap.add_argument("--shuffle-encoder-text", action="store_true",
help="control: the trainable encoder reads a *different* job's text "
"(fixed random permutation over jobs); surface/probe features keep "
"the true job's. Measures what the problem text itself contributes.")
ap.add_argument("--n-inits", type=int, default=1,
help="hf_lora/hf_finetune only: train this many independently "
"initialized models per split seed and average their predicted "
"break probabilities (each member early-stopped on the validation "
"fold). 1 (default) is the single-model run.")
ap.add_argument("--skip-existing-seeds", action="store_true",
help="Skip training for seeds whose per-seed cache exists "
"under <out-dir>/seeds/seed_<N>/<protocol>.json")
ap.add_argument("--allow-partial-summary", action="store_true",
help="Write summary.json even when some expected seeds are "
"missing (default: refuse to write an incomplete summary)")
ap.add_argument("--include-bertpe-vap3", action="store_true",
help="Add BERTPE/VAP3 (re-implementations of two published sensitivity "
"predictors, retargeted to pi -- see baselines/pi_adapters.py) as "
"extra baseline rows. Both fine-tune bert-base-uncased end to end; "
"expensive, GPU recommended for anything beyond --max-jobs smoke "
"testing.")
ap.add_argument("--bertpe-epochs", type=int, default=3)
ap.add_argument("--vap3-epochs", type=int, default=3)
ap.add_argument("--bertpe-vap3-batch-size", type=int, default=16)
ap.add_argument("--n-shuffled-head-repeats", type=int, default=100,
help="D^perp shuffled-head negative control: number of "
"random per-job reassignments of the predictor's "
"own outputs (tab:c2 shared-term control).")
ap.add_argument("--max-jobs", type=int, default=None,
help="Randomly subsample to this many solvable jobs before splitting "
"(e.g. for a fast --include-bertpe-vap3 smoke test on CPU)")
ap.add_argument("--max-jobs-seed", type=int, default=0)
ap.add_argument("--dump-predictions", action="store_true",
help="Write each seed's test-fold (base_id, pred_break_rate, "
"target_break_rate) to <out-dir>/predictions/ so a separate "
"run (e.g. a different --featurizer) can be blended with this "
"one post hoc -- see scripts/ensemble_fragility.py. Splits are "
"deterministic in (--dataset, seed), so two runs with the same "
"--dataset and --seeds share test folds even with different "
"featurizers.")
args = ap.parse_args()
print(f"Loading {args.dataset} ...")
pairs, paths = load_pairs(args.dataset)
doses = sorted({d for p in pairs if (d := dose_from_operator(p.operator)) is not None})
jobs = build_job_targets(pairs, solvable_only=True, min_obs=args.min_obs,
reserve_obs=args.reserve_obs,
reserve_mode=args.reserve_mode,
keep_twin_texts=args.include_bertpe_vap3)
if args.max_jobs and args.max_jobs < len(jobs):
import random
jobs = sorted(random.Random(args.max_jobs_seed).sample(jobs, args.max_jobs),
key=lambda j: j.base_id)
print(f" --max-jobs: subsampled to {len(jobs)} jobs")
if args.restrict_to_probe_file:
if not args.probe_file:
raise SystemExit("--restrict-to-probe-file requires --probe-file")
covered = set(probe_feats.read_probe_file(args.probe_file))
jobs = [j for j in jobs if j.base_id in covered]
print(f" restricted to the {len(jobs)} jobs covered by the probe file")
print(f" {len(pairs)} pairs -> {len(jobs)} solvable jobs, doses {doses}")
print(f" mean observations per job: {np.mean([j.n_obs for j in jobs]):.1f}")
cfg = TrainConfig(hidden_dim=args.hidden_dim, max_epochs=args.max_epochs,
patience=args.patience)
encoder_cfg = EncoderTrainConfig(
hidden_dim=args.hidden_dim, jobs_per_batch=args.jobs_per_batch,
encoder_microbatch=args.encoder_microbatch, encoder_lr=args.encoder_lr,
head_lr=args.head_lr, max_epochs=args.encoder_max_epochs,
patience=args.encoder_patience, device=args.device,
max_grad_norm=args.max_grad_norm, lambda_contrast=args.lambda_contrast,
max_contrast_pairs_per_job=args.max_contrast_pairs_per_job,
huber_delta=args.contrast_huber_delta, loss_mode=args.loss_mode,
rank_temperature=args.rank_temperature, reliability_eps=args.reliability_eps,
lr_schedule=args.encoder_lr_schedule, warmup_frac=args.encoder_warmup_frac,
layer_lr_decay=args.layer_lr_decay, bf16=args.encoder_bf16)
if args.use_family:
cfg.use_family = True
cfg.n_families = len(FAMILIES)
encoder_cfg.use_family = True
encoder_cfg.n_families = len(FAMILIES)
print(f" factorized head: threading {len(FAMILIES)} families into per-observation design")
if args.protocol == "both":
protocols = ("text", "text_probe")
elif args.protocol == "all":
protocols = ("text", "text_probe", "text_measured")
else:
protocols = (args.protocol,)
if "text_measured" in protocols and args.reserve_obs <= 0:
raise SystemExit("protocol text_measured requires --reserve-obs > 0")
aux_train_jobs = None
if args.aux_train_dataset:
aux_pairs, _ = load_pairs(args.aux_train_dataset)
aux_list = build_job_targets(aux_pairs, solvable_only=True, min_obs=args.min_obs,
reserve_obs=args.reserve_obs,
reserve_mode=args.reserve_mode)
aux_train_jobs = {j.base_id: j for j in aux_list}
print(f" aux train targets: {len(aux_list)} jobs, mean observations "
f"{np.mean([j.n_obs for j in aux_list]):.1f}")
if args.shuffle_encoder_text:
import random
donors = [getattr(j, "encoder_text", None) or j.base_text for j in jobs]
random.Random(12345).shuffle(donors)
for j, t in zip(jobs, donors):
j.encoder_text = t
print(" CONTROL: encoder texts permuted across jobs")
if args.solution_file:
if set(protocols) != {"text_probe"}:
raise SystemExit("--solution-file feeds solver output to the encoder, so it "
"is only allowed with --protocol text_probe")
solutions = json.loads(Path(args.solution_file).read_text())
missing = [j.base_id for j in jobs if j.base_id not in solutions]
if missing:
raise SystemExit(f"--solution-file lacks {len(missing)} of {len(jobs)} jobs")
for j in [*jobs, *(aux_train_jobs or {}).values()]:
if j.base_id in solutions:
j.encoder_text = f"{j.base_text}\n\nSolution: {solutions[j.base_id]}"
seeds = [int(s) for s in args.seeds.split(",")]
expected_seeds = seeds
cache_dir = args.cache_dir or str(ROOT / "cache" / args.dataset)
max_concurrency = args.max_concurrency
if args.featurizer == "openai_embed" and max_concurrency is None:
max_concurrency = 64
if args.featurizer == "openai_embed" and args.hf_batch_size is None:
args.hf_batch_size = 512
if args.featurizer == "hf_frozen" and args.hf_batch_size is None:
args.hf_batch_size = 1024
out_dir = Path(args.out_dir) if args.out_dir else ROOT / "outputs_fragility" / args.dataset
out_dir.mkdir(parents=True, exist_ok=True)
results: dict[str, list[dict]] = {}
for proto in protocols:
results[proto] = []
for seed in seeds:
cache_path = _seed_cache_path(out_dir, seed, proto)
if args.skip_existing_seeds and cache_path.is_file():
print(f"\n=== protocol={proto} seed={seed} (cached) ===")
results[proto].append(_load_seed_cache(cache_path))
continue
print(f"\n=== protocol={proto} seed={seed} ===")
predictions_out = (
out_dir / "predictions" / f"{args.featurizer}_{proto}_seed{seed}.json"
if args.dump_predictions else None)
res = run_seed(jobs, seed=seed, featurizer=args.featurizer, protocol=proto,
probe_file=args.probe_file, dim=args.text_dim,
cfg=cfg, val_frac=args.val_frac,
test_frac=args.test_frac, encoder_cfg=encoder_cfg,
hf_model=args.hf_model, device=args.device,
hf_batch_size=args.hf_batch_size,
cache_dir=cache_dir, max_concurrency=max_concurrency,
lora_r=args.lora_r, lora_alpha=args.lora_alpha,
lora_dropout=args.lora_dropout,
include_bertpe_vap3=args.include_bertpe_vap3,
bertpe_epochs=args.bertpe_epochs, vap3_epochs=args.vap3_epochs,
bertpe_vap3_batch_size=args.bertpe_vap3_batch_size,
predictions_out=predictions_out,
n_shuffled_head_repeats=args.n_shuffled_head_repeats,
n_inits=args.n_inits,
encoder_max_length=args.encoder_max_length,
encoder_pooling=args.encoder_pooling,
encoder_base_dtype=args.encoder_base_dtype,
aux_train_jobs=aux_train_jobs,
checkpoint_dir=(out_dir / "checkpoints"
if args.save_checkpoint else None),
checkpoint_meta={"dataset": args.dataset,
"solution_file": args.solution_file,
"aux_train_dataset": args.aux_train_dataset,
"min_obs": args.min_obs,
"argv": sys.argv[1:]})
_save_seed_cache(cache_path, res)
t = res["training"]
print(f" split {res['split']['n_train']}/{res['split']['n_val']}/"
f"{res['split']['n_test']} (fingerprint {res['split']['split_fingerprint']})")
print(f" early stopping: best epoch {t['best_epoch']} of "
f"{t['epochs_run']} run, val rho_S={t['best_val_spearman']:.3f}")
print(f" TEST rho_S break_rate={res['rows']['model']['break_rate']:+.3f} "
f"a={res['rows']['model']['a']:+.3f} b={res['rows']['model']['b']:+.3f}")
print(f" surface baseline break_rate="
f"{res['rows']['surface_features']['break_rate']:+.3f} "
f"D^perp model={res['dperp']['model']:+.3f}")
results[proto].append(res)
targets = ("break_rate", "break_rate_shrunk", "a", "b", "d_avg")
methods = ("model", "same_features_joblevel_regression", "surface_features",
"declared_complexity_only", "measured_base_correctness")
if args.include_bertpe_vap3:
methods = methods + ("bertpe", "vap3")
extra_metric_names = ("spearman", "mae", "ndcg@10", "auroc")
# Additive: same 5-column shape as Table tab:synth2 (rho_S, MAE, NDCG@10,
# AUROC, |rho_C|), but against d_avg -- see run_seed's d_avg_metrics block.
davg_metric_names = ("spearman", "mae", "ndcg@10", "auroc", "deconfound_|rho_C|")
dperp_keys = ("model", "surface_features", "spearman_target_vs_proxy")
if args.include_bertpe_vap3:
dperp_keys = dperp_keys + ("bertpe", "vap3")
summary: dict = {
"dataset": args.dataset,
"data_files": [str(p) for p in paths],
"doses": doses,
"n_solvable_jobs": len(jobs),
"mean_obs_per_job": float(np.mean([j.n_obs for j in jobs])),
"featurizer": args.featurizer,
"min_obs": args.min_obs,
"seeds": expected_seeds,
"protocols": {},
}
lines = [
f"# Fragility prediction -- {args.dataset}",
"",
f"Target: conditional break rate on the solvable stratum "
f"({len(jobs)} jobs, {np.mean([j.n_obs for j in jobs]):.0f} observations each, "
f"doses {doses}).",
f"Encoder: `{args.featurizer}`. Seeds: PLACEHOLDER. Test Spearman as mean +/- sd "
f"over seeds. Model trained in-process on the train fold, epochs chosen by "
f"early stopping on the validation fold.",
"",
]
for proto in protocols:
runs, missing = _collect_seed_results(out_dir, proto, expected_seeds, results[proto])
if missing and not args.allow_partial_summary:
print(f"\nSkip summary for protocol={proto}: missing seed results {missing}. "
f"Re-run with --seeds {','.join(str(s) for s in missing)} or place caches "
f"under {out_dir}/seeds/seed_<N>/{proto}.json")
continue
if not runs:
continue
summary_seeds = sorted({r["seed"] for r in runs})
agg: dict = {"rows": {}, "extra_metrics": {}, "d_avg_metrics": {}, "dperp": {},
"training": {}, "splits": []}
for method in methods:
agg["rows"][method] = {}
for tgt in targets:
m, s = _mean_sd([r["rows"][method][tgt] for r in runs])
agg["rows"][method][tgt] = {"mean": m, "sd": s}
agg["extra_metrics"][method] = {}
for metric in extra_metric_names:
m, s = _mean_sd([r["extra_metrics"][method][metric] for r in runs])
agg["extra_metrics"][method][metric] = {"mean": m, "sd": s}
# Additive: aggregate d_avg_metrics the same way as extra_metrics.
agg["d_avg_metrics"][method] = {}
for metric in davg_metric_names:
m, s = _mean_sd([r["d_avg_metrics"][method][metric] for r in runs])
agg["d_avg_metrics"][method][metric] = {"mean": m, "sd": s}
for key in dperp_keys:
m, s = _mean_sd([r["dperp"][key] for r in runs])
agg["dperp"][key] = {"mean": m, "sd": s}
agg["dperp_diagnostics"] = _aggregate_dperp_diagnostics(runs)
m, s = _mean_sd([r["training"]["best_val_spearman"] for r in runs])
agg["training"] = {
"best_val_spearman": {"mean": m, "sd": s},
"best_epochs": [r["training"]["best_epoch"] for r in runs],
"early_stopped": [r["training"]["early_stopped"] for r in runs],
}
agg["splits"] = [r["split"] for r in runs]
agg["ceiling_break_rate"] = runs[0]["ceiling_break_rate"]
# Spearman / reliability ceiling, per seed (the paper's headline scale: 1.0 is
# the best any predictor can do given the label noise). The pi ceiling is used
# for every target as a common scale.
agg["rows_normalized"] = {}
for method in methods:
agg["rows_normalized"][method] = {}
for tgt in targets:
vals = []
for r in runs:
c = r["ceiling_break_rate"]["ceiling_sqrt_r"]
v = r["rows"][method][tgt]
vals.append(v / c if np.isfinite(c) and c > 0 else float("nan"))
m, sd = _mean_sd(vals)
agg["rows_normalized"][method][tgt] = {"mean": m, "sd": sd}
agg["features"] = runs[0]["features"]
# Per-origin breakdown (only non-empty when --dataset pooled more than
# one suite): aggregate each origin's break_rate rho across seeds.
all_origins = sorted({o for r in runs for o in r["by_origin"]})
agg["by_origin"] = {}
for origin in all_origins:
vals = [r["by_origin"][origin]["break_rate"] for r in runs if origin in r["by_origin"]]
m, s = _mean_sd(vals)
agg["by_origin"][origin] = {
"break_rate": {"mean": m, "sd": s},
"n_test": [r["by_origin"][origin]["n_test"] for r in runs if origin in r["by_origin"]],
}
summary["protocols"][proto] = agg
summary["seeds"] = summary_seeds
ceiling = runs[0]["ceiling_break_rate"]["ceiling_sqrt_r"]
rho = agg["rows"]["model"]["break_rate"]["mean"]
lines += [
f"## Protocol: {proto}",
"",
f"Reliability ceiling on the break rate: {ceiling:.3f} "
f"(parametric bootstrap). Model reaches "
f"{rho:.3f}, i.e. {rho / ceiling * 100:.0f}% of it."
if np.isfinite(ceiling) and ceiling > 0 else "",
"",
"**Spearman divided by the reliability ceiling** (1.0 = the best attainable; "
"this is the scale used in the paper):",
"",
"| Method | " + " | ".join(targets) + " |",
"| --- | " + " | ".join("---" for _ in targets) + " |",
]
for method in methods:
cells = []
for tgt in targets:
v = agg["rows_normalized"][method][tgt]
cells.append("n/a" if not np.isfinite(v["mean"])
else f"{v['mean']:.3f} ± {v['sd']:.3f}")
lines.append(f"| {method} | " + " | ".join(cells) + " |")
lines += [
"",
"Raw Spearman:",
"",
"| Method | " + " | ".join(targets) + " |",
"| --- | " + " | ".join("---" for _ in targets) + " |",
]
for method in methods:
cells = []
for tgt in targets:
v = agg["rows"][method][tgt]
cells.append("n/a" if not np.isfinite(v["mean"])
else f"{v['mean']:.3f} ± {v['sd']:.3f}")
lines.append(f"| {method} | " + " | ".join(cells) + " |")
dperp_line = (
f"D^perp (residualized against the declared surface proxy): model "
f"{agg['dperp']['model']['mean']:.3f} ± {agg['dperp']['model']['sd']:.3f}, "
f"surface baseline {agg['dperp']['surface_features']['mean']:.3f}")
if args.include_bertpe_vap3:
dperp_line += (
f", BERTPE {agg['dperp']['bertpe']['mean']:.3f}, "
f"VAP3 {agg['dperp']['vap3']['mean']:.3f}")
dperp_line += (
f". Spearman(target, proxy) = "
f"{agg['dperp']['spearman_target_vs_proxy']['mean']:.3f}, which is how "
f"much complexity there was to remove.")
lines += [
"",
f"Metrics against the primary target (break rate / pi), fragile cutoff = "
f"median(pi) on this fold:",
"",
"| Method | " + " | ".join(extra_metric_names) + " |",
"| --- | " + " | ".join("---" for _ in extra_metric_names) + " |",
]
for method in methods:
cells = []
for metric in extra_metric_names:
v = agg["extra_metrics"][method][metric]
cells.append("n/a" if not np.isfinite(v["mean"])
else f"{v['mean']:.3f} ± {v['sd']:.3f}")
lines.append(f"| {method} | " + " | ".join(cells) + " |")
# Additive: same 5-column shape as Table tab:synth2 (rho_S, MAE,
# NDCG@10, AUROC, |rho_C|), against d_avg instead of break_rate/pi --
# see run_seed's d_avg_metrics block and paper_supports_synth2.py's
# _write_avg_table, which this mirrors column-for-column.
davg_metric_labels = ("spearman", "mae", "ndcg@10", "auroc", "|rho_C|")
lines += [
"",
"Metrics against d_avg (same column set as Table tab:synth2), "
"fragile cutoff = median(d_avg) on this fold:",
"",
"| Method | " + " | ".join(davg_metric_labels) + " |",
"| --- | " + " | ".join("---" for _ in davg_metric_labels) + " |",
]
for method in methods:
cells = []
for metric in davg_metric_names:
v = agg["d_avg_metrics"][method][metric]
cells.append("n/a" if not np.isfinite(v["mean"])
else f"{v['mean']:.3f} ± {v['sd']:.3f}")
lines.append(f"| {method} | " + " | ".join(cells) + " |")
origin_lines = []
if len(agg["by_origin"]) > 1:
origin_lines = [
"",
"Per-origin breakdown (this run's `--dataset` pooled more than one "
"suite; the table above is the mixed pool, this is each suite scored "
"on its own subset of the same test fold):",
"",
"| Origin | break_rate rho | mean n_test |",
"| --- | --- | --- |",
] + [
f"| {origin} | {v['break_rate']['mean']:.3f} ± {v['break_rate']['sd']:.3f} "
f"| {np.mean(v['n_test']):.0f} |"
for origin, v in agg["by_origin"].items()
]
lines += [
"",
dperp_line,
*origin_lines,
*_dperp_diagnostics_lines(agg["dperp_diagnostics"]),
"",
f"Early stopping selected epochs {agg['training']['best_epochs']} "
f"(validation rho_S "
f"{agg['training']['best_val_spearman']['mean']:.3f} ± "
f"{agg['training']['best_val_spearman']['sd']:.3f}).",
"",
"`measured_base_correctness` is not an ex-ante text predictor: it is the "
"model's own measured accuracy on the base problem, reported to show how "
"much of each target is just solvability."
+ (" `bertpe`/`vap3` are the published sensitivity predictors retargeted "
"from the retracted D_wc to this repaired pi -- see baselines/pi_adapters.py."
if args.include_bertpe_vap3 else ""),
"",
]
if not summary["protocols"]:
print("\nNo complete protocol summaries; not writing summary.json or report.md")
return
lines[3] = (
f"Encoder: `{args.featurizer}`. Seeds: {summary['seeds']}. Test Spearman as mean +/- sd "
f"over seeds. Model trained in-process on the train fold, epochs chosen by "
f"early stopping on the validation fold."
)
(out_dir / "summary.json").write_text(json.dumps(summary, indent=2))
(out_dir / "report.md").write_text("\n".join(l for l in lines if l is not None) + "\n")
print(f"\nWrote {out_dir}/report.md and summary.json")
if __name__ == "__main__":
main()
#!/usr/bin/env python
"""Headline fragility-prediction results on the repaired estimand.
Everything the retracted numbers got wrong is closed off here by construction:
* the target is the conditional break rate on the **solvable stratum** (and its
dose-response parameters), not a ``max`` capped by base correctness;
* the split is **three-way** with a fingerprint, and the model is trained inside
this process on the train fold only -- there is no ``--checkpoint`` path that
could smuggle in weights fit on the test fold;
* epochs are chosen by **early stopping on the validation fold**, never on test;
* the ceiling is the **parametric-bootstrap** reliability, not Spearman-Brown on
an order statistic;
* every number is reported over several seeds with a spread;
* the surface-feature baseline and the measured-base-correctness reference are
reported alongside, so a headline that merely rediscovers length or solvability
is visible as such.
Two protocols are reported separately and never merged. ``text`` uses the
problem statement only. ``text_probe`` adds ex-ante probe features from repeated
samples of the *base* prompt (no twin is ever run), which requires model access
and is therefore a different claim.
Usage
-----
python scripts/fragility_report.py --dataset gsmic_adv --seeds 0,1,2
python scripts/fragility_report.py --dataset math_adv --featurizer tfidf_svd
python scripts/fragility_report.py --dataset gsmic_adv --protocol both \\
--probe-file outputs_probes/gsmic_adv/base_probes.json
"""
from __future__ import annotations
import argparse
import gc
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
import numpy as np
import torch
from scipy.stats import spearmanr
from causal_difficulty.baselines.bertpe import BERTPEBaseline
from causal_difficulty.baselines.pi_adapters import bertpe_job_pairs, vap3_twin_pairs
from causal_difficulty.baselines.vap3 import VAP3Baseline
from causal_difficulty.eval.deconfound import (
cross_fitted_residual,
explained_variance_drop,
null_head_negative_control,
orthogonality_diagnostics,
predict_m,
stratified_rank_correlation,
)
from causal_difficulty.eval.estimands import (
FAMILIES,
build_job_targets,
dose_from_operator,
)
from causal_difficulty.eval.loading import load_pairs
from causal_difficulty.eval.metrics import all_metrics, deconfounding_probe
from causal_difficulty.eval.reliability import parametric_reliability
from causal_difficulty.eval.splits import three_way_split
from causal_difficulty.features import probes as probe_feats
from causal_difficulty.features.surface import (
SURFACE_FEATURE_NAMES,
declared_proxy_scores,
out_of_fold_predictions,
surface_baseline_predictions,
surface_matrix,
)
from causal_difficulty.features.text import TextFeaturizer
from causal_difficulty.models.fragility import (
FragilityModel,
TrainConfig,
dose_response_from_grid,
expected_mean,
)
from causal_difficulty.models.fragility_encoder import (
EncoderFragilityModel,
EncoderTrainConfig,
)
ROOT = Path(__file__).resolve().parents[1]
# Backbones whose whole point is gradient-based adaptation to the break-
# probability objective: routed through EncoderFragilityModel (joint
# encoder+head training) instead of the precomputed-feature TextFeaturizer
# path every other --featurizer value uses. See fragility_encoder.py's
# module docstring for why a frozen/precomputed split doesn't make sense here.
TRAINABLE_ENCODER_BACKBONES = ("hf_lora", "hf_finetune")
def _origin(base_id: str) -> str:
"""``<dataset>-<index>`` -> ``<dataset>``, so a pooled ``--dataset`` spec
spanning multiple suites (e.g. every gsmic_adv_* and math_adv_* file in one
run) can still be scored per-suite, not just on the mixed pool."""
return base_id.rsplit("-", 1)[0]