[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ADT1ZPKB2TF4RHRVF0CCNW":3,"skill-same:01M6ADT1ZPKB2TF4RHRVF0CCNW":106},{"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":23,"publishedAt":45,"linkOnly":46,"markdownContent":47,"markdownBody":48,"frontMatter":49,"refName":62,"commitSha":63,"skillDirectory":64,"forksCount":65,"repositoryHtmlUrl":66,"repositoryHomepageUrl":67,"ownerHtmlUrl":68,"ownerBlogUrl":69,"ownerDescription":70,"updatedAt":71,"install":72,"resources":85},"01M6ADT1ZPKB2TF4RHRVF0CCNW","mechanistic-interpretability-saelens",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.","davila7\u002Fclaude-code-templates","davila7","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6216945?v=4","01M6ADEWWFPS191NFM0Y1EX1JH","Daniel Avila","01M6ADJHGM78PHQRD3XZTFDVKK",33332,"MIT","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-saelens\u002FSKILL.md",[18],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000021","资料检索与研究","SCENARIO","使用场景",[24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],"mechanistic interpretability saelens","Interpretability","Mechanistic Interpretability","saelens","feature","when","features","for","orchestra","Transformer","lens","neural network","research","superposition","Neural","decompose","use","discovery","network","analyzing","training","2026-11-10 10:12:30",false,"---\nname: mechanistic-interpretability-saelens\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.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  author: Orchestra Research\n  tags: [Sparse Autoencoders, SAE, Mechanistic Interpretability, Feature Discovery, Superposition]\n  dependencies: [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,"license":15,"metadata":50,"description":7},{"tags":51,"author":56,"version":57,"dependencies":58},[52,53,26,54,55],"Sparse Autoencoders","SAE","Feature Discovery","Superposition","Orchestra Research","1.0.0",[59,60,61],"sae-lens>=6.0.0","transformer-lens>=2.0.0","torch>=2.0.0","main","2b749c82b5d11fac39d9a6e021ce3f5b8a541bd1","cli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-saelens",3911,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates","https:\u002F\u002Faitmpl.com","https:\u002F\u002Fgithub.com\u002Fdavila7","https:\u002F\u002Fdanielavila.me","Building AI dev tools with LLMs","2026-11-11 21:38:31",{"source":8,"skillName":5,"commands":73,"prompt":83,"zipAvailable":84},[74,77,80],{"tool":75,"command":76},"npx","npx skills add davila7\u002Fclaude-code-templates --skill mechanistic-interpretability-saelens",{"tool":78,"command":79},"bunx","bunx skills add davila7\u002Fclaude-code-templates --skill mechanistic-interpretability-saelens",{"tool":81,"command":82},"pnpm","pnpm dlx skills add davila7\u002Fclaude-code-templates --skill mechanistic-interpretability-saelens","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-saelens\u002FSKILL.md",true,[86,92,96,100],{"path":87,"resourceType":88,"resourceTypeDesc":89,"sizeBytes":90,"sourceHtmlUrl":91},"references\u002Fapi.md","REFERENCE","参考文档",6968,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-saelens\u002Freferences\u002Fapi.md",{"path":93,"resourceType":88,"resourceTypeDesc":89,"sizeBytes":94,"sourceHtmlUrl":95},"references\u002FREADME.md",2155,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-saelens\u002Freferences\u002FREADME.md",{"path":97,"resourceType":88,"resourceTypeDesc":89,"sizeBytes":98,"sourceHtmlUrl":99},"references\u002Ftutorials.md",9383,"https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fai-research\u002Fmechanistic-interpretability-saelens\u002Freferences\u002Ftutorials.md",{"path":101,"resourceType":102,"resourceTypeDesc":103,"sizeBytes":104,"sourceHtmlUrl":105},"SKILL.md.tmpl","OTHER","其他",8548,"https:\u002F\u002Fgithub.com\u002Fshengdabai\u002FTony-Claude-Code-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fgstack\u002Fpair-agent\u002FSKILL.md.tmpl",[107,134,161,194,229,253],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":116,"publishedAt":45},"01M70NHBTQ8BV0A2SCAZXEPHCX","wealthville-pool-scoring","Score DeFi liquidity pools before providing liquidity. Returns a 0-100 pool score and an Enter\u002FHold\u002FExit\u002FReduce\u002FAvoid verdict with calibrated confidence for ~68,800 Solana pools and 575 EVM pools, plus a public miss-inclusive track record. Use when asked whether a pool is worth LPing into, which pools look best right now, or how accurate the scores have actually been.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fweb-data\u002Fwealthville-pool-scoring\u002FSKILL.md",[113],{"categoryNo":114,"categoryName":115,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[117,118,119,120,121,31,122,123,40,29,124,125,126,127,128,129,130,131,132,133],"scoring","pool","wealthville pool scoring","liquidity","which","exit","now","reduce","with","record","track","verdict","evm","solana","how","public","look",{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":141,"publishedAt":45},"01M70MB6VR8ERJ4EM8D5KHBMEV","technical-debt-auditor","Scans a codebase and produces a quantified technical debt report with a prioritized remediation plan. Analyzes dead code, TODO\u002FFIXME\u002FHACK markers, dependency staleness, complexity hotspots, code duplication signals, test coverage gaps, unused exports, and outdated patterns. Use this skill when the user asks to audit their codebase for tech debt, wants a health check of their code quality, says things like \"where should I focus refactoring\", \"find code smells\", \"audit my codebase\", \"what technical debt do we have\", \"prioritize cleanup work\", or asks about code quality metrics. Also trigger when the user mentions \"code rot\", \"legacy cleanup\", \"refactoring priorities\", or wants to understand the overall health of a project before a major effort. Trigger even if the user doesn't say \"technical debt\" explicitly — any request to systematically assess code quality and identify improvement priorities belongs here.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdevelopment\u002Ftechnical-debt-auditor\u002FSKILL.md",[140],{"categoryNo":114,"categoryName":115,"taxonomyType":21,"taxonomyTypeDesc":22},[142,143,144,145,146,147,148,149,150,151,152,29,153,154,155,156,157,158,159,160],"technical debt","debt","technical","technical debt auditor","auditor","coverage","complexity","markers","project","cleanup","unused","code","todo","work","plan","focus","signals","audit","dependency",{"skillNo":162,"name":163,"nameZh":6,"description":164,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":165,"categories":166,"keywords":176,"publishedAt":45},"01M70KPYH9QNHCNME5GJQGE22K","readonly-sql-guard","Make an agent's database access provably read-only. Use when an agent runs caller-supplied SQL against a production\u002FERP\u002Fanalytics database (a \"query\" MCP tool, text-to-SQL, an admin console), or when reviewing DB-access code for write\u002FDDL\u002Fside-effect\u002Ftransaction-escape risks. Checks what a statement CALLS, not just its shape.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fdatabase\u002Freadonly-sql-guard\u002FSKILL.md",[167,170,171],{"categoryNo":168,"categoryName":169,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":114,"categoryName":115,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":172,"categoryName":173,"taxonomyType":174,"taxonomyTypeDesc":175},"01JBSEEDCAT000000000000033","数据分析师","PROFESSION","适用职业",[177,178,179,180,181,182,183,31,184,185,186,187,188,189,190,40,191,192,29,193],"readonly","guard","sql guard","sql","readonly sql guard","erp","effect","read-only","db","just","tool","calls","only","MCP","access","database","query",{"skillNo":195,"name":196,"nameZh":6,"description":197,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":198,"licenseFileUrl":199,"sourceHtmlUrl":200,"categories":201,"keywords":205,"publishedAt":45},"01M6AFY6F7CC2BBZP1QD6VTNVC","web-artifacts-builder","Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn\u002Fui). Use for complex artifacts requiring state management, routing, or shadcn\u002Fui components - not for simple single-file HTML\u002FJSX artifacts.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Futilities\u002Fweb-artifacts-builder\u002FSKILL.md",[202],{"categoryNo":203,"categoryName":204,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",[206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,31,228],"artifacts builder","web","web artifacts builder","artifacts","builder","state","routing","state management","component","css","frontend","ui","Tools","file","components","shadcn","react","Tailwind","suite","jsx","html","single-file","ui components",{"skillNo":230,"name":231,"nameZh":6,"description":232,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":198,"licenseFileUrl":233,"sourceHtmlUrl":234,"categories":235,"keywords":240,"publishedAt":45},"01M6AFWF33SFV9Z3SF4PEEE4BF","webapp-testing","Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fsecurity\u002Fwebapp-testing\u002FSKILL.md",[236,239],{"categoryNo":237,"categoryName":238,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":203,"categoryName":204,"taxonomyType":21,"taxonomyTypeDesc":22},[241,242,243,244,245,207,246,216,217,247,248,249,250,31,251,125,252],"webapp testing","testing","webapp","browser","playwright","applications","debugging","toolkit","logs","screenshots","local","behavior",{"skillNo":254,"name":255,"nameZh":6,"description":256,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":198,"licenseFileUrl":257,"sourceHtmlUrl":258,"categories":259,"keywords":267,"publishedAt":45},"01M6AF67Q67JJJ5V51JR2P52KA","discernment-nudge","After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals, or emails, estimates or projections, analysis or interpretation of data, factual claims they may rely on, or a multi-step argument — invoke this skill BEFORE finalizing your reply and then, if it applies, append 2-3 short follow-up questions, each tied to something specific in what you just produced, that help the user check key facts, probe the reasoning or assumptions, and notice missing context. Do this at most once per conversation. Skip it when the user asked a trivial how-to or simple lookup, wants a purely educational explanation, asked you only to format, convert, or assemble a file from content they provided, is writing code they will run, is doing creative writing or casual chat, or already asked you to double-check, cite, or review — the skill file explains these boundaries and the exact output format.","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fdavila7\u002Fclaude-code-templates\u002Fblob\u002Fmain\u002Fcli-tool\u002Fcomponents\u002Fskills\u002Fproductivity\u002Fdiscernment-nudge\u002FSKILL.md",[260,263,264],{"categoryNo":261,"categoryName":262,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":114,"categoryName":115,"taxonomyType":21,"taxonomyTypeDesc":22},{"categoryNo":265,"categoryName":266,"taxonomyType":174,"taxonomyTypeDesc":175},"01JBSEEDCAT000000000000036","内容创作者",[268,269,270,271,272,273,274,275,209,276,219,153,277,278,279,280,281,189,282,29,283,284,285,286,287,131,288],"discernment nudge","nudge","interpretation","help","run","reasoning","data","writing","lookup","content","review","conversation","short","up","invoke","you","analysis","claims","argument","assemble","recommendations"]