def softmax_weights(d, scale, num_keys=64, num_queries=2048):
"""Log-weights of random queries over random keys, scores scaled."""
q = torch.randn(num_queries, d)
keys = torch.randn(num_queries, num_keys, d)
scores = (keys @ q[..., None]).squeeze(-1) * scale
return F.log_softmax(scores, dim=-1)
def entropy(log_alpha):
return -(log_alpha.exp() * log_alpha).sum(-1).mean().item()
def largest_weight(log_alpha):
return log_alpha.exp().max(-1).values.mean().item()
def jacobian_norm(log_alpha):
"""Mean Frobenius norm of the Jacobian diag(alpha) - alpha alpha^T."""
alpha = log_alpha.exp()
J = torch.diag_embed(alpha) - alpha[..., :, None] * alpha[..., None, :]
return torch.linalg.matrix_norm(J).mean().item()10.2 Attention Scoring and Masking
In Section 10.1.2, attention weights were determined by a fixed Gaussian kernel over Euclidean distance in input space. In a sequence model, however, similarity must be learned—a verb seeking its subject needs the word playing that syntactic role, not the closest raw embedding. Turning soft lookup into a trainable network layer raises two questions: which scoring function \(a(\mathbf{q}, \mathbf{k})\) should the layer compute, and which query–key pairs should be excluded from the lookup?
Because a head reading \(n = 1{,}024\) tokens evaluates \(n^2 = 1{,}048{,}576\) query–key pairs per sequence, the score must be inexpensive and map cleanly onto matrix multiplication hardware. Furthermore, invalid pairs—such as padding tokens in a variable-length minibatch or future tokens in an autoregressive language model—must be zeroed out before normalization.
This section derives scaled dot-product attention (\(\mathbf{q}^\top\mathbf{k}/\sqrt{d}\)), explains how the \(1/\sqrt{d}\) factor prevents softmax saturation at initialization, implements boolean masking and mask composition, and demonstrates how learned attention recovers sequence alignments from output supervision alone.
10.2.1 Dot-Product Attention
Expanding the negative squared distance of the unit-bandwidth Gaussian kernel from Section 10.1.2 reveals an inner product plus two squared norms:
\[ a(\mathbf{q}, \mathbf{k}_i) = -\frac{1}{2} \|\mathbf{q} - \mathbf{k}_i\|^2 = \mathbf{q}^\top \mathbf{k}_i -\frac{1}{2} \|\mathbf{k}_i\|^2 -\frac{1}{2} \|\mathbf{q}\|^2. \tag{10.2.1}\]
Because \(-\tfrac{1}{2}\|\mathbf{q}\|^2\) is constant across all keys \(i\), the softmax normalization cancels it out. If all keys have equal norm, \(-\tfrac{1}{2}\|\mathbf{k}_i\|^2\) cancels as well. Dropping both norm terms even when key norms vary yields the dot-product score \(\mathbf{q}^\top \mathbf{k}_i\). Unlike the Gaussian kernel, which penalizes large \(\|\mathbf{k}_i\|\), the dot product allows a key’s norm to act as a multiplicative prior: a longer key attracts larger weight from every query aligned with it (Exercise 1c).
Early neural machine translation models instead used a one-hidden-layer MLP known as additive attention (Bahdanau et al. 2015):
\[a(\mathbf{q}, \mathbf{k}) = \mathbf{w}_v^\top \tanh(\mathbf{W}_q \mathbf{q} + \mathbf{W}_k \mathbf{k}) \in \mathbb{R}, \tag{10.2.2}\]
with learned matrices \(\mathbf{W}_q \in \mathbb{R}^{r \times d_q}\), \(\mathbf{W}_k \in \mathbb{R}^{r \times d_k}\), and weight vector \(\mathbf{w}_v \in \mathbb{R}^{r}\). Although additive and dot-product scoring have similar asymptotic operation counts (\(O(nmr)\) versus \(O(nmd)\) for \(n\) queries and \(m\) keys), additive attention must materialize an \(n \times m \times r\) tensor of hidden activations and apply \(\tanh\) elementwise. Dot-product attention computes all \(n \times m\) scores in a single matrix multiplication \(\mathbf{Q}\mathbf{K}^\top\). A bilinear score is less general than an MLP, but the loss is of no practical consequence when queries and keys are themselves produced by learned projections \((\mathbf{W}_q \mathbf{q})^\top (\mathbf{W}_k \mathbf{k})\) (see also Exercise 6).
One crucial scaling factor remains. Suppose the coordinates of \(\mathbf{q}, \mathbf{k} \in \mathbb{R}^d\) are independent random variables with mean \(0\) and variance \(1\). Then each term \(q_j k_j\) has mean \(0\) and variance \(1\), so the sum \(\mathbf{q}^\top \mathbf{k}\) has mean \(0\) and variance \(d\) (standard deviation \(8\) at \(d = 64\)). To prevent large dot products from pushing the softmax into regions of vanishing gradients at large \(d\), Vaswani et al. (2017) divide by \(\sqrt{d}\) to restore unit variance, giving the scaled dot-product score:
\[a(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i / \sqrt{d}. \tag{10.2.3}\]
Here \(1/\sqrt{d}\) plays the role of the inverse temperature \(1/\sigma^2\) in Section 10.1.2, calibrated automatically to the vector width \(d\). Softmax normalization then yields the attention weights
\[\alpha(\mathbf{q}, \mathbf{k}_i) = \mathrm{softmax}(a(\mathbf{q}, \mathbf{k}_i)) = \frac{\exp(\mathbf{q}^\top \mathbf{k}_i / \sqrt{d})}{\sum_{j=1}^m \exp(\mathbf{q}^\top \mathbf{k}_j / \sqrt{d})}, \tag{10.2.4}\]
and the output \(\sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i)\, \mathbf{v}_i\).
10.2.1.1 A Worked Example
Let \(d = 4\) (so \(1/\sqrt{d} = 1/2\)) with two queries and three key–value pairs:
\[ \begin{aligned} \mathbf{q}_1 &= (2, 2, 0, 0), & \mathbf{k}_1 &= (1, 1, 0, 0), & \mathbf{v}_1 &= (1, 0),\\ \mathbf{q}_2 &= (0, 0, 2, 0), & \mathbf{k}_2 &= (0, 0, 1, 1), & \mathbf{v}_2 &= (0, 1),\\ & & \mathbf{k}_3 &= (0, 0, 1, -1), & \mathbf{v}_3 &= (1, 1). \end{aligned} \]
- Scores: \(\mathbf{q}_1\) has raw dot products \((4, 0, 0)\) with the three keys; \(\mathbf{q}_2\) has \((0, 2, 2)\).
- Scaling: Dividing by \(\sqrt{4} = 2\) gives \((2, 0, 0)\) and \((0, 1, 1)\).
- Softmax: \(\mathbf{q}_1\) assigns weights \(\big(e^2/(e^2 + 2),\, 1/(e^2 + 2),\, 1/(e^2 + 2)\big) \approx (0.787, 0.107, 0.107)\); \(\mathbf{q}_2\) assigns \(\big(1/(1 + 2e),\, e/(1 + 2e),\, e/(1 + 2e)\big) \approx (0.155, 0.422, 0.422)\).
- Weighted sum: \(\mathbf{o}_1 = 0.787\,\mathbf{v}_1 + 0.107\,\mathbf{v}_2 + 0.107\,\mathbf{v}_3 \approx (0.893, 0.213)\) and \(\mathbf{o}_2 \approx (0.578, 0.845)\).
Even an orthogonal key receives nonzero softmax weight (\(0.107\)), and keys that tie on the active coordinates of a query (\(\mathbf{k}_2\) and \(\mathbf{k}_3\) under \(\mathbf{q}_2\)) split the remaining weight equally. Omitting the \(1/2\) scaling factor would sharpen \(\mathbf{q}_1\)’s weight on \(\mathbf{k}_1\) from \(0.787\) to \(e^4/(e^4 + 2) \approx 0.96\).
10.2.1.2 Score Variance and the \(1/\sqrt{d}\) Factor
When one score exceeds all others by a wide margin, the weight vector \(\boldsymbol{\alpha}\) approaches a one-hot vector and the softmax saturates. The Jacobian of \(\boldsymbol{\alpha} = \mathrm{softmax}(\mathbf{a})\),
\[ \frac{\partial \boldsymbol{\alpha}}{\partial \mathbf{a}} = \mathrm{diag}(\boldsymbol{\alpha}) - \boldsymbol{\alpha} \boldsymbol{\alpha}^\top, \tag{10.2.5}\]
converges to the zero matrix as \(\boldsymbol{\alpha}\) becomes one-hot (Exercise 2). In a saturated row, backpropagated gradients with respect to the scores vanish, making it difficult for unselected keys to gain weight during training.
We can measure this effect on random standard normal queries (\(2{,}048\) queries, each attending over \(64\) random keys) across dimensions \(d \in \{4, \ldots, 512\}\), comparing unscaled scores against scores scaled by \(1/\sqrt{d}\). Uniform weights over \(64\) keys have entropy \(\log 64 \approx 4.16\) nats, whereas a one-hot distribution has entropy \(0\).
def softmax_weights(d, scale, num_keys=64, num_queries=2048):
"""Log-weights of random queries over random keys, scores scaled."""
q = jax.random.normal(d2l.get_key(), (num_queries, d))
keys = jax.random.normal(d2l.get_key(), (num_queries, num_keys, d))
scores = (keys @ q[..., None]).squeeze(-1) * scale
return jax.nn.log_softmax(scores, axis=-1)
def entropy(log_alpha):
return float(-(jnp.exp(log_alpha) * log_alpha).sum(-1).mean())
def largest_weight(log_alpha):
return float(jnp.exp(log_alpha).max(-1).mean())
def jacobian_norm(log_alpha):
"""Mean Frobenius norm of the Jacobian diag(alpha) - alpha alpha^T."""
alpha = jnp.exp(log_alpha)
J = (alpha[..., None] * jnp.eye(alpha.shape[-1])
- alpha[..., :, None] * alpha[..., None, :])
return float(jnp.linalg.norm(J, axis=(-2, -1)).mean())Sweeping head width \(d\) from \(4\) to \(512\) on a logarithmic axis shows that unscaled dot-product attention suffers rapid entropy collapse as \(d\) grows, whereas scaling by \(1/\sqrt{d}\) holds the attention entropy flat across all widths:
ds = [2**k for k in range(2, 10)]
entropies = [[entropy(softmax_weights(d, 1.0)) for d in ds],
[entropy(softmax_weights(d, 1 / math.sqrt(d))) for d in ds]]
d2l.plot(ds, entropies, 'width d', 'entropy (nats)',
legend=['unscaled', 'scaled by 1/sqrt(d)'], xscale='log')ds = [2**k for k in range(2, 10)]
entropies = [[entropy(softmax_weights(d, 1.0)) for d in ds],
[entropy(softmax_weights(d, 1 / math.sqrt(d))) for d in ds]]
d2l.plot(ds, entropies, 'width d', 'entropy (nats)',
legend=['unscaled', 'scaled by 1/sqrt(d)'], xscale='log')The table below reports the entropy, mean maximum weight, and mean Frobenius norm of the softmax Jacobian at five widths.
print(' entropy (nats) largest weight Jacobian norm')
print(' d' + ' unscaled scaled' * 3)
for d in (4, 16, 64, 128, 512):
stats = [(entropy(la), largest_weight(la), jacobian_norm(la))
for la in (softmax_weights(d, 1.0),
softmax_weights(d, 1 / math.sqrt(d)))]
print(f'{d:3d}' + ''.join(f' {u:8.3f} {s:6.3f}'
for u, s in zip(*stats))) entropy (nats) largest weight Jacobian norm
d unscaled scaled unscaled scaled unscaled scaled
4 2.782 3.701 0.285 0.105 0.256 0.180
16 1.388 3.691 0.578 0.105 0.295 0.182
64 0.584 3.682 0.791 0.108 0.209 0.184
128 0.372 3.683 0.862 0.107 0.158 0.184
512 0.182 3.681 0.926 0.108 0.094 0.184
print(' entropy (nats) largest weight Jacobian norm')
print(' d' + ' unscaled scaled' * 3)
for d in (4, 16, 64, 128, 512):
stats = [(entropy(la), largest_weight(la), jacobian_norm(la))
for la in (softmax_weights(d, 1.0),
softmax_weights(d, 1 / math.sqrt(d)))]
print(f'{d:3d}' + ''.join(f' {u:8.3f} {s:6.3f}'
for u, s in zip(*stats))) entropy (nats) largest weight Jacobian norm
d unscaled scaled unscaled scaled unscaled scaled
4 2.819 3.706 0.273 0.104 0.257 0.180
16 1.367 3.682 0.583 0.109 0.293 0.183
64 0.598 3.686 0.786 0.106 0.214 0.183
128 0.383 3.687 0.855 0.106 0.163 0.183
512 0.180 3.685 0.928 0.108 0.091 0.184
With \(1/\sqrt{d}\) scaling, the entropy stays near \(\log 64 - \tfrac{1}{2} \approx 3.66\) nats across all widths (Exercise 5), with maximum weight \(\approx 0.11\) and Jacobian norm \(\approx 0.18\). Without scaling, score standard deviation grows as \(\sqrt{d}\): by \(d = 512\), entropy collapses to \(\approx 0.2\) nats, the top key takes over \(90\%\) of the weight at random initialization, and the Jacobian norm falls by half. Scaling by \(1/\sqrt{d}\) decouples initial softmax sharpness from head width while leaving learned projections free to sharpen weights during training (once queries and keys align, dot products grow as \(O(d)\), motivating the \(1/d\) scaling in maximal update parametrization, Section 9.9). Many recent models do not leave the temperature to the projections at all: they normalize queries and keys to unit length and learn the score scale as a separate parameter, a design called QK-norm that we meet in Section 11.1.
The scaling fixes the sharpness against the width \(d\) but not against the number of keys \(m\). With unit-variance scores the entropy is about \(\log m - \tfrac{1}{2}\), so the weights spread over roughly \(0.6\,m\) keys: a fixed fraction of the context, however long it is. A lookup is diluted in the same way. If the matching key leads each of the other \(m - 1\) keys by a score gap \(g\), it receives weight \(1/(1 + (m-1)e^{-g})\). A gap of \(g = 9\) gives about \(0.9\) among \(1{,}000\) keys and less than \(0.1\) among \(100{,}000\). To stay sharp, the gap must grow like \(\log m\). A model trained at one context length therefore attends more diffusely at a longer one, which is why some models raise the score scale with the length of the context (Section 10.8).
10.2.2 Masking
Two standard conditions exclude specific query–key pairs from attention:
- Padding: When sequences of unequal lengths are padded with
<blank>tokens to form a minibatch, no query should attend to padding positions. - Causality: In autoregressive language modeling, the query at position \(t\) may attend only to keys at positions \(j \le t\).
Both constraints are represented by a boolean mask tensor that is True where query \(i\) is permitted to attend to key \(j\).
10.2.2.1 The Masked Softmax Operation
To preserve dense tensor shapes, masked softmax replaces excluded scores (~mask) with a large negative number before calling softmax. The choice of fill value requires care across floating-point formats:
- A hardcoded constant such as \(-10^6\) overflows float16 (whose maximum finite magnitude is \(65{,}504\)).
- Literal \(-\infty\) produces
NaNwhenever an entire query row is masked out, because the numerically stable softmax subtracts the row maximum \(-\infty\) to form \(-\infty - (-\infty) = \mathrm{NaN}\). - Using the most negative finite value of the tensor’s data type (
finfo(dtype).min) underflows excluded exponentials to exact zero in float16, bfloat16, and float32 without producingNaN. For any query row where all keys are masked out (~mask.any(-1)),masked_softmaxexplicitly zeroes the resulting weights.
def masked_softmax(X, mask=None):
"""Softmax over the last axis with zero weight where mask is False."""
if mask is None:
return F.softmax(X, dim=-1)
# Most negative finite value: zero weight at any precision, no NaN
X = X.masked_fill(~mask, torch.finfo(X.dtype).min)
weights = F.softmax(X, dim=-1)
# A query without any valid key gets zero weights, not a uniform row
return torch.where(mask.any(-1, keepdim=True), weights, 0.0)def masked_softmax(X, mask=None):
"""Softmax over the last axis with zero weight where mask is False."""
if mask is None:
return jax.nn.softmax(X, axis=-1)
# Most negative finite value: zero weight at any precision, no NaN
X = jnp.where(mask, X, jnp.finfo(X.dtype).min)
weights = jax.nn.softmax(X, axis=-1)
# A query without any valid key gets zero weights, not a uniform row
return jnp.where(mask.any(-1, keepdims=True), weights, 0.0)Because mask only needs to broadcast against X, a padding mask shared across all queries in a sequence can be stored with shape (batch, 1, keys).
def padding_mask(valid_lens, num_keys):
"""Boolean mask that is True for the first valid_lens keys."""
# valid_lens of shape (batch,) gives (batch, 1, keys); per-query
# lengths of shape (batch, queries) give (batch, queries, keys)
if valid_lens.dim() == 1:
valid_lens = valid_lens[:, None]
keys = torch.arange(num_keys, device=valid_lens.device)
return keys < valid_lens[..., None]def padding_mask(valid_lens, num_keys):
"""Boolean mask that is True for the first valid_lens keys."""
# valid_lens of shape (batch,) gives (batch, 1, keys); per-query
# lengths of shape (batch, queries) give (batch, queries, keys)
if valid_lens.ndim == 1:
valid_lens = valid_lens[:, None]
return jnp.arange(num_keys) < valid_lens[..., None]On a batch of two zero-score sequences of length \(4\) with valid lengths \(2\) and \(3\), masked_softmax distributes weight uniformly over the valid prefix of each row:
masked_softmax(torch.zeros(2, 2, 4), padding_mask(torch.tensor([2, 3]), 4))tensor([[[0.5000, 0.5000, 0.0000, 0.0000],
[0.5000, 0.5000, 0.0000, 0.0000]],
[[0.3333, 0.3333, 0.3333, 0.0000],
[0.3333, 0.3333, 0.3333, 0.0000]]])
masked_softmax(jnp.zeros((2, 2, 4)), padding_mask(jnp.array([2, 3]), 4))Array([[[0.5 , 0.5 , 0. , 0. ],
[0.5 , 0.5 , 0. , 0. ]],
[[0.33333334, 0.33333334, 0.33333334, 0. ],
[0.33333334, 0.33333334, 0.33333334, 0. ]]], dtype=float32)
10.2.2.2 Causal Masking
A causal mask allows query \(i\) to attend to key \(j\) only if \(j \le i\), forming a lower-triangular matrix that excludes \(n(n-1)/2\) of the \(n^2\) pairs (\(523{,}776\) pairs at \(n = 1{,}024\)). When num_queries < num_keys (as during cached generation), causal_mask aligns the queries with the final positions of the sequence.
def causal_mask(num_queries, num_keys=None, device=None):
"""Boolean (queries, keys) mask, True where a query may see a key."""
# Queries are the last positions, as when new tokens attend to a
# cache: query i sees key j if j <= i + num_keys - num_queries
num_keys = num_queries if num_keys is None else num_keys
i = torch.arange(num_queries, device=device)[:, None]
j = torch.arange(num_keys, device=device)[None, :]
return j <= i + (num_keys - num_queries)def causal_mask(num_queries, num_keys=None):
"""Boolean (queries, keys) mask, True where a query may see a key."""
# Queries are the last positions, as when new tokens attend to a
# cache: query i sees key j if j <= i + num_keys - num_queries
num_keys = num_queries if num_keys is None else num_keys
i = jnp.arange(num_queries)[:, None]
j = jnp.arange(num_keys)[None, :]
return j <= i + (num_keys - num_queries)10.2.2.3 Composing Masks
When multiple constraints apply simultaneously, a pair is valid only if every constraint permits it, so boolean masks compose via logical AND (&) under broadcasting (Figure 10.2.1).
Combining a padding mask (valid lengths \(6\) and \(3\)) with a causal mask on equal scores produces a full causal triangle for the first sequence and truncates all rows of the second sequence at key \(3\):
n = 6
padding = padding_mask(torch.tensor([6, 3]), n) # (batch, 1, key)
causal = causal_mask(n) # (query, key)
mask = padding & causal # (batch, query, key)
weights = masked_softmax(torch.zeros(2, n, n), mask) # Equal scores
d2l.show_heatmaps(weights[None], xlabel='keys', ylabel='queries',
titles=['valid length 6', 'valid length 3'],
figsize=(5, 2.5))n = 6
padding = padding_mask(jnp.array([6, 3]), n) # (batch, 1, key)
causal = causal_mask(n) # (query, key)
mask = padding & causal # (batch, query, key)
weights = masked_softmax(jnp.zeros((2, n, n)), mask) # Equal scores
d2l.show_heatmaps(weights[None], xlabel='keys', ylabel='queries',
titles=['valid length 6', 'valid length 3'],
figsize=(5, 2.5))In the shorter sequence, queries \(4\) to \(6\) are padding themselves, yet each still has valid keys, because a causal triangle always reaches back to key \(1\). This is a property of the shape, not of AND. Had we combined the padding mask with a sliding window, which lets each query see only its few most recent keys, a query whose window lies entirely inside the padding would keep no valid key at all. Masks that are harmless alone can leave a row empty together, and this is the case that masked_softmax zeroes.
The same boolean algebra handles packed sequences, where multiple short documents are concatenated into a single row to avoid padding overhead. ANDing a same-document indicator doc[:, None] == doc[None, :] with causal_mask produces a block-diagonal causal mask:
doc = torch.tensor([0, 0, 0, 1, 1, 2]) # Document of each position
same_doc = doc[:, None] == doc[None, :]
packed = same_doc & causal_mask(6)
d2l.show_heatmaps(packed.float()[None, None], xlabel='keys',
ylabel='queries', cbar=False)doc = jnp.array([0, 0, 0, 1, 1, 2]) # Document of each position
same_doc = doc[:, None] == doc[None, :]
packed = same_doc & causal_mask(6)
d2l.show_heatmaps(packed.astype(jnp.float32)[None, None], xlabel='keys',
ylabel='queries', cbar=False)10.2.3 Attention for a Minibatch
Stacking \(n\) queries into \(\mathbf{Q} \in \mathbb{R}^{n \times d}\), \(m\) keys into \(\mathbf{K} \in \mathbb{R}^{m \times d}\), and \(m\) values into \(\mathbf{V} \in \mathbb{R}^{m \times d_v}\) expresses scaled dot-product attention as two matrix multiplications and a row-wise softmax (Figure 10.2.2):
\[\mathrm{softmax}\left(\frac{\mathbf{Q} \mathbf{K}^\top}{\sqrt{d}}\right) \mathbf{V} \in \mathbb{R}^{n \times d_v}. \tag{10.2.6}\]
For batched inputs with leading batch (and head) axes, the batched matrix product @ operates over the last two dimensions and broadcasts leading axes automatically. For one head of GPT-2 small (\(n = m = 1{,}024\), \(d = d_v =
64\)), the score matrix holds \(1{,}048{,}576\) floats (4 MiB in fp32) and the two products require \(4n^2 d \approx 0.27\) GFLOPs—both quadratic in \(n\).
10.2.3.1 The DotProductAttention Class
DotProductAttention implements Equation 10.2.6 with optional masking and attention-weight dropout (default \(0.0\)), storing the most recent attention weights in attention_weights for inspection.
class DotProductAttention(nn.Module):
"""Scaled dot-product attention over the last two axes."""
def __init__(self, dropout=0.0):
super().__init__()
self.dropout = nn.Dropout(dropout)
self.attention_weights = None
# Leading axes (batch, and heads if present) are carried along.
# Shape of queries: (..., no. of queries, d)
# Shape of keys: (..., no. of key-value pairs, d)
# Shape of values: (..., no. of key-value pairs, value dimension)
# mask: boolean, broadcastable to (..., no. of queries, no. of keys),
# True where a query may attend to a key
def forward(self, queries, keys, values, mask=None):
d = queries.shape[-1]
scores = queries @ keys.transpose(-2, -1) / math.sqrt(d)
self.attention_weights = masked_softmax(scores, mask)
return self.dropout(self.attention_weights) @ valuesclass DotProductAttention(nnx.Module):
"""Scaled dot-product attention over the last two axes."""
def __init__(self, dropout=0.0, *, rngs=None):
# rngs is needed only to draw dropout masks (dropout > 0)
self.dropout = nnx.Dropout(dropout, rngs=rngs)
# A Variable, so that views of the module (nnx.view) share it
self.last_weights = nnx.Intermediate(None)
# Leading axes (batch, and heads if present) are carried along.
# Shape of queries: (..., no. of queries, d)
# Shape of keys: (..., no. of key-value pairs, d)
# Shape of values: (..., no. of key-value pairs, value dimension)
# mask: boolean, broadcastable to (..., no. of queries, no. of keys),
# True where a query may attend to a key
def __call__(self, queries, keys, values, mask=None):
d = queries.shape[-1]
scores = queries @ keys.swapaxes(-2, -1) / math.sqrt(d)
weights = masked_softmax(scores, mask)
if not isinstance(weights, jax.core.Tracer):
# Record the weights of eager calls for inspection; inside
# jit-compiled code skip it, so the module state keeps a
# fixed structure and the compiled step is reused
self.last_weights.set_value(weights)
return self.dropout(weights) @ values
@property
def attention_weights(self):
"""Weights of the last eager call: (..., queries, keys)."""
return self.last_weights.get_value()Evaluating DotProductAttention on the vectors from Section 10.2.1.1 reproduces our hand calculation:
queries = d2l.tensor([[[2.0, 2, 0, 0], [0, 0, 2, 0]]]) # (1, 2, 4)
keys = d2l.tensor([[[1.0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, -1]]]) # (1, 3, 4)
values = d2l.tensor([[[1.0, 0], [0, 1], [1, 1]]]) # (1, 3, 2)
attention = DotProductAttention()
output = attention(queries, keys, values)
print('weights:', np.asarray(attention.attention_weights[0]).round(3))
print('output: ', np.asarray(output[0]).round(3))weights: [[0.787 0.107 0.107]
[0.155 0.422 0.422]]
output: [[0.893 0.213]
[0.578 0.845]]
queries = d2l.tensor([[[2.0, 2, 0, 0], [0, 0, 2, 0]]]) # (1, 2, 4)
keys = d2l.tensor([[[1.0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, -1]]]) # (1, 3, 4)
values = d2l.tensor([[[1.0, 0], [0, 1], [1, 1]]]) # (1, 3, 2)
attention = DotProductAttention()
output = attention(queries, keys, values)
print('weights:', np.asarray(attention.attention_weights[0]).round(3))
print('output: ', np.asarray(output[0]).round(3))weights: [[0.787 0.107 0.107]
[0.155 0.422 0.422]]
output: [[0.893 0.213]
[0.578 0.845]]
10.2.3.2 Matching the Letters of Two Words
To see what unprojected content matching can and cannot distinguish, assign each distinct letter in "attention" and "translation" a random standard normal embedding \(\mathbf{e} \in \mathbb{R}^{32}\) and let the letters of "attention" query the letters of "translation". Identical letters have expected scaled score \(\mathbb{E}[\|\mathbf{e}\|^2]/\sqrt{32} = \sqrt{32}
\approx 5.7\), whereas distinct letters have expected score \(0\) and unit variance.
words = 'attention', 'translation'
letters = sorted(set(''.join(words)))
emb = torch.randn(len(letters), 32)
queries, keys = (emb[[letters.index(c) for c in w]][None] for w in words)
attention = DotProductAttention()
attention(queries, keys, keys)
d2l.show_heatmaps(attention.attention_weights[None], xlabel='keys',
ylabel='queries', figsize=(4, 3.5), cmap='Blues',
xticklabels=words[1], yticklabels=words[0])words = 'attention', 'translation'
letters = sorted(set(''.join(words)))
emb = jax.random.normal(d2l.get_key(), (len(letters), 32))
queries, keys = (emb[jnp.array([letters.index(c) for c in w])][None]
for w in words)
attention = DotProductAttention()
attention(queries, keys, keys)
d2l.show_heatmaps(attention.attention_weights[None], xlabel='keys',
ylabel='queries', figsize=(4, 3.5), cmap='Blues',
xticklabels=words[1], yticklabels=words[0])Three behaviors stand out:
- Unique matches (
i,o) concentrate nearly all weight on their partner. - Repeated matches (
a,t,n) split their weight equally across every occurrence of the letter in"translation", because content-only keys carry no positional identity. - Unmatched queries (
e) spread their probability mass across random keys, because softmax weights must sum to one even when no relevant key exists (in trained language models, the initial token often absorbs such unused mass as an attention sink, (Xiao et al. 2024)).
10.2.4 Attention as Learned Alignment
Learned attention originated in neural machine translation (Bahdanau et al. 2015) to relieve the fixed-vector bottleneck of sequence-to-sequence RNNs (Section 12.2). At each decoding step, the decoder queried all encoder states, and the learned attention weights spontaneously recovered word alignments between source and target languages—a monotonic diagonal with off-diagonal crossings where word order differed (e.g., English “black cat” versus French “chat noir”).
We can observe alignment emergence in a minimal model ToyAligner. Source sequences consist of \(8\) tokens drawn from a vocabulary of size \(16\), and the target sequence applies a fixed permutation \(\pi\) that swaps positions \(3\) and \(4\). Each output position \(j\) has a learned query vector; each source key is a linear projection of the concatenated one-hot token and one-hot source position; and values are the one-hot source tokens.
class ToyAligner(nn.Module):
"""One learned query per output position; keys from token and position."""
def __init__(self, seq_len=8, vocab_size=16, d=16):
super().__init__()
self.vocab_size, n_in = vocab_size, vocab_size + seq_len
self.queries = nn.Parameter(torch.randn(seq_len, d))
self.W_k = nn.Parameter(torch.randn(n_in, d) / math.sqrt(n_in))
self.attention = DotProductAttention()
def forward(self, X):
# X: (batch, seq_len) token ids; the values are their one-hot vectors
tokens = F.one_hot(X, self.vocab_size).float()
eye = torch.eye(X.shape[1], device=X.device)
positions = eye.expand(len(X), -1, -1)
keys = torch.cat((tokens, positions), -1) @ self.W_k
# The queries broadcast over the batch: (batch, seq_len, vocab_size)
return self.attention(self.queries, keys, tokens)class ToyAligner(nnx.Module):
"""One learned query per output position; keys from token and position."""
def __init__(self, seq_len=8, vocab_size=16, d=16, *, rngs):
self.vocab_size, n_in = vocab_size, vocab_size + seq_len
self.queries = nnx.Param(
jax.random.normal(rngs.params(), (seq_len, d)))
self.W_k = nnx.Param(jax.random.normal(rngs.params(), (n_in, d))
/ math.sqrt(n_in))
self.attention = DotProductAttention()
def __call__(self, X):
# X: (batch, seq_len) token ids; the values are their one-hot vectors
tokens = jax.nn.one_hot(X, self.vocab_size)
n = X.shape[1]
positions = jnp.broadcast_to(jnp.eye(n), (len(X), n, n))
keys = jnp.concatenate((tokens, positions), -1) @ self.W_k
# The queries broadcast over the batch: (batch, seq_len, vocab_size)
return self.attention(self.queries, keys, tokens)We train ToyAligner with Adam for 100 steps by minimizing the negative log-likelihood of the permuted target tokens.
perm = torch.tensor([0, 1, 2, 4, 3, 5, 6, 7]) # Output j copies source perm[j]
def align_data(n, seq_len=8, vocab_size=16):
X = torch.randint(0, vocab_size, (n, seq_len))
return X, X[:, perm]
def train_aligner(num_steps=100):
model = ToyAligner()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)
for _ in range(num_steps):
X, Y = align_data(128)
loss = -model(X).gather(-1, Y[..., None]).log().mean()
optimizer.zero_grad()
loss.backward()
optimizer.step()
return modelperm = jnp.array([0, 1, 2, 4, 3, 5, 6, 7]) # Output j copies source perm[j]
def align_data(key, n, seq_len=8, vocab_size=16):
X = jax.random.randint(key, (n, seq_len), 0, vocab_size)
return X, X[:, perm]
@nnx.jit
def align_step(model, optimizer, key):
X, Y = align_data(key, 128)
loss = lambda model: -jnp.log(
jnp.take_along_axis(model(X), Y[..., None], -1)).mean()
optimizer.update(model, nnx.grad(loss)(model))
def train_aligner(num_steps=100):
model = ToyAligner(rngs=nnx.Rngs(d2l.get_key()))
optimizer = nnx.Optimizer(model, optax.adam(0.05), wrt=nnx.Param)
for key in jax.random.split(d2l.get_key(), num_steps):
align_step(model, optimizer, key)
return modelComparing an untrained model against three independent training runs on \(1{,}000\) test sequences shows that gradient descent reliably converges to \(100\%\) accuracy, placing more than \(99\%\) of the weight on \(\pi(j)\), on average over output positions:
X, Y = align_data(1000)
def evaluate_aligner(model, X, Y, name):
with torch.inference_mode():
accuracy = (model(X).argmax(-1) == Y).float().mean()
weights = model.attention.attention_weights # (1000, 8, 8)
largest = (weights.argmax(-1) == perm).float().mean()
on_perm = weights[:, torch.arange(8), perm].mean()
print(f'{name:>9}: accuracy {accuracy:.3f}, largest weight on pi(j) '
f'{largest:.3f}, mean weight on pi(j) {on_perm:.3f}')
untrained = ToyAligner()
evaluate_aligner(untrained, X, Y, 'untrained')
for run in range(1, 4):
model = train_aligner()
evaluate_aligner(model, X, Y, f'run {run}')untrained: accuracy 0.272, largest weight on pi(j) 0.161, mean weight on pi(j) 0.132
run 1: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000
run 2: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 0.999
run 3: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000
X, Y = align_data(d2l.get_key(), 1000)
def evaluate_aligner(model, X, Y, name):
accuracy = (model(X).argmax(-1) == Y).mean()
weights = model.attention.attention_weights # (1000, 8, 8)
largest = (weights.argmax(-1) == perm).mean()
on_perm = weights[:, jnp.arange(8), perm].mean()
print(f'{name:>9}: accuracy {accuracy:.3f}, largest weight on pi(j) '
f'{largest:.3f}, mean weight on pi(j) {on_perm:.3f}')
untrained = ToyAligner(rngs=nnx.Rngs(d2l.get_key()))
evaluate_aligner(untrained, X, Y, 'untrained')
for run in range(1, 4):
model = train_aligner()
evaluate_aligner(model, X, Y, f'run {run}')untrained: accuracy 0.214, largest weight on pi(j) 0.053, mean weight on pi(j) 0.120
run 1: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 0.999
run 2: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000
run 3: accuracy 1.000, largest weight on pi(j) 1.000, mean weight on pi(j) 1.000
Visualizing the attention weight matrix on the first test sequence before and after training confirms that ToyAligner turns an unstructured initial distribution into the exact permutation matrix of \(\pi\) (with the off-diagonal swap at positions \(3\) and \(4\)):
letters = 'abcdefghijklmnop' # One letter per token id
maps = d2l.stack([untrained.attention.attention_weights[0],
model.attention.attention_weights[0]])
d2l.show_heatmaps(maps[None], xlabel='source', ylabel='target',
titles=['untrained', 'trained'], figsize=(5.5, 3),
cmap='Blues', xticklabels=[letters[int(i)] for i in X[0]],
yticklabels=[letters[int(i)] for i in Y[0]])letters = 'abcdefghijklmnop' # One letter per token id
maps = d2l.stack([untrained.attention.attention_weights[0],
model.attention.attention_weights[0]])
d2l.show_heatmaps(maps[None], xlabel='source', ylabel='target',
titles=['untrained', 'trained'], figsize=(5.5, 3),
cmap='Blues', xticklabels=[letters[int(i)] for i in X[0]],
yticklabels=[letters[int(i)] for i in Y[0]])The trained attention heatmap recovers the exact permutation matrix of \(\pi\), even when tokens repeat in the source sequence, because the keys encode position alongside token identity. In general sequence modeling, however, queries must be derived from the sequence itself, a single position may need to retrieve multiple distinct values simultaneously (Section 10.3), and positional encodings must generalize across sequence lengths (Section 10.4).
10.2.5 Summary
Scaled dot-product scoring \(a(\mathbf{q}, \mathbf{k}) = \mathbf{q}^\top \mathbf{k} / \sqrt{d}\) drops the quadratic norm penalties of the Gaussian kernel and evaluates all pairwise scores in a single matrix multiplication \(\mathbf{Q}\mathbf{K}^\top\). Dividing by \(\sqrt{d}\) preserves unit score variance for unit-variance inputs, preventing softmax saturation and vanishing score gradients as head width \(d\) grows. Structural constraints such as sequence padding and causal decoding are enforced via boolean masks that compose under logical AND, using finfo(dtype).min alongside explicit empty-row zeroing to avoid float16 overflow and NaN propagation. Finally, content-only keys split attention equally across duplicate tokens, whereas position-aware keys allow sequence alignments to be learned end to end.
10.2.6 Exercises
- Invariances of the score. The Gaussian score Equation 10.2.1 and the scaled dot product Equation 10.2.3 both define attention weights through the softmax Equation 10.2.4.
- For each of the two scores, determine which of the following transformations leaves the weights unchanged: adding one vector \(\mathbf{c}\) to every key; adding \(\mathbf{c}\) to the query and to every key; multiplying the query and every key by one orthogonal matrix.
- Queries and keys are usually computed from inputs by affine maps, \(\mathbf{q} = \mathbf{W}_q \mathbf{x} + \mathbf{b}_q\) and \(\mathbf{k}_i = \mathbf{W}_k \mathbf{y}_i + \mathbf{b}_k\). Expand \(\mathbf{q}^\top \mathbf{k}_i\) into four terms and show that the weights do not depend on \(\mathbf{b}_k\). What is the gradient of the loss with respect to \(\mathbf{b}_k\)?
- Through which of the four terms does \(\mathbf{b}_q\) affect the weights, and what preference over the keys can it express that the bias-free score cannot?
- [code] The softmax Jacobian.
jacobian_normmeasures the Frobenius norm of the Jacobian Equation 10.2.5.- Derive Equation 10.2.5 from Equation 10.2.4, show that for finite scores its null space is spanned by the all-ones vector, and check the formula against automatic differentiation on a random score vector.
- Compute the norm for weights spread uniformly over \(k\) of the \(m\) keys, find the \(k\) that maximizes it, and confirm by sampling random weight vectors that none exceeds this maximum. Use the result to explain why the unscaled norm in the table rises from \(d = 4\) to \(d = 16\) and then falls.
- Fully masked rows.
masked_softmaxoverwrites excluded scores with the most negative finite value of the dtype and then zeroes the rows of queries that have no valid key.- Build a row of four scores in which every key is excluded. Fill it with \(-10^6\) in float16, with \(-\infty\) in float32, and with
finfo(dtype).minin float32, and apply the framework’s softmax to each, without the final zeroing ofmasked_softmax. Report what you get and trace each result through the subtraction of the row maximum. - In a self-attention layer, whose queries, keys, and values all come from the same sequence, let a query at a padding position have no valid key, as the composite masks of Section 10.2.2.3 can arrange, and let the excluded scores be overwritten with \(-\infty\), so that the output at that position is NaN. That output is discarded, and in the next attention layer every valid query excludes the padding position as a key. Explain why the NaN nevertheless corrupts the outputs of all valid positions of that sequence in the next layer.
- Build a row of four scores in which every key is excluded. Fill it with \(-10^6\) in float16, with \(-\infty\) in float32, and with
- Composite masks. Section 10.2.2.3 combines masks by logical AND and warns that masks that are harmless alone can leave a query with no valid key. A causal sliding window of width \(w\) lets the query at position \(t\) attend to the keys at positions \(t - w + 1, \ldots,
t\).
- For a sequence of length \(6\) with valid length \(3\), write the padding mask and the causal sliding window of width \(2\) as \(6 \times 6\) boolean matrices. Check that each leaves every query at least one key, and find the queries whose row of the AND is empty.
- Show that an AND of masks has no empty row if every mask allows each query to attend to its own position. Which of the padding, causal, sliding-window, and packed-sequence masks satisfy this condition, and what does the answer say about the empty rows you found?
- Some implementations add a bias matrix with entries \(0\) for allowed pairs and \(c < 0\) for excluded pairs, and compose masks by adding their biases. Take for \(c\) the most negative finite single-precision value, about \(-3.4 \times 10^{38}\). Compute the sum of two such biases in single precision, and determine what the softmax returns for a row in which every key is excluded by both masks and for a row in which every key is excluded but some keys by only one mask.
- Entropy of random scores. ● The scaled entropy curve above stays near \(3.7\) nats, below the uniform value \(\log 64 \approx 4.16\). Fix one query \(\mathbf{q} \in \mathbb{R}^d\) and draw \(m\) keys with independent standard normal coordinates, as
softmax_weightsdoes.- Show that the scaled scores \(a_i = \mathbf{q}^\top \mathbf{k}_i /
\sqrt{d}\) are independent normal variables with mean \(0\) and variance \(s^2 = \|\mathbf{q}\|^2 / d\), and compute the expected value of \(s^2\) when \(\mathbf{q}\) is drawn as in
softmax_weights. - The entropy of the weights is \(H = \log Z - \sum_i \alpha_i a_i\) with \(Z = \sum_j \exp(a_j)\). For large \(m\), replace \(Z/m\) and \(\sum_i \exp(a_i)\, a_i / m\) by their expected values and derive \[H \approx \log m - \frac{s^2}{2}.\] Evaluate the approximation for \(m = 64\) and \(s = 1\).
- The approximation needs \(Z\) to concentrate around its mean. Compute the relative standard deviation of \(Z\) as a function of \(s\) and \(m\), and derive from it a condition on \(s^2\) under which the approximation holds. Unscaled scores have \(s^2 = \|\mathbf{q}\|^2\), whose expected value is \(d\). Evaluate the relative standard deviation for \(m = 64\) at \(s^2 = 4\) and \(s^2 = 8\), and compare the approximation with the unscaled entropies plotted above for \(d = 4\) and \(d = 8\).
- Show that the scaled scores \(a_i = \mathbf{q}^\top \mathbf{k}_i /
\sqrt{d}\) are independent normal variables with mean \(0\) and variance \(s^2 = \|\mathbf{q}\|^2 / d\), and compute the expected value of \(s^2\) when \(\mathbf{q}\) is drawn as in
- [code] Additive scores near zero. ● The additive score Equation 10.2.2 adds the projected query and the projected key inside a \(\tanh\).
- Replace \(\tanh\) by the identity and show that the attention weights then do not depend on the query.
- Expand \(\tanh\) to third order around zero, identify the lowest-order terms through which the weights depend on the query, and state how this dependence scales when \(\mathbf{W}_q\) and \(\mathbf{W}_k\) are both multiplied by a small factor \(\epsilon\).
- Implement the additive score for \(3\) queries and \(6\) keys in \(\mathbb{R}^8\) with standard normal entries and a hidden width \(r = 16\), drawing \(\mathbf{W}_q\), \(\mathbf{W}_k\), and \(\mathbf{w}_v\) with standard normal entries divided by the square root of their input width. Multiply \(\mathbf{W}_q\) and \(\mathbf{W}_k\) by \(\epsilon \in \{1, 0.3, 0.1, 0.03\}\), measure the largest difference between the weight rows of the three queries, averaged over many draws, and check the scaling you derived. For which of these scales do the weights depend appreciably on the query?
- [code] Alignment variants. ●
ToyAlignerin Section 10.2.4 learns the permutation \(\pi\) from one learned query per output position and keys that carry the token and the position.- Remove the one-hot position from the keys, so that they depend on the token alone. Predict, before training, whether output position \(j\) can still put its weight on \(\pi(j)\) and roughly what accuracy the model can reach; then train it and compare. Relate the result to the letters of Section 10.2.3.2.
- Replace the score by the additive rule Equation 10.2.2 and compare the number of steps that each model needs to reach \(99\%\) accuracy. Before training, use Exercise 6 to predict how the additive model starts when its projections are initialized small, and test the prediction.
- Give queries and keys the width \(d \in \{16, 256, 1024\}\) with standard normal initialization, and train with and without the factor \(1/\sqrt{d}\). Relate the training curves to the entropy of the weights at initialization.
- Show that
ToyAlignercannot learn a reordering that depends on the tokens, such as swapping two neighbors only when the first belongs to a designated subset of the vocabulary. (Hint: its score is a token term shared by all positions plus a position term; compare the scores of the two neighbors.) State what the query, or the keys, would have to depend on.