""" 03_domain_aware_router.py ========================= Domain-aware ensemble router that exploits the complementary failure modes identified in Step 2: probe_score wins on specialist domains (gsm8k, humaneval) log_prob wins on generalist domains (mmlu, commonsenseqa) Routing logic ------------- 1. Classify the incoming prompt into a domain. 2. If domain ∈ SPECIALIST_DOMAINS → route using probe_score If domain ∈ GENERALIST_DOMAINS → route using mean_log_prob Two domain classification modes (--domain_mode): "label" Use ground-truth dataset column (upper bound — shows how good domain-aware routing could be with perfect domain knowledge). "predict" Train a TF-IDF + LogisticRegression domain classifier on the prompt text, then use its predictions at routing time. This is the realistic deployment scenario where domain labels are unknown. Outputs ------- results/domain_aware_routing.csv — full comparison table results/domain_classifier.csv — domain classifier accuracy (predict mode) trained_models/domain_clf.pkl — saved domain classifier (predict mode) Run after 02a_train_probes.py (needs *_results.parquet + *_probe.pkl). Usage ----- # Realistic mode (text classifier): python src/03_domain_aware_router.py # Oracle domain mode (upper bound): python src/03_domain_aware_router.py --domain_mode label # If your prompt text is in a column other than 'eval_name': python src/03_domain_aware_router.py --text_col prompt """ import argparse import warnings from pathlib import Path import joblib import numpy as np import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import accuracy_score, classification_report from sklearn.model_selection import cross_val_score warnings.filterwarnings("ignore") # ── Paths (match 01/03 layout) ──────────────────────────────────────────────── BASE_DIR = Path(__file__).resolve().parent.parent # project root (scripts live in src/) RESULTS_DIR = BASE_DIR / "results" HIDDEN_DIR = BASE_DIR / "hidden_states" MODEL_DIR = BASE_DIR / "trained_models" # ── Configuration ───────────────────────────────────────────────────────────── MODELS = [ "qwen25_1b", "qwen25_3b", "phi3_mini", "qwen25_math", "qwen25_coder", ] # Routing signal assigned to each domain. # Derived from per_dataset_routing results in Step 2: # gsm8k → probe_score (0.829 vs 0.814 log_prob) # humaneval → probe_score (0.530 vs 0.504 log_prob) # commonsenseqa→ mean_log_prob (0.800 vs 0.757 probe) # mmlu → mean_log_prob (0.574 vs 0.471 probe) DOMAIN_SIGNAL = { "gsm8k": "probe_score", "humaneval": "probe_score", "commonsenseqa": "mean_log_prob", "mmlu": "mean_log_prob", } # For specialist domains using probe_score, a generalist must beat the # specialist probe score by at least this margin to trigger a defection. # Motivation: on humaneval the probe correctly senses hard problems but # defects to generalists who score only 15.6% on those problems — worse # than the specialist would have. A threshold stops low-confidence defections. # gsm8k: 0.0 — defection accuracy was 73.7% (healthy, no guard needed) # humaneval: 0.15 — defection accuracy was 15.6% (broken, guard required) # Sweep values: [0.0, 0.05, 0.10, 0.15, 0.20, 0.25] on eval split # and pick the one that maximises humaneval routing accuracy. DEFECTION_THRESHOLD = { "gsm8k": 0.0, "humaneval": 0.15, } # The designated specialist for each domain using probe_score routing. # Used by defection threshold logic to identify the incumbent specialist. DOMAIN_SPECIALIST = { "gsm8k": "qwen25_math", "humaneval": "qwen25_coder", } # Column in the results parquet that holds the raw prompt text. # Change this if your parquet uses a different name (e.g. "prompt", "question"). DEFAULT_TEXT_COL = "eval_name" # Probe training split fraction — must match 02a_train_probes.py TRAIN_FRAC = 0.30 RANDOM_SEED = 42 # ── Data loading ────────────────────────────────────────────────────────────── def load_all_results() -> pd.DataFrame: """Load and combine all *_results.parquet files.""" dfs = [] for f in sorted(RESULTS_DIR.glob("*_results.parquet")): dfs.append(pd.read_parquet(f)) if not dfs: raise FileNotFoundError( "No *_results.parquet found in results/. " "Run 01_collect_data.py first." ) df = pd.concat(dfs, ignore_index=True) df["neg_entropy"] = -df["first_tok_entropy"] print( f"Loaded {len(df):,} rows | " f"{df['model_key'].nunique()} models | " f"datasets: {sorted(df['dataset'].unique())}" ) return df def make_split(df: pd.DataFrame): """ Reproduce the same train/eval split as 02a_train_probes.py. Uses identical seed and stratification so probe scores are never evaluated on prompts the probe was trained on. """ rng = np.random.default_rng(RANDOM_SEED) train_ids = set() for ds, grp in df.groupby("dataset"): unique = grp["prompt_id"].unique() n = max(1, int(len(unique) * TRAIN_FRAC)) train_ids.update(rng.choice(unique, size=n, replace=False).tolist()) eval_df = df[~df["prompt_id"].isin(train_ids)].copy() train_df = df[df["prompt_id"].isin(train_ids)].copy() print( f"Split → train: {train_df['prompt_id'].nunique()} prompts | " f"eval: {eval_df['prompt_id'].nunique()} prompts" ) return train_df, eval_df # ── Probe scores ────────────────────────────────────────────────────────────── def attach_probe_scores(eval_df: pd.DataFrame) -> pd.DataFrame: """ Load saved probe pkl files from Step 2 and score eval prompts. Adds a 'probe_score' column to eval_df. """ eval_df = eval_df.copy() eval_df["probe_score"] = np.nan for model_key in MODELS: pkl_path = MODEL_DIR / f"{model_key}_probe.pkl" npz_path = HIDDEN_DIR / f"{model_key}_hidden.npz" if not pkl_path.exists(): print(f" [{model_key}] No probe pkl found — probe_score will be NaN") continue if not npz_path.exists(): print(f" [{model_key}] No hidden states found — probe_score will be NaN") continue artefact = joblib.load(pkl_path) pca = artefact["pca"] probe = artefact["probe"] data = np.load(npz_path, allow_pickle=True) ids = data["prompt_ids"].tolist() vecs = data["vectors"].astype(np.float32) id_to_idx = {pid: i for i, pid in enumerate(ids)} mask = eval_df["model_key"] == model_key pids = eval_df.loc[mask, "prompt_id"].tolist() present = [(pid, id_to_idx[pid]) for pid in pids if pid in id_to_idx] if not present: continue sel_pids, sel_idxs = zip(*present) X = pca.transform(vecs[list(sel_idxs)]) scores = probe.predict_proba(X)[:, 1] score_series = pd.Series(dict(zip(sel_pids, scores))) update_idx = eval_df.loc[mask, "prompt_id"].map(score_series) eval_df.loc[update_idx.index, "probe_score"] = update_idx.values print(f" [{model_key}] probe scores attached ({len(sel_pids)} prompts)") return eval_df # ── Domain classifier ───────────────────────────────────────────────────────── def train_domain_classifier( train_df: pd.DataFrame, text_col: str, ) -> tuple: """ Train a TF-IDF + LogisticRegression domain classifier. Input: one row per (prompt, model) — we deduplicate to one row per prompt. Target: dataset label (gsm8k / humaneval / commonsenseqa / mmlu). Returns (vectorizer, classifier). """ # One row per prompt (text and label are the same across models) prompt_df = ( train_df[[text_col, "dataset"]] .drop_duplicates(subset=[text_col]) .dropna(subset=[text_col]) ) if len(prompt_df) < 20: raise ValueError( f"Only {len(prompt_df)} unique training prompts found. " f"Check that '{text_col}' is the correct text column " f"(use --text_col to override)." ) X_text = prompt_df[text_col].astype(str).tolist() y = prompt_df["dataset"].tolist() vec = TfidfVectorizer( ngram_range=(1, 2), max_features=5000, sublinear_tf=True, strip_accents="unicode", ) clf = LogisticRegression(max_iter=1000, C=5.0, random_state=RANDOM_SEED) X = vec.fit_transform(X_text) # Cross-val on training data cv_scores = cross_val_score(clf, X, y, cv=5, scoring="accuracy") print( f" Domain classifier 5-fold CV accuracy: " f"{cv_scores.mean():.3f} ± {cv_scores.std():.3f}" ) clf.fit(X, y) joblib.dump({"vec": vec, "clf": clf}, MODEL_DIR / "domain_clf.pkl") return vec, clf def predict_domains( vec, clf, df: pd.DataFrame, text_col: str, ) -> pd.Series: """ Returns a Series mapping prompt_id → predicted domain label. """ # One row per prompt prompt_df = ( df[["prompt_id", text_col]] .drop_duplicates(subset=["prompt_id"]) .dropna(subset=[text_col]) ) X = vec.transform(prompt_df[text_col].astype(str).tolist()) preds = clf.predict(X) return pd.Series(dict(zip(prompt_df["prompt_id"].tolist(), preds))) # ── Routing helpers ─────────────────────────────────────────────────────────── def route_single_signal(eval_df: pd.DataFrame, signal_col: str) -> float: """Standard single-signal router: pick the model with highest signal.""" 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 route_oracle(eval_df: pd.DataFrame) -> float: """Upper bound: pick a correct expert whenever 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 route_random(eval_df: pd.DataFrame, n_runs: int = 5) -> float: """Average accuracy of random expert selection over n_runs.""" rng = np.random.default_rng(RANDOM_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 else 0.0) return float(np.mean(accs)) def route_domain_aware( eval_df: pd.DataFrame, domain_col: str, # column holding the domain label for each row ) -> tuple[float, dict]: """ Domain-aware router. For each prompt: 1. Read its domain from domain_col. 2. Look up which signal to use from DOMAIN_SIGNAL. 3. Pick the model with the highest value of that signal. Returns (overall_accuracy, per_domain_accuracy_dict). """ correct, total = 0, 0 per_domain: dict[str, list] = {} for pid, grp in eval_df.groupby("prompt_id"): domain = grp[domain_col].iloc[0] signal = DOMAIN_SIGNAL.get(domain, "mean_log_prob") threshold = DEFECTION_THRESHOLD.get(domain, 0.0) specialist = DOMAIN_SPECIALIST.get(domain) valid = grp.dropna(subset=[signal]) if valid.empty: continue if threshold > 0.0 and specialist is not None: # Defection guard: only route away from the specialist if a # generalist beats its probe score by at least `threshold`. # Prevents defecting to weaker generalists on hard problems # where the specialist, though uncertain, is still the best bet. spec_row = valid[valid["model_key"] == specialist] if not spec_row.empty: spec_score = spec_row[signal].values[0] alts = valid[valid["model_key"] != specialist] best_alt_score = alts[signal].max() if not alts.empty else -np.inf if best_alt_score - spec_score >= threshold: # Generalist beats specialist by enough — defect best = valid.loc[valid[signal].idxmax()] else: # Specialist stays — defection blocked by threshold best = spec_row.iloc[0] else: best = valid.loc[valid[signal].idxmax()] else: best = valid.loc[valid[signal].idxmax()] is_right = int(best["is_correct"]) correct += is_right total += 1 per_domain.setdefault(domain, []).append(is_right) overall = correct / total if total > 0 else float("nan") per_ds = {ds: float(np.mean(v)) for ds, v in per_domain.items()} return overall, per_ds # ── Main ────────────────────────────────────────────────────────────────────── def main(): parser = argparse.ArgumentParser( description="Domain-aware ensemble router for logit-based competence routing." ) parser.add_argument( "--domain_mode", choices=["label", "predict"], default="predict", help=( "'label' = use ground-truth dataset column (upper bound). " "'predict' = train a text classifier and use its predictions (default)." ), ) parser.add_argument( "--text_col", default=DEFAULT_TEXT_COL, help=f"Column containing raw prompt text (default: '{DEFAULT_TEXT_COL}').", ) args = parser.parse_args() print("=== Step 3: Domain-Aware Ensemble Routing ===\n") print(f"Domain mode : {args.domain_mode}") print(f"Text column : {args.text_col}\n") # ── 1. Load data ────────────────────────────────────────────────────────── df = load_all_results() train_df, eval_df = make_split(df) # ── 2. Attach probe scores from saved Step 2 probes ─────────────────────── print("\n── Attaching probe scores ─────────────────────────────────") eval_df = attach_probe_scores(eval_df) probe_available = eval_df["probe_score"].notna().any() if not probe_available: print( "\n WARNING: No probe scores found. Run 02a_train_probes.py " "first to generate *_probe.pkl files.\n" " Domain-aware routing will fall back to log_prob for all domains.\n" ) # ── 3. Domain classification ────────────────────────────────────────────── print("\n── Domain classification ──────────────────────────────────") if args.domain_mode == "label": # Ground-truth labels already in the dataframe eval_df["_domain"] = eval_df["dataset"] domain_col = "_domain" print(" Using ground-truth dataset labels (upper bound).") else: # "predict" if args.text_col not in df.columns: available = ", ".join(df.columns.tolist()) raise ValueError( f"Text column '{args.text_col}' not found in parquet. " f"Available columns: {available}\n" f"Use --text_col to specify the correct column." ) print(f" Training TF-IDF domain classifier on '{args.text_col}'...") vec, clf = train_domain_classifier(train_df, args.text_col) # Evaluate classifier on eval prompts (ground-truth available → report accuracy) pred_map = predict_domains(vec, clf, eval_df, args.text_col) eval_df["_domain_pred"] = eval_df["prompt_id"].map(pred_map) # Per-domain classifier accuracy prompt_truth = ( eval_df[["prompt_id", "dataset"]] .drop_duplicates("prompt_id") .set_index("prompt_id")["dataset"] ) clf_acc_rows = [] for ds in sorted(eval_df["dataset"].unique()): pids = eval_df.loc[eval_df["dataset"] == ds, "prompt_id"].unique() truth = prompt_truth.loc[pids].values pred = pred_map.reindex(pids).values valid = ~pd.isna(pred) acc = accuracy_score(truth[valid], pred[valid]) if valid.any() else float("nan") clf_acc_rows.append({"dataset": ds, "classifier_accuracy": round(acc, 4)}) clf_acc_df = pd.DataFrame(clf_acc_rows) overall_clf_acc = accuracy_score( prompt_truth.values, pred_map.reindex(prompt_truth.index).fillna("unknown").values, ) clf_acc_df.loc[len(clf_acc_df)] = { "dataset": "OVERALL", "classifier_accuracy": round(overall_clf_acc, 4), } clf_acc_df.to_csv(RESULTS_DIR / "domain_classifier.csv", index=False) print(f"\n Domain classifier accuracy on eval set:") print(clf_acc_df.to_string(index=False)) domain_col = "_domain_pred" # ── 4. Routing evaluation ───────────────────────────────────────────────── print("\n── Routing accuracy ───────────────────────────────────────") results = {} results["random"] = route_random(eval_df) results["log_prob"] = route_single_signal(eval_df, "mean_log_prob") results["neg_entropy"] = route_single_signal(eval_df, "neg_entropy") results["probe_score"] = ( route_single_signal(eval_df, "probe_score") if probe_available else float("nan") ) results["oracle"] = route_oracle(eval_df) domain_overall, domain_per_ds = route_domain_aware(eval_df, domain_col) results["domain_aware"] = domain_overall # Also run domain-aware with ground-truth labels if we used predicted labels, # so we can see the headroom from better domain classification. if args.domain_mode == "predict": eval_df["_domain_truth"] = eval_df["dataset"] da_upper, _ = route_domain_aware(eval_df, "_domain_truth") results["domain_aware_upper"] = da_upper else: results["domain_aware_upper"] = domain_overall # same thing # ── 5. Print results table ──────────────────────────────────────────────── 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]", "domain_aware": f"Domain-aware ensemble ({args.domain_mode} labels) ★", "domain_aware_upper": "Domain-aware ensemble (ground-truth labels, upper bound)", "oracle": "Oracle — best expert, offline", } print(f"\n {'Signal':<30} {'Description':<45} {'Accuracy':>9}") print(" " + "─" * 86) for name, acc in results.items(): acc_str = f"{acc:.4f}" if not np.isnan(acc) else " n/a" print(f" {name:<30} {descriptions.get(name, ''):<45} {acc_str:>9}") # ── 6. Per-domain breakdown ─────────────────────────────────────────────── print("\n── Per-domain breakdown (domain-aware router) ─────────────") print(f"\n {'Domain':<18} {'Signal used':<16} {'Accuracy':>9}") print(" " + "─" * 45) for ds in sorted(domain_per_ds): sig = DOMAIN_SIGNAL.get(ds, "mean_log_prob") acc = domain_per_ds[ds] print(f" {ds:<18} {sig:<16} {acc:.4f}") # ── 7. Save outputs ─────────────────────────────────────────────────────── out_df = pd.DataFrame([ {"signal": k, "accuracy": v, "description": descriptions.get(k, "")} for k, v in results.items() ]) out_df.to_csv(RESULTS_DIR / "domain_aware_routing.csv", index=False) print(f"\n✓ Results → {RESULTS_DIR / 'domain_aware_routing.csv'}") if args.domain_mode == "predict": print(f"✓ Domain clf → {RESULTS_DIR / 'domain_classifier.csv'}") print(f"✓ Domain model → {MODEL_DIR / 'domain_clf.pkl'}") # ── 8. Summary insight ──────────────────────────────────────────────────── best_single = max( v for k, v in results.items() if k in ("log_prob", "neg_entropy", "probe_score") and not np.isnan(v) ) gain = results["domain_aware"] - best_single print( f"\nDomain-aware router: {results['domain_aware']:.4f} " f"({'▲' if gain >= 0 else '▼'}{abs(gain):.4f} vs best single signal {best_single:.4f})" ) if args.domain_mode == "predict": headroom = results["domain_aware_upper"] - results["domain_aware"] print( f"Headroom from better domain classification: {headroom:.4f} " f"(upper bound with ground-truth labels: {results['domain_aware_upper']:.4f})" ) # ── 9. Specialist routing diagnostic ───────────────────────────────────── # Checks whether the probe is capturing per-question competence or just # re-learning domain identity (i.e. always routing to the specialist). # # If a specialist is chosen 90%+ of the time on its own domain, the probe # has learned "this looks like a math/code question" rather than "this # particular question is one the math/code model will get right." # In that case the domain-aware router reduces to a simple rule: # gsm8k → qwen25_math, humaneval → qwen25_coder # which needs no ML. A healthy probe should defect to a generalist on # hard in-domain problems where the specialist is predicted to fail. if not probe_available: print("\n── Specialist routing diagnostic: skipped (no probe scores) ──") else: print("\n── Specialist routing diagnostic ──────────────────────────") print( f"\n {'Domain':<16} {'Specialist':<16} " f"{'Routed to spec':>14} {'Spec correct':>13} {'Defect correct':>15}" ) print(" " + "─" * 76) diagnostic_rows = [] SPECIALIST_MAP = { "gsm8k": "qwen25_math", "humaneval": "qwen25_coder", } for domain, spec_model in SPECIALIST_MAP.items(): domain_df = eval_df[eval_df["dataset"] == domain].copy() if domain_df.empty or domain_df["probe_score"].isna().all(): continue # For each prompt, find which model the probe would choose chosen = ( domain_df.dropna(subset=["probe_score"]) .groupby("prompt_id") .apply(lambda g: g.loc[g["probe_score"].idxmax(), "model_key"]) ) routed_to_spec = (chosen == spec_model).mean() # Accuracy when specialist is chosen spec_pids = chosen[chosen == spec_model].index spec_rows = domain_df[ (domain_df["prompt_id"].isin(spec_pids)) & (domain_df["model_key"] == spec_model) ] spec_acc = spec_rows["is_correct"].mean() if len(spec_rows) else float("nan") # Accuracy when router defects to a generalist defect_pids = chosen[chosen != spec_model].index defect_rows = domain_df[ domain_df["prompt_id"].isin(defect_pids) ].groupby("prompt_id").apply( lambda g: g.loc[g["probe_score"].idxmax()] ) defect_acc = defect_rows["is_correct"].mean() if len(defect_rows) else float("nan") print( f" {domain:<16} {spec_model:<16} " f"{routed_to_spec:>13.1%} {spec_acc:>12.1%} " f"{'n/a' if np.isnan(defect_acc) else f'{defect_acc:.1%}':>15}" ) diagnostic_rows.append({ "domain": domain, "specialist": spec_model, "pct_routed_to_specialist": round(routed_to_spec, 4), "specialist_accuracy": round(spec_acc, 4) if not np.isnan(spec_acc) else None, "defect_accuracy": round(defect_acc, 4) if not np.isnan(defect_acc) else None, "n_prompts": chosen.shape[0], "n_defections": int((chosen != spec_model).sum()), }) if diagnostic_rows: diag_df = pd.DataFrame(diagnostic_rows) diag_df.to_csv(RESULTS_DIR / "specialist_diagnostic.csv", index=False) print(f"\n ✓ Diagnostic → {RESULTS_DIR / 'specialist_diagnostic.csv'}") # Interpret the result print() for row in diagnostic_rows: pct = row["pct_routed_to_specialist"] if pct >= 0.90: verdict = ( f" ⚠ {row['domain']}: probe routes to {row['specialist']} " f"{pct:.0%} of the time — likely learned domain identity, " f"not per-question competence. " f"Focus probe training on within-domain difficulty variance." ) elif pct <= 0.50: verdict = ( f" ⚠ {row['domain']}: probe defects away from {row['specialist']} " f"{1-pct:.0%} of the time — may be underusing the specialist. " f"Check probe AUROC and training sample size." ) else: verdict = ( f" ✓ {row['domain']}: probe routes to {row['specialist']} " f"{pct:.0%} of the time — healthy mix of specialist use " f"and generalist defection." ) print(verdict) if __name__ == "__main__": main()