On this page
Read the sentence "Birds in the garden sing softly at dawn." When a model reaches "sing," it needs to know who is singing and how the sentence fits together. Because the right source word shifts with every sentence, a fixed lookup table cannot solve this routing problem.
Self-attention solves it with a soft, differentiable lookup.[1] Each token projects its hidden state into three vectors: a query asking what context it needs, a key advertising what it holds, and a value carrying the payload to share. Dot products score every query against every key, softmax turns each score row into probability weights, and multiplying by the values blends the chosen context into a fresh representation. Zooming into "Birds sing" under a causal mask, "Birds" reads only itself while "sing" blends 42% of "Birds" with 58% of itself into [1.42, 1.58].
![Causal attention flow for Birds and sing: Birds reads only its own value, while sing mixes 42.1 percent of Birds and 57.9 percent of sing, producing context [1.42, 1.58].](https://assets.leetllm.com/v1/481eb77f3288/fundamentals/scaled-dot-product-attention/illustrations/_generated/attention_flow_dark.png)
Three views of one token
Raw dot products force every token to ask for context and advertise context in the same subspace. Three learned linear projections and split routing from content cleanly:[1]
- Query (): what context this position needs (scores candidate sources).
- Key (): when another position should read this token (matched against incoming queries).
- Value (): what payload this token contributes once selected.
Even when raw scores are symmetric, attention weights are asymmetric because each query row normalizes by its own softmax denominator and causal masking removes future edges.
![The hidden state of the token Birds branches into three learned projections: query [1.0, 0.5] asks what to find, key [0.8, 0.2] describes the token for matching, and value [2.0, 1.0] carries the content to mix.](https://assets.leetllm.com/v1/9e9c16e1a54f/fundamentals/scaled-dot-product-attention/illustrations/_generated/qkv_projections_dark.png)
The core formula
Scaled dot-product attention packs scoring, scaling, masking, normalization, and value mixing into one matrix expression:[1]
The additive mask puts on allowed keys and on blocked keys so removes blocked positions before normalization while the remaining weights still sum to 1.
| Step | Operation | Shape | Role |
|---|---|---|---|
| Score & scale | Pairwise compatibility with steady variance | ||
| Mask | Blocks disallowed keys with | ||
| Normalize | Row-wise probability weights over keys | ||
| Mix | Weighted average of visible value vectors |
Notice that contracts away during , while determines the output width directly. They are usually equal, though the math never requires it.
A trace with real numbers
Take two tokens with 2-dimensional projections (): "Birds" has , , , and "sing" has , , . Multiplying , dividing by , and running row-wise softmax gives:
Multiplying blends "Birds" into and "sing" into . Because each valid row of is a probability distribution, every output stays inside the convex hull of visible values. Verify both unmasked and lower-triangular causal attention in NumPy:
import numpy as np
Q = np.array([[1.0, 0.5], [0.5, 1.0]])
K = np.array([[0.8, 0.2], [0.3, 0.9]])
V = np.array([[2.0, 1.0], [1.0, 2.0]])
def attention(Q, K, V, mask=None):
scores = (Q @ K.T) / np.sqrt(Q.shape[-1])
if mask is not None:
scores = np.where(mask, scores, -np.inf)
shifted = scores - scores.max(axis=-1, keepdims=True)
weights = np.exp(shifted)
weights /= weights.sum(axis=-1, keepdims=True)
return weights @ V, weights
out_bi, w_bi = attention(Q, K, V)
causal = np.tril(np.ones((2, 2), dtype=bool))
out_causal, w_causal = attention(Q, K, V, mask=causal)
print("Unmasked weights:\n", np.round(w_bi, 3))
print("Unmasked output:\n", np.round(out_bi, 3))
print("Causal weights:\n", np.round(w_causal, 3))
print("Causal output:\n", np.round(out_causal, 3))Unmasked weights:
[[0.526 0.474]
[0.421 0.579]]
Unmasked output:
[[1.526 1.474]
[1.421 1.579]]
Causal weights:
[[1. 0. ]
[0.421 0.579]]
Causal output:
[[2. 1. ]
[1.421 1.579]]With the causal mask, "Birds" puts weight 1.0 on itself and returns [2.0, 1.0], while "sing" sees both tokens and keeps [1.421, 1.579].
Why scale by ? The variance proof
With , dividing by barely shifts the scores. At or , omitting that factor silently stalls learning.
Model the coordinates of and at initialization as mutually independent with mean and variance .[1] Each coordinate product has mean and variance . Summing independent terms yields and standard deviation . Dividing by restores unit variance:
Why wide logits kill gradients
Softmax exponentiates logit gaps. When one score beats its neighbors by 20, , snapping the winning weight to and crushing every other weight to . From the softmax Jacobian , when , both and every off-diagonal term collapse toward zero, starving and of routing gradients. Adding a uniform constant (+1000) changes nothing because softmax is shift-invariant; it is logit spread that saturates it.

import numpy as np
rng = np.random.default_rng(7)
for d_k in (16, 64, 512):
q = rng.standard_normal((5000, d_k))
k = rng.standard_normal((5000, d_k))
raw = np.sum(q * k, axis=1)
scaled = raw / np.sqrt(d_k)
print(f"d_k={d_k:3d}: raw std={raw.std():5.2f}, scaled std={scaled.std():4.2f}")
def softmax(z):
e = np.exp(z - np.max(z))
return e / e.sum()
for name, logits in [("uniform", [0., 0., 0.]), ("shifted", [1000., 1000., 1000.]), ("gapped", [20., 0., 0.])]:
a = softmax(np.array(logits))
print(f"{name:8s}: p0={a[0]:.4f}, self-grad p0(1-p0)={a[0]*(1-a[0]):.2e}")d_k= 16: raw std= 3.99, scaled std=1.00
d_k= 64: raw std= 8.08, scaled std=1.01
d_k=512: raw std=22.74, scaled std=1.00
uniform : p0=0.3333, self-grad p0(1-p0)=2.22e-01
shifted : p0=0.3333, self-grad p0(1-p0)=2.22e-01
gapped : p0=1.0000, self-grad p0(1-p0)=4.12e-09A 20-point gap shrinks the self-derivative from 0.222 to 4.12e-09. Dividing by keeps initialization-time logits in softmax's responsive zone rather than over-shrinking them by .
Three types of attention
The attention operator stays identical across Transformer families; only the mask and where originate change.[1]
| Attention Type | Source | Source | Mask | Typical Models |
|---|---|---|---|---|
| Bidirectional Self | Same sequence | Same sequence | Padding only | BERT, ViT |
| Causal Self | Same sequence | Same sequence | Lower-triangular () + padding | GPT, Llama |
| Cross-Attention | Target sequence () | Source sequence () | Source padding | T5, original Transformer |
Bidirectional encoders let every real token read every other token; causal decoders block future keys () so training runs in parallel without leaking upcoming tokens; cross-attention forms a rectangular routing grid from reader queries to source keys/values.

Cached queries and PyTorch mask conventions
During KV-cache decoding, a new token at absolute position 4 attends to all five cached keys [0..4], even though its local query row index is 0. Passing is_causal=True to PyTorch's F.scaled_dot_product_attention aligns the triangle to the upper-left, blinding the query to keys 1..4.[2] Build explicit masks from absolute positions (key_pos <= query_pos) intersected with valid non-padding keys, and keep PyTorch's inverted boolean conventions straight: in F.scaled_dot_product_attention, True means allowed, whereas in nn.MultiheadAttention's key_padding_mask, True means ignored.[2][3]
import torch
import torch.nn.functional as F
# Query at absolute position 2 reading 3 cached keys, where position 1 is padding.
q = torch.tensor([[[[1.0, 0.0]]]])
k = torch.tensor([[[[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]]])
v = torch.tensor([[[[1.0, 0.0], [0.0, 1.0], [2.0, 2.0]]]])
allowed = torch.tensor([[True, False, True]]) # True = participating key in SDPA
cached = F.scaled_dot_product_attention(q, k, v, attn_mask=allowed)
wrong_upper_left = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print("explicit cached mask (reads keys 0 & 2):", cached.flatten().tolist())
print("wrong is_causal=True (reads key 0 only):", wrong_upper_left.flatten().tolist())explicit cached mask (reads keys 0 & 2): [1.5, 1.0]
wrong is_causal=True (reads key 0 only): [1.0, 0.0]Deep dive: left-padded batches and all-masked query rows
In left-padded batches ([PAD, birds, sing]), padded query row 0 has no allowed key. Passing all -inf to softmax yields NaN, while filling blocked logits with a finite constant like -1e4 makes every key tie and returns a bogus uniform row [1/3, 1/3, 1/3]. Substitute zero logits on inactive rows before softmax and zero them back out afterward so both forward outputs and backward gradients stay exact zeros:
import math
import torch
q = torch.tensor([[[[1., 0.], [1., 0.], [1., 0.]]]], requires_grad=True)
k = torch.tensor([[[[9., 9.], [1., 0.], [1., 1.]]]], requires_grad=True)
v = torch.tensor([[[[999., 999.], [2., 1.], [1., 2.]]]], requires_grad=True)
valid = torch.tensor([[False, True, True]]) # [PAD, birds, sing]
pos = torch.arange(3)
causal = pos[None, :] <= pos[:, None]
active = valid[:, None, :, None]
allowed = causal[None, None] & valid[:, None, None, :] & active
logits = (q @ k.transpose(-2, -1)) / math.sqrt(q.shape[-1])
safe_logits = torch.where(active, logits.masked_fill(~allowed, -torch.inf), 0.0)
weights = torch.softmax(safe_logits, dim=-1).masked_fill(~active, 0.0)
context = weights @ v
context[..., 0].sum().backward()
print("row sums:", weights.sum(dim=-1).flatten().tolist())
print("context:", context.detach()[0, 0].tolist())
print("pad token grad norm:", q.grad[0, 0, 0].norm().item())row sums: [0.0, 1.0, 1.0]
context: [[0.0, 0.0], [2.0, 1.0], [1.5, 1.5]]
pad token grad norm: 0.0Multi-head attention
One head averages every relationship into a single weight row. Multi-Head Attention (MHA) runs parallel heads of width , concatenates their outputs, and mixes them with :[1]
Each head learns an independent routing pattern (for example, local syntax or copy-like induction circuits),[4][5] though ablation studies show trained heads vary widely in importance.[6]

Gradient flow through attention
Writing one query output as and plugging in the softmax Jacobian gives:[7]
Raising key 's score pulls toward and away from the current blend . If all visible keys carry identical values () or only one key is unmasked (), routing gradients vanish () while the value path still receives nonzero gradient . With upstream scalar score , backward attention avoids building an Jacobian via one row-wise dot product:[7]
import torch
# 1. Verify (B, N, D) -> (B, h, N, d_k) -> (B, N, D) round-trip
B, N, D, h = 2, 3, 8, 4
x = torch.arange(B * N * D, dtype=torch.float64).reshape(B, N, D)
heads = x.view(B, N, h, D // h).transpose(1, 2)
restored = heads.transpose(1, 2).contiguous().view(B, N, D)
assert torch.equal(x, restored)
print("head tensor shape:", tuple(heads.shape))
# 2. Verify Jacobian-free softmax backward with a masked third key
z = torch.tensor([[0.0, 0.0, 5.0]], dtype=torch.float64, requires_grad=True)
allowed = torch.tensor([[True, True, False]])
a = torch.softmax(z.masked_fill(~allowed, -torch.inf), dim=-1)
upstream = torch.tensor([[2.0, 1.0, 99.0]], dtype=torch.float64)
manual_dz = a * (upstream - (a * upstream).sum(dim=-1, keepdim=True))
(a * upstream).sum().backward()
assert torch.allclose(manual_dz, z.grad)
print("weights:", a.detach().flatten().tolist())
print("logit gradients (masked key gets 0):", z.grad.flatten().tolist())head tensor shape: (2, 4, 3, 2)
weights: [0.5, 0.5, 0.0]
logit gradients (masked key gets 0): [0.25, -0.25, 0.0]Each logit gradient row sums to zero (reflecting shift invariance), and the masked key receives exact 0.0 gradient regardless of its upstream signal.
Complexity analysis
Attention hits two completely different walls depending on whether you are training/prefilling or decoding.
| Cost | Complexity | Driver |
|---|---|---|
| Attention core | and across all token pairs | |
| Q/K/V and projections | Four dense linear layers per block | |
| Naive score memory | Materializing one matrix per head | |
| KV-cache memory (decode) | Storing past keys and values across layers |
For batch 8, 32 heads, and in FP16 (2 bytes), a single layer's naive score matrix takes () before weights or optimizer state.

Training vs. decoding: two different hardware walls
- Training and prompt prefill hit the temporary score-matrix memory wall in GPU HBM.
- Autoregressive decoding () produces a tiny score vector, flipping the bottleneck to persistent KV-cache bandwidth: reading every cached key and value from HBM on every generated token.[8]
The persistent KV footprint across layers, batch , length , KV heads, width , and bytes/element is:
Sharing KV heads across query heads shrinks that read and boosts decode arithmetic intensity by : MHA uses ; Multi-Query Attention (MQA) shares one KV head ();[8] and Grouped-Query Attention (GQA) shares KV heads across query groups (Llama 3.1 70B uses , cutting a 320 GiB batch-16 FP16 cache at by 8x to 40 GiB).[9][10]
layers, tokens, d_head, bytes_fp16, q_heads = 32, 8192, 128, 2, 32
for label, kv_heads in [("MHA", 32), ("GQA-8", 8), ("MQA", 1)]:
cache_gib = (2 * layers * kv_heads * d_head * tokens * bytes_fp16) / 1024**3
core_flops = 4 * tokens * q_heads * d_head
kv_bytes = 2 * tokens * kv_heads * d_head * bytes_fp16
print(f"{label:5s}: cache={cache_gib:.3f} GiB, decode intensity={core_flops / kv_bytes:2.0f} FLOPs/byte")MHA : cache=4.000 GiB, decode intensity= 1 FLOPs/byte
GQA-8: cache=1.000 GiB, decode intensity= 4 FLOPs/byte
MQA : cache=0.125 GiB, decode intensity=32 FLOPs/byteFlashAttention and MQA/GQA solve opposite bottlenecks: FlashAttention eliminates temporary score traffic during training/prefill, while MQA/GQA shrink persistent KV-cache bandwidth during decode.
Softmax numerical stability
Raw overflows float32 near and float16 near . Subtracting the row maximum cancels algebraically while capping every exponent at :[11]
On [1000, 1001, 999], subtracting 1001 passes [-1, 0, -2] to exp, giving [0.2447, 0.6652, 0.0900].
Deep dive: FP16 score overflow before softmax
Max-shifting cannot fix scores that already overflowed to inf inside FP16 Q @ K.T (e.g., 300 * 300 = 90,000 > 65,504). Accumulate scores in FP32 before softmax, and always pass dropout_p=0.0 at evaluation so attention dropout does not perturb outputs:
import torch
q = torch.tensor([[300.]], dtype=torch.float16)
k = torch.tensor([[300.], [0.]], dtype=torch.float16)
late_cast = torch.softmax((q @ k.T).float(), dim=-1)
wide_first = torch.softmax(q.float() @ k.float().T, dim=-1)
print("late FP32 cast:", late_cast.flatten().tolist())
print("FP32 matmul first:", wide_first.flatten().tolist())late FP32 cast: [nan, nan]
FP32 matmul first: [1.0, 0.0]FlashAttention: tiled exact attention
Naive GPU attention writes , reads , writes , and reads across HBM. FlashAttention computes exact dense attention with zero HBM score writes by streaming , , and tiles through on-chip SRAM using online softmax:[7][11]
After streaming every key/value tile, one division recovers the exact attention row. Backward saves only row log-sum-exp statistics and recomputes score tiles on chip. Verify that tiled online attention matches full-row attention to 12 decimal places, even across [1000, 1001, 999] or a fully masked leading tile:
import math
def online_attention(tiles):
m, denom, num = -math.inf, 0.0, 0.0
for logits, values in tiles:
if not logits or max(logits) == -math.inf:
continue # Skip empty or fully masked tiles cleanly
m_new = max(m, max(logits))
scale = math.exp(m - m_new)
w = [math.exp(x - m_new) for x in logits]
denom = scale * denom + sum(w)
num = scale * num + sum(wi * vi for wi, vi in zip(w, values))
m = m_new
return num / denom
scores, values = [1000.0, 1001.0, 999.0], [2.0, 1.0, 4.0]
exps = [math.exp(s - max(scores)) for s in scores]
full = sum(w * v for w, v in zip(exps, values)) / sum(exps)
tiled = online_attention([(scores[:1], values[:1]), (scores[1:], values[1:])])
with_masked = online_attention([([-math.inf], [20.0]), (scores, values)])
assert abs(tiled - full) < 1e-12 and abs(with_masked - full) < 1e-12
print(f"full-row: {full:.6f}, two-tile: {tiled:.6f}, with masked tile: {with_masked:.6f}")full-row: 1.514820, two-tile: 1.514820, with masked tile: 1.514820In PyTorch, F.scaled_dot_product_attention dispatches fused FlashAttention kernels automatically without custom CUDA code.[2]
Mistakes that break attention
- Untransposed keys or wrong softmax axis: Test with and always apply softmax over keys (
dim=-1). - Missing scaling: Saturates softmax at large and kills routing gradients.
- Upper-left
is_causal=Trueduring cached decode: Build explicit masks from absolute positionsk_pos <= q_pos. - All-masked query rows: Suppress padded queries explicitly before and after softmax to avoid
NaN(with-inf) or bogus uniform weights (with-1e4). - Wrong bottleneck: Use FlashAttention for score-matrix I/O and MQA/GQA for persistent KV-cache reads.
Going deeper: additive attention vs. dot-product, and attending to nothing
- Dot-product vs. additive attention: Bahdanau et al. (2015)[12] scored compatibility via ; dot products match its quality while mapping directly to GPU matrix multiplications.[1]
- Attending to nothing: Valid softmax rows always sum to 1, so layers either cancel value vectors to zero or park unused weight on a low-norm sink token.
Practice drill
In the two-token NumPy script above, set both rows of V to [3.0, -1.0] while keeping Q and K distinct: every blend returns [3.0, -1.0], so even while . Restore distinct values and mask out key 1 so only key 0 remains visible: again , confirming that routing gradients flow only when a query sees multiple keys carrying distinct values.