import math
import torch
def attention(q, k, v, mask=None):
scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
weights = torch.softmax(scores, dim=-1)
return weights @ vAttention
Intuition
Compared to MLP, attention uses input-dependent mixing weights rather than a fixed learned weight matrix. The attention weight \(w_{ij}\) measures how strongly the query representation \(q_i\) matches the key representation \(k_j\).
For each output token \(o_i\), it is a weighted sum of the value sequence tokens \(v_j\), weighted by softmax-normalized similarity scores between the query token \(q_i\) and each key token \(k_j\). So intuitively:
query→which positions matter?
keys→what does each position match on?
values→what information gets retrieved?
SDPA
Derivation
Given query, key, and value matrices,
\[ Q \in \mathbb{R}^{n_q \times d}, \quad K \in \mathbb{R}^{n_k \times d}, \quad V \in \mathbb{R}^{n_k \times d_v}, \]
scaled dot-product attention is
\[ \operatorname{Attention}(Q,K,V) = \operatorname{softmax}\left(\frac{QK^T}{\sqrt d}\right)V. \]
Minimal PyTorch implementation
Sanity check
torch.manual_seed(0)
q = torch.randn(2, 4, 8)
k = torch.randn(2, 4, 8)
v = torch.randn(2, 4, 8)
out = attention(q, k, v)
out.shapetorch.Size([2, 4, 8])
Why Scale Dot-Product Attention by \(\sqrt{d_k}\)?
Why does a larger \(QK^T\) make softmax more peaked?
Softmax depends on the difference between logits, not whether all logits are large.
\[ \operatorname{softmax}(x_i) = \frac{e^{x_i}} {\sum_{j=1}^{n} e^{x_j}} \]
For example:
\[ \operatorname{softmax}([1,2,3]) \approx [0.09, 0.24, 0.67] \]
but
\[ \operatorname{softmax}([10,20,30]) \approx [0,0,1]. \]
Softmax is invariant to adding a constant:
\[ \operatorname{softmax}(x) = \operatorname{softmax}(x+c), \]
but not to multiplying by a constant:
\[ \operatorname{softmax}(\alpha x) = \operatorname{softmax}\left(\frac{x}{T}\right), \qquad T=\frac{1}{\alpha}. \]
So increasing the spread of the logits is equivalent to lowering the softmax temperature, which makes the distribution more peaked.
Why does \(q^T k\) grow with dimension?
Assume each component is approximately zero-mean with unit variance:
\[ q_r, k_r \sim (0,1). \]
Then
\[ q^T k = \sum_{r=1}^{d_k} q_r k_r. \]
If the terms are approximately independent,
\[ \operatorname{Var}(q^T k) \approx d_k, \]
so
\[ \operatorname{Std}(q^T k) \approx \sqrt{d_k}. \]
The scores do not all become large positive numbers. Instead, their spread grows with \(\sqrt{d_k}\), which makes softmax increasingly saturated (peaked).
Therefore attention uses
\[ \frac{q^T k}{\sqrt{d_k}} \]
so that the logit scale stays roughly constant as \(d_k\) changes.
Intuition: \(1/\sqrt{d_k}\) is variance normalization, not vector normalization.
Why Not Use Cosine Similarity?
Cosine similarity is
\[ \frac{q^T k}{\|q\|\|k\|}. \]
Since
\[ q^T k = \|q\|\|k\|\cos\theta, \]
dot-product attention can use both:
- direction / alignment
- vector magnitude
Cosine similarity removes the magnitude information.
This matters because \(Q\) and \(K\) are learned specifically for attention:
\[ q_i = x_iW_Q, \qquad k_j = x_jW_K. \]
The model may therefore learn useful information in their norms.
For random high-dimensional vectors,
\[ \|q\| \approx \sqrt{d_k}, \qquad \|k\| \approx \sqrt{d_k}, \]
so
\[ \frac{q^T k}{\|q\|\|k\|} \approx O\left(\frac{1}{\sqrt{d_k}}\right). \]
Cosine similarities therefore concentrate near zero as dimension grows, so cosine attention usually needs an additional temperature parameter to control softmax sharpness.
Interview Takeaway
Scaled dot-product attention uses
\[ \operatorname{softmax} \left( \frac{QK^T}{\sqrt{d_k}} \right)V. \]
The \(1/\sqrt{d_k}\) term keeps the variance of attention logits roughly constant as head dimension grows, preventing softmax saturation while preserving magnitude information in \(Q\) and \(K\).
Interview questions
- Why is the scaling factor \(1/\sqrt d\) rather than \(1/d\)?
- What happens to gradient flow when attention logits become very large?
- Softmax saturation. Gradients vanish for Q and K, but not for V. The routing becomes fixed.
- What are the time and memory complexities of standard attention?
- What does FlashAttention change, and what does it leave mathematically unchanged?
- How do MHA, MQA, and GQA differ?
Multi-Head Attention (MHA)
Motivation
Attention can be viewed as factorizing interaction into token mixing and feature mixing. MHA gives different feature subspaces different token-mixing operators.
In single-head attention, the same token-mixing scalar \(A_{ij}\) is shared across all feature dimensions. Multi-head attention relaxes this by introducing a head dimension, \(A_{ij}^{(h)}\), so different feature subspaces can use different attention weights. In this sense, heads are an efficient way to make token mixing conditional on the representation subspace, without paying the cost of fully feature-dependent routing \(A_{ijc}\).
Instead of performing one attention operation with the full model dimension, multi-head attention projects the input into \(h\) different query, key, and value subspaces:
\[ Q_i = XW_i^Q, \qquad K_i = XW_i^K, \qquad V_i = XW_i^V. \]
Each head independently computes
\[ \operatorname{head}_i = \operatorname{Attention}(Q_i,K_i,V_i), \]
and the results are concatenated and projected:
\[ \operatorname{MHA}(X) = \operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_h)W_O. \]
Low-Rank Note
For each head,
\[ S^{(h)} = Q^{(h)}K^{(h)T} \]
and therefore
\[ \operatorname{rank}(S^{(h)}) \le d_h. \]
So each head’s pre-softmax token-interaction matrix is low-rank when \(d_h \ll T\).
Shapes
Fill in the missing shapes:
| Tensor | Shape |
|---|---|
| Input \(X\) | \((B,T,d_{\text{model}})\) |
| Projected \(Q,K,V\) | TODO |
| Split into heads | TODO |
| Attention scores | TODO |
| Per-head output | TODO |
| Concatenated output | TODO |
Learning prompt: If the total projection dimension remains \(d_{\text{model}}\), does using more heads increase the leading-order compute complexity?
Minimal PyTorch implementation
import torch.nn as nn
class MultiHeadSelfAttention(nn.Module):
def __init__(self, d_model, num_heads):
super().__init__()
assert d_model % num_heads == 0
self.d_model = d_model
self.num_heads = num_heads
self.d_head = d_model // num_heads
self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False)
self.out_proj = nn.Linear(d_model, d_model, bias=False)
def forward(self, x, mask=None):
batch_size, seq_len, _ = x.shape
# (B, T, 3 * D) -> three tensors of shape (B, T, D)
q, k, v = self.qkv_proj(x).chunk(3, dim=-1)
# (B, T, D) -> (B, H, T, D_h)
def split_heads(tensor):
return tensor.view(
batch_size, seq_len, self.num_heads, self.d_head
).transpose(1, 2)
q, k, v = map(split_heads, (q, k, v))
# mask must be broadcastable to (B, H, T, T), where True means allowed.
head_outputs = attention(q, k, v, mask=mask)
# (B, H, T, D_h) -> (B, T, D)
output = head_outputs.transpose(1, 2).contiguous().view(
batch_size, seq_len, self.d_model
)
return self.out_proj(output)torch.manual_seed(0)
x = torch.randn(2, 4, 16)
mha = MultiHeadSelfAttention(d_model=16, num_heads=4)
mha(x).shapetorch.Size([2, 4, 16])
Implementation exercises
Causal Masking
In autoregressive self-attention, token \(i\) must not attend to future tokens \(j>i\).
\[ M_{ij} = \begin{cases} 0, & j \le i, \\ -\infty, & j > i. \end{cases} \]
The mask is applied before softmax:
\[ A = \operatorname{softmax}\left( \frac{QK^T}{\sqrt{d_k}} + M \right). \]
Minimal implementation
The attention function above uses a Boolean mask where True means that attention is allowed.
def causal_mask(seq_len, device=None):
return torch.ones(
seq_len, seq_len, dtype=torch.bool, device=device
).tril()
mask = causal_mask(seq_len=4)
masktensor([[ True, False, False, False],
[ True, True, False, False],
[ True, True, True, False],
[ True, True, True, True]])
For multi-head attention, (T, T) broadcasts across the batch and head dimensions:
out = mha(x, mask=causal_mask(x.shape[1], x.device))
out.shapetorch.Size([2, 4, 16])
Questions to fill in
- Why must masking happen before softmax?
- Why does using a large negative finite number sometimes work in place of \(-\infty\)?
- What happens if an entire row is masked?
- How do a causal mask and a padding mask combine?
- During single-token autoregressive decoding with a complete KV cache, is an explicit causal mask still necessary?
Multi-Query Attention (MQA) and Grouped-Query Attention (GQA)
MHA gives each query head its own key and value heads. MQA shares one key head and one value head across all query heads. GQA is the interpolation between them.
| Variant | Query heads | KV heads | Group size |
|---|---|---|---|
| MHA | \(h\) | \(h\) | \(1\) |
| GQA | \(h\) | \(g\), where \(1<g<h\) | \(h/g\) |
| MQA | \(h\) | \(1\) | \(h\) |
Using \(h_q\) query heads and \(h_{kv}\) key/value heads:
\[ Q \in \mathbb{R}^{B \times h_q \times T_q \times d_h}, \]
\[ K,V \in \mathbb{R}^{B \times h_{kv} \times T_{kv} \times d_h}, \qquad h_q \bmod h_{kv}=0. \]
Each KV head serves
\[ n_{\text{rep}} = \frac{h_q}{h_{kv}} \]
query heads.
Why use fewer KV heads?
Learning prompt: Separate the effect on training compute, parameter count, KV-cache memory, and memory bandwidth during autoregressive decoding.
Implementation skeleton
def repeat_kv(x, num_repeats):
"""Expand (B, H_kv, T, D_h) to (B, H_q, T, D_h)."""
if num_repeats == 1:
return x
batch_size, num_kv_heads, seq_len, d_head = x.shape
return (
x[:, :, None, :, :]
.expand(batch_size, num_kv_heads, num_repeats, seq_len, d_head)
.reshape(batch_size, num_kv_heads * num_repeats, seq_len, d_head)
)Implementation exercises:
Attention Optimization Methods
FlashAttention
Standard attention materializes the \(T \times T\) score and probability matrices in high-bandwidth memory (HBM). FlashAttention computes exact attention in tiles and uses an online softmax so these full intermediate matrices do not need to be stored in HBM.
Online Softmax Derivation
For the first \(k\) logits, maintain
\[ m_k = \max_{1 \le j \le k} x_j, \qquad \ell_k = \sum_{j=1}^{k} e^{x_j-m_k}. \]
After observing \(x_{k+1}\),
\[ m_{k+1} = \max(m_k, x_{k+1}). \]
Then
\[ \begin{aligned} \ell_{k+1} &= \sum_{j=1}^{k+1} e^{x_j-m_{k+1}} \\ &= \sum_{j=1}^{k} e^{x_j-m_{k+1}} + e^{x_{k+1}-m_{k+1}} \\ &= \sum_{j=1}^{k} e^{x_j-m_k} e^{m_k-m_{k+1}} + e^{x_{k+1}-m_{k+1}} \\ &= \ell_k e^{m_k-m_{k+1}} + e^{x_{k+1}-m_{k+1}}. \end{aligned} \]
Therefore the online recurrence is
\[ \boxed{ m_{k+1} = \max(m_k,x_{k+1}), \qquad \ell_{k+1} = \ell_k e^{m_k-m_{k+1}} + e^{x_{k+1}-m_{k+1}} } \]
and after processing all logits,
\[ \operatorname{softmax}(x_i) = \frac{e^{x_i-m_N}}{\ell_N}. \]
FlashAttention applies the same idea row-wise and block-wise. The score matrix is divided along both its query-row and key-column dimensions:
key positions
K¹ K² K³
┌─────────┬─────────┬─────────┐
│ S⁽¹˒¹⁾ │ S⁽¹˒²⁾ │ S⁽¹˒³⁾ │ → output tile O¹
query positions Q¹ │ │ │ │
├─────────┼─────────┼─────────┤
│ S⁽²˒¹⁾ │ S⁽²˒²⁾ │ S⁽²˒³⁾ │ → output tile O²
Q² │ │ │ │
└─────────┴─────────┴─────────┘
stream left to right →
Each score tile is
\[ S^{(i,j)} = Q^{(i)}K^{(j)T} \in \mathbb{R}^{B_q \times B_k}. \]
For one query tile \(Q^{(i)}\), the algorithm streams from left to right through all key/value tiles. The online-softmax state is maintained separately for each query row. Thus, a score tile spans both rows and columns, while the softmax reduction and streaming happen across the key-column dimension.
Symbols and state
The batch and head dimensions are omitted below. \(B_q\) and \(B_k\) are the query and key tile sizes, and \(d_v\) is the value-head dimension.
| Symbol | Shape | Scope | Meaning |
|---|---|---|---|
| \(Q^{(i)}\) | \(B_q \times d_h\) | Query tile \(i\) | A block of query vectors |
| \(K^{(j)}\) | \(B_k \times d_h\) | KV tile \(j\) | A block of key vectors |
| \(V^{(j)}\) | \(B_k \times d_v\) | KV tile \(j\) | The value vectors paired with \(K^{(j)}\) |
| \(S^{(i,j)}\) | \(B_q \times B_k\) | Current score tile | Scaled scores \(Q^{(i)}K^{(j)T}/\sqrt{d_h}\) |
| \(\widetilde m^{(i,j)}\) | \(B_q \times 1\) | Current score tile | Local row maximum within only \(S^{(i,j)}\) |
| \(m^{(i,j)}\) | \(B_q \times 1\) | Running state | Row maximum across KV tiles \(1,\ldots,j\) |
| \(P^{(i,j)}\) | \(B_q \times B_k\) | Current score tile | Shifted, unnormalized weights \(e^{S^{(i,j)}-m^{(i,j)}}\) |
| \(\ell^{(i,j)}\) | \(B_q \times 1\) | Running state | Softmax denominator across KV tiles \(1,\ldots,j\) |
| \(N^{(i,j)}\) | \(B_q \times d_v\) | Running state | Rescaled, unnormalized weighted sum of values |
| \(O^{(i)}\) | \(B_q \times d_v\) | Completed query tile | Final normalized output \(N^{(i,J)}/\ell^{(i,J)}\) |
Here, \(P\) is not yet the final softmax probability matrix. It contains the unnormalized contribution of the current score tile using the newest running maximum.
For a block of scores \(S^{(b)}\), let \(m^{(b-1)}\), \(\ell^{(b-1)}\), and \(N^{(b-1)}\) be the running row maximum, softmax denominator, and unnormalized attention output. The update for each row is
\[ \begin{aligned} \widetilde m^{(b)} &= \max_j S_{j}^{(b)}, \\ m^{(b)} &= \max\left(m^{(b-1)}, \widetilde m^{(b)}\right), \\ P^{(b)} &= \exp\left(S^{(b)}-m^{(b)}\right), \\ \ell^{(b)} &= e^{m^{(b-1)}-m^{(b)}}\ell^{(b-1)} + \sum_j P_j^{(b)}, \\ N^{(b)} &= e^{m^{(b-1)}-m^{(b)}}N^{(b-1)} + P^{(b)}V^{(b)}. \end{aligned} \]
After the final key/value block,
\[ O = \frac{N^{(B)}}{\ell^{(B)}}. \]
The factor \(e^{m^{(b-1)}-m^{(b)}}\) rescales the old denominator and numerator whenever a later block contains a larger maximum. This is the step that makes block-wise softmax exact: all old and new terms end up expressed relative to the same maximum.
How the tiled algorithm works
For each query tile, FlashAttention:
- Loads a block of \(Q\) into fast on-chip SRAM.
- Streams blocks of \(K\) and \(V\) through SRAM.
- Computes one score tile \(Q^{(i)}K^{(j)T}\) at a time.
- Updates the running \(m\), \(\ell\), and output numerator \(N\) with the equations above.
- Writes only the completed output tile back to HBM.
Thus, it never writes the full score matrix or softmax matrix to HBM. The arithmetic is still \(O(T^2d)\) for dense self-attention, but substantially less HBM traffic makes it faster in practice. During training, the backward pass can recompute score tiles from \(Q\), \(K\), and \(V\) instead of storing the full attention matrix.
Minimal tiled implementation
This implementation demonstrates the forward algorithm, including optional causal masking. It is mathematically equivalent to standard attention up to floating-point rounding, but Python loops and ordinary PyTorch operations do not make it a fast kernel. Real FlashAttention fuses these operations and manages SRAM explicitly in CUDA or Triton.
@torch.no_grad()
def flash_attention_reference(
q,
k,
v,
query_block_size=32,
kv_block_size=32,
causal=False,
):
"""Educational tiled attention for tensors shaped (B, H, T, D)."""
batch_size, num_heads, query_len, d_head = q.shape
_, _, kv_len, _ = k.shape
d_value = v.shape[-1]
scale = 1.0 / math.sqrt(d_head)
# Accumulate in FP32 even if the input uses a lower-precision dtype.
output = torch.empty(
batch_size,
num_heads,
query_len,
d_value,
device=q.device,
dtype=torch.float32,
)
for q_start in range(0, query_len, query_block_size):
q_end = min(q_start + query_block_size, query_len)
q_block = q[:, :, q_start:q_end].float()
rows = q_end - q_start
# One running state per attention row.
m = torch.full(
(batch_size, num_heads, rows, 1),
-torch.inf,
device=q.device,
)
ell = torch.zeros_like(m)
numerator = torch.zeros(
batch_size,
num_heads,
rows,
d_value,
device=q.device,
)
for kv_start in range(0, kv_len, kv_block_size):
kv_end = min(kv_start + kv_block_size, kv_len)
k_block = k[:, :, kv_start:kv_end].float()
v_block = v[:, :, kv_start:kv_end].float()
scores = (q_block @ k_block.transpose(-2, -1)) * scale
if causal:
q_positions = torch.arange(q_start, q_end, device=q.device)
kv_positions = torch.arange(kv_start, kv_end, device=q.device)
allowed = kv_positions[None, :] <= q_positions[:, None]
scores = scores.masked_fill(~allowed, -torch.inf)
block_max = scores.amax(dim=-1, keepdim=True)
new_m = torch.maximum(m, block_max)
correction = torch.exp(m - new_m)
exp_scores = torch.exp(scores - new_m)
ell = correction * ell + exp_scores.sum(dim=-1, keepdim=True)
numerator = (
correction * numerator + exp_scores @ v_block
)
m = new_m
output[:, :, q_start:q_end] = numerator / ell
return output.to(q.dtype)torch.manual_seed(0)
q = torch.randn(2, 4, 17, 8)
k = torch.randn(2, 4, 17, 8)
v = torch.randn(2, 4, 17, 8)
expected = attention(q, k, v, mask=causal_mask(17))
actual = flash_attention_reference(
q, k, v, query_block_size=5, kv_block_size=7, causal=True
)
torch.testing.assert_close(actual, expected, atol=1e-5, rtol=1e-5)
actual.shapetorch.Size([2, 4, 17, 8])
Key distinction: FlashAttention changes the algorithm’s memory access pattern, not the mathematical definition of attention.
Concepts to fill in
Interview checkpoint
Explain this statement precisely:
FlashAttention is IO-aware exact attention; it does not make dense attention asymptotically subquadratic in arithmetic complexity.
KV Caching
During autoregressive generation, previously computed keys and values do not change. Cache them instead of recomputing them at every decoding step.
At decoding step \(t\):
\[ K_{1:t} = \operatorname{Concat}(K_{1:t-1}, k_t), \qquad V_{1:t} = \operatorname{Concat}(V_{1:t-1}, v_t). \]
The new query attends to the cached prefix:
\[ o_t = \operatorname{softmax}\left( \frac{q_tK_{1:t}^T}{\sqrt{d_h}} \right)V_{1:t}. \]
Prefill versus decode
| Phase | Query length | Main operation | Typical bottleneck |
|---|---|---|---|
| Prefill | \(T\) | Process the prompt in parallel | TODO |
| Decode | \(1\) per step | Read cached K/V and produce one token | TODO |
Cache-size derivation
For \(L\) layers, batch size \(B\), sequence length \(T\), \(h_{kv}\) KV heads, head dimension \(d_h\), and \(s\) bytes per element:
\[ \text{KV-cache bytes} = 2LBTh_{kv}d_hs. \]
Exercise: Calculate the cache size for one sequence using your choice of model configuration in FP16/BF16. Then repeat for MHA, GQA, and MQA.
Implementation skeleton
def append_to_kv_cache(k_new, v_new, cache=None):
"""A simple educational cache; production systems preallocate storage."""
if cache is None:
return k_new, v_new
k_cache, v_cache = cache
k_cache = torch.cat([k_cache, k_new], dim=-2)
v_cache = torch.cat([v_cache, v_new], dim=-2)
return k_cache, v_cacheQuestions to fill in:
- Why is repeated
torch.catinefficient in a production decoder? - Why does KV caching reduce computation but increase persistent memory use?
- How do MQA and GQA reduce decode-time memory bandwidth?
- What changes when prompts in a batch have different lengths?
- What are paged attention, prefix caching, and cache quantization?
Suggested Next Topics
After the path above, useful additions would be:
- RoPE and positional information — attention alone is permutation-equivariant; modern LLMs need position-dependent Q/K representations.
- Numerical stability and precision — stable softmax, FP16/BF16 behavior, masking edge cases, and accumulation precision.
- Sliding-window and sparse attention — methods that change which token pairs interact and can reduce arithmetic complexity.
- Cross-attention — separates the query sequence from the key/value sequence and makes the general SDPA shapes concrete.
- Production inference details — paged KV caches, continuous batching, and speculative decoding.