paper_extraction / scripts /07_extract_layer_states.py
zaaabik's picture
Add files using upload-large-folder tool
3db31c5 verified
Raw History Blame Contribute Delete
7.17 kB
"""Cache the per-layer [CLS] states, the input every cross-layer analysis needs.
Stage 1 keeps only three depths (``cls_begin``/``cls_mid``/``cls_last``), and
Earlier extractors built the full ``(N, L+1, D)`` stack in memory and threw
it away once the 25 scalars are out. Three of the revision experiments --
multilayer Mahalanobis, the layer-wise correlation/AUROC diagnostic, and the
normalization ablation -- need every layer, so they would each pay for their own
encoder pass. This writes the stack once.
Layout, chosen so consumers can memory-map instead of loading a whole split:
data/layer_states/<cfg>/states_<split>.npy (N, L+1, D) float16
data/layer_states/<cfg>/meta_<split>.npz idx, label, n_layers, dim
Row order matches ``predictions_<split>.parquet``, exactly as
the prediction parquet orders it, so ``idx`` aligns with every existing feature
file without a join.
float16 halves the footprint and is well inside the precision these analyses
need -- they standardize per layer before use, and the states themselves come
from a bf16 forward pass. Consumers cast to float32 per layer.
python extraction/scripts/07_extract_layer_states.py \
--config extraction/configs/roberta_cola.yaml
"""
from __future__ import annotations
import argparse
import sys
import time
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from tqdm import tqdm
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from src.utils import load_config, seed_everything, device_from_cfg # noqa: E402
from src.load_data import load_splits # noqa: E402
from src.load_model import load_classification_model, move # noqa: E402
from src.extract_attention import _build_dataloader # noqa: E402
REPO = ROOT.parent
sys.path.insert(0, str(REPO))
from cct_reproduce.grids import is_decoder # noqa: E402
@torch.no_grad()
def cls_per_layer(model, loader, device):
"""(N, L+1, D) float16 [CLS] stack, layer 0 being the embedding output."""
out, labels = [], []
for batch in tqdm(loader, desc="cls-states", leave=False):
ids = batch["input_ids"].to(device)
att = batch["attention_mask"].to(device)
o = model(input_ids=ids, attention_mask=att, output_hidden_states=True)
hs = torch.stack([h[:, 0, :] for h in o.hidden_states], dim=1)
out.append(hs.half().cpu())
labels.append(batch["label"])
return torch.cat(out), torch.cat(labels)
def out_dir(cfg_name: str) -> Path:
return REPO / "data" / "layer_states" / cfg_name
def load_states(cfg_name: str, split: str, mmap: bool = True):
"""(states, idx, label) for one split. states is a float16 memmap by default.
The public read side of this cache; every consumer goes through it so the
layout is defined in one place.
"""
d = out_dir(cfg_name)
p = d / f"states_{split}.npy"
if not p.exists():
raise FileNotFoundError(
f"no cached layer states at {p}. Run\n"
f" python extraction/scripts/07_extract_layer_states.py "
f"--config extraction/configs/{cfg_name}.yaml")
states = np.load(p, mmap_mode="r" if mmap else None)
meta = np.load(d / f"meta_{split}.npz")
if is_decoder(cfg_name):
states = standardize_layers(states)
return states, meta["idx"], meta["label"]
def standardize_layers(states):
"""Every layer's state standardised per sample over the hidden dimension.
A pre-LN decoder leaves its residual stream unnormalised: the state norm
grows by an order of magnitude across the depth and a Mahalanobis
reference fitted on it measures that norm rather than the direction. The
encoders' post-LN layers emit standardised states already, so the same
transform (zero mean, unit variance per sample, as the final norm applies
before the head) puts the decoder cache on the same footing. Applied on
read by every consumer of the cache; nothing is written.
"""
out = np.empty(states.shape, np.float16)
for a in range(0, states.shape[0], 1024):
x = np.asarray(states[a:a + 1024], dtype=np.float32)
x = x - x.mean(-1, keepdims=True)
x = x / (x.std(-1, keepdims=True) + 1e-6)
out[a:a + 1024] = x.astype(np.float16)
return out
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--config", required=True)
ap.add_argument("--splits", nargs="+", default=["train", "validation", "test"])
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
cfg = load_config(args.config)
seed_everything(cfg["seed"])
cfg_name = cfg["run_name"]
dest = out_dir(cfg_name)
dest.mkdir(parents=True, exist_ok=True)
todo = [s for s in args.splits
if args.force or not (dest / f"states_{s}.npy").exists()]
if not todo:
print(f"[{cfg_name}] layer states already cached for "
f"{', '.join(args.splits)}")
return
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)
model.eval()
def predictions(split):
p = Path(cfg["paths"]["output_dir"]) / f"predictions_{split}.parquet"
if p.exists():
return pd.read_parquet(p)
staged = REPO / "data" / "features" / cfg_name / f"predictions_{split}.parquet"
if staged.exists():
return pd.read_parquet(staged)
raise FileNotFoundError(
f"no predictions for split '{split}': looked in {p} and {staged}")
for split in todo:
t0 = time.time()
# Same row order as the prediction parquet's idx sequence,
# reindexed out of the raw split. Anything else silently misaligns
# these states with every other feature file.
df = predictions(split)
idxs = df["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"])
states, labels = cls_per_layer(model, loader, device)
arr = states.numpy()
np.save(dest / f"states_{split}.npy", arr)
np.savez(dest / f"meta_{split}.npz",
idx=np.asarray(idxs, dtype=np.int64),
label=labels.numpy().astype(np.int64),
n_layers=np.int64(arr.shape[1]), dim=np.int64(arr.shape[2]))
print(f" [{split}] {arr.shape} float16 "
f"{arr.nbytes / 1e9:.2f} GB ({time.time() - t0:.0f}s)")
print(f"[{cfg_name}] wrote {dest.relative_to(REPO)}")
if __name__ == "__main__":
main()