跳到正文
Skillpedia
机器学习14k · #11187

transformer-lens-interpretability

它能做什么

这个技能讲解 TransformerLens,这是一个用于 GPT 风格模型机制可解释性研究的标准库。适合希望研究模型如何计算答案的研究人员。

适用场景

  • ✓你想研究注意力模式以及信息如何在模型中流动的时候。
  • ✓你想在模型中找出电路,例如归纳头的时候。
  • ✓你需要缓存并检查许多输入的中间激活值的时候。

技能链接

https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/04-mechanistic-interpretability/transformer-lens/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/04-mechanistic-interpretability/transformer-lens/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“请针对我输入的一句话,展示一个小型 GPT 模型中的注意力模式。”

每周 5 个新技能,1 分钟读完。

工作原理

该库包装 Transformer,使每个内部激活都有一个钩子点。你可以缓存一次运行中的数值,检查它们,并修改它们来观察对输出的影响。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

TransformerLens: Mechanistic Interpretability for Transformers

TransformerLens 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.

GitHub: TransformerLensOrg/TransformerLens (2,900+ stars)

When to Use TransformerLens

Use TransformerLens when you need to:

  • Reverse-engineer algorithms learned during training
  • Perform activation patching / causal tracing experiments
  • Study attention patterns and information flow
  • Analyze circuits (e.g., induction heads, IOI circuit)
  • Cache and inspect intermediate activations
  • Apply direct logit attribution

Consider alternatives when:

  • You need to work with non-transformer architectures → Use nnsight or pyvene
  • You want to train/analyze Sparse Autoencoders → Use SAELens
  • You need remote execution on massive models → Use nnsight with NDIF
  • You want higher-level causal intervention abstractions → Use pyvene

Installation

pip install transformer-lens

For development version:

pip install git+https://github.com/TransformerLensOrg/TransformerLens

Core Concepts

HookedTransformer

The main class that wraps transformer models with HookPoints on every activation:

from transformer_lens import HookedTransformer

# Load a model
model = HookedTransformer.from_pretrained("gpt2-small")

# For gated models (LLaMA, Mistral)
import os
os.environ["HF_TOKEN"] = "your_token"
model = HookedTransformer.from_pretrained("meta-llama/Llama-2-7b-hf")

Supported Models (50+)

Family Models
GPT-2 gpt2, gpt2-medium, gpt2-large, gpt2-xl
LLaMA llama-7b, llama-13b, llama-2-7b, llama-2-13b
EleutherAI pythia-70m to pythia-12b, gpt-neo, gpt-j-6b
Mistral mistral-7b, mixtral-8x7b
Others phi, qwen, opt, gemma

Activation Caching

Run the model and cache all intermediate activations:

# Get all activations
tokens = model.to_tokens("The Eiffel Tower is in")
logits, cache = model.run_with_cache(tokens)

# Access specific activations
residual = cache["resid_post", 5]  # Layer 5 residual stream
attn_pattern = cache["pattern", 3]  # Layer 3 attention pattern
mlp_out = cache["mlp_out", 7]  # Layer 7 MLP output

# Filter which activations to cache (saves memory)
logits, cache = model.run_with_cache(
    tokens,
    names_filter=lambda name: "resid_post" in name
)

ActivationCache Keys

Key Pattern Shape Description
resid_pre, layer [batch, pos, d_model] Residual before attention
resid_mid, layer [batch, pos, d_model] Residual after attention
resid_post, layer [batch, pos, d_model] Residual after MLP
attn_out, layer [batch, pos, d_model] Attention output
mlp_out, layer [batch, pos, d_model] MLP output
pattern, layer [batch, head, q_pos, k_pos] Attention pattern (post-softmax)
q, layer [batch, pos, head, d_head] Query vectors
k, layer [batch, pos, head, d_head] Key vectors
v, layer [batch, pos, head, d_head] Value vectors

Workflow 1: Activation Patching (Causal Tracing)

Identify which activations causally affect model output by patching clean activations into corrupted runs.

Step-by-Step

from transformer_lens import HookedTransformer, patching
import torch

model = HookedTransformer.from_pretrained("gpt2-small")

# 1. Define clean and corrupted prompts
clean_prompt = "The Eiffel Tower is in the city of"
corrupted_prompt = "The Colosseum is in the city of"

clean_tokens = model.to_tokens(clean_prompt)
corrupted_tokens = model.to_tokens(corrupted_prompt)

# 2. Get clean activations
_, clean_cache = model.run_with_cache(clean_tokens)

# 3. Define metric (e.g., logit difference)
paris_token = model.to_single_token(" Paris")
rome_token = model.to_single_token(" Rome")

def metric(logits):
    return logits[0, -1, paris_token] - logits[0, -1, rome_token]

# 4. Patch each position and layer
results = torch.zeros(model.cfg.n_layers, clean_tokens.shape[1])

for layer in range(model.cfg.n_layers):
    for pos in range(clean_tokens.shape[1]):
        def patch_hook(activation, hook):
            activation[0, pos] = clean_cache[hook.name][0, pos
常见问题

它适用于哪些模型?

这个技能针对 GPT 风格的 Transformer 语言模型。

什么是 HookPoint?

它是模型内部一个有名称的位置,可以在这里读取或修改激活值。

它能训练稀疏自编码器吗?

不能。这个技能建议使用 SAELens 来训练和分析稀疏自编码器。

详情

作者的原始描述

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.

repo: Orchestra-Research/AI-Research-SKILLs

热度

GitHub 星标
14k
排名
#11187
许可证
MIT
更新时间
2026/10/10

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能