Download src/02a_train_probes.py from Raj-deep/ScoutRoute: direct link, hf CLI and curl.
- Browser
- Download file 18.5 kB
-
https://huggingface.co/Raj-deep/ScoutRoute/resolve/main/src/02a_train_probes.py
- Command line
-
hf download hf://Raj-deep/ScoutRoute/src/02a_train_probes.py
-
curl -L -o 02a_train_probes.py https://huggingface.co/Raj-deep/ScoutRoute/resolve/main/src/02a_train_probes.py
18.5 kB
| """ | |
| Step 2a: Train Hidden-State Probe + Routing Evaluation | |
| ====================================================== | |
| Three logit-based routing signals β all extracted during Step 1, no sampling: | |
| mean_log_prob [Feature A] β avg log-prob of answer tokens (zero training) | |
| neg_entropy [Feature B] β negated first-token entropy (zero training) | |
| probe_score [Feature C] β logistic probe on last hidden state (needs labels) | |
| The probe (Feature C) is the only thing trained here. | |
| Variant 2a (baseline): every probe is trained on the full cross-domain pool. | |
| See 02b_train_probes_specialist.py for the specialist-filtered variant. | |
| It uses is_correct labels (from clean ground-truth answer keys collected | |
| in Step 1) as supervision β no sampling needed. | |
| Baselines: | |
| random β pick a random expert per prompt | |
| oracle β always pick the correct expert (offline upper bound) | |
| Run: | |
| python src/02a_train_probes.py [--skip_probe] | |
| --skip_probe Evaluate only Features A and B (useful before all models finish) | |
| """ | |
| import json, joblib, warnings, argparse | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.decomposition import PCA | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.metrics import roc_auc_score | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| warnings.filterwarnings("ignore") | |
| BASE_DIR = Path(__file__).resolve().parent.parent # project root (scripts live in src/) | |
| RESULTS_DIR = BASE_DIR / "results" | |
| CKPT_DIR = BASE_DIR / "checkpoints" | |
| HIDDEN_DIR = BASE_DIR / "hidden_states" | |
| MODEL_DIR = BASE_DIR / "trained_models" | |
| PLOTS_DIR = BASE_DIR / "plots" | |
| for d in [MODEL_DIR, PLOTS_DIR]: | |
| d.mkdir(exist_ok=True) | |
| MODELS = { | |
| "qwen25_1b": "Qwen/Qwen2.5-1.5B-Instruct", | |
| "qwen25_3b": "Qwen/Qwen2.5-3B-Instruct", | |
| "phi3_mini": "microsoft/Phi-3-mini-4k-instruct", | |
| "qwen25_math": "Qwen/Qwen2.5-Math-1.5B-Instruct", | |
| "qwen25_coder": "Qwen/Qwen2.5-Coder-1.5B-Instruct", | |
| } | |
| # ββ Data loading βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def load_all_results(): | |
| """Combine Step 1 Parquet files into one long DataFrame.""" | |
| dfs = [] | |
| for f in RESULTS_DIR.glob("*_results.parquet"): | |
| dfs.append(pd.read_parquet(f)) | |
| if not dfs: | |
| raise FileNotFoundError( | |
| "No *_results.parquet found. Run 01_collect_data.py first." | |
| ) | |
| df = pd.concat(dfs, ignore_index=True) | |
| print(f"Loaded {len(df):,} rows | " | |
| f"{df['model_key'].nunique()} models | " | |
| f"{df['dataset'].nunique()} datasets") | |
| # Sanity check: confirm logit features are present | |
| for col in ["mean_log_prob", "first_tok_entropy"]: | |
| if col not in df.columns: | |
| raise ValueError( | |
| f"Column '{col}' missing. Re-run 01_collect_data.py β " | |
| "old checkpoint files lack logit features." | |
| ) | |
| # Safety net: all four domains have clean ground-truth answer keys loaded | |
| # directly from HuggingFace, so is_correct should always be 0 or 1. This | |
| # filter just guards against any stray bad rows (e.g. a crashed/partial | |
| # HumanEval execution that returned something unexpected). | |
| before = len(df) | |
| df = df[df["is_correct"].isin([0, 1])].copy() | |
| dropped = before - len(df) | |
| if dropped: | |
| print(f" Dropped {dropped:,} rows with invalid is_correct values") | |
| return df | |
| def load_hidden_states(model_key): | |
| """ | |
| Load saved hidden-state vectors for one model. | |
| Returns (list[prompt_id], np.ndarray of shape [N, D]) or (None, None). | |
| """ | |
| path = HIDDEN_DIR / f"{model_key}_hidden.npz" | |
| if not path.exists(): | |
| print(f" [{model_key}] No hidden states found at {path} β probe skipped") | |
| return None, None | |
| data = np.load(path, allow_pickle=True) | |
| ids = data["prompt_ids"].tolist() | |
| vecs = data["vectors"].astype(np.float32) | |
| print(f" [{model_key}] Loaded {len(ids):,} hidden states shape={vecs.shape}") | |
| return ids, vecs | |
| # ββ Train/eval split βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def make_split(results_df, train_frac=0.3, seed=42): | |
| """ | |
| Reserve train_frac of prompts for probe training. | |
| The remainder is the routing eval set. | |
| Stratified by dataset so all domains are represented in both splits. | |
| """ | |
| rng = np.random.default_rng(seed) | |
| train_ids = set() | |
| for ds, grp in results_df.groupby("dataset"): | |
| unique = grp["prompt_id"].unique() | |
| n_train = max(1, int(len(unique) * train_frac)) | |
| chosen = rng.choice(unique, size=n_train, replace=False) | |
| train_ids.update(chosen.tolist()) | |
| train_df = results_df[results_df["prompt_id"].isin(train_ids)].copy() | |
| eval_df = results_df[~results_df["prompt_id"].isin(train_ids)].copy() | |
| print(f"\nTrain split: {train_df['prompt_id'].nunique():,} prompts " | |
| f"({100*train_frac:.0f}% β used only for probe training)") | |
| print(f"Eval split: {eval_df['prompt_id'].nunique():,} prompts " | |
| f"(used for routing evaluation)\n") | |
| return train_ids, eval_df | |
| # ββ Feature C: hidden-state probe βββββββββββββββββββββββββββββββββββββββββββββ | |
| def train_probe(model_key, train_ids, results_df): | |
| """ | |
| Train a logistic regression probe: | |
| last-layer hidden state β is_correct (binary) | |
| Uses only the training split so the probe is never evaluated on | |
| the same prompts it was trained on. | |
| Returns a dict {prompt_id: probe_score} for ALL prompts (train + eval), | |
| or None if insufficient data. | |
| """ | |
| ids, vecs = load_hidden_states(model_key) | |
| if ids is None: | |
| return None, None | |
| # Labels: correctness from Step 1 results | |
| label_df = ( | |
| results_df[results_df["model_key"] == model_key] | |
| [["prompt_id", "is_correct"]] | |
| .drop_duplicates("prompt_id") | |
| .set_index("prompt_id") | |
| ) | |
| # ββ Train split only βββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| id_to_idx = {pid: i for i, pid in enumerate(ids)} | |
| train_pids = [pid for pid in ids if pid in train_ids and pid in label_df.index] | |
| if len(train_pids) < 30: | |
| print(f" [{model_key}] Too few training samples ({len(train_pids)}) β probe skipped") | |
| return None, None | |
| X_train = vecs[[id_to_idx[p] for p in train_pids]] | |
| y_train = label_df.loc[train_pids, "is_correct"].values.astype(int) | |
| # PCA: compress to 128 dims (avoids overfitting on small training sets) | |
| n_components = min(128, X_train.shape[0] - 1, X_train.shape[1]) | |
| pca = PCA(n_components=n_components) | |
| X_train_r = pca.fit_transform(X_train) | |
| # Held-out validation inside the training split | |
| X_tr, X_val, y_tr, y_val = train_test_split( | |
| X_train_r, y_train, test_size=0.2, random_state=42 | |
| ) | |
| probe = LogisticRegression(max_iter=1000, C=1.0, class_weight="balanced") | |
| probe.fit(X_tr, y_tr) | |
| if len(np.unique(y_val)) > 1: | |
| auroc = roc_auc_score(y_val, probe.predict_proba(X_val)[:, 1]) | |
| print(f" [{model_key}] Probe val AUROC={auroc:.3f} " | |
| f"n_train={len(X_tr)} n_val={len(X_val)}") | |
| else: | |
| auroc = float("nan") | |
| print(f" [{model_key}] Probe trained (AUROC undefined β single class in val)") | |
| # Save artefacts | |
| joblib.dump({"pca": pca, "probe": probe}, | |
| MODEL_DIR / f"{model_key}_probe.pkl") | |
| # ββ Score ALL prompt IDs (train + eval) ββββββββββββββββββββββββββββββββββββ | |
| # We score all of them but only use eval prompts during routing evaluation. | |
| all_pids = [pid for pid in ids if pid in label_df.index] | |
| X_all = pca.transform(vecs[[id_to_idx[p] for p in all_pids]]) | |
| scores_all = probe.predict_proba(X_all)[:, 1] | |
| probe_map = dict(zip(all_pids, scores_all.tolist())) | |
| metrics = { | |
| "model_key": model_key, | |
| "probe_auroc": round(float(auroc), 4), | |
| "n_train": len(X_tr), | |
| "n_val": len(X_val), | |
| "pca_dims": n_components, | |
| "n_scored": len(probe_map), | |
| } | |
| return probe_map, metrics | |
| # ββ Routing helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def route_and_score(eval_df, signal_col): | |
| """ | |
| For each prompt in eval_df, pick the expert with the highest signal_col. | |
| Returns fraction of prompts answered correctly by the chosen expert. | |
| """ | |
| correct, total = 0, 0 | |
| for _, grp in eval_df.groupby("prompt_id"): | |
| valid = grp.dropna(subset=[signal_col]) | |
| if valid.empty: | |
| continue | |
| best = valid.loc[valid[signal_col].idxmax()] | |
| correct += int(best["is_correct"]) | |
| total += 1 | |
| return correct / total if total > 0 else float("nan") | |
| def oracle_accuracy(eval_df): | |
| """Upper bound: always pick a correct expert if one exists.""" | |
| correct, total = 0, 0 | |
| for _, grp in eval_df.groupby("prompt_id"): | |
| correct += int(grp["is_correct"].max()) | |
| total += 1 | |
| return correct / total if total > 0 else float("nan") | |
| def random_accuracy(eval_df, seed=42, n_runs=5): | |
| """Average accuracy across n_runs of random expert selection.""" | |
| rng = np.random.default_rng(seed) | |
| accs = [] | |
| for _ in range(n_runs): | |
| correct, total = 0, 0 | |
| for _, grp in eval_df.groupby("prompt_id"): | |
| chosen = grp.sample(1, random_state=int(rng.integers(1e6))) | |
| correct += int(chosen["is_correct"].values[0]) | |
| total += 1 | |
| accs.append(correct / total if total > 0 else 0.0) | |
| return float(np.mean(accs)) | |
| # ββ ECE & reliability diagram ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def normalise_signal(series): | |
| """Min-max normalise to [0, 1] for ECE computation.""" | |
| lo, hi = series.min(), series.max() | |
| if hi == lo: | |
| return series * 0.0 | |
| return (series - lo) / (hi - lo) | |
| def compute_ece(df, signal_col, n_bins=10): | |
| sub = df[["is_correct", signal_col]].dropna() | |
| if len(sub) < n_bins: | |
| return float("nan") | |
| norm = normalise_signal(sub[signal_col]) | |
| ece = 0.0 | |
| for lo in np.linspace(0, 1, n_bins + 1)[:-1]: | |
| hi = lo + 1 / n_bins | |
| mask = (norm >= lo) & (norm < hi) | |
| if mask.sum() == 0: | |
| continue | |
| acc = sub["is_correct"][mask].mean() | |
| conf = norm[mask].mean() | |
| ece += (mask.sum() / len(sub)) * abs(acc - conf) | |
| return round(float(ece), 4) | |
| def plot_reliability(eval_df, signal_col, model_key, label, n_bins=10): | |
| sub = eval_df[["is_correct", signal_col]].dropna() | |
| if len(sub) < 50: | |
| return | |
| norm = normalise_signal(sub[signal_col]) | |
| bin_conf, bin_acc = [], [] | |
| for lo in np.linspace(0, 1, n_bins + 1)[:-1]: | |
| hi = lo + 1 / n_bins | |
| mask = (norm >= lo) & (norm < hi) | |
| if mask.sum() > 5: | |
| bin_conf.append(float(norm[mask].mean())) | |
| bin_acc.append(float(sub["is_correct"][mask].mean())) | |
| if not bin_conf: | |
| return | |
| plt.figure(figsize=(4.5, 4.5)) | |
| plt.plot([0, 1], [0, 1], "k--", alpha=0.4, label="Perfect calibration") | |
| plt.plot(bin_conf, bin_acc, "o-", label=label) | |
| plt.xlabel("Normalised signal (higher = more confident)") | |
| plt.ylabel("Fraction correct") | |
| plt.title(f"{model_key} | {label}") | |
| plt.legend(fontsize=8) | |
| plt.tight_layout() | |
| fname = f"reliability_{model_key}_{signal_col}.png" | |
| plt.savefig(PLOTS_DIR / fname, dpi=150) | |
| plt.close() | |
| # ββ Main βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--skip_probe", action="store_true", | |
| help="Skip probe training β evaluate only log_prob and entropy") | |
| args = parser.parse_args() | |
| print("=== Step 2a: Train Probe + Evaluate Routing ===\n") | |
| # 1. Load Step 1 results | |
| results_df = load_all_results() | |
| # 2. Train/eval split β 30% for probe training, 70% for routing eval | |
| # 30% (not 20%) for probe training β dataset is smaller (~464 prompts) | |
| # than originally planned, so a larger training fraction is needed for | |
| # the probe to see enough variance per domain. | |
| train_ids, eval_df = make_split(results_df, train_frac=0.3) | |
| # 3. Add neg_entropy column β higher = less uncertain = prefer this expert | |
| eval_df = eval_df.copy() | |
| results_df = results_df.copy() | |
| eval_df["neg_entropy"] = -eval_df["first_tok_entropy"] | |
| results_df["neg_entropy"] = -results_df["first_tok_entropy"] | |
| # 4. Train one hidden-state probe per model (Feature C) | |
| probe_metrics = [] | |
| probe_score_map = {} # {model_key: {prompt_id: score}} | |
| if not args.skip_probe: | |
| print("ββ Training hidden-state probes (Feature C) ββββββββββ") | |
| for mk in MODELS: | |
| result = train_probe(mk, train_ids, results_df) | |
| if result[0] is not None: | |
| probe_map, metrics = result | |
| probe_score_map[mk] = probe_map | |
| probe_metrics.append(metrics) | |
| if probe_metrics: | |
| probe_df = pd.DataFrame(probe_metrics) | |
| probe_df.to_csv(RESULTS_DIR / "probe_metrics.csv", index=False) | |
| print(f"\n{probe_df.to_string(index=False)}\n") | |
| # Attach probe scores to eval_df | |
| eval_df["probe_score"] = eval_df.apply( | |
| lambda r: probe_score_map.get(r["model_key"], {}).get(r["prompt_id"], np.nan), | |
| axis=1, | |
| ) | |
| else: | |
| print("Skipping probe training (--skip_probe set)\n") | |
| eval_df["probe_score"] = np.nan | |
| # 5. Routing evaluation | |
| print("ββ Routing accuracy ββββββββββββββββββββββββββββββββββ") | |
| signals = { | |
| "random": None, | |
| "log_prob": "mean_log_prob", # Feature A | |
| "neg_entropy": "neg_entropy", # Feature B | |
| "probe_score": "probe_score", # Feature C | |
| "oracle": None, | |
| } | |
| routing_results = {} | |
| routing_results["random"] = random_accuracy(eval_df) | |
| routing_results["oracle"] = oracle_accuracy(eval_df) | |
| for name, col in signals.items(): | |
| if col is None: | |
| continue | |
| if col not in eval_df.columns or eval_df[col].isna().all(): | |
| routing_results[name] = float("nan") | |
| else: | |
| routing_results[name] = route_and_score(eval_df, col) | |
| # Print results table | |
| print(f"\n {'Signal':<18} {'Source':<35} {'Accuracy':>9}") | |
| print(" " + "β" * 64) | |
| descriptions = { | |
| "random": "Random expert selection", | |
| "log_prob": "Avg log-prob of answer tokens [A]", | |
| "neg_entropy": "Negated first-token entropy [B]", | |
| "probe_score": "Hidden-state logistic probe [C]", | |
| "oracle": "Oracle (best expert, offline)", | |
| } | |
| for name, acc in routing_results.items(): | |
| acc_str = f"{acc:.4f}" if not np.isnan(acc) else " n/a" | |
| print(f" {name:<18} {descriptions[name]:<35} {acc_str:>9}") | |
| pd.DataFrame([routing_results]).to_csv( | |
| RESULTS_DIR / "routing_results.csv", index=False | |
| ) | |
| # 6. ECE per model per signal | |
| print("\nββ ECE per model βββββββββββββββββββββββββββββββββββββ") | |
| ece_rows = [] | |
| for mk in MODELS: | |
| sub = eval_df[eval_df["model_key"] == mk] | |
| row = {"model_key": mk} | |
| for sig, lbl in [("mean_log_prob", "log_prob"), | |
| ("neg_entropy", "neg_entropy"), | |
| ("probe_score", "probe")]: | |
| row[f"ece_{lbl}"] = compute_ece(sub, sig) | |
| plot_reliability(sub, sig, mk, lbl) | |
| ece_rows.append(row) | |
| ece_df = pd.DataFrame(ece_rows) | |
| ece_df.to_csv(RESULTS_DIR / "ece_results.csv", index=False) | |
| print(ece_df.to_string(index=False)) | |
| # 7. Per-dataset routing breakdown | |
| print("\nββ Per-dataset breakdown βββββββββββββββββββββββββββββ") | |
| ds_rows = [] | |
| for ds in sorted(eval_df["dataset"].unique()): | |
| sub = eval_df[eval_df["dataset"] == ds] | |
| ds_rows.append({ | |
| "dataset": ds, | |
| "n_prompts": sub["prompt_id"].nunique(), | |
| "random": round(random_accuracy(sub), 4), | |
| "log_prob": round(route_and_score(sub, "mean_log_prob"), 4), | |
| "neg_entropy": round(route_and_score(sub, "neg_entropy"), 4), | |
| "probe_score": round(route_and_score(sub, "probe_score"), 4) | |
| if eval_df["probe_score"].notna().any() else float("nan"), | |
| "oracle": round(oracle_accuracy(sub), 4), | |
| }) | |
| ds_df = pd.DataFrame(ds_rows) | |
| ds_df.to_csv(RESULTS_DIR / "per_dataset_routing.csv", index=False) | |
| print(ds_df.to_string(index=False)) | |
| # 8. Per-model probe AUROC summary (if probe was run) | |
| if probe_metrics: | |
| print("\nββ Probe AUROC per model βββββββββββββββββββββββββββββ") | |
| print(pd.DataFrame(probe_metrics)[ | |
| ["model_key", "probe_auroc", "n_train", "pca_dims"] | |
| ].to_string(index=False)) | |
| print(f"\nβ Routing results β {RESULTS_DIR / 'routing_results.csv'}") | |
| print(f"β ECE results β {RESULTS_DIR / 'ece_results.csv'}") | |
| print(f"β Per-dataset β {RESULTS_DIR / 'per_dataset_routing.csv'}") | |
| print(f"β Reliability plots β {PLOTS_DIR}") | |
| if __name__ == "__main__": | |
| main() | |