File size: 27,272 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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
"""
Step 1: Direct-from-HuggingFace Prompt Collection + Model Inference
=====================================================================
Loads four benchmarks directly from HuggingFace (clean answer keys, no
RouterBench dependency) and runs each of 5 expert models on them, extracting
THREE logit-based signals per (prompt, expert) pair:

  Feature A β€” mean_log_prob     : avg log-prob of generated answer tokens
  Feature B β€” first_tok_entropy : entropy of the first-token distribution
  Feature C β€” last_hidden_state : last-layer last-token hidden vector (saved
                                   separately for probe training in Step 2)

No verbal self-assessment anywhere. All signals come from model internals.

DATASETS (chosen for specialist/generalist contrast β€” see project notes):
  GSM8K          100 prompts, stratified to the HARDER half of the test
                 split (avoids near-100% accuracy / class imbalance for
                 Qwen-Math). Qwen-Math expected to dominate.
  HumanEval      All 164 prompts. Code execution scoring via subprocess.
                 Qwen-Coder expected to dominate.
  MMLU           100 prompts across 6 diverse subjects (not all 57 β€” avoids
                 wasting compute on near-uniform-difficulty subjects).
                 General models (Phi-3, Qwen-3B) expected to win.
  CommonsenseQA  100 prompts. No specialist advantage β€” baseline domain
                 where routing signal should be weak/uniform.

  Total: ~464 prompts Γ— 5 models. No RouterBench, no answer-key workarounds.

Run:
  python src/01_collect_data.py [--model MODEL_KEY] [--max_prompts N] [--batch_size N]

  --model       Run one model only (parallelise across Kaggle sessions)
  --max_prompts Cap total prompts across all domains (for a smoke test)
  --batch_size  Prompts between progress log lines (default 50)
"""

import os, sys, json, argparse, traceback, random
from pathlib import Path
from datetime import datetime

import torch
import numpy as np
import pandas as pd
from datasets import load_dataset
from tqdm import tqdm

sys.path.insert(0, str(Path(__file__).parent))
from collect_data_helpers import build_prompt, load_model, score_answer

# ── Paths ──────────────────────────────────────────────────────────────────────
BASE_DIR    = Path(__file__).resolve().parent.parent  # project root (scripts live in src/)
CKPT_DIR    = BASE_DIR / "checkpoints"
RESULTS_DIR = BASE_DIR / "results"
HIDDEN_DIR  = BASE_DIR / "hidden_states"   # large numpy arrays, one file per model
LOG_DIR     = BASE_DIR / "logs"
for d in [CKPT_DIR, RESULTS_DIR, HIDDEN_DIR, LOG_DIR]:
    d.mkdir(exist_ok=True)

# ── Model registry ─────────────────────────────────────────────────────────────
# 5 models, all ≀3.8B β€” fits comfortably on a single T4 in fp16.
# 7B models dropped: too slow for the compute budget and not needed β€”
# the specialist/generalist contrast is already clear at this size.
MODELS = {
    "qwen25_1b":    "Qwen/Qwen2.5-1.5B-Instruct",       # general, 1.5B
    "qwen25_3b":    "Qwen/Qwen2.5-3B-Instruct",          # general, 3B
    "phi3_mini":    "microsoft/Phi-3-mini-4k-instruct",  # general, 3.8B (strong for size)
    "qwen25_math":  "Qwen/Qwen2.5-Math-1.5B-Instruct",   # math specialist, 1.5B
    "qwen25_coder": "Qwen/Qwen2.5-Coder-1.5B-Instruct",  # code specialist, 1.5B
}

# Precision per model β€” fp16 for everything (no 4-bit needed at this size;
# 4-bit dequantization overhead on small models is slower than fp16 outright)
USE_4BIT = {
    "qwen25_1b":    False,
    "qwen25_3b":    False,
    "phi3_mini":    False,
    "qwen25_math":  False,
    "qwen25_coder": False,
}

# Phi-3's remote code has a rope_scaling KeyError under trust_remote_code=True
# on some transformers versions β€” load it without remote code.
TRUST_REMOTE_CODE = {
    "qwen25_1b":    True,
    "qwen25_3b":    True,
    "phi3_mini":    False,
    "qwen25_math":  True,
    "qwen25_coder": True,
}


