#!/usr/bin/env python3 """Stage 1 for a decoder-only model on multiple-choice QA. The classifier here is a pre-trained instruction-tuned decoder answering a multiple-choice question zero-shot: the prediction is the answer letter with the largest next-token logit at the last prompt position. That position plays the role [CLS] plays for the encoders, so the residual stream there, at every layer, is written in exactly the layout scripts/25 produces, and the rest of the pipeline (scripts/26 onward) runs unchanged. Writes, for cfg = run_name and split in {train, validation, test}: data/features//predictions_.parquet idx, split, label, pred, correct, entropy, seq_len, logit_i, prob_i, subject data/features//cls_{begin,mid,last}_.npz features, columns, idx data/layer_states//states_.npy (N, L+1, D) float16 data/layer_states//meta_.npz idx, label, n_layers, dim extraction/outputs//predictions_.parquet (copy, as stage 1 does) The three splits are a random, subject-stratified partition of the pooled question set; the model is never trained on any of it. `data.split_seed` picks the partition, so replicates differ in the partition rather than in fine-tuning seed. python extraction/scripts/11_extract_decoder_states.py \ --config extraction/configs/qwen15_mmlu.yaml """ from __future__ import annotations import argparse import shutil import sys import time from pathlib import Path import numpy as np import pandas as pd import torch REPO = Path(__file__).resolve().parents[2] sys.path.insert(0, str(REPO / "extraction")) from src.utils import load_config, seed_everything # noqa: E402 LETTERS = "ABCDEFGH" # ---------------------------------------------------------------- datasets -- def load_questions(dcfg: dict) -> pd.DataFrame: """One row per question: idx, subject, question, choices (list), label.""" from datasets import load_dataset src = dcfg["source"] if src == "mmlu": parts = [] for sp in dcfg.get("hf_splits", ["test", "validation"]): ds = load_dataset("cais/mmlu", "all", split=sp) df = ds.to_pandas() df["hf_split"] = sp parts.append(df) df = pd.concat(parts, ignore_index=True) df = df.rename(columns={"answer": "label"}) df["choices"] = df["choices"].apply(list) elif src == "csqa": parts = [] for sp in dcfg.get("hf_splits", ["train", "validation"]): ds = load_dataset("tau/commonsense_qa", split=sp) df = ds.to_pandas() df["hf_split"] = sp parts.append(df) df = pd.concat(parts, ignore_index=True) df["subject"] = df["question_concept"] df["choices"] = df["choices"].apply(lambda c: list(c["text"])) df["label"] = df["answerKey"].map(lambda k: LETTERS.index(k)) elif src == "arc": # ARC-Easy and ARC-Challenge pooled; a few items use 1-4 keys and a # few have 3 or 5 choices; the 4-choice letter-keyed majority is kept # so the class set is fixed. parts = [] for cfg_name in ("ARC-Easy", "ARC-Challenge"): for sp in dcfg.get("hf_splits", ["train", "validation", "test"]): ds = load_dataset("allenai/ai2_arc", cfg_name, split=sp) df = ds.to_pandas() df["hf_split"] = f"{cfg_name}/{sp}" parts.append(df) df = pd.concat(parts, ignore_index=True) df["choices"] = df["choices"].apply(lambda c: list(c["text"])) df["answerKey"] = df["answerKey"].replace({"1": "A", "2": "B", "3": "C", "4": "D"}) df = df[df["choices"].apply(len) == 4].reset_index(drop=True) df["label"] = df["answerKey"].map(lambda k: LETTERS.index(k)) df["subject"] = "science" elif src == "openbookqa": parts = [] for sp in dcfg.get("hf_splits", ["train", "validation", "test"]): ds = load_dataset("allenai/openbookqa", "main", split=sp) df = ds.to_pandas() df["hf_split"] = sp parts.append(df) df = pd.concat(parts, ignore_index=True) df = df.rename(columns={"question_stem": "question"}) df["choices"] = df["choices"].apply(lambda c: list(c["text"])) df["label"] = df["answerKey"].map(lambda k: LETTERS.index(k)) df["subject"] = "elementary science" elif src == "sciq": parts = [] for sp in dcfg.get("hf_splits", ["train", "validation", "test"]): ds = load_dataset("allenai/sciq", split=sp) df = ds.to_pandas() df["hf_split"] = sp parts.append(df) df = pd.concat(parts, ignore_index=True) # the correct answer is a separate field; shuffle it among the # distractors with a fixed seed so the label position is uniform rng = np.random.RandomState(int(dcfg.get("option_seed", 0))) ch, lab = [], [] for _, r in df.iterrows(): opts = [r["correct_answer"], r["distractor1"], r["distractor2"], r["distractor3"]] perm = rng.permutation(4) ch.append([opts[i] for i in perm]); lab.append(int(np.where(perm == 0)[0][0])) df["choices"], df["label"] = ch, lab df["subject"] = "science" elif src == "medmcqa": ds = load_dataset("openlifescienceai/medmcqa", split="train") df = ds.to_pandas() df["hf_split"] = "train" n = int(dcfg.get("n_questions", 16000)) df = df.sample(n=min(n, len(df)), random_state=int(dcfg.get("sample_seed", 0))) df = df.reset_index(drop=True) df["choices"] = df.apply(lambda r: [r["opa"], r["opb"], r["opc"], r["opd"]], axis=1) df["label"] = df["cop"].astype(int) df["subject"] = df["subject_name"].fillna("medicine") elif src == "hellaswag": parts = [] for sp in dcfg.get("hf_splits", ["validation", "train"]): ds = load_dataset("Rowan/hellaswag", split=sp) df = ds.to_pandas() df["hf_split"] = sp parts.append(df) df = pd.concat(parts, ignore_index=True) n = int(dcfg.get("n_questions", 16000)) df = df.sample(n=min(n, len(df)), random_state=int(dcfg.get("sample_seed", 0))) df = df.reset_index(drop=True) df["question"] = df["ctx"] df["choices"] = df["endings"].apply(list) df["label"] = df["label"].astype(int) df["subject"] = df["activity_label"] else: raise ValueError(f"unknown data.source {src!r}") n_choice = dcfg.get("n_choices") if n_choice is not None: df = df[df["choices"].apply(len) == n_choice].reset_index(drop=True) df = df.reset_index(drop=True) df["idx"] = np.arange(len(df), dtype=np.int64) return df[["idx", "hf_split", "subject", "question", "choices", "label"]] def partition(df: pd.DataFrame, fractions, seed: int) -> pd.Series: """Stratified (by subject) random assignment to train/validation/test.""" rng = np.random.RandomState(seed) names = ["train", "validation", "test"] f = np.cumsum(fractions) assert abs(f[-1] - 1.0) < 1e-9, fractions out = pd.Series(index=df.index, dtype=object) for _, g in df.groupby("subject"): order = g.index.values[rng.permutation(len(g))] cut = (f * len(order)).round().astype(int) out[order[:cut[0]]] = names[0] out[order[cut[0]:cut[1]]] = names[1] out[order[cut[1]:]] = names[2] return out # ------------------------------------------------------------------ prompt -- def build_prompt(tok, row, template: str, system: str | None) -> str: opts = "\n".join(f"{LETTERS[i]}. {c}" for i, c in enumerate(row["choices"])) subject = str(row["subject"]).replace("_", " ") user = template.format(subject=subject, question=row["question"].strip(), options=opts) msgs = ([{"role": "system", "content": system}] if system else []) + \ [{"role": "user", "content": user}] return tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) def letter_token_ids(tok, n: int) -> list[list[int]]: """For each letter, the single-token ids of its bare and space-prefixed forms.""" ids = [] for L in LETTERS[:n]: cands = set() for s in (L, " " + L): t = tok.encode(s, add_special_tokens=False) if len(t) == 1: cands.add(t[0]) assert cands, f"letter {L!r} is not a single token" ids.append(sorted(cands)) return ids # --------------------------------------------------------------------- run -- @torch.no_grad() def run_split(model, tok, df, letter_ids, bs, max_length, layers_keep): """Returns (pred_df, states (N, L+1, D) float16) in df row order.""" n_cls = len(letter_ids) N = len(df) prompts = df["prompt"].tolist() lengths = np.array([len(tok.encode(p, add_special_tokens=False)) for p in prompts]) order = np.argsort(-lengths) # longest first: OOM shows up at once states = None logits_all = np.zeros((N, n_cls), np.float32) seq_len = np.zeros(N, np.int64) t0 = time.time() for b in range(0, N, bs): rows = order[b:b + bs] enc = tok([prompts[i] for i in rows], return_tensors="pt", padding=True, truncation=True, max_length=max_length) enc = {k: v.to(model.device) for k, v in enc.items()} out = model(**enc, output_hidden_states=True) hs = torch.stack(out.hidden_states, dim=1)[:, :, -1, :] # (B, L+1, D), left-padded if states is None: states = np.zeros((N, hs.shape[1], hs.shape[2]), np.float16) states[rows] = hs.to(torch.float16).cpu().numpy() last = out.logits[:, -1, :].float() # (B, V) lt = torch.stack([last[:, ids].max(1).values for ids in letter_ids], 1) logits_all[rows] = lt.cpu().numpy() seq_len[rows] = enc["attention_mask"].sum(1).cpu().numpy() if (b // bs) % 50 == 0: print(f" {b + len(rows):6d}/{N} maxlen={int(lengths[rows].max())} " f"{time.time() - t0:.0f}s", flush=True) probs = np.exp(logits_all - logits_all.max(1, keepdims=True)) probs /= probs.sum(1, keepdims=True) pred = probs.argmax(1) ent = -(probs * np.log(np.clip(probs, 1e-12, None))).sum(1) label = df["label"].values.astype(np.int64) # idx is the row position within the split: every downstream reader # indexes the split's prediction frame positionally with it. The pooled # question id is kept alongside as qid. pdf = pd.DataFrame({"idx": np.arange(N, dtype=np.int64), "qid": df["idx"].values.astype(np.int64), "split": df["split"].values, "label": label, "pred": pred.astype(np.int64), "correct": (pred == label).astype(np.int64), "entropy": ent.astype(np.float32), "seq_len": seq_len}) for c in range(n_cls): pdf[f"logit{c}"] = logits_all[:, c] pdf[f"prob{c}"] = probs[:, c].astype(np.float32) pdf["subject"] = df["subject"].values return pdf, states def main(): ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("--config", required=True) ap.add_argument("--force", action="store_true") ap.add_argument("--limit", type=int, default=None, help="debug: rows per split") a = ap.parse_args() cfg = load_config(a.config) name = cfg["run_name"] feat_dir = REPO / "data" / "features" / name st_dir = REPO / "data" / "layer_states" / name out_dir = REPO / cfg["paths"]["output_dir"] for d in (feat_dir, st_dir, out_dir): d.mkdir(parents=True, exist_ok=True) if (st_dir / "states_test.npy").exists() and not a.force: print(f"[{name}] already extracted; use --force to redo"); return seed_everything(int(cfg.get("seed", 0))) dcfg = cfg["data"] df = load_questions(dcfg) df["split"] = partition(df, dcfg.get("fractions", [0.5, 0.2, 0.3]), int(dcfg.get("split_seed", 0))) print(f"[{name}] {len(df)} questions, C={df['choices'].apply(len).max()}, " f"splits={df['split'].value_counts().to_dict()}") mcfg = cfg["model"] from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained(mcfg["pretrained_path"]) tok.padding_side = "left" tok.truncation_side = "left" if tok.pad_token is None: tok.pad_token = tok.eos_token dtype = {"bfloat16": torch.bfloat16, "float16": torch.float16, "float32": torch.float32}[mcfg.get("dtype", "bfloat16")] model = AutoModelForCausalLM.from_pretrained(mcfg["pretrained_path"], torch_dtype=dtype) model = model.to(cfg["inference"].get("device", "cuda")).eval() n_cls = int(df["choices"].apply(len).max()) letter_ids = letter_token_ids(tok, n_cls) print(f" letter token ids: {letter_ids}") template = mcfg.get("prompt", "The following is a multiple choice question about " "{subject}.\n\n{question}\n{options}\n\nAnswer with the letter only.") system = mcfg.get("system", None) df["prompt"] = [build_prompt(tok, r, template, system) for _, r in df.iterrows()] print(" example prompt:\n" + df["prompt"].iloc[0]) for split in ("train", "validation", "test"): sub = df[df["split"] == split].reset_index(drop=True) if a.limit: sub = sub.iloc[:a.limit] t0 = time.time() pdf, states = run_split(model, tok, sub, letter_ids, int(cfg["inference"].get("batch_size", 8)), int(mcfg.get("max_length", 2048)), None) acc = pdf["correct"].mean() print(f" [{split}] n={len(pdf)} acc={acc:.4f} states={states.shape} " f"{time.time() - t0:.0f}s", flush=True) pdf.to_parquet(feat_dir / f"predictions_{split}.parquet", index=False) shutil.copy(feat_dir / f"predictions_{split}.parquet", out_dir / f"predictions_{split}.parquet") np.save(st_dir / f"states_{split}.npy", states) L1, D = states.shape[1], states.shape[2] np.savez(st_dir / f"meta_{split}.npz", idx=pdf["idx"].values, label=pdf["label"].values, n_layers=np.int64(L1), dim=np.int64(D)) for tag, l in (("cls_begin", 0), ("cls_mid", (L1 - 1) // 2), ("cls_last", L1 - 1)): np.savez_compressed( feat_dir / f"{tag}_{split}.npz", features=states[:, l, :].astype(np.float32), columns=np.array([f"{tag}_{d}" for d in range(D)], dtype=object), idx=pdf["idx"].values) print(f"[{name}] DONE") if __name__ == "__main__": main()