Skip to content

TransformerLens: A Library for Mechanistic Interpretability of Generative Language Models

Skip →Activation patching
main track #4extendedfundamentaltoolrubric 8/122022 · ~45 min

Neel Nanda (creator); maintained by Bryce Meyer and Jonah Larson

Status

TL;DR. TransformerLens was created by Neel Nanda and is maintained by Bryce Meyer and Jonah Larson. It wraps a model so that every intermediate activation sits behind a named HookPoint. You can then cache, edit, remove or replace any activation without touching model code. The README says it loads 15,000+ open models across 140+ architecture families. Install with pip install transformer_lens.

A HookPoint is an nn.Identity placed at a named position such as blocks.5.hook_resid_post or blocks.0.attn.hook_q. It passes its input through unchanged, but a registered function can read, modify or replace the tensor. Underneath it is plain PyTorch register_forward_hook. The library adds two things: string names, so you never traverse the module tree, and scoped lifetimes, so hooks added in with model.hooks(...) are removed when the block exits.

from transformer_lens.model_bridge import TransformerBridge
model = TransformerBridge.boot_transformers("gpt2", device="cpu")
_, clean_cache = model.run_with_cache(clean_prompt)
target = clean_cache["blocks.5.hook_resid_post"]
def patch(resid, hook):
return target # replace the corrupted activation with the clean one
logits = model.run_with_hooks(
corrupted_prompt,
fwd_hooks=[("blocks.5.hook_resid_post", patch)],
)

Why it matters. Most mech-interp code from 2022–2025, including ARENA 1.2 and 1.4.1 and the IR studies on this site, is written against TransformerLens names. Nanda’s guide recommends it for models up to about 9B and for experiments that touch many models. Watch the version: tutorials that call HookedTransformer.from_pretrained need the 3.x branch or a one-line switch to the bridge. For a BERT cross-encoder, use TransformerBridge.boot_transformers in place of the removed HookedEncoder.

  • Activation patching explains the method the snippet above implements.
  • MechIR extends this hook style to bi-encoders and cross-encoders.
  • nnsight is the alternative for large or remotely hosted models.
  • ARENA Chapter 1 teaches the library through exercises.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Mechanism

    Implement denoising activation patching of the residual stream at layer 5 with TransformerLens hooks. Which calls do you make, what does the hook function return, and how do you sweep positions without leaking hooks?

    What a strong answer covers
    • Run the clean prompt with run_with_cache (optionally names_filter for blocks.5.hook_resid_post) and keep that tensor.
    • Define a hook fn(resid, hook) that copies the clean value into the chosen position and returns the tensor; returning None leaves the activation unchanged.
    • Call run_with_hooks(corrupted_prompt, fwd_hooks=[(name, fn)]) and compute the metric on the logits, e.g. a normalised logit difference.
    • Hooks passed to run_with_hooks or a with model.hooks(...) block are removed automatically; ones added with add_hook must be cleared with remove_all_hook_fns.
    • Clean and corrupted prompts must tokenise to the same length so positions line up.
  2. Critique

    TransformerBridge preserves raw HuggingFace numerics by default, while legacy HookedTransformer folded LayerNorm and centred weights. When does this choice change your interpretability results, and when does it not?

    What a strong answer covers
    • Output probabilities are unchanged either way: folding and centring are reparameterisations, and centring the unembedding only shifts logits by a constant per position.
    • Per-component quantities change: direct logit attribution, weight-based circuit analysis (QK/OV) and residual norms depend on centring and folded LayerNorm weights.
    • enable_compatibility_mode() reproduces the HookedTransformer defaults (LayerNorm folding, center_writing_weights, center_unembed), so old tutorial numbers can be matched.
    • Hook names are not the issue: HookedTransformer-style names such as blocks.5.hook_resid_post resolve as aliases on the bridge.
  3. Connect

    TransformerLens 4.0 removed HookedEncoder. How would you now load a BERT cross-encoder for patching, and which trap does the migration guide warn about?

    What a strong answer covers
    • Use TransformerBridge.boot_transformers(name) on the BERT model; the bridge replaces HookedEncoder.
    • Run the encoder through bridge(...) or run_with_cache, not bridge.encoder_output, which is the audio frame-entry method (HuBERT/Wav2Vec2) and refuses BERT.
    • A name-only migration passes a dir() parity check but fails at runtime.
    • The legacy stack is kept on the 3.x branch for bug fixes only.

Done with this page?

Status