16 Self-Attention and the Transformer
Companion material for the printed chapter
These links include items presented on other chapter pages.
In Chapter 15, cross-attention removed the fixed-state bottleneck by connecting the decoder to every encoder state through content-dependent weights, and scaled dot products turned query–key comparison into matrix multiplication. Yet the serial nature of recurrence remained.
Queries, keys, and values require neither two separate sequences nor a recurrent state. If a sequence queries itself, every token can pool context from every position, its own included, in one parallel operation.
That departure is the central idea of the Transformer. Abandoning recurrence, however, raises three problems: the model has no built-in representation of token order, a single attention distribution must combine several relationships at once, and stacking unconstrained routing layers destabilizes deep optimization. This chapter constructs the Transformer by addressing each problem from first principles, then trains a deliberately small causal Transformer on the book-corpus benchmark from Chapter 12.
Here is the result we have to explain on the same 14,860-character held-out tail. In one exactly matched seed, positional encoding improves the Transformer’s loss from 2.3405 to 1.9190. Yet Chapter 12’s compact LSTM remains better at 1.8881. The new architecture has learned, and position matters in this run, but the LSTM is still ahead.
16.1 Self-attention: when a sequence queries itself
With the scaled dot-product operator established, self-attention alters only the origin of the three inputs: rather than coming from two distinct sequences (such as an encoder and a decoder), all three come from the same sequence.
Consider a sentence containing the words bank, river, and boats. An effective representation of bank should route information from river and boats, while another occurrence, flanked by loan and interest, must integrate different context. Chapter 15 routed context between two sequences and reduced the score to scaled dot products. Here each token uses that operator to query the surrounding tokens of its own sequence.
The three operational roles remain: a query specifies what information is sought, a key provides the features used for matching, and a value carries the content to be pooled.
Let a batch of token representations be
\[ \matr{X} \in \mathbb{R}^{B \times n \times d}, \]
where \(B\) is the batch size, \(n\) is the sequence length, and \(d\) is the model dimension. Learned linear projections produce
\[ \matr{Q}=\matr{X}\matr{W}_Q,\qquad \matr{K}=\matr{X}\matr{W}_K,\qquad \matr{V}=\matr{X}\matr{W}_V, \]
with \(\matr{W}_Q,\matr{W}_K,\matr{W}_V\in\mathbb{R}^{d\times d}\). Scaled dot-product attention is
\[ \operatorname{Attention}(\matr{Q},\matr{K},\matr{V}) = \operatorname{softmax}\left(\frac{\matr{Q}\matr{K}^\top}{\sqrt d}\right)\matr{V}. \]
For a single sequence, \(\matr{Q}\matr{K}^\top\) has shape \(n\times n\). Row \(i\) contains the compatibility scores from query position \(i\) to every key position \(j\). A row-wise softmax normalizes each row into a probability distribution, and multiplying by \(\matr{V}\) computes a weighted combination of values for each query:
\[ (n,d)(d,n)\to(n,n),\qquad (n,n)(n,d)\to(n,d). \]
Figure 16.1 traces one query, bank, across the four-token sequence bank by the river: the same sequence supplies the queries, keys, and values, and the query’s row of the \(n\times n\) attention matrix gives the weights on the rows of \(\matr{V}\).
Self-attention shares its projections across positions, as an RNN shares its transition across time (Chapter 12): the weights in an attention row depend on content, and the comparison rule that computes them is the same for every query–key pair.
For a single sequence, that comparison rule reduces to a bilinear form governed by a single learned matrix. With \(\vect{x}_i^\top\) denoting row \(i\) of \(\matr{X}\), substituting the projections gives
\[ \frac{(\matr{Q}\matr{K}^\top)_{ij}}{\sqrt d} =\frac{\vect{x}_i^\top \matr{W}_Q\matr{W}_K^\top\vect{x}_j}{\sqrt d}. \]
The kernel smoother of Chapter 14 compared a query and key through a fixed distance metric and a single bandwidth. Here, training optimizes the \(d\times d\) matrix \(\matr{W}_Q\matr{W}_K^\top\), determining how features of the querying token interact with features of the token being read. Because \(\matr{W}_Q\) and \(\matr{W}_K\) are parameterized independently, \(\matr{W}_Q\matr{W}_K^\top\) is generally asymmetric, so the score of bank against river need not equal the score of river against bank. Chapter 15 noted that the kernel connection is an analogy for this reason: a Mercer kernel is symmetric and positive semidefinite, whereas \(\matr{W}_Q\matr{W}_K^\top\) is typically neither symmetric nor positive semidefinite.1 Asymmetric attention weights alone do not imply an asymmetric score matrix: because softmax normalizes each row independently, even a symmetric score matrix can assign most of bank’s weight to river while river’s row distributes its probability mass broadly across other keys. Figure 16.2 illustrates bank’s attention row geometrically in a two-dimensional toy setting, where each projection functions as a linear mapping between planes and each score appears as a signed projection along the query axis.
All query positions can be evaluated concurrently during training because no step depends on hidden states from preceding positions.
Animation 16.B · print companion
Watch the mechanism: reorder the tokens and follow bank's row
Reorder bank, by, the, river as by, river, bank, the. Bank's row of weights follows its query down to slot 2. The keys reorder too: does bank's 0.70 stay in column 3, or follow river's key?
The weights are those of the figure above, for bank, by, the, river: rows are queries, columns are keys, and slots count from 0. Only bank's row is printed; the fainter rows are shading.
\(\operatorname{Attention}(Q,K,V)=\operatorname{softmax}\left(\frac{\class{ba-q}{Q}\class{ba-kt}{K^\top}}{\sqrt d}\right)\class{ba-v}{V}\)
Bank's 0.20 is back on the diagonal, and 0.70 still meets river's value block.
The calculation is readable without playback. Opening this panel loads the optional controls.
One reordering of the chapter's illustrative weights, in bare self-attention with no mask and no position signal; the proof that follows covers every reordering.
Scope and caveats
The reordering (by, river, bank, the) is declared. Every token moves, and the reordering does not reverse itself. The chapter's own audit, later in this section, reorders random vectors in another order; the panel takes none of its numbers and none of its order.
The weights are the figure's illustrative ones. Only bank's row is printed, as in the figure; the other rows are shading.
Rows first, then columns, is a drawing device. The rows-only grid is a real quantity: reordered queries scored against keys still in their old order. But attention on the reordered sequence reorders rows and columns at once, as the one-move glide shows.
Had the value blocks moved while the columns stayed put, bank's 0.70 in column 3 would meet the's value block, and bank's output would change. The panel never draws that state.
One example, not a proof. “Bare” means no mask and nothing tied to slot numbers; the chapter adds both later, and each changes more than addresses.
The palette departs from the figure's house orange, grey and green: here the weights are green, as probabilities, and token names, value blocks and output blocks are blue.
Check yourself. Reorder to the, river, by, bank. In which cells (row, column; slots 0 to 3) do bank's 0.70 and bank's own 0.20 land, and how does bank's row read?
Row 3, bank's new slot: 0.70 follows river's key to (3, 1), and bank's 0.20 lands on the diagonal at (3, 3). The row reads 0.05, 0.70, 0.05, 0.20. Moving the rows alone would leave 0.70 at (3, 3), on bank's own diagonal cell.
Transcript and keyboard help
- The chapter's order, bank, by, the, river, on both axes: rows are queries, columns are keys, and the slot labels count from 0. Bank's row reads 0.20, 0.05, 0.05, 0.70: bank's 0.20 on its own key and 0.70 on river's. A tick marks each token's weight on itself, and all four ticks sit on the diagonal. A value block sits under each key column, and an output block ends each row.
- Reorder to by, river, bank, the. The query rows glide first, each with its token name and its output block. Bank's row lands in slot 2, still reading 0.20, 0.05, 0.05, 0.70, and bank's output lands in slot 2 with it. Every tick leaves the diagonal. The columns have not moved.
- The keys reorder too. Predict: does bank's 0.70 stay in column 3, or follow river's key? Nothing moves while you decide.
- The key columns glide, each with its token name, and each value block slides beneath its column on the same clock. 0.70 rides river's column to column 1, bank's 0.20 reaches the diagonal at (2, 2), and every tick returns to the diagonal. Bank's output block neither moves nor changes: river's value came along with river's weight.
- Back to the chapter's order by a brief fade, then the same reordering in one move: rows with their output blocks and columns with their value blocks, on one clock. Each weight travels straight from its old cell to its new one, and every tick slides along the diagonal without leaving it.
- Queries moved the rows, keys moved the columns, and each value block moved with its key.
- Bank's row holds the same four weights at new addresses and now reads 0.05, 0.70, 0.20, 0.05 in the new column order. Bank's output sits in slot 2, unchanged.
- A ghost outline marks where bank's row began, at slot 0, and a thin path runs from 0.70's first cell, (0, 3), to its last, (2, 1). Bank's 0.20 is back on the diagonal, and 0.70 still meets river's value block.
Silent; paused initially; 1.5× playback. Focus the animation pane: Space or K plays/pauses, arrows seek between beats, Home/End jump, Escape pauses. The scrubber and speed menu also work by keyboard. Reduced-motion mode holds each beat's state instead of moving between them.
Permutation equivariance without positional signals or masks
Consider first self-attention in the absence of positional encodings or attention masks. Permuting the input tokens permutes the output representations in the same way. (A causal mask breaks this symmetry by assigning distinct visible prefixes to different positions.)
Let \(\matr{P}\) be an \(n\times n\) permutation matrix, so that \(\matr{P}\matr{X}\) reorders the input tokens. Then
\[ \matr{Q}'=\matr{P}\matr{Q},\quad \matr{K}'=\matr{P}\matr{K},\quad \matr{V}'=\matr{P}\matr{V}, \]
and therefore
\[ \matr{Q}'\matr{K}'^\top=\matr{P}(\matr{Q}\matr{K}^\top)\matr{P}^\top. \]
Writing \(\matr{S}=\matr{Q}\matr{K}^\top/\sqrt d\), we have \(\matr{S}'=\matr{P}\matr{S}\matr{P}^\top\). Because row-wise softmax operates along each row independently, it commutes with simultaneous row and column permutations:
\[ \operatorname{softmax}(\matr{P}\matr{S}\matr{P}^\top) =\matr{P}\operatorname{softmax}(\matr{S})\matr{P}^\top. \]
With \(\operatorname{SA}\) denoting the self-attention operator, combining these steps yields
\[ \operatorname{SA}(\matr{P}\matr{X}) =\matr{P}\operatorname{SA}(\matr{X}). \]
Self-attention is therefore permutation equivariant: permuting the inputs induces the same permutation on the outputs. It is not permutation invariant, as reordering the input tokens permutes the output rows rather than leaving the output matrix unchanged. However, without an external positional signal, the operator has no mechanism for distinguishing “first” from “fifth.” Any pooling that treats all positions symmetrically (such as mean-pooling) is therefore permutation invariant and reduces the sequence to an unordered multiset.
In Chapter 9, convolution had locality by construction: a convolutional filter encodes neighborhood relationships because its kernel weights are tied to fixed relative offsets. Global attention discards this locality bias. Without positional encodings or structured masking, it has no intrinsic notion of sequence order.
- Define the reusable helpers:
numpy_attentionandnumpy_positions. - Draw five random width-8 tokens, permute them, and find the largest output mismatch, bare and with
peadded. - Report the permutation-equivariance and fixed-slot differences.
Experiment 16.D · print companion
import math
import numpy as np
import matplotlib.pyplot as plt
# [1]
def numpy_attention(x: np.ndarray) -> np.ndarray:
scores = x @ x.T / math.sqrt(x.shape[-1])
scores = scores - scores.max(axis=-1, keepdims=True)
weights = np.exp(scores)
weights = weights / weights.sum(axis=-1, keepdims=True)
return weights @ x
def numpy_positions(length: int, width: int) -> np.ndarray:
position = np.arange(length)[:, None]
frequency = np.exp(
np.arange(0, width, 2) * (-math.log(10_000.0) / width)
)
pe = np.zeros((length, width))
pe[:, 0::2] = np.sin(position * frequency)
pe[:, 1::2] = np.cos(position * frequency)
return pe
# [2]
rng = np.random.default_rng(6050)
x = rng.normal(size=(5, 8))
permutation = np.array([2, 4, 0, 1, 3])
bare_error = np.abs(
numpy_attention(x[permutation]) - numpy_attention(x)[permutation]
).max()
pe = numpy_positions(5, 8)
with_position = numpy_attention(x + pe)
fixed_slot_change = np.abs(
numpy_attention(x[permutation] + pe) - with_position[permutation]
).max()
# [3]
print(f"bare permutation-equivariance error: {bare_error:.2e}")
print(f"fixed-slot difference after adding position: {fixed_slot_change:.3f}")bare permutation-equivariance error: 2.22e-16
fixed-slot difference after adding position: 1.581
In the model without positional signals, the discrepancy is pure numerical roundoff, approximately \(2.2\times10^{-16}\). Adding fixed positional vectors raises the error to 1.581, breaking equivariance. Order must be supplied to the model explicitly.
16.2 Positional encoding: a bank of clocks
The simplest additive code repeats \(i/(n-1)\) across every coordinate. While it supplies order, every position vector lies along the same ray, differing only in magnitude rather than direction. A binary code provides richer directional variation, yet adjacent integers can differ across multiple bits, yielding poor metric locality. These are not impossible designs. Rather, they provide weak inductive biases for a model that must reason about relative shifts and distances.
Sinusoidal encoding equips every position with a bank of harmonic clocks. For an even model dimension \(d\) and frequency indices \(j\in\{0,\dots,d/2-1\}\), define
\[ \begin{aligned} \operatorname{PE}(i,2j) &=\sin\left(i\,10000^{-2j/d}\right),\\ \operatorname{PE}(i,2j+1) &=\cos\left(i\,10000^{-2j/d}\right). \end{aligned} \]
Small \(j\) yields a fast-turning clock, and large \(j\) yields a slow one. Every sine coordinate is paired with a cosine at the same frequency. The model receives
\[ \vect{z}_i=\sqrt d\,\vect{e}_i+\operatorname{PE}(i), \]
where \(\vect{e}_i\) is the token embedding. With token embeddings initialized at coordinate standard deviation \(1/\sqrt d\) (as in the book-corpus experiment below), scaling by \(\sqrt d\) gives unit-variance coordinates, so the embedding’s norm, about \(\sqrt d\), is comparable to the positional vector’s \(\sqrt{d/2}\).
Pairing sine and cosine expresses relative shifts as linear rotations. For an angular frequency \(\omega\), advancing position \(i\) by an offset \(\delta\) is an exact planar rotation:
\[ \begin{bmatrix} \sin((i+\delta)\omega)\\ \cos((i+\delta)\omega) \end{bmatrix} = \begin{bmatrix} \cos(\delta\omega)&\sin(\delta\omega)\\ -\sin(\delta\omega)&\cos(\delta\omega) \end{bmatrix} \begin{bmatrix} \sin(i\omega)\\ \cos(i\omega) \end{bmatrix}. \]
The transformation matrix depends only on the offset \(\delta\), not on the absolute index \(i\). This gives linear layers a convenient form for representing relative displacement. However, this is a property of the sinusoidal code itself, not a guarantee that unconstrained learned projections \(\matr{W}_Q\) and \(\matr{W}_K\) will preserve or exploit it.
In Figure 16.4, the four clocks of a width-8 code illustrate how a single step turns dial \(j\) by a constant angle \(\omega_j\) regardless of starting position. At \(i=44\), the fastest clock (\(j=0\)) has completed approximately seven full revolutions and nearly returned to its orientation at \(i=0\), while the slower clocks still distinguish the two positions.
Instead of adding positional vectors to token embeddings, an alternative is to rotate the projected queries and keys directly. Letting \(R_i\) be a block-diagonal rotation with angles proportional to \(i\), define \(\widetilde{\vect{q}}_i=R_i\vect{q}_i\) and \(\widetilde{\vect{k}}_j=R_j\vect{k}_j\). Their compatibility score becomes
\[ \widetilde{\vect{q}}_i^\top\widetilde{\vect{k}}_j =\vect{q}_i^\top R_i^\top R_j\vect{k}_j =\vect{q}_i^\top R_{j-i}\vect{k}_j, \]
where the final equality follows because transposition inverts each orthogonal planar block (\(R_i^\top=R_{-i}\)), isolating the relative offset \(j-i\). This formulation is rotary positional embedding (RoPE). Semantic content enters through \(\vect{q}_i\) and \(\vect{k}_j\), while RoPE injects relative position directly into their geometric comparison.
- Encode 100 positions at width 32, rotate position 13’s pair j = 5 by offset 7, and compute rotation and norm errors.
- Verify the rotation identity and constant-norm invariant.
Experiment 16.E · print companion
# [1]
pe = numpy_positions(100, 32)
delta = 7
j = 5
omega = 10_000 ** (-2 * j / 32)
rotation = np.array([
[np.cos(delta * omega), np.sin(delta * omega)],
[-np.sin(delta * omega), np.cos(delta * omega)],
])
pair_i = pe[13, 2 * j : 2 * j + 2]
pair_shifted = pe[13 + delta, 2 * j : 2 * j + 2]
rotation_error = np.abs(rotation @ pair_i - pair_shifted).max()
norm_error = np.abs(np.linalg.norm(pe, axis=1) - 4.0).max()
# [2]
print(f"rotation identity maximum error: {rotation_error:.2e}")
print(f"constant position-vector norm maximum error: {norm_error:.2e}")rotation identity maximum error: 1.11e-16
constant position-vector norm maximum error: 0.00e+00
At \(d=32\), each positional vector has Euclidean norm \(\sqrt{d/2}=4\), because each \(\sin^2(\cdot)+\cos^2(\cdot)\) coordinate pair contributes one to the squared norm. Adding this vector does not preserve the norm of the combined token representation: the embedding and positional vector can reinforce or cancel each other depending on their alignment. Layer normalization will subsequently stabilize feature scale at the block level.
16.3 Multi-head attention: routing across parallel subspaces
A single attention distribution forces a compromise among competing retrieval criteria. Multi-head attention runs several smaller routing systems in parallel, each operating on its own linear projection of the sequence representations. Let the number of heads \(N_h\) divide the model dimension \(d\), with per-head width \(D_h=d/N_h\). For each head \(h\),
\[ \matr{Q}_h=\matr{X}\matr{W}_Q^{(h)},\quad \matr{K}_h=\matr{X}\matr{W}_K^{(h)},\quad \matr{V}_h=\matr{X}\matr{W}_V^{(h)}, \]
where \(\matr{W}_Q^{(h)},\matr{W}_K^{(h)},\matr{W}_V^{(h)}\in\mathbb{R}^{d\times D_h}\). The head output is
\[ \matr{O}_h= \operatorname{softmax}\left( \frac{\matr{Q}_h\matr{K}_h^\top}{\sqrt{D_h}}+\matr{M} \right)\matr{V}_h, \]
where \(\matr{M}\) is the visibility mask defined below (\(\matr{M}=0\) for unmasked attention).
The complete operation concatenates the head representations and projects them back to model width:
\[ \operatorname{MHA}(\matr{X}) =\operatorname{Concat}(\matr{O}_1,\ldots,\matr{O}_{N_h})\matr{W}_O, \qquad \matr{W}_O\in\mathbb{R}^{d\times d}. \]
Tensor shapes provide the clearest operational guide:
\[ (B,n,d) \to(B,N_h,n,D_h) \to(B,N_h,n,n) \to(B,N_h,n,D_h) \to(B,n,d). \]
Scaling uses \(\sqrt{D_h}\) rather than \(\sqrt d\) because each head’s dot product sums over \(D_h\) coordinates, and the variance argument of Chapter 15 applies to that sum. With fixed \(d\), splitting into multiple heads does not increase parameter count: the projection matrices \(\matr{W}_Q\), \(\matr{W}_K\), \(\matr{W}_V\), and \(\matr{W}_O\) together contain \(4d^2\) parameters regardless of \(N_h\). Heads partition the model dimension rather than duplicating it.
The mask is part of the model
In Chapter 13, masking specified which sequence positions were invalid. Here, the mask enforces causality: position \(i\) may attend to tokens at earlier and current positions \(j\le i\), but must not attend to future tokens \(j>i\). Because rows correspond to queries and columns to keys, the forbidden region forms a strict upper triangle. We set
\[ \matr{M}_{ij}= \begin{cases} 0,&j\le i,\\ -\infty,&j>i \end{cases} \]
before softmax. Zeroing forbidden probabilities after softmax would leave the surviving distribution unnormalized. Adding \(-\infty\) prior to exponentiation is algebraically equivalent to setting forbidden probabilities to zero and renormalizing the remaining probabilities by their sum. Each row becomes the unmasked distribution conditioned on the causal event \(j\le i\). Masking every key in a row is ill-defined, as softmax over all \(-\infty\) yields NaN. In a causal mask, the main diagonal remains visible: the representation at position \(i\) may attend to token \(i\) while predicting token \(i+1\).
- Define the
CausalMultiHeadAttentionmodule. - Fix the seed, run 12 random width-32 tokens through a 4-head module, and build the strict upper-triangle
futuremask. - Implement causal multi-head attention and audit its mask.
Experiment 16.F · print companion
import torch
from torch import nn
torch.set_num_threads(4) # pinned: results depend on the CPU thread count
# [1]
class CausalMultiHeadAttention(nn.Module):
def __init__(self, width: int, heads: int) -> None:
super().__init__()
if width % heads != 0:
raise ValueError("width must be divisible by heads")
self.heads = heads
self.head_width = width // heads
self.qkv = nn.Linear(width, 3 * width)
self.project = nn.Linear(width, width)
nn.init.xavier_uniform_(self.qkv.weight)
nn.init.zeros_(self.qkv.bias)
def forward(self, x: torch.Tensor, return_weights: bool = False):
batch, length, width = x.shape
qkv = self.qkv(x)
qkv = qkv.reshape(
batch, length, 3, self.heads, self.head_width
).permute(2, 0, 3, 1, 4)
q, k, v = qkv.unbind(dim=0)
scores = q @ k.transpose(-2, -1) / math.sqrt(self.head_width)
forbidden = torch.triu(
torch.ones(length, length, dtype=torch.bool, device=x.device),
diagonal=1,
)
scores = scores.masked_fill(forbidden, float("-inf"))
weights = torch.softmax(scores, dim=-1)
routed = weights @ v
routed = routed.transpose(1, 2).reshape(batch, length, width)
output = self.project(routed)
if return_weights:
return output, weights
return output
# [2]
torch.manual_seed(6050)
demo_attention = CausalMultiHeadAttention(width=32, heads=4)
demo_x = torch.randn(1, 12, 32)
_, demo_weights = demo_attention(demo_x, return_weights=True)
future = torch.triu(torch.ones(12, 12, dtype=torch.bool), diagonal=1)
# [3]
assert demo_weights[0, :, future].max().item() == 0.0
assert torch.allclose(
demo_weights.sum(dim=-1),
torch.ones_like(demo_weights.sum(dim=-1)),
atol=1e-6,
)
- Report the causal-mask and normalization audit.
# [1]
print("maximum forbidden attention:", demo_weights[0, :, future].max().item())
print(
"maximum row-sum error:",
(demo_weights.sum(dim=-1) - 1).abs().max().item(),
)maximum forbidden attention: 0.0
maximum row-sum error: 1.1920928955078125e-07
Executable shape and normalization checks validate an implementation against its mathematical specification. A visually plausible triangular mask can still be transposed, offset along the diagonal by one, or applied after normalization, and explicit assertions catch these errors before training can hide them.
The mask restricts information flow, not arithmetic volume: the implementation still evaluates all \(n^2\) pairwise scores and instantiates \(BN_hn^2\) attention weights, in addition to the \(\mathcal{O}(Bnd^2)\) projection FLOPs and \(\mathcal{O}(Bndd_{\text{ff}})\) work in the feedforward sublayer of the Transformer block. Self-attention reduces the shortest path between distant tokens to a single routing step, but unit graph diameter does not imply constant computational complexity. Appendix C analyzes this quadratic bottleneck through Roofline modeling and FlashAttention’s I/O-aware schedule.
16.4 The Transformer block: residuals, normalization, and feedforward networks
Attention routes information across token positions. Transforming this mechanism into a deep network requires two additional components: an unobstructed path through depth and a nonlinear transformation at each position.
The residual stream
Chapter 10 introduced the residual stream: every sublayer reads from the stream and writes an additive correction back. If a sublayer computes \(F(\vect{x})\), the residual update is
\[ \vect{x}\leftarrow \vect{x}+F(\vect{x}). \]
The identity branch provides a direct conduit for representations and gradients, while the learned branch proposes a local correction. This structure makes deep optimization more tractable, though it does not eliminate the risk of vanishing or exploding gradients.
Layer normalization controls feature scale along the representation axis. For a single token vector \(\vect{x}\in\mathbb{R}^{d}\),
\[ \mu=\frac1d\sum_{\ell=1}^{d}x_\ell,\qquad \sigma^2=\frac1d\sum_{\ell=1}^{d}(x_\ell-\mu)^2, \]
and
\[ \operatorname{LN}(\vect{x})_\ell =\gamma_\ell\frac{x_\ell-\mu}{\sqrt{\sigma^2+\epsilon}}+\beta_\ell, \qquad \vect{\gamma},\vect{\beta}\in\mathbb{R}^d. \]
This adapts the normalization principle of Chapter 10 to a different tensor axis. Whereas BatchNorm2d pools statistics across batch and spatial dimensions for each channel, LayerNorm operates along the feature axis of each token: it computes empirical moments across the \(d\) features within one token, without aggregating across neighboring tokens or batch examples. Its formulation remains identical during training and evaluation. Prior to applying the learned parameters \(\vect{\gamma}\) and \(\vect{\beta}\), the normalized vector has mean zero and approximately unit variance. Geometrically, subtracting \(\mu\) removes \(\mu(1,\ldots,1)\), the orthogonal projection of \(\vect{x}\) onto the all-ones vector. Dividing by \(\sqrt{\sigma^2+\epsilon}\) scales the squared Euclidean norm to \(d\sigma^2/(\sigma^2+\epsilon)\). When \(\sigma^2\gg\epsilon\), this quantity approaches \(d\), so the normalized token lies approximately on the sphere of radius \(\sqrt d\) within the zero-mean hyperplane.
- Apply
layer_normto four width-4 tokens with different offsets and scales, then take each token’s mean and variance. - Verify LayerNorm centers and scales each token independently.
Experiment 16.G · print companion
# [1]
audit = torch.tensor([
[[1.0, 3.0, 5.0, 7.0], [40.0, 50.0, 60.0, 70.0]],
[[-3.0, 1.0, 5.0, 9.0], [2.0, 2.5, 3.0, 3.5]],
])
normalized = nn.functional.layer_norm(audit, (4,))
token_means = normalized.mean(dim=-1)
token_vars = normalized.var(dim=-1, unbiased=False)
# [2]
assert token_means.abs().max().item() < 1e-6
assert (token_vars - 1).abs().max().item() < 1e-4
Animation 16.C · print companion
Watch the mechanism: BatchNorm down, LayerNorm across
BatchNorm and LayerNorm apply the same formula. If a neighboring token's values change, does this token's normalized output change too?
First compare the groups that share statistics. Then follow the audit's first token as its feature profile shifts and rescales. Last comes a test: a neighboring token doubles. Decide beforehand what will move.
\( \mu=\dfrac1d\class{la-pool-term}{\sum_k}\featurepart{x_k} \) \( \predictionpart{z_k}=\dfrac{\class{la-center-term}{\featurepart{x_k}-\mu}}{\class{la-scale-term}{\sqrt{\sigma^2+\epsilon}}} \) \( \operatorname{Var}(\predictionpart{z})=\dfrac{\sigma^2}{\sigma^2+\epsilon},\quad\epsilon=10^{-5}>0 \)
A token's LayerNorm result does not depend on batchmates or sequence length; BatchNorm's statistics do. Before learned scale and shift.
The calculation is readable without playback. Opening this panel loads the optional controls.
The token tensor is not an image: its vertical bracket shows temporal BatchNorm during training, pooling examples and positions separately for each feature.
Scope and caveats
The separate CNN sketch holds one channel fixed and pools images and spatial positions. The LayerNorm profile keeps a fixed value ruler; its dashed blue ghost is the raw first token. Each row normalizes separately, before learned scale and shift. Positive epsilon makes the near-unit variance approximate. The closing test is a computed variant of the audit tensor, not new data: the neighboring token (40, 50, 60, 70) is doubled and the same LayerNorm is run again. Of BatchNorm, only the pooled feature-1 mean is shown, 10 before and 20 after; no BatchNorm output is computed. While the neighbor's numerals move they are rounded to whole numbers. The test holds this token's own features fixed; attention may already have mixed context into them.
Why BatchNorm fits images and LayerNorm fits sequences
Why sharing can fit a CNN. One convolutional channel measures the same kind of feature across a regular spatial grid. BatchNorm shares that channel's training statistics across images and positions, the \(N,H,W\) axes. Matching image sizes make dense minibatches convenient; fixed image size is not a requirement of BatchNorm itself. By default, evaluation uses running statistics collected during training.
Why token-local statistics fit variable lengths. Ordinary temporal BatchNorm pools the \(B,T\) axes. Unmasked padding enters those statistics; even masked pooling gives longer sequences more entries. LayerNorm instead pools a token's features: sequence length can vary while feature width stays fixed. With that token's input features held fixed, padding elsewhere or different batchmates cannot change its LayerNorm result. It uses the same calculation in training and evaluation. Attention and loss masks are still needed.
Check yourself. Multiply the first token's four features by 10, to (10, 30, 50, 70). What is its LayerNorm output?
The same: (−1.342, −0.447, 0.447, 1.342), up to the tiny effect of ε. The mean and the standard deviation both grow tenfold and cancel. LayerNorm removes each token's own offset and scale, whatever the other tokens are doing.
Transcript and keyboard help
- The audit has two examples, two tokens per example, and four features per token. The opening vertical bracket selects one feature across every example and token, the group used by temporal BatchNorm during training. A separate nonnumeric CNN sketch connects two images' feature maps for one channel to shared statistics across images and spatial positions. It does not reinterpret the token tensor as images.
- At five seconds the axis begins to change. One highlight turns, over two and a half seconds ending at ten seconds, from that vertical feature column into the horizontal row of example 1, token 1: 1, 3, 5, 7. It pivots about the one cell the two groups share, this token's own feature 1, so the reader follows a single rectangle rather than a swap. The column it leaves stays on the picture as a muted dashed outline until the closing test, and its numerals return to gray; the persistent axis key keeps both directions explicit. The token's raw profile appears as the turn begins, taking the place of the CNN sketch.
- This row's mean is 4 and its population variance is 5. None of the other tokens enters either calculation.
- Subtract 4 from every feature. The same profile translates to minus 3, minus 1, 1, 3 and has mean zero.
- Divide every centered feature by the square root of 5 plus the positive stability constant, approximately 2.236.
- The resulting values are approximately minus 1.342, minus 0.447, 0.447, 1.342. Their variance is approximately 0.999998, not exactly one.
- At thirty seconds both groups are outlined on the same tensor: BatchNorm's feature 1 column and LayerNorm's first-token row. Under the plot, one number line carries two pointers: this token's mean, 4, above it, and feature 1's pooled mean, 10, below it. The caption asks for a prediction: the neighboring token, example 1 token 2, is about to double. Then its values rise from 40, 50, 60, 70 to 80, 100, 120, 140. The pooled-mean pointer slides from 10 to 20, because the changed value, 40 to 80, lies inside BatchNorm's column. The token's own mean pointer and its normalized profile do not move: no changed value lies inside LayerNorm's row. LayerNorm was run again on the changed tensor to draw that unmoved profile.
- A token's LayerNorm result does not depend on its batchmates or on sequence length; BatchNorm's training statistics do. The final frame keeps both outlines, the doubled row, the pooled mean's move from 10 to 20, and the unmoved profile −1.342, −0.447, 0.447, 1.342. This is before learned scale and shift. A positive stability constant slightly changes the variance. Default BatchNorm evaluation uses running statistics; LayerNorm uses the same token-local calculation in training and evaluation. With that token's features held fixed, padding elsewhere does not enter its normalization. Attention may already have mixed context into those features; attention and loss masks remain necessary. Naive temporal BatchNorm pooling in a causal model can also include future positions.
Silent; paused initially; 1.5× playback. Focus the animation pane: Space or K plays/pauses, arrows seek between beats, Home/End jump, Escape pauses. The scrubber and speed menu also work by keyboard. Reduced-motion mode holds each beat's state instead of moving between them.
- Report the per-token LayerNorm audit.
# [1]
print("maximum absolute token mean:", token_means.abs().max().item())
print("maximum token variance error:", (token_vars - 1).abs().max().item())maximum absolute token mean: 0.0
maximum token variance error: 3.2067298889160156e-05
The original Transformer normalized after each residual addition:
\[ \vect{x}\leftarrow\operatorname{LN}(\vect{x}+\operatorname{MHA}(\vect{x})),\qquad \vect{x}\leftarrow\operatorname{LN}(\vect{x}+\operatorname{FFN}(\vect{x})). \]
Our implementation adopts the now-standard pre-LayerNorm design:
\[ \begin{aligned} \vect{x}&\leftarrow \vect{x}+\operatorname{MHA}(\operatorname{LN}(\vect{x})),\\ \vect{x}&\leftarrow \vect{x}+\operatorname{FFN}(\operatorname{LN}(\vect{x})). \end{aligned} \]
Post-LayerNorm normalizes the aggregated representation after each residual addition, analogous to applying an activation function after the shortcut merge in early ResNets (Chapter 10). Pre-LayerNorm moves normalization into the function branch, mirroring pre-activation ResNets. Pre-LayerNorm keeps an unobstructed identity path along the residual stream, and in the experiments of Xiong et al. it trained without the learning-rate warmup (Chapter 4) that post-LayerNorm needed.
RMSNorm retains the rescaling but omits mean centering:
\[ \operatorname{RMSNorm}(\vect{x}) =\vect{g}\odot \frac{\vect{x}} {\sqrt{\frac{1}{d}\sum_{\ell=1}^{d}x_\ell^2+\epsilon}}. \]
It divides each token by its root-mean-square magnitude and applies a learned per-feature gain \(\vect{g}\). Prior to modulation by \(\vect{g}\), it rescales \(\vect{x}\) to a sphere of radius approximately \(\sqrt d\) without shifting the representation into the zero-mean subspace. This omits one reduction operation per token. Whether this computational saving translates into empirical gains depends on model scale, precision format, and memory bandwidth.
The position-wise feedforward network
Once tokens exchange information through attention, the same two-layer feedforward network processes each sequence position independently:
\[ \operatorname{FFN}(\vect{z}) =\matr{W}_2\operatorname{ReLU}(\matr{W}_1\vect{z}+\vect{b}_1)+\vect{b}_2, \]
where \(\matr{W}_1\in\mathbb{R}^{d_{\text{ff}}\times d}\), \(\vect{b}_1\in\mathbb{R}^{d_{\text{ff}}}\), \(\matr{W}_2\in\mathbb{R}^{d\times d_{\text{ff}}}\), and \(\vect{b}_2\in\mathbb{R}^{d}\).
With \(\vect{w}_{1j}^\top\) as row \(j\) of \(\matr{W}_1\) and \(\vect{u}_j\) as column \(j\) of \(\matr{W}_2\), the transformation decomposes as
\[ \operatorname{FFN}(\vect{z}) =\sum_j [\vect{w}_{1j}^\top \vect{z}+b_{1j}]_+\,\vect{u}_j+\vect{b}_2. \]
This decomposition highlights an interpretation of the feedforward network as a key–value associative memory. Each row of \(\matr{W}_1\) acts as a pattern detector, testing whether the input falls within a learned half-space, and its rectified activation determines the degree to which the value vector \(\vect{u}_j\) is written to the representation. While Transformer feedforward layers can exhibit associative-memory behavior empirically, this remains an operational analogy: the activations are unnormalized, graded half-space responses rather than localized kernel weights that sum to one.
The complete block therefore alternates between two complementary operations:
- causal multi-head attention routes information between sequence positions; and
- the feedforward network transforms representations within each individual position.
Residual connections add the results of both operations to a single residual stream that persists across the depth of the network.
Within each attention head, every output is a convex combination of that head’s value vectors, so it lies within their convex hull. The multi-head output concatenates these averages and applies the output projection, a linear map that can move the result outside the hull of the original value vectors. Without residual shortcuts or feedforward layers, stacked attention layers apply such averaging again and again and can contract the token representations toward a single shared representation.
Dong, Cordonnier, and Loukas formalized this rank collapse for unmasked attention. When the projection matrices are small enough in norm and the token embeddings are clustered, the authors’ bound on the distance from the token matrix to a rank-one subspace shrinks doubly exponentially with depth, with the exponent tripling at every layer. Their empirical evaluations reproduced this collapse across pretrained language models when residual connections were removed.
The residual update \(\vect{x}\leftarrow \vect{x}+F(\vect{x})\) provides a bypass around every attention layer. The identity branch propagates token differences forward directly without averaging, so the collapse is no longer forced. A shared position-wise FFN cannot restore distinctions once token representations are identical. It maps identical inputs to identical outputs. Feedforward layers can dilate existing token differences and slow the collapse, and residual connections provide a path that bypasses the repeated averaging. The cited collapse result holds under its stated assumptions. It does not describe every attention architecture without residual connections.
16.5 From encoder–decoder translation to a causal language model
The original Transformer of Vaswani et al. was an encoder–decoder architecture designed for bilingual translation. Its encoder stack uses bidirectional (unmasked) self-attention to construct contextual representations of the source sequence. Its decoder stack applies causal self-attention over the target prefix, followed by cross-attention whose queries originate in the decoder while keys and values are retrieved from the encoder memory:
\[ \begin{array}{lll} \text{encoder:}& \matr{X}_s \to \text{self-attention} \to \text{FFN},\\ \text{decoder:}& \matr{X}_t \to \text{causal self-attention} \to \text{cross-attention to encoder} \to \text{FFN}. \end{array} \]
The book-corpus task of Chapter 12 requires autoregressive next-character prediction from preceding context alone. Because there is no external source sequence, both the encoder stack and the cross-attention sublayers are unnecessary. The resulting architecture is a decoder-only causal Transformer that consists of token and positional embeddings, two pre-LayerNorm blocks, a final layer normalization, and a linear projection to vocabulary logits. These logits feed directly into the cross-entropy loss. Softmax normalization belongs inside attention routing and autoregressive sampling, not between the output projection and the loss.
16.6 Character-level language modeling with a causal Transformer
To compare the causal Transformer directly against the recurrent baseline of Chapter 12, the experiment holds fixed every training setting that both architectures share. Chapter 12 trained on a committed snapshot of Chapters 1–6 and 8–10 with executable code cells and HTML comments removed: 148,594 characters, vocabulary 104, a contiguous 90/10 split, 100-character windows, batch size 64, and 2,501 updates with Adam at learning rate 0.002 and gradient clipping at norm 1. Freezing this text snapshot keeps the benchmark invariant across subsequent manuscript edits. The held-out evaluation scores each fixed window independently.
Although the two architectures differ in structure (recurrent gates versus attention blocks), their training inputs and parameter budgets can be matched. The code below reconstructs Chapter 12’s exact random-window schedule, then gives both Transformer variants the same initial parameter tensors and all 16,006,400 target characters in the same order.
- Implement the tiny Transformer: positions, block, model.
Experiment 16.H · print companion
# [1]
def sinusoidal_positions(length: int, width: int) -> torch.Tensor:
position = torch.arange(length, dtype=torch.float32).unsqueeze(1)
frequency = torch.exp(
torch.arange(0, width, 2, dtype=torch.float32)
* (-math.log(10_000.0) / width)
)
table = torch.zeros(length, width)
table[:, 0::2] = torch.sin(position * frequency)
table[:, 1::2] = torch.cos(position * frequency)
return table
class TransformerBlock(nn.Module):
def __init__(self) -> None:
super().__init__()
self.norm1 = nn.LayerNorm(WIDTH)
self.attention = CausalMultiHeadAttention(WIDTH, HEADS)
self.norm2 = nn.LayerNorm(WIDTH)
self.ff = nn.Sequential(
nn.Linear(WIDTH, FF_WIDTH),
nn.ReLU(),
nn.Linear(FF_WIDTH, WIDTH),
)
def forward(self, x: torch.Tensor, return_weights: bool = False):
if return_weights:
attended, weights = self.attention(self.norm1(x), True)
x = x + attended
return x + self.ff(self.norm2(x)), weights
x = x + self.attention(self.norm1(x))
return x + self.ff(self.norm2(x))
class TinyTransformerLM(nn.Module):
def __init__(self, vocab: int, positions: bool) -> None:
super().__init__()
self.positions = positions
self.token_embedding = nn.Embedding(vocab, WIDTH)
nn.init.normal_(
self.token_embedding.weight,
mean=0.0,
std=1 / math.sqrt(WIDTH),
)
self.blocks = nn.ModuleList(
[TransformerBlock() for _ in range(BLOCKS)]
)
self.final_norm = nn.LayerNorm(WIDTH)
self.output = nn.Linear(WIDTH, vocab)
self.register_buffer(
"position_table",
sinusoidal_positions(CONTEXT, WIDTH),
persistent=False,
)
def forward(self, tokens: torch.Tensor, return_weights: bool = False):
length = tokens.shape[1]
x = self.token_embedding(tokens) * math.sqrt(WIDTH)
if self.positions:
x = x + self.position_table[:length]
maps = []
for block in self.blocks:
if return_weights:
x, weights = block(x, True)
maps.append(weights)
else:
x = block(x)
logits = self.output(self.final_norm(x))
return (logits, maps) if return_weights else logitsTo match the window sequence of Chapter 12, an isolated generator steps through the same random state that produced the LSTM’s minibatches and precomputes the start indices for every update before training begins. Both Transformer variants then load the same saved initial parameter snapshot:
- Redraw Chapter 12’s window schedule, clone one Transformer initialization, and hash both.
- Implement the paired protocol: shared schedule, identical initial tensors.
# Reconstruct the random-number state immediately after Chapter 12 created
# its LSTM, then draw that chapter's complete minibatch-start schedule.
# [1]
torch.manual_seed(SEED)
_ = HistoricalCharLSTM(len(chars))
schedule_generator = torch.Generator()
schedule_generator.set_state(torch.random.get_rng_state())
starts = torch.randint(
0,
len(train_data) - CONTEXT - 1,
(UPDATES, BATCH),
generator=schedule_generator,
)
# The two Transformer variants begin with exactly the same tensors.
torch.manual_seed(SEED)
base_model = TinyTransformerLM(len(chars), positions=True)
initial_state = {
name: value.clone() for name, value in base_model.state_dict().items()
}
initial_hash = state_digest(initial_state)
schedule_hash = hashlib.sha256(starts.numpy().tobytes()).hexdigest()
# [2]
print(f"corpus: 9 chapters, {len(text):,} characters, vocab {len(chars)}")
print(
f"deterministic split: {len(train_data):,} train / "
f"{len(valid_data):,} held out"
)
print(
f"Transformer parameters: "
f"{sum(parameter.numel() for parameter in base_model.parameters()):,}"
)
print(f"first eight window starts: {starts[0, :8].tolist()}")
print(f"initial tensors: {initial_hash[:12]}…")
print(f"window schedule: {schedule_hash[:12]}…")corpus: 9 chapters, 148,594 characters, vocab 104
deterministic split: 133,734 train / 14,860 held out
Transformer parameters: 132,488
first eight window starts: [24368, 94128, 60074, 121547, 118001, 4396, 17011, 8495]
initial tensors: 4d2f7f434cb5…
window schedule: e470a091bd50…
The architecture contains 132,488 trainable parameters, 736 fewer than the LSTM of Chapter 12 (133,224 parameters), so the parameter counts match to within 0.55%. Its model dimension is \(d=84\), divided into \(N_h=4\) heads of width \(D_h=21\). Each of the two feedforward sublayers expands to \(d_{\text{ff}}=168\) features, with a ReLU between its two linear layers. We initialize token embeddings with coordinate standard deviation \(1/\sqrt d\) prior to the \(\sqrt d\) scaling, ensuring embedding features and sinusoidal coordinates begin on comparable scales. ModuleList registers the two repeated blocks with the model. The position table is registered as a non-persistent buffer: it moves with the module across devices but is neither optimized nor included in the state-dictionary fingerprint, as its entries derive deterministically from the closed-form formula. With dropout disabled, resetting the parameter tensors and window sequence makes the positional ablation reproducible.
Setting the same random seed before two training runs does not guarantee that both models encounter identical minibatches. Module instantiation consumes random draws, so differing architectural graphs silently shift the stream of random draws for all subsequent operations. To enforce a controlled ablation, we precompute the full window-index tensor with an isolated generator and initialize both models from an identical parameter snapshot, logging SHA-256 fingerprints for both artifacts.
We reuse the training and evaluation harnesses of Chapter 12 unchanged. The trainer’s signature:
- Reuse the shared trainer through its explicit model, data, schedule, and optimization interface.
# [1]
def fit_next_token(
model: nn.Module,
data: torch.Tensor,
*,
vocab: int,
context: int = 100,
batch: int = 64,
steps: int = 2501,
lr: float = 2e-3,
clip: float = 1.0,
schedule: list[torch.Tensor] | None = None,
log_every: int = 500,
log_decimals: int = 2,
) -> tuple[nn.Module, list[tuple[int, float]]]:… the body matches Listing 12.1; only the new pieces are printed below.
- Chapter 12’s trainer, imported: only the deltas printed.
from dlbook.training import fit_next_token # Listing 12.1, Ch. 12
from dlbook.evaluation import fixed_window_loss # Listing 12.2, Ch. 12
# [1]
def train_transformer(
positions: bool,
) -> tuple[nn.Module, list[tuple[int, float]]]:
net = TinyTransformerLM(len(chars), positions=positions)
net.load_state_dict(initial_state, strict=True) # paired start: same tensors
assert state_digest(net.state_dict()) == initial_hash
return fit_next_token(
net, train_data, vocab=len(chars),
schedule=starts, # minibatch order is protocol, not chance
log_every=250, log_decimals=4,
)
@torch.no_grad()
def transformer_sample(
net: nn.Module,
prompt: str,
n: int = 300,
temperature: float = 0.8,
) -> str:
net.eval()
generator = torch.Generator().manual_seed(1_406_050)
tokens = [stoi.get(char, 0) for char in prompt]
for _ in range(n):
context = torch.tensor(tokens[-CONTEXT:]).unsqueeze(0)
probabilities = F.softmax(
net(context)[0, -1] / temperature, dim=-1
)
next_token = torch.multinomial(
probabilities, 1, generator=generator
).item()
tokens.append(next_token)
return "".join(chars[index] for index in tokens)- Train the positional Transformer.
- Print the positional model’s fixed-window train and held-out losses.
# [1]
position_model, position_curve = train_transformer(positions=True)
position_train_loss = fixed_window_loss(position_model, train_data, vocab=len(chars))
position_valid_loss = fixed_window_loss(position_model, valid_data, vocab=len(chars))
# [2]
print(f"fixed-window train loss: {position_train_loss:.4f}")
print(f"fixed-window held-out loss: {position_valid_loss:.4f}")step 0 loss 4.7550
step 250 loss 2.1850
step 500 loss 1.7159
step 750 loss 1.5176
step 1000 loss 1.3955
step 1250 loss 1.3444
step 1500 loss 1.2813
step 1750 loss 1.2386
step 2000 loss 1.1708
step 2250 loss 1.1525
step 2500 loss 1.1083
fixed-window train loss: 1.1132
fixed-window held-out loss: 1.9190
- Repeat with position removed and everything else fixed.
- Print the no-position model’s fixed-window train and held-out losses.
# [1]
no_position_model, no_position_curve = train_transformer(positions=False)
no_position_train_loss = fixed_window_loss(
no_position_model, train_data, vocab=len(chars)
)
no_position_valid_loss = fixed_window_loss(
no_position_model, valid_data, vocab=len(chars)
)
# [2]
print(f"fixed-window train loss: {no_position_train_loss:.4f}")
print(f"fixed-window held-out loss: {no_position_valid_loss:.4f}")step 0 loss 4.7289
step 250 loss 2.4955
step 500 loss 2.3612
step 750 loss 2.2436
step 1000 loss 2.2153
step 1250 loss 2.1826
step 1500 loss 2.0792
step 1750 loss 1.9876
step 2000 loss 1.9527
step 2250 loss 1.8986
step 2500 loss 1.8435
fixed-window train loss: 1.8672
fixed-window held-out loss: 2.3405
- Store Chapter 12’s LSTM held-out loss, 1.888110429, as
lstm_valid_loss. - Report the positional improvement and LSTM gap.
# [1]
lstm_valid_loss = 1.888110429
# [2]
improvement = no_position_valid_loss - position_valid_loss
relative = improvement / no_position_valid_loss
lstm_gap = position_valid_loss - lstm_valid_loss
print(
f"position improvement: {improvement:.4f} loss "
f"({relative:.1%} relative)"
)
print(f"positional Transformer minus LSTM: {lstm_gap:.4f} loss")position improvement: 0.4214 loss (18.0% relative)
positional Transformer minus LSTM: 0.0309 loss
Figure 16.8 plots both training curves alongside held-out losses: the curves separate within the first 250 updates, and the gap persists throughout training. The positional model has a loss of 1.1132 on a full deterministic pass over the training corpus and 1.9190 on the held-out tail. Removing positional encodings raises these values to 1.8672 and 2.3405, respectively. Positional encodings lower held-out loss by 0.4214, or 18.0% relative to the variant without them.
The causal mask inherently leaks ordinal information: row \(i\) attends only to a prefix of length \(i+1\), allowing stacked layers to infer position from expanding receptive fields. This structural clue may explain why the unaugmented model performs better than an orderless model would. Training a model that observes only an unordered multiset of preceding characters on this schedule would test this explanation. Haviv et al. trained causal language models up to 1.3 billion parameters without positional encodings and found that held-out perplexity closely approached that of sinusoidal baselines as scale increased. A small probe network trained on internal activations recovered approximate token positions, and the authors conjectured that the causal mask supplies this signal through the count of predecessors. At our compact scale, however, explicit sinusoidal encodings provide a substantial empirical advantage.
Yet the LSTM of Chapter 12 still has a held-out loss 0.0309 (1.64%) lower than that of the positional Transformer. In this regime, with 100 characters of context and approximately 133,000 parameters, the sequential inductive bias of recurrence remains competitive. This experiment matches corpus, parameter count, gradient updates, minibatch order, and optimization settings, but it does not imply that either architecture reached its tuned optimum. Because the experiment uses a single initialization seed, these results are a controlled case study rather than an average over random trials.
What did the heads route?
An attention map records internal routing weights, not causal explanations, predictive confidence, or mechanistic justifications. Nonetheless, inspecting learned weight distributions can verify the mask and reveal the patterns that emerged during training. The next cell sends the prompt The gradient through the positional model and plots the second block’s four heads.
- Run the prompt through the positional model and assert the last block’s causal mask and unit row sums.
- Audit causal masking and row normalization.
Experiment 16.I · print companion
# [1]
prompt = "The gradient "
prompt_tokens = torch.tensor([[stoi[char] for char in prompt]])
position_model.eval()
with torch.no_grad():
_, learned_maps = position_model(prompt_tokens, return_weights=True)
learned = learned_maps[-1][0]
future = torch.triu(
torch.ones(len(prompt), len(prompt), dtype=torch.bool), diagonal=1
)
assert learned[:, future].max().item() == 0.0
assert torch.allclose(
learned.sum(dim=-1),
torch.ones_like(learned.sum(dim=-1)),
atol=1e-6,
)
# [2]
print("maximum future attention:", learned[:, future].max().item())
print(
"maximum row-sum error:",
(learned.sum(dim=-1) - 1).abs().max().item(),
)maximum future attention: 0.0
maximum row-sum error: 1.1920928955078125e-07
The learned maps satisfy both specifications: future positions receive identically zero weight, and each query row sums to one within single-precision floating-point tolerance. While the four heads exhibit distinct routing behaviors, labeling them as “the previous-character head” or “the word head” from a single prompt exceeds what the evidence establishes. Attention weights merely indicate where representations were pooled. Downstream feedforward layers and residual connections can transform, modulate, or neutralize what was retrieved.
Autoregressive sampling and qualitative evaluation
Both Transformer variants can generate text autoregressively: at each step, the model truncates the context to the most recent 100 characters, evaluates a categorical distribution over the vocabulary, samples a character, and appends it to the prefix. Unlike the LSTM of Chapter 12, this baseline implementation maintains no persistent recurrent state. It evaluates the entire context window afresh at every generation step.
For next-token logits \(z_i\), temperature is the dial from Chapter 2: it divides each logit by \(T\) before the softmax:
\[ p_i(T)=\frac{\exp(z_i/T)}{\sum_j\exp(z_j/T)},\qquad T>0. \]
Lower \(T\) concentrates probability; higher \(T\) flattens it. Top-\(k\) sampling keeps the \(k\) largest logits, sets the rest to negative infinity, then renormalizes. Nucleus (top-\(p\)) sampling first sorts the model probabilities and keeps the smallest prefix whose cumulative mass reaches \(p\), then renormalizes. The former fixes a candidate count; the latter lets that count adapt to the distribution’s shape. Neither changes the trained weights, and neither guarantees a better sample.
Keeping a set of tokens and renormalizing, as top-\(k\) and nucleus sampling do, is what the causal mask does to each attention row (zero the excluded entries, divide the rest by their sum), with next tokens in place of keys. It gives the distribution over the next token conditioned on that token lying in the kept set. Enforcing a rule that forbids tokens, such as characters that would break the ISO date format of Chapter 13, conditions the distribution at each step in the same way. A sampler that does this at every step need not return the outputs the rule allows in proportion to their probabilities under the model (Exercise 9 of Chapter 13).
For evaluation, if \(L\) is mean token negative log-likelihood in natural-log units, perplexity is \(\exp(L)\). It is an exponentiated loss, not a fluency score. Compare it only under the same tokenization, data, and per-token averaging.
- Deterministic samples from both Transformer variants.
Experiment 16.J · print companion
print("WITH POSITION\n")
# [1]
print(transformer_sample(position_model, "The gradient "))
print("\n\nWITHOUT POSITION\n")
print(transformer_sample(no_position_model, "The gradient "))WITH POSITION
The gradient choing fine on autograd it by tweight the clue larges of calling functions in What independes the gradients $\rightarrow$ well $\rightarrow$ with nexp for logits collapse it is the stanged
normalized of the argument builds give if the five is the funit or principled update a threshat mactumes at tow
WITHOUT POSITION
The gradient explens ine. The beveuind or clos? we the canlay. Wet orurle
this moples doing ther diest the the contive losio thes despunction erbiveng or of a the
corno isy la prenod in thrathe s to derngexperevive. With the chate is the compfathes bl. Thicte olo
tat ur is $L$\vect{w}^\vect{w} = \mectrimes \vect
The positional sample exhibits book-specific punctuation, recognizable LaTeX fragments, and localized syntactic coherence, even if it lacks global semantic consistency. In contrast, the model without position produces mostly degraded character sequences. Yet qualitative fluency must not be conflated with generalization: an autoregressive sample represents a single stochastic trajectory, whereas held-out loss evaluates every held-out target under the model’s conditional probability distribution.
16.7 Architectural trade-offs: gains and costs of self-attention
During autoregressive generation, exact attention converts past context into both a memory footprint and a computational bottleneck: every newly generated query must attend over all preceding keys and values. A key–value (KV) cache stores the projected key and value tensors from earlier steps, allowing new queries to attend over the prefix without recomputing historical activations. In the nonparametric regression framework of Chapter 14, the KV cache serves as the estimator’s dataset: an incoming query at step \(t\) reads a table that grows with \(t\), but earlier rows no longer require recomputation. In contrast, our sampler re-evaluates a sliding 100-character window with absolute slot encodings: when the window slides, every retained token shifts to a new slot index, changing its input representation. Caching past the window limit therefore requires a new positional or memory policy, not a drop-in speedup. Appendix C separates KV caching from FlashAttention’s I/O-aware kernel scheduling.
Self-attention leaves position and visibility to the modeler. Chapter 18 modifies visibility itself, while Chapter 19 explores what occurs when global routing trades away an image model’s locality bias.
Varying the kernel, predictor class, or update rule within this regression perspective yields alternative memory formulations. The following interlude contrasts the growing KV cache with finite sufficient statistics and delta updates.
Readers seeking deeper mathematical analysis of these architectures will find kernel geometry, exact I/O-aware algorithms, parallel recurrence, and feature-learning regimes in Shakeri (2026), “Beyond This Volume”.
Close the book for one minute and reconstruct the Transformer block.
- Without positional signals or a mask, why is self-attention permutation equivariant?
- What distinct roles do the identity path, the attention branch, and the FFN branch play in the residual stream?
- What structural properties change when a causal mask restricts visibility?
16.8 Okay, so: the Transformer routes, then transforms
- Self-attention reuses the scaled dot-product operator within a single sequence. Queries, keys, and values \(\matr{Q},\matr{K},\matr{V}\) all derive from the same input \(\matr{X}\), and one learned comparison rule is shared across every permitted query–key pair. All sequence positions can be evaluated in parallel during training, while autoregressive generation remains sequential.
- Without positional signals or a mask, self-attention is permutation equivariant, not invariant. \(\operatorname{SA}(\matr{P}\matr{X})=\matr{P}\operatorname{SA}(\matr{X})\). Sinusoidal clocks supply the order that global routing lacks (and that the convolutions of Chapter 9 built in), while sine–cosine coordinate pairs express relative displacements as planar rotations.
- Multi-head attention routes in parallel through partitioned subspaces. The computation partitions \((B,n,d)\to(B,N_h,n,D_h)\), scales scores by \(\sqrt{D_h}\), forms \((B,N_h,n,n)\) routing weights, concatenates, and projects. At fixed \(d\), the four projection matrices hold \(4d^2\) weights regardless of head count \(N_h\).
- The causal mask defines visibility, not computational cost. Future compatibility scores are set to \(-\infty\) prior to softmax. The underlying operator remains quadratic in sequence length.
- The block alternates routing across positions and transformation within them. The attention and feedforward sublayers both add corrections to the residual stream of Chapter 10, and layer normalization standardizes the features of each token independently.
- Position lowers held-out loss in this controlled benchmark. Explicit positional encodings reduce held-out loss from 2.3405 to 1.9190. Under this matched protocol, the compact LSTM has a slightly lower held-out loss than the small Transformer (1.8881 versus 1.9190). An architecture changes inductive bias but does not guarantee lower loss in every scale and data regime.
Sources and further reading
- Vaswani et al., Attention Is All You Need: multi-head attention, sinusoidal position, and the original post-LayerNorm encoder–decoder.
- Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding: rotates queries and keys so their positional interaction is expressed through relative offset.
- Ba, Kiros, and Hinton, Layer Normalization: normalization within one example and identical train/evaluation computation.
- Zhang and Sennrich, Root Mean Square Layer Normalization: RMSNorm’s scale-only normalization and empirical study.
- Xiong et al., On Layer Normalization in the Transformer Architecture: a qualified comparison of pre- and post-LayerNorm optimization: post-LayerNorm’s gradient growth near the output layers at initialization, and pre-LayerNorm training without warmup.
- Dong, Cordonnier, and Loukas, Attention Is Not All You Need: Pure Attention Loses Rank Doubly Exponentially with Depth: bounds the distance of a pure-attention stack’s output from a common row. For small projection norms and clustered tokens the bound shrinks doubly exponentially with depth. Residual connections remove this forced collapse, and FFNs can slow it.
- Geva et al., Transformer Feed-Forward Layers Are Key-Value Memories: empirical evidence behind the associative-memory interpretation of FFNs.
- Haviv et al., Transformer Language Models without Positional Encodings Still Learn Positional Information: causal language models trained without positional encodings come close to models with them in held-out loss and still carry each token’s approximate position, and the authors conjecture that the causal mask supplies it.
- Jain and Wallace, Attention Is Not Explanation: an important limit on reading attention maps as explanations.
- Tsai et al., Transformer Dissection: An Unified Understanding for Transformer’s Attention via the Lens of Kernel: attention written as a kernel smoother, with a comparison of kernel choices that includes a symmetric kernel made by tying the query and key projections.
- Holtzman et al., The Curious Case of Neural Text Degeneration: nucleus sampling and the distinction between likely continuations and useful generation behavior.
- Park et al., Grammar-Aligned Decoding: shows that a sampler that forbids, at each step, every token that cannot lead to a grammatical output can return grammatical outputs at rates not proportional to the model’s probabilities, as in Exercise 9 of Chapter 13.
- Shakeri, Deep Learning: Making It Trainable (2026), “Beyond This Volume”: kernel geometry, exact I/O-aware algorithms, parallel recurrence, and feature-learning regimes.
Exercises
- (Pencil.) Starting from \(\matr{Q}'=\matr{P}\matr{Q}\), \(\matr{K}'=\matr{P}\matr{K}\), and \(\matr{V}'=\matr{P}\matr{V}\), prove each step of \(\operatorname{SA}(\matr{P}\matr{X})=\matr{P}\operatorname{SA}(\matr{X})\) for self-attention without positional signals or a mask. Then show that mean-pooling the token outputs produces a permutation-invariant sequence representation.
- (Pencil.) For width \(d=512\) and \(N_h=8\), write every tensor shape in multi-head attention for \(B=32\) and \(n=100\). Count the weights in \(\matr{W}_Q,\matr{W}_K,\matr{W}_V,\matr{W}_O\). Repeat for \(N_h=16\) and explain which dimensions change while the leading parameter count does not.
- (Code.) Deliberately transpose the causal mask in Figure 16.6, then design an assertion that identifies the first leaked query–key pair. Next set forbidden probabilities to zero after softmax and measure the row-sum error.
- (Code.) Replace the fixed sinusoidal table with a learned \(\text{Embedding}(100,d)\) while matching the initial weights of all shared parameters and preserving the window schedule. State how the new position table is initialized. Compare held-out loss. Then extend the sinusoidal buffer by evaluating its formula beyond position 99, and propose an explicit extension rule for the learned table before testing either model on a longer context. Which design has a natural extension, and which has to invent one?
- (Code.) Aggregate learned attention by relative offset across the held-out tail rather than naming heads from one prompt. Report a distribution for every head and block. Then perturb the highest-weight key’s value vector and measure the logit change. Explain why routing weight and causal influence need not rank tokens identically.
Tying \(\matr{W}_Q=\matr{W}_K\) constrains the matrix to be symmetric and positive semidefinite. In the sequence experiments of Tsai et al., parameter tying yielded comparable empirical performance while reducing parameter count.↩︎