eai-sparsify 0.0.1__tar.gz

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,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,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,158 @@
1
+ ## Introduction
2
+ 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).
3
+
4
+ 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.
5
+
6
+ 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.
7
+
8
+ ## Loading pretrained SAEs
9
+
10
+ To load a pretrained SAE from the HuggingFace Hub, you can use the `Sae.load_from_hub` method as follows:
11
+
12
+ ```python
13
+ from sparsify import Sae
14
+
15
+ sae = Sae.load_from_hub("EleutherAI/sae-llama-3-8b-32x", hookpoint="layers.10")
16
+ ```
17
+
18
+ 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`:
19
+
20
+ ```python
21
+ saes = Sae.load_many("EleutherAI/sae-llama-3-8b-32x")
22
+ saes["layers.10"]
23
+ ```
24
+
25
+ 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:
26
+
27
+ ```python
28
+ from transformers import AutoModelForCausalLM, AutoTokenizer
29
+ import torch
30
+
31
+ tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B")
32
+ inputs = tokenizer("Hello, world!", return_tensors="pt")
33
+
34
+ with torch.inference_mode():
35
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Meta-Llama-3-8B")
36
+ outputs = model(**inputs, output_hidden_states=True)
37
+
38
+ latent_acts = []
39
+ for sae, hidden_state in zip(saes.values(), outputs.hidden_states):
40
+ # (N, D) input shape expected
41
+ hidden_state = hidden_state.flatten(0, 1)
42
+ latent_acts.append(sae.encode(hidden_state))
43
+
44
+ # Do stuff with the latent activations
45
+ ```
46
+
47
+ For use cases beyond collecting residual stream SAE activations, we recommend PyTorch hooks ([see examples](https://gist.github.com/luciaquirke/7105708dac0cfc632d68f33c79b59e5c).)
48
+
49
+ ## Training SAEs and transcoders
50
+
51
+ To train SAEs from the command line, you can use the following command:
52
+
53
+ ```bash
54
+ python -m sparsify EleutherAI/pythia-160m <optional dataset>
55
+ ```
56
+ 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).
57
+
58
+ The CLI supports all of the config options provided by the `TrainConfig` class. You can see them by running `python -m sparsify --help`.
59
+
60
+ Programmatic usage is simple. Here is an example:
61
+
62
+ ```python
63
+ import torch
64
+ from datasets import load_dataset
65
+ from transformers import AutoModelForCausalLM, AutoTokenizer
66
+
67
+ from sparsify import SaeConfig, Trainer, TrainConfig
68
+ from sparsify.data import chunk_and_tokenize
69
+
70
+ MODEL = "HuggingFaceTB/SmolLM2-135M"
71
+ dataset = load_dataset(
72
+ "EleutherAI/SmolLM2-135M-10B", split="train",
73
+ )
74
+ tokenizer = AutoTokenizer.from_pretrained(MODEL)
75
+ tokenized = chunk_and_tokenize(dataset, tokenizer)
76
+
77
+
78
+ gpt = AutoModelForCausalLM.from_pretrained(
79
+ MODEL,
80
+ device_map={"": "cuda"},
81
+ torch_dtype=torch.bfloat16,
82
+ )
83
+
84
+ cfg = TrainConfig(SaeConfig(), batch_size=16)
85
+ trainer = Trainer(cfg, tokenized, gpt)
86
+
87
+ trainer.fit()
88
+ ```
89
+
90
+ ## Finetuning SAEs
91
+
92
+ To finetune a pretrained SAE, pass its path to the `finetune` argument.
93
+
94
+ ```bash
95
+ python -m sparsify EleutherAI/pythia-160m togethercomputer/RedPajama-Data-1T-Sample --finetune EleutherAI/sae-pythia-160m-32x
96
+ ```
97
+
98
+ ## Custom hookpoints
99
+
100
+ 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:
101
+
102
+ ```bash
103
+ python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act"
104
+ ```
105
+
106
+ To restrict to the first three layers:
107
+
108
+ ```bash
109
+ python -m sparsify gpt2 --hookpoints "h.[012].attn" "h.[012].mlp.act"
110
+ ```
111
+
112
+ 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.
113
+
114
+ ## Distributed training
115
+
116
+ 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.
117
+
118
+ ```bash
119
+ 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
120
+ ```
121
+
122
+ 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.
123
+
124
+ ```bash
125
+ 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
126
+ ```
127
+
128
+ 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.
129
+
130
+ ## TODO
131
+
132
+ There are several features that we'd like to add in the near future:
133
+ - [ ] Support for caching activations
134
+ - [ ] Evaluate SAEs with KL divergence when grafted into the model
135
+
136
+ 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.
137
+
138
+ ## Development
139
+
140
+ Run `pip install pre-commit` then `pre-commit install`.
141
+
142
+ ## Experimental features
143
+
144
+ Linear k decay schedule:
145
+
146
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --k_decay_steps 10_000```
147
+
148
+ GroupMax activation function:
149
+
150
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --activation groupmax```
151
+
152
+ End-to-end training:
153
+
154
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --loss_fn ce```
155
+
156
+ or
157
+
158
+ ```bash python -m sparsify gpt2 --hookpoints "h.*.attn" "h.*.mlp.act" --loss_fn kl```
@@ -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,22 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ eai_sparsify.egg-info/PKG-INFO
5
+ eai_sparsify.egg-info/SOURCES.txt
6
+ eai_sparsify.egg-info/dependency_links.txt
7
+ eai_sparsify.egg-info/entry_points.txt
8
+ eai_sparsify.egg-info/requires.txt
9
+ eai_sparsify.egg-info/top_level.txt
10
+ sparsify/__init__.py
11
+ sparsify/__main__.py
12
+ sparsify/config.py
13
+ sparsify/data.py
14
+ sparsify/fused_encoder.py
15
+ sparsify/muon.py
16
+ sparsify/sign_sgd.py
17
+ sparsify/sparse_coder.py
18
+ sparsify/trainer.py
19
+ sparsify/utils.py
20
+ sparsify/xformers.py
21
+ tests/test_decode.py
22
+ tests/test_encode.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ sparsify = sparsify.__main__:run
@@ -0,0 +1,13 @@
1
+ accelerate
2
+ datasets
3
+ einops
4
+ huggingface-hub
5
+ natsort
6
+ safetensors
7
+ schedulefree
8
+ simple-parsing
9
+ torch
10
+ transformers
11
+
12
+ [dev]
13
+ pre-commit
@@ -0,0 +1 @@
1
+ sparsify