eai-sparsify 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: eai-sparsify
3
+ Version: 0.0.1
4
+ Summary: Sparsify transformers with SAEs and transcoders
5
+ License: MIT License
6
+ Keywords: interpretability,explainable-ai
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: accelerate
11
+ Requires-Dist: datasets
12
+ Requires-Dist: einops
13
+ Requires-Dist: huggingface-hub
14
+ Requires-Dist: natsort
15
+ Requires-Dist: safetensors
16
+ Requires-Dist: schedulefree
17
+ Requires-Dist: simple-parsing
18
+ Requires-Dist: torch
19
+ Requires-Dist: transformers
20
+ Provides-Extra: dev
21
+ Requires-Dist: pre-commit; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ ## Introduction
25
+ This library trains _k_-sparse autoencoders (SAEs) and transcoders on the activations of HuggingFace language models, roughly following the recipe detailed in [Scaling and evaluating sparse autoencoders](https://arxiv.org/abs/2406.04093v1) (Gao et al. 2024).
26
+
27
+ This is a lean, simple library with few configuration options. Unlike most other SAE libraries (e.g. [SAELens](https://github.com/jbloomAus/SAELens)), it does not cache activations on disk, but rather computes them on-the-fly. This allows us to scale to very large models and datasets with zero storage overhead, but has the downside that trying different hyperparameters for the same model and dataset will be slower than if we cached activations (since activations will be re-computed). We may add caching as an option in the future.
28
+
29
+ Following Gao et al., we use a TopK activation function which directly enforces a desired level of sparsity in the activations. This is in contrast to other libraries which use an L1 penalty in the loss function. We believe TopK is a Pareto improvement over the L1 approach, and hence do not plan on supporting it.
30
+
31
+ ## Loading pretrained SAEs
32
+
33
+ To load a pretrained SAE from the HuggingFace Hub, you can use the `Sae.load_from_hub` method as follows:
34
+
35
+ ```python
36
+ from sparsify import Sae
37
+
38
+ sae = Sae.load_from_hub("EleutherAI/sae-llama-3-8b-32x", hookpoint="layers.10")
39
+ ```
40
+
41
+ This will load the SAE for residual stream layer 10 of Llama 3 8B, which was trained with an expansion factor of 32. You can also load the SAEs for all layers at once using `Sae.load_many`:
42
+
43
+ ```python
44
+ saes = Sae.load_many("EleutherAI/sae-llama-3-8b-32x")
45
+ saes["layers.10"]
46
+ ```
47
+
48
+ The dictionary returned by `load_many` is guaranteed to be [naturally sorted](https://en.wikipedia.org/wiki/Natural_sort_order) by the name of the hook point. For the common case where the hook points are named `embed_tokens`, `layers.0`, ..., `layers.n`, this means that the SAEs will be sorted by layer number. We can then gather the SAE activations for a model forward pass as follows:
49
+
50
+ ```python
51
+ from transformers import AutoModelForCausalLM, AutoTokenizer
52
+ import torch
53
+
54
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B")
55
+ inputs = tokenizer("Hello, world!", return_tensors="pt")
56
+
57
+ with torch.inference_mode():
58
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B")
59
+ outputs = model(**inputs, output_hidden_states=True)
60
+
61
+ latent_acts = []
62
+ for sae, hidden_state in zip(saes.values(), outputs.hidden_states):
63
+ # (N, D) input shape expected
64
+ hidden_state = hidden_state.flatten(0, 1)
65
+ latent_acts.append(sae.encode(hidden_state))
66
+
67
+ # Do stuff with the latent activations
68
+ ```
69
+
70
+ For use cases beyond collecting residual stream SAE activations, we recommend PyTorch hooks ([see examples](https://gist.github.com/luciaquirke/7105708dac0cfc632d68f33c79b59e5c).)
71
+
72
+ ## Training SAEs and transcoders
73
+
74
+ To train SAEs from the command line, you can use the following command:
75
+
76
+ ```bash
77
+ python -m sparsify EleutherAI/pythia-160m <optional dataset>
78
+ ```
79
+ By default, we use the `EleutherAI/SmolLM2-135M-10B` dataset for training, but you can use any dataset from the HuggingFace Hub, or any local dataset in HuggingFace format (the string is passed to `load_dataset` from the `datasets` library).
80
+
81
+ The CLI supports all of the config options provided by the `TrainConfig` class. You can see them by running `python -m sparsify --help`.
82
+
83
+ Programmatic usage is simple. Here is an example:
84
+
85
+ ```python
86
+ import torch
87
+ from datasets import load_dataset
88
+ from transformers import AutoModelForCausalLM, AutoTokenizer
89
+
90
+ from sparsify import SaeConfig, Trainer, TrainConfig
91
+ from sparsify.data import chunk_and_tokenize
92
+
93
+ MODEL = "HuggingFaceTB/SmolLM2-135M"
94
+ dataset = load_dataset(
95
+ "EleutherAI/SmolLM2-135M-10B", split="train",
96
+ )
97
+ tokenizer = AutoTokenizer.from_pretrained(MODEL)
98
+ tokenized = chunk_and_tokenize(dataset, tokenizer)
99
+
100
+
101
+ gpt = AutoModelForCausalLM.from_pretrained(
102
+ MODEL,
103
+ device_map={"": "cuda"},
104
+ torch_dtype=torch.bfloat16,
105
+ )
106
+
107
+ cfg = TrainConfig(SaeConfig(), batch_size=16)
108
+ trainer = Trainer(cfg, tokenized, gpt)
109
+
110
+ trainer.fit()
111
+ ```
112
+
113
+ ## Finetuning SAEs
114
+
115
+ To finetune a pretrained SAE, pass its path to the `finetune` argument.
116
+
117
+ ```bash
118
+ python -m sparsify EleutherAI/pythia-160m togethercomputer/RedPajama-Data-1T-Sample --finetune EleutherAI/sae-pythia-160m-32x
119
+ ```
120
+
121
+ ## Custom hookpoints
122
+
123
+ By default, the SAEs are trained on the residual stream activations of the model. However, you can also train SAEs on the activations of any other submodule(s) by specifying custom hookpoint patterns. These patterns are like standard PyTorch module names (e.g. `h.0.ln_1`) but also allow [Unix pattern matching syntax](https://docs.python.org/3/library/fnmatch.html), including wildcards and character sets. For example, to train SAEs on the output of every attention module and the inner activations of every MLP in GPT-2, you can use the following code:
124
+
125
+ ```bash
126
+ python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act"
127
+ ```
128
+
129
+ To restrict to the first three layers:
130
+
131
+ ```bash
132
+ python -m sparsify gpt2 --hookpoints "h.[012].attn" "h.[012].mlp.act"
133
+ ```
134
+
135
+ We currently don't support fine-grained manual control over the learning rate, number of latents, or other hyperparameters on a hookpoint-by-hookpoint basis. By default, the `expansion_factor` option is used to select the appropriate number of latents for each hookpoint based on the width of that hookpoint's output. The default learning rate for each hookpoint is then set using an inverse square root scaling law based on the number of latents. If you manually set the number of latents or the learning rate, it will be applied to all hookpoints.
136
+
137
+ ## Distributed training
138
+
139
+ We support distributed training via PyTorch's `torchrun` command. By default we use the Distributed Data Parallel method, which means that the weights of each SAE are replicated on every GPU.
140
+
141
+ ```bash
142
+ torchrun --nproc_per_node gpu -m sparsify meta-llama/Meta-Llama-3-8B --batch_size 1 --layers 16 24 --k 192 --grad_acc_steps 8 --ctx_len 2048
143
+ ```
144
+
145
+ This is simple, but very memory inefficient. If you want to train SAEs for many layers of a model, we recommend using the `--distribute_modules` flag, which allocates the SAEs for different layers to different GPUs. Currently, we require that the number of GPUs evenly divides the number of layers you're training SAEs for.
146
+
147
+ ```bash
148
+ torchrun --nproc_per_node gpu -m sparsify meta-llama/Meta-Llama-3-8B --distribute_modules --batch_size 1 --layer_stride 2 --grad_acc_steps 8 --ctx_len 2048 --k 192 --load_in_8bit --micro_acc_steps 2
149
+ ```
150
+
151
+ The above command trains an SAE for every _even_ layer of Llama 3 8B, using all available GPUs. It accumulates gradients over 8 minibatches, and splits each minibatch into 2 microbatches before feeding them into the SAE encoder, thus saving a lot of memory. It also loads the model in 8-bit precision using `bitsandbytes`. This command requires no more than 48GB of memory per GPU on an 8 GPU node.
152
+
153
+ ## TODO
154
+
155
+ There are several features that we'd like to add in the near future:
156
+ - [ ] Support for caching activations
157
+ - [ ] Evaluate SAEs with KL divergence when grafted into the model
158
+
159
+ If you'd like to help out with any of these, please feel free to open a PR! You can collaborate with us in the sparse-autoencoders channel of the EleutherAI Discord.
160
+
161
+ ## Development
162
+
163
+ Run `pip install pre-commit` then `pre-commit install`.
164
+
165
+ ## Experimental features
166
+
167
+ Linear k decay schedule:
168
+
169
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --k_decay_steps 10_000```
170
+
171
+ GroupMax activation function:
172
+
173
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --activation groupmax```
174
+
175
+ End-to-end training:
176
+
177
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --loss_fn ce```
178
+
179
+ or
180
+
181
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --loss_fn kl```
@@ -0,0 +1,17 @@
1
+ eai_sparsify-0.0.1.dist-info/licenses/LICENSE,sha256=Yyd2HYK4ggjBZzBIW1EbRRCrJAe8bzSxSoeFjcZrTEk,1067
2
+ sparsify/__init__.py,sha256=R05ZbSclZIM4lxIH-Gku29PL1EIOTGzWr6zjrrBte1c,350
3
+ sparsify/__main__.py,sha256=PFDEHn8j1f3ma84cMM-5eM-KAWxrOyKmZYv_PczWC7U,5882
4
+ sparsify/config.py,sha256=F3aim-utDuq7VdUCtQJD1VUdKMjgXxBX-lJDYTJvqho,4011
5
+ sparsify/data.py,sha256=uRJymcp9py6ZOwkkdiPYKAK4JM2NMCquKvjQy0SPN4M,5603
6
+ sparsify/fused_encoder.py,sha256=6SWZG7jsuJVukr7Q4hkXkUVJZsymbzC7n0MyCHXeoMw,3513
7
+ sparsify/muon.py,sha256=kk63l53LgsJqvLYD7Poxxsr2j_ke2yK6_mv00rXXnu4,7298
8
+ sparsify/sign_sgd.py,sha256=00MT35zp0YrdEoM0znXXPmV4gtXTQtSIrqTAFSbnWK4,716
9
+ sparsify/sparse_coder.py,sha256=9OogGWuKElA7O5ZuVA037GVJZHUFf33UBzTI_qYRyMI,9207
10
+ sparsify/trainer.py,sha256=5PBAsFjAE0mBacR6eYLS-j_3dvP9UoEjk6V6Irm9lMk,26930
11
+ sparsify/utils.py,sha256=0E4kVw9Hk2GXz7QmzKZ0QsjJO_pHTRLZfojk7TZjP0Y,3226
12
+ sparsify/xformers.py,sha256=fqC5UJIlJQRdpZwcTS8VE8nvG2p4kYi-WOx1Io14UYk,7343
13
+ eai_sparsify-0.0.1.dist-info/METADATA,sha256=Gwp6buSZiy9mAMMZQ7XlTYej_rVNzVd_EbSaiq4Tjzg,8538
14
+ eai_sparsify-0.0.1.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
15
+ eai_sparsify-0.0.1.dist-info/entry_points.txt,sha256=vDwARFBst-K5tnQD-oDsqUktg7SHP4B1SEqtA4A5Gg4,51
16
+ eai_sparsify-0.0.1.dist-info/top_level.txt,sha256=-zMsquyWBNzuBZY81Uddr0jNtomYglh8G3FYNvYyzpA,9
17
+ eai_sparsify-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (78.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sparsify = sparsify.__main__:run
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 EleutherAI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ sparsify
sparsify/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ __version__ = "0.0.1"
2
+
3
+ from .config import SaeConfig, SparseCoderConfig, TrainConfig, TranscoderConfig
4
+ from .sparse_coder import Sae, SparseCoder
5
+ from .trainer import SaeTrainer, Trainer
6
+
7
+ __all__ = [
8
+ "Sae",
9
+ "SaeConfig",
10
+ "SaeTrainer",
11
+ "SparseCoder",
12
+ "SparseCoderConfig",
13
+ "Trainer",
14
+ "TrainConfig",
15
+ "TranscoderConfig",
16
+ ]
sparsify/__main__.py ADDED
@@ -0,0 +1,188 @@
1
+ import os
2
+ from contextlib import nullcontext, redirect_stdout
3
+ from dataclasses import dataclass
4
+ from datetime import timedelta
5
+ from multiprocessing import cpu_count
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ from datasets import Dataset, load_dataset
10
+ from safetensors.torch import load_model
11
+ from simple_parsing import field, parse
12
+ from transformers import (
13
+ AutoModel,
14
+ AutoModelForCausalLM,
15
+ AutoTokenizer,
16
+ BitsAndBytesConfig,
17
+ PreTrainedModel,
18
+ )
19
+
20
+ from .data import MemmapDataset, chunk_and_tokenize
21
+ from .trainer import TrainConfig, Trainer
22
+
23
+
24
+ @dataclass
25
+ class RunConfig(TrainConfig):
26
+ model: str = field(
27
+ default="HuggingFaceTB/SmolLM2-135M",
28
+ positional=True,
29
+ )
30
+ """Name of the model to train."""
31
+
32
+ dataset: str = field(
33
+ default="EleutherAI/SmolLM2-135M-10B",
34
+ positional=True,
35
+ )
36
+ """Path to the dataset to use for training."""
37
+
38
+ split: str = "train"
39
+ """Dataset split to use for training."""
40
+
41
+ ctx_len: int = 2048
42
+ """Context length to use for training."""
43
+
44
+ # Use a dummy encoding function to prevent the token from being saved
45
+ # to disk in plain text
46
+ hf_token: str | None = field(default=None, encoding_fn=lambda _: None)
47
+ """Huggingface API token for downloading models."""
48
+
49
+ revision: str | None = None
50
+ """Model revision to use for training."""
51
+
52
+ load_in_8bit: bool = False
53
+ """Load the model in 8-bit mode."""
54
+
55
+ max_examples: int | None = None
56
+ """Maximum number of examples to use for training."""
57
+
58
+ resume: bool = False
59
+ """Whether to try resuming from the checkpoint present at `checkpoints/run_name`."""
60
+
61
+ text_column: str = "text"
62
+ """Column name to use for text data."""
63
+
64
+ shuffle_seed: int = 42
65
+ """Random seed for shuffling the dataset."""
66
+
67
+ data_preprocessing_num_proc: int = field(
68
+ default_factory=lambda: cpu_count() // 2,
69
+ )
70
+ """Number of processes to use for preprocessing data"""
71
+
72
+
73
+ def load_artifacts(
74
+ args: RunConfig, rank: int
75
+ ) -> tuple[PreTrainedModel, Dataset | MemmapDataset]:
76
+ if args.load_in_8bit:
77
+ dtype = torch.float16
78
+ elif torch.cuda.is_bf16_supported():
79
+ dtype = torch.bfloat16
80
+ else:
81
+ dtype = "auto"
82
+
83
+ # End-to-end training requires a model with a causal LM head
84
+ model_cls = AutoModel if args.loss_fn == "fvu" else AutoModelForCausalLM
85
+ model = model_cls.from_pretrained(
86
+ args.model,
87
+ device_map={"": f"cuda:{rank}"},
88
+ quantization_config=(
89
+ BitsAndBytesConfig(load_in_8bit=args.load_in_8bit)
90
+ if args.load_in_8bit
91
+ else None
92
+ ),
93
+ revision=args.revision,
94
+ torch_dtype=dtype,
95
+ token=args.hf_token,
96
+ )
97
+
98
+ # For memmap-style datasets
99
+ if args.dataset.endswith(".bin"):
100
+ dataset = MemmapDataset(args.dataset, args.ctx_len, args.max_examples)
101
+ else:
102
+ # For Huggingface datasets
103
+ try:
104
+ dataset = load_dataset(
105
+ args.dataset,
106
+ split=args.split,
107
+ # TODO: Maybe set this to False by default? But RPJ requires it.
108
+ trust_remote_code=True,
109
+ )
110
+ except ValueError as e:
111
+ # Automatically use load_from_disk if appropriate
112
+ if "load_from_disk" in str(e):
113
+ dataset = Dataset.load_from_disk(args.dataset, keep_in_memory=False)
114
+ else:
115
+ raise e
116
+
117
+ assert isinstance(dataset, Dataset)
118
+ if "input_ids" not in dataset.column_names:
119
+ tokenizer = AutoTokenizer.from_pretrained(args.model, token=args.hf_token)
120
+ dataset = chunk_and_tokenize(
121
+ dataset,
122
+ tokenizer,
123
+ max_seq_len=args.ctx_len,
124
+ num_proc=args.data_preprocessing_num_proc,
125
+ text_key=args.text_column,
126
+ )
127
+ else:
128
+ print("Dataset already tokenized; skipping tokenization.")
129
+
130
+ print(f"Shuffling dataset with seed {args.shuffle_seed}")
131
+ dataset = dataset.shuffle(args.shuffle_seed)
132
+
133
+ dataset = dataset.with_format("torch")
134
+ if limit := args.max_examples:
135
+ dataset = dataset.select(range(limit))
136
+
137
+ return model, dataset
138
+
139
+
140
+ def run():
141
+ local_rank = os.environ.get("LOCAL_RANK")
142
+ ddp = local_rank is not None
143
+ rank = int(local_rank) if ddp else 0
144
+
145
+ if ddp:
146
+ torch.cuda.set_device(int(local_rank))
147
+
148
+ # Increase the default timeout in order to account for slow downloads
149
+ # and data preprocessing on the main rank
150
+ dist.init_process_group(
151
+ "nccl", device_id=torch.device(rank), timeout=timedelta(weeks=1)
152
+ )
153
+
154
+ if rank == 0:
155
+ print(f"Using DDP across {dist.get_world_size()} GPUs.")
156
+
157
+ args = parse(RunConfig)
158
+
159
+ # Prevent ranks other than 0 from printing
160
+ with nullcontext() if rank == 0 else redirect_stdout(None):
161
+ # Awkward hack to prevent other ranks from duplicating data preprocessing
162
+ if not ddp or rank == 0:
163
+ model, dataset = load_artifacts(args, rank)
164
+ if ddp:
165
+ dist.barrier()
166
+ if rank != 0:
167
+ model, dataset = load_artifacts(args, rank)
168
+ dataset = dataset.shard(dist.get_world_size(), rank)
169
+
170
+ print(f"Training on '{args.dataset}' (split '{args.split}')")
171
+ print(f"Storing model weights in {model.dtype}")
172
+
173
+ trainer = Trainer(args, dataset, model)
174
+ if args.resume:
175
+ trainer.load_state(f"checkpoints/{args.run_name}" or "checkpoints/unnamed")
176
+ elif args.finetune:
177
+ for name, sae in trainer.saes.items():
178
+ load_model(
179
+ sae,
180
+ f"{args.finetune}/{name}/sae.safetensors",
181
+ device=str(model.device),
182
+ )
183
+
184
+ trainer.fit()
185
+
186
+
187
+ if __name__ == "__main__":
188
+ run()
sparsify/config.py ADDED
@@ -0,0 +1,128 @@
1
+ from dataclasses import dataclass
2
+ from functools import partial
3
+ from typing import Literal
4
+
5
+ from simple_parsing import Serializable, list_field
6
+
7
+
8
+ @dataclass
9
+ class SparseCoderConfig(Serializable):
10
+ """
11
+ Configuration for training a sparse coder on a language model.
12
+ """
13
+
14
+ activation: Literal["groupmax", "topk"] = "topk"
15
+ """Activation function to use."""
16
+
17
+ expansion_factor: int = 32
18
+ """Multiple of the input dimension to use as the sparse coder dimension."""
19
+
20
+ normalize_decoder: bool = True
21
+ """Normalize the decoder weights to have unit norm."""
22
+
23
+ num_latents: int = 0
24
+ """Number of latents to use. If 0, use `expansion_factor`."""
25
+
26
+ k: int = 32
27
+ """Number of nonzero features."""
28
+
29
+ multi_topk: bool = False
30
+ """Use Multi-TopK loss."""
31
+
32
+ skip_connection: bool = False
33
+ """Include a linear skip connection."""
34
+
35
+ transcode: bool = False
36
+ """Whether we want to predict the output of a module given its input."""
37
+
38
+
39
+ # Support different naming conventions for the same configuration
40
+ SaeConfig = SparseCoderConfig
41
+ TranscoderConfig = partial(SparseCoderConfig, transcode=True)
42
+
43
+
44
+ @dataclass
45
+ class TrainConfig(Serializable):
46
+ sae: SparseCoderConfig
47
+
48
+ batch_size: int = 32
49
+ """Batch size measured in sequences."""
50
+
51
+ grad_acc_steps: int = 1
52
+ """Number of steps over which to accumulate gradients."""
53
+
54
+ micro_acc_steps: int = 1
55
+ """Chunk the activations into this number of microbatches for training."""
56
+
57
+ loss_fn: Literal["ce", "fvu", "kl"] = "fvu"
58
+ """Loss function to use for training the sparse coders.
59
+
60
+ - `ce`: Cross-entropy loss of the final model logits.
61
+ - `fvu`: Fraction of variance explained.
62
+ - `kl`: KL divergence of the final model logits w.r.t. the original logits.
63
+ """
64
+
65
+ optimizer: Literal["adam", "muon", "signum"] = "signum"
66
+ """Optimizer to use."""
67
+
68
+ lr: float | None = None
69
+ """Base LR. If None, it is automatically chosen based on the number of latents."""
70
+
71
+ lr_warmup_steps: int = 1000
72
+ """Number of steps over which to warm up the learning rate. Only used if
73
+ `optimizer` is `adam`."""
74
+
75
+ k_decay_steps: int = 0
76
+ """Number of steps over which to decay the number of active latents. Starts at
77
+ input width * 10 and decays to k. Experimental feature."""
78
+
79
+ auxk_alpha: float = 0.0
80
+ """Weight of the auxiliary loss term."""
81
+
82
+ dead_feature_threshold: int = 10_000_000
83
+ """Number of tokens after which a feature is considered dead."""
84
+
85
+ hookpoints: list[str] = list_field()
86
+ """List of hookpoints to train sparse coders on."""
87
+
88
+ init_seeds: list[int] = list_field(0)
89
+ """List of random seeds to use for initialization. If more than one, train a sparse
90
+ coder for each seed."""
91
+
92
+ layers: list[int] = list_field()
93
+ """List of layer indices to train sparse coders on."""
94
+
95
+ layer_stride: int = 1
96
+ """Stride between layers to train sparse coders on."""
97
+
98
+ distribute_modules: bool = False
99
+ """Store one copy of each sparse coder, instead of copying them across devices."""
100
+
101
+ save_every: int = 1000
102
+ """Save sparse coders every `save_every` steps."""
103
+
104
+ save_best: bool = False
105
+ """Save the best checkpoint found for each hookpoint."""
106
+
107
+ finetune: str | None = None
108
+ """Finetune the sparse coders from a pretrained checkpoint."""
109
+
110
+ log_to_wandb: bool = True
111
+ run_name: str | None = None
112
+ wandb_log_frequency: int = 1
113
+
114
+ save_dir: str = "checkpoints"
115
+
116
+ def __post_init__(self):
117
+ """Validate the configuration."""
118
+ if self.layers and self.layer_stride != 1:
119
+ raise ValueError("Cannot specify both `layers` and `layer_stride`.")
120
+
121
+ if self.distribute_modules and self.loss_fn in ("ce", "kl"):
122
+ raise ValueError(
123
+ "Distributing modules across ranks is not compatible with the "
124
+ "cross-entropy or KL divergence losses."
125
+ )
126
+
127
+ if not self.init_seeds:
128
+ raise ValueError("Must specify at least one random seed.")