Download src/04_cheap_router.py from Raj-deep/ScoutRoute: direct link, hf CLI and curl.
- Browser
- Download file 24.9 kB
-
https://huggingface.co/Raj-deep/ScoutRoute/resolve/main/src/04_cheap_router.py
- Command line
-
hf download hf://Raj-deep/ScoutRoute/src/04_cheap_router.py
-
curl -L -o 04_cheap_router.py https://huggingface.co/Raj-deep/ScoutRoute/resolve/main/src/04_cheap_router.py
24.9 kB
| """ | |
| 04_cheap_router.py | |
| ================== | |
| The deployable router. | |
| Steps 2 and 3 proved that hidden-state probe scores carry real routing signal, | |
| but they required running ALL five models to get five probe scores β defeating | |
| the point of routing. This script answers the follow-up question: | |
| Can we predict which expert will succeed using only ONE cheap forward pass? | |
| Architecture | |
| ------------ | |
| A single "scout" model (default: qwen25_1b, the cheapest) runs on every | |
| prompt. Its hidden state is used to train five independent cross-model probes, | |
| one per target expert: | |
| scout hidden state β P(qwen25_1b correct) | |
| β P(qwen25_3b correct) | |
| β P(phi3_mini correct) | |
| β P(qwen25_math correct) | |
| β P(qwen25_coder correct) | |
| At routing time only the scout runs. Its hidden state produces five predicted | |
| correctness scores, and the highest-scoring expert is selected. | |
| This is strictly harder than Step 2 (each model predicting its own | |
| correctness from its own hidden state) because the scout's representation | |
| must generalise across model families and sizes. | |
| Variants evaluated | |
| ------------------ | |
| cheap_router Pure cheap router β argmax of cross-model probe scores | |
| cheap_domain_aware Cheap router + domain-aware signal selection from Step 3 | |
| (probe for specialist domains, log_prob for generalist) | |
| The gap between cheap_router and the Step 2 per-expert oracle is the cost of | |
| using a single scout. The gap between cheap_domain_aware and the Step 3 | |
| domain-aware router is the additional cost of cross-model generalisation. | |
| Outputs | |
| ------- | |
| results/cheap_router_results.csv β full comparison table | |
| results/cheap_probe_metrics.csv β AUROC per (scout β target) probe | |
| trained_models/cheap_{target}_probe.pkl | |
| Usage | |
| ----- | |
| python src/04_cheap_router.py # default scout: qwen25_1b | |
| python src/04_cheap_router.py --scout qwen25_3b # try a larger scout | |
| python src/04_cheap_router.py --sweep_scouts # try all models as scout | |
| """ | |
| import argparse | |
| import warnings | |
| from pathlib import Path | |
| import joblib | |
| import numpy as np | |
| import pandas as pd | |
| from sklearn.decomposition import PCA | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.metrics import roc_auc_score | |
| from sklearn.model_selection import train_test_split | |
| from sklearn.preprocessing import StandardScaler | |
| warnings.filterwarnings("ignore") | |
| # ββ Paths βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| 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" | |
| CHEAP_DIR = MODEL_DIR / "cheap_probes" | |
| for d in [RESULTS_DIR, CHEAP_DIR]: | |
| d.mkdir(parents=True, exist_ok=True) | |
| # ββ Configuration βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| MODELS = [ | |
| "qwen25_1b", | |
| "qwen25_3b", | |
| "phi3_mini", | |
| "qwen25_math", | |
| "qwen25_coder", | |
| ] | |
| DEFAULT_SCOUT = "qwen25_1b" | |
| # Must match 03 and 04 exactly β same seed, same fraction | |
| TRAIN_FRAC = 0.30 | |
| RANDOM_SEED = 42 | |
| # PCA dims for cross-model probes. Can be lower than Step 2 since the | |
| # scout's hidden state is predicting a harder target (other models' | |
| # correctness) β too many dims risks overfitting on the small training set. | |
| PCA_DIMS = 64 | |
| # Defection threshold carried over from Step 3 for the domain-aware variant. | |
| DEFECTION_THRESHOLD = { | |
| "gsm8k": 0.0, | |
| "humaneval": 0.15, | |
| } | |
| DOMAIN_SIGNAL = { | |
| "gsm8k": "cheap_probe", | |
| "humaneval": "cheap_probe", | |
| "commonsenseqa": "mean_log_prob", | |
| "mmlu": "mean_log_prob", | |
| } | |
| DOMAIN_SPECIALIST = { | |
| "gsm8k": "qwen25_math", | |
| "humaneval": "qwen25_coder", | |
| } | |
| # ββ Data helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def load_all_results() -> pd.DataFrame: | |
| 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. 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 identical train/eval split used in Steps 2 and 3.""" | |
| 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 | |
| def load_hidden(model_key: str): | |
| """Returns (prompt_ids, vectors) or (None, None).""" | |
| path = HIDDEN_DIR / f"{model_key}_hidden.npz" | |
| if not path.exists(): | |
| return None, None | |
| data = np.load(path, allow_pickle=True) | |
| return data["prompt_ids"].tolist(), data["vectors"].astype(np.float32) | |
| # ββ Cross-model probe training ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def train_cross_model_probe( | |
| scout_key: str, | |
| target_key: str, | |
| train_df: pd.DataFrame, | |
| scout_ids: list, | |
| scout_vecs: np.ndarray, | |
| ) -> dict | None: | |
| """ | |
| Train a probe that maps scout hidden states β P(target model correct). | |
| scout_key : model whose hidden states are the input features | |
| target_key : model whose correctness is the prediction target | |
| train_df : rows for the training split only | |
| scout_ids : prompt_ids corresponding to rows of scout_vecs | |
| scout_vecs : hidden state matrix for the scout model (N, hidden_dim) | |
| Returns a dict with {pca, scaler, clf, auroc, ...} or None if skipped. | |
| """ | |
| # Labels: is the TARGET model correct on each training prompt? | |
| target_train = ( | |
| train_df[train_df["model_key"] == target_key] | |
| [["prompt_id", "is_correct"]] | |
| .drop_duplicates("prompt_id") | |
| .set_index("prompt_id")["is_correct"] | |
| .astype(int) | |
| ) | |
| # Align scout hidden states with target labels | |
| id_to_idx = {pid: i for i, pid in enumerate(scout_ids)} | |
| common_ids = [pid for pid in target_train.index if pid in id_to_idx] | |
| if len(common_ids) < 20: | |
| print( | |
| f" [{scout_key}β{target_key}] Only {len(common_ids)} aligned " | |
| f"training prompts β skipping." | |
| ) | |
| return None | |
| idxs = [id_to_idx[pid] for pid in common_ids] | |
| X = scout_vecs[idxs] | |
| y = target_train.loc[common_ids].values | |
| if len(np.unique(y)) < 2: | |
| print(f" [{scout_key}β{target_key}] Single class in training β skipping.") | |
| return None | |
| # PCA β scale β logistic regression | |
| n_dims = min(PCA_DIMS, X.shape[1], X.shape[0] - 1) | |
| pca = PCA(n_components=n_dims, random_state=RANDOM_SEED) | |
| scaler = StandardScaler() | |
| clf = LogisticRegression( | |
| max_iter=1000, C=1.0, | |
| class_weight="balanced", # handles correctness imbalance across domains | |
| random_state=RANDOM_SEED, | |
| ) | |
| X_pca = pca.fit_transform(X) | |
| X_sc = scaler.fit_transform(X_pca) | |
| # Inner 80/20 split for AUROC validation | |
| X_fit, X_val, y_fit, y_val = train_test_split( | |
| X_sc, y, test_size=0.2, random_state=RANDOM_SEED, stratify=y | |
| ) | |
| clf.fit(X_fit, y_fit) | |
| auroc = ( | |
| roc_auc_score(y_val, clf.predict_proba(X_val)[:, 1]) | |
| if len(np.unique(y_val)) > 1 | |
| else float("nan") | |
| ) | |
| # Refit on full training split | |
| clf_final = LogisticRegression( | |
| max_iter=1000, C=1.0, | |
| class_weight="balanced", | |
| random_state=RANDOM_SEED, | |
| ) | |
| clf_final.fit(X_sc, y) | |
| pipeline = { | |
| "scout_key": scout_key, | |
| "target_key": target_key, | |
| "pca": pca, | |
| "scaler": scaler, | |
| "clf": clf_final, | |
| "auroc": auroc, | |
| "n_train": len(X_fit), | |
| "n_val": len(X_val), | |
| "pca_dims": n_dims, | |
| } | |
| out = CHEAP_DIR / f"cheap_{scout_key}_to_{target_key}_probe.pkl" | |
| joblib.dump(pipeline, out) | |
| print( | |
| f" [{scout_key}β{target_key}] " | |
| f"AUROC={auroc:.4f} n_train={len(X_fit)} n_val={len(X_val)} " | |
| f"pca_dims={n_dims}" | |
| ) | |
| return pipeline | |
| # ββ Scoring eval prompts ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def score_eval_prompts( | |
| pipelines: dict, # target_key β pipeline dict | |
| eval_df: pd.DataFrame, | |
| scout_ids: list, | |
| scout_vecs: np.ndarray, | |
| ) -> pd.DataFrame: | |
| """ | |
| For every (prompt_id, model_key) row in eval_df, attach the predicted | |
| P(correct) from the cross-model probe trained on the scout's hidden state. | |
| Returns eval_df with a new 'cheap_probe' column. | |
| """ | |
| eval_df = eval_df.copy() | |
| eval_df["cheap_probe"] = np.nan | |
| id_to_idx = {pid: i for i, pid in enumerate(scout_ids)} | |
| for target_key, pipeline in pipelines.items(): | |
| if pipeline is None: | |
| continue | |
| pca = pipeline["pca"] | |
| scaler = pipeline["scaler"] | |
| clf = pipeline["clf"] | |
| mask = eval_df["model_key"] == target_key | |
| pids = eval_df.loc[mask, "prompt_id"].tolist() | |
| valid = [(pid, id_to_idx[pid]) for pid in pids if pid in id_to_idx] | |
| if not valid: | |
| continue | |
| sel_pids, sel_idxs = zip(*valid) | |
| X = scout_vecs[list(sel_idxs)] | |
| X_pca = pca.transform(X) | |
| X_sc = scaler.transform(X_pca) | |
| scores = clf.predict_proba(X_sc)[:, 1] | |
| score_map = dict(zip(sel_pids, scores)) | |
| update_idx = eval_df.loc[mask, "prompt_id"].map(score_map) | |
| eval_df.loc[update_idx.index, "cheap_probe"] = update_idx.values | |
| return eval_df | |
| # ββ Routing functions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def route_single_signal(eval_df: pd.DataFrame, signal_col: str) -> float: | |
| 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 else float("nan") | |
| def route_oracle(eval_df: pd.DataFrame) -> float: | |
| 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 else float("nan") | |
| def route_random(eval_df: pd.DataFrame, n_runs: int = 5) -> float: | |
| 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_cheap(eval_df: pd.DataFrame) -> tuple[float, dict]: | |
| """ | |
| Domain-aware router using cheap_probe for specialist domains and | |
| mean_log_prob for generalist domains β mirroring Step 3 but using | |
| cross-model probe scores from the scout instead of per-expert probes. | |
| Applies the same defection threshold as Step 3. | |
| """ | |
| correct, total = 0, 0 | |
| per_domain: dict[str, list] = {} | |
| for pid, grp in eval_df.groupby("prompt_id"): | |
| domain = grp["dataset"].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: | |
| 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: | |
| best = valid.loc[valid[signal].idxmax()] | |
| else: | |
| 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 else float("nan") | |
| per_ds = {ds: float(np.mean(v)) for ds, v in per_domain.items()} | |
| return overall, per_ds | |
| # ββ Probe AUROC diagnostic ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def print_auroc_comparison(pipelines: dict, scout_key: str) -> pd.DataFrame: | |
| """ | |
| Print and return a table comparing cross-model probe AUROC | |
| (scout β target) against Step 2 per-expert probe AUROC for context. | |
| """ | |
| # Step 2 AUROCs for reference (from probe_metrics.csv if available) | |
| step3_auroc = {} | |
| step3_path = RESULTS_DIR / "probe_metrics.csv" | |
| if step3_path.exists(): | |
| step3_df = pd.read_csv(step3_path) | |
| step3_auroc = dict( | |
| zip(step3_df["model_key"], step3_df["probe_auroc"]) | |
| ) | |
| rows = [] | |
| print( | |
| f"\n {'Target model':<16} {'ScoutβTarget AUROC':>20} " | |
| f"{'Step3 self AUROC':>18} {'Ξ':>8}" | |
| ) | |
| print(" " + "β" * 65) | |
| for target in MODELS: | |
| pipeline = pipelines.get(target) | |
| cross_auroc = pipeline["auroc"] if pipeline else float("nan") | |
| self_auroc = step3_auroc.get(target, float("nan")) | |
| delta = cross_auroc - self_auroc | |
| print( | |
| f" {target:<16} {cross_auroc:>20.4f} " | |
| f"{self_auroc:>18.4f} " | |
| f"{'n/a' if np.isnan(delta) else f'{delta:+.4f}':>8}" | |
| ) | |
| rows.append({ | |
| "scout": scout_key, | |
| "target": target, | |
| "cross_auroc": round(cross_auroc, 4), | |
| "self_auroc": round(self_auroc, 4) if not np.isnan(self_auroc) else None, | |
| "delta": round(delta, 4) if not np.isnan(delta) else None, | |
| }) | |
| return pd.DataFrame(rows) | |
| # ββ Single scout run ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_scout( | |
| scout_key: str, | |
| df: pd.DataFrame, | |
| train_df: pd.DataFrame, | |
| eval_df: pd.DataFrame, | |
| ) -> dict: | |
| """ | |
| Full pipeline for one scout model: train probes, score eval, route. | |
| Returns a dict of routing accuracy results for this scout. | |
| """ | |
| print(f"\n{'='*60}") | |
| print(f"Scout model: {scout_key}") | |
| print(f"{'='*60}") | |
| # Load scout hidden states | |
| scout_ids, scout_vecs = load_hidden(scout_key) | |
| if scout_ids is None: | |
| print(f" No hidden states found for {scout_key} β skipping.") | |
| return {} | |
| print(f" Loaded {len(scout_ids)} hidden states shape={scout_vecs.shape}") | |
| # ββ Train cross-model probes ββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nββ Cross-model probes ({scout_key} β each target) ββββββββββ") | |
| pipelines = {} | |
| for target_key in MODELS: | |
| pipelines[target_key] = train_cross_model_probe( | |
| scout_key, target_key, train_df, scout_ids, scout_vecs | |
| ) | |
| # ββ AUROC comparison table ββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nββ AUROC: cross-model vs self (Step 2) βββββββββββββββββββββ") | |
| auroc_df = print_auroc_comparison(pipelines, scout_key) | |
| auroc_df.to_csv( | |
| RESULTS_DIR / f"cheap_probe_metrics_{scout_key}.csv", index=False | |
| ) | |
| # ββ Score eval prompts ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nββ Scoring eval prompts ββββββββββββββββββββββββββββββββββββ") | |
| eval_scored = score_eval_prompts(pipelines, eval_df, scout_ids, scout_vecs) | |
| probe_ok = eval_scored["cheap_probe"].notna().any() | |
| if not probe_ok: | |
| print(f" WARNING: No cheap_probe scores produced β check hidden states.") | |
| # ββ Routing evaluation ββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nββ Routing accuracy ββββββββββββββββββββββββββββββββββββββββ") | |
| results = { | |
| "random": route_random(eval_scored), | |
| "log_prob": route_single_signal(eval_scored, "mean_log_prob"), | |
| "neg_entropy": route_single_signal(eval_scored, "neg_entropy"), | |
| "cheap_router": route_single_signal(eval_scored, "cheap_probe") if probe_ok else float("nan"), | |
| "oracle": route_oracle(eval_scored), | |
| } | |
| # Domain-aware cheap router | |
| if probe_ok: | |
| da_acc, da_per_ds = route_domain_aware_cheap(eval_scored) | |
| results["cheap_domain_aware"] = da_acc | |
| else: | |
| results["cheap_domain_aware"] = float("nan") | |
| da_per_ds = {} | |
| # Load Step 3 domain-aware result for comparison (if available) | |
| step4_path = RESULTS_DIR / "domain_aware_routing.csv" | |
| if step4_path.exists(): | |
| step4_df = pd.read_csv(step4_path) | |
| da_row = step4_df[step4_df["signal"] == "domain_aware"] | |
| if not da_row.empty: | |
| results["step4_domain_aware"] = float(da_row["accuracy"].values[0]) | |
| descriptions = { | |
| "random": "Random expert selection", | |
| "log_prob": "Avg log-prob of answer tokens [A]", | |
| "neg_entropy": "Negated first-token entropy [B]", | |
| "cheap_router": f"Cheap router β {scout_key} hidden state only β ", | |
| "cheap_domain_aware": f"Cheap router + domain-aware ensemble β β ", | |
| "step4_domain_aware": "Step 3 domain-aware (per-expert probes, reference)", | |
| "oracle": "Oracle β best expert, offline", | |
| } | |
| print(f"\n {'Signal':<26} {'Description':<44} {'Accuracy':>9}") | |
| print(" " + "β" * 81) | |
| for name, acc in results.items(): | |
| acc_str = f"{acc:.4f}" if not np.isnan(acc) else " n/a" | |
| print(f" {name:<26} {descriptions.get(name,''):<44} {acc_str:>9}") | |
| # ββ Per-domain breakdown ββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if da_per_ds: | |
| print(f"\nββ Per-domain (cheap domain-aware router) ββββββββββββββββββ") | |
| print(f"\n {'Domain':<18} {'Signal':<16} {'Accuracy':>9}") | |
| print(" " + "β" * 45) | |
| for ds in sorted(da_per_ds): | |
| sig = DOMAIN_SIGNAL.get(ds, "mean_log_prob") | |
| print(f" {ds:<18} {sig:<16} {da_per_ds[ds]:.4f}") | |
| # ββ Cost summary ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| print(f"\nββ Compute cost summary ββββββββββββββββββββββββββββββββββββ") | |
| print(f" Step 2 / Step 3 router : 5 forward passes per prompt (all experts)") | |
| print(f" Cheap router ({scout_key}): 1 forward pass per prompt (scout only)") | |
| if not np.isnan(results.get("cheap_router", float("nan"))): | |
| cost_of_cheapness = results.get("step4_domain_aware", results["log_prob"]) - results["cheap_router"] | |
| print( | |
| f" Accuracy cost of using 1 pass instead of 5: " | |
| f"{cost_of_cheapness:+.4f} vs Step 3 domain-aware" | |
| ) | |
| if not np.isnan(results.get("cheap_domain_aware", float("nan"))): | |
| gap_to_oracle = results["oracle"] - results["cheap_domain_aware"] | |
| print(f" Gap to oracle: {gap_to_oracle:.4f}") | |
| return {"scout": scout_key, "results": results, "per_domain": da_per_ds} | |
| # ββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def main(): | |
| parser = argparse.ArgumentParser( | |
| description="Train and evaluate a cheap single-forward-pass router." | |
| ) | |
| parser.add_argument( | |
| "--scout", | |
| default=DEFAULT_SCOUT, | |
| choices=MODELS, | |
| help=f"Scout model to use (default: {DEFAULT_SCOUT}).", | |
| ) | |
| parser.add_argument( | |
| "--sweep_scouts", | |
| action="store_true", | |
| help="Run all models as scout and compare. Ignores --scout.", | |
| ) | |
| args = parser.parse_args() | |
| print("=== Step 4: Cheap Single-Pass Router ===\n") | |
| # ββ Load and split data βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| df = load_all_results() | |
| train_df, eval_df = make_split(df) | |
| scouts = MODELS if args.sweep_scouts else [args.scout] | |
| all_runs = [] | |
| for scout_key in scouts: | |
| run = run_scout(scout_key, df, train_df, eval_df) | |
| if run: | |
| all_runs.append(run) | |
| # ββ Save combined results βββββββββββββββββββββββββββββββββββββββββββββββββ | |
| out_rows = [] | |
| for run in all_runs: | |
| scout = run["scout"] | |
| for signal, acc in run["results"].items(): | |
| out_rows.append({ | |
| "scout": scout, | |
| "signal": signal, | |
| "accuracy": acc, | |
| }) | |
| out_df = pd.DataFrame(out_rows) | |
| out_df.to_csv(RESULTS_DIR / "cheap_router_results.csv", index=False) | |
| print(f"\nβ Results β {RESULTS_DIR / 'cheap_router_results.csv'}") | |
| # ββ Scout sweep summary βββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if args.sweep_scouts and len(all_runs) > 1: | |
| print(f"\n{'='*60}") | |
| print("Scout sweep summary β cheap_domain_aware accuracy by scout") | |
| print(f"{'='*60}") | |
| print(f"\n {'Scout':<16} {'cheap_router':>14} {'cheap_domain_aware':>20}") | |
| print(" " + "β" * 52) | |
| for run in all_runs: | |
| cr = run["results"].get("cheap_router", float("nan")) | |
| cda = run["results"].get("cheap_domain_aware", float("nan")) | |
| print( | |
| f" {run['scout']:<16} " | |
| f"{cr:>14.4f} " | |
| f"{cda:>20.4f}" | |
| ) | |
| best = max(all_runs, key=lambda r: r["results"].get("cheap_domain_aware", 0.0)) | |
| print(f"\n Best scout: {best['scout']} " | |
| f"({best['results'].get('cheap_domain_aware', float('nan')):.4f})") | |
| if __name__ == "__main__": | |
| main() | |