Skip to content
Skip to lesson
Back to Topics
HardTransformer Architecture17 min read

Scaled Dot-Product Attention

Each token mixes content from positions it may read. The score scale, the mask, and the memory traffic decide whether that mix stays usable.

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.

solves it with a soft, differentiable lookup.[1] Each 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, 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 , "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].
One causal attention pass on "Birds sing." The mask restricts Birds to its own value, while sing blends 42% of Birds with 58% of itself to produce [1.42, 1.58].

Three views of one token

Raw XXTX X^T force every token to ask for context and advertise context in the same subspace. Three learned linear projections WQ,WK∈Rdmodel×dkW_Q, W_K \in \mathbb{R}^{d_{\text{model}} \times d_k} and WV∈Rdmodel×dvW_V \in \mathbb{R}^{d_{\text{model}} \times d_v} split routing from content cleanly:[1]

Q=XWQ,K=XWK,V=XWVQ = XW_Q, \quad K = XW_K, \quad V = XW_V
  • Query (QQ): what context this position needs (scores candidate sources).
  • Key (KK): when another position should read this token (matched against incoming queries).
  • Value (VV): what payload this token contributes once selected.

Even when raw scores QKTQK^T 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.
One hidden state splits into three views. Query [1.0, 0.5] and key [0.8, 0.2] compute routing score 0.90, while value [2.0, 1.0] waits to be mixed by the normalized weights.

The core formula

Scaled dot-product attention packs scoring, scaling, masking, normalization, and value mixing into one expression:[1]

Attention(Q,K,V;M)=softmax(QKTdk+M)V\text{Attention}(Q, K, V; M) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}} + M\right)V

The additive mask MM puts 00 on allowed keys and −∞-\infty on blocked keys so e−∞=0e^{-\infty} = 0 removes blocked positions before normalization while the remaining weights still sum to 1.

StepOperationShapeRole
Score & scaleL=QKT/dkL = QK^T / \sqrt{d_k}(B,h,Nq,Nk)(B, h, N_q, N_k)Pairwise compatibility with steady variance
MaskZ=L+MZ = L + M(B,h,Nq,Nk)(B, h, N_q, N_k)Blocks disallowed keys with −∞-\infty
Normalizeα=softmax(Z,dim=−1)\alpha = \text{softmax}(Z, \text{dim}=-1)(B,h,Nq,Nk)(B, h, N_q, N_k)Row-wise probability weights over keys
MixO=αVO = \alpha V(B,h,Nq,dv)(B, h, N_q, d_v)Weighted average of visible value vectors

Notice that dkd_k contracts away during QKTQK^T, while dvd_v 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 (dk=dv=2d_k = d_v = 2): "Birds" has q=[1.0,0.5]q=[1.0, 0.5], k=[0.8,0.2]k=[0.8, 0.2], v=[2.0,1.0]v=[2.0, 1.0], and "sing" has q=[0.5,1.0]q=[0.5, 1.0], k=[0.3,0.9]k=[0.3, 0.9], v=[1.0,2.0]v=[1.0, 2.0]. Multiplying QKTQ K^T, dividing by 2≈1.414\sqrt{2} \approx 1.414, and running row-wise softmax gives:

S=QKT=[0.900.750.601.05],L=S2≈[0.640.530.420.74],α=softmax(L)≈[0.530.470.420.58]\begin{aligned} S = QK^T &= \begin{bmatrix} 0.90 & 0.75 \\ 0.60 & 1.05 \end{bmatrix}, \qquad L = \frac{S}{\sqrt{2}} \approx \begin{bmatrix} 0.64 & 0.53 \\ 0.42 & 0.74 \end{bmatrix}, \qquad \alpha = \text{softmax}(L) \approx \begin{bmatrix} 0.53 & 0.47 \\ 0.42 & 0.58 \end{bmatrix} \end{aligned}

Multiplying αV\alpha V blends "Birds" into 0.53[2,1]+0.47[1,2]=[1.53,1.47]0.53[2,1] + 0.47[1,2] = [1.53, 1.47] and "sing" into 0.42[2,1]+0.58[1,2]=[1.42,1.58]0.42[2,1] + 0.58[1,2] = [1.42, 1.58]. Because each valid row of α\alpha is a probability distribution, every output stays inside the convex hull of visible values. Verify both unmasked and lower-triangular causal attention in NumPy:

