Approaches and Tools to Understand the Mechanistic Interpretability of LLMs
Introduction: Opening the Black Box
- What Mechanistic Interpretability Is and Is Not
- The Epistemological Stakes
- What You Will Learn
- How to Read This Book
- A Note on Scope and Limitations
Chapter 1: The Promise of Mechanistic Understanding
- Why Black-Box Models Fail Us
- Mechanistic Versus Behavioral Interpretability
- Landmark Discoveries
- The Map of This Book
- Open Questions and Honest Uncertainties
Chapter 2: Mathematical Foundations: Linear Algebra and Tensor Calculus
- Vector Spaces and Inner Products
- Basic Definitions
- Why Geometry Matters
- Subspaces and Projections
- A Worked Example
- Code: Visualizing Vector Geometry
- Matrix Factorizations and Spectral Decomposition
- Singular Value Decomposition
- Why SVD Matters for Interpretability
- Eigendecomposition
- A Worked Example: Analyzing Attention with SVD
- Tensor Algebra and Einstein Notation
- The Convention
- Why Einstein Notation for Transformers
- Code: Verifying Einstein Notation
- Position and Head Indices
- Jacobian and Hessian Analysis
- The Jacobian
- The Hessian
- Connection to Interpretability
- Numerical Stability and Floating-Point Arithmetic
- Floating-Point Basics
- Attention-Specific Issues
- Mixed Precision Training
- Code: Numerical Stability in Practice
- Summary
Chapter 3: Probability, Information Theory and Optimization
- Probability Distributions Over Sequences
- The Language Modeling Objective
- Cross-Entropy Loss
- Perplexity
- Conditional Distributions and Next-Token Prediction
- Code: Computing Language Model Probabilities
- Entropy, Cross-Entropy and KL Divergence
- Entropy
- KL Divergence
- Cross-Entropy and Its Decomposition
- Practical Considerations
- Gradient-Based Optimization
- Gradient Descent
- Stochastic Gradient Descent
- Adam Optimizer
- Learning Rate Schedules
- Code: Understanding Adam Dynamics
- Loss Landscapes and Critical Points
- Local Minima and Saddle Points
- Flat vs. Sharp Minima
- Code: Visualizing Loss Landscape Curvature
- Regularization and Generalization
- Explicit Regularization
- Implicit Regularization
- Implications for Interpretability
- Summary
Chapter 4: From Neurons to Layers: Computational Abstractions of Deep Learning
- The Forward Pass as a Computational Graph
- Composition and Data Flow
- The Computational Graph View
- Code: Visualizing a Computational Graph
- Activation Functions and Nonlinearities
- Common Activations
- Why the Choice Matters
- Code: Comparing Activation Functions
- The Universal Approximation Theorem and Its Limits
- What It Means
- What It Does Not Mean
- Representation Learning and Feature Hierarchies
- The Idea of a Hierarchy
- Code: Analyzing Representational Hierarchy
- Backpropagation and the Flow of Information
- The Chain Rule
- Gradient Flow and Vanishing Gradients
- Implications for Interpretability
- Code: Visualizing Gradient Flow
- Summary
Chapter 5: Transformer Architectures: Computational Graphs and Parameterized Computation
- The Original Transformer Architecture
- High-Level Structure
- Token Embedding and Positional Encoding
- The Transformer Layer
- The Complete Forward Pass
- Code: Transformer Forward Pass from Scratch
- Attention as a Soft Selection Mechanism
- Scaled Dot-Product Attention
- Multi-Head Attention
- Code: Understanding Attention Mechanics
- Residual Connections and Layer Normalization
- Residual Connections
- Layer Normalization
- Code: Comparing Normalization Variants
- Modern Variants
- Rotary Positional Embeddings (RoPE)
- SwiGLU
- Grouped Query Attention (GQA)
- FlashAttention
- Summary
Chapter 6: Embeddings, Positional Encoding and the Representation of Language
- Tokenization and Vocabulary Construction
- Why Subword Tokenization
- Byte Pair Encoding
- WordPiece and Unigram
- Tokenization and Interpretability
- Code: Exploring Tokenization
- Token Embeddings as Learned Representations
- Geometry of the Embedding Space
- Probing Embeddings
- The Embedding as Part of the Circuit
- Absolute and Relative Positional Encodings
- Sinusoidal Positional Encodings
- Learned Positional Embeddings
- Rotary Positional Embeddings (RoPE)
- ALiBi (Attention with Linear Biases)
- Code: Implementing Different Positional Encodings
- Positional Encoding Mechanisms
- Position in the Residual Stream
- Position Through Attention Biases
- Positional Awareness in Interpretability
- Summary
Chapter 7: The Residual Stream as Information Highway
- The Residual Stream: Definition and Dynamics
- What Is the Residual Stream?
- The Accumulator View
- Code: Tracing the Residual Stream
- Information Flow Analysis
- What Information Is in the Residual Stream?
- Measuring Information Content
- Code: Probing the Residual Stream
- Residual Stream Interference
- Feature Competition
- Cancellation and Cooperation
- Code: Visualizing Interference
- Experimental Studies of Residual Stream Structure
- Empirical Observations
- Key Findings from Literature
- Summary
Chapter 8: Attention Mechanisms: From Self-Similarity to Inductive Patterns
- Attention Head Specialization
- Why Different Heads Do Different Things
- Detecting Head Specialization
- Code: Analyzing Attention Patterns
- Pattern Recognition in Attention Maps
- Head Types
- Code: Detecting Head Types with TransformerLens
- Induction Heads
- What Are Induction Heads?
- The Mechanism in Detail
- Evidence for Induction Heads
- Code: Detecting Induction Heads
- Attention to Position and Syntax
- Positional Attention
- Syntactic Attention
- Code: Analyzing Syntactic Attention
- Attention Collapse and Redundancy
- Not All Heads Are Useful
- Measuring Head Importance
- Summary
Chapter 9: Feed-Forward Networks and the Geometry of Feature Processing
- MLP as Feature Transducers
- The Standard MLP
- The Expanded Dimension
- SwiGLU in Modern Models
- Code: Comparing MLP and SwiGLU
- Feature Selectivity in Neurons
- What Do Individual Neurons Respond To?
- Activation Maximization
- Code: Neuron Activation Analysis
- Direct Logit Bias
- MLP Contribution to Next-Token Prediction
- Detecting Direct Logit Bias
- Code: Analyzing Direct Logit Bias
- MLP-Attention Interaction
- How Attention and MLP Collaborate
- Key-Value Memory
- Summary
Chapter 10: Normalization, Initialization and the Stability of Deep Computation
- Layer Normalization: Variants and Effects
- Standard LayerNorm
- Pre-Norm vs. Post-Norm
- RMSNorm
- Code: Comparing Normalization Variants
- Parameter Initialization Strategies
- Why Initialization Matters
- Variance-Scaled Initialization
- Transformer-Specific Initialization
- Code: Analyzing Initialization Effects
- Signal Propagation in Deep Networks
- The Problem of Depth
- Empirical Observations
- Code: Measuring Residual Stream Growth
- Normalization and Interpretability
- How Normalization Affects Analysis Methods
- LN-Free Models for Interpretability
- Training Dynamics and Emergent Structure
- How Training Shapes the Network
- Summary
Chapter 11: The Nature of Learned Features: Superposition and Distributed Codes
- The Feature-Dimension Mismatch
- The Basic Problem
- Superposition: More Features Than Dimensions
- Code: Demonstrating Superposition
- Superposition and Ghost Features
- Ghost Features
- Interference Patterns
- Code: Visualizing Interference
- Polysemanticity and Context Dependence
- What Is Polysemanticity?
- Context Dependence
- Code: Detecting Polysemanticity
- Sparse Versus Dense Representations
- The Tradeoff
- Activation Sparsity
- Emergent Linear Structure in High Dimensions
- The Linear Representation Hypothesis
- Separability and Geometry
- Summary
Chapter 12: Probing Representations and Testing Hypotheses
- Probe Design and Training
- The Basic Idea
- Probe Types
- Training Details
- Code: Training Linear Probes
- What Probes Can and Cannot Show
- What Probes Show
- What Probes Cannot Show
- Code: Testing Probe Robustness
- Temporal Probe Analysis
- Tracking Representations Across Layers
- Code: Layer-Wise Probing
- Probe Robustness and Confounding
- The Confounding Problem
- Mitigation Strategies
- Code: Controlled Probing
- Probe Case Studies
- Syntax Probing
- Semantic Probing
- Task-Specific Probing
- Summary
Chapter 13: Feature Visualization and Activation Maximization
- Gradient-Based Activation Maximization
- The Basic Idea
- Continuous Relaxation
- Code: Activation Maximization in Embedding Space
- Input Perturbation Methods
- Changing Inputs to Target Activations
- Token Substitution
- Code: Token Substitution for Activation Maximization
- Latent Space Exploration
- Navigating Representation Space
- Feature Visualization via Reconstruction
- Feature Attribution Methods
- Attributing Outputs to Features
- Code: Simple Feature Attribution
- Interpretation and Validation
- How to Judge Visualizations
- Avoiding Artifacts
- Validation Methods
- Summary
Chapter 14: Activation Patching and Logit Attribution
- Mechanistic Interpretation Through Intervention
- The Core Idea
- Necessity and Sufficiency
- Activation Patching: Method and Variants
- The Basic Procedure
- The Logit Difference Metric
- Code: Basic Activation Patching with TransformerLens
- Layer-Level and Head-Level Patching
- Code: Head-Level Patching
- Logit Attribution
- Direct Logit Attribution
- Code: Direct Logit Attribution
- Patching Case Studies
- Understanding Factual Knowledge
- Understanding In-Context Learning
- Summary
Chapter 15: Causal Tracing, Mediation and Circuit Discovery
- Causal Tracing Methodology
- Following Computation Through the Graph
- Attribution Graphs
- Code: Building a Causal Trace
- Causal Mediation Analysis
- Quantifying Information Flow
- Application to Transformers
- Code: Causal Mediation Analysis
- Circuit Discovery Algorithms
- Manual vs. Automated Discovery
- Validation Criteria
- Indirect Object Identification Circuit: A Worked Case Study
- The IOI Task
- The Discovered Circuit
- How It Was Discovered
- Code: IOI Circuit Analysis
- Circuit Validation and Robustness
- Testing Circuit Explanations
- Backup Circuits
- Summary
Chapter 16: Ablation Studies and Interventional Interpretability
- Neuron and Head Ablation
- Zeroing Out Components
- Code: Attention Head Ablation
- MLP Neuron Ablation
- Gradual Versus Sudden Interventions
- Sudden Ablation
- Gradual Intervention
- Code: Gradual Intervention
- Ablation-Based Feature Importance
- Ranking Components
- Code: Component Ranking
- Reconstruction and Substitution
- Building Minimal Mechanisms
- Substitution Experiments
- Ablation Case Studies
- What Ablations Have Revealed
- Summary
Chapter 17: Sparse Autoencoders and Dictionary Learning for Feature Discovery
- Sparse Autoencoders: Motivation and Formulation
- The Problem with Neurons
- The Autoencoder Architecture
- Common Activation Functions
- Code: SAE Architecture
- Training Sparse Autoencoders
- The Loss Function
- Training Procedure
- Key Hyperparameters
- Code: Training an SAE
- Dictionary Learning and Feature Quality
- Evaluating Features
- Feature Interpretation
- Code: Feature Analysis
- Transcoder Architectures
- Alternatives to Standard SAEs
- Choosing an Architecture
- Scale and Generality
- Scaling SAEs
- Generality Across Models
- Limitations
- Summary
Chapter 18: Feature Engineering, Steering and Applied Interpretability
- Steering Vectors
- The Core Idea
- Extracting Steering Vectors
- Code: Difference of Means Steering
- Feature Splitting and Absorption
- How Features Evolve Across Layers
- Code: Tracking Feature Directions
- Model Diffing and Comparative Analysis
- What Changes Between Models?
- Applications
- Interpretability for Safety and Alignment
- Why Interpretability Matters for Safety
- Current State
- Challenges
- The Future of Mechanistic Understanding
- Open Problems
- Emerging Directions
- Summary
