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(q,k)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,024n = 1{,}024 tokens evaluates n2=1,048,576n^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 (q⊤k/d\mathbf{q}^\top\mathbf{k}/\sqrt{d}), explains how the 1/d1/\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(q,ki)=−12∥q−ki∥2=q⊤ki−12∥ki∥2−12∥q∥2.(10.2.1)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 −12∥q∥2-\tfrac{1}{2}\|\mathbf{q}\|^2 is constant across all keys ii, the softmax normalization cancels it out. If all keys have equal norm, −12∥ki∥2-\tfrac{1}{2}\|\mathbf{k}_i\|^2 cancels as well. Dropping both norm terms even when key norms vary yields the dot-product score q⊤ki\mathbf{q}^\top \mathbf{k}_i. Unlike the Gaussian kernel, which penalizes large ∥ki∥\|\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(q,k)=wv⊤tanh⁡(Wqq+Wkk)∈R,(10.2.2)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 Wq∈Rr×dq\mathbf{W}_q \in \mathbb{R}^{r \times d_q}, Wk∈Rr×dk\mathbf{W}_k \in \mathbb{R}^{r \times d_k}, and weight vector wv∈Rr\mathbf{w}_v \in \mathbb{R}^{r}. Although additive and dot-product scoring have similar asymptotic operation counts (O(nmr)O(nmr) versus O(nmd)O(nmd) for nn queries and mm keys), additive attention must materialize an n×m×rn \times m \times r tensor of hidden activations and apply tanh⁡\tanh elementwise. Dot-product attention computes all n×mn \times m scores in a single matrix multiplication QK⊤\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 (Wqq)⊤(Wkk)(\mathbf{W}_q \mathbf{q})^\top (\mathbf{W}_k \mathbf{k}) (see also Exercise 6).

One crucial scaling factor remains. Suppose the coordinates of q,k∈Rd\mathbf{q}, \mathbf{k} \in \mathbb{R}^d are independent random variables with mean 00 and variance 11. Then each term qjkjq_j k_j has mean 00 and variance 11, so the sum q⊤k\mathbf{q}^\top \mathbf{k} has mean 00 and variance dd (standard deviation 88 at d=64d = 64). To prevent large dot products from pushing the softmax into regions of vanishing gradients at large dd, Vaswani et al. (2017) divide by d\sqrt{d} to restore unit variance, giving the scaled dot-product score:

a(q,ki)=q⊤ki/d.(10.2.3)a(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i / \sqrt{d}. \tag{10.2.3}

Here 1/d1/\sqrt{d} plays the role of the inverse temperature 1/σ21/\sigma^2 in Section 10.1.2, calibrated automatically to the vector width dd. Softmax normalization then yields the attention weights

α(q,ki)=softmax(a(q,ki))=exp⁡(q⊤ki/d)∑j=1mexp⁡(q⊤kj/d),(10.2.4)\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 ∑i=1mα(q,ki) vi\sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i)\, \mathbf{v}_i.

10.2.1.1 A Worked Example#

Let d=4d = 4 (so 1/d=1/21/\sqrt{d} = 1/2) with two queries and three key--value pairs:

q1=(2,2,0,0),k1=(1,1,0,0),v1=(1,0),q2=(0,0,2,0),k2=(0,0,1,1),v2=(0,1),k3=(0,0,1,−1),v3=(1,1).\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}
  1. Scores: q1\mathbf{q}_1 has raw dot products (4,0,0)(4, 0, 0) with the three keys; q2\mathbf{q}_2 has (0,2,2)(0, 2, 2).
  2. Scaling: Dividing by 4=2\sqrt{4} = 2 gives (2,0,0)(2, 0, 0) and (0,1,1)(0, 1, 1).
  3. Softmax: q1\mathbf{q}_1 assigns weights (e2/(e2+2), 1/(e2+2), 1/(e2+2))≈(0.787,0.107,0.107)\big(e^2/(e^2 + 2),\, 1/(e^2 + 2),\, 1/(e^2 + 2)\big) \approx (0.787, 0.107, 0.107); q2\mathbf{q}_2 assigns (1/(1+2e), e/(1+2e), e/(1+2e))≈(0.155,0.422,0.422)\big(1/(1 + 2e),\, e/(1 + 2e),\, e/(1 + 2e)\big) \approx (0.155, 0.422, 0.422).
  4. Weighted sum: o1=0.787 v1+0.107 v2+0.107 v3≈(0.893,0.213)\mathbf{o}_1 = 0.787\,\mathbf{v}_1 + 0.107\,\mathbf{v}_2 + 0.107\,\mathbf{v}_3 \approx (0.893, 0.213) and o2≈(0.578,0.845)\mathbf{o}_2 \approx (0.578, 0.845).

