Overview

10 Exploring the transformer black box

This chapter opens the transformer black box by showing how to inspect internal activations instead of treating a model as a single opaque block. It explains that a Transformer layer is made of accessible submodules, especially the attention and MLP components, and that PyTorch hooks can be attached to these parts to record what happens during a forward pass. The chapter’s goal is not just to collect numbers, but to turn them into useful views of how information moves through the network and how the model gradually forms a response.

The core practical contribution is a reusable activation-capture pipeline built around hooks, cleanup routines, and prompt execution. The text shows how to register output hooks for most capture points and a pre-hook for inputs such as the MLP down projection, then use those captured tensors to build interpretable heatmaps. One view fixes a layer and shows which tokens activate which neurons, while another averages over tokens and tracks how activation patterns change across depth. A third visualization examines the GLU mechanism by comparing the gate activation, the up projection, and the input to the down projection, revealing that the multiplicative interaction filters and compresses information rather than simply amplifying it.

The chapter then shifts from activations to prediction itself through the logit lens, which projects intermediate hidden states through the final normalization and language-model head to see how candidate tokens emerge layer by layer. Early layers produce noisy or incoherent guesses, middle layers begin to stabilize around semantically relevant options, and the final layers crystallize the response into a coherent prediction. The closing discussion places these lightweight interpretability tools in a broader research context, contrasting them with more expensive approaches like sparse autoencoders and the tuned lens, and emphasizing that the methods presented here are practical, model-agnostic starting points for analyzing and eventually modifying model behavior.

Token × neuron activation heatmap for act_fn_layer_12 on the prompt "The cat sleeps". Each row is a token, each column is a bin of 256 neurons averaged together. Activation intensity varies visibly across tokens: "cat" shows consistently stronger responses across most neuron bins, while "The" and "sleeps" remain more uniform. The BOS token has been excluded from the visualization.
Token × neuron activation heatmap for act_fn_layer_12 on the prompt "The cat sleeps". Each row is a token, each column is a bin of 256 neurons averaged together. Activation intensity varies visibly across tokens: "cat" shows consistently stronger responses across most neuron bins, while "The" and "sleeps" remain more uniform. The BOS token has been excluded from the visualization.
Layer × neuron heatmap for act_fn on the prompt "The cat sleeps", averaged over tokens. Each row is a transformer layer, each column a bin of 256 neurons. The BOS token has been excluded before averaging.
Layer × neuron heatmap for act_fn on the prompt "The cat sleeps", averaged over tokens. Each row is a transformer layer, each column a bin of 256 neurons. The BOS token has been excluded before averaging.
GLU three-panel visualization for layer 14 on the prompt "The cat sleeps". From left to right: act_fn (SiLU(gate)), up_proj, and down_proj_input (SiLU(gate) × up). Each panel shares the same token axis but has its own independent color scale. The BOS token has been excluded.
GLU three-panel visualization for layer 14 on the prompt "The cat sleeps". From left to right: act_fn (SiLU(gate)), up_proj, and down_proj_input (SiLU(gate) × up). Each panel shares the same token axis but has its own independent color scale. The BOS token has been excluded.
Logit lens top-three tokens per layer for the prompt "The most significant building in Barcelona is the". Each cell shows the top-three predicted tokens and their probabilities for one layer, projected through the model's final normalization and lm_head. Background intensity encodes the top-1 probability, with darker cells indicating higher confidence.
Logit lens top-three tokens per layer for the prompt "The most significant building in Barcelona is the". Each cell shows the top-three predicted tokens and their probabilities for one layer, projected through the model's final normalization and lm_head. Background intensity encodes the top-1 probability, with darker cells indicating higher confidence.

Summary

  • PyTorch hooks let you capture a model's internal activations by attaching to the input or output of any submodule via forward hooks and forward pre-hooks.
  • The internal structure of a Transformer block is hierarchical and can be explored separately. Although submodule names vary between model families (self_attn versus linear_attn, for example), the MLP module keeps the same structure in Llama, Gemma, and Qwen, which lets you apply the same capture techniques consistently.
  • Activation heatmaps and grouping neurons into bins turn tensors of thousands of values into a manageable visual representation.
  • The GLU mechanism can be observed in action on real activations. Visualizing its three components side by side shows that the multiplication between act_fn and up_proj does not amplify the signal, it filters and selects it.
  • The logit lens technique extracts hidden states from intermediate layers and projects them through the final normalization and the prediction head. It lets you visualize how the model builds its output layer by layer.
  • Direct activation interpretability offers a viable alternative for resource-constrained environments compared to computationally expensive methods like sparse autoencoders.

FAQ

What is the main goal of exploring the transformer black box in this chapter?The chapter aims to open up the Transformer’s internal computation by capturing activations and visualizing them, so you can see how information flows through the model and how its decisions are formed layer by layer.
Which model components can be used as hook points for capturing activations?Any visible submodule can potentially be hooked, including the attention module, the MLP module, normalization layers, and internal projection layers such as gate_proj, up_proj, and down_proj.
Why does the chapter capture down_proj with a forward pre-hook instead of a forward hook?Because the goal is to inspect the expanded MLP representation before it is compressed back to the model’s hidden size. A forward pre-hook captures the input to down_proj, while a forward hook would capture its output after compression.
Why is the BOS token excluded from activation heatmaps?The BOS token often behaves like an attention sink and can produce unusually large activations that do not add useful semantic information. Excluding it prevents it from distorting the color scale and obscuring patterns in the rest of the prompt.
What does a token × neuron heatmap show?It shows how strongly each token activates groups of neurons within a chosen layer. Each row corresponds to a token, and each column represents a bin of neurons, making it easier to spot activation patterns across the prompt.
What does a layer × neuron heatmap tell us that a token × neuron heatmap does not?A layer × neuron heatmap shows how activation patterns change across depth by averaging over tokens. This reveals where in the network the model’s behavior becomes stronger, more stable, or more output-focused.
How does the GLU three-panel visualization help explain the MLP mechanism?It shows act_fn, up_proj, and down_proj_input side by side on the same prompt and layer. This makes it easier to see how the gated activation and the up projection interact through multiplication before the result enters down_proj.
What is the purpose of the logit lens?The logit lens projects each intermediate hidden state through the model’s final normalization and output head to reveal which tokens the model is leaning toward at each layer. It helps trace how the final answer gradually takes shape.
Why does the chapter use output_hidden_states=True for the logit lens instead of hooks?Because Hugging Face already provides all hidden states directly in the model output, so no hook registration is needed. This makes the logit lens simpler to implement than activation capture via hooks.
What general pattern does the logit lens reveal across layers in a decoder-only model?It typically shows an early phase of noisy or incoherent token predictions, followed by progressively more meaningful intermediate representations, and finally a sharp convergence toward a coherent answer in the last layers.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Rearchitecting LLMs Rearchitecting LLMs ebook for free