#!/usr/bin/env python """Cross-model transfer of the causal-difficulty predictor. Addresses the reviewer critique *"with N=1 scoring model there's no test of the most interesting question the framing invites: does fragility predicted for one model transfer to another?"*. The causal-difficulty estimand is defined *per model* -- ``tau`` is the effect of a perturbation on a *fixed* model. This script measures how well an SCE predictor trained on model A's measured ``tau`` ranks the fragility measured on a *different* model B. Given several configs that label the SAME GSM8K problems (same ``base_id = gsmic_adv-{i}``) with different scoring models, it builds the full train-model x eval-model transfer matrix: * diagonal (train A / eval A) -- in-distribution accuracy (held-out ``rho_S``) * off-diag (train A / eval B) -- cross-model transfer of the ranking Both arms use the SAME stratified holdout split (same seed), and predictions are joined to the eval model's measured ``tau`` by shared ``base_id``, so the comparison is apples-to-apples on a common held-out problem set. A high off-diagonal ``rho_S`` means the *tasks* an SCE flags as fragile for model A are also the fragile ones for model B -- evidence the signal is a property of the task, not an artifact of one model. PREREQUISITE -- produce the per-model labels first (no new code needed; the pipeline's ``--model`` flag already selects the scorer). IMPORTANT: the LLM response cache key is model-agnostic, so each model MUST use a distinct ``--cache-dir`` and ``--output`` or responses cross-contaminate:: python scripts/gsmic_adv_pipeline.py --model gpt-4o-mini \\ --max-problems 1319 --distractors-per-twin 9 --max-distractors 20 \\ --cache-dir cache/gsmic_adv_m9_gpt4omini \\ --output data/gsmic_adv_m9_gpt4omini_labeled_pairs.jsonl python scripts/gsmic_adv_pipeline.py --model gpt-4o --cache-dir cache/gsmic_adv_m9_gpt4o --output data/gsmic_adv_m9_gpt4o_labeled_pairs.jsonl ... python scripts/gsmic_adv_pipeline.py --model gpt-3.5-turbo --cache-dir cache/gsmic_adv_m9_gpt35 --output data/gsmic_adv_m9_gpt35_labeled_pairs.jsonl ... then add a thin config per model (copy ``configs/gsmic_adv_m9_4omini.yaml`` and change only ``paths.labeled_pairs`` / ``outputs_dir`` / ``cache_dir``). Usage ----- python scripts/cross_model_transfer.py \\ --configs gsmic_adv_m9_gpt4omini gsmic_adv_m9_gpt4o gsmic_adv_m9_gpt35 \\ --seed 7 """ from __future__ import annotations import argparse import json import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) import numpy as np ROOT = Path(__file__).resolve().parents[1] def _train_predictor(config_name, seed): """Train an SCE on ``config_name``'s train split; return a callable that predicts per-job mean contrast on arbitrary (base_text, twin_texts) jobs, plus this config's holdout base_ids (for the diagonal split).""" import torch from causal_difficulty.config import load_config from causal_difficulty.encoders import build_encoder from causal_difficulty.eval.reports import _aggregate, _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 cfg = load_config(config_name) pairs, pairs_path = read_labeled_pairs(cfg, config_name, LabeledPair) if not pairs: raise FileNotFoundError(f"No labeled pairs at {pairs_path} for {config_name}.") 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) hold_ids = sorted(_aggregate(hold_pairs).keys()) 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 predict(ids, base_texts, twins_by_base): out = [] with torch.no_grad(): for b, btext in zip(ids, base_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) return predict, set(hold_ids), pairs_path def _load_eval(config_name, seed): """Return the held-out jobs (aggregated) for the eval config under the same split seed: {base_id: (base_text, twins, measured_tau, complexity)}.""" from causal_difficulty.config import load_config from causal_difficulty.eval.reports import _aggregate, _split from causal_difficulty.io_utils import read_labeled_pairs from causal_difficulty.schemas import LabeledPair cfg = load_config(config_name) pairs, _ = read_labeled_pairs(cfg, config_name, LabeledPair) stratified = cfg.eval.get("stratified_split", False) holdout_frac = cfg.eval.get("holdout_frac", 0.3) _, hold_pairs = _split(pairs, holdout_frac, seed, stratified=stratified) hold = _aggregate(hold_pairs) threshold = cfg.eval.get("fragile_threshold", 0.05) return hold, float(threshold) def main() -> None: parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--configs", nargs="+", required=True, help="Two or more configs labeling the SAME problems with " "different scoring models (shared base_id).") parser.add_argument("--seed", type=int, default=7) parser.add_argument("--out-dir", default=None) args = parser.parse_args() from causal_difficulty.eval import metrics out_dir = (Path(args.out_dir) if args.out_dir else ROOT / "outputs_real_supports" / "cross_model_transfer") out_dir.mkdir(parents=True, exist_ok=True) if len(args.configs) < 2: sys.exit("ERROR: --configs needs >= 2 configs (different scoring models).") # Train one predictor per config, and load one eval holdout per config. predictors, eval_holds, thresholds = {}, {}, {} for cfgname in args.configs: print(f"\n=== training predictor on {cfgname} (seed {args.seed}) ===") predictors[cfgname], _hold_ids, path = _train_predictor(cfgname, args.seed) print(f" labels: {path}") for cfgname in args.configs: eval_holds[cfgname], thresholds[cfgname] = _load_eval(cfgname, args.seed) # Transfer matrix: rows train, cols eval. Join on the intersection of the # two configs' holdout base_ids so both arms score the same problems. matrix = {} for train_cfg in args.configs: matrix[train_cfg] = {} for eval_cfg in args.configs: hold = eval_holds[eval_cfg] thr = thresholds[eval_cfg] ids = sorted(hold.keys()) base_texts = [hold[b].base_text for b in ids] twins_by_base = {b: hold[b].twin_texts for b in ids} measured = np.array([hold[b].d_avg for b in ids], dtype=float) complexity = np.array([hold[b].complexity for b in ids], dtype=float) pred = predictors[train_cfg](ids, base_texts, twins_by_base) matrix[train_cfg][eval_cfg] = { "n_jobs": len(ids), "spearman": metrics.spearman(pred, measured), "ndcg@10": metrics.ndcg_at_k(pred, measured, 10), "auroc": metrics.auroc_fragile(pred, measured, thr), "deconfound_|rho_C|": metrics.deconfounding_probe(pred, complexity), } tag = " (in-dist)" if train_cfg == eval_cfg else " (transfer)" print(f"train={train_cfg:28s} eval={eval_cfg:28s} " f"rho_S={matrix[train_cfg][eval_cfg]['spearman']:.3f}{tag}") summary = {"configs": args.configs, "seed": args.seed, "matrix": matrix} (out_dir / "cross_model_transfer.json").write_text( json.dumps(summary, indent=2), encoding="utf-8") # Markdown: rho_S transfer matrix (rows=train model, cols=eval model) short = [c.replace("gsmic_adv_m9_", "").replace("gsmic_adv_", "") for c in args.configs] lines = [ "# Cross-model transfer of the SCE causal-difficulty predictor", "", f"Seed {args.seed}. Cell = held-out Spearman `rho_S` of the SCE contrast " "head trained on the ROW model's measured tau, evaluated against the " "COLUMN model's measured tau on the shared holdout problems. Diagonal = " "in-distribution; off-diagonal = cross-model transfer.", "", "| train \\\\ eval | " + " | ".join(short) + " |", "| --- | " + " | ".join("---" for _ in short) + " |", ] for train_cfg, tname in zip(args.configs, short): cells = [f"{matrix[train_cfg][ec]['spearman']:.3f}" for ec in args.configs] lines.append(f"| **{tname}** | " + " | ".join(cells) + " |") lines += ["", "Off-diagonal rho_S near the diagonal = the predictor's fragility " "ranking transfers across scoring models (the signal is a property " "of the task). Off-diagonal collapse toward 0 = model-specific."] (out_dir / "cross_model_transfer.md").write_text("\n".join(lines) + "\n", encoding="utf-8") print(f"\nWrote {out_dir / 'cross_model_transfer.md'}") print(f"Wrote {out_dir / 'cross_model_transfer.json'}") if __name__ == "__main__": main()