Chapter 03
Inside a Transformer Decoder
On this page
A transformer converts each token into a vector, lets that vector read earlier positions, and transforms the result through repeated layers. Tracing one layer explains both the model's use of context and the work a server must perform.
Begin with shapes¶
Let a prompt contain S tokens. An embedding lookup maps each token ID to a vector of width D, producing a matrix X of shape [S,D]. Each row describes one token position; each column is a learned feature coordinate. The coordinates are not predefined grammatical or application fields. Their use is learned during training.
A decoder repeats a stack of layers that preserve this outer shape. At the end, an output projection maps each row to vocabulary logits. The final prompt position supplies the distribution for the first generated token. During teacher-forced training, the earlier rows also supply their next-token predictions.
The original transformer paper establishes the attention construction. We will use a pre-normalized decoder variant common in language modeling. Architecture details vary, but we can understand this variant by following two operations: attention mixes information between positions; a feed-forward network transforms information within each position.
One decoder layer. Each sublayer produces a vector of width D, which is added back to its input through a residual connection.
Why the layer adds rather than replaces¶
Write the attention sublayer and feed-forward sublayer as:
The first residual addition incorporates information read from other positions.
The second residual addition incorporates a position-wise transformation.
The additions preserve a direct path through the stack. Each sublayer learns a change to the current representation instead of being its only route forward. Normalization controls the scale presented to that sublayer. Neither mechanism guarantees stable training on its own, but they make the computation and its gradients easier to manage as depth grows.
For example, RMS normalization divides a token vector by its root-mean-square magnitude, then applies learned gains. Ignoring the small stabilizing epsilon and taking unit gains, [3,4] is divided by sqrt((9+16)/2), giving approximately [0.849,1.131]. The reduction runs across channels within one token, not across unrelated requests. RMSNorm describes the method and its evaluated comparison with LayerNorm.
Queries, keys, and values¶
Attention gives each position a way to read information from eligible positions. Learned linear projections produce three vectors per head. The query describes what the reading position seeks; keys are compared with that query; values are the vectors combined using the resulting weights. These names explain the computation, not a guarantee that a head implements a human-readable retrieval rule.
For one head of width d, dot products between queries and keys form a score matrix. Dividing by sqrt(d) controls the scale of these scores. The causal mask adds negative infinity to future positions, and softmax normalizes across the remaining keys:
Softmax operates across eligible key positions for each query; M excludes forbidden positions.
The output at one position is a weighted sum of eligible value vectors.
For S positions, Q, K, and V each have S rows. The attention matrix has shape [S,S]. A row describes one query's distribution over key positions. It does not normalize across different heads or across different users in a batch.
The scale factor has a numerical motivation. If query and key coordinates are independent, zero-mean, and unit-variance, their width-d dot product has variance d. Dividing by sqrt(d) restores variance one under those assumptions. Learned coordinates need not satisfy that model exactly, but the calculation explains why unscaled scores can grow with head width and saturate softmax. Head width, normalization, and logit scale should therefore be checked together.
Calculate one row¶
Use a one-dimensional head, so sqrt(d)=1. Let the query be [1], the keys [[0],[log(3)],[100]], and the values [[2],[6],[999]]. Suppose the third key is a future position and must be masked.
The visible scores are zero and log(3). Their exponentials are 1 and 3, so their normalized weights are one quarter and three quarters. The output is (1/4)*2 + (3/4)*6 = 5. The enormous future score has no effect because masking happens before normalization. Setting its output weight to zero afterward would leave the earlier weights incorrectly normalized.
Example status: Runnable excerpt; execute from the repository root.
from math import log
from examples.attention import attention
q = [1.0]
keys = [[0.0], [log(3.0)], [100.0]]
values = [[2.0], [6.0], [999.0]]
visible = [True, True, False]
out = attention(q, keys, values, visible, shard_size=1)
assert abs(out[0] - 5.0) < 1e-12
The reference also supports partitioning the keys and combining partial results; Part IV explains why that is useful for memory-efficient execution. An all-masked row has no ordinary softmax distribution. The reference returns zero by convention. A model integration must specify its own compatible policy rather than relying on undefined division.
Multiple heads and positional information¶
One attention head returns one weighted combination. Multiple heads use separate query/key projections and can form different combinations at the same position. In standard multi-head attention with H heads, each head has width d=D/H. Their outputs concatenate back to width D and pass through an output projection before the residual addition.
With batch size B, a common representation is [B,H,S,d]. These axes have different meanings. Mixing the batch axis into attention would let one request read another request's data. A correct reshape must preserve which positions belong to each sequence.
We also need a way to represent position. The causal mask determines which positions are visible, but an explicit position mechanism gives the model additional information about location or distance. Rotary position embeddings, or RoPE, rotate pairs of query/key coordinates by position-dependent angles. For rotations R(a) and R(b), R(a)^T R(b)=R(b-a), so their dot product contains relative-angle information. RoFormer develops this mechanism. The pairing convention and frequencies are part of the model; changing them is not just changing a cache limit.
Extending a configured maximum sequence length does not establish useful long-context behavior. The model must still locate evidence, combine it, and follow instructions at those lengths. Chapter 7 will separate this quality question from the memory question.
The feed-forward transformation¶
After attention, each position passes through the same feed-forward network, independently of other positions at that sublayer. A common gated form uses two projections to width F, multiplies their outputs after a nonlinearity, and projects back to D:
W_g and W_u expand D to F; W_d returns F to D. Multiplication is elementwise.
Here SiLU(z)=z/(1+exp(-z)). If a scalar gate input is zero, it suppresses the corresponding up-projected value; a positive gate can pass a larger contribution. Every token executes these dense projections. This gate is not a mixture-of-experts router. GLU Variants Improve Transformer describes the architectural comparison.
The distinction between attention and the feed-forward network is useful for resource estimates. With ordinary full-width query, key, value, and output projections, attention has roughly 4D² parameters. The gated feed-forward network has roughly 3DF. Ignoring biases and small normalization vectors:
This count assumes standard multi-head projections; embeddings and the output head are separate.
Applying these matrices at S positions requires roughly 8SD²+6SDF forward FLOPs when a multiply-add counts as two FLOPs. Attention's score and value matrix products add approximately 4S²D for all pairs. An implementation that skips the masked causal triangle reduces that pair term to roughly half at long sequences. These are operation counts, not timing measurements.
This explains a frequently confusing observation: attention has a quadratic sequence-length term, yet it need not dominate a short-prompt model's arithmetic. The feed-forward and projection matrices can be substantial. At longer sequences, the pair term grows faster. Materializing the score matrix can also create a memory problem before it dominates arithmetic. Part IV develops execution schedules that avoid storing that entire intermediate.
What remains fixed, and what will change¶
In this chapter, we treated every projection and normalization gain as a fixed array. Given those arrays and an input sequence, the forward computation produces logits. The next chapter explains how training changes the arrays using the token loss from Chapter 2.
After training, generation returns to this same forward computation with fixed weights. Repeating it naively on the entire growing prefix would redo much of the work. Chapter 5 will show which intermediate values can be retained and why that cache grows as an answer gets longer.
Exercises and worked answers¶
- Why must causal masking precede softmax? A forbidden score must contribute neither output nor normalization mass. Removing its value contribution afterward does not renormalize the permitted scores.
- What shape must a sublayer return for a residual addition? The same
[S,D]shape as its input, with an additional matching batch axis when batched. - If sequence length doubles, which work grows fourfold? The dense all-pairs score/value term. At fixed widths, projection and feed-forward work double. Total runtime need not follow either factor exactly.
- Does a large attention weight prove that a generated claim is supported? No. It describes an internal numerical combination. Support must be checked against the source and the actual claim.
From the hand calculation to an executable decoder¶
examples/decoder_lab.py composes the attention calculation into two causal blocks: a 16-entry embedding, learned positions, width 24, three heads, pre-normalization, GELU feed-forward layers and a vocabulary projection. Its two sequences contain synthetic token IDs in the range 0–15; they are not the output of a text tokenizer. It omits RoPE, GQA and dropout to isolate the tested equivalences.
| Mechanism developed above | Decoder-lab choice | What the comparison establishes |
|---|---|---|
| Per-token normalization, illustrated with RMSNorm | LayerNorm | Residual shapes and cache equivalence; not RMSNorm numerics |
| Gated SiLU feed-forward network | Two linear layers with GELU | Position-wise transformation and gradients; not a gated-MLP implementation |
| Rotary position information | Learned absolute position embeddings | Cached positions retain their global offset; not RoPE pairing or scaling |
| Multi-head attention, with GQA introduced next | Three equal query/key/value heads | Rectangular causal visibility; not shared-KV head mapping |
These substitutions keep the runnable model small. A deployment using another normalization, position rule or head mapping needs equivalence tests for that actual computation.
Inputs [2,7] become [2,7,24] embeddings. Q/K/V reshape to [2,3,7,8], attention probabilities are [2,3,7,7], and final logits are [2,7,16]. Here is the actual Block.forward method; the complete model defines its projections and imports torch and math. A tensor test keeps this excerpt synchronized with the source.
Example status: Optional PyTorch excerpt; exact method from the complete runnable decoder.
def forward(self, x, cache=None):
batch, length, width = x.shape
q, k, v = self.qkv(self.norm1(x)).chunk(3, dim=-1)
q, k, v = [z.reshape(batch, length, self.heads, width // self.heads)
.transpose(1, 2) for z in (q, k, v)]
prefix = 0 if cache is None else cache[0].shape[2]
if cache is not None:
k = torch.cat((cache[0], k), dim=2)
v = torch.cat((cache[1], v), dim=2)
visible = (torch.arange(k.shape[2], device=x.device)[None, :] <=
(prefix + torch.arange(length, device=x.device))[:, None])
scores = (q @ k.transpose(-1, -2)) / math.sqrt(q.shape[-1])
probabilities = scores.masked_fill(~visible, float('-inf')).softmax(-1)
attended = (probabilities @ v).transpose(1, 2).reshape(batch, length, width)
x = x + self.out(attended)
return x + self.mlp(self.norm2(x)), (k, v)
The crucial offset is prefix. With three cached positions and four new positions, scores have shape [2,3,4,7]. New query row zero may see key columns zero through three. A four-by-seven upper-left triangular mask would permit only column zero in that row, silently changing the result. Global positions and rectangular visibility must agree: fixing the mask while restarting learned positions at zero still computes a different model.
The lab checks three independent views of the same sequence: a full pass; a three-token prefix followed by four tokens; and a six-token prefix followed by one token. Agreement below 1e-10 on this FP64 CPU fixture establishes implementation equivalence for the tested shapes. It is not an appropriate default tolerance for FP16 kernels, nor evidence of language quality. Change a future token and earlier logits must remain identical; change a cached prefix token and reusing that cache must fail the comparison. Together, these checks distinguish visibility, offset and invalidation bugs that a falling training loss can conceal.