Attention Scoring and Masking

Dive into Deep Learning · §10.2

Attention Scoring Functions, Scaled Dot-Product, and Masking
dot-product vs. additive scoring · 1/√d variance scaling · softmax Jacobian · boolean mask algebra · learned alignment

Two Requirements for a Trainable Attention Layer

Motivation

  • 1. Fast, Learnable Scoring (n^2 Pairs): A single attention head reading n = 1{,}024 tokens evaluates 1{,}024^2 = 1{,}048{,}576 query–key pairs per layer; the scoring rule a(\mathbf{q}, \mathbf{k}) must map directly onto dense GPU matrix-multiplication hardware.
  • 2. Excluding Invalid Pairs (Masking): Padded minibatches contain <blank> tokens, and causal language models must block n(n-1)/2 = 523{,}776 future pairs so position t cannot peek at tokens > t.

From Gaussian Distance to the Dot-Product Score

Deriving the Score

  • Gaussian Distance Expansion: -\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
  • Query Norm Cancels: Because -\frac{1}{2}\|\mathbf{q}\|^2 is constant across all keys i, softmax shift invariance cancels it out.
  • Key Length as a Prior: Dropping -\frac{1}{2}\|\mathbf{k}_i\|^2 yields a(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i, allowing \|\mathbf{k}_i\| to act as a multiplicative salience prior.

Additive (MLP) vs. Dot-Product Scoring

Hardware Efficiency

  • Additive Attention (Bahdanau et al., 2014): a_{\textrm{add}}(\mathbf{q}, \mathbf{k}) = \mathbf{w}_v^\top \tanh(\mathbf{W}_q \mathbf{q} + \mathbf{W}_k \mathbf{k}) materializes a 3D (n, m, r) intermediate activation tensor.
  • Small-Weight Hazard: Near 0, \tanh(u) \approx u is linear, so query terms \mathbf{W}_q\mathbf{q} cancel across keys in the softmax.
  • Scaled Dot-Product (\mathbf{Q}\mathbf{K}^\top / \sqrt{d}): Computes all n \times m scores in a single Tensor Core GEMM and couples \mathbf{q} and \mathbf{k} bilinearly at all scales.

Why Unscaled Dot Products Grow as √d

Variance Calibration

  • Linear Variance Growth: For independent unit-variance coordinates q_j, k_j: \mathbb{E}[\mathbf{q}^\top \mathbf{k}] = 0, \qquad \textrm{Var}(\mathbf{q}^\top \mathbf{k}) = d
  • Growing Spread: Unscaled dot products have standard deviation \sqrt{d} (8 at d = 64; 22.6 at d = 512), pushing softmax into saturation.
  • Automatic Temperature (1/\sqrt{d}): Dividing by \sqrt{d} restores unit score variance across all head widths d.

Worked Example: Scaled Dot-Product by Hand

Step-by-Step Trace

  • Setup (d = 4, scale 1/\sqrt{4} = 1/2): Queries \mathbf{q}_1 = (2,2,0,0), \mathbf{q}_2 = (0,0,2,0) attend to keys \mathbf{k}_1 = (1,1,0,0), \mathbf{k}_2 = (0,0,1,1), \mathbf{k}_3 = (0,0,1,-1).
  • Orthogonal Keys Still Receive Weight: Keys \mathbf{k}_2, \mathbf{k}_3 have dot product 0 with \mathbf{q}_1, yet e^0 = 1 gives each 10.7\% weight.
  • Effect of Scaling: Omitting the 1/2 scale factor sharpens \mathbf{q}_1’s weight on \mathbf{k}_1 from 0.787 to 0.965.

Softmax Saturation and the Softmax Jacobian

Gradient Dynamics

  • Symmetric Softmax Jacobian: \frac{\partial \boldsymbol{\alpha}}{\partial \mathbf{a}} = \mathrm{diag}(\boldsymbol{\alpha}) - \boldsymbol{\alpha}\boldsymbol{\alpha}^\top
  • Vanishing at One-Hot Corners: As \boldsymbol{\alpha} \to \mathbf{e}_{i^*}, every diagonal entry \alpha_i(1 - \alpha_i) \to 0 and off-diagonal -\alpha_i \alpha_j \to 0.
  • Training Consequence: In a saturated row, backpropagated score gradients \partial \mathcal{L} / \partial \mathbf{a} vanish, freezing unselected keys.

Measuring Entropy Collapse Across Head Widths

Empirical Verification

  • Experimental Setup: 2{,}048 standard normal queries attend over m = 64 standard normal keys across widths d \in \{4, \ldots, 512\}.
  • Scaled Invariance: With 1/\sqrt{d}, weight entropy stays flat near \log 64 - \frac{1}{2} \approx 3.66 nats (an effective pool of \approx 39 keys) across all widths.
  • Unscaled Collapse: Without 1/\sqrt{d}, entropy plunges to 0.21 nats by d = 512, becoming nearly one-hot before a single gradient update.

Largest Weight and Jacobian Norm vs. Dimension d

Quantitative Diagnostics

Comparing the mean maximum weight \max_i \alpha_i and the mean Frobenius norm \|\mathrm{diag}(\boldsymbol{\alpha}) - \boldsymbol{\alpha}\boldsymbol{\alpha}^\top\|_F confirms how 1/\sqrt{d} stabilizes gradients:

      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

Why does the unscaled Jacobian norm rise from d = 4 (\approx 0.26) to d = 16 (\approx 0.29) before falling? \|\mathbf{J}\|_F is maximized when weight splits evenly between k = 2 competing keys (\|\mathbf{J}\|_F = 1/2), which occurs transiently as weights transition from uniform (m = 64) toward one-hot (k = 1).

Why Sequence Models Need Boolean Attention Masks

Attention Masking

Dense GPU matrix multiplication evaluates all n \times m query–key pairs at once, so structural constraints are enforced by masking out forbidden pairs prior to softmax normalization:

  • 1. Padding Masks (Variable-Length Batches): When sequences of length 2, 3, 4 are padded with <blank> tokens to share a (batch, 4) tensor, no query should ever read a <blank> key.
  • Broadcast shape (batch, 1, keys) applies the same valid key prefix to every query in a sequence.
  • 2. Causal Masks (Autoregressive Decoding): When predicting token t + 1 from positions \le t, query i may attend to key j only if j \le i.
  • A lower-triangular boolean matrix of shape (queries, keys) excludes all n(n-1)/2 upper-triangular future pairs.

Pitfall: Choosing the Fill Value for Masked Softmax

Floating-Point Hazards

  • Hardcoded -1e6: Overflows float16 (whose maximum finite magnitude is 65{,}504).
  • Literal -inf: On any fully masked row (all False), the row maximum is -\infty, so max-subtraction evaluates -\infty - (-\infty) = \mathrm{NaN} and infects every token in the next layer’s GEMM.
  • finfo(dtype).min + Zeroing: Underflows excluded exponentials to 0.0 in float16, bfloat16, and float32, while where(mask.any(-1)) zeroes empty rows cleanly.

Implementing Safe Masked Softmax and Padding Masks

Implementation

masked_softmax fills excluded entries with finfo(X.dtype).min and explicitly zeroes any query row that has no valid keys:

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

Composing Masks via Boolean Algebra (Logical AND)

Mask Composition

  • Conjunction Rule: When multiple constraints apply simultaneously, query i may attend to key j if and only if every constraint permits (i, j): \texttt{mask} = \texttt{padding\_mask} \;\mathbin{\&}\; \texttt{causal\_mask}
  • Broadcasted Intersection: A (batch, 1, n) padding mask and an (n, n) causal mask broadcast under & to (batch, n, n) cleanly.

Padding and causal masks compose via logical AND under broadcasting.

Visualizing a Composite Padding-and-Causal Mask

Mask Heatmaps

  • Padding & Causal: On uniform zero scores, row i averages over \min(i+1, \ell_{\textrm{valid}}) keys, truncating the second sequence at key 3.

Visualizing a Packed-Document Mask

Mask Heatmaps

  • Document Packing: Concatenating short documents doc = [0,0,0, 1,1, 2] into one row and computing (doc[:, None] == doc[None, :]) & causal_mask(6) forms a block-diagonal causal mask with zero cross-document leakage.

Batched Attention as Two Matrix Multiplications

Matrix Formulation

  • 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} computes all n lookups in two GEMMs: \textrm{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}}\right)\mathbf{V} \in \mathbb{R}^{n \times d_v}
  • GPT-2 Small Head (n=m=1{,}024, d=d_v=64): Score matrix holds 1{,}024^2 = 1{,}048{,}576 floats (4\text{ MiB} in float32); the two products cost 4n^2 d \approx 0.27\text{ GFLOPs}.

