API
ActivationsStore
Class for streaming tokens and generating and storing activations while training SAEs.
Source code in sae_lens/training/activations_store.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 |
|
from_cache_activations(model, cfg)
classmethod
Public api to create an ActivationsStore from a cached activations dataset.
Source code in sae_lens/training/activations_store.py
get_activations(batch_tokens)
Returns activations of shape (batches, context, num_layers, d_in)
d_in may result from a concatenated head dimension.
Source code in sae_lens/training/activations_store.py
get_batch_tokens(batch_size=None, raise_at_epoch_end=False)
Streams a batch of tokens from a dataset.
If raise_at_epoch_end is true we will reset the dataset at the end of each epoch and raise a StopIteration. Otherwise we will reset silently.
Source code in sae_lens/training/activations_store.py
get_buffer(n_batches_in_buffer, raise_on_epoch_end=False, shuffle=True)
Loads the next n_batches_in_buffer batches of activations into a tensor and returns it.
The primary purpose here is maintaining a shuffling buffer.
If raise_on_epoch_end is True, when the dataset it exhausted it will automatically refill the dataset and then raise a StopIteration so that the caller has a chance to react.
Source code in sae_lens/training/activations_store.py
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 |
|
get_data_loader()
Return a torch.utils.dataloader which you can get batches from.
Should automatically refill the buffer when it gets to n % full. (better mixing if you refill and shuffle regularly).
Source code in sae_lens/training/activations_store.py
load_cached_activation_dataset()
Load the cached activation dataset from disk.
- If cached_activations_path is set, returns Huggingface Dataset else None
- Checks that the loaded dataset has current has activations for hooks in config and that shapes match.
Source code in sae_lens/training/activations_store.py
next_batch()
Get the next batch from the current DataLoader. If the DataLoader is exhausted, refill the buffer and create a new DataLoader.
Source code in sae_lens/training/activations_store.py
reset_input_dataset()
save(file_path)
shuffle_input_dataset(seed, buffer_size=1)
This applies a shuffle to the huggingface dataset that is the input to the activations store. This also shuffles the shards of the dataset, which is especially useful for evaluating on different sections of very large streaming datasets. Buffer size is only relevant for streaming datasets. The default buffer_size of 1 means that only the shard will be shuffled; larger buffer sizes will additionally shuffle individual elements within the shard.
Source code in sae_lens/training/activations_store.py
CacheActivationsRunner
Source code in sae_lens/cache_activations_runner.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 |
|
__str__()
Print the number of tokens to be cached. Print the number of buffers, and the number of tokens per buffer. Print the disk space required to store the activations.
Source code in sae_lens/cache_activations_runner.py
CacheActivationsRunnerConfig
dataclass
Configuration for creating and caching activations of an LLM.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset_path |
str
|
The path to the Hugging Face dataset. This may be tokenized or not. |
required |
model_name |
str
|
The name of the model to use. |
required |
model_batch_size |
int
|
How many prompts are in the batch of the language model when generating activations. |
required |
hook_name |
str
|
The name of the hook to use. |
required |
hook_layer |
int
|
The layer of the final hook. Currently only support a single hook, so this should be the same as hook_name. |
required |
d_in |
int
|
Dimension of the model. |
required |
total_training_tokens |
int
|
Total number of tokens to process. |
required |
context_size |
int
|
Context size to process. Can be left as -1 if the dataset is tokenized. |
-1
|
model_class_name |
str
|
The name of the class of the model to use. This should be either |
'HookedTransformer'
|
new_cached_activations_path |
str
|
The path to save the activations. |
None
|
shuffle |
bool
|
Whether to shuffle the dataset. |
True
|
seed |
int
|
The seed to use for shuffling. |
42
|
dtype |
str
|
Datatype of activations to be stored. |
'float32'
|
device |
str
|
The device for the model. |
'cuda' if is_available() else 'cpu'
|
buffer_size_gb |
float
|
The buffer size in GB. This should be < 2GB. |
2.0
|
hf_repo_id |
str
|
The Hugging Face repository id to save the activations to. |
None
|
hf_num_shards |
int
|
The number of shards to save the activations to. |
None
|
hf_revision |
str
|
The revision to save the activations to. |
'main'
|
hf_is_private_repo |
bool
|
Whether the Hugging Face repository is private. |
False
|
model_kwargs |
dict
|
Keyword arguments for |
dict()
|
model_from_pretrained_kwargs |
dict
|
Keyword arguments for the |
dict()
|
compile_llm |
bool
|
Whether to compile the LLM. |
False
|
llm_compilation_mode |
str
|
The torch.compile mode to use. |
None
|
prepend_bos |
bool
|
Whether to prepend the beginning of sequence token. You should use whatever the model was trained with. |
True
|
seqpos_slice |
tuple
|
Determines slicing of activations when constructing batches during training. The slice should be (start_pos, end_pos, optional[step_size]), e.g. for Othello we sometimes use (5, -5). Note, step_size > 0. |
(None,)
|
streaming |
bool
|
Whether to stream the dataset. Streaming large datasets is usually practical. |
True
|
autocast_lm |
bool
|
Whether to use autocast during activation fetching. |
False
|
dataset_trust_remote_code |
bool
|
Whether to trust remote code when loading datasets from Huggingface. |
None
|
Source code in sae_lens/config.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
|
GatedSAE
Bases: SAE[GatedSAEConfig]
GatedSAE is an inference-only implementation of a Sparse Autoencoder (SAE) using a gated linear encoder and a standard linear decoder.
Source code in sae_lens/saes/gated_sae.py
decode(feature_acts)
Decode the feature activations back into the input space
1) Apply optional finetuning scaling. 2) Linear transform plus bias. 3) Run any reconstruction hooks and out-normalization if configured. 4) If the SAE was reshaping hook_z activations, reshape back.
Source code in sae_lens/saes/gated_sae.py
encode(x)
Encode the input tensor into the feature space using a gated encoder. This must match the original encode_gated implementation from SAE class.
Source code in sae_lens/saes/gated_sae.py
fold_W_dec_norm()
Override to handle gated-specific parameters.
Source code in sae_lens/saes/gated_sae.py
initialize_decoder_norm_constant_norm(norm=0.1)
Initialize decoder with constant norm.
GatedSAEConfig
dataclass
GatedTrainingSAE
Bases: TrainingSAE[GatedTrainingSAEConfig]
GatedTrainingSAE is a concrete implementation of BaseTrainingSAE for the "gated" SAE architecture. It implements: - initialize_weights: sets up gating parameters (as in GatedSAE) plus optional training-specific init. - encode: calls encode_with_hidden_pre (standard training approach). - decode: linear transformation + hooking, same as GatedSAE or StandardTrainingSAE. - encode_with_hidden_pre: gating logic + optional noise injection for training. - calculate_aux_loss: includes an auxiliary reconstruction path and gating-based sparsity penalty. - training_forward_pass: calls encode_with_hidden_pre, decode, and sums up MSE + gating losses.
Source code in sae_lens/saes/gated_sae.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
|
encode_with_hidden_pre(x)
Gated forward pass with pre-activation (for training). We also inject noise if self.training is True.
Source code in sae_lens/saes/gated_sae.py
initialize_decoder_norm_constant_norm(norm=0.1)
Initialize decoder with constant norm
log_histograms()
Log histograms of the weights and biases.
Source code in sae_lens/saes/gated_sae.py
GatedTrainingSAEConfig
dataclass
Bases: TrainingSAEConfig
Configuration class for training a GatedTrainingSAE.
Source code in sae_lens/saes/gated_sae.py
HookedSAETransformer
Bases: HookedTransformer
Source code in sae_lens/analysis/hooked_sae_transformer.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
|
__init__(*model_args, **model_kwargs)
Model initialization. Just HookedTransformer init, but adds a dictionary to keep track of attached SAEs.
Note that if you want to load the model from pretrained weights, you should use
:meth:from_pretrained
instead.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*model_args |
Any
|
Positional arguments for HookedTransformer initialization |
()
|
**model_kwargs |
Any
|
Keyword arguments for HookedTransformer initialization |
{}
|
Source code in sae_lens/analysis/hooked_sae_transformer.py
add_sae(sae, use_error_term=None)
Attaches an SAE to the model
WARNING: This sae will be permanantly attached until you remove it with reset_saes. This function will also overwrite any existing SAE attached to the same hook point.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sae |
SAE[Any]
|
SparseAutoencoderBase. The SAE to attach to the model |
required |
use_error_term |
bool | None
|
(bool | None) If provided, will set the use_error_term attribute of the SAE to this value. Determines whether the SAE returns input or reconstruction. Defaults to None. |
None
|
Source code in sae_lens/analysis/hooked_sae_transformer.py
reset_saes(act_names=None, prev_saes=None)
Reset the SAEs attached to the model
If act_names are provided will just reset SAEs attached to those hooks. Otherwise will reset all SAEs attached to the model. Optionally can provide a list of prev_saes to reset to. This is mainly used to restore previously attached SAEs after temporarily running with different SAEs (eg with run_with_saes).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
act_names |
str | list[str] | None
|
The act_names of the SAEs to reset. If None, will reset all SAEs attached to the model. Defaults to None. |
None
|
prev_saes |
list[SAE | None] | None
|
List of SAEs to replace the current ones with. If None, will just remove the SAEs. Defaults to None. |
None
|
Source code in sae_lens/analysis/hooked_sae_transformer.py
run_with_cache_with_saes(*model_args, saes=[], reset_saes_end=True, use_error_term=None, return_cache_object=True, remove_batch_dim=False, **kwargs)
Wrapper around 'run_with_cache' in HookedTransformer.
Attaches given SAEs before running the model with cache and then removes them. By default, will reset all SAEs to original state after.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*model_args |
Any
|
Positional arguments for the model forward pass |
()
|
saes |
SAE[Any] | list[SAE[Any]]
|
(SAE | list[SAE]) The SAEs to be attached for this forward pass |
[]
|
reset_saes_end |
bool
|
(bool) If True, all SAEs added during this run are removed at the end, and previously attached SAEs are restored to their original state. Default is True. |
True
|
use_error_term |
bool | None
|
(bool | None) If provided, will set the use_error_term attribute of all SAEs attached during this run to this value. Determines whether the SAE returns input or reconstruction. Defaults to None. |
None
|
return_cache_object |
bool
|
(bool) if True, this will return an ActivationCache object, with a bunch of useful HookedTransformer specific methods, otherwise it will return a dictionary of activations as in HookedRootModule. |
True
|
remove_batch_dim |
bool
|
(bool) Whether to remove the batch dimension (only works for batch_size==1). Defaults to False. |
False
|
**kwargs |
Any
|
Keyword arguments for the model forward pass |
{}
|
Source code in sae_lens/analysis/hooked_sae_transformer.py
run_with_hooks_with_saes(*model_args, saes=[], reset_saes_end=True, fwd_hooks=[], bwd_hooks=[], reset_hooks_end=True, clear_contexts=False, **model_kwargs)
Wrapper around 'run_with_hooks' in HookedTransformer.
Attaches the given SAEs to the model before running the model with hooks and then removes them. By default, will reset all SAEs to original state after.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*model_args |
Any
|
Positional arguments for the model forward pass |
()
|
saes |
SAE[Any] | list[SAE[Any]]
|
(SAE | list[SAE]) The SAEs to be attached for this forward pass |
[]
|
reset_saes_end |
bool
|
(bool) If True, all SAEs added during this run are removed at the end, and previously attached SAEs are restored to their original state. (default: True) |
True
|
fwd_hooks |
list[tuple[str | Callable, Callable]]
|
(list[tuple[str | Callable, Callable]]) List of forward hooks to apply |
[]
|
bwd_hooks |
list[tuple[str | Callable, Callable]]
|
(list[tuple[str | Callable, Callable]]) List of backward hooks to apply |
[]
|
reset_hooks_end |
bool
|
(bool) Whether to reset the hooks at the end of the forward pass (default: True) |
True
|
clear_contexts |
bool
|
(bool) Whether to clear the contexts at the end of the forward pass (default: False) |
False
|
**model_kwargs |
Any
|
Keyword arguments for the model forward pass |
{}
|
Source code in sae_lens/analysis/hooked_sae_transformer.py
run_with_saes(*model_args, saes=[], reset_saes_end=True, use_error_term=None, **model_kwargs)
Wrapper around HookedTransformer forward pass.
Runs the model with the given SAEs attached for one forward pass, then removes them. By default, will reset all SAEs to original state after.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*model_args |
Any
|
Positional arguments for the model forward pass |
()
|
saes |
SAE[Any] | list[SAE[Any]]
|
(SAE | list[SAE]) The SAEs to be attached for this forward pass |
[]
|
reset_saes_end |
bool
|
If True, all SAEs added during this run are removed at the end, and previously attached SAEs are restored to their original state. Default is True. |
True
|
use_error_term |
bool | None
|
(bool | None) If provided, will set the use_error_term attribute of all SAEs attached during this run to this value. Defaults to None. |
None
|
**model_kwargs |
Any
|
Keyword arguments for the model forward pass |
{}
|
Source code in sae_lens/analysis/hooked_sae_transformer.py
saes(saes=[], reset_saes_end=True, use_error_term=None)
A context manager for adding temporary SAEs to the model. See HookedTransformer.hooks for a similar context manager for hooks. By default will keep track of previously attached SAEs, and restore them when the context manager exits.
Example:
.. code-block:: python
from transformer_lens import HookedSAETransformer
from sae_lens.saes.sae import SAE
model = HookedSAETransformer.from_pretrained('gpt2-small')
sae_cfg = SAEConfig(...)
sae = SAE(sae_cfg)
with model.saes(saes=[sae]):
spliced_logits = model(text)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
saes |
SAE | list[SAE]
|
SAEs to be attached. |
[]
|
reset_saes_end |
bool
|
If True, removes all SAEs added by this context manager when the context manager exits, returning previously attached SAEs to their original state. |
True
|
use_error_term |
bool | None
|
If provided, will set the use_error_term attribute of all SAEs attached during this run to this value. Defaults to None. |
None
|
Source code in sae_lens/analysis/hooked_sae_transformer.py
JumpReLUSAE
Bases: SAE[JumpReLUSAEConfig]
JumpReLUSAE is an inference-only implementation of a Sparse Autoencoder (SAE) using a JumpReLU activation. For each unit, if its pre-activation is <= threshold, that unit is zeroed out; otherwise, it follows a user-specified activation function (e.g., ReLU, tanh-relu, etc.).
It implements
- initialize_weights: sets up parameters, including a threshold.
- encode: computes the feature activations using JumpReLU.
- decode: reconstructs the input from the feature activations.
The BaseSAE.forward() method automatically calls encode and decode, including any error-term processing if configured.
Source code in sae_lens/saes/jumprelu_sae.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
|
decode(feature_acts)
Decode the feature activations back to the input space. Follows the same steps as StandardSAE: apply scaling, transform, hook, and optionally reshape.
Source code in sae_lens/saes/jumprelu_sae.py
encode(x)
Encode the input tensor into the feature space using JumpReLU. The threshold parameter determines which units remain active.
Source code in sae_lens/saes/jumprelu_sae.py
fold_W_dec_norm()
Override to properly handle threshold adjustment with W_dec norms. When we scale the encoder weights, we need to scale the threshold by the same factor to maintain the same sparsity pattern.
Source code in sae_lens/saes/jumprelu_sae.py
JumpReLUSAEConfig
dataclass
JumpReLUTrainingSAE
Bases: TrainingSAE[JumpReLUTrainingSAEConfig]
JumpReLUTrainingSAE is a training-focused implementation of a SAE using a JumpReLU activation.
Similar to the inference-only JumpReLUSAE, but with: - A learnable log-threshold parameter (instead of a raw threshold). - Forward passes that add noise during training, if configured. - A specialized auxiliary loss term for sparsity (L0 or similar).
Methods of interest include: - initialize_weights: sets up W_enc, b_enc, W_dec, b_dec, and log_threshold. - encode_with_hidden_pre_jumprelu: runs a forward pass for training, optionally adding noise. - training_forward_pass: calculates MSE and auxiliary losses, returning a TrainStepOutput.
Source code in sae_lens/saes/jumprelu_sae.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
|
threshold: torch.Tensor
property
Returns the parameterized threshold > 0 for each unit. threshold = exp(log_threshold).
calculate_aux_loss(step_input, feature_acts, hidden_pre, sae_out)
Calculate architecture-specific auxiliary loss terms.
Source code in sae_lens/saes/jumprelu_sae.py
fold_W_dec_norm()
Override to properly handle threshold adjustment with W_dec norms.
Source code in sae_lens/saes/jumprelu_sae.py
initialize_decoder_norm_constant_norm(norm=0.1)
Initialize decoder with constant norm
initialize_weights()
Initialize parameters like the base SAE, but also add log_threshold.
Source code in sae_lens/saes/jumprelu_sae.py
process_state_dict_for_loading(state_dict)
Convert threshold to log_threshold for loading
Source code in sae_lens/saes/jumprelu_sae.py
process_state_dict_for_saving(state_dict)
Convert log_threshold to threshold for saving
Source code in sae_lens/saes/jumprelu_sae.py
JumpReLUTrainingSAEConfig
dataclass
Bases: TrainingSAEConfig
Configuration class for training a JumpReLUTrainingSAE.
Source code in sae_lens/saes/jumprelu_sae.py
LanguageModelSAERunnerConfig
dataclass
Bases: Generic[T_TRAINING_SAE_CONFIG]
Configuration for training a sparse autoencoder on a language model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sae |
T_TRAINING_SAE_CONFIG
|
The configuration for the SAE itself (e.g. StandardSAEConfig, GatedSAEConfig). |
required |
model_name |
str
|
The name of the model to use. This should be the name of the model in the Hugging Face model hub. |
'gelu-2l'
|
model_class_name |
str
|
The name of the class of the model to use. This should be either |
'HookedTransformer'
|
hook_name |
str
|
The name of the hook to use. This should be a valid TransformerLens hook. |
'blocks.0.hook_mlp_out'
|
hook_eval |
str
|
NOT CURRENTLY IN USE. The name of the hook to use for evaluation. |
'NOT_IN_USE'
|
hook_layer |
int
|
The index of the layer to hook. Used to stop forward passes early and speed up processing. |
0
|
hook_head_index |
int
|
When the hook is for an activation with a head index, we can specify a specific head to use here. |
None
|
dataset_path |
str
|
A Hugging Face dataset path. |
''
|
dataset_trust_remote_code |
bool
|
Whether to trust remote code when loading datasets from Huggingface. |
True
|
streaming |
bool
|
Whether to stream the dataset. Streaming large datasets is usually practical. |
True
|
is_dataset_tokenized |
bool
|
Whether the dataset is already tokenized. |
True
|
context_size |
int
|
The context size to use when generating activations on which to train the SAE. |
128
|
use_cached_activations |
bool
|
Whether to use cached activations. This is useful when doing sweeps over the same activations. |
False
|
cached_activations_path |
str
|
The path to the cached activations. Defaults to "activations/{dataset_path}/{model_name}/{hook_name}_{hook_head_index}". |
None
|
from_pretrained_path |
str
|
The path to a pretrained SAE. We can finetune an existing SAE if needed. |
None
|
n_batches_in_buffer |
int
|
The number of batches in the buffer. When not using cached activations, a buffer in RAM is used. The larger it is, the better shuffled the activations will be. |
20
|
training_tokens |
int
|
The number of training tokens. |
2000000
|
store_batch_size_prompts |
int
|
The batch size for storing activations. This controls how many prompts are in the batch of the language model when generating activations. |
32
|
seqpos_slice |
tuple[int | None, ...]
|
Determines slicing of activations when constructing batches during training. The slice should be (start_pos, end_pos, optional[step_size]), e.g. for Othello we sometimes use (5, -5). Note, step_size > 0. |
(None,)
|
device |
str
|
The device to use. Usually "cuda". |
'cpu'
|
act_store_device |
str
|
The device to use for the activation store. "cpu" is advised in order to save VRAM. Defaults to "with_model" which uses the same device as the main model. |
'with_model'
|
seed |
int
|
The seed to use. |
42
|
dtype |
str
|
The data type to use for the SAE and activations. |
'float32'
|
prepend_bos |
bool
|
Whether to prepend the beginning of sequence token. You should use whatever the model was trained with. |
True
|
autocast |
bool
|
Whether to use autocast (mixed-precision) during SAE training. Saves VRAM. |
False
|
autocast_lm |
bool
|
Whether to use autocast (mixed-precision) during activation fetching. Saves VRAM. |
False
|
compile_llm |
bool
|
Whether to compile the LLM using |
False
|
llm_compilation_mode |
str
|
The compilation mode to use for the LLM if |
None
|
compile_sae |
bool
|
Whether to compile the SAE using |
False
|
sae_compilation_mode |
str
|
The compilation mode to use for the SAE if |
None
|
train_batch_size_tokens |
int
|
The batch size for training, in tokens. This controls the batch size of the SAE training loop. |
4096
|
adam_beta1 |
float
|
The beta1 parameter for the Adam optimizer. |
0.0
|
adam_beta2 |
float
|
The beta2 parameter for the Adam optimizer. |
0.999
|
lr |
float
|
The learning rate. |
0.0003
|
lr_scheduler_name |
str
|
The name of the learning rate scheduler to use (e.g., "constant", "cosineannealing", "cosineannealingwarmrestarts"). |
'constant'
|
lr_warm_up_steps |
int
|
The number of warm-up steps for the learning rate. |
0
|
lr_end |
float
|
The end learning rate if using a scheduler like cosine annealing. Defaults to |
None
|
lr_decay_steps |
int
|
The number of decay steps for the learning rate if using a scheduler with decay. |
0
|
n_restart_cycles |
int
|
The number of restart cycles for the cosine annealing with warm restarts scheduler. |
1
|
dead_feature_window |
int
|
The window size (in training steps) for detecting dead features. |
1000
|
feature_sampling_window |
int
|
The window size (in training steps) for resampling features (e.g. dead features). |
2000
|
dead_feature_threshold |
float
|
The threshold below which a feature's activation frequency is considered dead. |
1e-08
|
n_eval_batches |
int
|
The number of batches to use for evaluation. |
10
|
eval_batch_size_prompts |
int
|
The batch size for evaluation, in prompts. Useful if evals cause OOM. |
None
|
logger |
LoggingConfig
|
Configuration for logging (e.g. W&B). |
LoggingConfig()
|
n_checkpoints |
int
|
The number of checkpoints to save during training. 0 means no checkpoints. |
0
|
checkpoint_path |
str
|
The path to save checkpoints. A unique ID will be appended to this path. |
'checkpoints'
|
verbose |
bool
|
Whether to print verbose output. |
True
|
model_kwargs |
dict[str, Any]
|
Keyword arguments for |
dict_field(default={})
|
model_from_pretrained_kwargs |
dict[str, Any]
|
Additional keyword arguments to pass to the model's |
dict_field(default=None)
|
sae_lens_version |
str
|
The version of the sae_lens library. |
lambda: __version__()
|
sae_lens_training_version |
str
|
The version of the sae_lens training library. |
lambda: __version__()
|
exclude_special_tokens |
bool | list[int]
|
Whether to exclude special tokens from the activations. If True, excludes all special tokens. If a list of ints, excludes those token IDs. |
False
|
Source code in sae_lens/config.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 |
|
PretokenizeRunner
Runner to pretokenize a dataset using a given tokenizer, and optionally upload to Huggingface.
Source code in sae_lens/pretokenize_runner.py
run()
Load the dataset, tokenize it, and save it to disk and/or upload to Huggingface.
Source code in sae_lens/pretokenize_runner.py
PretokenizeRunnerConfig
dataclass
Configuration class for pretokenizing a dataset.
Source code in sae_lens/config.py
SAE
Bases: HookedRootModule
, Generic[T_SAE_CONFIG]
, ABC
Abstract base class for all SAE architectures.
Source code in sae_lens/saes/sae.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 |
|
__init__(cfg, use_error_term=False)
Initialize the SAE.
Source code in sae_lens/saes/sae.py
decode(feature_acts)
abstractmethod
encode(x)
abstractmethod
fold_W_dec_norm()
Fold decoder norms into encoder.
Source code in sae_lens/saes/sae.py
forward(x)
Forward pass through the SAE.
Source code in sae_lens/saes/sae.py
from_dict(config_dict)
classmethod
Create an SAE from a config dictionary.
Source code in sae_lens/saes/sae.py
from_pretrained(release, sae_id, device='cpu', force_download=False, converter=None)
classmethod
Load a pretrained SAE from the Hugging Face model hub.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
release |
str
|
The release name. This will be mapped to a huggingface repo id based on the pretrained_saes.yaml file. |
required |
id |
The id of the SAE to load. This will be mapped to a path in the huggingface repo. |
required | |
device |
str
|
The device to load the SAE on. |
'cpu'
|
return_sparsity_if_present |
If True, will return the log sparsity tensor if it is present in the model directory in the Hugging Face model hub. |
required |
Source code in sae_lens/saes/sae.py
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 |
|
get_activation_fn()
get_name()
get_sae_class_for_architecture(architecture)
classmethod
Get the SAE class for a given architecture.
Source code in sae_lens/saes/sae.py
initialize_weights()
Initialize model weights.
Source code in sae_lens/saes/sae.py
save_model(path)
Save model weights and config to disk.
Source code in sae_lens/saes/sae.py
SAEConfig
dataclass
Bases: ABC
Base configuration for SAE models.
Source code in sae_lens/saes/sae.py
SAETrainingRunner
Class to run the training of a Sparse Autoencoder (SAE) on a TransformerLens model.
Source code in sae_lens/sae_training_runner.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
|
run()
Run the training of the SAE.
Source code in sae_lens/sae_training_runner.py
StandardSAE
Bases: SAE[StandardSAEConfig]
StandardSAE is an inference-only implementation of a Sparse Autoencoder (SAE) using a simple linear encoder and decoder.
It implements the required abstract methods from BaseSAE
- initialize_weights: sets up simple parameter initializations for W_enc, b_enc, W_dec, and b_dec.
- encode: computes the feature activations from an input.
- decode: reconstructs the input from the feature activations.
The BaseSAE.forward() method automatically calls encode and decode, including any error-term processing if configured.
Source code in sae_lens/saes/standard_sae.py
decode(feature_acts)
Decode the feature activations back to the input space. Now, if hook_z reshaping is turned on, we reverse the flattening.
Source code in sae_lens/saes/standard_sae.py
encode(x)
Encode the input tensor into the feature space. For inference, no noise is added.
Source code in sae_lens/saes/standard_sae.py
StandardSAEConfig
dataclass
StandardTrainingSAE
Bases: TrainingSAE[StandardTrainingSAEConfig]
StandardTrainingSAE is a concrete implementation of BaseTrainingSAE using the "standard" SAE architecture. It implements: - initialize_weights: basic weight initialization for encoder/decoder. - encode: inference encoding (invokes encode_with_hidden_pre). - decode: a simple linear decoder. - encode_with_hidden_pre: computes pre-activations, adds noise when training, and then activates. - calculate_aux_loss: computes a sparsity penalty based on the (optionally scaled) p-norm of feature activations.
Source code in sae_lens/saes/standard_sae.py
log_histograms()
Log histograms of the weights and biases.
StandardTrainingSAEConfig
dataclass
Bases: TrainingSAEConfig
Configuration class for training a StandardTrainingSAE.
Source code in sae_lens/saes/standard_sae.py
TopKSAE
Bases: SAE[TopKSAEConfig]
An inference-only sparse autoencoder using a "topk" activation function. It uses linear encoder and decoder layers, applying the TopK activation to the hidden pre-activation in its encode step.
Source code in sae_lens/saes/topk_sae.py
__init__(cfg, use_error_term=False)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg |
TopKSAEConfig
|
SAEConfig defining model size and behavior. |
required |
use_error_term |
bool
|
Whether to apply the error-term approach in the forward pass. |
False
|
Source code in sae_lens/saes/topk_sae.py
decode(feature_acts)
Reconstructs the input from topk feature activations. Applies optional finetuning scaling, hooking to recons, out normalization, and optional head reshaping.
Source code in sae_lens/saes/topk_sae.py
encode(x)
Converts input x into feature activations. Uses topk activation from the config (cfg.activation_fn == "topk") under the hood.
Source code in sae_lens/saes/topk_sae.py
TopKSAEConfig
dataclass
TopKTrainingSAE
Bases: TrainingSAE[TopKTrainingSAEConfig]
TopK variant with training functionality. Injects noise during training, optionally calculates a topk-related auxiliary loss, etc.
Source code in sae_lens/saes/topk_sae.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
|
calculate_topk_aux_loss(sae_in, sae_out, hidden_pre, dead_neuron_mask)
Calculate TopK auxiliary loss.
This auxiliary loss encourages dead neurons to learn useful features by having them reconstruct the residual error from the live neurons. It's a key part of preventing neuron death in TopK SAEs.
Source code in sae_lens/saes/topk_sae.py
encode_with_hidden_pre(x)
Similar to the base training method: cast input, optionally add noise, then apply TopK.
Source code in sae_lens/saes/topk_sae.py
TopKTrainingSAEConfig
dataclass
Bases: TrainingSAEConfig
Configuration class for training a TopKTrainingSAE.
Source code in sae_lens/saes/topk_sae.py
TrainingSAE
Bases: SAE[T_TRAINING_SAE_CONFIG]
, ABC
Abstract base class for training versions of SAEs.
Source code in sae_lens/saes/sae.py
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 |
|
calculate_aux_loss(step_input, feature_acts, hidden_pre, sae_out)
abstractmethod
Calculate architecture-specific auxiliary loss terms.
Source code in sae_lens/saes/sae.py
decode(feature_acts)
Decodes feature activations back into input space, applying optional finetuning scale, hooking, out normalization, etc.
Source code in sae_lens/saes/sae.py
encode(x)
For inference, just encode without returning hidden_pre. (training_forward_pass calls encode_with_hidden_pre).
Source code in sae_lens/saes/sae.py
encode_with_hidden_pre(x)
abstractmethod
Encode with access to pre-activation values for training.
get_sae_class_for_architecture(architecture)
classmethod
Get the SAE class for a given architecture.
Source code in sae_lens/saes/sae.py
log_histograms()
Log histograms of the weights and biases.
Source code in sae_lens/saes/sae.py
process_state_dict_for_saving_inference(state_dict)
Process the state dict for saving the inference model. This is a hook that can be overridden to change how the state dict is processed for the inference model.
Source code in sae_lens/saes/sae.py
remove_gradient_parallel_to_decoder_directions()
Remove gradient components parallel to decoder directions.
Source code in sae_lens/saes/sae.py
save_inference_model(path)
Save inference version of model weights and config to disk.
Source code in sae_lens/saes/sae.py
to_inference_config_dict()
abstractmethod
training_forward_pass(step_input)
Forward pass during training.
Source code in sae_lens/saes/sae.py
TrainingSAEConfig
dataclass
Bases: SAEConfig
, ABC
Source code in sae_lens/saes/sae.py
get_base_sae_cfg_dict()
Creates a dictionary containing attributes corresponding to the fields defined in the base SAEConfig class.