Download scripts/12_extract_mlp_path.py from zaaabik/paper_extraction: direct link, hf CLI and curl.
- Browser
- Download file 8.02 kB
-
https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/scripts/12_extract_mlp_path.py
- Command line
-
hf download hf://datasets/zaaabik/paper_extraction/scripts/12_extract_mlp_path.py
-
curl -L -o 12_extract_mlp_path.py https://huggingface.co/datasets/zaaabik/paper_extraction/resolve/main/scripts/12_extract_mlp_path.py
8.02 kB
| """Stage 1e: the per-layer MLP write-vectors at the read position, as the | |
| eleven path descriptors of Eusebi et al. (2026). | |
| Decoders: a forward hook on every decoder layer's MLP captures its output at | |
| the last prompt position (the answer position; left padding), for the same | |
| prompts in the same split order as 11_extract_decoder_states.py, which is | |
| checked by recomputing the prediction. Encoders: a hook on every layer's | |
| feed-forward output projection captures it at the [CLS] position, in the | |
| prediction parquet's row order, as 07_extract_layer_states.py does. Only the | |
| descriptors are written (data/features/<cfg>/mlppath_<split>.npz); the | |
| write-vectors themselves are not kept. | |
| python extraction/scripts/12_extract_mlp_path.py --config extraction/configs/qwen05_mmlu.yaml | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import importlib.util | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| ROOT = Path(__file__).resolve().parents[1] | |
| REPO = ROOT.parent | |
| sys.path.insert(0, str(ROOT)); sys.path.insert(0, str(REPO)) | |
| from src.utils import load_config, seed_everything, device_from_cfg # noqa: E402 | |
| from cct_reproduce.grids import is_decoder # noqa: E402 | |
| from cct_reproduce.mlp_path import write_features # noqa: E402 | |
| def _load_11(): | |
| spec = importlib.util.spec_from_file_location("dec11", ROOT / "scripts" / "11_extract_decoder_states.py") | |
| mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod) | |
| return mod | |
| class _Capture: | |
| """Forward hooks that keep the module output at one position.""" | |
| def __init__(self, modules, position): | |
| self.buf, self.position = [None] * len(modules), position | |
| self.handles = [m.register_forward_hook(self._hook(i)) for i, m in enumerate(modules)] | |
| def _hook(self, i): | |
| def f(_m, _in, out): | |
| o = out[0] if isinstance(out, tuple) else out | |
| self.buf[i] = o[:, self.position, :].detach().float().cpu() | |
| return f | |
| def stack(self): | |
| return torch.stack(self.buf, dim=1).numpy() # (B, L, D) | |
| def close(self): | |
| for h in self.handles: | |
| h.remove() | |
| def decoder(cfg, name, a): | |
| d11 = _load_11() | |
| df = d11.load_questions(cfg["data"]) | |
| df["split"] = d11.partition(df, cfg["data"].get("fractions", [0.5, 0.2, 0.3]), | |
| int(cfg["data"].get("split_seed", 0))) | |
| 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 = d11.letter_token_ids(tok, n_cls) | |
| template = mcfg.get("prompt", "The following is a multiple choice question about " | |
| "{subject}.\n\n{question}\n{options}\n\nAnswer with the letter only.") | |
| df["prompt"] = [d11.build_prompt(tok, r, template, mcfg.get("system", None)) for _, r in df.iterrows()] | |
| df = df.set_index("idx") | |
| cap = _Capture([layer.mlp for layer in model.model.layers], position=-1) | |
| bs, max_length = int(cfg["inference"].get("batch_size", 8)), int(mcfg.get("max_length", 2048)) | |
| for split in ("train", "validation", "test"): | |
| pdf = pd.read_parquet(REPO / "data" / "features" / name / f"predictions_{split}.parquet") | |
| sub = df.loc[pdf["qid"].values] | |
| prompts = sub["prompt"].tolist() | |
| N = len(prompts) | |
| lengths = np.array([len(tok.encode(p, add_special_tokens=False)) for p in prompts]) | |
| order = np.argsort(-lengths) | |
| M = None; pred = 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) | |
| m = cap.stack() | |
| if M is None: | |
| M = np.zeros((N, m.shape[1], m.shape[2]), np.float16) | |
| M[rows] = m.astype(np.float16) | |
| last = out.logits[:, -1, :].float() | |
| lt = torch.stack([last[:, ids].max(1).values for ids in letter_ids], 1) | |
| pred[rows] = lt.argmax(1).cpu().numpy() | |
| if (b // bs) % 100 == 0: | |
| print(f" {b + len(rows):6d}/{N} {time.time() - t0:.0f}s", flush=True) | |
| agree = float((pred == pdf["pred"].values).mean()) | |
| print(f" [{split}] n={N} M={M.shape} prediction agreement with the cache {agree:.4f} " | |
| f"{time.time() - t0:.0f}s", flush=True) | |
| if agree < 0.98: | |
| raise RuntimeError(f"{name} {split}: prompts or order differ from the cached run") | |
| write_features(name, split, M, pdf["idx"].values, REPO / "data") | |
| cap.close() | |
| def encoder(cfg, name, a): | |
| from src.load_data import load_splits | |
| from src.load_model import load_classification_model, move | |
| from src.extract_attention import _build_dataloader | |
| device = device_from_cfg(cfg) | |
| splits_data = load_splits(cfg) | |
| model, tokenizer = load_classification_model( | |
| cfg["model"]["pretrained_path"], num_labels=cfg["model"].get("num_labels"), | |
| base_tokenizer=cfg["model"].get("base_tokenizer"), | |
| do_lower_case=cfg["model"].get("do_lower_case"), | |
| is_peft=cfg["model"].get("is_peft", False), base_model=cfg["model"].get("base_model")) | |
| model = move(model, device).eval() | |
| layers = model.base_model.encoder.layer | |
| cap = _Capture([layer.output.dense for layer in layers], position=0) | |
| for split in ("train", "validation", "test"): | |
| p = REPO / "data" / "features" / name / f"predictions_{split}.parquet" | |
| pdf = pd.read_parquet(p) | |
| idxs = pdf["idx"].tolist() | |
| raw = splits_data[split].reset_index(drop=True) | |
| raw_m = raw.loc[raw["idx"].isin(idxs)].set_index("idx").loc[idxs].reset_index() | |
| loader = _build_dataloader(raw_m, tokenizer, cfg["data"]["text_col"], | |
| cfg["data"]["label_col"], cfg["model"]["max_length"], | |
| cfg["inference"]["batch_size"]) | |
| Ms, preds = [], [] | |
| t0 = time.time() | |
| for batch in loader: | |
| o = model(input_ids=batch["input_ids"].to(device), | |
| attention_mask=batch["attention_mask"].to(device)) | |
| Ms.append(cap.stack().astype(np.float16)); preds.append(o.logits.argmax(-1).cpu().numpy()) | |
| M = np.concatenate(Ms); pred = np.concatenate(preds) | |
| agree = float((pred == pdf["pred"].values).mean()) | |
| print(f" [{split}] n={len(M)} M={M.shape} prediction agreement {agree:.4f} " | |
| f"{time.time() - t0:.0f}s", flush=True) | |
| if agree < 0.98: | |
| raise RuntimeError(f"{name} {split}: row order differs from the cached predictions") | |
| write_features(name, split, M, np.asarray(idxs), REPO / "data") | |
| cap.close() | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | |
| ap.add_argument("--config", required=True) | |
| ap.add_argument("--force", action="store_true") | |
| a = ap.parse_args() | |
| cfg = load_config(a.config) | |
| name = cfg["run_name"] | |
| if (REPO / "data" / "features" / name / "mlppath_test.npz").exists() and not a.force: | |
| print(f"[{name}] mlppath features already present"); return | |
| seed_everything(int(cfg.get("seed", 0))) | |
| (decoder if is_decoder(name) else encoder)(cfg, name, a) | |
| print(f"[{name}] DONE") | |
| if __name__ == "__main__": | |
| main() | |