Improving Dictionary Learning with Gated Sparse Autoencoders
Senthooran Rajamanoharan Arthur Conmy Lewis Smith Tom Lieberum Vikrant Varma János Kramár Rohin Shah Neel Nanda

Editable Image Elements for 
 Controllable Synthesis
    Jiteng Mu1* Michaël Gharbi2 Richard Zhang2 Eli Shechtman2 Nuno Vasconcelos1 Xiaolong Wang1 Taesung Park2

    25 April 2024
=============================================================================================================



§ INTRODUCTION



Mechanistic interpretability research aims to explain how neural networks produce outputs in terms of the learned algorithms executed during a forward pass <cit.>. Much work makes use of the fact that many concept representations appear to be linear <cit.>. However, finding the set of all interpretable directions is a highly non-trivial problem. Classic approaches, like interpreting neurons (i.e. directions in the standard basis) are insufficient, as many are polysemantic and tend to activate for a range of different seemingly unrelated concepts <cit.>. 

The superposition hypothesis <cit.> posits a mechanistic explanation for these observations: in an intermediate representation of dimension , a model will encode ≫ concepts as linear directions, where the set of concepts and their directions is fixed across all inputs, but on a given input only a sparse subset of concepts are active, ensuring that there is not much simultaneous interference <cit.> between these (non-orthogonal) concepts. Motivated by the superposition hypothesis, <cit.> and <cit.> recently used sparse autoencoders (SAEs; <cit.>) to find sparse decompositions of model activations in terms of an overcomplete basis, or dictionary <cit.>.[Although motivated by the superposition hypothesis, the utility of line of research is not contingent on this hypothesis being true. If a faithful, sparse and interpretable decomposition can be found, we expect this to be a useful basis in its own right for downstream interpretability tasks, such as understanding or intervening on a model's representations and circuits, even if some fraction of the model's computation is e.g. represented non-linearly and not captured.] 

Although SAEs show promise in this regard, the L1 penalty used in the prevailing training method to encourage sparsity also introduces biases that harm the accuracy of SAE reconstructions, as the loss can be decreased by trading-off some reconstruction accuracy for lower L1. We refer to this existing training methodology as the baseline SAE, defined fully in <Ref>-<ref> and which borrows heavily from <cit.>. In this paper, we introduce a modification to the baseline SAE architecture – a Gated SAE – along with an accompanying loss function, which partially overcomes these limitations. Our key insight is to use separate affine transformations for (a) determining which dictionary elements to use in a reconstruction and (b) estimating the coefficients of active elements, and to apply the sparsity penalty only to the former task. We share a subset of weights between these transformations to avoid significantly increasing the parameter count and inference-time compute requirements of a Gated SAE compared to a baseline SAE of equivalent width.[Although due to an auxiliary loss term, computing the Gated SAE loss for training purposes does require 50% more compute than computing the loss for a matched-width baseline SAE.]


We evaluate Gated SAEs on multiple models: one layer GELU activation language models <cit.>, Pythia-2.8B <cit.> and Gemma-7B <cit.>, and on multiple sites within models: MLP layer outputs, attention layer outputs, and residual stream activations. Across these models and sites, we find Gated SAEs to be a Pareto improvement over baseline SAEs holding training compute fixed (<ref>): they yield sparser decompositions at any desired level of reconstruction fidelity. We also conduct further follow up ablations and investigations on a subset of these models and sites to better understand the differences between Gated SAEs and baseline SAEs.

Overall, the key contributions of this work are that we:


  * Introduce the Gated SAE, a modification to the standard SAE architecture that decouples detection of which features are present from estimating their magnitudes (<Ref>);

  * Show that Gated SAEs Pareto improve the sparsity and reconstruction fidelity trade-off, compared to baseline SAEs (<Ref>);

  * Confirm that Gated SAEs overcome the shrinkage problem (<Ref>), while outperforming other methods that also address this problem (<Ref>);

  * Provide evidence from a small double-blind study that Gated SAE features are comparably interpretable to baseline SAE features (<Ref>).






§ SPARSE AUTOENCODER BACKGROUND



In this section we summarise the concepts and notation necessary to understand existing SAE architectures and training methods, which we call the baseline SAE. We define Gated SAEs in <Ref>. We follow notation broadly similar to <cit.> and recommend that work as a more complete introduction to training SAEs on LMs.  

As motivated in <Ref>, we wish to decompose a model's activation 𝐱∈ℝ^ into a sparse, linear combination of feature directions:

    𝐱≈𝐱_0 + ∑_i=1^ f_i(𝐱) 𝐝_i,

where 𝐝_i are ≫ latent unit-norm feature directions, and the sparse coefficients f_i(𝐱) ≥ 0 are the corresponding feature activations for 𝐱.[In this work, we use the term feature only in the context of the learned features of SAEs, i.e. the overcomplete basis directions that are linearly combined to produce reconstructions. In particular, learned features are always linear and not necessarily interpretable, sidestepping the difficulty in defining what a feature is (<cit.>'s `What are features?' section).] The right-hand side of <ref> naturally has the structure of an autoencoder: an input activation 𝐱 is encoded into a (sparse) feature activations vector 𝐟(𝐱)∈ℝ^, which in turn is linearly decoded to reconstruct 𝐱.



 §.§ Baseline Architecture



Using this correspondence, <cit.> and subsequent works attempt to learn a suitable sparse decomposition by parameterising a single-layer autoencoder (𝐟, 𝐱̂) defined by:

    𝐟(𝐱)    := ReLU((𝐱 - ) + ) 
    𝐱̂(𝐟)    := 𝐟 +

and training it (<Ref>) to reconstruct a large dataset of model activations 𝐱∼𝒟, constraining the hidden representation 𝐟 to be sparse.[Model activations are typically taken from a specific layer and site, e.g. the output of the MLP part of layer 17.] Once the sparse autoencoder has been trained, we obtain a decomposition of the form of <ref> by identifying the (suitably normalised) columns of the decoder weight matrix ∈ℝ^× with the dictionary of feature directions 𝐝_𝐢, the decoder bias ∈ℝ^ with the centering term 𝐱_0, and the (suitably normalised) entries of the latent representation 𝐟(𝐱) ∈ℝ^ with the feature activations f_i(𝐱).



 §.§ Baseline Training Methodology



