[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EPEB7Z9P9TMFWX1M9ZS677":3,"skill-same:01M7EPEB7Z9P9TMFWX1M9ZS677":70},{"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":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":34,"commitSha":35,"skillDirectory":36,"forksCount":37,"repositoryHtmlUrl":38,"repositoryHomepageUrl":6,"ownerHtmlUrl":39,"ownerBlogUrl":40,"ownerDescription":6,"updatedAt":41,"install":42,"resources":55},"01M7EPEB7Z9P9TMFWX1M9ZS677","mechanistic-interpretability-transformer-lens",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.","TanNhatCMS\u002Fjarvis","TanNhatCMS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F113796420?v=4","01M753MV17KG5CD3152G3WQEQY","KietNT","01M7EKEDYVYQ6PWVJJMZ911VMX",0,"MIT","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-mechanistic-interpretability-transformer-lens\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: mechanistic-interpretability-transformer-lens\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.\nversion: 1.0.0\nauthor: Orchestra Research\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":24,"author":29,"license":15,"version":30,"description":7,"dependencies":31},[25,26,27,28],"Mechanistic Interpretability","TransformerLens","Activation Patching","Circuit Analysis","Orchestra Research","1.0.0",[32,33],"transformer-lens>=2.0.0","torch>=2.0.0","main","af388a77c2fe5e0b4fd879cca4300a0ffa9a6579","skills\u002Fams-imp-mechanistic-interpretability-transformer-lens",1,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis","https:\u002F\u002Fgithub.com\u002FTanNhatCMS","https:\u002F\u002Fmrkiet.name.vn","2026-11-07 14:23:08",{"source":8,"skillName":5,"commands":43,"prompt":53,"zipAvailable":54},[44,47,50],{"tool":45,"command":46},"npx","npx skills add TanNhatCMS\u002Fjarvis --skill mechanistic-interpretability-transformer-lens",{"tool":48,"command":49},"bunx","bunx skills add TanNhatCMS\u002Fjarvis --skill mechanistic-interpretability-transformer-lens",{"tool":51,"command":52},"pnpm","pnpm dlx skills add TanNhatCMS\u002Fjarvis --skill mechanistic-interpretability-transformer-lens","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-mechanistic-interpretability-transformer-lens\u002FSKILL.md",true,[56,62,66],{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"references\u002Fapi.md","REFERENCE","参考文档",8349,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-mechanistic-interpretability-transformer-lens\u002Freferences\u002Fapi.md",{"path":63,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":64,"sourceHtmlUrl":65},"references\u002FREADME.md",1643,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-mechanistic-interpretability-transformer-lens\u002Freferences\u002FREADME.md",{"path":67,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":68,"sourceHtmlUrl":69},"references\u002Ftutorials.md",10142,"https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fams-imp-mechanistic-interpretability-transformer-lens\u002Freferences\u002Ftutorials.md",[71,78,86,93,100,107],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M7EWYJR0J8DARY7E59Z6Y9MV","web-scrape","Turn web pages into LLM-ready markdown via the Firecrawl API (renders JS, anti-bot handling). Use when browser_open\u002Ffetch fails on JS-heavy pages, or when you need clean markdown\u002Fstructured extraction from a site. Requires FIRECRAWL_API_KEY.","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fweb-scrape\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":82,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M7EWYBN5P6F2AJG3FR24T9BP","design-taste-frontend","tasteskill v2, the anti-slop frontend skill. Art direction for websites, distilled from a study of 247 curated gallery sites (One Page Love, Awwwards Sites of the Day). Deals researched directions (idea, composition, type, palette, photographs, section blueprints) from a library, enforces a strict no-slop house style with a real-browser inspector, and runs a look-and-fix loop on screenshots. Use this whenever you build, design, redesign, restyle, polish or review a landing page, marketing site, portfolio, product page, one-pager, hero or any public-facing web page, in any stack (HTML\u002FCSS, React, Next.js, Vue, Svelte, Astro, Tailwind) — also when the user says a page looks generic, templated, \"AI-made\", sloppy, or asks to make it look designed, premium, award-level or less like every other site. Not for dashboards or app screens.","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Ftaste-design\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Ftaste-design\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M7EWY8FQFNQ2GB7NZZWGSSDX","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-tdd\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M7EWY5SHBFRH1HDHVWM9K7TV","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-debugging\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M7EWY3NM0Z0JAKS7HDZ24K66","requesting-code-review","Use when completing tasks, implementing major features, or before merging to verify work meets requirements","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-code-review\u002FSKILL.md",[],[],{"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":113,"publishedAt":19},"01M7EWY0WRMWX4M9ZFY0WKC593","brainstorming","You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).","https:\u002F\u002Fgithub.com\u002FTanNhatCMS\u002Fjarvis\u002Fblob\u002Fmain\u002Fskills\u002Fsuperpowers-brainstorming\u002FSKILL.md",[],[]]