[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MBA34HBP3EXRN51WMZ6FBV":3,"skill-same:01M6MBA34HBP3EXRN51WMZ6FBV":89},{"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":40,"linkOnly":41,"markdownContent":42,"markdownBody":43,"frontMatter":44,"refName":51,"commitSha":52,"skillDirectory":53,"forksCount":54,"repositoryHtmlUrl":55,"repositoryHomepageUrl":56,"ownerHtmlUrl":57,"ownerBlogUrl":58,"ownerDescription":59,"updatedAt":60,"install":61,"resources":74},"01M6MBA34HBP3EXRN51WMZ6FBV","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.","hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1559,"MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Ftransformer-lens-interpretability\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39],"transformer lens interpretability","transformer lens","Interpretability","Transformer","lens","caching","when","inspect","circuit","Activation Patching","circuit analysis","experiments","algorithms","patterns","activation","model","patching","analysis","Safety","Evaluation","reverse-engineering","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.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: ml-evaluation-and-safety\n  maintainer: Kalaris Labs\n  tags: Mechanistic Interpretability, TransformerLens, Activation Patching, Circuit Analysis\n  dependencies: 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)\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\n## Agent operating procedure\n\n1. **Check the environment.** Confirm the model, checkpoint, benchmark version and evaluation harness version.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Evaluate on a small subset to verify prompts, parsing and scoring.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Use the benchmark's official splits and metrics; check for contamination; report variance across seeds or prompts.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Scores differ from published numbers | Check prompt format, few-shot settings and harness version before concluding. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Report evaluation settings in full; never cherry-pick prompts, seeds or subsets.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `pyvene-interventions`: Provides guidance for performing causal interventions on PyTorch models using pyvene's declarative intervention framework.\n- `nnsight-remote-interpretability`: Provides guidance for interpreting and manipulating neural network internals using nnsight with optional NDIF remote execution.\n- `sparse-autoencoder-training`: Provides guidance for training and analyzing Sparse Autoencoders (SAEs) using SAELens to decompose neural network activations into interpre…\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)\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\n## Agent operating procedure\n\n1. **Check the environment.** Confirm the model, checkpoint, benchmark version and evaluation harness version.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Evaluate on a small subset to verify prompts, parsing and scoring.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Use the benchmark's official splits and metrics; check for contamination; report variance across seeds or prompts.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Scores differ from published numbers | Check prompt format, few-shot settings and harness version before concluding. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Report evaluation settings in full; never cherry-pick prompts, seeds or subsets.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n\n## Related skills\n\n- `pyvene-interventions`: Provides guidance for performing causal interventions on PyTorch models using pyvene's declarative intervention framework.\n- `nnsight-remote-interpretability`: Provides guidance for interpreting and manipulating neural network internals using nnsight with optional NDIF remote execution.\n- `sparse-autoencoder-training`: Provides guidance for training and analyzing Sparse Autoencoders (SAEs) using SAELens to decompose neural network activations into interpre…\n",{"name":5,"license":15,"metadata":45,"description":7},{"tags":46,"version":47,"category":48,"maintainer":49,"dependencies":50},"Mechanistic Interpretability, TransformerLens, Activation Patching, Circuit Analysis","1.0.0","ml-evaluation-and-safety","Kalaris Labs","transformer-lens>=2.0.0, torch>=2.0.0","main","2b63f856ce19c2a797929cacabd9e0fc936812fa","plugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Ftransformer-lens-interpretability",474,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-11 14:40:14",{"source":8,"skillName":5,"commands":62,"prompt":72,"zipAvailable":73},[63,66,69],{"tool":64,"command":65},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill transformer-lens-interpretability",{"tool":67,"command":68},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill transformer-lens-interpretability",{"tool":70,"command":71},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill transformer-lens-interpretability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Ftransformer-lens-interpretability\u002FSKILL.md",true,[75,81,85],{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"references\u002Fapi.md","REFERENCE","参考文档",8349,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Ftransformer-lens-interpretability\u002Freferences\u002Fapi.md",{"path":82,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002FREADME.md",1630,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Ftransformer-lens-interpretability\u002Freferences\u002FREADME.md",{"path":86,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":87,"sourceHtmlUrl":88},"references\u002Ftutorials.md",10142,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FKalarisLabs\u002Fresearch-agent-skills\u002Fskills\u002Ftransformer-lens-interpretability\u002Freferences\u002Ftutorials.md",[90,99,106,113,139,164],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":98},"01M746ZWACVKMZ1BJXJZHYJSSX","migrate-to-e2e","Moves an existing Playwright, Cypress, Selenium, Appium, Detox, Maestro, or TesterArmy suite to e2e one slice at a time, with the old suite running beside the new one until each ported test is proven. Keeps a MIGRATION.md progress file so any later session resumes where the last stopped. Optionally plants a defect to show both suites catch it. Use for \u002Fmigrate-to-e2e, \"migrate our tests to e2e\", \"port these Maestro flows\", \"move our TesterArmy tests\", or when a project has an e2e config and an older suite still running.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fmigrate-to-e2e\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":98},"01M746ZPTAX1Q0FBKAB1CYND7E","e2e","Writes, runs, and debugs end-to-end tests for web and mobile apps with e2e, the agentic test runner, which mixes agent.act goals with exact locator assertions on a Playwright browser or an iOS or Android device. Also drives a project's running app live over the e2e MCP server to look at a screen, check a UI change, take a screenshot or record a video, and try a locator; and runs bug bashes, parallel e2e explore runs with each bug proven by a repro test. Use when a project depends on e2e or has an e2e.config.ts, when asked for end-to-end, browser, mobile, or agentic UI tests, to check a change in the running app, to QA or bug bash an app or branch, or when an e2e run fails.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fe2e\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":98},"01M746ZJN784HVHMDP9MQGCSGG","create-verification-skill","Generate a project-local verify-\u003Capp> skill on top of e2e, so any coding agent can launch the app, check it is worth driving, exercise a feature the way a user does, keep evidence, and bug bash it. Writes the skill, a feature map with one explore charter per feature, and proves it once. Use for \u002Fcreate-verification-skill, \"make a verification skill for this repo\", or when a project has no scripted way to prove UI behavior.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftester-army\u002Fe2e\u002Fskills\u002Fcreate-verification-skill\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":40},"01M716A6ETNB9B1SQ3GXZC75VR","deja-search","deja-vu memory — search the user's past AI coding sessions with the deja CLI. Holds what they already settled and never wrote into the repo (naming rules, banned or already-tried tools, required checks before merge, preferred values, who owns what). Use before your first edit in a task, before you call a change done or ready to merge, before you recommend a tool, library, design or reviewer, before re-debugging an error that may already be solved, when they say 'didn't we fix this before', 'what did we decide about X' or 'I already have that', and before telling them something on this machine does not exist.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fvshulcz\u002Fdeja-vu\u002Fskills\u002Fdeja-search\u002FSKILL.md",[],[120,121,122,123,124,125,126,127,128,129,130,25,131,132,133,134,135,136,137,138],"search","deja search","never","error","ready","memory","re","decide","fix","design","debugging","you","done","reviewer","io","change","cli","merge","past",{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":145,"publishedAt":40},"01M716A3J2W5SENSE9VGMXB375","deja-reflect","End-of-session reflection and memory curation with deja-vu. Review what was decided, what commands broke and what repaired them, and record durable project rules or decisions with deja remember so the next session starts with them.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fvshulcz\u002Fdeja-vu\u002Fskills\u002Fdeja-reflect\u002FSKILL.md",[],[146,147,148,134,149,150,151,152,153,154,155,156,157,158,125,159,160,161,162,163],"deja reflect","reflect","review","with","record","github","next","https","node","Rules","decisions","brew","remember","project rules","project","session","end","reflection",{"skillNo":165,"name":166,"nameZh":6,"description":167,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":181,"publishedAt":40},"01M715T3RR4BAYSR57HPPTJ0PF","revid","Make, edit, export and post AI videos with Revid (revid.ai) through the Revid MCP server. Use whenever the user wants a short-form or long-form video made (from an idea, a script, a URL, an article, a PDF, a tweet, a product page, their own clips, or a song), wants to find what is going viral on TikTok, YouTube, Instagram or X before making something, wants to edit or re-export an existing Revid project, generate a standalone AI image or clip, make a series episode, or publish and schedule a finished video to connected social accounts. Covers setup (hosted MCP with OAuth, or an API key), the 36 tools, credits, polling and the rules for publishing. Routes to the more specific revid-* skills when one fits.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Ftmakersas\u002Frevid-skills\u002Fskills\u002Frevid\u002FSKILL.md",[170,175,178],{"categoryNo":171,"categoryName":172,"taxonomyType":173,"taxonomyTypeDesc":174},"01JBSEEDCAT000000000000016","图像与多媒体","SCENARIO","使用场景",{"categoryNo":176,"categoryName":177,"taxonomyType":173,"taxonomyTypeDesc":174},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":179,"categoryName":180,"taxonomyType":173,"taxonomyTypeDesc":174},"01JBSEEDCAT000000000000010","后端与接口",[166,182,183,184,185,186,187,160,188,126,189,190,191,192,25,193,194,195,196,197],"URL","Video","short-form","standalone","PDF","viral","tiktok","short","social","MCP","song","image","mcp server","schedule","api","publish"]