scaled-dot-product-attention.py
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)
Output
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].

Read attention row by row from scaled scores to normalized weights to mixed values. Every query row sums to 1, while columns do not need to because many queries can read the same key.

Why scale by dk\sqrt{d_k}? The variance proof

With dk=2d_k = 2, dividing by 2\sqrt{2} barely shifts the scores. At dk=64d_k = 64 or 128128, omitting that factor silently stalls learning.

Model the coordinates of qq and kk at initialization as mutually independent with mean 00 and variance 11.[1] Each coordinate product qikiq_i k_i has mean 00 and variance E[qi2]E[ki2]=1\mathbb{E}[q_i^2]\mathbb{E}[k_i^2] = 1. Summing dkd_k independent terms yields Var(q⋅k)=dk\text{Var}(q \cdot k) = d_k and standard deviation dk\sqrt{d_k}. Dividing by dk\sqrt{d_k} restores unit variance:

Var ⁣(q⋅kdk)=1dkVar(q⋅k)=1\text{Var}\!\left(\frac{q \cdot k}{\sqrt{d_k}}\right) = \frac{1}{d_k}\text{Var}(q \cdot k) = 1

Why wide logits kill gradients

Softmax exponentiates logit gaps. When one score beats its neighbors by 20, e20≈4.85×108e^{20} \approx 4.85 \times 10^8, snapping the winning weight to amax⁡≈1a_{\max} \approx 1 and crushing every other weight to 00. From the softmax Jacobian ∂ai/∂zj=ai(δij−aj)\partial a_i / \partial z_j = a_i (\delta_{ij} - a_j), when amax⁡→1a_{\max} \to 1, both amax⁡(1−amax⁡)a_{\max}(1 - a_{\max}) and every off-diagonal term aiaja_i a_j collapse toward zero, starving QQ and KK of routing gradients. Adding a uniform constant (+1000) changes nothing because softmax is shift-invariant; it is logit spread that saturates it.

Under independent, mean-zero, unit-variance query and key components, raw dot-product standard deviation grows as square root of d_k while the scaled standard deviation stays at 1. These are analytic population curves; learned vectors need not satisfy the assumptions.
Raw dot-product standard deviation climbs as dk\sqrt{d_k} across head widths, while dividing by dk\sqrt{d_k} holds score spread steady at 1.
variance-scaling-simulation.py
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}")
Output
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-09

A 20-point gap shrinks the self-derivative from 0.222 to 4.12e-09. Dividing by dk\sqrt{d_k} keeps initialization-time logits in softmax's responsive zone rather than over-shrinking them by dkd_k.


Three types of attention

The attention operator stays identical across Transformer families; only the mask MM and where Q,K,VQ, K, V originate change.[1]

Attention TypeQQ SourceK,VK, V SourceMaskTypical Models
Bidirectional SelfSame sequenceSame sequencePadding onlyBERT, ViT
Causal SelfSame sequenceSame sequenceLower-triangular (k≤qk \le q) + paddingGPT, Llama
Target sequence (NqN_q)Source sequence (NkN_k)Source paddingT5, original Transformer

Bidirectional encoders let every real token read every other token; causal decoders block future keys (k>qk > q) so training runs in parallel without leaking upcoming tokens; cross-attention forms a rectangular Nq×NkN_q \times N_k routing grid from reader queries to source keys/values.

Three attention weight matrices: encoder bidirectional self-attention lets all four tokens read one another, decoder causal self-attention zeroes future columns above the diagonal, and cross-attention compares decoder queries q0 and q1 against four encoder keys k0 through k3.
One operator powers all three patterns: dense bidirectional rows, lower-triangular causal rows, and rectangular Nq×NkN_q \times N_k cross-attention between two sequences.

Cached queries and PyTorch mask conventions

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

cached-causal-and-padding.py
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())
Output
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:

batched-causal-padding-reference.py
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())
Output
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.0

