Datasets:
Download selection/count_fires.py from AmiriHayes/sae_token_programs: direct link, hf CLI and curl.
- Browser
- Download file 9.08 kB
-
https://huggingface.co/datasets/AmiriHayes/sae_token_programs/resolve/main/selection/count_fires.py
- Command line
-
hf download hf://datasets/AmiriHayes/sae_token_programs/selection/count_fires.py
-
curl -L -o count_fires.py https://huggingface.co/datasets/AmiriHayes/sae_token_programs/resolve/main/selection/count_fires.py
9.08 kB
| """Count per-(feature, token-string) firings for all 13 SAE layers over a large | |
| corpus, WITHOUT ever materialising an activation store. | |
| Why counting and not storing: at 36.8M read positions the full threshold-free | |
| store would hold ~2.8 billion nonzeros (~22 GB per layer). Token-only programs | |
| need only a contingency table -- how often each feature fires on each decoded | |
| string -- which is four orders of magnitude smaller. So we accumulate that | |
| directly in one forward pass. | |
| Keys are CANONICAL DECODED STRINGS, not token ids, because 255 GPT-2 ids decode | |
| to the same replacement character and a program can only test what it can see. | |
| This matches the convention used by the shipped programs exactly. | |
| Memory: a running (key -> count) table per layer, flushed and merged when the | |
| pending buffer grows. Peak is bounded by the number of DISTINCT (feature, | |
| string) pairs per layer, not by the number of firing events. | |
| python count_fires.py --limit 5000 # pilot | |
| python count_fires.py # full corpus | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, sys, time | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| HERE = Path(__file__).resolve().parent | |
| ROOT = HERE.parent | |
| for p in (ROOT / "lib", ROOT / "eda_phase0", ROOT): | |
| sys.path.insert(0, str(p)) | |
| import config as C | |
| import sae_synthesis as S | |
| THR = 0.1 | |
| FLUSH = 20_000_000 # merge pending keys once the buffer reaches this | |
| SPILL_PAIRS = 40_000_000 # spill a layer to disk once its table exceeds this | |
| class LayerCounter: | |
| """Running (feature*NS + string_id) -> count, EXACT, spilled to disk. | |
| The full corpus implies ~2.4 billion distinct (feature, string) pairs across | |
| 13 layers -- about 28 GB, well past RAM. So each layer keeps a bounded | |
| in-memory table and spills a sorted shard to disk whenever it grows past | |
| SPILL_PAIRS; the shards are k-way merged at the end. Nothing is pruned or | |
| approximated: a pair seen twice in different shards is summed correctly. | |
| """ | |
| def __init__(self, n_strings: int, layer: int, tmp: Path): | |
| self.ns, self.layer, self.tmp = n_strings, layer, tmp | |
| self.keys = np.zeros(0, dtype=np.int64) | |
| self.cnt = np.zeros(0, dtype=np.int64) | |
| self.buf: list[np.ndarray] = [] | |
| self.pending = 0 | |
| self.shards: list[Path] = [] | |
| def add(self, feat: np.ndarray, sid: np.ndarray) -> None: | |
| self.buf.append(feat.astype(np.int64) * self.ns + sid.astype(np.int64)) | |
| self.pending += len(feat) | |
| if self.pending >= FLUSH: | |
| self.merge() | |
| if len(self.keys) >= SPILL_PAIRS: | |
| self.spill() | |
| def _combine(k1, c1, k2, c2): | |
| allk = np.concatenate([k1, k2]) | |
| allc = np.concatenate([c1, c2]) | |
| o = np.argsort(allk, kind="stable") | |
| allk, allc = allk[o], allc[o] | |
| first = np.concatenate([[True], allk[1:] != allk[:-1]]) | |
| return allk[first], np.add.reduceat(allc, np.flatnonzero(first)) | |
| def merge(self) -> None: | |
| if not self.buf: | |
| return | |
| k, c = np.unique(np.concatenate(self.buf), return_counts=True) | |
| self.buf, self.pending = [], 0 | |
| if len(self.keys) == 0: | |
| self.keys, self.cnt = k, c.astype(np.int64) | |
| else: | |
| self.keys, self.cnt = self._combine(self.keys, self.cnt, k, | |
| c.astype(np.int64)) | |
| def spill(self) -> None: | |
| p = self.tmp / f"L{self.layer:02d}_shard{len(self.shards):03d}.npz" | |
| np.savez(p, keys=self.keys, cnt=self.cnt) | |
| self.shards.append(p) | |
| self.keys = np.zeros(0, dtype=np.int64) | |
| self.cnt = np.zeros(0, dtype=np.int64) | |
| def finalize(self, n_features: int, block: int = 2048, min_count: int = 1): | |
| """Exact k-way merge, done in FEATURE BLOCKS so memory stays bounded. | |
| Keys are feature*NS + string_id, so a feature range is a contiguous key | |
| range and every shard's slice for it is found by binary search. A naive | |
| whole-table merge of the deepest layer would peak near 16 GB; this peaks | |
| at one block's worth. | |
| min_count is applied only AFTER every shard has been summed, so it is a | |
| decision about what to keep, never an approximation of the count. | |
| """ | |
| self.merge() | |
| if self.keys.size: | |
| self.spill() | |
| loaded = [np.load(p) for p in self.shards] | |
| parts_k, parts_c = [], [] | |
| for f0 in range(0, n_features, block): | |
| lo, hi = f0 * self.ns, min(f0 + block, n_features) * self.ns | |
| bk = np.zeros(0, dtype=np.int64); bc = np.zeros(0, dtype=np.int64) | |
| for z in loaded: | |
| zk = z["keys"] | |
| i0, i1 = np.searchsorted(zk, [lo, hi]) | |
| if i1 > i0: | |
| bk, bc = self._combine(bk, bc, zk[i0:i1], | |
| z["cnt"][i0:i1].astype(np.int64)) | |
| if bk.size: | |
| if min_count > 1: | |
| m = bc >= min_count | |
| bk, bc = bk[m], bc[m] | |
| parts_k.append(bk); parts_c.append(bc) | |
| for z in loaded: | |
| z.close() | |
| for p in self.shards: | |
| p.unlink() | |
| self.shards = [] | |
| self.keys = np.concatenate(parts_k) if parts_k else np.zeros(0, np.int64) | |
| self.cnt = np.concatenate(parts_c) if parts_c else np.zeros(0, np.int64) | |
| return self.keys, self.cnt | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--limit", type=int, default=0, help="pilot on N sequences") | |
| ap.add_argument("--batch", type=int, default=48) | |
| ap.add_argument("--layers", type=int, nargs="*", default=list(range(13))) | |
| ap.add_argument("--out", default=None) | |
| a = ap.parse_args() | |
| vocab = np.load(ROOT / "layer_plots" / "vocab_strings.npy", allow_pickle=True) | |
| uniq, sid_of_id = np.unique(vocab, return_inverse=True) | |
| NS = len(uniq) | |
| tokens = np.load(HERE / "corpus_300k.npz")["tokens"] | |
| if a.limit: | |
| tokens = tokens[:a.limit] | |
| n_seq, seq_len = tokens.shape | |
| first = C.FIRST_READ_POSITION | |
| n_read = seq_len - first | |
| print(f"{n_seq:,} sequences x {n_read} read positions = " | |
| f"{n_seq * n_read:,} positions; {NS:,} distinct strings", flush=True) | |
| dev = "mps" if torch.backends.mps.is_available() else "cpu" | |
| from transformer_lens import HookedTransformer | |
| from sae_lens import SAE | |
| model = HookedTransformer.from_pretrained("gpt2-small", device=dev) | |
| model.eval() | |
| saes = {} | |
| for L in a.layers: | |
| sae, _, _ = SAE.from_pretrained(release="gpt2-small-res-jb", | |
| sae_id=S.HOOKS[L].replace("blocks.", "blocks."), | |
| device=dev) | |
| saes[L] = (sae.W_enc.detach().float(), sae.b_enc.detach().float(), | |
| sae.b_dec.detach().float()) | |
| print(f"device {dev}; {len(saes)} SAEs loaded", flush=True) | |
| tmp = HERE / "shards"; tmp.mkdir(exist_ok=True) | |
| counters = {L: LayerCounter(NS, L, tmp) for L in a.layers} | |
| occ = np.zeros(NS, dtype=np.int64) | |
| hooks = [S.HOOKS[L] for L in a.layers] | |
| t0 = time.time() | |
| for b0 in range(0, n_seq, a.batch): | |
| chunk = tokens[b0:b0 + a.batch] | |
| ids = torch.from_numpy(chunk.astype(np.int64)).to(dev) | |
| with torch.no_grad(): | |
| _, cache = model.run_with_cache(ids, names_filter=hooks, | |
| return_type=None) | |
| sidx = sid_of_id[chunk[:, first:]].ravel() | |
| np.add.at(occ, sidx, 1) | |
| for L in a.layers: | |
| resid = cache[S.HOOKS[L]][:, first:, :].reshape(-1, model.cfg.d_model) | |
| W, be, bd = saes[L] | |
| acts = torch.relu((resid - bd) @ W + be) | |
| fpos, ffeat = torch.nonzero(acts > THR, as_tuple=True) | |
| if len(fpos): | |
| counters[L].add(ffeat.cpu().numpy(), sidx[fpos.cpu().numpy()]) | |
| del cache | |
| done = min(b0 + a.batch, n_seq) | |
| if (b0 // a.batch) % 50 == 0 or done == n_seq: | |
| el = time.time() - t0 | |
| rate = done / max(el, 1e-9) | |
| print(f" {done:,}/{n_seq:,} seqs {el/60:.1f} min " | |
| f"{rate:.0f} seq/s eta {max(n_seq-done,0)/max(rate,1e-9)/60:.0f} min", | |
| flush=True) | |
| out = Path(a.out) if a.out else (HERE / ("counts_pilot.npz" if a.limit | |
| else "counts_300k.npz")) | |
| saved = {"strings": uniq, "occ": occ, "n_seq": n_seq, "n_read": n_read, | |
| "threshold": THR} | |
| for L in a.layers: | |
| k, c = counters[L].finalize(n_features=24576) | |
| saved[f"keys_{L}"] = k | |
| saved[f"cnt_{L}"] = c.astype(np.int32) | |
| print(f" layer {L}: {len(k):,} distinct (feature,string) pairs, " | |
| f"{int(c.sum()):,} firings", flush=True) | |
| del counters[L].keys, counters[L].cnt | |
| np.savez(out, **saved) | |
| print(f"\nwrote {out} ({out.stat().st_size/1e9:.2f} GB) " | |
| f"total {(time.time()-t0)/60:.1f} min") | |
| if __name__ == "__main__": | |
| main() | |