""" 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()