# ── Logging ────────────────────────────────────────────────────────────────────
def get_logger(model_key):
    import logging
    log_file = LOG_DIR / f"{model_key}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s | %(levelname)s | %(message)s",
        handlers=[logging.FileHandler(log_file), logging.StreamHandler()],
    )
    return logging.getLogger(model_key)


# ── Checkpoint helpers ─────────────────────────────────────────────────────────
def ckpt_path(model_key):
    return CKPT_DIR / f"{model_key}_progress.jsonl"


def load_checkpoint(model_key):
    """Return (set of completed prompt_ids, list of saved rows)."""
    path = ckpt_path(model_key)
    done_ids, rows = set(), []
    if path.exists():
        with open(path) as f:
            for line in f:
                row = json.loads(line)
                done_ids.add(row["prompt_id"])
                rows.append(row)
    return done_ids, rows


def save_row(model_key, row):
    """Append one result row immediately β€” crash-safe."""
    with open(ckpt_path(model_key), "a") as f:
        f.write(json.dumps(row) + "\n")


def finalise(model_key, logger):
    """Consolidate JSONL checkpoint β†’ Parquet (excludes the bulky hidden states)."""
    path = ckpt_path(model_key)
    if not path.exists():
        logger.warning(f"No checkpoint for {model_key}")
        return
    df = pd.read_json(path, lines=True)
    out = RESULTS_DIR / f"{model_key}_results.parquet"
    df.to_parquet(out, index=False)
    logger.info(f"Saved {len(df)} rows β†’ {out}")
    return df


# ── Hidden-state store ─────────────────────────────────────────────────────────
class HiddenStateStore:
    """
    Incrementally saves hidden states to a .npz archive.
    Hidden states are large (e.g. 4096-dim for 7B models), so they are stored
    separately from the main results to keep the JSONL checkpoint small.

    Layout: hidden_states/{model_key}_hidden.npz
      keys: prompt_ids  β€” (N,) array of prompt_id strings
            vectors     β€” (N, hidden_dim) float32 array
    """

    def __init__(self, model_key):
        self.path    = HIDDEN_DIR / f"{model_key}_hidden.npz"
        self.tmp_ids = []
        self.tmp_vecs = []
        self._load_existing()

    def _load_existing(self):
        if self.path.exists():
            data = np.load(self.path, allow_pickle=True)
            self.existing_ids  = set(data["prompt_ids"].tolist())
            self.existing_vecs = data["vectors"]            # (N, D)
            self.ex_id_list    = data["prompt_ids"].tolist()
        else:
            self.existing_ids  = set()
            self.existing_vecs = None
            self.ex_id_list    = []

    def already_saved(self, prompt_id):
        return prompt_id in self.existing_ids

    def add(self, prompt_id, vector):
        """Buffer one hidden state. Call flush() periodically."""
        self.tmp_ids.append(prompt_id)
        self.tmp_vecs.append(vector)

    def flush(self):
        """Write buffered states to disk, merging with existing."""
        if not self.tmp_ids:
            return
        new_ids  = np.array(self.tmp_ids)
        new_vecs = np.stack(self.tmp_vecs, axis=0).astype(np.float32)

        if self.existing_vecs is not None:
            all_ids  = np.array(self.ex_id_list + self.tmp_ids)
            all_vecs = np.concatenate([self.existing_vecs, new_vecs], axis=0)
        else:
            all_ids  = new_ids
            all_vecs = new_vecs

        np.savez_compressed(self.path, prompt_ids=all_ids, vectors=all_vecs)

        # Update in-memory index
        self.ex_id_list   += self.tmp_ids
        self.existing_ids |= set(self.tmp_ids)
        self.existing_vecs = all_vecs
        self.tmp_ids   = []
        self.tmp_vecs  = []