To train sparse autoencoders, <cit.> use a loss function that jointly encourages (i) faithful reconstruction and (ii) sparsity. Reconstruction fidelity is encouraged by the squared distance between SAE input and its reconstruction, 𝐱-𝐱̂(𝐟(𝐱))_2^2, which we call the reconstruction loss, whereas sparsity is encouraged by the L1 norm of the active features, 𝐟(𝐱)_1, which we call the sparsity penalty.[Note that we cannot directly optimize the L0 norm (i.e. the number of active features) since this is not a differentiable function. We do however use the L0 norm to evaluate SAE sparsity (<Ref>).] Balancing these two terms with a L1 coefficient λ, the loss used to optimize SAEs is given by 

    ℒ(𝐱) := 𝐱-𝐱̂(𝐟(𝐱))_2^2 + λ𝐟(𝐱)_1.

Since it is possible to arbitrarily reduce the sparsity loss term without affecting reconstructions or sparsity by simply scaling down encoder outputs and scaling up the norm of the decoder weights, it is important to constrain the norms of the columns of  during training. Following <cit.>, we constrain columns to have exactly unit norm. See <ref> for full details about our (Gated and baseline) SAE training.



 §.§ Evaluation



To get a sense of the quality of trained SAEs we use two metrics from <cit.>: L0, a measure of SAE sparsity and loss recovered, a measure of SAE reconstruction fidelity.



  * The L0 of a SAE is defined by the average number of active features on a given input, i.e 𝔼_𝐱∼𝒟𝐟(𝐱)_0.

  * The loss recovered of a SAE is calculated from the average cross-entropy loss of the language model on an evaluation dataset, when the SAE's reconstructions are spliced into it. If we denote by CE(ϕ) the average loss of the language model when we splice in a function ϕ: ℝ^→ℝ^ at the SAE's site during the model's forward pass, then loss recovered is 

    1 - CE(𝐱̂∘𝐟) - CE(𝐈𝐝)/CE(ζ) - CE(𝐈𝐝),

Where 𝐱̂∘𝐟 is the autoencoder function, ζ: 𝐱↦0 the zero-ablation function and Id:𝐱↦𝐱 the identity function. According to this definition, a SAE that always outputs the zero vector as its reconstruction would get a loss recovered of 0%, whereas a SAE that reconstructs its inputs perfectly would get a loss recovered of 100%.

Of course, these metrics do not paint the full picture of SAE quality,[For example, see <cit.>.] hence we perform manual analysis of SAE interpretability in <Ref>.



§ GATED SAES




 §.§ Motivation






The intuition behind how SAEs are trained is to maximise reconstruction fidelity at a given level of sparsity, as measured by L0, although in practice we optimize a mixture of reconstruction fidelity and L1 regularization. This difference is a source of unwanted bias in the training of a sparse autoencoder: for any fixed level of sparsity, a trained SAE can achieve lower loss (as defined in <ref>) by trading off a little reconstruction fidelity to perform better on the L1 sparsity penalty.

The clearest consequence of this bias is shrinkage <cit.>, illustrated in <Ref>. Holding the decoder 𝐱̂(∙) fixed, the L1 penalty pushes feature activations 𝐟(𝐱) towards zero, while the reconstruction loss pushes 𝐟(𝐱) high enough to produce an accurate reconstruction. Thus, the optimal value is somewhere in between, which means it systematically underestimates the magnitude of feature activations, without any necessarily having any compensatory benefit for sparsity.[Conversely, rescaling the shrunk feature activations <cit.> is not necessarily enough to overcome the bias induced by by L1 penalty: a SAE trained with the L1 penalty could have learnt sub-optimal encoder and decoder directions that are not improved by such a fix. In <Ref> and <Ref> we provide empirical evidence that this is true in practice.]

How can we reduce the bias introduced by the L1 penalty? The output of the encoder 𝐟(𝐱) of a baseline SAE (<Ref>) has two roles:


  * It detects which features are active (according to whether the outputs are zero or strictly positive). For this role, the L1 penalty is necessary to ensure the decomposition is sparse.

  * It estimates the magnitudes of active features. For this role, the L1 penalty is a source of unwanted bias.

If we could separate out these two functions of the SAE encoder, we could design a training loss that narrows down the scope of SAE parameters that are affected (and therefore to some extent biased) by the L1 sparsity penalty to precisely those parameters that are involved in feature detection, minimising its impact on parameters used in feature magnitude estimation.




 §.§ Gated SAEs





  §.§.§ Architecture


How should we modify the baseline SAE encoder to achieve this separation of concerns? Our solution is to replace the single-layer ReLU encoder of a baseline SAE with a gated ReLU encoder. Taking inspiration from Gated Linear Units <cit.>, we define the gated encoder as follows:

    𝐟̃(𝐱) := 1[((𝐱 - ) + )^(𝐱) > 0]_(𝐱)⊙ReLU((𝐱 - ) + )_(𝐱),

where 1[∙>0] is the (pointwise) Heaviside step function and ⊙ denotes elementwise multiplication. Here,  determines which features are deemed to be active, while  estimates feature activation magnitudes (which only matter for features that have been deemed to be active); (𝐱) are the  sub-layer's pre-activations, which are used in the gated SAE loss, defined below.

Naively, we appear to have doubled the number of parameters in the encoder, increasing the total number of parameters by 50%. We mitigate this through weight sharing: we parameterise these layers so that the two layers share the same projection directions, but allow the norms of these directions as well as the layer biases to differ. Concretely, we define  in terms of  and an additional vector-valued rescaling parameter ∈ℝ^ as follows:

    ()_ij :=
        (exp())_i·()_ij.

See <ref> for an illustration of the tied-weight Gated SAEs architecture.
With this weight tying scheme, the Gated SAE has only 2× more parameters than a baseline SAE.
In <ref>, we perform an ablation study showing that this weight tying scheme leads to a small increase in performance.

