Sparse Autoencoder (SAE) API¶
Sparse Autoencoders, training, concepts, and related modules for mechanistic interpretability.
Core SAE Classes¶
mi_crow.mechanistic.sae.sae.Sae ¶
Sae(n_latents, n_inputs, hook_id=None, device='cpu', store=None, *args, **kwargs)
Bases: Controller, Detector, ABC
Source code in src/mi_crow/mechanistic/sae/sae.py
29 30 31 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 | |
process_activations
abstractmethod
¶
process_activations(module, input, output)
Process activations to save neuron activations in metadata.
This implements the Detector interface. It extracts activations, encodes them to get neuron activations (latents), and saves metadata for each item in the batch individually, including nonzero latent indices and activations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
The PyTorch module being hooked |
required |
input
|
HOOK_FUNCTION_INPUT
|
Tuple of input tensors to the module |
required |
output
|
HOOK_FUNCTION_OUTPUT
|
Output tensor(s) from the module |
required |
Source code in src/mi_crow/mechanistic/sae/sae.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
set_context ¶
set_context(context)
Set the LanguageModelContext for this hook and sync to AutoencoderContext.
When the hook is registered, this method is called with the LanguageModelContext. It automatically syncs relevant values to the AutoencoderContext, including device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
LanguageModelContext
|
The LanguageModelContext instance from the LanguageModel |
required |
Source code in src/mi_crow/mechanistic/sae/sae.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
mi_crow.mechanistic.sae.modules.topk_sae.TopKSae ¶
TopKSae(n_latents, n_inputs, hook_id=None, device='cpu', store=None, *args, **kwargs)
Bases: Sae
Initialize TopK SAE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_latents
|
int
|
Number of latent dimensions (concepts) |
required |
n_inputs
|
int
|
Number of input dimensions |
required |
hook_id
|
str | None
|
Optional hook identifier |
None
|
device
|
str
|
Device to run on ('cpu', 'cuda', 'mps') |
'cpu'
|
store
|
Store | None
|
Optional store instance |
None
|
Note
The k parameter must be provided in TopKSaeTrainingConfig during training.
For loaded models, k is restored from saved metadata.
A temporary default k=1 is used for engine initialization and will be
overridden with the actual k value from config during training.
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
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 | |
decode ¶
decode(x)
Decode latents using sae_engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Encoded tensor of shape [batch_size, n_latents] |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed tensor of shape [batch_size, n_inputs] |
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
109 110 111 112 113 114 115 116 117 118 119 | |
encode ¶
encode(x)
Encode input using sae_engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor of shape [batch_size, n_inputs] |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Encoded latents (TopK sparse activations) |
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
95 96 97 98 99 100 101 102 103 104 105 106 107 | |
forward ¶
forward(x)
Forward pass using sae_engine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Input tensor of shape [batch_size, n_inputs] |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Reconstructed tensor of shape [batch_size, n_inputs] |
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
121 122 123 124 125 126 127 128 129 130 131 132 133 | |
load
staticmethod
¶
load(path)
Load TopKSAE from saved file using overcomplete's load method + our metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to saved model file |
required |
Returns:
| Type | Description |
|---|---|
TopKSae
|
Loaded TopKSAE instance |
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
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 | |
modify_activations ¶
modify_activations(module, inputs, output)
Modify activations using TopKSAE (Controller hook interface).
Extracts tensor from inputs/output, applies SAE forward pass, and optionally applies concept manipulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
The PyTorch module being hooked |
required |
inputs
|
Tensor | None
|
Tuple of inputs to the module |
required |
output
|
Tensor | None
|
Output from the module (None for pre_forward hooks) |
required |
Returns:
| Type | Description |
|---|---|
Tensor | None
|
Modified activations with same shape as input |
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
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 | |
process_activations ¶
process_activations(module, input, output)
Process activations (Detector interface).
Metadata saving is handled in modify_activations to avoid duplicate work. This method is kept for interface compatibility but does nothing since modify_activations already saves the metadata when called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
The PyTorch module being hooked |
required |
input
|
HOOK_FUNCTION_INPUT
|
Tuple of input tensors to the module |
required |
output
|
HOOK_FUNCTION_OUTPUT
|
Output tensor(s) from the module |
required |
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | |
save ¶
save(name, path=None, k=None)
Save model using overcomplete's state dict + our metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Model name |
required |
path
|
str | Path | None
|
Directory path to save to (defaults to current directory) |
None
|
k
|
int | None
|
Top-K value to save (if None, attempts to get from engine or raises error) |
None
|
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
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 | |
train ¶
train(store, run_id, layer_signature, config=None, training_run_id=None)
Train TopKSAE using activations from a Store.
This method delegates to the SaeTrainer composite class. The SAE engine will be reinitialized with the k value from config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
Store
|
Store instance containing activations |
required |
run_id
|
str
|
Run ID to train on |
required |
config
|
TopKSaeTrainingConfig | None
|
Training configuration (must include k parameter) |
None
|
training_run_id
|
str | None
|
Optional training run ID |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary with keys: - "history": Training history dictionary - "training_run_id": Training run ID where outputs were saved |
Raises:
| Type | Description |
|---|---|
ValueError
|
If config is None or config.k is not set |
Source code in src/mi_crow/mechanistic/sae/modules/topk_sae.py
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 | |
mi_crow.mechanistic.sae.autoencoder_context.AutoencoderContext
dataclass
¶
AutoencoderContext(autoencoder, n_latents, n_inputs, lm=None, lm_layer_signature=None, model_id=None, device='cpu', experiment_name=None, run_id=None, text_tracking_enabled=False, text_tracking_k=5, text_tracking_negative=False, store=None, tied=False, bias_init=0.0, init_method='kaiming')
Shared context for Autoencoder and its nested components.
Training¶
mi_crow.mechanistic.sae.sae_trainer.SaeTrainer ¶
SaeTrainer(sae)
Composite trainer class for SAE models using overcomplete's training functions.
This trainer handles training of any SAE that has a sae_engine attribute compatible with overcomplete's train_sae functions.
Initialize SaeTrainer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sae
|
Sae
|
The SAE instance to train |
required |
Source code in src/mi_crow/mechanistic/sae/sae_trainer.py
68 69 70 71 72 73 74 75 76 | |
mi_crow.mechanistic.sae.sae_trainer.SaeTrainingConfig
dataclass
¶
SaeTrainingConfig(epochs=1, batch_size=1024, lr=0.001, l1_lambda=0.0, device='cpu', dtype=None, max_batches_per_epoch=None, verbose=False, use_amp=True, amp_dtype=None, grad_accum_steps=1, clip_grad=1.0, monitoring=1, scheduler=None, max_nan_fallbacks=5, use_wandb=False, wandb_project=None, wandb_entity=None, wandb_name=None, wandb_tags=None, wandb_config=None, wandb_mode='online', wandb_slow_metrics_frequency=50, wandb_api_key=None, memory_efficient=False, snapshot_every_n_epochs=None, snapshot_base_path=None)
Configuration for SAE training (compatible with overcomplete.train_sae).
mi_crow.mechanistic.sae.modules.topk_sae.TopKSaeTrainingConfig
dataclass
¶
TopKSaeTrainingConfig(epochs=1, batch_size=1024, lr=0.001, l1_lambda=0.0, device='cpu', dtype=None, max_batches_per_epoch=None, verbose=False, use_amp=True, amp_dtype=None, grad_accum_steps=1, clip_grad=1.0, monitoring=1, scheduler=None, max_nan_fallbacks=5, use_wandb=False, wandb_project=None, wandb_entity=None, wandb_name=None, wandb_tags=None, wandb_config=None, wandb_mode='online', wandb_slow_metrics_frequency=50, wandb_api_key=None, memory_efficient=False, snapshot_every_n_epochs=None, snapshot_base_path=None, k=10)
Bases: SaeTrainingConfig
Training configuration for TopK SAE models.
This class extends SaeTrainingConfig to provide a type-safe configuration
interface specifically for TopK SAE models. It adds the k parameter which
specifies how many top activations to keep during encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
Number of top activations to keep (required for TopK SAE training) |
10
|
Note
All other parameters are inherited from SaeTrainingConfig.
Attributes:
| Name | Type | Description |
|---|---|---|
k |
int
|
Number of top activations to keep during TopK encoding |
Example
config = TopKSaeTrainingConfig( ... k=10, ... epochs=100, ... batch_size=1024, ... lr=1e-3, ... l1_lambda=1e-4 ... )
Concepts¶
mi_crow.mechanistic.sae.concepts.autoencoder_concepts.AutoencoderConcepts ¶
AutoencoderConcepts(context)
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
enable_text_tracking ¶
enable_text_tracking()
Enable text tracking using context parameters.
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
export_bottom_texts_to_json ¶
export_bottom_texts_to_json(filepath)
Export bottom texts (negative activations) to JSON file.
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
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 | |
export_top_texts_to_json ¶
export_top_texts_to_json(filepath)
Export top texts (positive activations) to JSON file.
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
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 | |
generate_concepts_with_llm ¶
generate_concepts_with_llm(llm_provider=None)
Generate concepts using LLM based on current top texts
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
get_all_bottom_texts ¶
get_all_bottom_texts()
Get bottom texts for all neurons (negative activations).
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
312 313 314 315 316 | |
get_all_top_texts ¶
get_all_top_texts()
Get top texts for all neurons (positive activations).
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
306 307 308 309 310 | |
get_bottom_texts_for_neuron ¶
get_bottom_texts_for_neuron(neuron_idx, top_m=None)
Get bottom texts for a specific neuron (negative activations).
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | |
get_top_texts_for_neuron ¶
get_top_texts_for_neuron(neuron_idx, top_m=None)
Get top texts for a specific neuron (positive activations).
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
reset_top_texts ¶
reset_top_texts()
Reset all tracked top texts.
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
318 319 320 321 | |
update_top_texts_from_latents ¶
update_top_texts_from_latents(latents, texts, original_shape=None)
Update top texts heaps from latents and texts.
Optimized version that: - Only processes active neurons (non-zero activations) - Vectorizes argmax/argmin operations - Eliminates per-neuron tensor slicing
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
latents
|
Tensor
|
Latent activations tensor, shape [B*T, n_latents] or [B, n_latents] (already flattened) |
required |
texts
|
Sequence[str]
|
List of texts corresponding to the batch |
required |
original_shape
|
tuple[int, ...] | None
|
Original shape before flattening, e.g., (B, T, D) or (B, D) |
None
|
Source code in src/mi_crow/mechanistic/sae/concepts/autoencoder_concepts.py
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 | |
mi_crow.mechanistic.sae.concepts.concept_dictionary.ConceptDictionary ¶
ConceptDictionary(n_size, store=None)
Source code in src/mi_crow/mechanistic/sae/concepts/concept_dictionary.py
22 23 24 25 26 27 28 29 30 | |
mi_crow.mechanistic.sae.concepts.concept_models ¶
mi_crow.mechanistic.sae.concepts.input_tracker.InputTracker ¶
InputTracker(language_model)
Simple listener that saves input texts before tokenization.
This is a singleton per LanguageModel instance. It's used as a listener during inference to capture texts before they are tokenized. SAE hooks can then access these texts to track top activating texts for their neurons.
Initialize InputTracker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
language_model
|
LanguageModel
|
Language model instance |
required |
Source code in src/mi_crow/mechanistic/sae/concepts/input_tracker.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | |
disable ¶
disable()
Disable input tracking.
Source code in src/mi_crow/mechanistic/sae/concepts/input_tracker.py
47 48 49 | |
enable ¶
enable()
Enable input tracking.
Source code in src/mi_crow/mechanistic/sae/concepts/input_tracker.py
43 44 45 | |
get_current_texts ¶
get_current_texts()
Get the current batch of texts.
Source code in src/mi_crow/mechanistic/sae/concepts/input_tracker.py
65 66 67 | |
reset ¶
reset()
Reset stored texts.
Source code in src/mi_crow/mechanistic/sae/concepts/input_tracker.py
51 52 53 | |
set_current_texts ¶
set_current_texts(texts)
Set the current batch of texts being processed.
This is called by LanguageModel._inference() before tokenization if tracking is enabled.
Source code in src/mi_crow/mechanistic/sae/concepts/input_tracker.py
55 56 57 58 59 60 61 62 63 | |
Training Utilities¶
mi_crow.mechanistic.sae.training.wandb_logger.WandbLogger ¶
WandbLogger(config, run_id)
Handles wandb logging for SAE training.
Encapsulates all wandb-related operations including initialization, metric logging, and summary updates.
Initialize WandbLogger.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SaeTrainingConfig
|
Training configuration |
required |
run_id
|
str
|
Training run identifier |
required |
Source code in src/mi_crow/mechanistic/sae/training/wandb_logger.py
19 20 21 22 23 24 25 26 27 28 29 30 | |
initialize ¶
initialize()
Initialize wandb run if enabled in config.
Returns:
| Type | Description |
|---|---|
bool
|
True if wandb was successfully initialized, False otherwise |
Source code in src/mi_crow/mechanistic/sae/training/wandb_logger.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 | |
log_metrics ¶
log_metrics(history, verbose=False)
Log training metrics to wandb.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history
|
dict[str, list[float | None]]
|
Dictionary with training history (loss, r2, l1, l0, etc.) |
required |
verbose
|
bool
|
Whether to log verbose information |
False
|
Source code in src/mi_crow/mechanistic/sae/training/wandb_logger.py
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 | |