3.1 Self-Attention Mathematics
A recurrent model passes information through a chain: to connect the first token to the hundredth, the computation traverses the intervening positions. Self-attention gives each position a direct, learned way to read other positions. In the original Transformer, this removed the recurrence that limited parallelism within training examples [1].
Consider “The key to the cabinets is missing.” The representation at “is” can combine information from “key” without first compressing the whole prefix into one recurrent state. That is a capability of the architecture, not proof that a particular head learns this grammatical relationship. A causal decoder can read only earlier positions and itself; parallel training does not make autoregressive generation parallel.
The mechanism has three parts: decide what to look for, score what is available, and mix the information found. The filing-cabinet analogy makes those roles concrete.
The Metaphor: The Filing Cabinet System
Suppose you want to know what a library’s bird collection says about flight. Your search phrase plays the role of a query. The label on each folder is its key. The pages inside are its value.
Attention assigns a raw score to each visible key by comparing it with the query. Softmax converts those scores into weights. If two folders receive weights 0.7 and 0.3, their values contribute in those proportions. A folder with a perfect label can still contain an unhelpful page. The score tells you how the weights were assigned, while the value determines what reaches the output.
In self-attention every position supplies all three vectors. A causal mask limits which positions a query can read.
From Embeddings to Q, K, V: Linear Projections
Each row of describes one token at the input to this layer. If there are tokens with coordinates each, has shape . A head learns three projections:
and have shape , so a query and a key have the same width and can be compared by a dot product. has shape . Choosing sets the width of the information a head can return.

