muscari.sae¶
Sparse autoencoders: the Top-K model, its trainers, and the common on-disk format.
Model¶
TopKSAE
¶
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
kexceedsnum_latents.
Source code in src/muscari/sae/model.py
reset_parameters
¶
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
init_b_dec
¶
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
encode
¶
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
decode_sparse
¶
Sum values[b, j] * decoder[indices[b, j]] over j; both inputs are (batch, n).
Source code in src/muscari/sae/model.py
TopKObjective
¶
Bases: Module
Mixin with the loss and the decoder maintenance of TopKSAE.
loss
¶
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]–valuesandindices: the selected activations,(batch, k).
Source code in src/muscari/sae/objective.py
remove_parallel_decoder_grad
¶
Project out the gradient component that would only change a decoder row's norm.
Source code in src/muscari/sae/objective.py
normalize_decoder
¶
sparse_topk
¶
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
normalized_mse
¶
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
geometric_median
¶
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
pointsis not a non-empty matrix.
Source code in src/muscari/sae/metrics.py
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_stepso far.
Source code in src/muscari/sae/trainers/topk.py
dead_mask
¶
Boolean (num_latents,) mask of the latents currently considered dead.
unused_frac
¶
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
train_step
¶
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
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.jsonandtrain_log.jsonlare written there, pluscheckpoint.pteverycheckpoint_everysteps 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
Checkpoints
¶
Mixin that turns a trainer's state into a checkpoint file and back.
state_dict
¶
Everything needed to continue training, as tensors and plain Python values.
Source code in src/muscari/sae/trainers/checkpoint.py
load_state_dict
¶
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
save_checkpoint
¶
Write a checkpoint atomically: a crash mid-write leaves the previous file intact.
Source code in src/muscari/sae/trainers/checkpoint.py
load_checkpoint
¶
Restore from save_checkpoint and return the stored data-stream state.
Source code in src/muscari/sae/trainers/checkpoint.py
warmup_cosine
¶
Learning-rate multiplier for the 0-based step: linear warmup, then cosine decay to zero.
Source code in src/muscari/sae/trainers/schedule.py
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_saein 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_windowin 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
topktrainer 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 leastcfg.total_stepsof them. -
out_dir(str | Path) –where
sae.safetensorsandsae_config.jsonare 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
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
ExportedSAE
¶
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,)withb_decfolded in. -
decoder_weight(Tensor) –(d_in, num_latents). -
decoder_bias(Tensor) –(d_in,). -
threshold(Tensor | None) –(num_latents,)for JumpReLU SAEs, otherwiseNone.
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
encode
¶
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
decode
¶
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
reconstruct
¶
The SAE's reconstruction of x on the scale of x; features default to encode(x).
Source code in src/muscari/sae/exported.py
resolve_sae_dir
¶
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
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
read_config
¶
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
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
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
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,
kis out of range or the shapes disagree.
Source code in src/muscari/sae/importing.py
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
activationsis empty or has the wrong width.