TransformerLens PyTorch Quick Reference
TransformerLens PyTorch Quick Reference
1 TransformerLens: Model Loading 3.2 Forward with Cache 5 TransformerLens: Weight Access
1.1 Load Pretrained Model logits , cache = model . run _with_c ache ( tokens ) # Embeddings
model . W_E # [ d_vocab , d_model ]
# Cache only specific activations model . W_pos # [ n_ctx , d_model ]
from t r a n s f o r m e r _ l e n s import H o o k e d T r a n s f o r m e r logits , cache = model . run _with_c ache ( model . W_U # [ d_model , d_vocab ]
tokens ,
model = H o o k e d T r a n s f o r m e r . f r om _p re t ra in e d ( names_filter = lambda n : n . endswith ( " pattern " ) ,
" gpt2 - small " , # Attention weights ( all have layer , head dims )
return_type = None # Don ’t return logits model . W_Q [ layer , head ] # [ d_model , d_head ]
cente r_unemb ed = True , # Center W_U )
c e n t e r _ w r i t i n g _ w e i g h t s = True , model . W_K [ layer , head ] # [ d_model , d_head ]
fold_ln = True , # Fold LayerNorm model . W_V [ layer , head ] # [ d_model , d_head ]
r e f a c t o r _ f a c t o r e d _ a t t n _ m a t r i c e s = True , 3.3 Forward with Hooks model . W_O [ layer , head ] # [ d_head , d_model ]
device = device
) def my_hook ( activation , hook ) : # MLP weights
# Modify activation model . W_in [ layer ] # [ d_model , d_mlp ]
model . W_out [ layer ] # [ d_mlp , d_model ]
1.2 Create Custom Model return activation # Must return if modifying
model . b_in [ layer ] # [ d_mlp ]
logits = model . run_w ith_hoo ks ( model . b_out [ layer ] # [ d_model ]
from t r a n s f o r m e r _ l e n s import H o o k e d T r a n s f o r m e r C o n f i g tokens ,
fwd_hooks =[ # Composed circuits
cfg = H o o k e d T r a n s f o r m e r C o n f i g ( ( utils . get_act_name ( " z " , 0) , my_hook ) , W_OV = model . W_V [l , h ] @ model . W_O [l , h ] # OV circuit
n_layers =2 , n_heads =12 , d_model =768 , ( " blocks .1. attn . hook_pattern " , other_hook ) , W_QK = model . W_Q [l , h ] @ model . W_K [l , h ]. T # QK circuit
d_head =64 , d_mlp =3072 , d_vocab =50257 , ]
n_ctx =1024 , act_fn = " gelu " , )
n o r m a l i z a t i o n _ t y p e = " LN " , # or " LNPre " , None
attention_dir = " causal " , # or " bidirectional "
6 TransformerLens: Hook Names
)
device = device
4 TransformerLens: Cache Access from transformer_lens import utils
model = H o o k e d T r a n s f o r m e r ( cfg )
# Get hook name for activation type
4.1 Access Patterns utils . get_act_name ( " pattern " , layer )
1.3 Model Config Access # Tuple syntax ( preferred )
utils . get_act_name ( " z " , layer )
utils . get_act_name ( " result " , layer )
model . cfg . n_layers # Number of layers cache [ " pattern " , layer ] # Attention patterns utils . get_act_name ( " resid_pre " , layer )
model . cfg . n_heads # Heads per layer cache [ " q " , layer ] # Query vectors utils . get_act_name ( " resid_post " , layer )
model . cfg . d_model # Model dimension cache [ " k " , layer ] # Key vectors utils . get_act_name ( " q " , layer )
model . cfg . d_head # Head dimension cache [ " v " , layer ] # Value vectors utils . get_act_name ( " k " , layer )
model . cfg . d_mlp # MLP dimension cache [ " z " , layer ] # Pre - projection output utils . get_act_name ( " v " , layer )
model . cfg . d_vocab # Vocabulary size cache [ " result " , layer ] # Post - projection output utils . get_act_name ( " mlp_out " , layer )
model . cfg . n_ctx # Context length cache [ " resid_pre " , layer ] # Residual before layer utils . get_act_name ( " post " , layer ) # MLP post - act
model . cfg . device # Device cache [ " resid_mid " , layer ] # After attn , before MLP
cache [ " resid_post " , layer ] # After layer # Common hook name patterns
cache [ " attn_out " , layer ] # Attention output " hook_embed "
2 TransformerLens: Tokenization cache [ " mlp_out " , layer ]
cache [ " post " , layer ]
#
#
MLP output
MLP post - activation
" hook_pos_embed "
" blocks .{ L }. hook_resid_pre "
cache [ " pre " , layer ] # MLP pre - activation " blocks .{ L }. attn . hook_pattern "
# Text -> Token IDs ( prepends BOS by default ) " blocks .{ L }. attn . hook_z "
tokens = model . to_tokens ( " Hello world " ) # String syntax " blocks .{ L }. attn . hook_result "
tokens = model . to_tokens ( text , prepend_bos = False ) cache [ " blocks .0. attn . hook_pattern " ] " blocks .{ L }. hook_mlp_out "
" ln_final . hook_normalized "
# Text -> String tokens list
str_toks = model . to_str_tokens ( " Hello world " ) 4.2 Cache Methods
# [ ’ <| endoftext | > ’ , ’ Hello ’, ’ world ’]
# Apply LayerNorm to stacked residuals 7 TransformerLens: FactoredMatrix
# Token IDs -> String scaled = cache . a p p l y _ l n _ t o _ s t a c k (
text = model . to_string ( tokens ) residual_stack , layer = -1 , pos_slice = -1 from transformer_lens import FactoredMatrix
)
# Single token operations # Create from two matrices ( stores A , B separately )
tok_id = model . t o _s in gl e _t ok en ( " Paris " ) # Get accumulated residual stream OV = FactoredMatrix ( model . W_V [l , h ] , model . W_O [l , h ])
tok_str = model . t o _ s i n g l e _ s t r _ t o k e n ( tok_id ) accum , labels = cache . a c c u m u l a t e d _ r e s i d (
layer = -1 , incl_mid = True , # Chain operations ( stays factored )
# Batch decode pos_slice = -1 , return_labels = True full_OV = model . W_E @ OV @ model . W_U
texts = model . tokenizer . batch_decode ( token_ids ) )
# Materialize only when needed
# Decompose by component full_matrix = OV . AB
3 TransformerLens: Forward Pass decomp , labels = cache . de c om po se _ re si d (
layer = -1 , pos_slice = -1 , return_labels = True # Efficient properties
) OV . eigenvalues # Only non - zero eigenvalues
3.1 Basic Forward Pass # Stack all head outputs
OV . S # Singular values
OV . norm () # Frobenius norm
logits = model ( tokens ) # [ batch , seq , d_vocab ] heads , labels = cache . s t a c k _ h e a d _ r e s u l t s ( OV . shape # Shape of full matrix
loss = model ( tokens , return_type = " loss " ) layer = -1 , pos_slice = -1 , return_labels = True
) # Efficient indexing ( returns FactoredMatrix )
submatrix = full_OV [ indices , indices ]
1
TransformerLens + PyTorch ARENA Quick Reference
)
" gpt2 - small " , device = device 12 PyTorch: Tensor Operations # Sorting
sorted_vals , indices = tensor . sort ( dim = -1)
# Shape operations indices = tensor . argsort ( descending = True )
# Load pretrained SAE tensor . shape # Get shape
sae , cfg , sparsity = SAE . f r om _p r et ra in e d ( tensor . size ( dim ) # Size of dimension
release = " gpt2 - small - res - jb " , # Unique
tensor . numel () # Total elements unique , counts = t . unique ( tensor , return_counts = True )
sae_id = " blocks .7. hook_ resid_p re " , tensor . squeeze ( dim ) # Remove dim of size 1
device = str ( device ) , tensor . unsqueeze ( dim ) # Add dim of size 1
) # Nonzero
tensor . flatten () # Flatten to 1 D indices = t . nonzero ( tensor > 0)
tensor . flatten ( start , end ) # Flatten range indices = t . argwhere ( tensor > 0)
# Run with SAE ( context manager ) tensor . reshape ( shape )
with model . saes ( saes =[ sae ]) : tensor . view ( shape ) # Must be contiguous
logits = model ( tokens ) # Diagonal
tensor . T # Transpose (2 D ) tensor . diagonal ( offset =0)
tensor . transpose ( d1 , d2 ) tensor . diag ( offset )
# Run with SAE ( explicit ) tensor . permute ( dims )
model . add_sae ( sae )
logits = model ( tokens )
model . reset_saes () # Don ’t forget !
# Stacking / Concatenation
t . stack ([ t1 , t2 ] , dim =0) # New dimension 15 PyTorch: In-Place & Masking
t . cat ([ t1 , t2 ] , dim =0) # Existing dim
# Cache SAE activations t . concat ([ t1 , t2 ]) # Alias for cat # In - place operations ( end with _ )
_ , cache = model . r u n _ w i t h _ c a c h e _ w i t h _ s a e s ( tensor . zero_ ()
tokens , saes =[ sae ] # Splitting tensor . fill_ ( value )
) t . split ( tensor , size , dim ) tensor . masked_fill_ ( mask , value )
sae_acts = cache [ f " { sae . cfg . hook_name }. h o o k _ s a e _ a c t s _ p o s t " ] t . chunk ( tensor , chunks , dim )
tensor . unbind ( dim ) # Returns tuple # Masking patterns
# SAE weights mask = t . triu ( t . ones ( seq , seq ) , diagonal =1) . bool ()
sae . W_enc # [ d_in , d_sae ] encoder tensor . masked_fill_ ( mask , float ( ’ - inf ’) )
sae . W_dec # [ d_sae , d_in ] decoder
13 PyTorch: Math Operations # Clone vs reference
new = tensor . clone () # Copy data
10 PyTorch: Device Management # Elementwise
tensor . abs ()
new = tensor . detach () # Detach from graph
new = tensor . detach () . clone () # Both
tensor . exp ()
import torch as t tensor . log ()
# Device selection
device = t . device (
tensor . sqrt ()
tensor . pow ( n ) 16 PyTorch: Type Conversion
tensor . clip ( min , max )
" mps " if t . backends . mps . is_available () tensor . float () # to float32
else " cuda " if t . cuda . is_available () # Reductions tensor . half () # to float16
else " cpu " tensor . sum ( dim ) tensor . long () # to int64
) tensor . mean ( dim ) tensor . int () # to int32
2
TransformerLens + PyTorch ARENA Quick Reference
ing )
a t t e n t i o n _ h e a d _ n a m e s =[ f " L { l } H { h } " for h in range ( n_heads ) ]
import circuitsvis as cv
import plotly . express as px
def patch_hook ( # Attention heads view
corrupted_act , hook , pos , clean_cache cv . attention . at te nt i on _h e ad s (