Multi-head attention

One head averages every relationship into a single weight row. Multi-Head Attention (MHA) runs hh parallel heads of width dk=dv=dmodel/hd_k = d_v = d_{\text{model}} / h, concatenates their outputs, and mixes them with WOW^O:[1]

headi=Attention(XWiQ,XWiK,XWiV),MultiHead(X)=Concat(head1,…,headh)WO\text{head}_i = \text{Attention}(XW_i^Q, XW_i^K, XW_i^V), \qquad \text{MultiHead}(X) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h) W^O

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]

For one token, each projected Q, K, and V vector has width 8. Matching color pairs split each stream into four parallel width-2 heads; their four width-2 outputs concatenate to width 8, then W_O maps that result to model width 8.
A width-8 stream projects into Q, K, and V, splits into four width-2 parallel heads, concatenates back to width 8, and mixes through WOW^O.

Gradient flow through attention

Writing one query output as o=∑jajvjo = \sum_j a_j v_j and plugging in the softmax Jacobian gives:[7]

∂o∂zj=aj(vj−o)\frac{\partial o}{\partial z_j} = a_j (v_j - o)

Raising key jj's score pulls oo toward vjv_j and away from the current blend oo. If all visible keys carry identical values (vj=ov_j = o) or only one key is unmasked (aj=1a_j = 1), routing gradients vanish (∂o/∂zj=0\partial o / \partial z_j = 0) while the value path still receives nonzero gradient ∂ℓ/∂V=ATG\partial \ell / \partial V = A^T G. With upstream scalar score tj=gTvjt_j = g^T v_j, backward attention avoids building an Nk×NkN_k \times N_k Jacobian via one row-wise dot product:[7]

∂ℓ∂zj=aj(tj−∑iaiti),∂ℓ∂q=1dk∑j∂ℓ∂zjkj,∂ℓ∂V=ATG\frac{\partial \ell}{\partial z_j} = a_j \left(t_j - \sum_i a_i t_i\right), \qquad \frac{\partial \ell}{\partial q} = \frac{1}{\sqrt{d_k}}\sum_j \frac{\partial \ell}{\partial z_j} k_j, \qquad \frac{\partial \ell}{\partial V} = A^T G
mha-reshape-and-backward.py
# 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())
Output
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.

CostComplexityDriver
Attention coreO(n2dmodel)O(n^2 d_{\text{model}})QKTQK^T and αV\alpha V across all token pairs
Q/K/V and WOW^O projectionsO(ndmodel2)O(n d_{\text{model}}^2)Four dense linear layers per block
Naive score memoryO(hn2)O(h n^2)Materializing one n×nn \times n matrix per head
KV-cache memory (decode)O(L⋅hKV⋅dk⋅n)O(L \cdot h_{\text{KV}} \cdot d_k \cdot n)Storing past keys and values across LL layers

For batch 8, 32 heads, and n=8,192n = 8{,}192 in (2 bytes), a single layer's naive score matrix takes 8×32×8,1922×2=34.4 GB8 \times 32 \times 8{,}192^2 \times 2 = 34.4\text{ GB} (32 GiB32\text{ GiB}) before weights or .

Top: side-by-side 8x8 attention grids contrast Standard Attention materializing the entire N by N score matrix in HBM (O(N^2)) against FlashAttention streaming a single active B_r by B_c tile in on-chip SRAM (O(N) temporary HBM). Bottom: FP16 score-matrix size per head grows quadratically from 2 MiB at N=1k to 32 MiB at 4k, 128 MiB at 8k, and 512 MiB at 16k, while tiled FlashAttention stays flat near the bottom axis.
Naive attention writes an N×NN \times N FP16 score matrix per head to HBM (2 MiB at N=1,024N=1{,}024 up to 512 MiB at N=16,384N=16{,}384). Tiled FlashAttention keeps only one active block in on-chip SRAM so temporary HBM memory stays O(N)O(N).

Training vs. decoding: two different hardware walls

The persistent KV footprint across LL layers, batch BB, length NN, hKVh_{\text{KV}} KV heads, width dkd_k, and PbytesP_{\text{bytes}} bytes/element is:

MemoryKV=2⋅L⋅hKV⋅dk⋅N⋅B⋅Pbytes\text{Memory}_{\text{KV}} = 2 \cdot L \cdot h_{\text{KV}} \cdot d_k \cdot N \cdot B \cdot P_{\text{bytes}}

Sharing KV heads across query heads shrinks that read and boosts decode arithmetic intensity by hQ/hKVh_Q / h_{\text{KV}}: MHA uses hKV=hQh_{\text{KV}} = h_Q; Multi-Query Attention (MQA) shares one KV head (hKV=1h_{\text{KV}} = 1);[8] and Grouped-Query Attention (GQA) shares GG KV heads across query groups (Llama 3.1 70B uses L=80,hQ=64,hKV=8,dk=128L=80, h_Q=64, h_{\text{KV}}=8, d_k=128, cutting a 320 GiB batch-16 FP16 cache at N=8,192N=8{,}192 by 8x to 40 GiB).[9][10]

kv-head-bandwidth.py
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")
Output
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/byte

FlashAttention and MQA/GQA solve opposite bottlenecks: FlashAttention eliminates temporary O(n2)O(n^2) score traffic during training/prefill, while MQA/GQA shrink persistent KV-cache bandwidth during decode.


Softmax numerical stability

Raw exe^x overflows float32 near x>88x > 88 and float16 near x>11x > 11. Subtracting the row maximum m=max⁡jxjm = \max_j x_j cancels algebraically while capping every exponent at e0=1e^0 = 1:[11]

softmax(xi)=exi−m∑jexj−m\text{softmax}(x_i) = \frac{e^{x_i - m}}{\sum_j e^{x_j - m}}

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:

score-overflow-precedes-softmax.py
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())
Output
late FP32 cast: [nan, nan]
FP32 matmul first: [1.0, 0.0]

FlashAttention: tiled exact attention

Naive GPU attention writes SS, reads SS, writes PP, and reads PP across HBM. FlashAttention computes exact dense attention with zero HBM score writes by streaming QQ, KK, and VV tiles through on-chip SRAM using :[7][11]

mnew=max⁡(mold,m~),α=exp⁡(mold−mnew)ℓnew=α⋅ℓold+∑kexp⁡(S~ij,k−mnew),unew=α⋅uold+∑kexp⁡(S~ij,k−mnew)Vj,k\begin{aligned} m_{\text{new}} &= \max(m_{\text{old}}, \tilde{m}), \qquad \alpha = \exp(m_{\text{old}} - m_{\text{new}}) \\ \ell_{\text{new}} &= \alpha \cdot \ell_{\text{old}} + \sum_k \exp(\tilde{S}_{ij, k} - m_{\text{new}}), \qquad u_{\text{new}} = \alpha \cdot u_{\text{old}} + \sum_k \exp(\tilde{S}_{ij, k} - m_{\text{new}}) V_{j, k} \end{aligned}

After streaming every key/value tile, one division Oi=ufinal/ℓfinalO_i = u_{\text{final}} / \ell_{\text{final}} recovers the exact attention row. Backward saves only O(n)O(n) 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:

online-tiled-attention.py
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}")
Output
full-row: 1.514820, two-tile: 1.514820, with masked tile: 1.514820

In PyTorch, F.scaled_dot_product_attention dispatches fused FlashAttention kernels automatically without custom code.[2]


Mistakes that break attention

  • Untransposed keys or wrong softmax axis: Test with Nk≠dkN_k \neq d_k and always apply softmax over keys (dim=-1).
  • Missing 1/dk1/\sqrt{d_k} scaling: Saturates softmax at large dkd_k and kills routing gradients.
  • Upper-left is_causal=True during cached decode: Build explicit masks from absolute positions k_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 O(n2)O(n^2) score-matrix I/O and MQA/GQA for persistent KV-cache reads.
