[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6XGF7T0VDSSAKK0KRFNS7EA":3,"skill-same:01M6XGF7T0VDSSAKK0KRFNS7EA":91},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":14,"repositoryHtmlUrl":60,"repositoryHomepageUrl":6,"ownerHtmlUrl":61,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":62,"install":63,"resources":76},"01M6XGF7T0VDSSAKK0KRFNS7EA","sparse-autoencoder-training",null,"Provides guidance for training and analyzing Sparse Autoencoders (SAEs) using SAELens to decompose neural network activations into interpretable features. Use when discovering interpretable features, analyzing superposition, or studying monosemantic representations in language models.","fadrienne\u002FMyGitHub","fadrienne","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F197874571?v=4","01M6X64V8VWCRSMFZ4EPS2BWXG","Francesca Adrienne","01M6X64VD5MW4F9PHDWQKS7ZAF",0,"MIT","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Fsaelens\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"training","sparse autoencoder training","when","ml","features","for","Interpretability","Transformer","lens","neural network","synthetic","saelens","feature","superposition","Neural","decompose","use","discovery","network","analyzing","2026-11-10 10:12:30",false,"---\nname: sparse-autoencoder-training\ndescription: Provides guidance for training and analyzing Sparse Autoencoders (SAEs) using SAELens to decompose neural network activations into interpretable features. Use when discovering interpretable features, analyzing superposition, or studying monosemantic representations in language models.\ncategory: ml-training\nversion: 1.0.0\nauthor: Synthetic Sciences\nlicense: MIT\ntags: [Sparse Autoencoders, SAE, Mechanistic Interpretability, Feature Discovery, Superposition]\ndependencies: [sae-lens>=6.0.0, transformer-lens>=2.0.0, torch>=2.0.0]\n---\n\n# SAELens: Sparse Autoencoders for Mechanistic Interpretability\n\nSAELens is the primary library for training and analyzing Sparse Autoencoders (SAEs) - a technique for decomposing polysemantic neural network activations into sparse, interpretable features. Based on Anthropic's groundbreaking research on monosemanticity.\n\n**GitHub**: [jbloomAus\u002FSAELens](https:\u002F\u002Fgithub.com\u002FjbloomAus\u002FSAELens) (1,100+ stars)\n\n## The Problem: Polysemanticity & Superposition\n\nIndividual neurons in neural networks are **polysemantic** - they activate in multiple, semantically distinct contexts. This happens because models use **superposition** to represent more features than they have neurons, making interpretability difficult.\n\n**SAEs solve this** by decomposing dense activations into sparse, monosemantic features - typically only a small number of features activate for any given input, and each feature corresponds to an interpretable concept.\n\n## When to Use SAELens\n\n**Use SAELens when you need to:**\n- Discover interpretable features in model activations\n- Understand what concepts a model has learned\n- Study superposition and feature geometry\n- Perform feature-based steering or ablation\n- Analyze safety-relevant features (deception, bias, harmful content)\n\n**Consider alternatives when:**\n- You need basic activation analysis → Use **TransformerLens** directly\n- You want causal intervention experiments → Use **pyvene** or **TransformerLens**\n- You need production steering → Consider direct activation engineering\n\n## Installation\n\n```bash\npip install sae-lens\n```\n\nRequirements: Python 3.10+, transformer-lens>=2.0.0\n\n## Core Concepts\n\n### What SAEs Learn\n\nSAEs are trained to reconstruct model activations through a sparse bottleneck:\n\n```\nInput Activation → Encoder → Sparse Features → Decoder → Reconstructed Activation\n    (d_model)       ↓        (d_sae >> d_model)    ↓         (d_model)\n                 sparsity                      reconstruction\n                 penalty                          loss\n```\n\n**Loss Function**: `MSE(original, reconstructed) + L1_coefficient × L1(features)`\n\n### Key Validation (Anthropic Research)\n\nIn \"Towards Monosemanticity\", human evaluators found **70% of SAE features genuinely interpretable**. Features discovered include:\n- DNA sequences, legal language, HTTP requests\n- Hebrew text, nutrition statements, code syntax\n- Sentiment, named entities, grammatical structures\n\n## Workflow 1: Loading and Analyzing Pre-trained SAEs\n\n### Step-by-Step\n\n```python\nfrom transformer_lens import HookedTransformer\nfrom sae_lens import SAE\n\n# 1. Load model and pre-trained SAE\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\", device=\"cuda\")\nsae, cfg_dict, sparsity = SAE.from_pretrained(\n    release=\"gpt2-small-res-jb\",\n    sae_id=\"blocks.8.hook_resid_pre\",\n    device=\"cuda\"\n)\n\n# 2. Get model activations\ntokens = model.to_tokens(\"The capital of France is Paris\")\n_, cache = model.run_with_cache(tokens)\nactivations = cache[\"resid_pre\", 8]  # [batch, pos, d_model]\n\n# 3. Encode to SAE features\nsae_features = sae.encode(activations)  # [batch, pos, d_sae]\nprint(f\"Active features: {(sae_features > 0).sum()}\")\n\n# 4. Find top features for each position\nfor pos in range(tokens.shape[1]):\n    top_features = sae_features[0, pos].topk(5)\n    token = model.to_str_tokens(tokens[0, pos:pos+1])[0]\n    print(f\"Token '{token}': features {top_features.indices.tolist()}\")\n\n# 5. Reconstruct activations\nreconstructed = sae.decode(sae_features)\nreconstruction_error = (activations - reconstructed).norm()\n```\n\n### Available Pre-trained SAEs\n\n| Release | Model | Layers |\n|---------|-------|--------|\n| `gpt2-small-res-jb` | GPT-2 Small | Multiple residual streams |\n| `gemma-2b-res` | Gemma 2B | Residual streams |\n| Various on HuggingFace | Search tag `saelens` | Various |\n\n### Checklist\n- [ ] Load model with TransformerLens\n- [ ] Load matching SAE for target layer\n- [ ] Encode activations to sparse features\n- [ ] Identify top-activating features per token\n- [ ] Validate reconstruction quality\n\n## Workflow 2: Training a Custom SAE\n\n### Step-by-Step\n\n```python\nfrom sae_lens import SAE, LanguageModelSAERunnerConfig, SAETrainingRunner\n\n# 1. Configure training\ncfg = LanguageModelSAERunnerConfig(\n    # Model\n    model_name=\"gpt2-small\",\n    hook_name=\"blocks.8.hook_resid_pre\",\n    hook_layer=8,\n    d_in=768,  # Model dimension\n\n    # SAE architecture\n    architecture=\"standard\",  # or \"gated\", \"topk\"\n    d_sae=768 * 8,  # Expansion factor of 8\n    activation_fn=\"relu\",\n\n    # Training\n    lr=4e-4,\n    l1_coefficient=8e-5,  # Sparsity penalty\n    l1_warm_up_steps=1000,\n    train_batch_size_tokens=4096,\n    training_tokens=100_000_000,\n\n    # Data\n    dataset_path=\"monology\u002Fpile-uncopyrighted\",\n    context_size=128,\n\n    # Logging\n    log_to_wandb=True,\n    wandb_project=\"sae-training\",\n\n    # Checkpointing\n    checkpoint_path=\"checkpoints\",\n    n_checkpoints=5,\n)\n\n# 2. Train\ntrainer = SAETrainingRunner(cfg)\nsae = trainer.run()\n\n# 3. Evaluate\nprint(f\"L0 (avg active features): {trainer.metrics['l0']}\")\nprint(f\"CE Loss Recovered: {trainer.metrics['ce_loss_score']}\")\n```\n\n### Key Hyperparameters\n\n| Parameter | Typical Value | Effect |\n|-----------|---------------|--------|\n| `d_sae` | 4-16× d_model | More features, higher capacity |\n| `l1_coefficient` | 5e-5 to 1e-4 | Higher = sparser, less accurate |\n| `lr` | 1e-4 to 1e-3 | Standard optimizer LR |\n| `l1_warm_up_steps` | 500-2000 | Prevents early feature death |\n\n### Evaluation Metrics\n\n| Metric | Target | Meaning |\n|--------|--------|---------|\n| **L0** | 50-200 | Average active features per token |\n| **CE Loss Score** | 80-95% | Cross-entropy recovered vs original |\n| **Dead Features** | \u003C5% | Features that never activate |\n| **Explained Variance** | >90% | Reconstruction quality |\n\n### Checklist\n- [ ] Choose target layer and hook point\n- [ ] Set expansion factor (d_sae = 4-16× d_model)\n- [ ] Tune L1 coefficient for desired sparsity\n- [ ] Enable L1 warm-up to prevent dead features\n- [ ] Monitor metrics during training (W&B)\n- [ ] Validate L0 and CE loss recovery\n- [ ] Check dead feature ratio\n\n## Workflow 3: Feature Analysis and Steering\n\n### Analyzing Individual Features\n\n```python\nfrom transformer_lens import HookedTransformer\nfrom sae_lens import SAE\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\", device=\"cuda\")\nsae, _, _ = SAE.from_pretrained(\n    release=\"gpt2-small-res-jb\",\n    sae_id=\"blocks.8.hook_resid_pre\",\n    device=\"cuda\"\n)\n\n# Find what activates a specific feature\nfeature_idx = 1234\ntest_texts = [\n    \"The scientist conducted an experiment\",\n    \"I love chocolate cake\",\n    \"The code compiles successfully\",\n    \"Paris is beautiful in spring\",\n]\n\nfor text in test_texts:\n    tokens = model.to_tokens(text)\n    _, cache = model.run_with_cache(tokens)\n    features = sae.encode(cache[\"resid_pre\", 8])\n    activation = features[0, :, feature_idx].max().item()\n    print(f\"{activation:.3f}: {text}\")\n```\n\n### Feature Steering\n\n```python\ndef steer_with_feature(model, sae, prompt, feature_idx, strength=5.0):\n    \"\"\"Add SAE feature direction to residual stream.\"\"\"\n    tokens = model.to_tokens(prompt)\n\n    # Get feature direction from decoder\n    feature_direction = sae.W_dec[feature_idx]  # [d_model]\n\n    def steering_hook(activation, hook):\n        # Add scaled feature direction at all positions\n        activation += strength * feature_direction\n        return activation\n\n    # Generate with steering\n    output = model.generate(\n        tokens,\n        max_new_tokens=50,\n        fwd_hooks=[(\"blocks.8.hook_resid_pre\", steering_hook)]\n    )\n    return model.to_string(output[0])\n```\n\n### Feature Attribution\n\n```python\n# Which features most affect a specific output?\ntokens = model.to_tokens(\"The capital of France is\")\n_, cache = model.run_with_cache(tokens)\n\n# Get features at final position\nfeatures = sae.encode(cache[\"resid_pre\", 8])[0, -1]  # [d_sae]\n\n# Get logit attribution per feature\n# Feature contribution = feature_activation × decoder_weight × unembedding\nW_dec = sae.W_dec  # [d_sae, d_model]\nW_U = model.W_U    # [d_model, vocab]\n\n# Contribution to \"Paris\" logit\nparis_token = model.to_single_token(\" Paris\")\nfeature_contributions = features * (W_dec @ W_U[:, paris_token])\n\ntop_features = feature_contributions.topk(10)\nprint(\"Top features for 'Paris' prediction:\")\nfor idx, val in zip(top_features.indices, top_features.values):\n    print(f\"  Feature {idx.item()}: {val.item():.3f}\")\n```\n\n## Common Issues & Solutions\n\n### Issue: High dead feature ratio\n```python\n# WRONG: No warm-up, features die early\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=1e-4,\n    l1_warm_up_steps=0,  # Bad!\n)\n\n# RIGHT: Warm-up L1 penalty\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=8e-5,\n    l1_warm_up_steps=1000,  # Gradually increase\n    use_ghost_grads=True,   # Revive dead features\n)\n```\n\n### Issue: Poor reconstruction (low CE recovery)\n```python\n# Reduce sparsity penalty\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=5e-5,  # Lower = better reconstruction\n    d_sae=768 * 16,       # More capacity\n)\n```\n\n### Issue: Features not interpretable\n```python\n# Increase sparsity (higher L1)\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=1e-4,  # Higher = sparser, more interpretable\n)\n# Or use TopK architecture\ncfg = LanguageModelSAERunnerConfig(\n    architecture=\"topk\",\n    activation_fn_kwargs={\"k\": 50},  # Exactly 50 active features\n)\n```\n\n### Issue: Memory errors during training\n```python\ncfg = LanguageModelSAERunnerConfig(\n    train_batch_size_tokens=2048,  # Reduce batch size\n    store_batch_size_prompts=4,    # Fewer prompts in buffer\n    n_batches_in_buffer=8,         # Smaller activation buffer\n)\n```\n\n## Integration with Neuronpedia\n\nBrowse pre-trained SAE features at [neuronpedia.org](https:\u002F\u002Fneuronpedia.org):\n\n```python\n# Features are indexed by SAE ID\n# Example: gpt2-small layer 8 feature 1234\n# → neuronpedia.org\u002Fgpt2-small\u002F8-res-jb\u002F1234\n```\n\n## Key Classes Reference\n\n| Class | Purpose |\n|-------|---------|\n| `SAE` | Sparse Autoencoder model |\n| `LanguageModelSAERunnerConfig` | Training configuration |\n| `SAETrainingRunner` | Training loop manager |\n| `ActivationsStore` | Activation collection and batching |\n| `HookedSAETransformer` | TransformerLens + SAE integration |\n\n## Reference Documentation\n\nFor detailed API documentation, tutorials, and advanced usage, see the `references\u002F` folder:\n\n| File | Contents |\n|------|----------|\n| [references\u002FREADME.md](references\u002FREADME.md) | Overview and quick start guide |\n| [references\u002Fapi.md](references\u002Fapi.md) | Complete API reference for SAE, TrainingSAE, configurations |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for training, analysis, steering |\n\n## External Resources\n\n### Tutorials\n- [Basic Loading & Analysis](https:\u002F\u002Fgithub.com\u002FjbloomAus\u002FSAELens\u002Fblob\u002Fmain\u002Ftutorials\u002Fbasic_loading_and_analysing.ipynb)\n- [Training a Sparse Autoencoder](https:\u002F\u002Fgithub.com\u002FjbloomAus\u002FSAELens\u002Fblob\u002Fmain\u002Ftutorials\u002Ftraining_a_sparse_autoencoder.ipynb)\n- [ARENA SAE Curriculum](https:\u002F\u002Fwww.lesswrong.com\u002Fposts\u002FLnHowHgmrMbWtpkxx\u002Fintro-to-superposition-and-sparse-autoencoders-colab)\n\n### Papers\n- [Towards Monosemanticity](https:\u002F\u002Ftransformer-circuits.pub\u002F2023\u002Fmonosemantic-features) - Anthropic (2023)\n- [Scaling Monosemanticity](https:\u002F\u002Ftransformer-circuits.pub\u002F2024\u002Fscaling-monosemanticity\u002F) - Anthropic (2024)\n- [Sparse Autoencoders Find Highly Interpretable Features](https:\u002F\u002Farxiv.org\u002Fabs\u002F2309.08600) - Cunningham et al. (ICLR 2024)\n\n### Official Documentation\n- [SAELens Docs](https:\u002F\u002Fjbloomaus.github.io\u002FSAELens\u002F)\n- [Neuronpedia](https:\u002F\u002Fneuronpedia.org) - Feature browser\n\n## SAE Architectures\n\n| Architecture | Description | Use Case |\n|--------------|-------------|----------|\n| **Standard** | ReLU + L1 penalty | General purpose |\n| **Gated** | Learned gating mechanism | Better sparsity control |\n| **TopK** | Exactly K active features | Consistent sparsity |\n\n```python\n# TopK SAE (exactly 50 features active)\ncfg = LanguageModelSAERunnerConfig(\n    architecture=\"topk\",\n    activation_fn=\"topk\",\n    activation_fn_kwargs={\"k\": 50},\n)\n```\n","# SAELens: Sparse Autoencoders for Mechanistic Interpretability\n\nSAELens is the primary library for training and analyzing Sparse Autoencoders (SAEs) - a technique for decomposing polysemantic neural network activations into sparse, interpretable features. Based on Anthropic's groundbreaking research on monosemanticity.\n\n**GitHub**: [jbloomAus\u002FSAELens](https:\u002F\u002Fgithub.com\u002FjbloomAus\u002FSAELens) (1,100+ stars)\n\n## The Problem: Polysemanticity & Superposition\n\nIndividual neurons in neural networks are **polysemantic** - they activate in multiple, semantically distinct contexts. This happens because models use **superposition** to represent more features than they have neurons, making interpretability difficult.\n\n**SAEs solve this** by decomposing dense activations into sparse, monosemantic features - typically only a small number of features activate for any given input, and each feature corresponds to an interpretable concept.\n\n## When to Use SAELens\n\n**Use SAELens when you need to:**\n- Discover interpretable features in model activations\n- Understand what concepts a model has learned\n- Study superposition and feature geometry\n- Perform feature-based steering or ablation\n- Analyze safety-relevant features (deception, bias, harmful content)\n\n**Consider alternatives when:**\n- You need basic activation analysis → Use **TransformerLens** directly\n- You want causal intervention experiments → Use **pyvene** or **TransformerLens**\n- You need production steering → Consider direct activation engineering\n\n## Installation\n\n```bash\npip install sae-lens\n```\n\nRequirements: Python 3.10+, transformer-lens>=2.0.0\n\n## Core Concepts\n\n### What SAEs Learn\n\nSAEs are trained to reconstruct model activations through a sparse bottleneck:\n\n```\nInput Activation → Encoder → Sparse Features → Decoder → Reconstructed Activation\n    (d_model)       ↓        (d_sae >> d_model)    ↓         (d_model)\n                 sparsity                      reconstruction\n                 penalty                          loss\n```\n\n**Loss Function**: `MSE(original, reconstructed) + L1_coefficient × L1(features)`\n\n### Key Validation (Anthropic Research)\n\nIn \"Towards Monosemanticity\", human evaluators found **70% of SAE features genuinely interpretable**. Features discovered include:\n- DNA sequences, legal language, HTTP requests\n- Hebrew text, nutrition statements, code syntax\n- Sentiment, named entities, grammatical structures\n\n## Workflow 1: Loading and Analyzing Pre-trained SAEs\n\n### Step-by-Step\n\n```python\nfrom transformer_lens import HookedTransformer\nfrom sae_lens import SAE\n\n# 1. Load model and pre-trained SAE\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\", device=\"cuda\")\nsae, cfg_dict, sparsity = SAE.from_pretrained(\n    release=\"gpt2-small-res-jb\",\n    sae_id=\"blocks.8.hook_resid_pre\",\n    device=\"cuda\"\n)\n\n# 2. Get model activations\ntokens = model.to_tokens(\"The capital of France is Paris\")\n_, cache = model.run_with_cache(tokens)\nactivations = cache[\"resid_pre\", 8]  # [batch, pos, d_model]\n\n# 3. Encode to SAE features\nsae_features = sae.encode(activations)  # [batch, pos, d_sae]\nprint(f\"Active features: {(sae_features > 0).sum()}\")\n\n# 4. Find top features for each position\nfor pos in range(tokens.shape[1]):\n    top_features = sae_features[0, pos].topk(5)\n    token = model.to_str_tokens(tokens[0, pos:pos+1])[0]\n    print(f\"Token '{token}': features {top_features.indices.tolist()}\")\n\n# 5. Reconstruct activations\nreconstructed = sae.decode(sae_features)\nreconstruction_error = (activations - reconstructed).norm()\n```\n\n### Available Pre-trained SAEs\n\n| Release | Model | Layers |\n|---------|-------|--------|\n| `gpt2-small-res-jb` | GPT-2 Small | Multiple residual streams |\n| `gemma-2b-res` | Gemma 2B | Residual streams |\n| Various on HuggingFace | Search tag `saelens` | Various |\n\n### Checklist\n- [ ] Load model with TransformerLens\n- [ ] Load matching SAE for target layer\n- [ ] Encode activations to sparse features\n- [ ] Identify top-activating features per token\n- [ ] Validate reconstruction quality\n\n## Workflow 2: Training a Custom SAE\n\n### Step-by-Step\n\n```python\nfrom sae_lens import SAE, LanguageModelSAERunnerConfig, SAETrainingRunner\n\n# 1. Configure training\ncfg = LanguageModelSAERunnerConfig(\n    # Model\n    model_name=\"gpt2-small\",\n    hook_name=\"blocks.8.hook_resid_pre\",\n    hook_layer=8,\n    d_in=768,  # Model dimension\n\n    # SAE architecture\n    architecture=\"standard\",  # or \"gated\", \"topk\"\n    d_sae=768 * 8,  # Expansion factor of 8\n    activation_fn=\"relu\",\n\n    # Training\n    lr=4e-4,\n    l1_coefficient=8e-5,  # Sparsity penalty\n    l1_warm_up_steps=1000,\n    train_batch_size_tokens=4096,\n    training_tokens=100_000_000,\n\n    # Data\n    dataset_path=\"monology\u002Fpile-uncopyrighted\",\n    context_size=128,\n\n    # Logging\n    log_to_wandb=True,\n    wandb_project=\"sae-training\",\n\n    # Checkpointing\n    checkpoint_path=\"checkpoints\",\n    n_checkpoints=5,\n)\n\n# 2. Train\ntrainer = SAETrainingRunner(cfg)\nsae = trainer.run()\n\n# 3. Evaluate\nprint(f\"L0 (avg active features): {trainer.metrics['l0']}\")\nprint(f\"CE Loss Recovered: {trainer.metrics['ce_loss_score']}\")\n```\n\n### Key Hyperparameters\n\n| Parameter | Typical Value | Effect |\n|-----------|---------------|--------|\n| `d_sae` | 4-16× d_model | More features, higher capacity |\n| `l1_coefficient` | 5e-5 to 1e-4 | Higher = sparser, less accurate |\n| `lr` | 1e-4 to 1e-3 | Standard optimizer LR |\n| `l1_warm_up_steps` | 500-2000 | Prevents early feature death |\n\n### Evaluation Metrics\n\n| Metric | Target | Meaning |\n|--------|--------|---------|\n| **L0** | 50-200 | Average active features per token |\n| **CE Loss Score** | 80-95% | Cross-entropy recovered vs original |\n| **Dead Features** | \u003C5% | Features that never activate |\n| **Explained Variance** | >90% | Reconstruction quality |\n\n### Checklist\n- [ ] Choose target layer and hook point\n- [ ] Set expansion factor (d_sae = 4-16× d_model)\n- [ ] Tune L1 coefficient for desired sparsity\n- [ ] Enable L1 warm-up to prevent dead features\n- [ ] Monitor metrics during training (W&B)\n- [ ] Validate L0 and CE loss recovery\n- [ ] Check dead feature ratio\n\n## Workflow 3: Feature Analysis and Steering\n\n### Analyzing Individual Features\n\n```python\nfrom transformer_lens import HookedTransformer\nfrom sae_lens import SAE\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\", device=\"cuda\")\nsae, _, _ = SAE.from_pretrained(\n    release=\"gpt2-small-res-jb\",\n    sae_id=\"blocks.8.hook_resid_pre\",\n    device=\"cuda\"\n)\n\n# Find what activates a specific feature\nfeature_idx = 1234\ntest_texts = [\n    \"The scientist conducted an experiment\",\n    \"I love chocolate cake\",\n    \"The code compiles successfully\",\n    \"Paris is beautiful in spring\",\n]\n\nfor text in test_texts:\n    tokens = model.to_tokens(text)\n    _, cache = model.run_with_cache(tokens)\n    features = sae.encode(cache[\"resid_pre\", 8])\n    activation = features[0, :, feature_idx].max().item()\n    print(f\"{activation:.3f}: {text}\")\n```\n\n### Feature Steering\n\n```python\ndef steer_with_feature(model, sae, prompt, feature_idx, strength=5.0):\n    \"\"\"Add SAE feature direction to residual stream.\"\"\"\n    tokens = model.to_tokens(prompt)\n\n    # Get feature direction from decoder\n    feature_direction = sae.W_dec[feature_idx]  # [d_model]\n\n    def steering_hook(activation, hook):\n        # Add scaled feature direction at all positions\n        activation += strength * feature_direction\n        return activation\n\n    # Generate with steering\n    output = model.generate(\n        tokens,\n        max_new_tokens=50,\n        fwd_hooks=[(\"blocks.8.hook_resid_pre\", steering_hook)]\n    )\n    return model.to_string(output[0])\n```\n\n### Feature Attribution\n\n```python\n# Which features most affect a specific output?\ntokens = model.to_tokens(\"The capital of France is\")\n_, cache = model.run_with_cache(tokens)\n\n# Get features at final position\nfeatures = sae.encode(cache[\"resid_pre\", 8])[0, -1]  # [d_sae]\n\n# Get logit attribution per feature\n# Feature contribution = feature_activation × decoder_weight × unembedding\nW_dec = sae.W_dec  # [d_sae, d_model]\nW_U = model.W_U    # [d_model, vocab]\n\n# Contribution to \"Paris\" logit\nparis_token = model.to_single_token(\" Paris\")\nfeature_contributions = features * (W_dec @ W_U[:, paris_token])\n\ntop_features = feature_contributions.topk(10)\nprint(\"Top features for 'Paris' prediction:\")\nfor idx, val in zip(top_features.indices, top_features.values):\n    print(f\"  Feature {idx.item()}: {val.item():.3f}\")\n```\n\n## Common Issues & Solutions\n\n### Issue: High dead feature ratio\n```python\n# WRONG: No warm-up, features die early\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=1e-4,\n    l1_warm_up_steps=0,  # Bad!\n)\n\n# RIGHT: Warm-up L1 penalty\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=8e-5,\n    l1_warm_up_steps=1000,  # Gradually increase\n    use_ghost_grads=True,   # Revive dead features\n)\n```\n\n### Issue: Poor reconstruction (low CE recovery)\n```python\n# Reduce sparsity penalty\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=5e-5,  # Lower = better reconstruction\n    d_sae=768 * 16,       # More capacity\n)\n```\n\n### Issue: Features not interpretable\n```python\n# Increase sparsity (higher L1)\ncfg = LanguageModelSAERunnerConfig(\n    l1_coefficient=1e-4,  # Higher = sparser, more interpretable\n)\n# Or use TopK architecture\ncfg = LanguageModelSAERunnerConfig(\n    architecture=\"topk\",\n    activation_fn_kwargs={\"k\": 50},  # Exactly 50 active features\n)\n```\n\n### Issue: Memory errors during training\n```python\ncfg = LanguageModelSAERunnerConfig(\n    train_batch_size_tokens=2048,  # Reduce batch size\n    store_batch_size_prompts=4,    # Fewer prompts in buffer\n    n_batches_in_buffer=8,         # Smaller activation buffer\n)\n```\n\n## Integration with Neuronpedia\n\nBrowse pre-trained SAE features at [neuronpedia.org](https:\u002F\u002Fneuronpedia.org):\n\n```python\n# Features are indexed by SAE ID\n# Example: gpt2-small layer 8 feature 1234\n# → neuronpedia.org\u002Fgpt2-small\u002F8-res-jb\u002F1234\n```\n\n## Key Classes Reference\n\n| Class | Purpose |\n|-------|---------|\n| `SAE` | Sparse Autoencoder model |\n| `LanguageModelSAERunnerConfig` | Training configuration |\n| `SAETrainingRunner` | Training loop manager |\n| `ActivationsStore` | Activation collection and batching |\n| `HookedSAETransformer` | TransformerLens + SAE integration |\n\n## Reference Documentation\n\nFor detailed API documentation, tutorials, and advanced usage, see the `references\u002F` folder:\n\n| File | Contents |\n|------|----------|\n| [references\u002FREADME.md](references\u002FREADME.md) | Overview and quick start guide |\n| [references\u002Fapi.md](references\u002Fapi.md) | Complete API reference for SAE, TrainingSAE, configurations |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for training, analysis, steering |\n\n## External Resources\n\n### Tutorials\n- [Basic Loading & Analysis](https:\u002F\u002Fgithub.com\u002FjbloomAus\u002FSAELens\u002Fblob\u002Fmain\u002Ftutorials\u002Fbasic_loading_and_analysing.ipynb)\n- [Training a Sparse Autoencoder](https:\u002F\u002Fgithub.com\u002FjbloomAus\u002FSAELens\u002Fblob\u002Fmain\u002Ftutorials\u002Ftraining_a_sparse_autoencoder.ipynb)\n- [ARENA SAE Curriculum](https:\u002F\u002Fwww.lesswrong.com\u002Fposts\u002FLnHowHgmrMbWtpkxx\u002Fintro-to-superposition-and-sparse-autoencoders-colab)\n\n### Papers\n- [Towards Monosemanticity](https:\u002F\u002Ftransformer-circuits.pub\u002F2023\u002Fmonosemantic-features) - Anthropic (2023)\n- [Scaling Monosemanticity](https:\u002F\u002Ftransformer-circuits.pub\u002F2024\u002Fscaling-monosemanticity\u002F) - Anthropic (2024)\n- [Sparse Autoencoders Find Highly Interpretable Features](https:\u002F\u002Farxiv.org\u002Fabs\u002F2309.08600) - Cunningham et al. (ICLR 2024)\n\n### Official Documentation\n- [SAELens Docs](https:\u002F\u002Fjbloomaus.github.io\u002FSAELens\u002F)\n- [Neuronpedia](https:\u002F\u002Fneuronpedia.org) - Feature browser\n\n## SAE Architectures\n\n| Architecture | Description | Use Case |\n|--------------|-------------|----------|\n| **Standard** | ReLU + L1 penalty | General purpose |\n| **Gated** | Learned gating mechanism | Better sparsity control |\n| **TopK** | Exactly K active features | Consistent sparsity |\n\n```python\n# TopK SAE (exactly 50 features active)\ncfg = LanguageModelSAERunnerConfig(\n    architecture=\"topk\",\n    activation_fn=\"topk\",\n    activation_fn_kwargs={\"k\": 50},\n)\n```\n",{"name":5,"tags":44,"author":50,"license":15,"version":51,"category":52,"description":7,"dependencies":53},[45,46,47,48,49],"Sparse Autoencoders","SAE","Mechanistic Interpretability","Feature Discovery","Superposition","Synthetic Sciences","1.0.0","ml-training",[54,55,56],"sae-lens>=6.0.0","transformer-lens>=2.0.0","torch>=2.0.0","main","4aa39efd1cdab0b4657ecee16c92a92011a5b10f","openscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Fsaelens","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub","https:\u002F\u002Fgithub.com\u002Ffadrienne","2026-10-28 00:43:09",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add fadrienne\u002FMyGitHub --skill sparse-autoencoder-training",{"tool":69,"command":70},"bunx","bunx skills add fadrienne\u002FMyGitHub --skill sparse-autoencoder-training",{"tool":72,"command":73},"pnpm","pnpm dlx skills add fadrienne\u002FMyGitHub --skill sparse-autoencoder-training","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Fsaelens\u002FSKILL.md",true,[77,83,87],{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Fapi.md","REFERENCE","参考文档",6968,"https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Fsaelens\u002Freferences\u002Fapi.md",{"path":84,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002FREADME.md",2155,"https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Fsaelens\u002Freferences\u002FREADME.md",{"path":88,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Ftutorials.md",9383,"https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Fsaelens\u002Freferences\u002Ftutorials.md",[92,123,148,181,208,235],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":103,"publishedAt":39},"01M7167B28PK20HP7R7ZED2DY0","statistical-power","Sample size calculation, power analysis, and effect size conversion for scientific studies. Use BEFORE data collection (a priori) to determine required N, or after (post-hoc) to compute achieved power. Covers parametric tests (t-test, ANOVA, chi-square, proportions, correlation, regression), simulation-based power for complex\u002Fclustered\u002Fnested designs, and power curves. Use this skill when someone asks 'how many samples do I need', 'what is my power', 'what effect size can I detect', or any variant. Pairs with \u002Fexperimental-design (choose design first, then compute power) and \u002Fstatistical-analysis (analyze data after collection).","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fscientific-agent-skills\u002Fskills\u002Fstatistical-power\u002FSKILL.md",[98],{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[104,105,106,107,108,109,110,111,21,112,113,114,115,116,117,118,119,120,121,122],"power","statistical power","effect","scipy","regression","choose","design","uv","Bash","collection","analysis","calculation","ANOVA","conversion","analyze","t-test","chi-square","simulation","sample",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":132,"publishedAt":39},"01M71677EBCM8EPCE9BZCK8505","statistical-analysis","Guided statistical analysis with test selection and reporting. Use when you need help choosing appropriate tests for your data, assumption checking, power analysis, and APA-formatted results. Best for academic research reporting, test selection guidance. For implementing specific models programmatically use statsmodels.","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fscientific-agent-skills\u002Fskills\u002Fstatistical-analysis\u002FSKILL.md",[129],{"categoryNo":130,"categoryName":131,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000008","测试与质量",[114,133,104,134,135,136,21,137,138,139,24,140,35,141,142,143,144,145,146,147],"statistical analysis","academic research","implementing","selection","you","reporting","data","tests","with","test","research","results","statsmodels","models","help",{"skillNo":149,"name":150,"nameZh":6,"description":151,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":152,"categories":153,"keywords":163,"publishedAt":39},"01M71673R93XAHFH81DBNVNG7H","scientific-writing","Core skill for the deep research and writing tool. Write scientific manuscripts in full paragraphs (never bullet points). Use two-stage process with (1) section outlines with key points using research-lookup then (2) convert to flowing prose. IMRAD structure, citations (APA\u002FAMA\u002FVancouver), figures\u002Ftables, reporting guidelines (CONSORT\u002FSTROBE\u002FPRISMA), for research papers and journal submissions.","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fscientific-agent-skills\u002Fskills\u002Fscientific-writing\u002FSKILL.md",[154,157,158],{"categoryNo":155,"categoryName":156,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},{"categoryNo":159,"categoryName":160,"taxonomyType":161,"taxonomyTypeDesc":162},"01JBSEEDCAT000000000000036","内容创作者","PROFESSION","适用职业",[164,165,166,167,168,169,170,171,172,173,112,174,175,176,177,178,179,180,138,23],"writing","scientific","scientific writing","Citations","deep","deep research","never","papers","journal","false","api","prisma","structure","openrouter","Outlines","core skill","read",{"skillNo":182,"name":183,"nameZh":6,"description":184,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":185,"categories":186,"keywords":191,"publishedAt":39},"01M7166ZPKXBF4EBPHVTJPQBB1","scientific-visualization","Meta-skill for publication-ready figures. Use when creating journal submission figures requiring multi-panel layouts, significance annotations, error bars, colorblind-safe palettes, and specific journal formatting (Nature, Science, Cell). Orchestrates matplotlib\u002Fseaborn\u002Fplotly with publication styles. For quick exploration use seaborn or plotly directly.","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fscientific-agent-skills\u002Fskills\u002Fscientific-visualization\u002FSKILL.md",[187,190],{"categoryNo":188,"categoryName":189,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000013","分析与可视化",{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},[192,165,193,194,195,196,197,198,199,172,21,200,201,202,203,204,205,206,24,207],"visualization","scientific visualization","error","ready","quick","exploration","meta-skill","Meta","safe","plotly","annotations","formatting","Publication","figures","panel","submission",{"skillNo":209,"name":210,"nameZh":6,"description":211,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":212,"categories":213,"keywords":220,"publishedAt":39},"01M7166VXJWQSSC3RQZP60WBGR","research-code","Debug, profile, review, and restructure Python research and analysis code. Use when analysis scripts crash, produce wrong results, run too slowly, or need a correctness review. Covers: reading tracebacks and diagnosing root causes, hypothesis-driven debugging, reviewing code for common statistical\u002Fnumerical errors, profiling data pipelines, improving reproducibility (seeds, environments, determinism), and structuring analysis scripts for sharing. Distinct from \u002Fexploratory-data-analysis (which understands data) and \u002Fstatistical-analysis (which chooses and runs tests) — this skill focuses on the code itself.","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fscientific-agent-skills\u002Fskills\u002Fresearch-code\u002FSKILL.md",[214,217],{"categoryNo":215,"categoryName":216,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000021","资料检索与研究",{"categoryNo":218,"categoryName":219,"taxonomyType":161,"taxonomyTypeDesc":162},"01JBSEEDCAT000000000000030","开发工程师",[221,222,143,223,224,225,226,111,227,21,112,114,228,229,230,231,232,233,180,234],"code","research code","which","memory","data-analysis","errors","debugging","common","review","data pipelines","run","scripts","line","write",{"skillNo":236,"name":237,"nameZh":6,"description":238,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":239,"licenseFileUrl":6,"sourceHtmlUrl":240,"categories":241,"keywords":248,"publishedAt":39},"01M7166CF5HSR7SVZYZFWTDX55","markdown-mermaid-writing","Comprehensive markdown and Mermaid diagram writing skill. Use when creating any scientific document, report, analysis, or visualization. Establishes text-based diagrams as the default documentation standard with full style guides (markdown + mermaid), 24 diagram type references, and 9 document templates.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fscientific-agent-skills\u002Fskills\u002Fmarkdown-mermaid-writing\u002FSKILL.md",[242,245,246,247],{"categoryNo":243,"categoryName":244,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000002","文档处理",{"categoryNo":155,"categoryName":156,"taxonomyType":101,"taxonomyTypeDesc":102},{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},{"categoryNo":159,"categoryName":160,"taxonomyType":161,"taxonomyTypeDesc":162},[164,249,250,251,252,253,192,254,255,21,112,114,256,257,258,259,260,261,165,180],"markdown mermaid writing","mermaid","markdown","community","diagrams","project","default","team","guides","text","documentation","references","diagram"]