Attention Mechanism
How scaled dot-product attention lets every position directly query every other position.
The previous article added positional information to each token's embedding. The model now knows what each token is and where it sits in the sequence. What it still cannot do is combine information across positions in a learned, content-dependent way. The word "sat" needs to know about "cat" (its subject) much more than it needs to know about "the". The word "it" in a long sentence needs to find the noun it refers to, which could be many positions away.
An architecture that addresses this must let every position directly query every other position, weighted by relevance. That is exactly what attention provides.
The Query-Key-Value Idea
The library analogy captures the intuition well. Imagine a library where:
- You arrive with a query — a description of what information you need.
- Every book has a key — an index card summarising what it contains.
- Every book also has a value — its actual content.
To find relevant information, you compare your query against every key. The similarity score determines how much of each book's value you read. The final result is a blend: a weighted combination of all values, weighted by how well each key matched your query.
In self-attention, each token simultaneously acts as a query (asking "what other tokens are relevant to me?"), a key (advertising "here is what I can offer to others"), and a value (providing the actual information to be aggregated). All three roles are computed from the same input via separate learned linear projections.
Query, Key, Value Projections
Given the input sequence (a row per position), three projections produce three matrices:
where and are the learned weight matrices. The dimension is the key/query dimension; is the value dimension. Typical choices are , where is the number of attention heads — a detail that belongs to the next article.
Scaled Dot-Product Attention
The core formula is:
Breaking this into steps:
Step 1: compute raw scores. The score matrix gives the dot product of every query with every key. Entry measures how well position 's query matches position 's key — in other words, how relevant position is to position .
Step 2: scale. Divide by to prevent the dot products from becoming too large.
Step 3: apply softmax row-wise. normalises each row to a valid probability distribution. Entry is the attention weight: the fraction of position 's value that flows into position 's output. Each row of sums to .
Step 4: weighted sum of values. The output is a weighted blend of all value vectors. Row of is a convex combination of all value vectors, with position contributing in proportion to .
Why Scale by
The dot product of two -dimensional vectors with unit-normal entries has variance . Without scaling, large produces large dot products, pushing the softmax into a nearly one-hot distribution: one score dominates and the rest become effectively zero.
This saturation prevents gradients from reaching the positions that "almost" matched — the softmax gradient is near zero when any is near or . Dividing by brings the dot products back to roughly unit variance, keeping the softmax in a smooth regime where gradients flow to all positions.
What Attention Weights Represent
Each row of is a distribution over the key positions. It encodes the answer to: "given position 's query, how relevant is each position ?" After training, these distributions capture learned linguistic and semantic relationships.
Example. For the sentence "The cat sat down", one attention head might learn weights like:
The verb "sat" attends strongly to "cat" — the subject — reflecting the subject-verb dependency. "down" attends to "sat" — the verb it modifies. These patterns are not hard-coded; they emerge from training on a language modelling objective.
Causal Masking
In an autoregressive language model, the goal is to predict the next token from the preceding ones. When training on the sequence , position must not see tokens — otherwise the model trivially reads the answer.
This is enforced by causal masking: before applying the softmax, set for all . Since , the softmax assigns zero weight to all future positions:
The resulting attention matrix is lower-triangular: position can only draw information from positions through . The original Transformer encoder uses full (bidirectional) attention; GPT-style decoders use causal attention.
Example for T=4:
Each row still sums to over the unmasked positions.
Computational Properties
A single attention layer compares every pair of positions: the score matrix has entries, each requiring a dot product of multiplications. The total cost is per layer.
This is expensive for very long sequences — produces over 16 million attention scores — but the computation is entirely parallel: is a single matrix multiplication that runs in one GPU step. Compare this to the RNN's sequential computation from the Limits of RNNs article: attention achieves parallel operations where RNNs required sequential operations. The constant is worse, but the hardware can use it.
The cost is also the direct answer to the bottleneck problem: there is no compressed through which all information must flow. Every output position has direct access to every input position, weighted by content.
In Code
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
# ── Scaled dot-product attention ──────────────────────────────────────────────
# Everything is a tensor operation: gradients flow through the softmax and the matmuls.
# The causal mask sets the scores of future positions (j > i) to −inf, so they get
# a weight of exactly 0 after the softmax.
def scaled_dot_product_attention(Q, K, V, causal=False):
"""Q, K, V: (..., T, d_k) tensors."""
d_k = Q.size(-1)
scores = Q @ K.transpose(-2, -1) / math.sqrt(d_k) # (..., T, T)
if causal:
T = Q.size(-2)
mask = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(mask, float("-inf"))
A = F.softmax(scores, dim=-1) # (..., T, T): rows sum to 1
return A @ V # (..., T, d_k)
# Simple example: T=3, d_k=2, identity projections (Q = K = V = X)
X = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
Z = scaled_dot_product_attention(X, X, X)
print(Z)
# tensor([[0.8022, 0.5989],
# [0.5989, 0.8022],
# [0.7517, 0.7517]])
# Each output row is a weighted average of all the input rows.
# Causal mask: position i attends only to positions 0..i
Z_causal = scaled_dot_product_attention(X, X, X, causal=True)
print(Z_causal)
# tensor([[1.0000, 0.0000], — position 0 sees only itself
# [0.3302, 0.6698], — position 1 blends rows 0 and 1
# [0.7517, 0.7517]]) — position 2 sees all three (no future to mask)
# ── SingleHeadAttention as an nn.Module ───────────────────────────────────────
class SingleHeadAttention(nn.Module):
def __init__(self, d_model: int, d_k: int):
super().__init__()
self.W_Q = nn.Linear(d_model, d_k, bias=False)
self.W_K = nn.Linear(d_model, d_k, bias=False)
self.W_V = nn.Linear(d_model, d_k, bias=False)
def forward(self, x: torch.Tensor, causal: bool = False):
# x: (batch, T, d_model)
Q = self.W_Q(x) # (batch, T, d_k)
K = self.W_K(x)
V = self.W_V(x)
return scaled_dot_product_attention(Q, K, V, causal=causal) # (batch, T, d_k)
attn = SingleHeadAttention(d_model=64, d_k=32)
x = torch.randn(2, 6, 64) # batch=2, seq_len=6
z = attn(x, causal=True)
print(z.shape) # torch.Size([2, 6, 32])
# Gradients flow back through the softmax and the matmuls to all three projection weights
z.sum().backward()
print(attn.W_Q.weight.grad.shape) # torch.Size([32, 64]) — ∂L/∂W_Q
print(attn.W_K.weight.grad.shape) # torch.Size([32, 64]) — ∂L/∂W_K
print(attn.W_V.weight.grad.shape) # torch.Size([32, 64]) — ∂L/∂W_V
# PyTorch's built-in fused implementation gives the same result
z_builtin = F.scaled_dot_product_attention(
attn.W_Q(x), attn.W_K(x), attn.W_V(x), is_causal=True,
)
print(torch.allclose(z, z_builtin, atol=1e-6)) # True
Single-head attention computes one set of scores, one attention distribution, and one output. But a sentence has many types of relationships simultaneously — subject-verb, modifier-noun, pronoun-antecedent, long-range coreference — and a single attention distribution cannot specialise in all of them at once. The next article extends attention by running several independent heads in parallel, each free to focus on a different kind of dependency.