Going deeper: additive attention vs. dot-product, and attending to nothing

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 ∂ℓ/∂Q=0\partial \ell / \partial Q = 0 even while ∂ℓ/∂V≠0\partial \ell / \partial V \neq 0. Restore distinct values and mask out key 1 so only key 0 remains visible: again ∂ℓ/∂Q=0\partial \ell / \partial Q = 0, confirming that routing gradients flow only when a query sees multiple keys carrying distinct values.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.An image encoder produces seven patch vectors. Four summary tokens each read all seven patches through one cross-attention head. Which inputs supply Q, K, and V, and what shape does the weight matrix have?
2.In scaled dot-product attention, Q has shape (B, h, 5, 64), K has shape (B, h, 20, 64), and V has shape (B, h, 20, 128). What are the shapes of the attention weights and the output?
3.A query attends to two keys. Each vector has 81 coordinates, and all coordinates are mutually independent with mean 0 and variance 1. What is the population standard deviation of a raw dot product? For two unequal scores, how does skipping the usual scaling affect the larger softmax weight and its sensitivity to its own logit?
4.Two attention rows each start with logits [2, 1, 5] over three keys. The code fills blocked logits with -1e4 and then applies softmax over the keys. In the active row, only key 3 is blocked. In the padded query row, all three keys are blocked. What weights does each row get?
5.During cached decoding, a two-token chunk at absolute positions 3 and 4 reads keys at positions 0 to 4. Position 1 is padding. Using T for allowed and F for blocked, which masks are correct for the two queries?
6.A dense self-attention layer changes from two heads of width 192 to six heads of width 64. Within each head, Q, K, and V have the same width. The batch, sequence length, and score precision stay fixed. Relative to the old layout, how many multiply-adds does the attention core need for scoring and mixing values? How much memory does it need to store all scores?
7.A naive attention implementation stores one FP16 score for every query-key pair in every head. With batch size 4, 16 heads, and sequence length 4096, how large is that score tensor?
8.Keys A, B, and C have scalar values 6, −2, and 6. A mask blocks B before softmax. With attention-weight dropout off, A gets one quarter of the weight and C gets the rest. The loss equals this row's output. Which scores before masking and which individual values have nonzero gradients from this loss?
9.A team has two problems. Training on long sequences runs out of memory because it stores every attention score. Serving is limited by the bandwidth needed to read the growing KV cache for each new token. Which pair of changes targets these problems?
10.Online softmax processes one row in tiles. After the first tile, which has the single score 1000, the running maximum is 1000 and the running sum of exponentials is e1000−1000=1e^{1000-1000} = 1. The next tile has scores 1002 and 999. What is the running sum after this tile?

10 questions remaining.

References

Attention Is All You Need.

Vaswani, A., et al. · 2017

https://arxiv.org/abs/1706.03762

torch.nn.functional.scaled_dot_product_attention

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html

torch.nn.MultiheadAttention

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/generated/torch.nn.MultiheadAttention.html

Analyzing Multi-Head Self-Attention: Specialized Heads Do the Heavy Lifting, the Rest Can Be Pruned

Voita, E., Talbot, D., Moiseev, F., Sennrich, R., & Titov, I. · 2019 · ACL 2019

https://arxiv.org/abs/1905.09418

In-context Learning and Induction Heads.

Olsson, C., et al. · 2022

https://arxiv.org/abs/2209.11895

Are Sixteen Heads Really Better than One?

Michel, P., Levy, O., & Neubig, G. · 2019 · NeurIPS 2019

https://arxiv.org/abs/1905.10650

FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

Dao, T., Fu, D. Y., Ermon, S., Rudra, A., Ré, C. · 2022 · NeurIPS 2022

https://arxiv.org/abs/2205.14135

Fast Transformer Decoding: One Write-Head is All You Need.

Shazeer, N. · 2019 · arXiv preprint

https://arxiv.org/abs/1911.02150

GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints.

Ainslie, J., et al. · 2023 · EMNLP 2023

https://arxiv.org/abs/2305.13245

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

Online normalizer calculation for softmax.

Milakov, M. & Gimelshein, N. · 2018

https://arxiv.org/abs/1805.02867

Neural Machine Translation by Jointly Learning to Align and Translate.

Bahdanau, D., Cho, K., & Bengio, Y. · 2015 · ICLR 2015

https://arxiv.org/abs/1409.0473

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.