Tensor shapes in batched scaled dot-product attention.

The DotProductAttention Module

Module Implementation

Working on the last two axes, DotProductAttention carries any leading batch and head axes along:

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

Verifying the Hand Calculation in Code

Sanity Check

Passing the two 4\text{D} queries and three 4\text{D} keys from our worked example into DotProductAttention reproduces our exact hand-computed weights and outputs:

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

Always verify custom attention and masking modules on small inputs with known closed-form softmax outputs before training at scale.

What Content-Only Matching Can and Cannot Do

Content-Only Lookup

  • Assign each distinct letter in "attention" and "translation" a random embedding \mathbf{e} \in \mathbb{R}^{32} (identical letters score \approx \sqrt{32} \approx 5.7; distinct letters score \approx 0 \pm 1):
  • Unique matches (i, o): Concentrate nearly 100\% of their weight on their partner.
  • Repeated matches (a, t, n): Split weight equally across all copies—content alone cannot distinguish positions.
  • Unmatched query (e): Forced to sum to 1, spreading mass across random keys (motivating attention sinks in LLMs).

Learning Sequence Alignments End to End

Learned Alignment

Can gradient descent discover a word reordering from output supervision alone? In ToyAligner, output position j must copy source token \pi(j) where \pi = (0, 1, 2, 4, 3, 5, 6, 7) swaps positions 3 and 4:

  • Model Architecture: Each output position j holds a trainable query \mathbf{q}_j \in \mathbb{R}^{16}.
  • Position-Aware Keys: Source position i concatenates its one-hot token (16\text{D}) and one-hot position (8\text{D}) before multiplying by \mathbf{W}_k \in \mathbb{R}^{24 \times 16}.
  • Values: One-hot source tokens, so the attention output directly gives the predicted token distribution.

