Skip to content
Edit this page

muscari.sae

Sparse autoencoders: the Top-K model, its trainers, and the common on-disk format.

Model

TopKSAE

TopKSAE(d_in: int, num_latents: int, k: int)

Bases: TopKObjective

Trainable Top-K SAE.

Parameters:

  • d_in (int) –

    width of the activations being reconstructed.

  • num_latents (int) –

    dictionary size M.

  • k (int) –

    number of latents kept per token.

Shapes

encoder.weight is (num_latents, d_in), encoder.bias is (num_latents,), decoder is (num_latents, d_in) and b_dec is (d_in,).

Raises:

  • ValueError –

    if a size is not positive or k exceeds num_latents.

Source code in src/muscari/sae/model.py
def __init__(self, d_in: int, num_latents: int, k: int) -> None:
    super().__init__()
    if d_in < 1 or num_latents < 1 or k < 1:
        raise ValueError("d_in, num_latents and k must be positive.")
    if k > num_latents:
        raise ValueError(f"k ({k}) cannot exceed num_latents ({num_latents}).")

    self.d_in = d_in
    self.num_latents = num_latents
    self.k = k

    self.encoder = nn.Linear(d_in, num_latents)
    self.decoder = nn.Parameter(torch.empty(num_latents, d_in))
    self.b_dec = nn.Parameter(torch.zeros(d_in))
    self.reset_parameters()

reset_parameters

reset_parameters() -> None

Initialise with unit-norm random directions and a tied, rescaled encoder.

The encoder starts as the transpose of the decoder. It is then scaled by one factor so that random unit-norm inputs are reconstructed with unit norm on average. This follows the public reference implementation of Gao et al., whose authors note that they found no clear evidence that the rescaling helps.

Source code in src/muscari/sae/model.py
@torch.no_grad()
def reset_parameters(self) -> None:
    """Initialise with unit-norm random directions and a tied, rescaled encoder.

    The encoder starts as the transpose of the decoder. It is then scaled by one factor so
    that random unit-norm inputs are reconstructed with unit norm on average. This follows
    the public reference implementation of Gao et al., whose authors note that they found
    no clear evidence that the rescaling helps.
    """
    directions = F.normalize(torch.randn(self.num_latents, self.d_in), dim=-1)
    self.decoder.copy_(directions)
    self.encoder.weight.copy_(directions)
    self.encoder.bias.zero_()
    self.b_dec.zero_()

    probes = F.normalize(torch.randn(256, self.d_in), dim=-1).to(self.decoder)
    recon_norm = self(probes).norm(dim=-1).mean()
    self.encoder.weight.div_(recon_norm.clamp_min(1e-8))

init_b_dec

init_b_dec(
    sample: Tensor, *, max_rows: int = 32768
) -> None

Start b_dec at the geometric median of sample (n, d_in).

The SAE then models deviations from a typical activation. At most max_rows rows are used.

Source code in src/muscari/sae/model.py
@torch.no_grad()
def init_b_dec(self, sample: torch.Tensor, *, max_rows: int = 32_768) -> None:
    """Start ``b_dec`` at the geometric median of ``sample`` ``(n, d_in)``.

    The SAE then models deviations from a typical activation. At most ``max_rows`` rows
    are used.
    """
    median = geometric_median(sample[:max_rows])
    self.b_dec.copy_(median.to(self.b_dec))

encode

encode(x: Tensor) -> tuple[Tensor, Tensor]

Return (values, indices), both (batch, k), for x of shape (batch, d_in).

These are the k largest pre-activations per token after ReLU and the latents they belong to, in no particular order. A value of zero means the latent was selected but did not fire.