# ── Dataset loader ─────────────────────────────────────────────────────────────
#
# Four benchmarks loaded directly from HuggingFace with clean ground-truth
# answer keys β€” no RouterBench dependency, no reference-answer workarounds.
#
# GSM8K (math, Qwen-Math should dominate):
#   Stratified to the HARDER half of the test split. Qwen-Math scores near
#   100% on easy GSM8K problems, which gives almost no negative examples for
#   probe training β€” class imbalance kills the probe. Taking harder problems
#   (the latter portion of the test split, which tends to need more reasoning
#   steps) produces real variance in correctness.
#
# HumanEval (code, Qwen-Coder should dominate):
#   All 164 prompts used β€” small enough to run in full. Scored via actual
#   code execution in a subprocess sandbox with a timeout, not string
#   matching. This is the only domain requiring code execution.
#
# MMLU (knowledge, general models should win):
#   100 prompts across 6 deliberately diverse subjects rather than a random
#   sample across all 57 β€” avoids wasting compute on subjects with uniform
#   difficulty. Subjects chosen for topic diversity: math, physics, CS,
#   history, medicine, law.
#
# CommonsenseQA (no specialist advantage β€” baseline domain):
#   100 prompts. Tests whether routing degrades gracefully to "no clear
#   winner" when no expert has a domain edge.

GSM8K_N        = 100
HUMANEVAL_N    = 164   # full set
MMLU_N         = 100
MMLU_SUBJECTS  = ["abstract_algebra", "college_physics", "college_computer_science",
                   "high_school_world_history", "clinical_knowledge", "professional_law"]
COMMONSENSE_N  = 100

RANDOM_SEED = 42


