Interactive mechanistic interpretability for PyTorch & HuggingFace LLMs.
Attach directly to a model already in GPU VRAM with zero weight duplication. Inspect Logit Lens trajectories, run 2-forward / 1-backward Attribution Patching, decompose logits with DLA, and test Contrastive Activation Steering from a single local web studio.
What's New in v2.0.0
Version 2.0 turns InterpLens from a single-model GPT-2 prototype into a multi-architecture circuit workbench tested on real 7B, 14B, and MoE models.
Quickstart
Run InterpLens locally on a laptop CPU/GPU or attach to 7B–32B checkpoints on Google Colab (T4 / A100).
pip install interplens
interplens launch --model gpt2 --device auto --port 8000
# Open http://127.0.0.1:8000
import interplens as il
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-3B-Instruct", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B-Instruct")
# Attach directly to the in-memory model with zero VRAM duplication
il.launch(model=model, tokenizer=tokenizer, port=8000)
!pip install -q interplens accelerate nvidia-ml-py
import interplens as il
from google.colab import output
adapter = il.launch(
model_name="Qwen/Qwen2.5-7B-Instruct", # or "allenai/OLMoE-1B-7B-0924-Instruct"
device="cuda",
dtype="bfloat16", # use "float16" on T4 GPUs
port=8000,
block=False,
)
output.serve_kernel_port_as_window(8000)
import torch.nn as nn
import interplens as il
class ResearchTransformer(nn.Module):
def __init__(self, vocab=1000, d_model=128, n_layers=4):
super().__init__()
self.embed = nn.Embedding(vocab, d_model)
self.layers = nn.ModuleList([
nn.TransformerEncoderLayer(d_model=d_model, nhead=4, batch_first=True)
for _ in range(n_layers)
])
self.lm_head = nn.Linear(d_model, vocab, bias=False)
def forward(self, x):
h = self.embed(x)
for layer in self.layers:
h = layer(h)
return self.lm_head(h)
il.launch(model=ResearchTransformer(), auto_hook=True, port=8000)
Analysis Engines
Every engine degrades gracefully according to model capabilities (L0–L4) and surfaces explicit warnings whenever a model does not expose a given internal tensor.
Direct Logit Attribution (DLA)
v2.0Projects Embedding, Attention, and MLP/MoE outputs onto the unembedding direction W_U[:, target] - W_U[:, foil] to measure exact per-layer logit contributions.
Gradient Attribution Patching
v2.0Approximates the full Layer × Position causal patching matrix and sublayer circuit rankings in 2 forward passes and 1 backward pass.
Contrastive Activation Steering
v2.0Computes Difference-in-Means vectors from positive/negative prompt pairs and runs side-by-side Baseline vs. Steered multi-token generation.
Mermaid Architecture Graph
v2.0Auto-detects GQA vs MHSA, RMSNorm vs LayerNorm, SwiGLU, MoE routers, and tied embeddings with residual skip paths, zoom, and SVG export.
Logit Lens & Entropy Drift
CoreProjects intermediate residual states through LN_final and W_U to track token rank trajectories, Shannon entropy, and layer-to-layer KL divergence.
Residual Stream & 2D PCA
CoreTracks L2 norm growth, layer-by-layer cosine similarity matrices, and SVD-based 2D PCA residual trajectories across depth.
Attention & Induction Heads
CoreInspects N×N attention heatmaps, query-key arc diagrams, and runs automated prefix-matching sweeps to detect induction heads.
Hardware & Memory Profiler
CoreLive WebSocket telemetry for CUDA VRAM (or system RAM on CPU laptops), NVML temperature/power/clocks, and per-layer parameter footprints.
Fast Circuits (DLA & AtP)
Run both Direct Logit Attribution and Gradient Attribution Patching programmatically or from the Fast Circuits tab in the studio.
from interplens.analysis.dla import compute_direct_logit_attribution
from interplens.analysis.attribution_patching import run_attribution_patching
# 1. Direct Logit Attribution
logits, cache = adapter.run_with_cache("The Eiffel Tower is located in the city of")
dla = compute_direct_logit_attribution(
adapter=adapter,
cache=cache,
tokens=adapter.tokenize("The Eiffel Tower is located in the city of"),
session_id="paris_check",
target_token=" Paris",
foil_token=" London",
logits=logits,
)
print(dla.top_components[:3])
# 2. Gradient Attribution Patching (2 forward + 1 backward pass)
atp = run_attribution_patching(
adapter=adapter,
clean_prompt="When Mary and John went to the store, John gave a drink to",
corrupt_prompt="When Mary and John went to the store, Mary gave a drink to",
)
print(f"{atp.runtime_ms} ms | Peak: L{atp.max_attribution_layer} Pos {atp.max_attribution_position}")
Contrastive Activation Steering (CAA)
Extract a Difference-in-Means direction from positive and negative prompt sets, then compare baseline and steered multi-token completions side-by-side.
from interplens.analysis.steering import (
compute_contrastive_steering_vector,
generate_steered_comparison,
)
vec = compute_contrastive_steering_vector(
adapter=adapter,
positive_prompts=["I am so happy and grateful today!", "Everything is going wonderfully!"],
negative_prompts=["I am miserable and frustrated today.", "Everything is going horribly wrong."],
target_layer=adapter.num_layers // 2,
)
result = generate_steered_comparison(
adapter=adapter,
prompt="Today I walked outside and thought to myself,",
vector_id=vec.vector_id,
multiplier=2.5,
max_new_tokens=24,
)
print("Baseline:", result.baseline_completion)
print("Steered :", result.steered_completion)
Supported Models
InterpLens discovers transformer topologies automatically across HuggingFace AutoModelForCausalLM, TransformerLens, and custom PyTorch modules.
| Family | Example Checkpoints | Hook Layout |
|---|---|---|
| Qwen 2.5 | Qwen2.5-0.5B, 3B, 7B, 14B, 32B |
model.layers.{l} (GQA + SwiGLU) |
| Meta Llama 3 / 3.2 | Llama-3.2-1B, 3B, Llama-3.1-8B |
model.layers.{l} (GQA + RMSNorm) |
| Mistral & Mixtral MoE | Mistral-7B-v0.3, Mixtral-8x7B |
model.layers.{l} / block_sparse_moe |
| OLMoE | OLMoE-1B-7B-0924-Instruct |
model.layers.{l} (MoE + BFloat16) |
| Google Gemma 2 | gemma-2-2b-it, gemma-2-9b-it |
model.layers.{l} (GQA + GeGLU) |
| GPT-2 & Pythia | gpt2, gpt2-xl, pythia-160m..12b |
transformer.h.{l} / blocks.{l} / gpt_neox.layers.{l} |
Python API
| Function | Description |
|---|---|
il.launch(model=None, model_name="gpt2", port=8000, device="auto", dtype=None, hf_token=None, block=False) |
Attaches to an in-memory model or loads a HuggingFace/TransformerLens checkpoint and starts the visual debugger server. |
il.inspect(prompt, model=None, model_name="gpt2", device="auto") |
Runs a forward pass under @torch.inference_mode() and returns an ActivationSession with cached CPU-offloaded tensors. |
il.stop_server() |
Stops the background Uvicorn server cleanly (useful when switching models in notebooks). |
il.free_gpu_memory() |
Runs garbage collection and clears CUDA memory cache. |
Configuration & Citation
| Environment Variable | Default | Description |
|---|---|---|
INTERPLENS_PORT |
8000 |
HTTP & WebSocket server port. |
INTERPLENS_HOST |
127.0.0.1 |
Bind address (0.0.0.0 for remote VMs / Colab). |
INTERPLENS_DEVICE |
auto |
Compute device (cuda, mps, cpu). |
INTERPLENS_MAX_SESSIONS |
3 |
Max cached activation sessions in memory. |
Citation
@software{ahsan2026interplens,
author = {Syed Sarim Ahsan},
title = {InterpLens: An Interactive Mechanistic Interpretability Toolkit and Visual Debugger for LLMs},
year = {2026},
url = {https://github.com/sarimahsan/interplens},
version = {2.0.0}
}