Source code in src/muscari/sae/model.py
def encode(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Return ``(values, indices)``, both ``(batch, k)``, for ``x`` of shape ``(batch, d_in)``.

    These are the ``k`` largest pre-activations per token after ReLU and the latents they
    belong to, in no particular order. A value of zero means the latent was selected but
    did not fire.
    """
    values, indices, _, _ = self._select(x)
    return values, indices

decode_sparse

decode_sparse(
    values: Tensor,
    indices: Tensor,
    *,
    add_bias: bool = True,
) -> Tensor

Sum values[b, j] * decoder[indices[b, j]] over j; both inputs are (batch, n).

Source code in src/muscari/sae/model.py
def decode_sparse(self, values: torch.Tensor, indices: torch.Tensor, *, add_bias: bool = True) -> torch.Tensor:
    """Sum ``values[b, j] * decoder[indices[b, j]]`` over ``j``; both inputs are ``(batch, n)``."""
    recon = sparse_decode(values.to(self.decoder.dtype), indices, self.decoder)
    return recon + self.b_dec if add_bias else recon

forward

forward(x: Tensor) -> Tensor

Reconstruct x (batch, d_in).

Source code in src/muscari/sae/model.py
def forward(self, x: torch.Tensor) -> torch.Tensor:
    """Reconstruct ``x`` ``(batch, d_in)``."""
    values, indices = self.encode(x)
    return self.decode_sparse(values, indices)

TopKObjective

Bases: Module

Mixin with the loss and the decoder maintenance of TopKSAE.

loss

loss(
    x: Tensor,
    *,
    dead_mask: Tensor | None = None,
    aux_k: int = 0,
) -> dict[str, Tensor]

Reconstruction loss plus the AuxK term that revives dead latents.

AuxK: the aux_k strongest dead latents try to reconstruct what the live latents missed. The residual is detached, so this term trains only the dead latents and pulls them back towards directions that are still unexplained.

Parameters:

  • x (Tensor) –

    activations (batch, d_in).

  • dead_mask (Tensor | None, default: None ) –

    boolean (num_latents,), true for latents considered dead.

  • aux_k (int, default: 0 ) –

    number of dead latents used by the auxiliary reconstruction; 0 disables it. At most the number of dead latents is used.

Returns:

  • dict[str, Tensor] –

    fvu: batch-normalised reconstruction error (scalar).

  • dict[str, Tensor] –

    aux: auxiliary error, normalised by the variance of the residual (scalar, zero

  • dict[str, Tensor] –

    when there are no dead latents or the residual is degenerate).

  • dict[str, Tensor] –

    values and indices: the selected activations, (batch, k).

Source code in src/muscari/sae/objective.py
def loss(
    self,
    x: torch.Tensor,
    *,
    dead_mask: torch.Tensor | None = None,
    aux_k: int = 0,
) -> dict[str, torch.Tensor]:
    """Reconstruction loss plus the AuxK term that revives dead latents.

    AuxK: the ``aux_k`` strongest *dead* latents try to reconstruct what the live latents
    missed. The residual is detached, so this term trains only the dead latents and pulls
    them back towards directions that are still unexplained.

    Args:
        x: activations ``(batch, d_in)``.
        dead_mask: boolean ``(num_latents,)``, true for latents considered dead.
        aux_k: number of dead latents used by the auxiliary reconstruction; 0 disables it.
            At most the number of dead latents is used.

    Returns:
        ``fvu``: batch-normalised reconstruction error (scalar).
        ``aux``: auxiliary error, normalised by the variance of the residual (scalar, zero
        when there are no dead latents or the residual is degenerate).
        ``values`` and ``indices``: the selected activations, ``(batch, k)``.
    """
    dead_index = None
    if dead_mask is not None and aux_k > 0:
        dead_index = dead_mask.nonzero().squeeze(1)

    values, indices, aux_values, aux_indices = self._select(x, dead_index, aux_k)
    recon = self.decode_sparse(values, indices)
    fvu = normalized_mse(recon, x)

    aux = recon.new_zeros(())
    if dead_index is not None and aux_indices.shape[1] > 0:
        residual = (x - recon).detach()
        aux_recon = self._decode_auxiliary(aux_values, aux_indices, dead_index)
        aux = torch.nan_to_num(normalized_mse(aux_recon, residual), nan=0.0, posinf=0.0)

    return {"fvu": fvu, "aux": aux, "values": values, "indices": indices}

remove_parallel_decoder_grad

remove_parallel_decoder_grad() -> None

Project out the gradient component that would only change a decoder row's norm.

Source code in src/muscari/sae/objective.py
@torch.no_grad()
def remove_parallel_decoder_grad(self) -> None:
    """Project out the gradient component that would only change a decoder row's norm."""
    grad = self.decoder.grad
    if grad is not None:
        grad.sub_((grad * self.decoder).sum(dim=-1, keepdim=True) * self.decoder)

normalize_decoder

normalize_decoder() -> None

Rescale every decoder row to unit norm.

Source code in src/muscari/sae/objective.py
@torch.no_grad()
def normalize_decoder(self) -> None:
    """Rescale every decoder row to unit norm."""
    self.decoder.div_(self.decoder.norm(dim=-1, keepdim=True).clamp_min(1e-8))

sparse_topk

sparse_topk(
    x: Tensor, weight: Tensor, bias: Tensor, k: int
) -> tuple[Tensor, Tensor]

The k largest entries of x @ weight.T + bias per row and the columns they sit in.

x is (batch, d_in) and weight is (num_latents, d_in). The values are returned before any ReLU. Gradients reach x, weight and bias through the selected entries only, so the dense (batch, num_latents) product is never kept for the backward pass.

Source code in src/muscari/sae/encode.py
def sparse_topk(
    x: torch.Tensor,
    weight: torch.Tensor,
    bias: torch.Tensor,
    k: int,
) -> tuple[torch.Tensor, torch.Tensor]:
    """The ``k`` largest entries of ``x @ weight.T + bias`` per row and the columns they sit in.

    ``x`` is ``(batch, d_in)`` and ``weight`` is ``(num_latents, d_in)``. The values are returned
    before any ReLU. Gradients reach ``x``, ``weight`` and ``bias`` through the selected entries
    only, so the dense ``(batch, num_latents)`` product is never kept for the backward pass.
    """
    values, indices, _, _ = _SparseEncode.apply(
        x,
        weight,
        bias,
        x.new_zeros(x.shape[1]),
        torch.empty(0, dtype=torch.long, device=x.device),
        k,
        0,
    )
    return values, indices

normalized_mse

normalized_mse(recon: Tensor, target: Tensor) -> Tensor

Squared error divided by the squared error of predicting the batch mean of target.

For a reconstruction this is the fraction of variance unexplained (FVU) of the batch.

Source code in src/muscari/sae/metrics.py
def normalized_mse(recon: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    """Squared error divided by the squared error of predicting the batch mean of ``target``.

    For a reconstruction this is the fraction of variance unexplained (FVU) of the batch.
    """
    residual = (target - recon).pow(2).sum()
    total = (target - target.mean(dim=0, keepdim=True)).pow(2).sum()
    return residual / total.clamp_min(1e-12)

geometric_median

geometric_median(
    points: Tensor,
    *,
    max_iter: int = 100,
    tol: float = 1e-05,
) -> Tensor

Geometric median of the rows of points (n, d) by Weiszfeld's algorithm.

The geometric median minimises the sum of Euclidean distances to the rows, which makes it less sensitive to a few extreme activations than the mean. Iteration stops when the update is smaller than tol relative to the spread of the data, or after max_iter rounds.

Raises:

  • ValueError –

    if points is not a non-empty matrix.

Source code in src/muscari/sae/metrics.py
@torch.no_grad()
def geometric_median(points: torch.Tensor, *, max_iter: int = 100, tol: float = 1e-5) -> torch.Tensor:
    """Geometric median of the rows of ``points`` ``(n, d)`` by Weiszfeld's algorithm.

    The geometric median minimises the sum of Euclidean distances to the rows, which makes it
    less sensitive to a few extreme activations than the mean. Iteration stops when the update
    is smaller than ``tol`` relative to the spread of the data, or after ``max_iter`` rounds.

    Raises:
        ValueError: if ``points`` is not a non-empty matrix.
    """
    if points.ndim != 2 or points.shape[0] == 0:
        raise ValueError("points must be a non-empty (n, d) tensor.")

    points = points.float()
    median = points.mean(dim=0)
    scale = (points - median).norm(dim=1).mean().clamp_min(1e-12)

    for _ in range(max_iter):
        distances = (points - median).norm(dim=1).clamp_min(1e-8 * scale)
        weights = 1.0 / distances
        updated = (weights.unsqueeze(1) * points).sum(dim=0) / weights.sum()

        converged = (updated - median).norm() <= tol * scale
        median = updated
        if converged:
            break

    return median

Trainers

TopKTrainerConfig dataclass

TopKTrainerConfig(
    num_latents: int = 65536,
    k: int = 16,
    aux_k: int = 256,
    aux_coef: float = 1 / 32,
    dead_after_tokens: int = 10000000,
    lr: float = 0.0005,
    warmup_frac: float = 0.05,
    adam_betas: tuple[float, float] = (0.9, 0.999),
    adam_eps: float = 1e-08,
    total_tokens: int = 1000000000,
    batch_tokens: int = 8192,
    amp: bool = False,
    log_every: int = 100,
    checkpoint_every: int = 0,
    seed: int = 42,
    device: str = "auto",
)

Hyperparameters of TopKTrainer.

Attributes:

  • num_latents (int) –

    dictionary size M.

  • k (int) –

    active latents per token.

  • aux_k (int) –

    dead latents used by the auxiliary reconstruction; 0 disables AuxK.

  • aux_coef (float) –

    weight of the auxiliary loss.

  • dead_after_tokens (int) –

    a latent is dead once it has not fired for this many tokens.

  • lr (float) –

    peak learning rate of Adam.

  • warmup_frac (float) –

    share of the steps spent on linear warmup.

  • adam_betas (tuple[float, float]) –

    Adam (beta1, beta2).

  • adam_eps (float) –

    Adam epsilon.

  • total_tokens (int) –

    training length in tokens; the number of steps is this over batch_tokens.

  • batch_tokens (int) –

    activations per optimisation step.

  • amp (bool) –

    run the SAE forward pass under bfloat16 autocast. Only used on CUDA.

  • log_every (int) –

    steps between log records.

  • checkpoint_every (int) –

    steps between checkpoints, with one more at the end; 0 writes none.

  • seed (int) –

    seed for the SAE initialisation.

  • device (str) –

    "auto" or a device string.

TopKTrainer

TopKTrainer(cfg: TopKTrainerConfig, d_in: int)

Bases: Checkpoints, Fitting

Trains a TopKSAE on batches of activations.

Parameters:

  • cfg (TopKTrainerConfig) –

    hyperparameters.

  • d_in (int) –

    width of the activations.

Attributes:

  • sae –

    the SAE being trained, on device.

  • step –

    optimisation steps taken so far.

  • tokens_seen –

    activations trained on so far.

  • tokens_since_fired –

    per-latent count of tokens since the latent last fired.

  • step_seconds –

    wall-clock time spent in train_step so far.

Source code in src/muscari/sae/trainers/topk.py
def __init__(self, cfg: TopKTrainerConfig, d_in: int) -> None:
    self.cfg = cfg
    self.device = resolve_device(cfg.device)

    torch.manual_seed(cfg.seed)
    self.sae = TopKSAE(d_in, cfg.num_latents, cfg.k).to(self.device)
    self.optimizer = torch.optim.Adam(
        self.sae.parameters(),
        lr=cfg.lr,
        betas=cfg.adam_betas,
        eps=cfg.adam_eps,
    )

    self.tokens_since_fired = torch.zeros(cfg.num_latents, dtype=torch.long, device=self.device)
    self.step = 0
    self.tokens_seen = 0
    self.step_seconds = 0.0

dead_mask

dead_mask() -> Tensor

Boolean (num_latents,) mask of the latents currently considered dead.

Source code in src/muscari/sae/trainers/topk.py
def dead_mask(self) -> torch.Tensor:
    """Boolean ``(num_latents,)`` mask of the latents currently considered dead."""
    return self.tokens_since_fired > self.cfg.dead_after_tokens

unused_frac

unused_frac(window_tokens: int = 10000000) -> float

Share of latents that did not fire during the last window_tokens training tokens.

When fewer tokens have been seen, the window is the whole run. Unlike a count on an evaluation sample, this does not depend on how many tokens are evaluated.

Source code in src/muscari/sae/trainers/topk.py
def unused_frac(self, window_tokens: int = 10_000_000) -> float:
    """Share of latents that did not fire during the last ``window_tokens`` training tokens.

    When fewer tokens have been seen, the window is the whole run. Unlike a count on an
    evaluation sample, this does not depend on how many tokens are evaluated.
    """
    window = min(window_tokens, self.tokens_seen)
    if window == 0:
        return 0.0

    return (self.tokens_since_fired >= window).float().mean().item()

train_step

train_step(x: Tensor) -> dict[str, float]

Take one optimisation step on x (batch, d_in) and return its metrics.

The first step also initialises b_dec from x. dead_frac describes the dictionary before this step; lr is the rate this step used.

Source code in src/muscari/sae/trainers/topk.py
def train_step(self, x: torch.Tensor) -> dict[str, float]:
    """Take one optimisation step on ``x`` ``(batch, d_in)`` and return its metrics.

    The first step also initialises ``b_dec`` from ``x``. ``dead_frac`` describes the
    dictionary before this step; ``lr`` is the rate this step used.
    """
    started = time.perf_counter()
    x = x.to(self.device)
    if self.step == 0:
        self.sae.init_b_dec(x)

    learning_rate = self.cfg.lr * warmup_cosine(self.step, self.cfg.total_steps, self.cfg.warmup_steps)
    dead = self.dead_mask()
    out = self._optimise(x, dead, learning_rate)
    self._record_firing(out, x.shape[0])

    metrics = {
        "step": self.step,
        "tokens": self.tokens_seen,
        "fvu": out["fvu"].item(),  # reading the value also waits for the device
        "aux": out["aux"].item(),
        "dead_frac": dead.float().mean().item(),
        "lr": learning_rate,
    }
    self.step_seconds += time.perf_counter() - started
    return metrics

Fitting

Mixin with fit; the trainer provides train_step and save_checkpoint.

fit

fit(
    batches: Iterable[Tensor],
    *,
    out_dir: str | Path | None = None,
    log_fn: Callable[[dict[str, float]], None]
    | None = None,
    data_state: Callable[[], Mapping[str, int]]
    | None = None,
) -> TopKSAE

Train until total_tokens have been seen or batches runs out.

Parameters:

  • batches (Iterable[Tensor]) –

    activation batches (batch_tokens, d_in).

  • out_dir (str | Path | None, default: None ) –

    if given, trainer_config.json and train_log.jsonl are written there, plus checkpoint.pt every checkpoint_every steps and at the end.

  • log_fn (Callable[[dict[str, float]], None] | None, default: None ) –

    called with each log record.

  • data_state (Callable[[], Mapping[str, int]] | None, default: None ) –

    called at checkpoint time; its result is stored in the checkpoint so the caller can reposition its data stream when resuming.

Returns:

  • TopKSAE –

    The trained SAE (the same object as self.sae).

Source code in src/muscari/sae/trainers/fitting.py
def fit(
    self,
    batches: Iterable[torch.Tensor],
    *,
    out_dir: str | Path | None = None,
    log_fn: Callable[[dict[str, float]], None] | None = None,
    data_state: Callable[[], Mapping[str, int]] | None = None,
) -> TopKSAE:
    """Train until ``total_tokens`` have been seen or ``batches`` runs out.

    Args:
        batches: activation batches ``(batch_tokens, d_in)``.
        out_dir: if given, ``trainer_config.json`` and ``train_log.jsonl`` are written
            there, plus ``checkpoint.pt`` every ``checkpoint_every`` steps and at the end.
        log_fn: called with each log record.
        data_state: called at checkpoint time; its result is stored in the checkpoint so
            the caller can reposition its data stream when resuming.

    Returns:
        The trained SAE (the same object as ``self.sae``).
    """
    if self.step >= self.cfg.total_steps:
        return self.sae  # a resumed run that is already complete must not pull a batch

    with RunLog(out_dir, self.cfg, log_fn, tokens_at_start=self.tokens_seen) as run_log:
        for x in batches:
            if self.step >= self.cfg.total_steps:
                break

            metrics = self.train_step(x)
            if self.step % self.cfg.log_every == 0 or self.step == self.cfg.total_steps:
                run_log.write(metrics, self.tokens_seen)
            if self._checkpoint_due():
                self._checkpoint(out_dir, data_state)

        # A final checkpoint lets a later run extend the training length from here.
        if not self._checkpoint_due():
            self._checkpoint(out_dir, data_state)

    return self.sae

Checkpoints

Mixin that turns a trainer's state into a checkpoint file and back.

state_dict

state_dict() -> dict[str, Any]

Everything needed to continue training, as tensors and plain Python values.

Source code in src/muscari/sae/trainers/checkpoint.py
def state_dict(self) -> dict[str, Any]:
    """Everything needed to continue training, as tensors and plain Python values."""
    return {
        "version": CHECKPOINT_VERSION,
        "config": asdict(self.cfg),
        "d_in": self.sae.d_in,
        "sae": self.sae.state_dict(),
        "optimizer": self.optimizer.state_dict(),
        "tokens_since_fired": self.tokens_since_fired,
        "step": self.step,
        "tokens_seen": self.tokens_seen,
    }

load_state_dict

load_state_dict(state: Mapping[str, Any]) -> None

Restore a state produced by state_dict.

Raises:

  • ValueError –

    if the state comes from an unknown checkpoint version or from an SAE of a different shape or batch size.

Source code in src/muscari/sae/trainers/checkpoint.py
def load_state_dict(self, state: Mapping[str, Any]) -> None:
    """Restore a state produced by ``state_dict``.

    Raises:
        ValueError: if the state comes from an unknown checkpoint version or from an SAE of
            a different shape or batch size.
    """
    self._check_compatible(state)

    self.sae.load_state_dict(state["sae"])
    self.optimizer.load_state_dict(state["optimizer"])
    self.tokens_since_fired = state["tokens_since_fired"].to(self.device)
    self.step = int(state["step"])
    self.tokens_seen = int(state["tokens_seen"])

save_checkpoint

save_checkpoint(
    path: str | Path,
    *,
    data: Mapping[str, int] | None = None,
) -> None

Write a checkpoint atomically: a crash mid-write leaves the previous file intact.

Source code in src/muscari/sae/trainers/checkpoint.py
def save_checkpoint(self, path: str | Path, *, data: Mapping[str, int] | None = None) -> None:
    """Write a checkpoint atomically: a crash mid-write leaves the previous file intact."""
    target = Path(path)
    temporary = target.with_name(target.name + ".tmp")

    state = self.state_dict()
    state["data"] = dict(data) if data is not None else {}
    torch.save(state, temporary)
    os.replace(temporary, target)

load_checkpoint

load_checkpoint(path: str | Path) -> dict[str, int]

Restore from save_checkpoint and return the stored data-stream state.

Source code in src/muscari/sae/trainers/checkpoint.py
def load_checkpoint(self, path: str | Path) -> dict[str, int]:
    """Restore from ``save_checkpoint`` and return the stored data-stream state."""
    state = torch.load(Path(path), map_location=self.device, weights_only=True)
    self.load_state_dict(state)
    return dict(state.get("data", {}))

warmup_cosine

warmup_cosine(
    step: int, total_steps: int, warmup_steps: int
) -> float

Learning-rate multiplier for the 0-based step: linear warmup, then cosine decay to zero.

Source code in src/muscari/sae/trainers/schedule.py
def warmup_cosine(step: int, total_steps: int, warmup_steps: int) -> float:
    """Learning-rate multiplier for the 0-based ``step``: linear warmup, then cosine decay to zero."""
    if step < warmup_steps:
        return (step + 1) / warmup_steps

    progress = (step - warmup_steps) / max(1, total_steps - warmup_steps)
    return 0.5 * (1.0 + math.cos(math.pi * min(1.0, progress)))

SAELensTrainerConfig dataclass

SAELensTrainerConfig(
    architecture: str = "topk",
    num_latents: int = 65536,
    k: int = 16,
    aux_loss_coefficient: float = 1.0,
    dead_after_tokens: int = 10000000,
    lr: float = 0.0005,
    lr_end: float = 5e-06,
    warmup_frac: float = 0.05,
    adam_betas: tuple[float, float] = (0.9, 0.999),
    total_tokens: int = 1000000000,
    batch_tokens: int = 8192,
    amp: bool = False,
    init_b_dec: bool = True,
    seed: int = 42,
    log_to_wandb: bool = False,
    wandb_project: str = "muscari",
    device: str = "auto",
)

Hyperparameters passed on to SAELens.

Attributes:

  • architecture (str) –

    "topk" or "batchtopk".

  • num_latents (int) –

    dictionary size (d_sae in SAELens).

  • k (int) –

    active latents per token (on average for batchtopk).

  • aux_loss_coefficient (float) –

    SAELens' weight of its auxiliary loss. Not comparable to TopKTrainerConfig.aux_coef.

  • dead_after_tokens (int) –

    converted to SAELens' dead_feature_window in steps.

  • lr (float) –

    peak learning rate.

  • lr_end (float) –

    learning rate at the end of the cosine schedule.

  • warmup_frac (float) –

    share of the steps spent on linear warmup.

  • adam_betas (tuple[float, float]) –

    Adam (beta1, beta2).

  • total_tokens (int) –

    training length in tokens.

  • batch_tokens (int) –

    activations per optimisation step.

  • amp (bool) –

    let SAELens run under autocast.

  • init_b_dec (bool) –

    start the decoder bias at the geometric median of the first batch, as the topk trainer does. SAELens itself starts it at zero.

  • seed (int) –

    seed for the SAE initialisation.

  • log_to_wandb (bool) –

    send SAELens' metrics to Weights & Biases.

  • wandb_project (str) –

    project name used when logging is on.

  • device (str) –

    "auto" or a device string.

train_with_saelens

train_with_saelens(
    cfg: SAELensTrainerConfig,
    d_in: int,
    batches: Iterable[Tensor],
    out_dir: str | Path,
    export_config: dict[str, Any] | None = None,
) -> Path

Run SAETrainer.fit() and write the result in muscari's common format.

Parameters:

  • cfg (SAELensTrainerConfig) –

    hyperparameters.

  • d_in (int) –

    width of the activations.

  • batches (Iterable[Tensor]) –

    activation batches (batch_tokens, d_in); must provide at least cfg.total_steps of them.

  • out_dir (str | Path) –

    where sae.safetensors and sae_config.json are written.

  • export_config (dict[str, Any] | None, default: None ) –

    extra provenance stored in sae_config.json.

Returns:

  • Path –

    The output directory.

Raises:

  • ImportError –

    if SAELens is not installed.

Source code in src/muscari/sae/trainers/saelens.py
def train_with_saelens(
    cfg: SAELensTrainerConfig,
    d_in: int,
    batches: Iterable[torch.Tensor],
    out_dir: str | Path,
    export_config: dict[str, Any] | None = None,
) -> Path:
    """Run ``SAETrainer.fit()`` and write the result in muscari's common format.

    Args:
        cfg: hyperparameters.
        d_in: width of the activations.
        batches: activation batches ``(batch_tokens, d_in)``; must provide at least
            ``cfg.total_steps`` of them.
        out_dir: where ``sae.safetensors`` and ``sae_config.json`` are written.
        export_config: extra provenance stored in ``sae_config.json``.

    Returns:
        The output directory.

    Raises:
        ImportError: if SAELens is not installed.
    """
    device = resolve_device(cfg.device)
    sae = new_training_sae(cfg, d_in, device)  # raises the ImportError first

    from sae_lens.training.sae_trainer import SAETrainer

    stream = _start_at_median(sae, batches) if cfg.init_b_dec else iter(batches)

    trainer = SAETrainer(
        cfg=trainer_config(cfg, device),
        sae=sae,
        data_provider=_on_device(stream, device),
    )
    trained = trainer.fit()
    unused_frac, window_tokens = _unused_frac(trainer, cfg)

    with tempfile.TemporaryDirectory() as temporary:
        trained.save_inference_model(temporary)
        return save_saelens_sae(
            out_dir,
            temporary,
            config={
                **(export_config or {}),
                "trainer": f"saelens-{cfg.architecture}",
                "b_dec_init": "geometric_median" if cfg.init_b_dec else "zero",
                "train_unused_frac": unused_frac,
                "train_unused_window_tokens": window_tokens,
            },
        )

Saving and loading

load_sae

load_sae(
    sae: str | Path,
    device: str | device = "cpu",
    *,
    revision: str | None = None,
) -> ExportedSAE

Load an SAE written by save_sae, from a directory or a Hugging Face Hub repository.

Raises:

  • FileNotFoundError –

    if the weights or the config are missing.

  • ValueError –

    if the files were written by a newer format version.

Source code in src/muscari/sae/exported.py
def load_sae(
    sae: str | Path,
    device: str | torch.device = "cpu",
    *,
    revision: str | None = None,
) -> ExportedSAE:
    """Load an SAE written by ``save_sae``, from a directory or a Hugging Face Hub repository.

    Raises:
        FileNotFoundError: if the weights or the config are missing.
        ValueError: if the files were written by a newer format version.
    """
    directory = resolve_sae_dir(sae, revision=revision)
    config = read_config(directory)
    tensors = load_file(directory / WEIGHTS_NAME)

    return ExportedSAE(tensors, config).to(resolve_device(device))

ExportedSAE

ExportedSAE(
    tensors: dict[str, Tensor], config: dict[str, Any]
)

Bases: Module

Inference-only view of a saved SAE; the same code serves both trainers' outputs.

Attributes:

  • config –

    the parsed sae_config.json.

  • encoder_weight (Tensor) –

    (num_latents, d_in).

  • encoder_bias (Tensor) –

    (num_latents,) with b_dec folded in.

  • decoder_weight (Tensor) –

    (d_in, num_latents).

  • decoder_bias (Tensor) –

    (d_in,).

  • threshold (Tensor | None) –

    (num_latents,) for JumpReLU SAEs, otherwise None.

An SAE whose config has normalize_inputs was trained on activations scaled to unit length. encode then scales its input the same way, so the features do not depend on the length of the activation, and forward gives the reconstruction that length back, so it can be compared with, or put in place of, the original activation.

Source code in src/muscari/sae/exported.py
def __init__(self, tensors: dict[str, torch.Tensor], config: dict[str, Any]) -> None:
    super().__init__()
    self.config = config

    self.register_buffer("encoder_weight", tensors["encoder.weight"])
    self.register_buffer("encoder_bias", tensors["encoder.bias"])
    self.register_buffer("decoder_weight", tensors["decoder.weight"])
    self.register_buffer("decoder_bias", tensors["decoder.bias"])
    self.register_buffer("threshold", tensors.get("threshold"))

encode

encode(x: Tensor, k: int | None = None) -> Tensor

Dense, non-negative feature activations (..., num_latents) for x (..., d_in).

A Top-K SAE keeps the k largest pre-activations per token after ReLU; k defaults to the training value. A JumpReLU SAE keeps every pre-activation above its latent's threshold and ignores k.

Source code in src/muscari/sae/exported.py
def encode(self, x: torch.Tensor, k: int | None = None) -> torch.Tensor:
    """Dense, non-negative feature activations ``(..., num_latents)`` for ``x`` ``(..., d_in)``.

    A Top-K SAE keeps the ``k`` largest pre-activations per token after ReLU; ``k``
    defaults to the training value. A JumpReLU SAE keeps every pre-activation above its
    latent's threshold and ignores ``k``.
    """
    if self.normalize_inputs:
        x = F.normalize(x, dim=-1)

    pre = x @ self.encoder_weight.T + self.encoder_bias
    if self.threshold is not None:
        return pre * (pre > self.threshold)

    top_k = int(self.config["k"]) if k is None else k
    values, indices = pre.topk(top_k, dim=-1)
    return torch.zeros_like(pre).scatter_(-1, indices, values.relu())

decode

decode(features: Tensor) -> Tensor

Reconstruct activations (..., d_in) from features (..., num_latents).

With normalize_inputs this is the reconstruction of the unit-length activation; reconstruct restores the length.

Source code in src/muscari/sae/exported.py
def decode(self, features: torch.Tensor) -> torch.Tensor:
    """Reconstruct activations ``(..., d_in)`` from features ``(..., num_latents)``.

    With ``normalize_inputs`` this is the reconstruction of the unit-length activation;
    ``reconstruct`` restores the length.
    """
    return features @ self.decoder_weight.T + self.decoder_bias

reconstruct

reconstruct(
    x: Tensor, features: Tensor | None = None
) -> Tensor

The SAE's reconstruction of x on the scale of x; features default to encode(x).

Source code in src/muscari/sae/exported.py
def reconstruct(self, x: torch.Tensor, features: torch.Tensor | None = None) -> torch.Tensor:
    """The SAE's reconstruction of ``x`` on the scale of ``x``; ``features`` default to ``encode(x)``."""
    reconstruction = self.decode(self.encode(x) if features is None else features)

    if self.normalize_inputs:
        reconstruction = reconstruction * x.norm(dim=-1, keepdim=True)

    return reconstruction

resolve_sae_dir

resolve_sae_dir(
    sae: str | Path, *, revision: str | None = None
) -> Path

A local directory holding the SAE: sae itself, or its files fetched from the Hugging Face Hub.

A path that is not an existing directory is taken as a Hub repository id; only sae.safetensors and sae_config.json are downloaded.

Source code in src/muscari/sae/exported.py
def resolve_sae_dir(sae: str | Path, *, revision: str | None = None) -> Path:
    """A local directory holding the SAE: ``sae`` itself, or its files fetched from the Hugging Face Hub.

    A path that is not an existing directory is taken as a Hub repository id; only
    ``sae.safetensors`` and ``sae_config.json`` are downloaded.
    """
    if Path(sae).is_dir():
        return Path(sae)

    from huggingface_hub import snapshot_download

    files = [WEIGHTS_NAME, CONFIG_NAME]
    return Path(snapshot_download(str(sae), revision=revision, allow_patterns=files))

save_sae

save_sae(
    out_dir: str | Path,
    *,
    encoder_weight: Tensor,
    encoder_bias: Tensor,
    decoder_weight: Tensor,
    decoder_bias: Tensor,
    config: dict[str, Any],
    threshold: Tensor | None = None,
) -> Path

Write the tensors and config in the common format and return the directory.

config must contain k unless threshold is given. d_in, num_latents, activation and format_version are derived here and override any such keys. normalize_inputs: true records that the SAE was trained on activations scaled to unit length; ExportedSAE and the retrieval head then scale their inputs the same way.

Raises:

  • ValueError –

    if the tensor shapes disagree or a Top-K SAE has no k.

Source code in src/muscari/sae/format.py
def save_sae(
    out_dir: str | Path,
    *,
    encoder_weight: torch.Tensor,
    encoder_bias: torch.Tensor,
    decoder_weight: torch.Tensor,
    decoder_bias: torch.Tensor,
    config: dict[str, Any],
    threshold: torch.Tensor | None = None,
) -> Path:
    """Write the tensors and config in the common format and return the directory.

    ``config`` must contain ``k`` unless ``threshold`` is given. ``d_in``, ``num_latents``,
    ``activation`` and ``format_version`` are derived here and override any such keys.
    ``normalize_inputs: true`` records that the SAE was trained on activations scaled to unit
    length; ``ExportedSAE`` and the retrieval head then scale their inputs the same way.

    Raises:
        ValueError: if the tensor shapes disagree or a Top-K SAE has no ``k``.
    """
    _check_shapes(encoder_weight, encoder_bias, decoder_weight, decoder_bias)
    if threshold is None and "k" not in config:
        raise ValueError("A Top-K SAE needs 'k' in its config.")

    tensors = {
        "encoder.weight": encoder_weight,
        "encoder.bias": encoder_bias,
        "decoder.weight": decoder_weight,
        "decoder.bias": decoder_bias,
    }
    if threshold is not None:
        tensors["threshold"] = threshold

    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    save_file(
        {name: tensor.detach().float().cpu().contiguous() for name, tensor in tensors.items()},
        out / WEIGHTS_NAME,
    )

    num_latents, d_in = encoder_weight.shape
    full_config = {
        **config,
        "format_version": FORMAT_VERSION,
        "d_in": d_in,
        "num_latents": num_latents,
        "activation": "jumprelu" if threshold is not None else "topk",
    }
    (out / CONFIG_NAME).write_text(
        json.dumps(full_config, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
    return out

read_config

read_config(sae_dir: str | Path) -> dict[str, Any]

The parsed sae_config.json of a saved SAE.

Raises:

  • FileNotFoundError –

    if there is no config.

  • ValueError –

    if it was written by a newer format version.

Source code in src/muscari/sae/format.py
def read_config(sae_dir: str | Path) -> dict[str, Any]:
    """The parsed ``sae_config.json`` of a saved SAE.

    Raises:
        FileNotFoundError: if there is no config.
        ValueError: if it was written by a newer format version.
    """
    source = Path(sae_dir)
    config: dict[str, Any] = json.loads((source / CONFIG_NAME).read_text(encoding="utf-8"))

    if int(config.get("format_version", FORMAT_VERSION)) > FORMAT_VERSION:
        raise ValueError(f"{source} uses format version {config['format_version']}; upgrade muscari to read it.")

    return config

save_topk_sae

save_topk_sae(
    out_dir: str | Path,
    sae: TopKSAE,
    config: dict[str, Any],
) -> Path

Export a TopKSAE, folding b_dec into the encoder bias.

Source code in src/muscari/sae/conversion.py
def save_topk_sae(out_dir: str | Path, sae: TopKSAE, config: dict[str, Any]) -> Path:
    """Export a ``TopKSAE``, folding ``b_dec`` into the encoder bias."""
    weight = sae.encoder.weight.detach()
    folded_bias = sae.encoder.bias.detach() - weight @ sae.b_dec.detach()

    return save_sae(
        out_dir,
        encoder_weight=weight,
        encoder_bias=folded_bias,
        decoder_weight=sae.decoder.detach().T,
        decoder_bias=sae.b_dec.detach(),
        config={**config, "k": sae.k},
    )

save_saelens_sae

save_saelens_sae(
    out_dir: str | Path,
    saelens_inference_dir: str | Path,
    config: dict[str, Any],
) -> Path

Convert a directory written by SAELens save_inference_model.

SAELens stores W_enc as (d_in, d_sae) and W_dec as (d_sae, d_in); its inference export has already folded the decoder norms into the weights. A BatchTopK SAE arrives as a JumpReLU SAE with a per-latent threshold.

Raises:

  • ValueError –

    if the SAE was trained with activation normalisation, which cannot be folded into this format.

Source code in src/muscari/sae/conversion.py
def save_saelens_sae(
    out_dir: str | Path,
    saelens_inference_dir: str | Path,
    config: dict[str, Any],
) -> Path:
    """Convert a directory written by SAELens ``save_inference_model``.

    SAELens stores ``W_enc`` as ``(d_in, d_sae)`` and ``W_dec`` as ``(d_sae, d_in)``; its
    inference export has already folded the decoder norms into the weights. A BatchTopK SAE
    arrives as a JumpReLU SAE with a per-latent ``threshold``.

    Raises:
        ValueError: if the SAE was trained with activation normalisation, which cannot be
            folded into this format.
    """
    source = Path(saelens_inference_dir)
    saelens_config = json.loads((source / "cfg.json").read_text(encoding="utf-8"))
    if saelens_config.get("normalize_activations", "none") != "none":
        raise ValueError("normalize_activations must be 'none'; a scaler cannot be folded here.")

    state = load_file(source / "sae_weights.safetensors")
    w_enc, w_dec, b_enc, b_dec = state["W_enc"], state["W_dec"], state["b_enc"], state["b_dec"]
    apply_b_dec = saelens_config.get("apply_b_dec_to_input", False)
    folded_bias = b_enc - b_dec @ w_enc if apply_b_dec else b_enc

    extra = {"k": saelens_config["k"]} if "k" in saelens_config else {}
    return save_sae(
        out_dir,
        encoder_weight=w_enc.T,
        encoder_bias=folded_bias,
        decoder_weight=w_dec.T,
        decoder_bias=b_dec,
        threshold=state.get("threshold"),
        config={
            **config,
            **extra,
            "saelens_architecture": saelens_config.get("architecture"),
        },
    )

import_sae

import_sae(
    weights: str | Path,
    out_dir: str | Path,
    *,
    k: int,
    base_model: str,
    max_seq_length: int,
    columns: Sequence[TextColumn] = (),
    layer: str | int = "last_hidden_state",
    layout: str = "muscari",
    fold_decoder_bias: bool = False,
    normalize_inputs: bool = False,
    source: str | None = None,
) -> Path

Write out_dir in muscari's format from a safetensors or .pt file of an SAE.

layout names the tensors of the source (see LAYOUTS). layer is "last_hidden_state" or an index into the model's hidden_states.

normalize_inputs records that the SAE was trained on activations scaled to unit length, so that every use of it scales its input the same way.

Raises:

  • ValueError –

    if the layout is unknown, a tensor is missing, k is out of range or the shapes disagree.

Source code in src/muscari/sae/importing.py
def import_sae(
    weights: str | Path,
    out_dir: str | Path,
    *,
    k: int,
    base_model: str,
    max_seq_length: int,
    columns: Sequence[TextColumn] = (),
    layer: str | int = "last_hidden_state",
    layout: str = "muscari",
    fold_decoder_bias: bool = False,
    normalize_inputs: bool = False,
    source: str | None = None,
) -> Path:
    """Write ``out_dir`` in muscari's format from a safetensors or ``.pt`` file of an SAE.

    ``layout`` names the tensors of the source (see ``LAYOUTS``). ``layer`` is
    ``"last_hidden_state"`` or an index into the model's ``hidden_states``.

    ``normalize_inputs`` records that the SAE was trained on activations scaled to unit length,
    so that every use of it scales its input the same way.

    Raises:
        ValueError: if the layout is unknown, a tensor is missing, ``k`` is out of range or the
            shapes disagree.
    """
    tensors = _read_tensors(weights, layout)
    encoder_weight = tensors["encoder.weight"].float()
    encoder_bias = tensors["encoder.bias"].float()
    decoder_bias = tensors["decoder.bias"].float()

    if not 0 < k <= encoder_weight.shape[0]:
        raise ValueError(f"k must be between 1 and {encoder_weight.shape[0]}.")
    if fold_decoder_bias:
        encoder_bias = encoder_bias - encoder_weight @ decoder_bias

    config: dict[str, Any] = {
        "k": k,
        "base_model": base_model,
        "layer": int(layer) if str(layer).isdigit() else layer,
        "max_seq_length": max_seq_length,
        "imported_from": source or Path(weights).name,
        "decoder_bias_folded_on_import": fold_decoder_bias,
    }
    if normalize_inputs:
        config["normalize_inputs"] = True
    if columns:
        config["columns"] = {column.name: column.prompt for column in columns}
        config["labels"] = {column.name: column.label for column in columns if column.label}

    return save_sae(
        out_dir,
        encoder_weight=encoder_weight,
        encoder_bias=encoder_bias,
        decoder_weight=tensors["decoder.weight"].float(),
        decoder_bias=decoder_bias,
        config=config,
    )

Quality

evaluate_sae

evaluate_sae(
    sae: ExportedSAE,
    activations: Tensor,
    batch_size: int = 1024,
) -> dict[str, float]

Measure reconstruction and how evenly the dictionary is used on activations (n, d_in).

Returns:

  • dict[str, float] –

    fvu: squared reconstruction error over the variance around the mean activation.

  • dict[str, float] –

    l0: mean number of active latents per token.

  • dict[str, float] –

    never_fired_frac: share of latents that never fire on these tokens.

  • dict[str, float] –

    rare_frac: share of latents that fire less than a tenth as often as the average

  • dict[str, float] –

    latent (the average frequency is l0 / num_latents); never-fired latents included.

  • dict[str, float] –

    dense_frac: share of latents that fire on more than 10% of the tokens.

  • dict[str, float] –

    median_frequency: the firing frequency of the median latent.

  • dict[str, float] –

    max_frequency: the largest share of tokens any single latent fires on.

  • dict[str, float] –

    eval_tokens: number of activations evaluated.

The frequency figures depend on eval_tokens: with few tokens many rare latents have had no chance to fire, so compare never_fired_frac only between equally sized samples.

Raises:

  • ValueError –

    if activations is empty or has the wrong width.

Source code in src/muscari/sae/quality.py
@torch.no_grad()
def evaluate_sae(
    sae: ExportedSAE,
    activations: torch.Tensor,
    batch_size: int = 1024,
) -> dict[str, float]:
    """Measure reconstruction and how evenly the dictionary is used on ``activations`` ``(n, d_in)``.

    Returns:
        ``fvu``: squared reconstruction error over the variance around the mean activation.
        ``l0``: mean number of active latents per token.
        ``never_fired_frac``: share of latents that never fire on these tokens.
        ``rare_frac``: share of latents that fire less than a tenth as often as the average
        latent (the average frequency is ``l0 / num_latents``); never-fired latents included.
        ``dense_frac``: share of latents that fire on more than 10% of the tokens.
        ``median_frequency``: the firing frequency of the median latent.
        ``max_frequency``: the largest share of tokens any single latent fires on.
        ``eval_tokens``: number of activations evaluated.

    The frequency figures depend on ``eval_tokens``: with few tokens many rare latents have had
    no chance to fire, so compare ``never_fired_frac`` only between equally sized samples.

    Raises:
        ValueError: if ``activations`` is empty or has the wrong width.
    """
    if activations.ndim != 2 or activations.shape[0] == 0 or activations.shape[1] != sae.d_in:
        raise ValueError(f"activations must be a non-empty (n, {sae.d_in}) tensor.")

    device = sae.encoder_weight.device
    n_tokens = activations.shape[0]
    mean = activations.mean(dim=0, keepdim=True).to(device)

    residual = 0.0
    total = 0.0
    fire_counts = torch.zeros(sae.num_latents, dtype=torch.long, device=device)

    for start in range(0, n_tokens, batch_size):
        x = activations[start : start + batch_size].to(device)
        features = sae.encode(x)

        residual += (x - sae.reconstruct(x, features)).pow(2).sum().item()
        total += (x - mean).pow(2).sum().item()
        fire_counts += (features > 0).sum(dim=0)

    return {
        "fvu": residual / max(total, 1e-12),
        **_frequency_summary(fire_counts, n_tokens, sae.num_latents),
        "eval_tokens": n_tokens,
    }