File size: 8,017 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
"""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()


@torch.no_grad()
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()


@torch.no_grad()
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()