Generative AI
Inside a Transformer Block: An Operational Anatomy
Develop a precise working model of transformer blocks without confusing attention weights with complete explanations.
By the end you can
- Trace token states through attention, feed-forward mixing, residual connections, and normalization
- Explain query, key, and value roles without assigning them human intentions
- Identify how masking and position information constrain interactions
- Recognize why attention maps alone do not establish causal explanation
Visual
A block updates every position through two main transformations
Exact ordering differs across implementations, and the difference is not cosmetic. Where the layer normalization sits decides whether learning-rate warm-up is needed at all. Xiong and nine colleagues showed this in 2020 with a mean-field analysis. Put the normalization after the sublayer — the Post-LN arrangement — and the expected gradients near the output layer are large at initialization. Put it inside the residual block instead and, as they write, “On the other hand, our theory also shows that if the layer normalization is put inside the residual blocks (recently proposed as Pre-LN Transformer), the gradients are well-behaved at initialization.” With Pre-LN the warm-up stage can be removed. The ordering is a documented engineering choice with a measured training consequence, not an implementation detail.
The recurring components keep stable roles whichever ordering is used. A normalization scheme controls scale before or after a sublayer. Attention then routes information: queries score keys and combine the corresponding values under a mask. The sublayer update is added to the incoming representation along the residual path rather than replacing it. A feed-forward network mixes features position-wise using parameters shared across positions. The next block receives states that now contain both local and routed information.
- 1
Normalize or prepare states
A normalization scheme controls scale before or after a sublayer.
- 2
Route information with attention
Queries score keys and combine corresponding values under a mask.
- 3
Add the residual path
The sublayer update is added to the incoming representation.
- 4
Mix features position-wise
A feed-forward network transforms each position using shared parameters.
- 5
Return updated states
The next block receives representations containing local and routed information.
Queries, keys, and values are learned projections
Each token state is projected into query, key, and value vectors. A query-key score determines how strongly one position uses a value from another allowed position. These names describe computational roles. A query vector is not a conscious question, and a key is not a symbolic database key with guaranteed meaning.
The vocabulary is portable enough that the same words have been applied to a different sublayer entirely. The position-wise feed-forward sublayers themselves behave as key-value memories, with their outputs refined across layers through the residual connections. Geva and colleagues argued that in 2021, and their abstract opens: “Feed-forward layers constitute two-thirds of a transformer model's parameters, yet their role in the network remains under-explored.” Two consequences follow. First, "key" and "value" are labels for what a computation does in a given place, not fixed objects with a single meaning across the architecture. Second, if two-thirds of the parameters live in the mixing step, then studying only the routing step means studying the smaller share of the block.
Case
Six layers, eight heads, and three and a half days on eight GPUs
The original configuration is small by current standards. The base Transformer had six layers, a model dimension of 512, a feed-forward inner dimension of 2,048, and eight heads with d_k = d_v = 64. That is 65 million parameters, in the row labelled base of Table 3 of "Attention Is All You Need" (2017). The arithmetic is worth reading twice. 8 × 64 = 512 exactly, so the heads partition the model dimension rather than widening it, while the feed-forward layer is four times that dimension, applied inside each of the 6 layers.
The headline number belongs to a different run. The big model is the one “establishing a new state-of-the-art BLEU score of 28.4” on the WMT 2014 English-to-German task, and the same paper reports “Training took 3.5 days on 8 P100 GPUs.” Base and big are separate configurations, and the paper labels them as such.
Jain and Wallace showed in 2019 that learned attention weights are frequently uncorrelated with gradient-based measures of feature importance, and that very different attention distributions can yield equivalent predictions. The scale changed. The block did not, and neither did the difficulty of reading it.
Figure
Comparison
Masks define which information paths exist
Attention cannot use a position that the mask or architecture makes unavailable. The causal mask is the clearest case, and it is worth seeing how literally it is implemented. The 2017 paper describes it in two sentences: “We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to −∞) all values in the input of the softmax which correspond to illegal connections.” The restriction is arithmetic, not structural. A value of −∞ entering the softmax leaves a weight of zero. It supports autoregressive generation and prevents direct leakage from future target tokens, while leaving all permitted earlier context available. It guarantees nothing about sensible time reasoning.
A padding mask does a different job. Variable-length batches need artificial padding positions excluded from useful attention so that padding does not contaminate states. It depends on correct sequence boundaries, and it does not solve truncation.
A structured mask restricts interactions by role or region, and the best-measured instance is BigBird: local windows, random links and O(1) global tokens, which reduces the quadratic dependency on sequence length to linear. Zaheer and colleagues published it in 2020, and the abstract states: “The proposed sparse attention can handle sequences of length up to 8x of what was previously possible using similar hardware.” That is what a structured mask buys. The cost comes with it: a pattern chosen in advance can block useful evidence if designed poorly, so it requires task-specific evaluation.
Causal mask
A position cannot attend to future target tokens.
- Supports autoregressive generation
- Prevents direct leakage from future outputs
- Still allows all permitted earlier context
- Does not guarantee sensible time reasoning
Padding mask
Artificial padding positions are excluded from useful attention.
- Needed for variable-length batches
- Prevents padding from contaminating states
- Depends on correct sequence boundaries
- Does not solve truncation
Structured mask
The application or architecture restricts interactions by role or region.
- Can encode local windows or document blocks
- May reduce cost or enforce separation
- Can block useful evidence if designed poorly
- Requires task-specific evaluation
Residual paths preserve a route for existing representations
A residual connection adds a sublayer update to its input instead of replacing the state entirely. That helps the optimizer, and it lets later layers refine information while retaining a direct path. The idea did not originate in the Transformer. He and colleagues introduced it for image recognition in 2016: “We explicitly reformulate the layers as learning residual functions with reference to the layer inputs, instead of learning unreferenced functions.” Vaswani et al. cite that paper for the residual connection placed around each sublayer.
The payoff was depth that had not previously been trainable: networks up to 152 layers deep. An ensemble of them reached 3.57% error on the ImageNet test set and won ILSVRC 2015. That is the evidence behind "helps the optimizer" — a specific depth and a specific error rate, not a general reassurance.
Residuals still do not guarantee that every useful feature survives. Scale, normalization, depth, and learned transformations all affect which information remains accessible further up the stack.
Example
What a block-level investigation can reveal
These tools are evidence about what the block computed. None is a complete explanation by itself, and the interventions carry more weight than the pictures.
How much more is measurable. Take a WMT English–French Transformer with 6 layers × 16 heads, that is 96 encoder self-attention heads, and remove heads at test time. Only 8 of the 96 caused a statistically significant change in performance — and half of those changes were a higher BLEU score. Iterative pruning went further: “We observe that this approach allows us to prune up to 20% and 40% of heads from WMT and BERT (respectively), without incurring any noticeable negative impact.” Michel and colleagues ran that experiment in 2019, under the title "Are Sixteen Heads Really Better than One?". A head that looks busy in a heatmap can be one of the ninety-odd whose removal changes nothing measurable.
- Activation statistics: Detect saturation, extreme norms, dead dimensions, or layer-specific drift.
- Attention patterns: Show routed associations under one input, head, layer, and mask — and the 8-of-96 result above is the reason that is a weaker claim than it looks.
- Ablations: Remove heads, tokens, or layers and measure the behavior change. Voita and colleagues did this systematically in 2019, with stochastic gates and an L0 relaxation: “Our novel pruning method removes the vast majority of heads without seriously affecting performance. For example, on the English-Russian WMT dataset, pruning 38 out of 48 encoder heads results in a drop of only 0.15 BLEU.”
- Probes: Test whether a representation contains linearly recoverable information.
- Counterfactual prompts: Change one factor and observe whether outputs follow the intended distinction.
Key idea
Attention is not automatically an explanation
An attention map records one set of routing weights inside a larger computation. Feed-forward layers, residual streams, earlier representations, and later transformations also shape the output. On Geva and colleagues' accounting, the feed-forward sublayers alone hold two-thirds of the parameters that the map does not show.
A visually appealing map can be unstable or causally irrelevant. That is a published finding, not a caution. Jain and Wallace found learned attention weights frequently uncorrelated with gradient-based importance, and very different attention distributions yielding equivalent predictions. Serrano and Smith reached a compatible verdict the same year from a different direction, in a paper titled "Is Attention Interpretable?". They manipulated attention weights inside already-trained text classifiers, and gradient-based rankings often predicted the effect of removing a component better than the attention magnitudes did. Their abstract closes: “We conclude that while attention noisily predicts input components' overall importance to a model, it is by no means a fail-safe indicator.”
Stronger evidence combines perturbation, ablation, alternate methods, and behavior-level tests.
Use attention maps as diagnostic observations, not as complete causal stories.
Analogy
A committee route is not the final decision record
Every member of a committee chooses which notes to read before revising a draft. The reading pattern resembles attention. The revision step resembles feature mixing. A committee member holds a standing view. And an attention head does not. Transformer heads are numerical projections without stable identities or intentions. Their routing weights also interact with residual paths and later layers.
The analogy breaks in one further place, and the pruning results mark it. A committee that lost 38 of its 48 members would notice. The English–Russian encoder lost that many heads for 0.15 BLEU. Membership in the block is not evidence of contribution.
A block routes and transforms information; the whole network and workflow determine behavior.
Steps
Trace one token through a minimal transformer
Use a short sequence so every tensor and mask can be inspected. Five passes are enough. Each one turns a claim from this lesson into something you can read off your own screen.
First, record the tensor shapes: batch, sequence, head, and feature dimensions. On the base configuration of "Attention Is All You Need" those last two are eight heads of 64 inside a model dimension of 512. Checking that 8 × 64 = 512 on your own tensors confirms the heads partition the block rather than widening it. Second, display the mask and verify exactly which positions can interact. Before the softmax the disallowed entries should be the −∞ the original paper describes, and after it, zeros. Third, inspect the attention scores for one head, comparing pre-softmax and normalized values. Fourth, measure the residual updates: compare the norm of each sublayer update with the norm of the incoming state. That is what "adds rather than replaces" looks like numerically. Fifth, perturb one token and test whether routing and output change in a plausible direction. For the stronger version of that test, delete the head entirely and measure the behavior change, the way the pruning experiments did.
1. Record tensor shapes
Write batch, sequence, head, and feature dimensions.
2. Display the mask
Verify exactly which positions can interact.
3. Inspect attention scores
Compare pre-softmax and normalized values for one head.
4. Measure residual updates
Compare update norms with incoming state norms.
5. Perturb one token
Test whether routing and output change in a plausible direction.
Key takeaways
- Attention routes value information according to learned query-key compatibility under a mask, and the mask is arithmetic: the original Transformer sets illegal connections to −∞ in the input of the softmax.
- Query, key, and value are computational roles rather than human-like intentions — Geva and colleagues apply the same key-value vocabulary to the feed-forward sublayers instead.
- Residual paths add updates while preserving a direct route for prior representations; He and colleagues introduced them to train 152 layers, reaching 3.57% error on the ImageNet test set.
- Feed-forward sublayers mix features at each position using shared parameters and hold two-thirds of a transformer's parameters.
- Masks and position information determine which interactions the architecture can express; BigBird's local, random and global pattern takes the length dependency from quadratic to linear and sequences to 8x longer on similar hardware.
- Interpretability requires perturbations and ablations beyond a single visualization: 38 of 48 encoder heads came out for 0.15 BLEU, and only 8 of 96 heads mattered significantly at test time.