Download scripts/downstream_curation.py from Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs: direct link, hf CLI and curl.
- Browser
- Download file 14.4 kB
-
https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/downstream_curation.py
- Command line
-
hf download hf://Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/scripts/downstream_curation.py
-
curl -L -o downstream_curation.py https://huggingface.co/Upwork-AIML/Conditional_Causal_Difficulty_for_LLMs/resolve/main/scripts/downstream_curation.py
14.4 kB
| #!/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() | |