[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6XGGMERHPCT9DDV6D35ZT0E":3,"skill-same:01M6XGGMERHPCT9DDV6D35ZT0E":88},{"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":54,"commitSha":55,"skillDirectory":56,"forksCount":14,"repositoryHtmlUrl":57,"repositoryHomepageUrl":6,"ownerHtmlUrl":58,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":59,"install":60,"resources":73},"01M6XGGMERHPCT9DDV6D35ZT0E","transformer-lens-interpretability",null,"Provides guidance for mechanistic interpretability research using TransformerLens to inspect and manipulate transformer internals via HookPoints and activation caching. Use when reverse-engineering model algorithms, studying attention patterns, or performing activation patching experiments.","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\u002Ftransformer-lens\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"transformer lens interpretability","transformer lens","Interpretability","Transformer","lens","synthetic","when","inspect","Activation Patching","circuit analysis","experiments","caching","algorithms","patterns","activation","model","patching","analysis","reverse-engineering","training","2026-11-10 10:12:30",false,"---\nname: transformer-lens-interpretability\ndescription: Provides guidance for mechanistic interpretability research using TransformerLens to inspect and manipulate transformer internals via HookPoints and activation caching. Use when reverse-engineering model algorithms, studying attention patterns, or performing activation patching experiments.\ncategory: ml-training\nversion: 1.0.0\nauthor: Synthetic Sciences\nlicense: MIT\ntags: [Mechanistic Interpretability, TransformerLens, Activation Patching, Circuit Analysis]\ndependencies: [transformer-lens>=2.0.0, torch>=2.0.0]\n---\n\n# TransformerLens: Mechanistic Interpretability for Transformers\n\nTransformerLens is the de facto standard library for mechanistic interpretability research on GPT-style language models. Created by Neel Nanda and maintained by Bryce Meyer, it provides clean interfaces to inspect and manipulate model internals via HookPoints on every activation.\n\n**GitHub**: [TransformerLensOrg\u002FTransformerLens](https:\u002F\u002Fgithub.com\u002FTransformerLensOrg\u002FTransformerLens) (2,900+ stars)\n\n## When to Use TransformerLens\n\n**Use TransformerLens when you need to:**\n- Reverse-engineer algorithms learned during training\n- Perform activation patching \u002F causal tracing experiments\n- Study attention patterns and information flow\n- Analyze circuits (e.g., induction heads, IOI circuit)\n- Cache and inspect intermediate activations\n- Apply direct logit attribution\n\n**Consider alternatives when:**\n- You need to work with non-transformer architectures → Use **nnsight** or **pyvene**\n- You want to train\u002Fanalyze Sparse Autoencoders → Use **SAELens**\n- You need remote execution on massive models → Use **nnsight** with NDIF\n- You want higher-level causal intervention abstractions → Use **pyvene**\n\n## Installation\n\n```bash\npip install transformer-lens\n```\n\nFor development version:\n```bash\npip install git+https:\u002F\u002Fgithub.com\u002FTransformerLensOrg\u002FTransformerLens\n```\n\n## Core Concepts\n\n### HookedTransformer\n\nThe main class that wraps transformer models with HookPoints on every activation:\n\n```python\nfrom transformer_lens import HookedTransformer\n\n# Load a model\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# For gated models (LLaMA, Mistral)\nimport os\nos.environ[\"HF_TOKEN\"] = \"your_token\"\nmodel = HookedTransformer.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n```\n\n### Supported Models (50+)\n\n| Family | Models |\n|--------|--------|\n| GPT-2 | gpt2, gpt2-medium, gpt2-large, gpt2-xl |\n| LLaMA | llama-7b, llama-13b, llama-2-7b, llama-2-13b |\n| EleutherAI | pythia-70m to pythia-12b, gpt-neo, gpt-j-6b |\n| Mistral | mistral-7b, mixtral-8x7b |\n| Others | phi, qwen, opt, gemma |\n\n### Activation Caching\n\nRun the model and cache all intermediate activations:\n\n```python\n# Get all activations\ntokens = model.to_tokens(\"The Eiffel Tower is in\")\nlogits, cache = model.run_with_cache(tokens)\n\n# Access specific activations\nresidual = cache[\"resid_post\", 5]  # Layer 5 residual stream\nattn_pattern = cache[\"pattern\", 3]  # Layer 3 attention pattern\nmlp_out = cache[\"mlp_out\", 7]  # Layer 7 MLP output\n\n# Filter which activations to cache (saves memory)\nlogits, cache = model.run_with_cache(\n    tokens,\n    names_filter=lambda name: \"resid_post\" in name\n)\n```\n\n### ActivationCache Keys\n\n| Key Pattern | Shape | Description |\n|-------------|-------|-------------|\n| `resid_pre, layer` | [batch, pos, d_model] | Residual before attention |\n| `resid_mid, layer` | [batch, pos, d_model] | Residual after attention |\n| `resid_post, layer` | [batch, pos, d_model] | Residual after MLP |\n| `attn_out, layer` | [batch, pos, d_model] | Attention output |\n| `mlp_out, layer` | [batch, pos, d_model] | MLP output |\n| `pattern, layer` | [batch, head, q_pos, k_pos] | Attention pattern (post-softmax) |\n| `q, layer` | [batch, pos, head, d_head] | Query vectors |\n| `k, layer` | [batch, pos, head, d_head] | Key vectors |\n| `v, layer` | [batch, pos, head, d_head] | Value vectors |\n\n## Workflow 1: Activation Patching (Causal Tracing)\n\nIdentify which activations causally affect model output by patching clean activations into corrupted runs.\n\n### Step-by-Step\n\n```python\nfrom transformer_lens import HookedTransformer, patching\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# 1. Define clean and corrupted prompts\nclean_prompt = \"The Eiffel Tower is in the city of\"\ncorrupted_prompt = \"The Colosseum is in the city of\"\n\nclean_tokens = model.to_tokens(clean_prompt)\ncorrupted_tokens = model.to_tokens(corrupted_prompt)\n\n# 2. Get clean activations\n_, clean_cache = model.run_with_cache(clean_tokens)\n\n# 3. Define metric (e.g., logit difference)\nparis_token = model.to_single_token(\" Paris\")\nrome_token = model.to_single_token(\" Rome\")\n\ndef metric(logits):\n    return logits[0, -1, paris_token] - logits[0, -1, rome_token]\n\n# 4. Patch each position and layer\nresults = torch.zeros(model.cfg.n_layers, clean_tokens.shape[1])\n\nfor layer in range(model.cfg.n_layers):\n    for pos in range(clean_tokens.shape[1]):\n        def patch_hook(activation, hook):\n            activation[0, pos] = clean_cache[hook.name][0, pos]\n            return activation\n\n        patched_logits = model.run_with_hooks(\n            corrupted_tokens,\n            fwd_hooks=[(f\"blocks.{layer}.hook_resid_post\", patch_hook)]\n        )\n        results[layer, pos] = metric(patched_logits)\n\n# 5. Visualize results (layer x position heatmap)\n```\n\n### Checklist\n- [ ] Define clean and corrupted inputs that differ minimally\n- [ ] Choose metric that captures behavior difference\n- [ ] Cache clean activations\n- [ ] Systematically patch each (layer, position) combination\n- [ ] Visualize results as heatmap\n- [ ] Identify causal hotspots\n\n## Workflow 2: Circuit Analysis (Indirect Object Identification)\n\nReplicate the IOI circuit discovery from \"Interpretability in the Wild\".\n\n### Step-by-Step\n\n```python\nfrom transformer_lens import HookedTransformer\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# IOI task: \"When John and Mary went to the store, Mary gave a bottle to\"\n# Model should predict \"John\" (indirect object)\n\nprompt = \"When John and Mary went to the store, Mary gave a bottle to\"\ntokens = model.to_tokens(prompt)\n\n# 1. Get baseline logits\nlogits, cache = model.run_with_cache(tokens)\n\njohn_token = model.to_single_token(\" John\")\nmary_token = model.to_single_token(\" Mary\")\n\n# 2. Compute logit difference (IO - S)\nlogit_diff = logits[0, -1, john_token] - logits[0, -1, mary_token]\nprint(f\"Logit difference: {logit_diff.item():.3f}\")\n\n# 3. Direct logit attribution by head\ndef get_head_contribution(layer, head):\n    # Project head output to logits\n    head_out = cache[\"z\", layer][0, :, head, :]  # [pos, d_head]\n    W_O = model.W_O[layer, head]  # [d_head, d_model]\n    W_U = model.W_U  # [d_model, vocab]\n\n    # Head contribution to logits at final position\n    contribution = head_out[-1] @ W_O @ W_U\n    return contribution[john_token] - contribution[mary_token]\n\n# 4. Map all heads\nhead_contributions = torch.zeros(model.cfg.n_layers, model.cfg.n_heads)\nfor layer in range(model.cfg.n_layers):\n    for head in range(model.cfg.n_heads):\n        head_contributions[layer, head] = get_head_contribution(layer, head)\n\n# 5. Identify top contributing heads (name movers, backup name movers)\n```\n\n### Checklist\n- [ ] Set up task with clear IO\u002FS tokens\n- [ ] Compute baseline logit difference\n- [ ] Decompose by attention head contributions\n- [ ] Identify key circuit components (name movers, S-inhibition, induction)\n- [ ] Validate with ablation experiments\n\n## Workflow 3: Induction Head Detection\n\nFind induction heads that implement [A][B]...[A] → [B] pattern.\n\n```python\nfrom transformer_lens import HookedTransformer\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# Create repeated sequence: [A][B][A] should predict [B]\nrepeated_tokens = torch.tensor([[1000, 2000, 1000]])  # Arbitrary tokens\n\n_, cache = model.run_with_cache(repeated_tokens)\n\n# Induction heads attend from final [A] back to first [B]\n# Check attention from position 2 to position 1\ninduction_scores = torch.zeros(model.cfg.n_layers, model.cfg.n_heads)\n\nfor layer in range(model.cfg.n_layers):\n    pattern = cache[\"pattern\", layer][0]  # [head, q_pos, k_pos]\n    # Attention from pos 2 to pos 1\n    induction_scores[layer] = pattern[:, 2, 1]\n\n# Heads with high scores are induction heads\ntop_heads = torch.topk(induction_scores.flatten(), k=5)\n```\n\n## Common Issues & Solutions\n\n### Issue: Hooks persist after debugging\n```python\n# WRONG: Old hooks remain active\nmodel.run_with_hooks(tokens, fwd_hooks=[...])  # Debug, add new hooks\nmodel.run_with_hooks(tokens, fwd_hooks=[...])  # Old hooks still there!\n\n# RIGHT: Always reset hooks\nmodel.reset_hooks()\nmodel.run_with_hooks(tokens, fwd_hooks=[...])\n```\n\n### Issue: Tokenization gotchas\n```python\n# WRONG: Assuming consistent tokenization\nmodel.to_tokens(\"Tim\")  # Single token\nmodel.to_tokens(\"Neel\")  # Becomes \"Ne\" + \"el\" (two tokens!)\n\n# RIGHT: Check tokenization explicitly\ntokens = model.to_tokens(\"Neel\", prepend_bos=False)\nprint(model.to_str_tokens(tokens))  # ['Ne', 'el']\n```\n\n### Issue: LayerNorm ignored in analysis\n```python\n# WRONG: Ignoring LayerNorm\npre_activation = residual @ model.W_in[layer]\n\n# RIGHT: Include LayerNorm\nln_scale = model.blocks[layer].ln2.w\nln_out = model.blocks[layer].ln2(residual)\npre_activation = ln_out @ model.W_in[layer]\n```\n\n### Issue: Memory explosion with large models\n```python\n# Use selective caching\nlogits, cache = model.run_with_cache(\n    tokens,\n    names_filter=lambda n: \"resid_post\" in n or \"pattern\" in n,\n    device=\"cpu\"  # Cache on CPU\n)\n```\n\n## Key Classes Reference\n\n| Class | Purpose |\n|-------|---------|\n| `HookedTransformer` | Main model wrapper with hooks |\n| `ActivationCache` | Dictionary-like cache of activations |\n| `HookedTransformerConfig` | Model configuration |\n| `FactoredMatrix` | Efficient factored matrix operations |\n\n## Integration with SAELens\n\nTransformerLens integrates with SAELens for Sparse Autoencoder analysis:\n\n```python\nfrom transformer_lens import HookedTransformer\nfrom sae_lens import SAE\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\nsae = SAE.from_pretrained(\"gpt2-small-res-jb\", \"blocks.8.hook_resid_pre\")\n\n# Run with SAE\ntokens = model.to_tokens(\"Hello world\")\n_, cache = model.run_with_cache(tokens)\nsae_acts = sae.encode(cache[\"resid_pre\", 8])\n```\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 HookedTransformer, ActivationCache, HookPoints |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for activation patching, circuit analysis, logit lens |\n\n## External Resources\n\n### Tutorials\n- [Main Demo Notebook](https:\u002F\u002Ftransformerlensorg.github.io\u002FTransformerLens\u002Fgenerated\u002Fdemos\u002FMain_Demo.html)\n- [Activation Patching Demo](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FTransformerLensOrg\u002FTransformerLens\u002Fblob\u002Fmain\u002Fdemos\u002FActivation_Patching_in_TL_Demo.ipynb)\n- [ARENA Mech Interp Course](https:\u002F\u002Farena-foundation.github.io\u002FARENA\u002F) - 200+ hours of tutorials\n\n### Papers\n- [A Mathematical Framework for Transformer Circuits](https:\u002F\u002Ftransformer-circuits.pub\u002F2021\u002Fframework\u002Findex.html)\n- [In-context Learning and Induction Heads](https:\u002F\u002Ftransformer-circuits.pub\u002F2022\u002Fin-context-learning-and-induction-heads\u002Findex.html)\n- [Interpretability in the Wild (IOI)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2211.00593)\n\n### Official Documentation\n- [Official Docs](https:\u002F\u002Ftransformerlensorg.github.io\u002FTransformerLens\u002F)\n- [Model Properties Table](https:\u002F\u002Ftransformerlensorg.github.io\u002FTransformerLens\u002Fgenerated\u002Fmodel_properties_table.html)\n- [Neel Nanda's Glossary](https:\u002F\u002Fwww.neelnanda.io\u002Fmechanistic-interpretability\u002Fglossary)\n\n## Version Notes\n\n- **v2.0**: Removed HookedSAE (moved to SAELens)\n- **v3.0 (alpha)**: TransformerBridge for loading any nn.Module\n","# TransformerLens: Mechanistic Interpretability for Transformers\n\nTransformerLens is the de facto standard library for mechanistic interpretability research on GPT-style language models. Created by Neel Nanda and maintained by Bryce Meyer, it provides clean interfaces to inspect and manipulate model internals via HookPoints on every activation.\n\n**GitHub**: [TransformerLensOrg\u002FTransformerLens](https:\u002F\u002Fgithub.com\u002FTransformerLensOrg\u002FTransformerLens) (2,900+ stars)\n\n## When to Use TransformerLens\n\n**Use TransformerLens when you need to:**\n- Reverse-engineer algorithms learned during training\n- Perform activation patching \u002F causal tracing experiments\n- Study attention patterns and information flow\n- Analyze circuits (e.g., induction heads, IOI circuit)\n- Cache and inspect intermediate activations\n- Apply direct logit attribution\n\n**Consider alternatives when:**\n- You need to work with non-transformer architectures → Use **nnsight** or **pyvene**\n- You want to train\u002Fanalyze Sparse Autoencoders → Use **SAELens**\n- You need remote execution on massive models → Use **nnsight** with NDIF\n- You want higher-level causal intervention abstractions → Use **pyvene**\n\n## Installation\n\n```bash\npip install transformer-lens\n```\n\nFor development version:\n```bash\npip install git+https:\u002F\u002Fgithub.com\u002FTransformerLensOrg\u002FTransformerLens\n```\n\n## Core Concepts\n\n### HookedTransformer\n\nThe main class that wraps transformer models with HookPoints on every activation:\n\n```python\nfrom transformer_lens import HookedTransformer\n\n# Load a model\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# For gated models (LLaMA, Mistral)\nimport os\nos.environ[\"HF_TOKEN\"] = \"your_token\"\nmodel = HookedTransformer.from_pretrained(\"meta-llama\u002FLlama-2-7b-hf\")\n```\n\n### Supported Models (50+)\n\n| Family | Models |\n|--------|--------|\n| GPT-2 | gpt2, gpt2-medium, gpt2-large, gpt2-xl |\n| LLaMA | llama-7b, llama-13b, llama-2-7b, llama-2-13b |\n| EleutherAI | pythia-70m to pythia-12b, gpt-neo, gpt-j-6b |\n| Mistral | mistral-7b, mixtral-8x7b |\n| Others | phi, qwen, opt, gemma |\n\n### Activation Caching\n\nRun the model and cache all intermediate activations:\n\n```python\n# Get all activations\ntokens = model.to_tokens(\"The Eiffel Tower is in\")\nlogits, cache = model.run_with_cache(tokens)\n\n# Access specific activations\nresidual = cache[\"resid_post\", 5]  # Layer 5 residual stream\nattn_pattern = cache[\"pattern\", 3]  # Layer 3 attention pattern\nmlp_out = cache[\"mlp_out\", 7]  # Layer 7 MLP output\n\n# Filter which activations to cache (saves memory)\nlogits, cache = model.run_with_cache(\n    tokens,\n    names_filter=lambda name: \"resid_post\" in name\n)\n```\n\n### ActivationCache Keys\n\n| Key Pattern | Shape | Description |\n|-------------|-------|-------------|\n| `resid_pre, layer` | [batch, pos, d_model] | Residual before attention |\n| `resid_mid, layer` | [batch, pos, d_model] | Residual after attention |\n| `resid_post, layer` | [batch, pos, d_model] | Residual after MLP |\n| `attn_out, layer` | [batch, pos, d_model] | Attention output |\n| `mlp_out, layer` | [batch, pos, d_model] | MLP output |\n| `pattern, layer` | [batch, head, q_pos, k_pos] | Attention pattern (post-softmax) |\n| `q, layer` | [batch, pos, head, d_head] | Query vectors |\n| `k, layer` | [batch, pos, head, d_head] | Key vectors |\n| `v, layer` | [batch, pos, head, d_head] | Value vectors |\n\n## Workflow 1: Activation Patching (Causal Tracing)\n\nIdentify which activations causally affect model output by patching clean activations into corrupted runs.\n\n### Step-by-Step\n\n```python\nfrom transformer_lens import HookedTransformer, patching\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# 1. Define clean and corrupted prompts\nclean_prompt = \"The Eiffel Tower is in the city of\"\ncorrupted_prompt = \"The Colosseum is in the city of\"\n\nclean_tokens = model.to_tokens(clean_prompt)\ncorrupted_tokens = model.to_tokens(corrupted_prompt)\n\n# 2. Get clean activations\n_, clean_cache = model.run_with_cache(clean_tokens)\n\n# 3. Define metric (e.g., logit difference)\nparis_token = model.to_single_token(\" Paris\")\nrome_token = model.to_single_token(\" Rome\")\n\ndef metric(logits):\n    return logits[0, -1, paris_token] - logits[0, -1, rome_token]\n\n# 4. Patch each position and layer\nresults = torch.zeros(model.cfg.n_layers, clean_tokens.shape[1])\n\nfor layer in range(model.cfg.n_layers):\n    for pos in range(clean_tokens.shape[1]):\n        def patch_hook(activation, hook):\n            activation[0, pos] = clean_cache[hook.name][0, pos]\n            return activation\n\n        patched_logits = model.run_with_hooks(\n            corrupted_tokens,\n            fwd_hooks=[(f\"blocks.{layer}.hook_resid_post\", patch_hook)]\n        )\n        results[layer, pos] = metric(patched_logits)\n\n# 5. Visualize results (layer x position heatmap)\n```\n\n### Checklist\n- [ ] Define clean and corrupted inputs that differ minimally\n- [ ] Choose metric that captures behavior difference\n- [ ] Cache clean activations\n- [ ] Systematically patch each (layer, position) combination\n- [ ] Visualize results as heatmap\n- [ ] Identify causal hotspots\n\n## Workflow 2: Circuit Analysis (Indirect Object Identification)\n\nReplicate the IOI circuit discovery from \"Interpretability in the Wild\".\n\n### Step-by-Step\n\n```python\nfrom transformer_lens import HookedTransformer\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# IOI task: \"When John and Mary went to the store, Mary gave a bottle to\"\n# Model should predict \"John\" (indirect object)\n\nprompt = \"When John and Mary went to the store, Mary gave a bottle to\"\ntokens = model.to_tokens(prompt)\n\n# 1. Get baseline logits\nlogits, cache = model.run_with_cache(tokens)\n\njohn_token = model.to_single_token(\" John\")\nmary_token = model.to_single_token(\" Mary\")\n\n# 2. Compute logit difference (IO - S)\nlogit_diff = logits[0, -1, john_token] - logits[0, -1, mary_token]\nprint(f\"Logit difference: {logit_diff.item():.3f}\")\n\n# 3. Direct logit attribution by head\ndef get_head_contribution(layer, head):\n    # Project head output to logits\n    head_out = cache[\"z\", layer][0, :, head, :]  # [pos, d_head]\n    W_O = model.W_O[layer, head]  # [d_head, d_model]\n    W_U = model.W_U  # [d_model, vocab]\n\n    # Head contribution to logits at final position\n    contribution = head_out[-1] @ W_O @ W_U\n    return contribution[john_token] - contribution[mary_token]\n\n# 4. Map all heads\nhead_contributions = torch.zeros(model.cfg.n_layers, model.cfg.n_heads)\nfor layer in range(model.cfg.n_layers):\n    for head in range(model.cfg.n_heads):\n        head_contributions[layer, head] = get_head_contribution(layer, head)\n\n# 5. Identify top contributing heads (name movers, backup name movers)\n```\n\n### Checklist\n- [ ] Set up task with clear IO\u002FS tokens\n- [ ] Compute baseline logit difference\n- [ ] Decompose by attention head contributions\n- [ ] Identify key circuit components (name movers, S-inhibition, induction)\n- [ ] Validate with ablation experiments\n\n## Workflow 3: Induction Head Detection\n\nFind induction heads that implement [A][B]...[A] → [B] pattern.\n\n```python\nfrom transformer_lens import HookedTransformer\nimport torch\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\n\n# Create repeated sequence: [A][B][A] should predict [B]\nrepeated_tokens = torch.tensor([[1000, 2000, 1000]])  # Arbitrary tokens\n\n_, cache = model.run_with_cache(repeated_tokens)\n\n# Induction heads attend from final [A] back to first [B]\n# Check attention from position 2 to position 1\ninduction_scores = torch.zeros(model.cfg.n_layers, model.cfg.n_heads)\n\nfor layer in range(model.cfg.n_layers):\n    pattern = cache[\"pattern\", layer][0]  # [head, q_pos, k_pos]\n    # Attention from pos 2 to pos 1\n    induction_scores[layer] = pattern[:, 2, 1]\n\n# Heads with high scores are induction heads\ntop_heads = torch.topk(induction_scores.flatten(), k=5)\n```\n\n## Common Issues & Solutions\n\n### Issue: Hooks persist after debugging\n```python\n# WRONG: Old hooks remain active\nmodel.run_with_hooks(tokens, fwd_hooks=[...])  # Debug, add new hooks\nmodel.run_with_hooks(tokens, fwd_hooks=[...])  # Old hooks still there!\n\n# RIGHT: Always reset hooks\nmodel.reset_hooks()\nmodel.run_with_hooks(tokens, fwd_hooks=[...])\n```\n\n### Issue: Tokenization gotchas\n```python\n# WRONG: Assuming consistent tokenization\nmodel.to_tokens(\"Tim\")  # Single token\nmodel.to_tokens(\"Neel\")  # Becomes \"Ne\" + \"el\" (two tokens!)\n\n# RIGHT: Check tokenization explicitly\ntokens = model.to_tokens(\"Neel\", prepend_bos=False)\nprint(model.to_str_tokens(tokens))  # ['Ne', 'el']\n```\n\n### Issue: LayerNorm ignored in analysis\n```python\n# WRONG: Ignoring LayerNorm\npre_activation = residual @ model.W_in[layer]\n\n# RIGHT: Include LayerNorm\nln_scale = model.blocks[layer].ln2.w\nln_out = model.blocks[layer].ln2(residual)\npre_activation = ln_out @ model.W_in[layer]\n```\n\n### Issue: Memory explosion with large models\n```python\n# Use selective caching\nlogits, cache = model.run_with_cache(\n    tokens,\n    names_filter=lambda n: \"resid_post\" in n or \"pattern\" in n,\n    device=\"cpu\"  # Cache on CPU\n)\n```\n\n## Key Classes Reference\n\n| Class | Purpose |\n|-------|---------|\n| `HookedTransformer` | Main model wrapper with hooks |\n| `ActivationCache` | Dictionary-like cache of activations |\n| `HookedTransformerConfig` | Model configuration |\n| `FactoredMatrix` | Efficient factored matrix operations |\n\n## Integration with SAELens\n\nTransformerLens integrates with SAELens for Sparse Autoencoder analysis:\n\n```python\nfrom transformer_lens import HookedTransformer\nfrom sae_lens import SAE\n\nmodel = HookedTransformer.from_pretrained(\"gpt2-small\")\nsae = SAE.from_pretrained(\"gpt2-small-res-jb\", \"blocks.8.hook_resid_pre\")\n\n# Run with SAE\ntokens = model.to_tokens(\"Hello world\")\n_, cache = model.run_with_cache(tokens)\nsae_acts = sae.encode(cache[\"resid_pre\", 8])\n```\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 HookedTransformer, ActivationCache, HookPoints |\n| [references\u002Ftutorials.md](references\u002Ftutorials.md) | Step-by-step tutorials for activation patching, circuit analysis, logit lens |\n\n## External Resources\n\n### Tutorials\n- [Main Demo Notebook](https:\u002F\u002Ftransformerlensorg.github.io\u002FTransformerLens\u002Fgenerated\u002Fdemos\u002FMain_Demo.html)\n- [Activation Patching Demo](https:\u002F\u002Fcolab.research.google.com\u002Fgithub\u002FTransformerLensOrg\u002FTransformerLens\u002Fblob\u002Fmain\u002Fdemos\u002FActivation_Patching_in_TL_Demo.ipynb)\n- [ARENA Mech Interp Course](https:\u002F\u002Farena-foundation.github.io\u002FARENA\u002F) - 200+ hours of tutorials\n\n### Papers\n- [A Mathematical Framework for Transformer Circuits](https:\u002F\u002Ftransformer-circuits.pub\u002F2021\u002Fframework\u002Findex.html)\n- [In-context Learning and Induction Heads](https:\u002F\u002Ftransformer-circuits.pub\u002F2022\u002Fin-context-learning-and-induction-heads\u002Findex.html)\n- [Interpretability in the Wild (IOI)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2211.00593)\n\n### Official Documentation\n- [Official Docs](https:\u002F\u002Ftransformerlensorg.github.io\u002FTransformerLens\u002F)\n- [Model Properties Table](https:\u002F\u002Ftransformerlensorg.github.io\u002FTransformerLens\u002Fgenerated\u002Fmodel_properties_table.html)\n- [Neel Nanda's Glossary](https:\u002F\u002Fwww.neelnanda.io\u002Fmechanistic-interpretability\u002Fglossary)\n\n## Version Notes\n\n- **v2.0**: Removed HookedSAE (moved to SAELens)\n- **v3.0 (alpha)**: TransformerBridge for loading any nn.Module\n",{"name":5,"tags":44,"author":48,"license":15,"version":49,"category":50,"description":7,"dependencies":51},[45,46,27,47],"Mechanistic Interpretability","TransformerLens","Circuit Analysis","Synthetic Sciences","1.0.0","ml-training",[52,53],"transformer-lens>=2.0.0","torch>=2.0.0","main","4aa39efd1cdab0b4657ecee16c92a92011a5b10f","openscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Ftransformer-lens","https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub","https:\u002F\u002Fgithub.com\u002Ffadrienne","2026-10-28 00:43:09",{"source":8,"skillName":5,"commands":61,"prompt":71,"zipAvailable":72},[62,65,68],{"tool":63,"command":64},"npx","npx skills add fadrienne\u002FMyGitHub --skill transformer-lens-interpretability",{"tool":66,"command":67},"bunx","bunx skills add fadrienne\u002FMyGitHub --skill transformer-lens-interpretability",{"tool":69,"command":70},"pnpm","pnpm dlx skills add fadrienne\u002FMyGitHub --skill transformer-lens-interpretability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Ftransformer-lens\u002FSKILL.md",true,[74,80,84],{"path":75,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Fapi.md","REFERENCE","参考文档",8349,"https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Ftransformer-lens\u002Freferences\u002Fapi.md",{"path":81,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002FREADME.md",1643,"https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Ftransformer-lens\u002Freferences\u002FREADME.md",{"path":85,"resourceType":76,"resourceTypeDesc":77,"sizeBytes":86,"sourceHtmlUrl":87},"references\u002Ftutorials.md",10142,"https:\u002F\u002Fgithub.com\u002Ffadrienne\u002FMyGitHub\u002Fblob\u002Fmain\u002Fopenscience\u002Fbackend\u002Fcli\u002Fskills\u002Fml-training\u002Ftransformer-lens\u002Freferences\u002Ftutorials.md",[89,119,146,180,207,234],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":100,"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",[95],{"categoryNo":96,"categoryName":97,"taxonomyType":98,"taxonomyTypeDesc":99},"01JBSEEDCAT000000000000023","Skill与智能体开发","SCENARIO","使用场景",[101,102,103,104,105,106,107,108,25,109,110,36,111,112,113,114,115,116,117,118],"power","statistical power","effect","scipy","regression","choose","design","uv","Bash","collection","calculation","ANOVA","conversion","analyze","t-test","chi-square","simulation","sample",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":128,"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",[125],{"categoryNo":126,"categoryName":127,"taxonomyType":98,"taxonomyTypeDesc":99},"01JBSEEDCAT000000000000008","测试与质量",[36,129,101,130,131,132,25,133,134,135,136,137,138,139,140,141,142,143,144,145],"statistical analysis","academic research","implementing","selection","you","reporting","data","for","tests","use","with","test","research","results","statsmodels","models","help",{"skillNo":147,"name":148,"nameZh":6,"description":149,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":161,"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",[152,155,156],{"categoryNo":153,"categoryName":154,"taxonomyType":98,"taxonomyTypeDesc":99},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":96,"categoryName":97,"taxonomyType":98,"taxonomyTypeDesc":99},{"categoryNo":157,"categoryName":158,"taxonomyType":159,"taxonomyTypeDesc":160},"01JBSEEDCAT000000000000036","内容创作者","PROFESSION","适用职业",[162,163,164,165,166,167,168,169,170,171,109,172,173,174,175,176,177,178,134,179],"writing","scientific","scientific writing","Citations","deep","deep research","never","papers","journal","false","api","prisma","structure","openrouter","Outlines","core skill","read","features",{"skillNo":181,"name":182,"nameZh":6,"description":183,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":184,"categories":185,"keywords":190,"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",[186,189],{"categoryNo":187,"categoryName":188,"taxonomyType":98,"taxonomyTypeDesc":99},"01JBSEEDCAT000000000000013","分析与可视化",{"categoryNo":96,"categoryName":97,"taxonomyType":98,"taxonomyTypeDesc":99},[191,163,192,193,194,195,196,197,198,170,25,199,200,201,202,203,204,205,136,206],"visualization","scientific visualization","error","ready","quick","exploration","meta-skill","Meta","safe","plotly","annotations","formatting","Publication","figures","panel","submission",{"skillNo":208,"name":209,"nameZh":6,"description":210,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":211,"categories":212,"keywords":219,"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",[213,216],{"categoryNo":214,"categoryName":215,"taxonomyType":98,"taxonomyTypeDesc":99},"01JBSEEDCAT000000000000021","资料检索与研究",{"categoryNo":217,"categoryName":218,"taxonomyType":159,"taxonomyTypeDesc":160},"01JBSEEDCAT000000000000030","开发工程师",[220,221,141,222,223,224,225,108,226,25,109,36,227,228,229,230,231,232,178,233],"code","research code","which","memory","data-analysis","errors","debugging","common","review","data pipelines","run","scripts","line","write",{"skillNo":235,"name":236,"nameZh":6,"description":237,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":238,"licenseFileUrl":6,"sourceHtmlUrl":239,"categories":240,"keywords":247,"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",[241,244,245,246],{"categoryNo":242,"categoryName":243,"taxonomyType":98,"taxonomyTypeDesc":99},"01JBSEEDCAT000000000000002","文档处理",{"categoryNo":153,"categoryName":154,"taxonomyType":98,"taxonomyTypeDesc":99},{"categoryNo":96,"categoryName":97,"taxonomyType":98,"taxonomyTypeDesc":99},{"categoryNo":157,"categoryName":158,"taxonomyType":159,"taxonomyTypeDesc":160},[162,248,249,250,251,252,191,253,254,25,109,36,255,256,257,258,259,260,163,178],"markdown mermaid writing","mermaid","markdown","community","diagrams","project","default","team","guides","text","documentation","references","diagram"]