With tied weights, the gated encoder can be reinterpreted as a single-layer linear encoder with a non-standard and discontinuous “Jump ReLU” activation function <cit.>, σ_θ(z), illustrated in <ref>. To be precise, using the weight tying scheme of <ref>, 𝐟̃(𝐱) can be re-expressed as 𝐟̃(𝐱) = σ_θ(·𝐱 + ), with the Jump ReLU gap given by θ =  - e^⊙; see <ref> for an explanation. We think this is a useful intuition for reasoning about how Gated SAEs reconstruct activations in practice. See Appendix <ref> for a walkthrough of a toy example where an SAE with Jump ReLUs outperforms one with standard ReLUs.








  §.§.§ Training Gated SAEs



A natural idea for training gated SAEs would be to apply <ref>, while restricting the sparsity penalty to just 𝐟_gate:

    ℒ_incorrect(𝐱) :=
    𝐱 - 𝐱̂(𝐟̃(𝐱))_2^2_ℒ_reconstruct
    + λ(𝐱)
    _1_ℒ_sparsity

Unfortunately, due to the Heaviside step activation function in , no gradients would propagate to  and . To mitigate this for the sparsity penalty, we instead apply the L1 norm to the positive parts of the preactivation, ReLU((𝐱)). To ensure  aids reconstruction by detecting active features, we add an auxiliary task requiring that these same rectified preactivations can be used by the decoder to produce a good reconstruction:

    ℒ_gated(𝐱) :=
    𝐱 - 𝐱̂(𝐟̃(𝐱))_2^2_ℒ_reconstruct
    + λ((𝐱))_1_ℒ_sparsity
    + 𝐱 - 𝐱̂_frozen(((𝐱)))_2^2_ℒ_aux

where 𝐱̂_frozen is a frozen copy of the decoder, 𝐱̂_frozen(𝐟) := ^copy𝐟 + ^copy, to ensure that gradients from ℒ_aux do not propagate back to  or . This can typically be implemented by stop gradient operations rather than creating copies – see <ref> for pseudo-code for the forward pass and loss function.

To calculate this loss (or its gradient), we have to run the decoder twice: once to perform the main reconstruction for ℒ_reconstruct and once to perform the auxiliary reconstruction for ℒ_aux. This leads to a 50% increase in the compute required to perform a training update step. However, the increase in overall training time is typically much less, as in our experience much of the training wall clock time goes to generating language model activations (if these are being generated on the fly) or disk I/O (if training on saved activations).



§ EVALUATION



In this section we benchmark Gated SAEs across a large variety of models and at different sites (<Ref>), show that they resolve the shrinkage problem (<Ref>), and show that they produce features that are similarly interpretable to baseline SAE features according to expert human raters, although we could not conclusively determine whether one is better than the other (<Ref>).



 §.§ Comprehensive Benchmarking



In this subsection we show that Gated SAEs are a Pareto improvement over baseline SAEs on the loss recovered and L0 metrics (<Ref>). We show this by evaluating SAEs trained to reconstruct:


  * The MLP neuron activations in GELU-1L, which is the closest direct comparison to <cit.>;

  * The MLP outputs, attention layer outputs (taken pre W_O as in <cit.>) and residual stream activations in 5 different layers throughout Pythia-2.8B and four different layers in the Gemma-7B base model.

In both experiments, we vary the L1 coefficient λ (<Ref>) used to train the SAEs, which enables us to compare the Pareto frontiers of L0 and loss recovered between Gated and baseline SAEs.

Gated SAEs require at most 1.5× more compute to train than regular SAEs (<Ref>). To therefore ensure fair comparison in our evaluations, we compare Gated SAEs to baseline SAEs with 50% more learned features. We show the results for GELU-1L in  <Ref> and the results for Pythia-2.8B and Gemma-7B in <Ref>. In <Ref> (<Ref>), at all sites tested, Gated SAEs are a Pareto improvement over regular SAEs. In some cases in <Ref> and <ref> there is a non-monotonic Pareto frontier. We attribute this to difficulties training SAEs (<Ref>).





 §.§ Shrinkage



As described in <ref>, the L1 sparsity penalty used to train baseline SAEs causes feature activations to be systematically underestimated, a phenomenon called shrinkage. Since this in turn shrinks the reconstructions produced by the SAE decoder, we can observe the extent to which a trained SAE is affected by shrinkage by measuring the average norm of its reconstructions.

Concretely, the metric we use is the relative reconstruction bias,

    γ := _γ'𝔼_𝐱∼𝒟[𝐱̂_SAE(𝐱) - γ'𝐱_2^2].

γ^-1 is the optimum multiplicative factor by which an SAE's reconstructions should be rescaled in order to minimise the L2 reconstruction loss; γ=1 for an unbiased SAE and γ<1 when there's shrinkage.[We have defined γ this way round so that γ<1 intuitively corresponds to shrinkage.] Explicitly solving the optimization problem in <ref>, the relative reconstruction bias can be expressed analytically in terms of the average SAE reconstruction loss, the average norm of input activations and the average norm of SAE reconstructions, making γ easy to compute and track during training:

    γ = √(𝔼_𝐱∼𝒟[𝐱̂_SAE(𝐱)_2^2]/𝔼_𝐱∼𝒟[𝐱_2^2] - 𝔼_𝐱∼𝒟[𝐱̂_SAE(𝐱) - 𝐱_2^2]).


As shown in <Ref>, Gated SAEs' reconstructions are unbiased, with γ≈1, whereas baseline SAEs exhibit shrinkage (γ < 1), with the impact of shrinkage getting worse as the L1 coefficient λ increases (and L0 consequently decreases). In <Ref> we show that this result generalizes to Pythia-2.8B.





 §.§ Manual Interpretability Scores





  §.§.§ Experimental Methodology

