본문으로 건너뛰기
Skillpedia
머신러닝14k · #11187

transformer-lens-interpretability

하는 일

이 스킬은 GPT 스타일 모델의 기계적 해석을 위한 표준 라이브러리 TransformerLens를 설명합니다. 모델이 답을 계산하는 방식을 연구하려는 연구자를 위한 스킬입니다.

사용하는 경우

  • ✓어텐션 패턴과 정보가 모델을 통해 흐르는 방식을 연구하고 싶을 때.
  • ✓인덕션 헤드처럼 모델 내부의 회로를 찾고 싶을 때.
  • ✓여러 입력에 대한 중간 활성화를 캐시하고 살펴봐야 하는 경우.

스킬 링크

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

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/Orchestra-Research/AI-Research-SKILLs/blob/main/04-mechanistic-interpretability/transformer-lens/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제가 입력한 문장에 대해 작은 GPT 모델의 어텐션 패턴을 보여 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 라이브러리는 Transformer를 감싸서 모든 내부 활성화에 hook 지점을 제공합니다. 실행 결과를 캐시하고, 살펴보고, 값을 바꿔서 출력에 미치는 영향을 볼 수 있습니다.

기술 내용 (원본 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

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