The Visual Debugger for LLM Internals
InterpLens is a production-grade mechanistic interpretability toolkit and visual workbench for PyTorch and TransformerLens. Inspect intermediate vocabulary projections, trace causal circuits, compute induction head metrics, steer representations, and introspect attention graphs in real time with zero-copy GPU memory attachment.
Installation Options
Install InterpLens directly from PyPI using your preferred package manager.
# Standard installation (PyTorch, FastAPI, UI Debugger)
pip install interplens
# Full bundle (TransformerLens + Scikit-Learn PCA support)
pip install interplens[all]
uv pip install interplens[all]
poetry add interplens --extras "all"
Target specific optional dependencies based on your environment:
interplens[tl]: Addstransformer-lens>=2.0.0for HookedTransformer support.interplens[analysis]: Addsscikit-learn>=1.2.0for high-dimensional PCA residual trajectory calculations.interplens[all]: Installs all optional engines and dependencies.interplens[dev]: Installs testing dependencies (pytest,pytest-asyncio).
Configuration & Environment Variables
Fine-tune server behavior, compute devices, and memory settings via environment variables.
| Variable | Default | Type | Description & Fallback Behavior |
|---|---|---|---|
INTERPLENS_PORT |
8000 |
int |
HTTP server port. Automatically falls back to 8000 if invalid integer string is passed. |
INTERPLENS_HOST |
127.0.0.1 |
str |
Host binding IP. Automatically switches to 0.0.0.0 when Google Colab is detected. |
INTERPLENS_DEVICE |
auto |
str |
Compute target (cuda, cpu, mps, auto). Falls back to cpu if CUDA is requested but unavailable. |
INTERPLENS_MAX_SESSIONS |
3 |
int |
Maximum number of cached activation sessions in memory before LRU eviction. |
INTERPLENS_FP16 |
true |
bool |
Whether to use half-precision (float16) when loading HuggingFace models on GPU to conserve VRAM. |
INTERPLENS_DEBUG |
false |
bool |
Enables verbose diagnostic logging across adapters and analysis modules. |
Complete Code Recipes & How-To Guides
Copy-paste ready code examples covering every supported model type, research scenario, and analysis engine.
If your model is already loaded in CUDA memory (e.g. inside a research script), pass the instance directly to il.launch(). InterpLens wraps the model in-place with zero memory duplication:
import interplens as il
from transformer_lens import HookedTransformer
# 1. Suppose your model is already loaded in GPU memory:
model = HookedTransformer.from_pretrained("gpt2-small", device="cuda")
# 2. Attach visual debugger backend (runs in background thread by default)
adapter = il.launch(model=model, port=8000)
print(f"Debugger active at: http://127.0.0.1:8000")
print(f"Model: {adapter.model_name} | Layers: {adapter.num_layers} | Hidden Dim: {adapter.hidden_dim}")
# 3. Stop the background server whenever you are finished:
# il.stop_server()
Pass any HuggingFace model identifier. InterpLens automatically discovers the architecture, attaches PyTorch hooks, and extracts the unembedding projection matrix:
import interplens as il
# Load Qwen 2.5 0.5B on GPU with eager attention hooks
adapter = il.launch(
model_name="Qwen/Qwen2.5-0.5B",
device="cuda",
port=8000,
block=True # Blocks main thread (ideal for dedicated server scripts)
)
# Pass token via CLI flag
interplens launch --model meta-llama/Llama-3.2-1B --hf-token "hf_YourAuthTokenHere" --device cuda
# Or pass via environment variable:
export HF_TOKEN="hf_YourAuthTokenHere"
interplens launch --model meta-llama/Llama-3.2-1B --device cuda
When passing a novel `nn.Module` without TransformerLens, set `auto_hook=True` to let `PyTorchAutoHooker` discover internal residual streams and attention layers:
import torch
import torch.nn as nn
import interplens as il
from transformers import AutoTokenizer
# Your custom PyTorch transformer class
class CustomTransformer(nn.Module):
def __init__(self):
super().__init__()
self.embed = nn.Embedding(50257, 256)
self.layers = nn.ModuleList([
nn.TransformerEncoderLayer(d_model=256, nhead=4, batch_first=True)
for _ in range(4)
])
self.ln_f = nn.LayerNorm(256)
self.lm_head = nn.Linear(256, 50257, bias=False)
def forward(self, input_ids, **kwargs):
x = self.embed(input_ids)
for layer in self.layers:
x = layer(x)
x = self.ln_f(x)
return self.lm_head(x)
# Instantiate custom model and tokenizer
my_model = CustomTransformer().eval()
tokenizer = AutoTokenizer.from_pretrained("gpt2")
# Launch visual debugger with automated hook discovery
adapter = il.launch(model=my_model, tokenizer=tokenizer, auto_hook=True, port=8000)
InterpLens automatically detects the Colab environment, sets host binding to 0.0.0.0, and calls google.colab.output.serve_kernel_port():
# Inside a Google Colab notebook cell:
!pip install interplens[all]
import interplens as il
from transformer_lens import HookedTransformer
model = HookedTransformer.from_pretrained("gpt2-small", device="cuda")
il.launch(model=model, port=8000)
# InterpLens automatically prints the secure Colab proxy iframe link
import interplens as il
from interplens.adapters import get_adapter_for_model
from interplens.analysis import apply_activation_steering
adapter = get_adapter_for_model("gpt2", device="cuda")
adapter.load()
# Inject steering vector at layer 6 with multiplier 2.5
steered_result = apply_activation_steering(
adapter=adapter,
prompt="Love and compassion are",
target_layer=6,
multiplier=2.5,
steering_vector=None # Computes synthetic steering if None, or pass List[float]
)
print("Original Top-1 Prediction:", steered_result.original_prediction)
print("Steered Top-1 Prediction:", steered_result.steered_prediction)
print("Shift Cosine Distance:", steered_result.cosine_distance)
import interplens as il
from interplens.adapters import get_adapter_for_model
from interplens.analysis import run_causal_patching_sweep
adapter = get_adapter_for_model("gpt2", device="cuda")
adapter.load()
# Run full ROME causal tracing sweep across all layers and token positions
sweep_results = run_causal_patching_sweep(
adapter=adapter,
clean_prompt="The Eiffel Tower is located in the city of",
corrupt_prompt="The Colosseum is located in the city of",
target_token_str=" Paris"
)
print(f"Max Causal Recovery: {sweep_results.max_recovery_percentage:.1f}%")
print(f"Locus of Factual Association: Layer L{sweep_results.max_recovery_layer}, Position {sweep_results.max_recovery_position}")
print(f"Target Clean Token: {sweep_results.target_token}")
import interplens as il
from interplens.adapters import get_adapter_for_model
from interplens.analysis import detect_induction_heads
adapter = get_adapter_for_model("gpt2", device="cuda")
adapter.load()
# Automatically generate random repeated token sequence [A][B]...[A] and scan all heads
report = detect_induction_heads(adapter=adapter, seq_len=50)
print(f"Total Heads Scanned: {report.total_heads_scanned}")
print(f"Flagged Induction Heads: {report.flagged_count}")
for head in report.top_induction_heads[:3]:
print(f" → Layer {head.layer}, Head {head.head} (Induction Score: {head.score:.3f})")
from interplens.adapters import (
BaseArchitectureStrategy,
ArchitectureFamily,
register_architecture_strategy,
get_adapter_for_model
)
class MyCustomMoEStrategy(BaseArchitectureStrategy):
family = ArchitectureFamily.CUSTOM
def matches(self, model_or_name) -> bool:
# Match models with 'my-custom-moe' in name or class
return "custom-moe" in str(getattr(model_or_name, "__name__", model_or_name)).lower()
def get_layer_count(self, model) -> int:
return len(model.custom_blocks)
def get_hidden_dim(self, model) -> int:
return model.config.d_model
def get_head_count(self, model) -> int:
return model.config.n_heads
def get_residual_hook_names(self, model):
return [f"custom_blocks.{i}.post_residual" for i in range(len(model.custom_blocks))]
# Register strategy into global registry
register_architecture_strategy(MyCustomMoEStrategy())
# InterpLens will now automatically use this strategy for any custom-moe model
adapter = get_adapter_for_model("my-custom-moe-7b")
import interplens as il
from interplens.adapters import get_adapter_for_model, generate_model_report
from interplens.utils import generate_model_report_pdf
adapter = get_adapter_for_model("gpt2", device="cpu")
adapter.load()
# 1. Generate structured model capability report
report = generate_model_report(adapter)
# 2. Export publication-ready PDF document
pdf_bytes = generate_model_report_pdf(report, output_path="interplens_report_gpt2.pdf")
print("Report PDF generated successfully!")
Robustness & Fail-Safe Fallbacks Matrix
How InterpLens prevents crashes across non-standard architectures, invalid inputs, and memory constraints.
| Subsystem | Potential Failure Condition | InterpLens Fallback Mechanism | Resulting Behavior |
|---|---|---|---|
| Model Loading | FlashAttention / SDPA unsupported on CPU / device | 3-Stage Fallback: (1) eager attention → (2) default attention → (3) patched config |
Model loads safely without C-extension errors |
| Dependency Loading | transformer-lens not installed in environment |
Fast find_spec check in get_adapter_for_model falls back to HuggingFace AutoModel |
Loads without requiring heavy optional dependencies |
| Tokenizer Missing | Bare PyTorch model without a tokenizer object | Converts prompt strings to ASCII integer token tensors or float vectors | Forward pass executes and activations are captured |
| Vocabulary Unembed | Model lacks linear unembedding matrix $W_U$ | Raises UnembeddingNotFoundError and disables Logit Lens while keeping Residual/Attention active |
Graceful capability degradation (L3 instead of L2) |
| Attention Division | Zero token distance in synthetic attention calculations | Guarded by max(1, i - j) in diagonal decay functions |
Prevents ZeroDivisionError |
| Causal Target Decoding | Target token decode failure or out-of-vocab token | 3-Tier Decode: (1) adapter.decode() → (2) tokenizer.decode() → (3) fallback string |
Causal sweep completes with exact token label |
| Cross-Device Patching | Vector norm difference between CPU and CUDA tensors | Explicit .detach().cpu() before torch.norm calculation |
Prevents PyTorch device mismatch exceptions |
| Session Concurrency | Model forward pass raises runtime CUDA out-of-memory | Forward pass executes before LRU cache eviction | Existing valid cached sessions are preserved |
| Config Parsing | Invalid environment variable string in INTERPLENS_PORT |
Safe _get_env_int helper catches (ValueError, TypeError) and returns default 8000 |
Server starts reliably without import-time crash |
| Colab Execution | Default 127.0.0.1 localhost binding unreachable in Colab |
Detects google.colab and switches host to 0.0.0.0 + calls kernel port proxy |
Seamless remote web UI access in cloud notebook |
Adaptive Capability Matrix (L0 – L4)
How InterpLens dynamically enables and adapts engines according to model features.
| Level | Classification | Capabilities Present | Available Debugger Engines |
|---|---|---|---|
| Level 0 | Black-Box Model | Forward output logits only | Final token probabilities, top-K vocabulary predictions |
| Level 1 | Residual Only | Intermediate layer hidden states ($x_l$) | Residual Stream Inspector, L2 vector norms, Cosine similarity drift |
| Level 2 | Unembed Ready | Residual states + Unembedding matrix ($W_U$) | Logit Lens Engine, Entropy dynamics, KL divergence, Top-K trajectories |
| Level 3 | Component Hooked | Residual + Attention weights + MLP activations | Attention Head Explorer, Arc Diagrams, Neuron Activation Explorer, Token Attribution |
| Level 4 | Full Interventional | Hooks + Causal activation patching + Vector steering | ROME Causal Patching Sweeps, Continuous Activation Steering, Induction Head Detector |
Major Supported Models & Architectures
Out-of-the-box support for open-weights transformer models across PyTorch and TransformerLens.
InterpLens features native auto-discovery and hook strategies for all major decoder-only transformer architectures. Launch any model below by repo string or pass a pre-loaded instance:
| Model Family | Popular Checkpoints & Variants | Default Level | Eager Hook Strategy | CLI Launch Command |
|---|---|---|---|---|
|
Meta Llama 3 / 3.2
|
Llama-3.2-1B, Llama-3.2-3B, Llama-3-8B, Llama-3-70B, Llama-2-7B |
L4 Full | LlamaStrategy (model.layers[i]) |
interplens launch --model meta-llama/Llama-3.2-1B --hf-token "hf_..." |
|
Alibaba Qwen 2.5
|
Qwen2.5-0.5B, 1.5B, 3B, 7B, 14B, 32B, Qwen2.5-Coder-7B |
L4 Full | QwenStrategy (model.layers[i]) |
interplens launch --model Qwen/Qwen2.5-0.5B --device cuda |
|
Mistral & Mixtral MoE
|
Mistral-7B-v0.1, Mistral-7B-v0.3, Mistral-7B-Instruct, Mixtral-8x7B |
L4 Full | MistralStrategy (model.layers[i]) |
interplens launch --model mistralai/Mistral-7B-v0.1 |
|
Google Gemma & Gemma 2
|
gemma-2b, gemma-7b, gemma-2-2b, gemma-2-9b, gemma-2-27b |
L4 Full | GemmaStrategy (model.model.layers[i]) |
interplens launch --model google/gemma-2b |
|
OpenAI GPT-2 Family
|
gpt2 (124M), gpt2-medium (355M), gpt2-large (774M), gpt2-xl (1.5B) |
L4 Full | GPT2Strategy / HookedTransformer |
interplens launch --model gpt2 --device cuda |
|
EleutherAI Pythia & NeoX
|
pythia-70m, 160m, 410m, 1b, 1.4b, 2.8b, 6.9b, 12b |
L4 Full | PythiaStrategy (gpt_neox.layers[i]) |
interplens launch --model EleutherAI/pythia-70m |
|
SmolLM & TinyLlama
|
SmolLM-135M, SmolLM-360M, SmolLM-1.7B, TinyLlama-1.1B |
L4 Full | LlamaStrategy (model.layers[i]) |
interplens launch --model HuggingFaceTB/SmolLM-135M |
|
DeepSeek LLM & Coder
|
deepseek-llm-7b-base, deepseek-coder-1.3b, deepseek-coder-6.7b |
L4 Full | LlamaStrategy / GenericAdapter |
interplens launch --model deepseek-ai/deepseek-llm-7b-base |
|
Custom PyTorch Models
|
Any custom nn.Module, research transformer, or proprietary architecture |
L3–L4 | PyTorchAutoHooker (auto_hook=True) |
il.launch(model=my_custom_model, auto_hook=True) |
Core Interpretability Engines Deep-Dive
Mathematical formulations, telemetry diagnostics, and visual analytics for transformer networks.
The residual stream serves as a shared memory highway. The Logit Lens projects intermediate vectors $x_l$ into vocabulary space by applying the unembedding matrix $W_U$:
Introspects model parameter tensors to calculate exact parameter budgets across MLP Expansion, Self-Attention QKVO, Embeddings ($W_E$), Language Model Head ($W_U$), and Normalization layers.
Complete Python API Reference
Full signature and documentation for all public functions, classes, and submodules in interplens.
Top-Level Functions (import interplens as il)
# 1. Launch visual debugger server
il.launch(
model: Optional[Any] = None, # Pre-loaded HookedTransformer or nn.Module
model_name: str = "gpt2", # HuggingFace repo ID or local checkpoint
port: int = 8000, # Server port (default: 8000)
host: str = "127.0.0.1", # Host binding (auto 0.0.0.0 in Colab)
device: str = "auto", # Target device (cuda, cpu, mps, auto)
auto_hook: bool = False, # Use PyTorchAutoHooker for novel nn.Modules
tokenizer: Optional[Any] = None, # Custom tokenizer object or HF string
block: bool = False # Run blocking or in background daemon thread
) -> BaseModelAdapter
# 2. Stop running background debugger server
il.stop_server() -> None
# 3. Pure-Python forward pass inspection
il.inspect(
prompt: str,
model: Optional[Any] = None,
model_name: str = "gpt2",
device: str = "auto",
corrupted_prompt: Optional[str] = None
) -> ActivationSession
Analysis Engine Functions (interplens.analysis)
from interplens.analysis import (
compute_logit_lens, # (adapter, cache, tokens, session_id, position, top_k=5) -> LogitLensResponse
compute_residual_metrics, # (adapter, cache, tokens, session_id, position) -> ResidualStreamResponse
apply_activation_steering, # (adapter, prompt, target_layer=0, multiplier=1.0, steering_vector=None) -> SteeredResponse
compute_attention_metrics, # (adapter, cache, tokens, session_id, layer=0, head=0) -> AttentionHeadResponse
compute_neuron_activations, # (adapter, cache, tokens, session_id, layer=0, position=0, top_k=10) -> NeuronAnalysisResponse
compute_token_attributions, # (adapter, cache, tokens, session_id, target_position=-1) -> TokenAttributionResponse
run_causal_patching_sweep, # (adapter, clean_prompt, corrupt_prompt, target_token_str=None) -> CausalTracingResponse
detect_induction_heads, # (adapter, seq_len=50) -> InductionDetectorResponse
inspect_model_topology # (adapter) -> ModelTopologyResponse
)
Device Utilities (interplens.utils)
from interplens.utils import (
get_optimal_device, # () -> torch.device (cuda > mps > cpu)
resolve_device, # (device_str: str) -> torch.device
get_vram_usage, # (device) -> {"allocated_mb": int, "reserved_mb": int, "total_mb": int}
free_gpu_memory, # (device) -> None (invokes torch.cuda.empty_cache & gc.collect)
get_gpu_grid_status, # () -> Dict[int, GPUStatus]
get_detailed_gpu_profiler, # (adapter, cache) -> Dict[str, Any]
generate_model_report_pdf # (report: ModelReport, output_path: str = None) -> bytes
)
FastAPI REST & WebSocket Endpoints
HTTP API specification for programmatic integrations, dashboards, and automated analysis jobs.
| Method | Endpoint | Parameters / Body | Description |
|---|---|---|---|
| GET | /api/health |
None | Health check returning active model name, device, and cached sessions. |
| POST | /api/run |
{"prompt": str, "corrupted_prompt": Optional[str]} |
Executes forward pass, stores activations in LRU session store, and returns session ID & token list. |
| GET | /api/analysis/logit-lens |
session_id, position (int), top_k (int) |
Returns layer-by-layer predicted tokens, probabilities, entropy, and KL divergence. |
| GET | /api/analysis/residual-stream |
session_id, position (int) |
Returns L2 vector norms curve and $L \times L$ Cosine similarity matrix. |
| GET | /api/analysis/attention |
session_id, layer (int), head (int) |
Returns single-head $N \times N$ attention matrix, multi-head layer grid, and arc link connection lists. |
| GET | /api/analysis/neurons |
session_id, layer (int), position (int) |
Returns top-10 firing MLP neurons and prompt text lighting activation strips. |
| GET | /api/analysis/attribution |
session_id, target_position (int) |
Returns input prompt token attribution scores computed via Attention Rollout. |
| POST | /api/analysis/causal-patching |
{"clean_prompt": str, "corrupt_prompt": str, "target_token": str} |
Executes ROME causal tracing sweep and returns $N_{\text{layers}} \times N_{\text{pos}}$ recovery heatmap. |
| POST | /api/analysis/steer |
{"prompt": str, "target_layer": int, "multiplier": float} |
Injects activation steering vector and returns original vs steered logits and predictions. |
| GET | /api/model/report |
None | Returns comprehensive model discovery report and evaluated capability levels. |
| GET | /api/model/topology |
None | Inspects model parameter tensors and returns percentage breakdown by architectural component. |
| GET | /api/report/pdf |
session_id |
Generates and downloads publication-ready PDF diagnostic report. |
| WS | /api/ws/telemetry |
WebSocket Connection | Real-time streaming telemetry push (VRAM allocated/reserved, session count, device status). |
Command Line Interface (CLI) Flags
Full list of arguments for the interplens launch CLI console script.
| CLI Flag | Default | Description |
|---|---|---|
--model <name> |
gpt2 |
Model repo identifier or local checkpoint path (e.g. gpt2, Qwen/Qwen2.5-3B, meta-llama/Llama-3.2-1B). |
--device <target> |
auto |
Target compute device: cuda, cpu, mps, or auto (selects best available). |
--port <number> |
8000 |
HTTP server port for web debugger. |
--host <address> |
127.0.0.1 |
Network host address binding. |
--hf-token <token> |
None |
HuggingFace user access token for gated models (aliases: --token). |
--tokenizer <id> |
None |
Custom HuggingFace tokenizer repository ID or path override. |
Exception Hierarchy Reference
Structured exceptions defined under interplens.exceptions for robust error handling.
InterpLensError (Base exception for all InterpLens errors)
├── ModelLoadError # Raised when model weights or tokenizer fails to load
├── AdapterNotFoundError # Raised when no suitable adapter strategy can be resolved
├── CapabilityError # Raised when model lacks required interpretability capability
│ └── UnembeddingNotFoundError # Raised when unembedding matrix W_U is absent or inaccessible
└── ServerExecutionError # Raised when the debugger web server encounters a runtime fault
Example of structured error handling in production code:
import interplens as il
from interplens.exceptions import ModelLoadError, UnembeddingNotFoundError
try:
adapter = il.launch(model_name="nonexistent-model-id")
except ModelLoadError as e:
print(f"Caught model load failure: {e}")
except UnembeddingNotFoundError as e:
print(f"Model lacks W_U unembedding: {e}")