A visual lesson
Attention
How tokens share
information.
Start with the running token vectors.
See how context changes what they represent.
Socks and shoes · Train an encoder · Infinite Jest · Predictions and SHAP

Build one attention head
Socks and shoes
Follow every number from input vectors through Q/K matching, values, and a prediction. Then complete the same prediction by updating the residual stream and pooling its rows.
From a constructed solution to a learned one
Now learn the ordering rule.
The notebook replaces socks and shoes with A and B among ten distractor tokens. The target is 1 when A comes before B, and 0 otherwise. Each example is paired with a copy in which A and B swap places.
The challenge is the same: make order survive mean pooling. Even after adding position vectors, those paired sequences have the same average initial representation. The encoder must transform the token vectors so their final averages can differ.
Here we chose the projections and scoring rule. The notebook trains the token and position embeddings, encoder, and classifier together. Its two encoder blocks use four attention heads each, followed by mean pooling and a learned linear classifier.
From token representations to sentiment
Infinite Jest
Apply the same attention operations to two reviews. Follow the representation updates, then inspect a trained classifier’s predictions, word contributions, and internal messages.
The schematic used mean pooling. The trained classifier below instead reads the final token state, after six encoder blocks with twelve attention heads each.
The saved model results could not be loaded. Reload this page to try again; the socks-and-shoes calculation above remains available.
Explore the original reviews.
Inspect any of the 72 heads. The token labels stay fixed; the information at those positions changes across layers.
Evidence, limits, and reproduction
The two-message removal was selected after inspecting this checkpoint. It reverses all five tested short reviews; their full versions remain positive. State swaps after block 4 reverse 15 of 16 new directions. These tests establish particular dependencies, not a universal job for a head or a complete explanation of either original review.
The model also predicts “Bad and Infinite Jest don’t belong in the same sentence” as negative. Two original successes do not establish reliable understanding of every related construction. A message norm measures vector magnitude, not its signed effect on sentiment.
Each layer has its own heads. The value-swap experiment holds all layer-5 attention weights fixed; layer 6 reruns. The earlier mean-pooling schematic is distinct from this checkpoint’s final [CLS] readout.
Exact token Shapley contributions · Reproduce SHAP · Measured interventions and validation cases · All original attention matrices · Reproduce the interventions · Complete reading version.
Model: DistilBERT SST-2, pinned checkpoint. Further reading: Kobayashi et al. (2020), weights and transformed values; Abnar and Zuidema (2020), mixing across layers; Clark et al. (2019), patterns across heads.
Using attention in research
What can we learn from the output?
An attention heatmap describes a particular computation: for one head, in one layer, each destination forms a weighted mixture of source value vectors. A large weight tells us that the source receives a large mixing coefficient. Its effect on a particular classification also depends on the value vector and everything that follows.
The Infinite Jest schematic uses two reviews to motivate sentiment classification. The DistilBERT chapter reports measured predictions and attention weights for those exact reviews. The residual path carries each token’s current vector forward, while attention and the position-wise MLP add updates. A sentiment readout uses the final token representations.
That makes attention useful for investigating the relationships a model has learned. For example, Clark et al. (2019) found BERT heads associated with syntactic relations and coreference. Such patterns can suggest what to inspect or test next. A pattern across token positions and an explanation of a particular sentiment score answer different questions.
Choose the question before the visualization
| Question | Useful display | Interpretation |
|---|---|---|
| Where is information being read? | A named layer, head and destination row of attention | Mixing coefficients for source representations. |
| What adds to this class score? | Signed output terms, when the architecture permits an exact decomposition | Contributions to this computation, including values and the readout. |
| How can we allocate this prediction across words? | Exact token Shapley contributions and their word sums | An additive allocation relative to the specified masked-input baseline. |
| Which words change this prediction? | Replace or remove a word or phrase, rerun the whole model, and compare a fixed class score | Sensitivity to that particular text edit. |
| What caused an outcome outside the model? | An experiment or an identified causal design | A different question that attention weights alone do not answer. |
A useful sentiment exercise
Begin with a fixed target, such as the positive-minus-negative logit margin, and show the original prediction. Start with the Infinite Jest reviews above, then compare “Infinite Jest was good” with “Infinite Jest was not good.” Rerun the classifier on each complete sentence. These further edits are proposed checks; the saved DistilBERT results include the original reviews and the interventions shown above.
Put the chosen attention row beside the score changes and ask whether its highlighted positions help explain them. Inspect negation as a phrase: in a deep transformer, the representation at “good” may already contain information from “not.” Removing a token also changes the context, positions, and potentially every attention row. It does not isolate a unique contribution inherent to that word.
The SHAP calculation above allocates the difference between a masked baseline and the original sentiment margin across input token positions. It averages marginal changes over all token subsets. Its contributions depend on the masking rule; changing the rule changes the attribution problem. Integrated gradients provides another signed attribution relative to a specified baseline. See Sundararajan et al. (2017) and Lundberg and Lee (2017).
From words to marketing touchpoints
LiDDA predicts conversion from a sequence of marketing interactions and uses aggregated, normalized attention to assign relative touchpoint credit. Its single attention layer and flattened readout are deliberate design choices. The paper also reports sensitivity checks, comparison with incremental propensity, MMM calibration, and email experiments. These provide evidence beyond the attention visualization itself. LiDDA v3, §§2.1, 2.4, 2.7, 3.2 and Appendix B.2.
A 40% credit share is a model-based allocation within a path. It is not automatically a 40% change in conversion probability or a 40% causal effect. The Infinite Jest example illustrates the interpretive distinction; it is not a reconstruction of LiDDA.
A technical qualification about LiDDA
The paper describes aggregation across heads and normalization, but does not fully specify how its query-by-source attention tensor reduces to one credit per touchpoint. We therefore leave that query-axis reduction unspecified here.
What to remember about Q, K and V
A query is what a destination is matched on; a key is what each source is matched on; a value is what that source contributes to the mixture. In a trained transformer, these projections are learned from the training task. “Looking for” is an analogy, not a claim that their coordinates have human-readable meanings. The socks-and-shoes calculation makes this matching and mixing explicit; the trained-model experiments test how it affects predictions.
Return to socks and shoesOptional: decoders and causal maskingRead the complete text
Optional extension: decoders and causal masking
A different prediction task
When the next token is unknown.
The encoder classifier could read the whole input. For next-token prediction, each position may use only itself and earlier positions. Revisit socks and shoes to see how a causal mask enforces that restriction.
Keep the two operations in view
Choose where to read.
Choose what to carry.
Queries and keys determine a distribution over source positions. Values determine the information those positions contribute. The output at each destination is a weighted sum of the source values.
When the attention output is used to update a representation, an output map returns it to the input width before addition:
Notation for this lesson
The value projection reads features from each source. The output projection maps their weighted mixtures back to the residual stream’s feature width:
Each row of is a source value vector; each row of is a weighted mixture at a destination. Neither is an outcome label. The update has the same shape as , so it can be added to the residual stream. These schematic equations omit attention biases and normalization.
Tokens are rows of . Query and key maps have shape ; the value map has shape . Thus and . The output map for a representation update is . A subscripted token vector denotes a row throughout.
The full Q/K/V calculation follows one constructed socks-and-shoes head. First, it matches a destination to a source and mixes position values to produce a task score. Then we generalize the scalar query–key calculation, project its output into the residual stream, and recover the same target scores by pooling the updated rows. An optional decoder section later changes the task to next-token prediction with a causal mask. The original classifier has access to both items; its target scores are not claims about the masked calculation. The parameters are chosen to make every step inspectable.
The exact socks-and-shoes model
The target is 0 for socks before shoes and −1 for shoes before socks. Each input row contains a socks indicator, a shoes indicator, and a position value: +1 in the first slot and −1 in the second. This is a constructed model with fixed parameters, not a pretrained language model.
We form by adding token embeddings and position vectors of the same width. Position embeddings can be learned without reserving a coordinate. For this example, we choose fixed vectors: the token embeddings are zero in the third coordinate, and the position vectors are zero in the first two. We follow this one construction through the calculation.
Adding positions does not yet solve the pooling problem: both orders have mean . The rows contain position information, but averaging loses which token occupies which position.
Queries and keys read token identity; values carry position. With , the score matrix is . Shoes assigns 75% to socks and 25% to itself. The socks row is uniform. All weights come from finite softmax scores.
Swapping the token order preserves the identity-based matching rule while changing which position is carried by each token. The mean output changes from +0.25 to −0.25, giving predictions 0 and −1. Removing positional information or using uniform attention gives −0.5 for both orders. This exact solution covers the two sequences shown; it does not demonstrate generalization to arbitrary clothing sequences.
The exact attention weights are not special. Write the socks-first matrix as , with . The values are , so mean pooling gives . Identity-only queries and keys make the reversed attention matrix , where P swaps the two tokens. The position values remain attached to their slots, giving .
Whenever , the shared linear readout recovers 0 and −1. Thus almost every row-stochastic 2×2 pattern can work with a suitable readout. Keeping the original readout gives the exact targets only when . This result concerns the unmasked, identity-based matching rule used here; holding A fixed in slot order instead would give the same output for both sequences.
The exceptional family is : both column sums are one, so the matrix is doubly stochastic and both pooled values are zero. Identity, a pure swap, uniform attention, and balanced selective attention all fail. Identical but biased rows can work: gives pooled values +0.5 and −0.5. Invertibility is therefore not the criterion. Every interior choice of a and b is realizable with one-dimensional identity-only Q/K maps: take query values and key values . Exact zero/one weights are softmax limits.
From a constructed head to a pretrained model
A useful next step is Neel Nanda’s pretrained one-layer attention-only model. Its configuration has eight parallel attention heads and no feed-forward network in the layer. Embeddings, positional information, normalization, and a prediction readout remain. One layer need not mean one head.
The current lesson computes its constructed examples in the browser. It does not display measurements from that checkpoint or GPT-2. Those models can provide a later comparison using actual tokenization, attention weights, and continuation probabilities.
Sources and conventions
The opening distinguishes a token’s shared lookup embedding from its position-dependent input and later contextual representations. The DistilBERT implementation used for the measured chapter adds word and position embeddings, then normalizes them before the transformer blocks. The desert diagrams are conceptual; their routes and sense labels are not measured model outputs.
The primer then separates learned projection matrices from quantities computed for each input. Within a head, determine query–key matching, while transform the content that is mixed and written back. The attention matrix is computed from the current representations, not stored as a free parameter. Training differentiates through this computation to learn the projections and upstream parameters. Parameters remain fixed during inference; attention weights are recomputed. Attention and MLP updates refine the running token vectors across layers; they can also cancel or overwrite features. These diagrams omit normalization and biases.
Goro Kobayashi and colleagues (2020), Attention is Not Only a Weight, motivates examining transformed values as well as attention weights. Samira Abnar and Willem Zuidema (2020), Quantifying Attention Flow in Transformers, explains why repeated mixing complicates attribution to original input tokens.
Ashish Vaswani and colleagues (2017), Attention Is All You Need, §3.2, defines the matching and weighted-value operation. Sarthak Jain and Byron Wallace (2019), Attention is not Explanation, and Sarah Wiegreffe and Yuval Pinter (2019), Attention is not not Explanation, motivate testing an explanation against the architecture and prediction behavior. Their disagreement is useful: attention can be diagnostic without every heatmap being a faithful word-importance explanation.
Nelson Elhage and colleagues (2021), A Mathematical Framework for Transformer Circuits, especially “Attention Heads as Information Movement,” the QK/OV decomposition, and the tensor-product appendix. The distinction between moving information across positions and transforming it within each position motivates this lesson.
Simon J. D. Prince (2023), Understanding Deep Learning, chapter 12, §§12.2–12.3, equations 12.6–12.9. Prince stores tokens as columns. We transpose the convention: projection matrices multiply from the right, attention multiplies from the left, and softmax normalizes each row. The paper’s per-token maps likewise transpose when translated into this convention.
Additional visual reference: Grant Sanderson, Attention in transformers, step-by-step. Its emphasis on what information a destination seeks and how values change a representation informs this sequence. That lesson uses column vectors; this one retains tokens as rows.
The QK and OV products in our row convention
Writing gives scores . Including the output map gives and a head contribution . These product orders differ from the column-vector definitions in the Transformer Circuits paper; they express the same operations after transposition.
Several heads can perform different mixtures in parallel. With their output maps included, their contributions add: . Each head follows the mechanism shown here.
From an attention output to a representation update
The socks-and-shoes task reads its score directly from . To complete the same task through the residual stream, choose . This maps each scalar output into three features before adding it to the original input row.
For socks first, the shoes row changes from to . The updated coordinates need no longer have the meanings of the original input features. This socks-and-shoes illustration covers the attention contribution and residual addition. The main opening also shows the MLP update and sentence readout.
Mean pooling the updated rows gives : for socks first and for shoes first. The shared readout produces 0 and −1. It matches the earlier readout from U because the original third coordinate averages to zero.