File size: 7,171 Bytes
55d72e6 3db31c5 55d72e6 3db31c5 55d72e6 3db31c5 55d72e6 | 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 | """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()
|