File size: 15,044 Bytes
3db31c5 | 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 | #!/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/<cfg>/predictions_<split>.parquet idx, split, label, pred,
correct, entropy, seq_len,
logit_i, prob_i, subject
data/features/<cfg>/cls_{begin,mid,last}_<split>.npz features, columns, idx
data/layer_states/<cfg>/states_<split>.npy (N, L+1, D) float16
data/layer_states/<cfg>/meta_<split>.npz idx, label, n_layers, dim
extraction/outputs/<cfg>/predictions_<split>.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()
|