Multi-head causal self-attention
- Why one head isn't enough, and why more heads add no parameters and no matmul FLOPs
- Cut each token's channels into heads with view then transpose, and join them back without mixing positions
- Follow every shape from (B, T, C) in to (B, T, C) out
- Build the causal mask once, keep it with the module, cut it to the input's length, and keep the diagonal
- Check the head count in the constructor, add the output projection, and say what breaks without each
- The follow-ups: parameters, FLOPs and memory per layer, then multi-query and grouped-query attention
Multi-head attention, the way the coding round asks for it
Model coding rounds go one step past attention: the version with heads, in PyTorch, as a module. One OpenAI ML engineer's phone screen mainly tested how well they knew the Transformer (1 report), and a Netflix screen asked exactly how Q, K and V are computed (1 report). An OpenAI debug round ended with a KV cache as the follow-up (1 report), and that cache is where grouped-query attention comes in. This lesson's practice problem is the module, in four levels:
Write
CausalSelfAttention(n_embd, n_head)in PyTorch:xof shape(B, T, C)in,(B, T, C)out, by hand, with noF.scaled_dot_product_attentionand nonn.MultiheadAttention.
- The layers: one fused projection
self.qkv = nn.Linear(C, 3 * C), q then k then v, andself.proj = nn.Linear(C, C). RaiseValueErrorwhenn_headdoesn't dividen_embd.- The heads: split q, k and v into
n_headheads ofC // n_head, attend in every head at once, merge the heads back and project.- The mask: token
tsees only tokens<= t, with the mask built once.GroupedQueryAttention(n_embd, n_head, n_kv_head): the same layer withn_kv_headkey/value heads, each shared by a group of query heads.
Call Returns CausalSelfAttention(48, 6)onxof shape(3, 9, 48)shape (3, 9, 48)CausalSelfAttention(10, 3)ValueErrorthe outputs at positions 0 to 4, after tokens 5 to 7 change unchanged GroupedQueryAttention(32, 8, 2)2 key/value heads, each read by 4 query heads
The lesson builds the module one piece at a time: why heads, the fused projection, the split and the merge, the mask, the head check and the output projection, then the follow-ups on cost and grouped-query attention. Ten steps end with a small task in the editor. It builds on the attention lesson and on PyTorch tensors.
One head gives each token one blend
Start with why attention has heads at all.
Token 7 needs token 6 and token 3. With one head, what does it read?
Five letters name every shape
The rest of the lesson names every shape with five letters.
C = 512 and H = 8. What's d, the head size?
Several heads, each with its own softmax
Each head is a whole attention function of its own.
So run several attention functions side by side. Each head projects the full input into its own queries, keys and values, each wide. Then it runs its own softmax.
Their outputs sit in separate channels until a final projection mixes them.
The paper writes it like this:
In words:
- is the input, one row of numbers per token.
- , and are head 's own query, key and value projections, each .
- puts the head outputs side by side, and is the output projection, .
More heads add no parameters and no FLOPs: each one gets narrower
Heads sound expensive. They aren't.
C = 768 and H = 12. What shape is one head's W_Q?
One wide layer instead of 3H small ones
Every head needs its own queries, keys and values. One layer makes them all.
One nn.Linear makes every head's q, k and v at once. What are its in and out sizes?
split cuts q, k and v apart, in that order
The layer's output holds q, k and v side by side.
The layer gives each token 36 numbers, with C = 12. Which ones are k?
Each head owns a run of d channels
Inside q, the heads are just runs of channels.
C = 12 and H = 4. Which channels does head 2 own?
view cuts each token's row into heads, and moves nothing
Cutting the channels into heads takes two calls.
(2, 5, 12) viewed as (B, T, H, d) with H = 4. What's the new shape?
Every head runs at once, with no loop
With the heads in front, one matmul serves them all.
Start with one head of one sequence. qh[0, 0] is its 5 queries and kh[0, 0] its 5 keys, 3 numbers each.
kh = k.view(B, T, H, d).transpose(1, 2)
print((qh[0, 0] @ kh[0, 0].T).shape)
qh[0, 0] and kh[0, 0] are both (5, 3). What shape is qh[0, 0] @ kh[0, 0].T?
All three in one line
q, k and v all need the same split, so one line does all three.
q, k, v = (t.view(B, T, H, d).transpose(1, 2) for t in (q, k, v))
print(tuple(q.shape), tuple(k.shape), tuple(v.shape))
(2, 4, 5, 3) (2, 4, 5, 3) (2, 4, 5, 3)
t.view(B, T, H, d).transpose(1, 2) is what happens to each t, and for t in (q, k, v) runs it on all three. q, k, v = unpacks the three results back into the same names.
The same split, animated on the twelve labeled numbers that the next steps print. View cuts each position's channels into heads, transpose gathers them, and reshaping straight to heads first mixes up positions.
Label each number with where it came from
A small labeled tensor shows exactly what the split does.
Each number is 10 × position + channel. Where did 21 come from?
view and transpose keep each row one position
Now split it the right way.
print(q.view(B, T, H, d).transpose(1, 2))
tensor([[[[ 0, 1],
[10, 11],
[20, 21]],
[[ 2, 3],
[12, 13],
[22, 23]]]])
Laid side by side:
Row of each head is position , and each head holds its own two channels of it.
A bare reshape mixes positions
Now the tempting shortcut: a reshape straight to the heads' shape.
print(q.reshape(B, H, T, d))
tensor([[[[ 0, 1],
[ 2, 3],
[10, 11]],
[[12, 13],
[20, 21],
[22, 23]]]])
A bare reshape reads the twelve numbers in order, position 0's four channels, then position 1's, then position 2's, and pours them into the new shape:
"head 0" (3, 2)"head 1" (3, 2)Red rows hold the wrong position. "head 0", row 1 is the back half of position 0, and "head 1", row 0 is the back half of position 1.
The shape is right. The rows are no longer positions.
Then the mask guards the wrong rows, and the future leaks in
Mixed rows aren't just untidy. They break the mask.
view + transpose (3, 3)bare reshape (3, 3)x means the output depends on that input. Red is the future leaking in.
The causal mask trusts that row is position . After a bare reshape it guards the wrong rows.
The future leaks in, every shape is right, and nothing raises.
In the editor, write split_heads(x, n_head). It prints the split of the labeled tensor from the last few steps, so you can check that every row keeps one tens digit.
Transpose back, then join each position's pieces
After attention, the heads have to go back together.
heads = q.view(B, T, H, d).transpose(1, 2).contiguous()
print(heads.transpose(1, 2).reshape(B, T, C))
tensor([[[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23]]])
Here heads stands in for att @ v: every head's output at every position, (B, H, T, d), in a fresh tensor. The rows come back exactly as they went in.
Undo the split in reverse:
After a transpose, view fails and reshape works
One call in the merge fails, and it's worth knowing why.
heads is (1, 2, 3, 2) and contiguous, with strides (12, 6, 2, 1). What are the strides of heads.transpose(1, 2)?
Skip the transpose and the positions scramble, with no error
The quiet failure is worse: a merge without the transpose.
With no transpose, reshape(B, T, C) reads the memory of heads in order. What lands in position 0's row?
Every shape, from (B, T, C) in to (B, T, C) out
Here's the whole forward pass, one line per step.
| Step | Shape, and what it is |
|---|---|
x | (B, T, C), the input |
self.qkv(x) | (B, T, 3C): q, k and v together |
.split(C, dim=2) | (B, T, C) each: q, k and v |
.view(B, T, H, d) | (B, T, H, d): channels cut into heads |
.transpose(1, 2) | (B, H, T, d): heads first |
q @ k.transpose(-2, -1) | (B, H, T, T): the scores |
/ math.sqrt(d) | (B, H, T, T): scaled |
.masked_fill(...) | (B, H, T, T): the future set to -inf |
.softmax(dim=-1) | (B, H, T, T): the weights |
att @ v | (B, H, T, d): the values blended |
.transpose(1, 2) | (B, T, H, d): positions first |
.reshape(B, T, C) | (B, T, C): heads merged |
self.proj(y) | (B, T, C): the output |
the whole way down. The scores are the only step with two axes: one row per query, one column per key.
Scale by the square root of d, not C
One number in that table is easy to get wrong: the scale.
C = 768 and H = 12. What do you divide each score by?
Build the triangle once, then cut it to the input's length
The mask comes next, and it belongs to the module.
The mask is built once at block_size × block_size. A forward pass gets T = 4. Which part do you use?
masked_fill writes where its mask is True, so pass the flip
Applying the mask takes one call, and its argument is easy to flip the wrong way.
Pass the triangle itself to masked_fill, not its flip. Which keys can token 0 read?
Keep it as a buffer: saved and moved, never trained
Where the mask lives matters too.
class Masked(nn.Module):
def __init__(self, block_size=8):
super().__init__()
self.proj = nn.Linear(4, 4)
ones = torch.ones(block_size, block_size, dtype=torch.bool)
self.register_buffer("mask", torch.tril(ones))
m = Masked()
print(list(m.state_dict()))
print([name for name, _ in m.named_parameters()])
['mask', 'proj.weight', 'proj.bias']
['proj.weight', 'proj.bias']
The mask is saved with the model, but it isn't a parameter. A buffer is a tensor the module keeps and saves but never trains:
Keep the mask as a plain attribute, self.mask = torch.tril(...), instead. Is it saved in state_dict, and does it move with .to()?
A plain attribute stays behind when the model moves
Here's what goes wrong with a plain attribute instead.
class Plain(nn.Module):
def __init__(self, block_size=8):
super().__init__()
self.proj = nn.Linear(4, 4)
ones = torch.ones(block_size, block_size, dtype=torch.bool)
self.mask = torch.tril(ones)
for model in (Masked(), Plain()):
model.to("meta")
print(type(model).__name__, model.proj.weight.device, model.mask.device)
Masked meta meta
Plain meta cpu
meta is a stand-in device that holds shapes but no numbers. It shows the move on any machine, with no GPU. The buffer moved with the layer. The plain attribute stayed on the CPU.
On a GPU that's a crash. The first forward pass fails with expected self and mask to be on the same device, because the scores are on the GPU and the mask isn't.
If the name doesn't come to you, build the mask in forward
In an interview you can build the triangle inside forward, on the input's device:
mask = torch.tril(torch.ones(T, T, dtype=torch.bool, device=x.device))
That builds a small triangle on every call, with the same result. Say that you would keep it as a buffer, and that's a fine answer. The task in the editor names the call for you.
Buffers are saved by default. How much does a 1024 × 1024 bool mask add to each layer of a checkpoint?
Raise ValueError when C doesn't split into H heads
The constructor has one job before it builds anything: check the head count.
if n_embd % n_head:
raise ValueError("n_embd must be divisible by n_head")
The head size has to be a whole number, and PyTorch won't check it for you. So check it first thing in __init__.
Raise ValueError, not assert. The test expects a ValueError, and python -O strips asserts out.
Without the check, the error comes late and never mentions heads
Here's what happens without the check.
qkv = nn.Linear(10, 30)
q, k, v = qkv(torch.randn(1, 4, 10)).split(10, dim=2)
try:
q.view(1, 4, 3, 10 // 3)
except RuntimeError as e:
print(e)
shape '[1, 4, 3, 3]' is invalid for input of size 40
Ten channels don't fit in three heads of three. With C = 10 and H = 3, d = 10 // 3 = 3:
| Head | Channels |
|---|---|
| 0 | 0, 1, 2 |
| 1 | 3, 4, 5 |
| 2 | 6, 7, 8 |
| none | 9 |
nn.Linear(10, 30) is a valid layer, and it knows nothing about heads. So the module builds fine, and the error waits for the first forward pass.
In the editor, finish __init__: the check, self.n_head and the fused self.qkv. It prints the layer's weight shape, then tries 10 channels in 3 heads.
The output projection is where the heads meet
After the merge, y has the same layout as q before the split: channels to hold head 's output and nothing else. No head has seen another head's result yet.
self.proj = nn.Linear(C, C) is , and it's where they meet. Every output channel can draw on every head.
Concatenating, then projecting, is a sum over heads
The projection's math has a useful reading.
proj.weight is (C, C), stored out by in. Which part of it do head h's d channels of y meet?
Parameters: 4C² + 4C, with no H in it
Once the module works, interviewers ask what it costs. Then they ask how to make it cheaper at inference.
Which layer holds about three quarters of the parameters?
FLOPs: 8BTC² + 4BT²C, and H drops out again
Compute is the next number they ask for.
Count a multiply-add as 2 FLOPs. What does the qkv projection cost for B sequences of T tokens?
Past T = 2C, attention costs more than the projections
The two terms grow at different rates.
A wide model, C = 12,288, reads T = 2,048 tokens. Which part of the layer costs more?
The mask saves no compute
Hiding the future doesn't make the scores any cheaper.
scores (4, 4)s is a score that's kept, and - is computed, then set to -inf. At T = 1,024, 523,776 of 1,048,576 are thrown away.
You compute all scores and then throw away the future ones, just under half: 523,776 of 1,048,576 at .
Memory: the scores are the one cost with H in it
Memory is where the heads finally show up.
H = 12, T = 1,024, fp32. How much memory do one sequence's scores take, in one layer?
A narrower head keeps its full T × T grid
That's why more heads cost memory but not compute.
| C = 768, T = 1,024 | 12 heads | 24 heads |
|---|---|---|
| head size d | 64 | 32 |
| parameters | 2,362,368 | 2,362,368 |
| matmul FLOPs | same | same |
| score grids, each T × T | 12 | 24 |
| score memory, fp32 | 48 MiB | 96 MiB |
A head does FLOPs for its two matmuls and stores scores. Narrow the head and its compute shrinks, but its score grid doesn't: 1,048,576 scores, 4 MiB in fp32 at , whether is 64 or 32.
So going from 12 heads to 24 at the same keeps the parameters and the FLOPs, and doubles the score memory.
FlashAttention never stores the T × T grid
FlashAttention is the answer to the score memory. It computes exact attention in tiles with a running softmax, so the matrix never lands in the GPU's main memory.
In production code you'd call F.scaled_dot_product_attention(q, k, v, is_causal=True) instead of writing these lines. The practice bans it so you show you can.
Multi-query and grouped-query attention shrink the KV cache
The last follow-up is about generating text, one token at a time.
Grouped-query attention with 8 query heads and 2 key/value heads. How many query heads share each key/value head?
H = 32 and d = 128. Grouped-query attention keeps 8 key/value heads. How much smaller is its cache than multi-head's?
Which call turns the KV head numbers [0, 1] into [0, 0, 0, 0, 1, 1, 1, 1]?
The practice problem, start to finish
That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.You split heads with
q.reshape(B, n_head, T, C // n_head)and skip the transpose. What happens?2.Your mask is
torch.tril(torch.ones(T, T, dtype=torch.bool), diagonal=-1). What comes out for the first token?3.
CausalSelfAttention(10, 3)has no divisibility check. When does it fail?4.You forgot the causal mask, and the training loss is dropping fast. What's going on?
5.C is 768. You go from 12 heads to 24. Which cost doubles?
Where this shows up
The reports behind this lesson, each with its source.
MLE candidate (interviewed Oct 2025, rejected): phone screen ML coding mainly tested Transformer architecture knowledge.
Same screen: what attention is and exactly how Q, K and V are computed.
Same April 2026 MLE report, ML debug round: fix a broken miniGPT in PyTorch until it generates correct text, then implement a KV cache.
Practice
Sources (6)
- Attention Is All You Need · arXiv 1706.03762 · Jun 12, 2017
“Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.”
- torch.Tensor.view · PyTorch 2.15 documentation · Oct 28, 2026
“When it is unclear whether a view() can be performed, it is advisable to use reshape(), which returns a view if the shapes are compatible, and copies (equivalent to calling contiguous()) otherwise.”
- torch.nn.Module.register_buffer · PyTorch 2.15 documentation · Oct 28, 2026
“Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by setting persistent to False.”
- Fast Transformer Decoding: One Write-Head is All You Need · arXiv 1911.02150 · Nov 6, 2019
“We propose a variant called multi-query attention, where the keys and values are shared across all of the different attention "heads", greatly reducing the size of these tensors and hence the memory bandwidth requirements of incremental decoding.”
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints · arXiv 2305.13245 · May 22, 2023
“introduce grouped-query attention (GQA), a generalization of multi-query attention which uses an intermediate (more than one, less than number of query heads) number of key-value heads. We show that uptrained GQA achieves quality close to multi-head attention with comparable speed to MQA.”
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness · arXiv 2205.14135 · May 27, 2022
“We propose FlashAttention, an IO-aware exact attention algorithm that uses tiling to reduce the number of memory reads/writes between GPU high bandwidth memory (HBM) and GPU on-chip SRAM.”