19.2 Logit Lens & Attention Visualization
Two intermediate states both read out Paris as their top token. The largest entry matches, but the rest of the readout can still change. In the worked example below, the top token stays the same while its probability falls from about 67.52% to 54.05%.
A logit lens applies a model’s output decoder to an intermediate residual state. An attention view shows weights between token positions. Both help locate a question worth investigating; neither is a direct transcript of a model’s thoughts.
1. What a Logit Lens Actually Computes
For a decoder-only model with a linear vocabulary head and no additional logit transformation, let be the residual state after block , before the model’s final normalization, at input position . A direct readout is
Here is hidden width, is the output matrix for vocabulary size , and is its bias, or zero when absent. Softmax runs over the vocabulary. The state at position reads out a prediction for position , not a label for the input token at .
Use the model’s actual final normalization, such as LayerNorm or RMSNorm, with its learned parameters. An activation interface may already return the last state after normalization; applying the norm again changes the procedure. If the architecture applies further logit scaling or soft-capping, reproduce those operations as part of the readout. At the final block, a correctly extracted readout using the complete output path should agree with the ordinary model logits within numerical tolerance. At an earlier block, it is a diagnostic projection that skips the remaining computation.
nostalgebraist’s original post introduced this lens for inspecting intermediate GPT representations [1]. The path below makes each operation explicit.
- Select a residual stateRecord block l output hₗ,ₜ at the same token position t.
- Apply final normalizationUse the model’s actual final norm. Do not normalize an already normalized state twice.
- Apply the fixed output headzₗ,ₜ = Wᵤ Norm(hₗ,ₜ) + bᵤ. Use bᵤ = 0 when the model has no output bias.
- Softmax over the vocabularyRead out a distribution for token t+1. This does not execute the remaining blocks.
2. Compute a Small Readout Yourself
The interactive example uses three authored vectors, one fixed output matrix and a four-token vocabulary. It contains no trained model. Compare states B and C with normalization enabled, then disable normalization and see which numbers change. The bars show all four probabilities, not a renormalized top-four subset of a larger vocabulary.
Same top token, different distribution
Computed from three authored states and a fixed output matrix. These are not model layers; the four tokens are the entire toy vocabulary.
- Raw state h
- [1.5, 0.3, -0.3]
- Normalized state
- [1.667, 0.333, -0.333]
Top token: Paris · 67.52%
Inspect output matrix and current logits
| Token | Wᵤ[i, :] | Logit |
|---|---|---|
| Paris | [1, 0, 0] | 1.667 |
| London | [0, 1, 0] | 0.333 |
| city | [0, 0, 1] | -0.333 |
| other | [-0.5, -0.5, -0.5] | -0.833 |
B and C both select Paris, but normalized probabilities are about 67.52% and 54.05%. These values do not measure factual correctness or confidence in a real model. Bypassing normalization changes the measurement procedure.
Deliberately simplified, CPU-smoke-tested readout. Python/PyTorch code below uses FP64, three fixed states and a fixed output head. RMS normalization has unit gain, zero output bias and epsilon . This is not model extraction or training: it omits tokenization, attention blocks, learned normalization parameters, hooks, batching/padding, model weights and causal validation of a real checkpoint.
import torch
states = torch.tensor([
[0.6, 1.2, -0.6], # A
[1.5, 0.3, -0.3], # B
[1.2, 0.6, 0.3], # C
], dtype=torch.float64)
tokens = ["Paris", "London", "city", "other"]
output_head = torch.tensor([
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[-0.5, -0.5, -0.5],
], dtype=torch.float64)
normalized = states / (states.square().mean(-1, keepdim=True) + 1e-5).sqrt()
logits = normalized @ output_head.T # [3 states, 4 vocabulary entries]
probabilities = logits.softmax(-1)
assert torch.allclose(probabilities.sum(-1), torch.ones(3, dtype=torch.float64))
assert probabilities.argmax(-1).tolist() == [1, 0, 0]
assert not torch.allclose(probabilities[1], probabilities[2])
for name, row in zip("ABC", probabilities):
top = row.argmax().item()
print(name, tokens[top], round(100 * row[top].item(), 2))
# A London 57.71; B Paris 67.52; C Paris 54.05
The calculation demonstrates a counterexample to “same argmax means same distribution.” It does not demonstrate that real layers follow A → B → C, or that a probability assigned to Paris is calibrated factual confidence. Intermediate predictions can reverse, remain uninformative or inherit a mistaken final answer.
3. Extract the Right Tensor Before Interpreting It
For a real checkpoint, record the prompt/template and token IDs, token position, block index, pre/post-normalization location, dtype and output head. “Layer 20 activation” is insufficient: a block input, attention output and post-block residual are different tensors. At a fixed position, compare complete readouts under the same extraction convention.
When using hooks, inspect the actual module contract. Some blocks return a tensor, others a tuple. Taking [0] from a tensor removes its batch dimension; taking it from a tuple may select the intended tensor. Remove hooks after the run, including on exceptions. Inference without gradients avoids retaining an autograd graph, but storing detached states still consumes memory.
For an authored FP32 budget with 32 captured states, batch one, 512 positions, width 4,096 and vocabulary 50,000:
| Retained object | Calculation | Payload |
|---|---|---|
| All residual states | bytes | 256 MiB |
| All full-vocabulary readouts | bytes | About 3.05 GiB |
| Readouts at one selected position | bytes | About 6.10 MiB |
These are separate allocations, excluding weights, forward activations, temporaries and allocator reserve. If only the final prompt position is relevant, extract and project that position rather than retaining all logits. Streaming states can further reduce retention, but hook timing, model placement and available memory still require an implementation-specific check.
Use a small fixture to verify that the final-block readout, including any model-specific post-head transformations, matches normal forward logits and that positions predict the intended next tokens. Then compare several prompts and counterfactual evidence. Do not infer that a readout failure means the state contains no relevant information: the decoder itself may be poorly matched to that state.
4. The Tuned Lens Changes the Decoder
The final output head need not decode intermediate states reliably. Retaining the simplified linear-head convention above, Belrose et al. train a layer-specific affine translator before the frozen final decoder [2]:
Here and are learned translator parameters. The training target is the frozen model’s final distribution , using , rather than the ground-truth next token. Its targets therefore include the base model’s errors.
A tuned lens can improve the readout while leaving the base model unchanged. Predictive agreement alone does not establish the causal role of an activation; the paper’s causal experiments ask a separate question. For a reproducible fitted lens, retain the base-model identity, activation location, translator parameters, training-data split and objective configuration, and evaluate on held-out prompts. Do not compare different lenses as if only the underlying model changed.
5. Attention Weights Need Values and Outputs
BertViz’s neuron, head and model views expose different parts of attention [3]. A neuron view inspects query/key components, a head view shows weights between positions, and a model view compares heads and layers. Label query versus key axes, the selected layer/head, and causal or padding masks. Token positions on both sides are not separate generated input/output sentences.
For one query and two available keys, consider the following authored scalar-value example. The single-head output before any output projection is .
| Case | Attention weights | Values | Weighted contributions | Output |
|---|---|---|---|---|
| A | 1.009 | |||
| B | 9.001 |
The heatmap is identical, but the outputs differ. In case A, the smaller attention weight multiplies the much larger value and contributes more. Real heads add vector directions and an output projection, and other components can reinforce or cancel those contributions.
Jain and Wallace report cases where attention weights are poor explanations in the studied NLP models [4]. That is evidence against treating a weight map as a complete causal attribution, not a theorem that attention is always useless. High BOS attention can suggest an attention-sink hypothesis; inspect value/output contributions and controlled interventions before concluding that the head is unimportant or harmless.
6. Turn a Picture into an Experiment
For a suspicious RAG answer, hold the checkpoint, prompt format, extraction location and readout fixed. Change one source fact, remove one evidence passage, or patch a candidate activation, and measure the effect on the final answer and relevant control cases. An intervention can create an out-of-distribution state, so compare plausible controls rather than treating every output change as proof of a natural mechanism.
For early exit, evaluate the complete stopping policy: task quality, calibration, selective risk, critical slices, latency and cost. Stable top tokens can be wrong. Keep a tested full-depth route and revert if the policy fails its predeclared release gates.
The next section, 19.3 Probing Classifiers, asks whether a specified property is decodable from a state. A successful probe is another measurement; it also needs a separate argument before becoming a causal explanation.
Quizzes
Quiz 1: What can you not infer from states B and C having the same top token?
They share an argmax but have different complete probability distributions. An argmax discards probability and representation changes. This counterexample does not itself prove that any real later layer is useful; that requires a task-level intervention or early-exit evaluation.
Quiz 2: A hidden-state API already returns the final normalized state. Should the lens apply the final norm again?
No. Extract the agreed residual location or bypass the extra norm for an already normalized state. Verify the final readout against ordinary model logits within a suitable numerical tolerance before interpreting intermediate readouts.
Quiz 3: Why does retaining full-vocabulary logits cost more than the residual states in the worked memory budget?
Each residual has width 4,096, while each readout has 50,000 vocabulary entries. The 32 × 512 FP32 readouts use about 3.05 GiB, compared with 256 MiB for residual states. Selecting one token position reduces retained readouts to about 6.10 MiB, without accounting for other runtime allocations.
Quiz 4: Does a tuned lens learn ground truth by matching the final distribution?
No. It learns to predict the frozen base model’s distribution, including its mistakes. Agreement measures decoding performance under that objective, not factual correctness or causal fidelity by itself.
Quiz 5: Why does the key with weight 0.1 contribute more in attention case A?
Its scalar value is 10, so its contribution is 1. The other contribution is 0.9 × 0.01 = 0.009. Weights without values and output processing cannot establish total contribution; the authored example is not a measurement of a real head.
References
- nostalgebraist. (2020). interpreting GPT: the logit lens. Original post.
- Belrose, N., et al. (2023; revised 2025). Eliciting Latent Predictions from Transformers with the Tuned Lens. arXiv:2303.08112v6.
- Vig, J. (2019). A Multiscale Visualization of Attention in the Transformer Model. arXiv:1906.05714.
- Jain, S., & Wallace, B. C. (2019). Attention is not Explanation. arXiv:1902.10186.