Deep architectures
Attention as Content-Based Routing
Derive the query–key–value view of attention and evaluate its routing behavior, normalization, masking, heads, and interpretability limits.
By the end you can
- Explain query, key, value, score, normalization, and weighted aggregation
- Distinguish self-attention, cross-attention, and masked attention
- Explain the purpose of scaling and multiple heads
- Diagnose attention collapse, diffuse routing, leakage through masks, and misleading visualizations
Analogy
A request matched against an indexed archive
A reader submits a request to an archive. The request is a query, index cards are keys, and the documents retrieved from matching cards provide the values. Queries decide what is sought; keys advertise relevance; values carry the information that is combined. Matching an index card is a discrete yes or no. Neural matching is continuous, learned, and usually blends many values. The lookup criterion and the returned content are two different learned projections.
The archive was not built as a metaphor. Translation models used to squeeze a whole source sentence into one fixed-length vector. Content-based attention was invented to remove that bottleneck. Bahdanau and two co-authors put the fix in one sentence in 2015: “Each time the proposed model generates a word in a translation, it (soft-)searches for a set of positions in a source sentence where the most relevant information is concentrated.” That is the routing claim entire. One query per output position, issued against every source position at once.
The table in that paper says what the change was worth. On the WMT'14 English-to-French test set — news-test-2014, 3,003 sentences — the model that searches, RNNsearch-50, reached 26.75 BLEU over all sentences. The model with the single summary vector, RNNencdec-50, reached 17.82. On sentences containing no unknown words, RNNsearch-50* reached 36.15 against 35.63 for Moses, the phrase-based system of the day. The single-summary interface was not merely inelegant. It cost roughly nine BLEU on the same data.
Three researchers at Stanford reproduced the effect the following year. They report “a significant gain of 5.0 BLEU points over the non-attentional baseline, which already includes known techniques such as source reversing and dropout”, and a new state of the art of 25.9 BLEU on WMT'15 English–German. Two labs, two language pairs, the same direction.
Routing earned its place by measurement: 17.82 BLEU for the single-summary interface against 26.75 for the one that searches.
Visual
The attention computation
Five stages. Each one has a distinct failure mode, and each of those failures is documented somewhere in the literature this lesson quotes.
First, project queries, keys and values: map representations into separate spaces for matching and for content transfer. Second, compute compatibility scores: compare each query with the keys it is permitted to see. Third, apply scale and mask: control numeric magnitude and disallow illegal connections. The Transformer paper argues for the scale factor. The mask is where PyTorch and Hugging Face disagree about what True means. Fourth, normalize: convert scores into a distribution-like weighting, commonly with softmax. This is the step that can saturate onto one position — over half of BERT's attention in layers 6–10 lands on a single delimiter. Fifth, aggregate values: produce a content-dependent mixture for each query. This is where weight and effect come apart. A position can take most of the weight and still change almost nothing downstream.
- 1
Project queries, keys, and values
Map representations into spaces for matching and content transfer.
- 2
Compute compatibility scores
Compare each query with permitted keys.
- 3
Apply scale and mask
Control numeric magnitude and disallow illegal connections.
- 4
Normalize weights
Convert scores into a distribution-like weighting, commonly with softmax.
- 5
Aggregate values
Produce a content-dependent mixture for each query.
Comparison
Three attention modes
The source of queries and keys determines the architectural role.
Self-attention draws queries, keys and values from one representation set. It mixes information within a sequence or set, can be causal or bidirectional, needs position or structure information, and produces contextual token encodings.
Cross-attention draws queries from one stream and keys or values from another. It is not an abstraction. It is the conditioning interface in a deployed text-to-image system. Latent diffusion was built that way in 2022, and the paper says so plainly: “We turn DMs into more flexible conditional image generators by augmenting their underlying UNet backbone with the cross-attention mechanism”. Q comes from the image latent, K and V from the prompt encoder. The queries are pixels asking what they should become. The keys and values are the words.
That interface was then probed causally rather than admired. Six authors at Google, in the same August, wrote that “we analyze a text-conditioned model in depth and observe that the cross-attention layers are the key to controlling the relation between the spatial layout of the image to each word in the prompt”. Their method, prompt-to-prompt, edits an image by swapping the attention maps and changing nothing else. An intervention, not a visualization.
Neighborhood attention lets queries attend only to selected local or graph-connected elements. It reduces cost and encodes locality or topology, but may miss distant evidence. Shifted windows and graph neighbors are the usual instances.
Self-attention
Queries, keys, and values come from one representation set.
- Mixes information within a sequence or set
- Can be causal or bidirectional
- Needs position or structure information
- Example: contextual token encoding
Cross-attention
Queries come from one stream and keys or values from another.
- Conditions a decoder on an encoder
- Supports multimodal fusion
- Requires interface alignment
- Example: text-guided image denoising
Neighborhood attention
Queries attend only to selected local or graph-connected elements.
- Reduces cost
- Encodes locality or topology
- May miss distant evidence
- Example: shifted windows or graph neighbors
Why dot-product scores are scaled
As key dimension grows, unscaled dot products can have larger variance. Softmax may then become extremely peaked, which leaves small gradients for most alternatives.
The divisor is not a convention someone tuned. The Transformer paper gave the reasoning in 2017: “we suspect that for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients. To counteract this effect, we scale the dot products by 1/√dk”. A footnote supplies the whole argument in two sentences: “assume that the components of q and k are independent random variables with mean 0 and variance 1. Then their dot product … has mean 0 and variance dk”.
So the divisor tracks the width by construction. Under those assumptions the standard deviation of an unscaled logit is the square root of the key dimension: 8 at the paper's own dk of 64, and 22.63 if a single head ran at the full model width of 512. Dividing by the square root of the key dimension flattens that curve to 1 at every width. It is a design rationale resting on stated assumptions. It is not a promise that every head stays well behaved.
Figure
Scaled scores protect optimization from a predictable dimension-dependent magnitude effect.
Example
What unhealthy routing can look like
Attention statistics are useful when they are tied to task behavior. The best-documented failure is not hypothetical, and it is a whole model measured head by head. Clark and three co-authors went through all 144 attention heads of BERT-base, 12 layers by 12 heads, and reported this: “For example, over half of BERT’s attention in layers 6-10 focuses on [SEP].” Chance would be about 1/64 for a token occurring twice in a 128-token segment. The second half of the finding is what makes it sharp. The gradient of the loss with respect to that attention goes small from layer 5 onward. The routing that dominates the picture does almost nothing to the output.
An independent group reached the same place. They found the “vertical” attention pattern “is associated predominantly, if not exclusively, with attention to [CLS] and [SEP] tokens”. Disabling single heads raised accuracy by up to 1.2% absolute on MRPC. Disabling a whole layer raised it by 3.2% on RTE. Switching the collapsed routing off made the model better.
- Uniform weights: the head may be unable to distinguish relevant positions, or the task may genuinely require broad averaging.
- Single-position collapse: over half of BERT's attention in layers 6–10 lands on the [SEP] delimiter, against a chance baseline of about 1/64 — the shortcut token, border patch or special marker absorbs the row.
- Redundant heads: 38 of 48 encoder heads were pruned on English–Russian WMT for a 0.15 BLEU drop; capacity deletable that cheaply was adding little.
- Mask leakage: a causal or padding mask applied with the wrong orientation or broadcast shape — a live risk when scaled_dot_product_attention and MultiheadAttention read True in opposite directions inside one library.
- Value bottleneck: correct positions receive weight but value projections fail to carry the needed information. The [SEP] heads show the converse — weight with no effect, the loss gradient through that attention going small from layer 5 onward.
Key idea
Attention is a routing mechanism, not a complete explanation
A high weight shows that one value contributes strongly through that head under the current representation. It does not measure every path through residual streams, feed-forward layers, or later computation.
This is a documented dispute with published tests on both sides, not an editorial caution. Jain and Wallace put the case against in 2019: “For example, learned attention weights are frequently uncorrelated with gradient-based measures of feature importance, and one can identify very different attention distributions that nonetheless yield equivalent predictions.” Two different routes, the same prediction.
The reply came the same year, with four alternative tests: a uniform-weights baseline, a variance calibration over random seeds, a frozen-weights diagnostic, and an end-to-end adversarial training protocol. Wiegreffe and Pinter concluded that “prior work does not disprove the usefulness of attention mechanisms for explainability”. What remains unresolved is what counts as a faithfulness test. That is why claims need interventions — value replacement, edge removal, counterfactual inputs, or comparison with gradient and causal methods. Prompt-to-prompt is the constructive form of the same move: swap the cross-attention maps and see whether the image follows.
Visualizing a route is not the same as proving why the final decision changed.
Steps
Test attention masks with tiny deterministic cases
Mask errors can produce plausible losses while violating causality or padding rules. They survive review because the conventions genuinely disagree with each other. PyTorch says so in its own reference note: “In scaled_dot_product_attention(), True indicates values to participate in attention. In MultiheadAttention, True indicates values to be masked out (padding).” Same library, opposite polarity. The note then instructs “If migrating from MHA, ensure you invert your boolean mask”. A third convention sits on top of those two. The Hugging Face Transformers glossary documents the keep-polarity, where (for the BertTokenizer) “1 indicates a value that should be attended to, while 0 indicates a padded value” — the same orientation as scaled_dot_product_attention, and therefore inverted relative to MultiheadAttention.
The test that catches this costs a minute. Use a four-element sequence, so that every permitted and forbidden connection can be enumerated by hand. Set distinctive values, chosen so the output reveals exactly which positions were aggregated. Verify each query row separately for causal direction, padding, and batch broadcasting. This is the step where an inverted boolean shows up as a row that saw the future. Test mixed lengths, to confirm that one example's padding cannot affect another. Then repeat in reduced precision, so that masked scores stay numerically safe at deployment precision.
1. Use a four-element sequence
Make every permitted and forbidden connection easy to enumerate.
2. Set distinctive values
Assign values that reveal exactly which positions were aggregated.
3. Verify each query row
Check causal direction, padding, and batch broadcasting separately.
4. Test mixed lengths
Confirm that one example’s padding cannot affect another.
5. Repeat in reduced precision
Ensure masked scores remain numerically safe under deployment precision.
Multiple heads create multiple routing subspaces
Each head uses its own projections, allowing different compatibility patterns and value channels. Heads can specialize by position, relation, scale, or feature type, but specialization is not guaranteed. More heads also shrink per-head dimension when total width is fixed.
The Transformer's own configuration states the trade: “in this work we employ h = 8 parallel attention layers, or heads. For each of these we use dk = dv = dmodel/h = 64. Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.”
Whether all eight earn their keep was then measured twice, by two groups, with the same answer. Voita and four co-authors report: “For example, on the English-Russian WMT dataset, pruning 38 out of 48 encoder heads results in a drop of only 0.15 BLEU.” A second group observes that “a large proportion of attention heads can be removed at test time without significantly impacting performance, and that some layers can even be reduced to a single head”. In their WMT Transformer, “only 8 (out of 96) heads cause a statistically significant change in performance when they are removed from the model, half of which actually result in a higher BLEU score”.
The asymmetry is the part worth carrying away. That same work finds that reducing the last encoder–decoder attention layer to a single head degrades performance “by at least 13.5 BLEU points”. Self-attention heads are largely fungible after training. The heads that carry conditioning from another stream are not. So ablate head count alongside width, latency, and observed diversity. Run the ablation separately for each attention mode.
Multi-head attention offers parallel routing hypotheses, not a fixed catalog of semantic roles.
Key takeaways
- Attention performs content-dependent routing by matching queries with keys and aggregating values; it was introduced to move WMT'14 English-to-French from 17.82 to 26.75 BLEU.
- Self-attention mixes one representation set, while cross-attention conditions one stream on another — in latent diffusion the queries come from the image latent and the keys and values from the prompt encoder.
- Masks are architectural constraints and must be verified with deterministic unit tests: PyTorch's own documentation gives True opposite meanings in scaled_dot_product_attention and MultiheadAttention.
- Score scaling addresses a predictable dimension-related optimization problem: with components of mean 0 and variance 1 the dot product has variance dk, a standard deviation of 8 at the paper's dk of 64.
- Heads are not uniformly load-bearing — 38 of 48 encoder heads pruned for 0.15 BLEU, only 8 of 96 significant — yet encoder–decoder attention loses at least 13.5 BLEU when reduced to one head.
- Attention weights expose one route and remain a contested explanation: one team found them frequently uncorrelated with gradient-based importance, and another answered with four alternative tests.