While we believe that the metrics we have investigated above convey meaningful information about an SAE's quality, they are only imperfect proxies.
As of now, there is no consensus on how to gauge the degree to which a learned feature is `interpretable'. To gain a more qualitative understanding of the difference between the learned dictionary feature, we conduct a blinded human rater experiment, in which we rated the interpretability of a set of randomly sampled features.

We study a variety of SAEs from different layers and sites.

For Pythia-2.8B we had 5 raters, who each rated one feature from baseline and Gated SAEs trained on each (Site, Layer) pair from <Ref>, for a total of 150 features.
For Gemma-7B we had 7 raters; one rated 2 features each, and the rest 1 feature each, from baseline or Gated SAEs trained on each (Site, Layer) pair from <Ref>, for a total of 192 features.

In both cases, the raters were shown the features in random order, without revealing what SAE, site[Except due to a debugging issue, Gemma attention SAEs were rated separately, so raters were not blind to that.], or layer they came from. To assess a feature, the rater needed to decide whether there is an explanation of the feature's behavior, in particular for its highest activating examples.
The rater then entered that explanation (if applicable) and selected whether the feature is interpretable (`Yes'), uninterpretable (`No') or maybe interpretable (`Maybe'). As an interface we use an open source SAE visualizer library <cit.>.



  §.§.§ Statistical Analysis


To test whether Gated SAEs may be more interpretable and estimate the difference, we pair our datapoints according to all covariates (model, layer, site, rater); this lets us control for all of them without making any parametric assumptions, and thus reduces variance in the comparison. We use a one-sided paired Wilcoxon-Pratt signed-rank test, and provide a 90% BCa bootstrap confidence interval for the mean difference between Baseline and Gated labels, where we count `No' as 0, `Maybe' as 1, and `Yes' as 2. Overall the test of the null hypothesis that Gated SAEs are at most as interpretable as Baseline SAEs gets p=.060 (estimate .13, mean difference CI [0, .26]). This breaks down into p=.15 on just the Pythia-2.8B data (mean difference CI [-.07, .33]), and p=.13 on just the Gemma-7B data (mean difference CI [-.04, .29]).

A Mann-Whitney U rank test on the label differences, comparing results on the two models, fails to reject (p=.95) the null hypothesis that they're from the same distribution; the same test directly on the labels similarly fails to reject (p=.84) the null hypothesis that they're similarly interpretable overall.

The contingency tables used for these results are shown in <Ref>. The overall conclusion is that, while we can't definitively say the Gated SAE features are more interpretable than those from the Baseline SAEs, they are at least comparable. We provide more analysis of how these break down by site and layer in <Ref>.





§ WHY DO GATED SAES IMPROVE SAE TRAINING?



In this section we describe an ablation study that reveals the important parts of Gated SAE training (<Ref>) and benchmark Gated SAEs against a closely related approach to resolving shrinkage (<Ref>).



 §.§ Ablation Study



In this section, we vary several parts of the Gated SAE training methodology (<Ref>) to gain insight into which aspects of the training are required for the observed improvement in performance. Gated SAEs differ from baseline SAEs in many respect, making it easy to incorrectly attribute the performance gains to spurious details without a careful ablation study. <Ref> shows Pareto frontiers for these variations and below which we describe each variation in turn and discuss our interpretation of the results.





  * Unfreeze decoder: Here we unfreeze the decoder weights in ℒ_aux – i.e. allow this auxiliary task to update the decoder weights in addition to training 𝐟_gate's parameters. Although this (slightly) simplifies the loss, there is a reduction in performance, providing evidence in support of the hypothesis that it is beneficial to limit the impact of the L1 sparsity penalty to just those parameters in the SAE that need it – i.e. those used to detect which features are active.

  * No : Here we remove the  scaling parameter in <ref>, effectively setting it to zero (so that we multiply by e^0=1); this further ties 𝐟_gate's and 𝐟_mag's parameters together. With this change, the two encoder sublayers' preactivations can at most differ by an elementwise shift.[Because the two biases  and  can still differ.] There is a slight drop in performance, suggesting  contributes somewhat (but not critically) to the improved performance of the Gated SAE.

  * Untied encoders: Here we check whether our choice to share the majority of parameters between the two encoders has meaningfully hurt performance, by training Gated SAEs with gating and ReLU encoder parameters completely untied. Despite the greater expressive power of an untied encoder, we see no improvement in performance – in fact a slight deterioration. This suggests our tying scheme (<ref>) – where encoder directions are shared, but magnitudes and biases aren't – is effective at capturing the advantages of using a gated SAE while avoiding the 50% increase in parameter count and inference-time compute of using an untied SAE.




 §.§ Is it sufficient to just address shrinkage?



As explained in <ref>, SAEs trained with the baseline architecture and L1 loss systematically underestimate the magnitudes of latent features' activations (i.e. shrinkage). Gated SAEs, through modifications to their architecture and loss function, overcome these limitations, thereby addressing shrinkage.

It is natural to ask to what extent the performance improvement of Gated SAEs is solely attributable to addressing shrinkage. Although addressing shrinkage would – all else staying equal – improve reconstruction fidelity, it is not the only way to improve SAEs' performance: for example, gated SAEs could also improve upon baseline SAEs by learning better encoder directions (for estimating when features are active and their magnitudes) or by learning better decoder directions (i.e. better dictionaries for reconstructing activations).

In this section, we try to answer this question by comparing Gated SAEs trained as described in <ref> with an alternative (architecturally equivalent) approach that also addresses shrinkage, but in a way that uses frozen encoder and decoder directions from a baseline SAE of equal dictionary size.[Concretely, we do this by training baseline SAEs, freezing their weights, and then learning additional rescale and shift parameters (similar to <cit.>) to be applied to the (frozen) encoder pre-activations before estimating feature magnitudes.] Any performance improvement over baseline SAEs obtained by this alternative approach (which we dub “baseline + rescale & shift”) can only be due to better estimations of active feature magnitudes, since by construction an SAE parameterised by “baseline + rescale & shift” shares the same encoder and decoder directions as a baseline SAE.



As shown in <ref>, although resolving shrinkage only (“baseline + rescale & shift”) does improvement baseline SAEs' performance a little, a significant gap remains with respect to the performance of gated SAEs. This suggests that the benefit of the gated architecture and loss comes from learning better encoder and decoder directions, not just from overcoming shrinkage. In <ref> we explore further how Gated and baseline SAEs' decoders differ by replacing their respective encoders with an optimization algorithm at inference time.


§ RELATED WORK



Mechanistic Interpretability. We hope that our improvements to Sparse Autoencoders are helpful for mechanistic interpretability research. Recent mechanistic interpretability work has found recurring components in small and large LMs <cit.>, identified computational subgraphs that carry out specific tasks in small LMs (circuits; <cit.>) and reverse-engineered how toy tasks are carried out in small transformers <cit.>. Limitations of existing work include (i) how they only study narrow subsets of the natural language training distribution are studied (though see <cit.>) and (ii) current work has not explained how frontier language models function mechanistically <cit.>. SAEs may be key to explaining model behaviour across the whole training distribution <cit.> and are trained without supervision, which may enable future work to explain how larger models function on broader tasks.

Classical Dictionary Learning. Our work builds on a large amount of research that precedes transformers, and even deep learning. For example, sparse coding <cit.> studies how discrete and continuous representations can involve more representations than basis vectors, like our setup in <Ref>, and sparse representations are also studied in neuroscience <cit.>. Further, shrinkage (<Ref>) is built into the Lasso <cit.> and well-studied in statistical learning <cit.>. One dictionary learning algorithm, k-SVD <cit.> also uses two stages to learn a dictionary like Gated SAEs.

Dictionary Learning in Language Models. Early work into applying Dictionary Learning to LMs include <cit.> (on a GPT-2-like model), <cit.> (on a BERT model), <cit.> (with discrete features, and during LM pretraining) and <cit.> (on a small Pythia model). <cit.>'s work later provided a widely-scoped analysis of SAEs trained on a 1L model, evaluating the loss when splicing the SAE into the forward pass (<Ref>), evaluating the impact of learned features on LM rollouts, and visualizing and interpreting all learned features with autointerpretability <cit.>. Following this work, other researchers have extended SAE training to attention layer outputs <cit.> and residual stream states <cit.>.

Dictionary Learning's Limitations and Improvements. <cit.> raised awareness of shrinkage (<Ref>) and proposed addressing this via decoder finetuning. A difficulty with this approach is that it is not possible to fine tune all the SAEs parameters in this way without losing sparsity and/or interpretability of feature directions. This limits the extent to which fine-tuning can remove the biases baked into the SAEs parameters during L1-based pre-training. Gated SAEs address this issue (<Ref>). <cit.> stress-test how useful SAEs are, and find success but also rely on methods that leave many error nodes in their computational subgraphs, which represent the difference between SAE reconstructions and the ground truth. A series of updates to the work in <cit.> have also proposed SAE training methodology improvements <cit.>. In parallel to our work, <cit.> finds early improvements with a similar Jump ReLU <cit.> architecture change to SAEs, but with a different loss function, and without addressing the problems of L1.

Disentanglement <cit.> aims to learn representations that separate out distinct, independent `factors of variation' of the underlying data generating process.
This is somewhat similar to our aims with dictionary learning, as we want to separate an activation vector into distinct, sparse factors of variation (weights on feature directions), although the dictionary elements are not completely independent, as it may not be possible to accurately represent two features simultaneously due to interference between non-orthogonal dictionary features.
Methods explicitly motivated by learning a disentangled representation typically enforce a prior structure on the learned representation, typically that features are aligned with the basis of a latent space <cit.>.
In contrast, in our work we focus on the representation space of a pre-trained language model, rather than trying to learn a representation directly from data, and enforce a different prior structure, of decomposition into a sparse linear combination of an overcomplete basis.
In a sense, our work proceeds from the theory that language models have succeeded in learning a disentangled representation of the data with a particular structure, which we are trying to recover.




§ CONCLUSION



In this work we introduced Gated SAEs (<Ref>) which are a Pareto improvement in terms of reconstruction quality and sparisty compared to baseline SAEs (<Ref>), and are comparably interpretable (<Ref>). We showed via an ablation study that every key part of the Gated SAE methodology was necessary for strong performance (<Ref>). This represents significant progress on improving Dictionary Learning in LLMs – at many sites, Gated SAEs require half the L0 to achieve the same loss recovered (<Ref>). This is likely to improve work that uses SAEs to steer language models <cit.>, interpret circuits <cit.>, or understand language model components across the full distribution <cit.>.

Limitations. Our work, like all sparse autoencoder research, is motivated by several assumptions about the sparsity and linearity of computation in Large Language Models (<Ref>). If these assumptions are false, our work may still be useful (see footnote 1), but we may be making incorrect conclusions from work using SAEs, since they bake in the sparsity and linearity assumptions. Separately, our work complicates SAE training with a more complex encoder.

One worry about increasing the expressivity of sparse autoencoders is that they will overfit when reconstructing activations <cit.>, since the underlying model only uses simple MLPs and attention heads, and in particular lacks discontinuities such as step functions. Overall we do not see evidence for this. Our evaluations use held-out test data and we check for interpretability manually. But these evaluations are not totally comprehensive: for example, they do not test that the dictionaries learned contain causally meaningful intermediate variables in the model's computation. The discontinuity in particular introduces issues with methods like integrated gradients <cit.> that discretely approximate a path integral, as applied to SAEs by <cit.>.

Finally, it could be argued that some of the performance gap between Gated and baseline SAEs could be closed by inexpensive inference-time interventions that prune the many low activating features that tend to appear in baseline SAEs – because baseline SAEs don't have a thresholding mechanism like Gated SAEs do (<ref>). Without such interventions, these low activating features increase baseline SAEs' L0 at a given loss recovered without contributing much to reconstruction (due to low magnitude), and with unclear impact on interpretability.

Future work. Future work could verify that Gated SAEs continue to improve dictionary learning beyond 7B base LLMs, such as by extending to larger chat models, or even to multimodal or Mixture-of-Experts models. Alternatively, work could look into the features learned by Gated and baseline SAEs and determine whether the architectures have differences in inductive biases beyond those we noted in this work. We expect it may be possible to further improve Gated SAEs' performance through additional tweaks to the architecture and training procedure. Finally, we would be most excited to work on using dictionary learning techniques to further interpretability in general, such as to improve circuit finding <cit.> or steering <cit.> in language models, and hope that Gated SAEs can serve to accelerate such work.



§ ACKNOWLEDGEMENTS


We would like to thank Romeo Valentin for conversations that got us thinking about k-SVD in the context of SAEs, which inspired part of our work. Additionally, we are grateful for Vladimir Mikulik's detailed feedback on a draft of this work which greatly improved our presentation, and Nicholas Sonnerat's work on our codebase and help with feature labelling. We would also like to thank Glen Taggart who found in parallel work <cit.> that a similar method gave improvements to SAE training, helping give us more confidence in our results.



§ AUTHOR CONTRIBUTIONS


Senthooran Rajamanoharan developed the Gated SAE architecture and training methodology, inspired by discussions with Lewis Smith on the topic of shrinkage. Arthur Conmy and Senthooran Rajamanoharan performed the mainline experiments in <ref> and <ref> and led the writing of all sections of the paper. Tom Lieberum implemented the manual interpretability study of <ref>, which was designed and analysed by János Kramár. Tom Lieberum also created <ref>. Lewis Smith contributed <ref> and Neel Nanda contributed <ref>. Our SAE codebase was designed by Vikrant Varma who implemented it with Tom Lieberum, and was scaled to Gemma by Arthur Conmy, with contributions from Senthooran Rajamanoharan and Lewis Smith. János Kramár built most of our underlying interpretability infrastructure. Rohin Shah and Neel Nanda edited the manuscript and provided leadership and advice throughout the project.




§ APPENDIX





§ INFERENCE-TIME OPTIMIZATION



The task SAEs perform can be split into two sub-tasks: sparse coding, or learning a set of features from a dataset, and sparse approximation, where a given datapoint is approximated as a sparse linear combination of these features.
The decoder weights are the set of learned features, and the mapping represented by the encoder is a sparse approximation algorithm.
Formally, sparse approximation is the problem of finding a vector α that minimises;

    α = min𝐱 - 𝐃α^2_2  s.t.  α_0 < γ

i.e. that best reconstructs the signal 𝐱 as a linear combination of vectors in a dictionary 𝐃, subject to a constraint on the L0 pseudo-norm on α. 
Sparse approximation is a well studied problem, and SAEs are a weak sparse approximation algorithm.
SAEs, at least in the formulation conventional in dictionary learning for language models, in fact solve a slightly more restricted version of this problem where the weights α on each feature are constrained to be non-negative, leading to the related problem 

    α = min𝐱 - 𝐃α^2_2   s.t.  α_0 < γ, α > 0


In this paper, we do not explore using more powerful algorithms for sparse coding.
This is partly because we are using SAEs not just to recover a sparse reconstruction of activations of a LM; ideally we hope that the learned features will coincide with the linear representations actually used by the LM, under the superposition hypothesis.
Prior work <cit.> has argued that SAEs are more likely to recover these due to the correspondence between the SAE encoder and the structure of the network itself; the argument is that it is implausible that the network can make use of features which can only be recovered from the vector via an iterative optimisation algorithm, whereas the structure of the SAE means that it can only find features whose presence can be predicted well by a simple linear mapping.
Whether this is true remains, in our view, an important question for future work, but we do not address it in this paper.

In this section we discuss some results obtained by using the dictionaries learned via SAE training, but replacing the encoder with a different sparse approximation algorithm at inference time.
This allows us to compare the dictionaries learned by different SAE training regimes independently of the quality of the encoder.
It also allows us to examine the gap between the sparse reconstruction performed by the encoder against the baseline of a more powerful sparse approximation algorithm.
As mentioned, for a fair comparison to the task the encoder is trained for, it is important to solve the sparse approximation problem of <ref>, rather than the more conventional formulation of <ref>, but most sparse approximation algorithms can be modified to solve this with relatively minor changes.


Solving <ref> exactly is equivalent to integer linear programming, and is NP hard.
The integer linear programs in question would be large, as our SAE decoders routinely have hundreds of thousands of features, and solving them to guaranteed optimality would likely be intractable.
Instead, as is commonly done, we use iterative greedy algorithms to find an approximate solution.
While the solution found by these sparse approximation algorithms is not guaranteed to be the global optimum, these are significantly more powerful than the SAE encoder, and we feel it is acceptable in practice to treat them as an upper bound on possible encoder performance.

For all results in this section, we use gradient pursuit, as described in <cit.>, as our inference time optimisation (ITO) algorithm.
This algorithm is a variant of orthogonal matching pursuit <cit.> which solves the orgothonalisation of the residual to the span of chosen dictionary elements approximately at every step rather than exactly, but which only requires matrix multiplies rather than matrix solves and is easier to implement on accelerators as a result.
It is possibly not crucial for performance that our optimisation algorithm be implementable on TPUs, but being able to avoid a host-device transfer when splicing this into the forward pass allowed us to re-use our existing evaluation pipeline with minimal changes.

When we use a sparse approximation algorithm at test time, we simply use the decoder of a trained SAE as a dictionary, ignoring the encoder.
This allows us to sweep the target sparsity at test time without retraining the model, meaning that we can plot an entire Pareto frontier of loss recovered against sparsity for a single decoder, as in done in <Ref>.


<Ref> compares the loss recovered when using ITO for a suite of SAEs decoders trained with both methods at three different test time L0 thresholds.
This graph shows a somewhat surprising result; while Gated SAEs learn better decoders generally, and often achieve the best loss recovered using ITO close to their training sparsity, SAE decoders are often outperformed by decoders which achieved a higher test time L0; it's better to do ITO with a target L0 of 10 with an decoder with an achieved L0 of around 100 during training than one which was actually trained with this level of sparsity.
For instance, the left hand panel in <Ref> shows that SAEs with a training L0 of 100 are better than those with an L0 of around 10 at almost every sparsity level in terms of ITO reconstruction. 
However, gated SAE dictionaries have a small but real advantage over standard SAEs in terms of loss recovered at most target sparsity levels, suggesting that part of the advantage of gated SAEs is that they learn better dictionaries as well as addressing issues with shrinkage.
However, there are some subtleties here; for example, we find that baseline SAEs trained with a lower sparsity penalty (higher training L0) often outperform more sparse baseline SAEs according to this measure, and the best performing baseline SAE (L0 ≈ 99) is comparable to the best performing Gated SAE (L0 ≈ 20).




<Ref> compares the Pareto frontiers of a baseline model and a gated model to the Pareto frontier of an ITO sweep of the best performing dictionary of each.
Note that, while the Pareto curve of the baseline dictionary is formed by several models as each encoder is specialised to a given sparsity level, as mentioned, ITO lets us plot a Pareto frontier by sweeping the target sparsity with a single dictionary; here we plot only the best performing dictionary from each model type to avoid cluttering the figure.
This figure suggests that the performance gap between the encoder and using ITO is smaller for the gated model. Interestingly, this cannot solely be explained by addressing shrinkage, as we demonstrate by experimenting with a baseline model which learns a rescale and shift with a frozen encoder and decoder directions. 





§ MORE LOSS RECOVERED / L0 PARETO FRONTIERS



In <Ref> we show that Gated SAEs outperform baseline SAEs. In <Ref> we show that Gated SAEs ourperform baseline SAEs at all but one MLP output or residual stream site that we tested on.

In <Ref> at the attention output pre-linear site at layer 27, loss recovered is bigger than 1.0. On investigation, we found that the dataset used to train the SAE was not identical to Gemma's pretraining dataset, and at this site it was possible to mean ablate this quantity and decrease loss – explaining why SAE reconstructions had lower loss than the original model.







§ FURTHER SHRINKAGE PLOTS



In <Ref>, we show that Gated SAEs resolve shrinkage (as measured by relative reconstruction bias (<Ref>)) in Pythia-2.8B.





§ TRAINING AND EVALUATION: HYPERPARAMETERS AND OTHER DETAILS.





 §.§ Training




  §.§.§ General training details


Other minor details of SAE training are:



  * Training data. We use activations from hundreds of millions to billions of activations from LM forward passes as input data to the SAE. Following <cit.>, we use a shuffled buffer of these activations, so that optimization steps don't use data from highly correlated activations.[In contrast to earlier findings <cit.>, we found that when using Pythia-2.8B's activations from sequences of length 2048, rather than GELU-1L's activations from sequences of length 128, it was important to shuffle the 10^6 length activation buffer used to train our SAEs.] 


  * Resampling. We used resampling, a technique which at a high-level reinitializes features that activate extremely rarely on SAE inputs periodically throughout training. We mostly follow the approach described in the `Neuron Resampling' appendix of <cit.>, except we reapply learning rate warm-up after each resampling event, reducing learning rate to 0.1x the ordinary value, and, increasing it with a cosine schedule back to the ordinary value over the next 1000 training steps.


  * Optimizer hyperparameters. We use the Adam optimizer with β_2 = 0.999 and β_1 = 0.0, following <cit.>, as we also find this to be a slight improvement to training. We use a learning rate of 0.001 for baseline SAEs and 0.0003 for Gated SAEs, and use a learning rate warm-up.


  * Decoder weight norm constraints. <cit.> suggest constraining columns to have at most unit norm (instead of exactly unit norm), which can help distinguish between productive and unproductive feature directions (although it should have no systematic impact on performance). However, we follow the original approach of constraining columns to have exact unit norms in this work for the sake of simplicity.




  §.§.§ Experiment-specific training details



    

  * We use learning rate 0.0003 for all Gated SAE experiments, and 0.001 for all baseline SAE experiments (we use a higher learning rate since our baseline loss function implementation divides the reconstruction loss by 𝔼 ||x||_2, motivated by better hyperparameter transfer, and we didn't use this normalization for Gated experiments).


  * We generate activations from sequences of length 128 for GELU-1L, 2048 for Pythia-2.8B and 1024 for Gemma-7B.


  * We use a batch size of 4096 for all runs. We use 300,000 training steps for GELU-1L and Gemma-7B runs, and 400,000 steps for Pythia-2.8B runs. 



  §.§.§ Lessons learned scaling SAEs




  * Learned feature death is unpredictable. In <Ref> we show that there are few patterns that can be gleaned from staring at which runs have high numbers of dead learned features (called dead neurons in <cit.>)


  * Resampling makes hyperparameter sweeps difficult. We found that resampling caused L0 and loss recovered to increase, similar to <cit.>.


  * Training appears to converge earlier than expected. We found that we did not need 20B tokens as in <cit.>, as generally resampling had stopped causing gains and loss curves plateaued after just over one billion tokens.







 §.§ Evaluation



We evaluated the models on over a million held-out tokens. We also removed one Gated SAE extreme point (with >400 L0) from <Ref>, but show it in <Ref>.





§ EQUIVALENCE BETWEEN GATED ENCODER WITH TIED WEIGHTS AND LINEAR ENCODER WITH NON-STANDARD ACTIVATION FUNCTION











In this section we show under the weight sharing scheme defined in <ref>, a gated encoder as defined in <ref> is equivalent to a linear layer with a non-standard (and parameterised) activation function.

Without loss of generality, consider the case of a single latent feature (M = 1) and set the pre-encoder bias to zero. In this case, the gated encoder is defined as

    f̃(𝐱) := 1_·𝐱  +  > 0 ReLU(·𝐱 + )

and the weight sharing scheme becomes

    :=

with a non-negative parameter ≡exp().

Substituting <ref> into <ref> and re-arranging, we can re-express f̃(𝐱) as a single linear layer

    f̃(𝐱) := σ_-(·𝐱 + )

with the parameterised activation function

    σ_θ(z) := 1_z > θ ReLU(z).

called JumpReLU in a different context <cit.>. <ref> illustrates the shape of this activation function.



§ A TOY SETTING WHERE JUMP RELU SAES OUTPERFORM BASELINE SAES





An additional reason that Gated SAEs may perform baseline SAEs, beyond resolving shrinkage, is that they are a more expressive architecture: at inference time, they're equivalent to an SAE with the ReLU replaced by a potentially discontinuous Jump ReLU <cit.>, as shown in <ref>. In this appendix we present a toy setting where a Jump ReLU is a more natural activation function for sparsely reconstructing activations than a ReLU. We adopt a more intuitive and less formal style, for pedagogical purposes. 

Consider a sparsely activating but continuously valued feature X, and a fixed unit encoder direction . If X is off (X=0), the projection of activations 𝐚 onto  is normally distributed as 𝒩(0, 1) (simulating noise from non-orthogonal features firing); if X is on (X>0) then the projection is normally distributed as 𝒩(2, 1/4). Suppose further that X is on with 50% probability. So a ·v̂∼1_X  is on(0.5 Z_1 + 2) + 1_X  is off Z_2. Where A is the activation and Z_1, Z_2 ∼𝒩(0, 1^2) are standard 1D Gaussians. The empirical distribution is shown in Figure <ref>.

Consider the problem of fitting a ReLU encoder to this. With fixed encoder unit direction v̂, the encoder is parametrised by a bias b and magnitude m, where a →max(m a ·v̂ + b, 0). b can be reparametrised in terms of a threshold t = -b/m, so it is now a →1_a·v̂ > t m(a·v̂-t). Geometrically, we set some threshold t, a vertical line. Everything to the left is set to zero, and everything to the right is set to some multiple of the distance from the line. 

This illuminates the core problem with ReLU SAEs: the threshold both determines whether to fire at all, and gives an origin to take the distance from if firing. The optimal reconstruction when X is on requires us to take t=0. But now we fire half the time when X is off, as a lot of the blue histogram is to the right of the green line. However, if we take a high enough threshold to exclude most blue, e.g. t=1, we now need to take the distance from t=1 too when X is on, distorting things, even if we try to correct by rescaling with m, see the blue line in Figure <ref>. 

Jump ReLUs solve this problem. Mathematically, we can parametrise a Jump ReLU, at least in the setting of Gated SAEs, as 1_(x>t) m(x-d). Geometrically, we now have two vertical lines. x=t sets the threshold: anything to the left is set to zero. x=d sets the origin point (for some d≤ t), we return the distance to d times some magnitude m. This solves our problem: we can set t=1 (the purple line), d=0 (the green line) and m=1 (no distortion correction needed), and get the blue line in Figure <ref>, a near perfect reconstruction!

Some caveats and reflections on this toy model:

    
  * The numbers t=1, m=2 are likely not the mathematically optimal solution, and are given for pedagogical purposes, but this seems unlikely to change the conceptual takeaways.
    
  * This toy model has not been empirically tested, and could be totally off. But we've found it useful for building intuition.
    
  * Why was it realistic to assume that the projection wasn't just zero when X was off? Because there are likely many other non-orthogonal features firing, due to superposition, which in aggregate creates significant interference. Indeed, a common problem when studying SAE features/other interpretable directions is that, while the tails are monosemantic, activations near zero are very noisy (see e.g. the Arabic feature in <cit.> or the sentiment feature in <cit.>). We speculate that this is a consequence of ReLU SAEs needing to choose a threshold with a mix of on and off activations (a mix of red and blue in <ref>) to minimise distortion to the tails, as L1 does not penalise incorrectly firing at small magnitudes much. We hope that Gated SAEs may have less of these issues, as they can just have a large gap between t and d.
    
  * We asserted that X was a sparsely activating but continuous feature. It's an open question how much such features actually exist in models (though at least some likely do <cit.>). Our intuition is that most features are essentially binary (e.g. "is this about basketball"), but that models track their confidences in them as coefficients of the feature directions, and that reconstructing the precise coefficients matters (otherwise, we should just discretise SAE activations at inference time!), so they can be thought of as continuous. We think understanding this better is a promising direction of future work.
    
  * In real models, the probability that X fires is likely much less than 50%! But this assumption simplified the reasoning and diagrams, without qualitatively changing much. 
    
  * We assumed that the encoder direction (v̂) was frozen, even if its magnitude was not. This was a simplifying assumption that is clearly false in Gated SAEs, and indeed, as shown in Section <ref>, their ability to choose different directions to a standard SAE is key to performance, and they outperform a standard SAE fine-tuned with Jump ReLUs. 
    
  * The main reason a standard ReLU SAE doesn't want t=0 is that this includes too many activations when X is off. But, actually, this is good for reconstruction, just bad for L1 and sparsity. Gated SAEs decouple L1 from their encoder directions, making it hard to reason clearly about whether the need for a high threshold would still apply in a hypothetical Gated SAE with standard ReLUs (though in an actual Gated SAE, the L1 crucially is still applied to t)





§ PSEUDO-CODE FOR GATED SAES AND THE GATED SAE LOSS FUNCTION








§ FURTHER ANALYSIS OF THE HUMAN INTERPRETABILITY STUDY



We perform some further analysis on the data from <Ref>, to understand the impact of different sites, layers, and raters.



 §.§ Sites


We first pose the question of whether there's evidence that the sites had different interpretability outcomes. A Friedman test across sites shows significant differences (at p=.047) between the Gated-vs-Baseline differences, though not (p=.92) between the raw labels.

Breaking down by site and repeating the Wilcoxon-Pratt one-sided tests and computing confidence intervals, we find the result on MLP outputs is strongest, with mean .40, significance p=.003, and CI [.18, .63]; this is as compared with the attention outputs (p=.47, mean .05, CI [-.16, .26]) and final residual (p=.59, mean -0.07, CI [-.28, .12]) SAEs.



 §.§ Layers


Next we test whether different layers had different outcomes. We do this separately for the 2 models, since the layers aren't directly comparable. We run 2 tests in each setting: Page's trend test (which tests for a monotone trend across layers) and the Friedman test (which tests for any difference, without any expectation of a monotone trend).

Results are presented in <Ref>; they suggest there are some significant nonmonotone differences between layers. To elucidate this, we present 90% BCa bootstrap confidence intervals of the mean raw label (where `No'=0, `Maybe'=1, `Yes'=2) and the Gated-vs-Baseline difference, per layer, in <Ref> and <Ref>, respectively.






























 §.§ Raters


In <Ref> we present test results weakly suggesting that the raters differed in their judgments. This underscores that there's still a significant subjective component to this interpretability labeling. (Notably, different raters saw different proportions of Pythia vs Gemma features, so aggregating across the models is partially confounded by that.)




