File size: 24,912 Bytes
c950b9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
"""
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()