Even an orthogonal key receives nonzero softmax weight (0.1070.107), and keys that tie on the active coordinates of a query (k2\mathbf{k}_2 and k3\mathbf{k}_3 under q2\mathbf{q}_2) split the remaining weight equally. Omitting the 1/21/2 scaling factor would sharpen q1\mathbf{q}_1's weight on k1\mathbf{k}_1 from 0.7870.787 to e4/(e4+2)≈0.96e^4/(e^4 + 2) \approx 0.96.

10.2.1.2 Score Variance and the 1/d1/\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 α=softmax(a)\boldsymbol{\alpha} = \mathrm{softmax}(\mathbf{a}),

∂α∂a=diag(α)−αα⊤,(10.2.5)\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,0482{,}048 queries, each attending over 6464 random keys) across dimensions d∈{4,…,512}d \in \{4, \ldots, 512\}, comparing unscaled scores against scores scaled by 1/d1/\sqrt{d}. Uniform weights over 6464 keys have entropy log⁡64≈4.16\log 64 \approx 4.16 nats, whereas a one-hot distribution has entropy 00.

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()

Sweeping head width dd from 44 to 512512 on a logarithmic axis shows that unscaled dot-product attention suffers rapid entropy collapse as dd grows, whereas scaling by 1/d1/\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')

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

With 1/d1/\sqrt{d} scaling, the entropy stays near log⁡64−12≈3.66\log 64 - \tfrac{1}{2} \approx 3.66 nats across all widths (Exercise 5), with maximum weight ≈0.11\approx 0.11 and Jacobian norm ≈0.18\approx 0.18. Without scaling, score standard deviation grows as d\sqrt{d}: by d=512d = 512, entropy collapses to ≈0.2\approx 0.2 nats, the top key takes over 90%90\% of the weight at random initialization, and the Jacobian norm falls by half. Scaling by 1/d1/\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)O(d), motivating the 1/d1/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 dd but not against the number of keys mm. With unit-variance scores the entropy is about log⁡m−12\log m - \tfrac{1}{2}, so the weights spread over roughly 0.6 m0.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−1m - 1 keys by a score gap gg, it receives weight 1/(1+(m−1)e−g)1/(1 + (m-1)e^{-g}). A gap of g=9g = 9 gives about 0.90.9 among 1,0001{,}000 keys and less than 0.10.1 among 100,000100{,}000. To stay sharp, the gap must grow like log⁡m\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:

  1. Padding: When sequences of unequal lengths are padded with <blank> tokens to form a minibatch, no query should attend to padding positions.
  2. Causality: In autoregressive language modeling, the query at position tt may attend only to keys at positions j≤tj \le t.

Both constraints are represented by a boolean mask tensor that is True where query ii is permitted to attend to key jj.

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 −106-10^6 overflows float16 (whose maximum finite magnitude is 65,50465{,}504).
  • Literal −∞-\infty produces NaN whenever an entire query row is masked out, because the numerically stable softmax subtracts the row maximum −∞-\infty to form −∞−(−∞)=NaN-\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 producing NaN. For any query row where all keys are masked out (~mask.any(-1)), masked_softmax explicitly 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)

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]

On a batch of two zero-score sequences of length 44 with valid lengths 22 and 33, 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]]])

10.2.2.2 Causal Masking#

A causal mask allows query ii to attend to key jj only if j≤ij \le i, forming a lower-triangular matrix that excludes n(n−1)/2n(n-1)/2 of the n2n^2 pairs (523,776523{,}776 pairs at n=1,024n = 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)

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).

Figure 10.2.1:

Masks compose by logical AND. For a sequence of length 6 with valid length 3, the padding mask stores one row of keys, which broadcasting repeats for every query (faint); the causal mask is a lower triangle; their AND allows a pair only if both do. Rows are queries, columns are keys, and filled entries are allowed.

Combining a padding mask (valid lengths 66 and 33) 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 33:

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))

In the shorter sequence, queries 44 to 66 are padding themselves, yet each still has valid keys, because a causal triangle always reaches back to key 11. 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)

10.2.3 Attention for a Minibatch#

Stacking nn queries into Q∈Rn×d\mathbf{Q} \in \mathbb{R}^{n \times d}, mm keys into K∈Rm×d\mathbf{K} \in \mathbb{R}^{m \times d}, and mm values into V∈Rm×dv\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):

softmax(QK⊤d)V∈Rn×dv.(10.2.6)\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}
Figure 10.2.2:

Shapes in scaled dot-product attention. QK⊤/d\mathbf{Q}\mathbf{K}^\top/\sqrt{d} holds the scores of all n×mn \times m query--key pairs; masking and a softmax over each row turn them into the weights A\mathbf{A} (here with a causal mask, which leaves the upper triangle empty); multiplying by V\mathbf{V} gives one weighted sum of values per query.

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,024n = m = 1{,}024, d=dv=64d = d_v = 64), the score matrix holds 1,048,5761{,}048{,}576 floats (4 MiB in fp32) and the two products require 4n2d≈0.274n^2 d \approx 0.27 GFLOPs—both quadratic in nn.

10.2.3.1 The DotProductAttention Class#

DotProductAttention implements (10.2.6) with optional masking and attention-weight dropout (default 0.00.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) @ values

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]]

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 e∈R32\mathbf{e} \in \mathbb{R}^{32} and let the letters of "attention" query the letters of "translation". Identical letters have expected scaled score E[∥e∥2]/32=32≈5.7\mathbb{E}[\|\mathbf{e}\|^2]/\sqrt{32} = \sqrt{32} \approx 5.7, whereas distinct letters have expected score 00 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])

Three behaviors stand out:

  1. Unique matches (i, o) concentrate nearly all weight on their partner.
  2. 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.
  3. 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 88 tokens drawn from a vocabulary of size 1616, and the target sequence applies a fixed permutation π\pi that swaps positions 33 and 44. Each output position jj 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)

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 model

