Skip to content
Transformers

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 X∈RT×D\mathbf{X} \in \mathbb{R}^{T \times D} (a row per position), three projections produce three matrices:

Q=XWQ∈RT×dkK=XWK∈RT×dkV=XWV∈RT×dv\mathbf{Q} = \mathbf{X}\mathbf{W}_Q \in \mathbb{R}^{T \times d_k} \qquad \mathbf{K} = \mathbf{X}\mathbf{W}_K \in \mathbb{R}^{T \times d_k} \qquad \mathbf{V} = \mathbf{X}\mathbf{W}_V \in \mathbb{R}^{T \times d_v}

where WQ,WK∈RD×dk\mathbf{W}_Q, \mathbf{W}_K \in \mathbb{R}^{D \times d_k} and WV∈RD×dv\mathbf{W}_V \in \mathbb{R}^{D \times d_v} are the learned weight matrices. The dimension dkd_k is the key/query dimension; dvd_v is the value dimension. Typical choices are dk=dv=D/hd_k = d_v = D/h, where hh is the number of attention heads — a detail that belongs to the next article.

Scaled Dot-Product Attention

The core formula is:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}

Breaking this into steps:

Step 1: compute raw scores. The score matrix S=QK⊤∈RT×T\mathbf{S} = \mathbf{Q}\mathbf{K}^\top \in \mathbb{R}^{T \times T} gives the dot product of every query with every key. Entry SijS_{ij} measures how well position ii's query matches position jj's key — in other words, how relevant position jj is to position ii.

Step 2: scale. Divide by dk\sqrt{d_k} to prevent the dot products from becoming too large.

Step 3: apply softmax row-wise. A=softmax(S/dk)\mathbf{A} = \text{softmax}(\mathbf{S}/\sqrt{d_k}) normalises each row to a valid probability distribution. Entry AijA_{ij} is the attention weight: the fraction of position jj's value that flows into position ii's output. Each row of A\mathbf{A} sums to 11.

Step 4: weighted sum of values. The output Z=AV∈RT×dv\mathbf{Z} = \mathbf{A}\mathbf{V} \in \mathbb{R}^{T \times d_v} is a weighted blend of all value vectors. Row ii of Z\mathbf{Z} is a convex combination of all value vectors, with position jj contributing in proportion to AijA_{ij}.

X (input sequence, T × D)Q = XWQ, K = XWK, V = XWVscores = QKᵀ / √d_k (T × T)A = softmax(scores) × V = Z (T × d_v)attention: every position queries every other position

Why Scale by dk\sqrt{d_k}

The dot product qi⋅kj\mathbf{q}_i \cdot \mathbf{k}_j of two dkd_k-dimensional vectors with unit-normal entries has variance dkd_k. Without scaling, large dkd_k 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 ∂softmax/∂sj=Aj(1−Aj)\partial \text{softmax} / \partial s_j = A_j(1 - A_j) is near zero when any AjA_j is near 00 or 11. Dividing by dk\sqrt{d_k} 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 ii of A\mathbf{A} is a distribution over the TT key positions. It encodes the answer to: "given position ii's query, how relevant is each position jj?" 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:

key (source)ThecatsatdownqueryThecatsatdown0.700.100.100.100.100.600.200.100.150.450.300.100.050.200.350.40attention weights A (each row sums to 1)"sat" attends strongly to "cat" — the subject

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 [t1,t2,…,tT][t_1, t_2, \ldots, t_T], position tt must not see tokens t+1,t+2,…,Tt+1, t+2, \ldots, T — otherwise the model trivially reads the answer.

This is enforced by causal masking: before applying the softmax, set Sij=−∞S_{ij} = -\infty for all j>ij > i. Since exp⁡(−∞)=0\exp(-\infty) = 0, the softmax assigns zero weight to all future positions:

S~ij={Sijj≤i−∞j>iAij=softmax(S~i⋅)j\tilde{S}_{ij} = \begin{cases} S_{ij} & j \leq i \\ -\infty & j > i \end{cases} \qquad A_{ij} = \text{softmax}(\tilde{S}_{i\cdot})_j

The resulting attention matrix A\mathbf{A} is lower-triangular: position ii can only draw information from positions 00 through ii. The original Transformer encoder uses full (bidirectional) attention; GPT-style decoders use causal attention.

Example for T=4:

A=(a11000a21a2200a31a32a330a41a42a43a44)\mathbf{A} = \begin{pmatrix} a_{11} & 0 & 0 & 0 \\ a_{21} & a_{22} & 0 & 0 \\ a_{31} & a_{32} & a_{33} & 0 \\ a_{41} & a_{42} & a_{43} & a_{44} \end{pmatrix}

Each row still sums to 11 over the unmasked positions.

Computational Properties

A single attention layer compares every pair of positions: the score matrix QK⊤\mathbf{Q}\mathbf{K}^\top has T2T^2 entries, each requiring a dot product of dkd_k multiplications. The total cost is O(T2dk)O(T^2 d_k) per layer.

This is expensive for very long sequences — T=4,096T = 4{,}096 produces over 16 million attention scores — but the computation is entirely parallel: QK⊤\mathbf{Q}\mathbf{K}^\top 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 O(T2)O(T^2) parallel operations where RNNs required O(T)O(T) sequential operations. The constant is worse, but the hardware can use it.

The O(T2)O(T^2) cost is also the direct answer to the bottleneck problem: there is no compressed hTh_T 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.