{"id":"transformer-lens","name":"transformer-lens-interpretability","summary":"TransformerLensを用いてHookPointsおよびアクティベーションキャッシュを通じてトランスフォーマー内部を検査・操作するメカニズム的解釈可能性研究の指針を提供します。","body":"# 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/TransformerLens](https://github.com/TransformerLensOrg/TransformerLens) (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 / 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/analyze 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://github.com/TransformerLensOrg/TransformerLens\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/Llama-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/S 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/` folder:\n\n| File | Contents |\n|------|----------|\n| [references/README.md](references/README.md) | Overview and quick start guide |\n| [references/api.md](references/api.md) | Complete API reference for HookedTransformer, ActivationCache, HookPoints |\n| [references/tutorials.md](references/tutorials.md) | Step-by-step tutorials for activation patching, circuit analysis, logit lens |\n\n## External Resources\n\n### Tutorials\n- [Main Demo Notebook](https://transformerlensorg.github.io/TransformerLens/generated/demos/Main_Demo.html)\n- [Activation Patching Demo](https://colab.research.google.com/github/TransformerLensOrg/TransformerLens/blob/main/demos/Activation_Patching_in_TL_Demo.ipynb)\n- [ARENA Mech Interp Course](https://arena-foundation.github.io/ARENA/) - 200+ hours of tutorials\n\n### Papers\n- [A Mathematical Framework for Transformer Circuits](https://transformer-circuits.pub/2021/framework/index.html)\n- [In-context Learning and Induction Heads](https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html)\n- [Interpretability in the Wild (IOI)](https://arxiv.org/abs/2211.00593)\n\n### Official Documentation\n- [Official Docs](https://transformerlensorg.github.io/TransformerLens/)\n- [Model Properties Table](https://transformerlensorg.github.io/TransformerLens/generated/model_properties_table.html)\n- [Neel Nanda's Glossary](https://www.neelnanda.io/mechanistic-interpretability/glossary)\n\n## Version Notes\n\n- **v2.0**: Removed HookedSAE (moved to SAELens)\n- **v3.0 (alpha)**: TransformerBridge for loading any nn.Module","author":"@Orchestra-Research","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/Orchestra-Research/AI-Research-SKILLs/tree/main/04-mechanistic-interpretability/transformer-lens","license":"MIT","category":"coding","lang":"en","tokens":2940,"stars":0,"calls30d":1,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/api.md","size":8349,"sha256":"5a31038f94351c645f2816b569fd0b963f1f972a52d0f5d39e7118437ce585cb"},{"path":"references/README.md","size":1643,"sha256":"ebdf1731226920bd3ba3fd8265e033a5e19af48651429023af9ab3ef346766b0"},{"path":"references/tutorials.md","size":10142,"sha256":"c13d376cd9aaebfe6e946e9227d007ac07d69657b8a73d19b58af645f1b91019"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["arena-foundation.github.io","arxiv.org","colab.research.google.com","transformer-circuits.pub","transformerlensorg.github.io","www.neelnanda.io","www.youtube.com"]}}