"""Activation-shard cache. One shard = activations for a single (model, dataset, distribution) triple. Stored as a directory of `.npy` files so that the (potentially multi-GB) activation tensor can be memory-mapped and sliced by layer without loading everything into RAM. Layout: cache//// acts.npy float16 [N, L+1, H] (L+1 = embeddings + L transformer layers) labels.npy int64 [N] ids.npy int64 [N] (stable example ids, for cross-shard alignment) meta.json {model, dataset, distribution, pooling, n, n_layers, hidden, dtype} """ from __future__ import annotations import json from pathlib import Path import numpy as np from config import CACHE_DIR def shard_dir(model_key: str, dataset_key: str, distribution: str) -> Path: return CACHE_DIR / model_key / dataset_key / distribution def exists(model_key: str, dataset_key: str, distribution: str) -> bool: d = shard_dir(model_key, dataset_key, distribution) return (d / "acts.npy").exists() and (d / "meta.json").exists() def save_shard( model_key: str, dataset_key: str, distribution: str, acts: np.ndarray, # [N, L+1, H] float16 labels: np.ndarray, # [N] ids: np.ndarray, # [N] pooling: str, ) -> Path: d = shard_dir(model_key, dataset_key, distribution) d.mkdir(parents=True, exist_ok=True) acts = np.ascontiguousarray(acts.astype(np.float16)) np.save(d / "acts.npy", acts) np.save(d / "labels.npy", labels.astype(np.int64)) np.save(d / "ids.npy", ids.astype(np.int64)) meta = { "model": model_key, "dataset": dataset_key, "distribution": distribution, "pooling": pooling, "n": int(acts.shape[0]), "n_layers": int(acts.shape[1]), # includes embedding layer "hidden": int(acts.shape[2]), "dtype": "float16", } (d / "meta.json").write_text(json.dumps(meta, indent=2)) return d def load_meta(model_key: str, dataset_key: str, distribution: str) -> dict: return json.loads((shard_dir(model_key, dataset_key, distribution) / "meta.json").read_text()) def load_shard( model_key: str, dataset_key: str, distribution: str, layer: int | None = None, mmap: bool = True, ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Return (acts, labels, ids). If `layer` is given, acts is [N, H] for that layer (0 = embeddings, 1..L = layers). Otherwise acts is the full [N, L+1, H] tensor (mmap'd by default — do not mutate). """ d = shard_dir(model_key, dataset_key, distribution) mode = "r" if mmap else None acts = np.load(d / "acts.npy", mmap_mode=mode) labels = np.load(d / "labels.npy") ids = np.load(d / "ids.npy") if layer is not None: acts = np.asarray(acts[:, layer, :], dtype=np.float32) # materialise one layer # sanitise fp16-overflow inf/nan (e.g. Qwen "massive activations") -> finite. # No-op for models without overflow (pythia/gpt2), so existing results are unchanged. if not np.isfinite(acts).all(): acts = np.nan_to_num(acts, nan=0.0, posinf=65504.0, neginf=-65504.0) return acts, labels, ids