TorchLens

Inspect, visualize and intervene on any operation in any neural network.
Install · Tutorials · Visualizations · Model Menagerie · Cite

vit = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224").eval()
cat = tl.trace(vit, "cat.jpg")
cat["vit.layers.5.attention"].facets.pattern.shape # torch.Size([1, 12, 197, 197])
cat.draw(direction="leftright", depth=1)
# ablate one attention head: tabby becomes Egyptian cat
ablated = cat.fork().do(tl.module("vit.layers.5.attention") & tl.head(3), tl.zero_ablate())
ablated.output_table(k=3)
# rank label prob
# 1 Egyptian cat 0.489
# 2 tabby, tabby cat 0.341
# 3 tiger cat 0.147
Why?
Understanding and controlling the computations inside neural networks is the most important scientific challenge of our time (at least). Progress on this problem, known as mechanistic interpretability, would make AI more beneficial for society, illuminate how our brains work, and guard against undesirable behaviors like deception or killing us all.
Some aspects of mechanistic interpretability are deep and open-ended. We need to understand dauntingly complex systems that may soon outsmart us, with new frontier models arriving faster than we can study the current ones. It's not even clear what a "solution" would look like, or how many obstacles remain. We'll surely need help from the AI agents themselves.
Other aspects are just plumbing, and while tedious, they are finite: the same small set of tasks for every model, like extracting and editing its activations and gradients. For instance, PyTorch has long lacked a built-in way to extract every intermediate activation from arbitrary networks (an official docstring admits this can take "some massaging"). But all networks are built from the same basic parts, so a few well-made tools should work on all of them.
The modest goal of TorchLens is to fix these plumbing problems once and for all, so you and your agents can spend your time and tokens on the deep questions, and maybe even solve some of them.
What TorchLens does
Almost everything you do in TorchLens starts with one function, tl.trace. You don't have to set anything up. Pass it any PyTorch model and its input exactly as they are, with no hooks, wrappers or changes to your code:
import torchlens as tl
from transformers import GPT2LMHeadModel
gpt2 = GPT2LMHeadModel.from_pretrained("gpt2").eval()
text = "The capital of France is"
trace = tl.trace(gpt2, text) # run model as-is, logging every operation
op = trace["tanh_6"] # fetch the 6th tanh operation
op.out.shape # torch.Size([1, 5, 3072])
op.parents, op.children # the operations before and after tanh_6
mlp = trace["transformer.h.5.mlp"] # look up a module's record by its address
mlp.total_flops_forward # MLP's forward FLOPs (one of 800+ metadata fields in TorchLens)
trace.draw(module="transformer.h.5.mlp.act") # draw the graph of the MLP's GELU activation module