Learning Sequence Alignments End to End (cont.)

Learned Alignment

ToyAligner builds the position-aware keys and lets DotProductAttention read out the one-hot values:

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)

Emergence of the Permutation Matrix in ToyAligner

Training Results

  • After 100 Adam steps minimizing negative log-likelihood on random sequences, all three runs reach 100\% test accuracy and place more than 99\% of their weight on \pi(j) on average:
  • Even when source tokens repeat (c, o), the learned key projection routes each query cleanly to \pi(j), visible as the off-diagonal crossing in rows 3 and 4.

Concept Check: Scaling, Masking, and Invariances

Check Your Understanding

Test your understanding of scaled dot-product scoring and boolean masking:

  1. Score Ratio Without Scaling: In a head of width d = 64, two keys lie one standard deviation apart in raw dot-product score (\Delta = \sqrt{64} = 8). What is the ratio of their softmax weights without 1/\sqrt{d} versus with 1/\sqrt{d}?
  2. Affine Key Bias Invariance: Suppose keys are produced by an affine layer \mathbf{k}_i = \mathbf{W}_k \mathbf{y}_i + \mathbf{b}_k. Why does the bias vector \mathbf{b}_k have zero gradient (\nabla_{\mathbf{b}_k} \mathcal{L} = \mathbf{0}) in dot-product attention?
  3. Composite Window + Padding Hazard: Suppose sequence 2 has valid length 3 in a padded length-6 tensor, and we apply padding_mask & sliding_window(w=2). What happens to the mask row for query position i = 5?

Answers:

  1. Unscaled: e^8 \approx 2{,}981 : 1. Scaled by 1/\sqrt{64} = 1/8: \Delta' = 1, giving e^1 \approx 2.72 : 1.
  2. Expanding \mathbf{q}^\top(\mathbf{W}_k\mathbf{y}_i + \mathbf{b}_k) = \mathbf{q}^\top\mathbf{W}_k\mathbf{y}_i + \mathbf{q}^\top\mathbf{b}_k shows that \mathbf{q}^\top\mathbf{b}_k is independent of key index i, so softmax shift invariance cancels it out identically.
  3. Row i = 5 is completely empty (all False). The window allows keys \{4, 5\} while padding allows \{0, 1, 2\}, whose intersection is \emptyset—why masked_softmax must safely zero out empty rows.

Summary: Attention Scoring and Masking

Key Takeaways

  • Scaled Dot-Product (\mathbf{q}^\top\mathbf{k} / \sqrt{d}): Evaluates all n \times m pairs in a single GEMM (2nmd FLOPs) while keeping \textrm{Var}(a) = 1 so the softmax Jacobian \mathrm{diag}(\boldsymbol{\alpha}) - \boldsymbol{\alpha}\boldsymbol{\alpha}^\top never vanishes.
  • Additive Scoring: Handles d_q \neq d_k via \mathbf{w}_v^\top \tanh(\mathbf{W}_q\mathbf{q} + \mathbf{W}_k\mathbf{k}) at O(nmr) memory cost.
  • Safe Mask Algebra: Combines padding and causal masks via boolean & and fills forbidden scores before softmax.