Comparing an untrained model against three independent training runs on 1,0001{,}000 test sequences shows that gradient descent reliably converges to 100%100\% accuracy, placing more than 99%99\% of the weight on π(j)\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

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 33 and 44):

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(q,k)=q⊤k/da(\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 QK⊤\mathbf{Q}\mathbf{K}^\top. Dividing by d\sqrt{d} preserves unit score variance for unit-variance inputs, preventing softmax saturation and vanishing score gradients as head width dd 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#

  1. Invariances of the score. The Gaussian score (10.2.1) and the scaled dot product (10.2.3) both define attention weights through the softmax (10.2.4).

    1. For each of the two scores, determine which of the following transformations leaves the weights unchanged: adding one vector c\mathbf{c} to every key; adding c\mathbf{c} to the query and to every key; multiplying the query and every key by one orthogonal matrix.
    2. Queries and keys are usually computed from inputs by affine maps, q=Wqx+bq\mathbf{q} = \mathbf{W}_q \mathbf{x} + \mathbf{b}_q and ki=Wkyi+bk\mathbf{k}_i = \mathbf{W}_k \mathbf{y}_i + \mathbf{b}_k. Expand q⊤ki\mathbf{q}^\top \mathbf{k}_i into four terms and show that the weights do not depend on bk\mathbf{b}_k. What is the gradient of the loss with respect to bk\mathbf{b}_k?
    3. Through which of the four terms does bq\mathbf{b}_q affect the weights, and what preference over the keys can it express that the bias-free score cannot?
  2. [code] The softmax Jacobian. jacobian_norm measures the Frobenius norm of the Jacobian (10.2.5).

    1. Derive (10.2.5) from (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.
    2. Compute the norm for weights spread uniformly over kk of the mm keys, find the kk 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=4d = 4 to d=16d = 16 and then falls.
  3. Fully masked rows. masked_softmax overwrites excluded scores with the most negative finite value of the dtype and then zeroes the rows of queries that have no valid key.

    1. Build a row of four scores in which every key is excluded. Fill it with −106-10^6 in float16, with −∞-\infty in float32, and with finfo(dtype).min in float32, and apply the framework's softmax to each, without the final zeroing of masked_softmax. Report what you get and trace each result through the subtraction of the row maximum.
    2. 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.
  4. 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 ww lets the query at position tt attend to the keys at positions t−w+1,…,tt - w + 1, \ldots, t.

    1. For a sequence of length 66 with valid length 33, write the padding mask and the causal sliding window of width 22 as 6×66 \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.
    2. 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?
    3. Some implementations add a bias matrix with entries 00 for allowed pairs and c<0c \lt 0 for excluded pairs, and compose masks by adding their biases. Take for cc the most negative finite single-precision value, about −3.4×1038-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.
  5. Entropy of random scores. ● The scaled entropy curve above stays near 3.73.7 nats, below the uniform value log⁡64≈4.16\log 64 \approx 4.16. Fix one query q∈Rd\mathbf{q} \in \mathbb{R}^d and draw mm keys with independent standard normal coordinates, as softmax_weights does.

    1. Show that the scaled scores ai=q⊤ki/da_i = \mathbf{q}^\top \mathbf{k}_i / \sqrt{d} are independent normal variables with mean 00 and variance s2=∥q∥2/ds^2 = \|\mathbf{q}\|^2 / d, and compute the expected value of s2s^2 when q\mathbf{q} is drawn as in softmax_weights.
    2. The entropy of the weights is H=log⁡Z−∑iαiaiH = \log Z - \sum_i \alpha_i a_i with Z=∑jexp⁡(aj)Z = \sum_j \exp(a_j). For large mm, replace Z/mZ/m and ∑iexp⁡(ai) ai/m\sum_i \exp(a_i)\, a_i / m by their expected values and derive
H≈log⁡m−s22.H \approx \log m - \frac{s^2}{2}.

Evaluate the approximation for m=64m = 64 and s=1s = 1.

  1. The approximation needs ZZ to concentrate around its mean. Compute the relative standard deviation of ZZ as a function of ss and mm, and derive from it a condition on s2s^2 under which the approximation holds. Unscaled scores have s2=∥q∥2s^2 = \|\mathbf{q}\|^2, whose expected value is dd. Evaluate the relative standard deviation for m=64m = 64 at s2=4s^2 = 4 and s2=8s^2 = 8, and compare the approximation with the unscaled entropies plotted above for d=4d = 4 and d=8d = 8.
  1. [code] Additive scores near zero. ● The additive score (10.2.2) adds the projected query and the projected key inside a tanh⁡\tanh.

    1. Replace tanh⁡\tanh by the identity and show that the attention weights then do not depend on the query.
    2. Expand tanh⁡\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 Wq\mathbf{W}_q and Wk\mathbf{W}_k are both multiplied by a small factor ϵ\epsilon.
    3. Implement the additive score for 33 queries and 66 keys in R8\mathbb{R}^8 with standard normal entries and a hidden width r=16r = 16, drawing Wq\mathbf{W}_q, Wk\mathbf{W}_k, and wv\mathbf{w}_v with standard normal entries divided by the square root of their input width. Multiply Wq\mathbf{W}_q and Wk\mathbf{W}_k by ϵ∈{1,0.3,0.1,0.03}\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?
  2. [code] Alignment variants. ● ToyAligner in Section 10.2.4 learns the permutation π\pi from one learned query per output position and keys that carry the token and the position.

    1. Remove the one-hot position from the keys, so that they depend on the token alone. Predict, before training, whether output position jj can still put its weight on π(j)\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.
    2. Replace the score by the additive rule (10.2.2) and compare the number of steps that each model needs to reach 99%99\% accuracy. Before training, use Exercise 6 to predict how the additive model starts when its projections are initialized small, and test the prediction.
    3. Give queries and keys the width d∈{16,256,1024}d \in \{16, 256, 1024\} with standard normal initialization, and train with and without the factor 1/d1/\sqrt{d}. Relate the training curves to the entropy of the weights at initialization.
    4. Show that ToyAligner cannot 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.

Discussions