"""Residual-stream activation extraction (pipeline stage M1 — the only big GPU cost). For each (model, dataset, distribution) we run a single forward pass over the texts with `output_hidden_states=True`, masked-mean-pool (or last-token-pool) each layer, cast to float16, and write one cache shard. Everything downstream reads the cache. Memory discipline (24 GB 4090): * model loaded in float16 * inference under torch.no_grad() * per-batch hidden states pooled and moved to CPU immediately (we never keep [B,L,T,H]) * batch_size tuned per model in config (drop for pythia-1.4b) """ from __future__ import annotations import numpy as np import cache from config import EXTRACT, MODELS, ExtractConfig def _pool(hidden_stack, attention_mask, pooling: str): """hidden_stack: [B, L+1, T, H] ; attention_mask: [B, T] -> [B, L+1, H].""" import torch if pooling == "mean": mask = attention_mask[:, None, :, None] # [B,1,T,1] summed = (hidden_stack * mask).sum(dim=2) # [B,L+1,H] counts = mask.sum(dim=2).clamp(min=1) # [B,1,H]->broadcast return summed / counts if pooling == "last": # index of last non-pad token per example lengths = attention_mask.sum(dim=1).long() - 1 # [B] idx = lengths[:, None, None, None].expand(-1, hidden_stack.size(1), 1, hidden_stack.size(3)) return torch.gather(hidden_stack, 2, idx).squeeze(2) # [B,L+1,H] raise ValueError(f"unknown pooling {pooling}") def extract_texts(model_key: str, texts: list[str], cfg: ExtractConfig) -> np.ndarray: """Return pooled activations [N, L+1, H] (float16) for the given texts.""" import torch from transformers import AutoModel, AutoTokenizer spec = MODELS[model_key] tok = AutoTokenizer.from_pretrained(spec.hf_name) if tok.pad_token is None: tok.pad_token = tok.eos_token dtype = getattr(torch, cfg.dtype) device = cfg.device if torch.cuda.is_available() else "cpu" model = AutoModel.from_pretrained( spec.hf_name, torch_dtype=dtype, output_hidden_states=True ).to(device).eval() chunks = [] with torch.no_grad(): for i in range(0, len(texts), cfg.batch_size): batch = texts[i:i + cfg.batch_size] enc = tok(batch, return_tensors="pt", padding=True, truncation=True, max_length=cfg.max_length).to(device) out = model(**enc) hs = torch.stack(out.hidden_states, dim=1) # [B, L+1, T, H] pooled = _pool(hs, enc.attention_mask, cfg.pooling) # [B, L+1, H] chunks.append(pooled.to(torch.float16).cpu().numpy()) del out, hs, pooled, enc del model if torch.cuda.is_available(): torch.cuda.empty_cache() return np.concatenate(chunks, axis=0) def extract_shard(model_key: str, dataset_key: str, distribution: str, record: dict, cfg: ExtractConfig = EXTRACT, overwrite: bool = False): """Extract + cache one shard. `record` = {texts, labels, ids}.""" if len(record["texts"]) == 0: return None # empty record (e.g. paraphrase fully filtered out) -> skip, don't crash if cache.exists(model_key, dataset_key, distribution) and not overwrite: return cache.shard_dir(model_key, dataset_key, distribution) acts = extract_texts(model_key, record["texts"], cfg) return cache.save_shard(model_key, dataset_key, distribution, acts, record["labels"], record["ids"], cfg.pooling)