clsa-code / src /clsa /transcoder /topk_sae.py
fahadhafeezofficial's picture
Upload folder using huggingface_hub
fd5366a verified
Raw History Blame Contribute Delete
4.88 kB
# Copyright (c) 2026 CLSA contributors
# SPDX-License-Identifier: MIT
"""TopK sparse autoencoder over trajectory activations.
Gemma Scope SAEs are the preferred substrate when a Gemma-class backbone with
matching SAE weights is available. On CPU-only hardware the 2B Gemma model does
not fit the time budget, so this module trains its own TopK transcoder on the
agent's own trajectory activations. The interface is the same, and a Gemma Scope
adapter can be dropped in (see transcoder/gemma_scope_adapter.py).
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class TopKSAE(nn.Module):
"""Sparse transcoder: x -> TopK(z) -> x_hat, with unit-norm dictionary."""
def __init__(self, d_in: int, n_features: int = 64, k: int = 8):
super().__init__()
self.d_in = d_in
self.n_features = n_features
self.k = k
self.enc = nn.Linear(d_in, n_features)
self.dec = nn.Linear(n_features, d_in, bias=False)
self.b_dec = nn.Parameter(torch.zeros(d_in))
with torch.no_grad():
self.dec.weight.data = F.normalize(self.dec.weight.data, dim=1)
def encode(self, x: torch.Tensor) -> torch.Tensor:
pre = self.enc(x - self.b_dec)
k = min(self.k, self.n_features)
vals, idx = pre.topk(k, dim=-1)
z = torch.zeros_like(pre)
z.scatter_(-1, idx, F.relu(vals))
return z
def decode(self, z: torch.Tensor) -> torch.Tensor:
w = F.normalize(self.dec.weight.data, dim=1)
return F.linear(z, w) + self.b_dec
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
z = self.encode(x)
return self.decode(z), z
def train_sae(
x: np.ndarray,
n_features: int = 64,
k: int = 8,
epochs: int = 400,
lr: float = 3e-3,
l1: float = 1e-3,
seed: int = 0,
batch_size: int = 256,
verbose: bool = False,
) -> tuple[TopKSAE, dict]:
"""Train the transcoder; returns the model and a metrics dict."""
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
X = torch.as_tensor(x, dtype=torch.float32)
X = X - X.mean(dim=0, keepdim=True)
scale = X.std().clamp_min(1e-6)
X = X / scale
model = TopKSAE(X.shape[1], n_features=n_features, k=k)
opt = torch.optim.Adam(model.parameters(), lr=lr)
n = X.shape[0]
history = []
for epoch in range(epochs):
perm = torch.as_tensor(rng.permutation(n))
total = 0.0
for i in range(0, n, batch_size):
batch = X[perm[i : i + batch_size]]
x_hat, z = model(batch)
mse = F.mse_loss(x_hat, batch)
sparsity = l1 * z.abs().mean()
loss = mse + sparsity
opt.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
with torch.no_grad():
model.dec.weight.data = F.normalize(model.dec.weight.data, dim=1)
total += float(mse) * batch.shape[0]
history.append(total / n)
if verbose and epoch % 50 == 0:
print(f"epoch {epoch} mse {history[-1]:.4f}")
with torch.no_grad():
x_hat, z = model(X)
mse = float(F.mse_loss(x_hat, X))
var = float(X.var())
l0 = float((z > 0).float().sum(dim=1).mean())
dead = int(((z > 0).float().sum(dim=0) == 0).sum())
metrics = {
"mse": mse,
"fvu": mse / max(var, 1e-9),
"l0": l0,
"dead_features": dead,
"n_features": n_features,
"k": k,
"n_train": int(n),
"final_curve": history[-5:],
"scale": float(scale),
"mean": [float(v) for v in X.mean(dim=0)[:4]],
}
return model, metrics
def save_sae(model: TopKSAE, path: str | Path, meta: dict | None = None) -> None:
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
torch.save(
{
"state_dict": model.state_dict(),
"d_in": model.d_in,
"n_features": model.n_features,
"k": model.k,
"meta": meta or {},
},
path,
)
if meta is not None:
with open(path.with_suffix(".json"), "w", encoding="utf-8") as fh:
json.dump(meta, fh, indent=2)
def load_sae(path: str | Path) -> tuple[TopKSAE, dict]:
blob = torch.load(path, map_location="cpu", weights_only=False)
model = TopKSAE(blob["d_in"], blob["n_features"], blob["k"])
model.load_state_dict(blob["state_dict"])
model.eval()
return model, blob.get("meta", {})
@torch.no_grad()
def encode_np(model: TopKSAE, x: np.ndarray, scale: float = 1.0) -> np.ndarray:
X = torch.as_tensor(x, dtype=torch.float32) / max(scale, 1e-9)
return model.encode(X).numpy()