The Mathematics of Scaled Dot-Product Attention
Compare each query with every key, then use those scores to mix the values. For a sequence of tokens the full calculation is
Each row of contains scores for one query. Softmax acts across that row. Multiplication by then gives one output vector of width for each of the queries.
Step-by-Step Breakdown
- Dot Product (): Measures the raw similarity between each query and all keys.
- Scaling (): Dividing by the square root of the key width reduces the tendency of softmax to concentrate on one key as width increases. The variance argument in Quiz 1 explains the assumptions.
- Softmax: Converts the scaled scores into probabilities (attention weights) that sum to 1.
- Weighted Sum (): Multiplies the attention weights by the values to get the final output.
When does “cat” first depend on the word before it?
Pass red cat and blue cat through the base SmolLM2-135M checkpoint. With special tokens disabled, each phrase has two tokens. In both, the second token has ID 2644. Record the largest absolute difference between matching coordinates at that position. [3]
| Where the script measures “cat” | Largest difference |
|---|---|
| First layer, Q / K / V projections (before rotary position encoding for Q and K) | 0 / 0 / 0 |
| First layer, attention output after the output projection | 0.08247 |
| Second layer, Q projection | 0.20685 |
The first query is identical in both runs, but the key at the earlier position changed. In head 0 the final query assigns 0.3381 of its weight to red and 0.3990 to blue. Mixing the values changes what reaches the next layer. Reverse the experiment by replacing red cat with red dog and observing the first token instead. At red, all five differences stay zero because its causal attention cannot read the changed suffix.
Reproduce the comparison on CPU (Python) · Inspect token IDs, head weights and measured differences (JSON). These measurements describe two-token inputs in FP32. They establish where the representations diverge in this example. A head’s weight alone cannot tell you whether the model understood the color.
PyTorch Implementation
For a calculation you can do by hand, use the four tokens in The cat sat here and assign their vectors explicitly. Give “cat” the query and use the keys , , and in sentence order.
For the query at “cat,” the four raw dot products are 1, 2, 1 and −1. After scaling by and masking future keys, only “The” and “cat” compete. Their weights are about 0.3302 and 0.6698. Multiplying by their values, and , gives . Open the mask to all four keys and the output becomes about . You can reproduce both rows with the controls below at temperature 1.
Runnable CPU example. Run python self_attention.py in an environment with PyTorch installed. The example uses float32 and the four fixed input vectors per role shown in the interactive. It materializes the score matrix and checks all four outputs against PyTorch SDPA with dropout disabled. The example leaves out training, fused-kernel optimization and KV-cache offsets. [2]
Try both checks from the worksheet. Add 8 to the second coordinate of the value at “here.” With all keys visible, the second output coordinate at “cat” increases by about 0.4554. With the causal mask, it stays fixed. Now zero the future weights after softmax. The weights left for “The” and “cat” sum to only 0.7090. The script checks that dividing by this sum recovers the two causal weights.
A boolean True allows a key in this example and in PyTorch’s functional SDPA. An entirely blocked query has no distribution over valid keys. Replacing every score in that row with the same finite number makes softmax assign equal weights to all keys. This function rejects that input explicitly. [2]
Which axis does a padding mask hide?
Suppose sequence A has values [1, 3] and sequence B has [10, PAD]. Set all queries and keys to zero and allow attention in both directions. The visible keys get equal weights, so A’s two outputs must both be 2. B’s one real query must return 10, whatever value occupies the padding slot.
The key-validity table is [[True, True], [True, False]], one row per sequence. The scores have axes [batch, head, query, key]. Passing the table directly aligns its two axes to query and key. This happens to fit because both the batch and the query axis have length two. With a padding value of 90, B’s first query now reads both values and returns 50. Changing just the pad to 900 raises that output to 455. Even a comparison against native SDPA passes if both implementations get the same mistaken mask. [2]
Use valid[:, None, None, :] to retain the batch axis and share key validity across heads and queries. The script checks the three real outputs against [2, 2, 10] under both padding values. B’s second query still produces an output because it can read a valid key. Exclude that padded query from pooling and loss.
A NaN in the value tensor is a separate test. The materialized sum in this script evaluates zero weight times NaN, which can contaminate even a real query. Replacing the known padding value with zero and keeping its key masked restores the result. Even a position whose value vector is zero will take a share of the softmax denominator if its key is visible.
Download the PyTorch example (self_attention.py)
"""CPU PyTorch exercises on causal attention and padding a batch of two sequences.
Source: Foundation Model Engineering, §3.1, Self-Attention Mathematics.
Worksheet and interactive example:
https://sungeuns.github.io/foundation-model-engineering/chapter-3/self-attention-mathematics/#attention-weight-example
https://sungeuns.github.io/foundation-model-engineering/ko/chapter-3/self-attention-mathematics/#attention-weight-example
Batch padding example:
English: https://sungeuns.github.io/foundation-model-engineering/chapter-3/self-attention-mathematics/#batched-padding-example
한국어: https://sungeuns.github.io/foundation-model-engineering/ko/chapter-3/self-attention-mathematics/#batched-padding-example
"""
from math import sqrt
import torch
from torch.nn import functional as F
def attention(q, k, v, allowed=None):
"""Materialized scores [..., query, key]; True means visible.
A 2D mask aligns to [query, key]. For per-example key validity [B, S],
pass valid[:, None, None, :] for scores shaped [B, H, T, S].
Use finite inputs; a zero weight times a NaN value can still produce NaN.
"""
scores = (q @ k.transpose(-2, -1)) / sqrt(q.size(-1))
if allowed is not None:
if allowed.dtype != torch.bool:
raise TypeError("Use a boolean visibility mask")
allowed = torch.broadcast_to(allowed, scores.shape)
if not allowed.any(dim=-1).all():
raise ValueError("Every query must see at least one key")
scores = scores.masked_fill(~allowed, float("-inf"))
weights = scores.softmax(dim=-1)
return weights @ v, weights
def batched_padding_example():
# Both sequences have two slots. Only B's second slot is padding.
valid = torch.tensor([[True, True], [True, False]])
q = torch.zeros(2, 1, 2, 1)
k = torch.zeros_like(q)
v = torch.tensor([[1., 3.], [10., 90.]])[:, None, :, None]
key_mask = valid[:, None, None, :] # [batch, 1, 1, key]
expected = torch.tensor([2., 2., 10.]) # A0, A1, B0
for pad, wrong_b0 in ((90., 50.), (900., 455.)):
v[1, 0, 1, 0] = pad
# Diagnostic: [2, 2] also fits [query, key], with different meaning.
wrong, _ = attention(q, k, v, valid)
torch.testing.assert_close(wrong[:, 0, :, 0][valid], torch.tensor([2., 1., wrong_b0]))
torch.testing.assert_close(wrong, F.scaled_dot_product_attention(q, k, v, attn_mask=valid))
out, _ = attention(q, k, v, key_mask)
torch.testing.assert_close(out[:, 0, :, 0][valid], expected)
native = F.scaled_dot_product_attention(q, k, v, attn_mask=key_mask, dropout_p=0.0)
torch.testing.assert_close(native, out)
# A NaN pad tests a separate failure: dense matrix multiplication sums 0 * NaN.
v[1, 0, 1, 0] = float("nan")
contaminated, _ = attention(q, k, v, key_mask)
assert contaminated[1, 0, 0, 0].isnan()
clean_v = v.masked_fill(~valid[:, None, :, None], 0.)
cleaned, _ = attention(q, k, clean_v, key_mask)
torch.testing.assert_close(cleaned[:, 0, :, 0][valid], expected)
print("Valid outputs (A0, A1, B0):", cleaned[:, 0, :, 0][valid].tolist())
if __name__ == "__main__":
# The, cat, sat, here. Shape: [batch=1, heads=1, tokens=4, features=2].
q = torch.tensor([[1, 0], [1, 1], [0, 1], [-1, 1]], dtype=torch.float32)[None, None]
k = torch.tensor([[1, 0], [1, 1], [0, 1], [-1, 0]], dtype=torch.float32)[None, None]
v = torch.tensor([[1, 0], [0, 2], [2, 1], [-1, 1]], dtype=torch.float32)[None, None]
causal = torch.ones(4, 4, dtype=torch.bool).tril()
# Worksheet 3: increase only the second coordinate of V(here).
change = torch.tensor([0., 8.])
changed = v.clone()
changed[0, 0, 3] += change
for label, mask in [("All keys", None), ("Causal", causal)]:
out, weights = attention(q, k, v, mask)
expected = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0)
torch.testing.assert_close(out, expected)
print(label, "cat weights:", weights[0, 0, 1], "output:", out[0, 0, 1])
after, _ = attention(q, k, changed, mask)
delta = after - out
torch.testing.assert_close(delta, weights[..., 3:4] * change)
print(label, "change in cat output:", delta[0, 0, 1])
# Worksheet 4: what if we zero the future weights *after* softmax?
_, all_weights = attention(q, k, v)
_, causal_weights = attention(q, k, v, causal)
late_mask = all_weights[0, 0, 1].masked_fill(~causal[1], 0.)
mass = late_mask.sum()
print(f"Late mask on cat: remaining weight {mass.item():.4f}")
assert 0 < mass < 1
torch.testing.assert_close(late_mask / mass, causal_weights[0, 0, 1])
batched_padding_example()
Example: Attention Weight Matrix
Follow one attention row all the way to its output. The example below uses four tokens and explicitly authored two-dimensional Q, K, and V vectors. Select a query, compare the weights with and without a causal mask, and inspect how the weighted values add up. These are exact calculations on toy inputs, not attention measured from a trained model.
To work through the numbers first, open the printable attention worksheet (PDF, 2 pages). The first page asks you to calculate the weights for “cat” and change a future value. The second gives the worked solution.
From attention weights to an output vector
The calculation below shows “cat” attending to all four tokens at temperature 1. Enable JavaScript to change the inputs, or compare the masked and unmasked results in the worksheet and answer key (PDF).
softmax(Q2Kᵀ / (√2 × 1.00)) V
Lower temperature concentrates weight on larger scores. Masking makes future-token weights exactly zero and renormalizes the visible weights.
Inspect the vectors and intermediate calculation
| Token | Q | K | V | Score | Weight × V |
|---|---|---|---|---|---|
| The | [1, 0] | [1, 0] | [1, 0] | 0.707 | [0.234, 0] |
| cat | [1, 1] | [1, 1] | [0, 2] | 1.414 | [0, 0.950] |
| sat | [0, 1] | [0, 1] | [2, 1] | 0.707 | [0.468, 0.234] |
| here | [-1, 1] | [-1, 0] | [-1, 1] | -0.707 | [-0.057, 0.057] |
Authored two-dimensional Q/K/V example, not measured model attention or evidence about word meaning. τ is an attention-score teaching control, separate from output-token sampling temperature. The standard equation uses τ = 1.
Here each query used one set of weights for both value coordinates. In the two-head calculation, two heads compute separate weights from the same input. If one head contributes zero, which output coordinates change?
Quizzes
Quiz 1: Why is the scaling factor necessary in the attention formula?
If query and key components are independent, zero-mean, and unit-variance, their dot product has variance . Dividing by the square root of keeps its variance near one under those assumptions and reduces softmax saturation. Learned vectors need not satisfy them exactly, and this scaling alone does not guarantee stable training.
Quiz 2: In encoder–decoder cross-attention, which states supply the queries, keys and values?
Decoder states supply queries, while encoder states supply keys and values. In self-attention all three projections begin with states from the same sequence. Either arrangement still has to specify a scoring rule and which positions are visible.
Quiz 3: In the interactive example, why does the first token’s output stop changing with temperature when the causal mask is enabled?
Only the first token is visible to its own query. Its normalized weight is therefore 1 at every allowed temperature, and its output is exactly its value vector V₁ = [1, 0]. The other values cannot contribute because their masked weights are zero. These authored vectors demonstrate the calculation, not learned word meaning.
Quiz 4: Why do we use linear projections to create Q, K, V instead of using the input embeddings directly?
They let matching queries, matching keys, and returned values use different learned features. The input may already be contextual in deeper layers; the distinction is between roles, not between static and contextual representations.
Quiz 5: You pad a two-token sequence to four tokens for batching. Which axis grows, and how do you keep padding out of the result?
The output has one row per query, with features per row. Padding adds rows, while the feature width stays fixed. Mask padded keys before normalizing each real query, and discard padded query outputs before loss or pooling. A causal mask alone does not identify padding.
Quiz 6: Count parameters and dominant FLOPs for Q, K, V projections plus the attention core with sequence length and . How does adding a square output projection change the count?
Excluding biases and the output projection, the three projection matrices contain parameters. Counting a multiply and add as two FLOPs, the projections cost , while and the weighted-value product together cost . Thus the dominant total is ; scaling and softmax add work. Adding raises the parameter count to and the dominant FLOPs to . These counts exclude normalization and the feed-forward sublayer.
References
- Vaswani, A., et al. (2017). Attention is all you need. In Advances in neural information processing systems (pp. 5998-6008). arXiv:1706.03762.
- PyTorch. Scaled dot product attention, PyTorch 2.15.
- Hugging Face TB. SmolLM2-135M base checkpoint and configuration.