def _load_gsm8k(n=GSM8K_N, seed=RANDOM_SEED):
    """
    Load the HARDER half of GSM8K test split.
    Stratification rationale: Qwen-Math-1.5B scores near 100% on easy GSM8K
    problems, leaving almost no incorrect examples for the probe to learn
    from. Taking only the harder half (by position in the test split, which
    correlates with reasoning depth) produces real correctness variance.
    """
    ds = load_dataset("gsm8k", "main", split="test")
    total = len(ds)
    harder_half = ds.select(range(total // 2, total))  # back half = harder

    random.seed(seed)
    indices = list(range(len(harder_half)))
    random.shuffle(indices)
    indices = indices[:n]

    rows = []
    for i in indices:
        r = harder_half[i]
        answer_key = r["answer"].split("####")[-1].strip().replace(",", "")
        rows.append({
            "prompt_id":  f"gsm8k_{total//2 + i}",
            "prompt":     r["question"],
            "eval_name":  "gsm8k",
            "dataset":    "gsm8k",
            "answer_key": answer_key,
        })
    return rows


def _load_humaneval(n=HUMANEVAL_N):
    """Load all HumanEval prompts. Scored via subprocess execution in score_answer."""
    ds = load_dataset("openai_humaneval", split="test")
    rows = []
    for i, r in enumerate(ds):
        if i >= n:
            break
        rows.append({
            "prompt_id":   f"humaneval_{r['task_id'].replace('/', '_')}",
            "prompt":      r["prompt"],          # function signature + docstring
            "eval_name":   "humaneval",
            "dataset":     "humaneval",
            "answer_key":  r["canonical_solution"],
            "test_code":   r["test"],            # unit tests β€” needed for execution scoring
            "entry_point": r["entry_point"],
        })
    return rows


def _load_mmlu(n=MMLU_N, subjects=MMLU_SUBJECTS, seed=RANDOM_SEED):
    """Load n prompts spread across deliberately diverse MMLU subjects."""
    random.seed(seed)
    per_subject = max(1, n // len(subjects))
    cmap = {0: "A", 1: "B", 2: "C", 3: "D"}
    rows = []

    for subject in subjects:
        try:
            ds = load_dataset("cais/mmlu", subject, split="test")
        except Exception:
            continue
        indices = list(range(len(ds)))
        random.shuffle(indices)
        indices = indices[:per_subject]

        for i in indices:
            r = ds[i]
            choices_text = "\n".join(
                f"{cmap[j]}. {c}" for j, c in enumerate(r["choices"])
            )
            prompt = f"{r['question']}\n{choices_text}\nAnswer with a single letter (A, B, C, or D):"
            rows.append({
                "prompt_id":  f"mmlu_{subject}_{i}",
                "prompt":     prompt,
                "eval_name":  f"mmlu-{subject}",
                "dataset":    "mmlu",
                "answer_key": cmap[r["answer"]],
            })
    return rows[:n]


def _load_commonsenseqa(n=COMMONSENSE_N, seed=RANDOM_SEED):
    """Load CommonsenseQA β€” domain with no specialist advantage (baseline)."""
    ds = load_dataset("tau/commonsense_qa", split="validation")
    random.seed(seed)
    indices = list(range(len(ds)))
    random.shuffle(indices)
    indices = indices[:n]

    rows = []
    for i in indices:
        r = ds[i]
        labels  = r["choices"]["label"]
        texts   = r["choices"]["text"]
        choices_text = "\n".join(f"{l}. {t}" for l, t in zip(labels, texts))
        prompt = f"{r['question']}\n{choices_text}\nAnswer with a single letter:"
        rows.append({
            "prompt_id":  f"csqa_{r['id']}",
            "prompt":     prompt,
            "eval_name":  "commonsenseqa",
            "dataset":    "commonsenseqa",
            "answer_key": r["answerKey"],
        })
    return rows


def load_prompts(max_prompts=None, cache_dir=None, logger=None):
    """
    Load all four domains directly from HuggingFace. Clean ground-truth
    answer keys throughout β€” no RouterBench, no reference-answer extraction.

    Parameters
    ----------
    max_prompts : int | None
        If set, stratified-cap the TOTAL across all four domains.
        Per-domain caps (GSM8K_N, HUMANEVAL_N, MMLU_N, COMMONSENSE_N) apply
        first regardless β€” this only trims further if max_prompts is smaller.
    cache_dir   : Path | None
        Unused now (kept for CLI compatibility) β€” HuggingFace `datasets`
        manages its own cache under ~/.cache/huggingface.
    logger      : logging.Logger | None

    Returns
    -------
    list of dicts: {prompt_id, prompt, eval_name, dataset, answer_key, ...}
    HumanEval rows additionally carry 'test_code' and 'entry_point'.
    """
    import logging
    if logger is None:
        logger = logging.getLogger("load_prompts")

    logger.info("Loading datasets directly from HuggingFace (no RouterBench)...")

    prompts = []

    logger.info(f"  GSM8K (hard half, n={GSM8K_N})...")
    gsm8k_rows = _load_gsm8k()
    prompts.extend(gsm8k_rows)
    logger.info(f"    β†’ {len(gsm8k_rows)} prompts")

    logger.info(f"  HumanEval (n={HUMANEVAL_N})...")
    he_rows = _load_humaneval()
    prompts.extend(he_rows)
    logger.info(f"    β†’ {len(he_rows)} prompts")

    logger.info(f"  MMLU ({len(MMLU_SUBJECTS)} subjects, n={MMLU_N})...")
    mmlu_rows = _load_mmlu()
    prompts.extend(mmlu_rows)
    logger.info(f"    β†’ {len(mmlu_rows)} prompts")

    logger.info(f"  CommonsenseQA (n={COMMONSENSE_N})...")
    csqa_rows = _load_commonsenseqa()
    prompts.extend(csqa_rows)
    logger.info(f"    β†’ {len(csqa_rows)} prompts")

    logger.info(f"Total loaded: {len(prompts):,} prompts")

    # ── Optional further cap (stratified across domains) ───────────────────────
    if max_prompts and len(prompts) > max_prompts:
        by_ds = {}
        for p in prompts:
            by_ds.setdefault(p["dataset"], []).append(p)
        per_ds = max(1, max_prompts // len(by_ds))
        random.seed(RANDOM_SEED)
        prompts = []
        for rows in by_ds.values():
            random.shuffle(rows)
            prompts.extend(rows[:per_ds])
        prompts = prompts[:max_prompts]
        logger.info(f"Capped to {len(prompts):,} prompts (stratified)")

    # Log final counts per domain
    counts = {}
    for p in prompts:
        counts[p["dataset"]] = counts.get(p["dataset"], 0) + 1
    for ds, n in sorted(counts.items()):
        logger.info(f"  {ds}: {n:,}")

    return prompts


# ── Inference + feature extraction ────────────────────────────────────────────
@torch.no_grad()
def run_inference(model, tokenizer, prompt_text, model_key, device,
                  dataset=None, max_new_tokens=128):
    """
    Single forward pass + generation.

    max_new_tokens is bumped to 256 for HumanEval β€” code solutions routinely
    exceed 128 tokens and silent truncation gets scored as incorrect, which
    biases HumanEval accuracy downward for no good reason.

    Returns
    -------
    response          : str   β€” decoded answer
    mean_log_prob     : float β€” Feature A: avg log-prob of answer tokens
    first_tok_entropy : float β€” Feature B: entropy of first-token distribution
    last_hidden       : np.ndarray β€” Feature C: last-layer last-token vector
    """
    if dataset == "humaneval":
        max_new_tokens = max(max_new_tokens, 256)
    if model_key == "qwen25_math":
        # Qwen-Math uses chain-of-thought before outputting \boxed{answer}.
        # 128 tokens cuts off mid-reasoning before the answer appears.
        # Official model card uses max_new_tokens=512.
        max_new_tokens = max(max_new_tokens, 512)

    formatted = build_prompt(prompt_text, tokenizer, model_key, dataset=dataset)
    inputs    = tokenizer(
        formatted,
        return_tensors="pt",
        truncation=True,
        max_length=1024,
        return_attention_mask=True,   # always return mask explicitly β€”
                                      # avoids the warning when pad_token==eos_token
                                      # (all Qwen models) and prevents incorrect
                                      # attention behaviour on padded sequences
    )
    input_ids      = inputs["input_ids"].to(device)
    attention_mask = inputs["attention_mask"].to(device)
    prompt_len     = input_ids.shape[1]

    out = model.generate(
        input_ids,
        attention_mask=attention_mask,    # pass mask explicitly β€” required when
                                          # pad_token_id == eos_token_id so the
                                          # model knows which tokens are real input
        max_new_tokens=max_new_tokens,
        do_sample=False,                  # greedy β€” reproducible
        return_dict_in_generate=True,
        output_scores=True,               # logits at each step β†’ Features A & B
        output_hidden_states=True,        # hidden states at each step β†’ Feature C
        pad_token_id=tokenizer.pad_token_id,
    )

    # ── Decode answer ──────────────────────────────────────────────────────────
    gen_ids  = out.sequences[0, prompt_len:]
    response = tokenizer.decode(gen_ids, skip_special_tokens=True).strip()

    # ── Feature A: mean log-prob of generated tokens ───────────────────────────
    if out.scores:
        log_probs = []
        for step, score in enumerate(out.scores):
            if step >= len(gen_ids):
                break
            token_id = gen_ids[step].item()
            lp = torch.log_softmax(score[0], dim=-1)[token_id].item()
            log_probs.append(lp)
        mean_log_prob = float(sum(log_probs) / len(log_probs)) if log_probs else 0.0

        # ── Feature B: entropy of the first-token distribution ─────────────────
        first_dist        = torch.softmax(out.scores[0][0], dim=-1)
        first_tok_entropy = float(
            -(first_dist * torch.log(first_dist + 1e-9)).sum().item()
        )
    else:
        mean_log_prob, first_tok_entropy = 0.0, 0.0

    # ── Feature C: last-layer hidden state at the last generated token ─────────
    # out.hidden_states is a tuple of length n_generated_tokens.
    # Each element is a tuple of (n_layers+1) tensors, shape [1, seq_len, D].
    # We take the final generation step β†’ final layer β†’ last token position.
    last_hidden = None
    if out.hidden_states:
        # Last generation step, last layer, last position
        final_step_hiddens = out.hidden_states[-1]   # tuple of layer tensors
        last_layer_tensor  = final_step_hiddens[-1]  # [1, seq_len_at_step, D]
        last_hidden = last_layer_tensor[0, -1, :].cpu().float().numpy()

    return response, mean_log_prob, first_tok_entropy, last_hidden


# ── Main per-model loop ────────────────────────────────────────────────────────
def run_model(model_key, prompts, batch_size, logger):
    model_id = MODELS[model_key]
    device   = "cuda" if torch.cuda.is_available() else "cpu"

    done_ids, _ = load_checkpoint(model_key)
    hs_store    = HiddenStateStore(model_key)
    remaining   = [p for p in prompts if p["prompt_id"] not in done_ids]

    logger.info(
        f"Prompts total={len(prompts)} done={len(done_ids)} remaining={len(remaining)}"
    )

    if not remaining:
        logger.info("Already complete β€” running finalise.")
        finalise(model_key, logger)
        return

    use_4bit = USE_4BIT.get(model_key, True)
    trust_remote = TRUST_REMOTE_CODE.get(model_key, True)
    model, tokenizer = load_model(model_key, model_id, logger,
                                  use_4bit=use_4bit, trust_remote_code=trust_remote)
    errors = 0

    for i, p in enumerate(tqdm(remaining, desc=model_key)):
        pid = p["prompt_id"]
        try:
            response, mean_log_prob, entropy, last_hidden = run_inference(
                model, tokenizer, p["prompt"], model_key, device,
                dataset=p["dataset"]
            )
            # score_answer needs the full prompt dict (eval_name + answer_key,
            # plus test_code/entry_point for HumanEval)
            is_correct = score_answer(response, p)

            # ── Save scalar features to JSONL checkpoint ───────────────────────
            row = {
                "prompt_id":         pid,
                "prompt":            p["prompt"],
                "eval_name":         p["eval_name"],
                "dataset":           p["dataset"],
                "answer_key":        p.get("answer_key", ""),
                "model_key":         model_key,
                "model_id":          model_id,
                "response":          response,
                "is_correct":        is_correct,
                "mean_log_prob":     mean_log_prob,     # Feature A
                "first_tok_entropy": entropy,            # Feature B
                "timestamp":         datetime.utcnow().isoformat(),
            }
            save_row(model_key, row)

            # ── Buffer hidden state separately ─────────────────────────────────
            if last_hidden is not None and not hs_store.already_saved(pid):
                hs_store.add(pid, last_hidden)

        except Exception as e:
            errors += 1
            logger.error(f"Error on {pid}: {e}\n{traceback.format_exc()}")
            if errors > 50:
                logger.error("Too many errors β€” stopping. Fix and resume.")
                break

        # Flush hidden states and log every batch_size prompts
        if (i + 1) % batch_size == 0:
            hs_store.flush()
            done_now = len(done_ids) + i + 1
            logger.info(f"Progress {done_now}/{len(prompts)} | errors={errors}")

    hs_store.flush()   # flush any remaining

    del model
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

    finalise(model_key, logger)
    logger.info(f"Finished {model_key}. Total errors: {errors}")


# ── Entry point ────────────────────────────────────────────────────────────────
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model",       type=str, default=None,
                        help=f"One of {list(MODELS.keys())} β€” omit to run all")
    parser.add_argument("--max_prompts", type=int, default=None,
                        help="Cap prompts (200 for smoke test)")
    parser.add_argument("--batch_size",  type=int, default=50,
                        help="Prompts between progress logs and hidden-state flushes")
    parser.add_argument("--cache_dir",   type=str, default=None,
                        help="Unused β€” kept for CLI compatibility. HuggingFace "
                             "datasets manages its own cache under "
                             "~/.cache/huggingface/datasets")
    parser.add_argument("--reset",  action="store_true",
                        help="Delete existing checkpoint for the specified model "
                             "and rerun from scratch. Use this when you have fixed "
                             "the prompt format and need fresh results. "
                             "Only deletes the checkpoint for --model, not all models.")
    args = parser.parse_args()

    if args.reset and args.model:
        ckpt = ckpt_path(args.model)
        hidden = HIDDEN_DIR / f"{args.model}_hidden.npz"
        result = RESULTS_DIR / f"{args.model}_results.parquet"
        for p in [ckpt, hidden, result]:
            if p.exists():
                p.unlink()
                print(f"Deleted: {p}")
        print(f"Checkpoint cleared for {args.model} β€” will rerun from scratch")

    # Datasets are loaded fresh each run via HuggingFace `datasets`, which
    # caches downloads automatically β€” no manual pkl caching needed anymore.
    bootstrap_logger = get_logger("bootstrap")
    prompts = load_prompts(
        max_prompts=args.max_prompts,
        cache_dir=args.cache_dir,
        logger=bootstrap_logger,
    )
    models_to_run = [args.model] if args.model else list(MODELS.keys())

    for mk in models_to_run:
        if mk not in MODELS:
            print(f"Unknown model key '{mk}'. Valid: {list(MODELS.keys())}")
            continue
        logger = get_logger(mk)
        logger.info(f"=== Starting {mk} ===")
        run_model(mk, prompts, args.batch_size, logger)

    print("\nDone. Results β†’", RESULTS_DIR)
    print("Hidden states β†’", HIDDEN_DIR)


if __name__ == "__main__":
    main()