Disentangling Polysemantic Superposition: TopK & JumpReLU Sparse Autoencoders (SAEs) and Dead-Latent Resurrection
Why is a single neuron inside a Transformer MLP or residual stream $x \in \mathbb{R}^d$ almost always polysemantic – firing simultaneously on unrelated concepts like Arabic script, DNA sequences, and HTTP headers? As formalized in Toy Models of Superposition (Elhage et al., 2022), a $d$-dimensional space can pack $M \gg d$ almost-orthogonal unit vectors ($\le \exp(c\, d\,\epsilon^2)$ vectors with pairwise inner product $|\langle f_i, f_j \rangle| \le \epsilon$) provided the underlying features activate sparsely.
Sparse Autoencoders (SAEs) reverse-engineer this compressed representation by projecting $x \in \mathbb{R}^d$ into an overcomplete dictionary $z \in \mathbb{R}_{\ge 0}^M$ ($M = 8d \text{ to } 64d$). However, first-generation ReLU SAEs trained with an $\ell_1$ penalty $\mathcal{L} = \|x - \hat{x}\|_2^2 + \lambda \|z\|_1$ suffer from systematic activation shrinkage – pushing all active feature magnitudes downward by $\lambda$. Modern frontier interpretability stacks have converged on TopK SAEs (Gao et al., 2024, arXiv:2406.04093) and JumpReLU SAEs (Rajamanoharan et al., 2024, arXiv:2407.14435) that enforce $\ell_0$ sparsity directly without shrinking active feature amplitudes.
0. Why $L_1$ Shrinks Features – and How TopK + AuxK Eliminates Shrinkage & Dead Latents
Given centered residual activations $x - b_{\text{pre}} \in \mathbb{R}^d$, encoder weights $W_{\text{enc}} \in \mathbb{R}^{M \times d}$, and unit-norm decoder columns $W_{\text{dec}} \in \mathbb{R}^{d \times M}$ ($\|W_{\text{dec}}[:, i]\|_2 = 1$), compare the proximal operator of an $L_1$ penalty against hard TopK selection:
In an $L_1$ SAE, minimizing $\|x - d_i z_i\|_2^2 + \lambda z_i$ for a single unit-norm atom yields $z_i^* = \max(0, \langle x, d_i \rangle - \lambda/2)$, under-predicting the true feature coefficient by $\lambda/2$. TopK zeroes out the $M - k$ smallest pre-activations while leaving the top $k$ winners completely unshrunk ($\lambda = 0$)!
F.normalize(W_dec, dim=0) after optimizer.step() corrupts Adam's running second moment $v_t$ along the radial direction – always subtract the radial gradient component $g_i \leftarrow g_i - \langle g_i, d_i \rangle d_i$ before calling optimizer.step()!
(2) Initializing $W_{\text{dec}}$ Independently of $W_{\text{enc}}^\top$: Initialize $W_{\text{dec}} = W_{\text{enc}}^\top$ (with unit-norm columns) and subtract the dataset geometric median $b_{\text{pre}}$ before encoding; otherwise 60%+ of latents die in the first 500 steps.
1. Runnable PyTorch Reference: TopK SAE with Tangent Gradient Projection & AuxK Loss
The self-contained PyTorch script below verifies zero activation shrinkage in TopK selection and implements the exact Riemannian tangent gradient projection and AuxK dead-latent residual loss:
💻 Python: TopK Sparse Autoencoder with AuxK Dead-Latent Revival & Tangent ProjectionPyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
class TopKSparseAutoencoder(nn.Module):
"""TopK + AuxK Sparse Autoencoder (Gao et al., arXiv:2406.04093)."""
def __init__(self, d_model: int, n_latents: int, k_active: int, k_aux: int = 8) -> None:
super().__init__()
self.k_active = k_active
self.k_aux = k_aux
self.b_pre = nn.Parameter(torch.zeros(d_model))
self.b_enc = nn.Parameter(torch.zeros(n_latents))
self.W_enc = nn.Parameter(torch.randn(n_latents, d_model) / (d_model ** 0.5))
# Tied transpose initialization with unit-norm decoder columns [d_model, n_latents]
self.W_dec = nn.Parameter(F.normalize(self.W_enc.data.T.clone(), dim=0))
def forward(self, x: torch.Tensor, dead_mask: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
# x: [B, d_model], dead_mask: [n_latents] boolean mask of dormant features
x_cent = x - self.b_pre
pre_act = F.relu(x_cent @ self.W_enc.T + self.b_enc) # [B, n_latents]
# Primary TopK selection (zero shrinkage on active features!)
vals, idx = torch.topk(pre_act, k=self.k_active, dim=-1)
z_topk = torch.zeros_like(pre_act).scatter_(-1, idx, vals)
x_hat = z_topk @ self.W_dec.T + self.b_pre
mse_loss = (x - x_hat).pow(2).mean()
# AuxK loss: reconstruct detached residual error using top-k_aux dead latents
residual = (x - x_hat).detach()
dead_acts = pre_act * dead_mask.to(pre_act.dtype)
aux_vals, aux_idx = torch.topk(dead_acts, k=min(self.k_aux, dead_acts.size(-1)), dim=-1)
z_aux = torch.zeros_like(pre_act).scatter_(-1, aux_idx, aux_vals)
aux_loss = (residual - z_aux @ self.W_dec.T).pow(2).mean()
return mse_loss + (1.0 / 32.0) * aux_loss, z_topk
@torch.no_grad()
def project_decoder_weights_and_grads(self) -> None:
"""Project W_dec columns to unit sphere and remove radial gradient component before Adam step."""
self.W_dec.data = F.normalize(self.W_dec.data, dim=0)
if self.W_dec.grad is not None:
radial_proj = (self.W_dec.grad * self.W_dec.data).sum(dim=0, keepdim=True)
self.W_dec.grad.sub_(radial_proj * self.W_dec.data)
if __name__ == "__main__":
torch.manual_seed(42)
sae = TopKSparseAutoencoder(d_model=16, n_latents=64, k_active=4, k_aux=8)
x_batch = torch.randn(8, 16)
dead_mask = torch.zeros(64, dtype=torch.bool)
dead_mask[48:] = True # Mark last 16 latents as dormant to test AuxK gradient flow
loss, z_out = sae(x_batch, dead_mask)
loss.backward()
sae.project_decoder_weights_and_grads()
radial_ip = (sae.W_dec.grad * sae.W_dec.data).sum(dim=0).abs().max().item()
dead_grad_norm = sae.W_enc.grad[48:].norm().item()
print(f"[PASS] Active L0 Sparsity per Token : {(z_out > 0).float().sum(dim=-1).mean().item():.1f} (Exact k=4)")
print(f"[PASS] Decoder Tangent Grad Orthogonality Err: {radial_ip:.2e}")
print(f"[PASS] AuxK Revived Dormant Encoder Grad Norm: {dead_grad_norm:.4f} (>0 prevents dead latents!)")
# Output:
# [PASS] Active L0 Sparsity per Token : 4.0 (Exact k=4)
# [PASS] Decoder Tangent Grad Orthogonality Err: 3.35e-08
# [PASS] AuxK Revived Dormant Encoder Grad Norm: 0.2694 (>0 prevents dead latents!)
2. Sparse Dictionary Architectures: Head-to-Head
| Architecture | ReLU + $L_1$ SAE | Gated SAE | TopK + AuxK SAE (Gao et al., 2024) |
|---|---|---|---|
| Sparsity Mechanism | Soft $\ell_1$ penalty $\lambda \|z\|_1$ | Separate Heaviside gate + magnitude path | Exact hard $\mathrm{TopK}$ projection ($\ell_0 \equiv k$) |
| Activation Shrinkage | Severe ($\Delta z = -\lambda/2$) | Eliminated via decoupled magnitude branch | Zero shrinkage with $1.5\times$ fewer encoder params |
| Dead Feature Rate at 131k Width | $30\%\text{–}70\%$ without resampling | $15\%\text{–}35\%$ | $\lt 2\%$ via continuous AuxK residual reconstruction |