Multi-head causal self-attention

70 min6 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • 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: x of shape (B, T, C) in, (B, T, C) out, by hand, with no F.scaled_dot_product_attention and no nn.MultiheadAttention.

  1. The layers: one fused projection self.qkv = nn.Linear(C, 3 * C), q then k then v, and self.proj = nn.Linear(C, C). Raise ValueError when n_head doesn't divide n_embd.
  2. The heads: split q, k and v into n_head heads of C // n_head, attend in every head at once, merge the heads back and project.
  3. The mask: token t sees only tokens <= t, with the mask built once.
  4. GroupedQueryAttention(n_embd, n_head, n_kv_head): the same layer with n_kv_head key/value heads, each shared by a group of query heads.
CallReturns
CausalSelfAttention(48, 6) on x of shape (3, 9, 48)shape (3, 9, 48)
CausalSelfAttention(10, 3)ValueError
the outputs at positions 0 to 4, after tokens 5 to 7 changeunchanged
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.

Part 1 of 6about 5 min
Why heads

One head gives each token one blend

Start with why attention has heads at all.

Predict

Token 7 needs token 6 and token 3. With one head, what does it read?

Pick an answer above to see the rest

Five letters name every shape

The rest of the lesson names every shape with five letters.

Predict

C = 512 and H = 8. What's d, the head size?

Pick an answer above to see the rest

Several heads, each with its own softmax

Each head is a whole attention function of its own.

One token through H headsInteractive
x, one token = C numbers.

So run several attention functions side by side. Each head projects the full input into its own queries, keys and values, each d=C/Hd = C / H 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:

headh=Attention(XWQ(h), XWK(h), XWV(h))MultiHead(X)=Concat(head1,…,headH) WO\begin{aligned} \text{head}_h &= \text{Attention}\big(X W_Q^{(h)},\ X W_K^{(h)},\ X W_V^{(h)}\big) \\ \text{MultiHead}(X) &= \text{Concat}(\text{head}_1, \dots, \text{head}_H)\, W_O \end{aligned}

In words:

  • XX is the input, one row of CC numbers per token.
  • WQ(h)W_Q^{(h)}, WK(h)W_K^{(h)} and WV(h)W_V^{(h)} are head hh's own query, key and value projections, each C×dC \times d.
  • Concat\text{Concat} puts the HH head outputs side by side, and WOW_O is the output projection, C×CC \times C.

More heads add no parameters and no FLOPs: each one gets narrower

Heads sound expensive. They aren't.

Predict

C = 768 and H = 12. What shape is one head's W_Q?

Pick an answer above to see the rest
Part 1 done
Part 2 of 6about 12 min
Split the heads

One wide layer instead of 3H small ones

Every head needs its own queries, keys and values. One layer makes them all.

Predict

One nn.Linear makes every head's q, k and v at once. What are its in and out sizes?

Pick an answer above to see the rest

split cuts q, k and v apart, in that order

The layer's output holds q, k and v side by side.

Predict

The layer gives each token 36 numbers, with C = 12. Which ones are k?

Pick an answer above to see the rest

Each head owns a run of d channels

Inside q, the heads are just runs of channels.

Predict

C = 12 and H = 4. Which channels does head 2 own?

Pick an answer above to see the rest

view cuts each token's row into heads, and moves nothing

Cutting the channels into heads takes two calls.

Predict

(2, 5, 12) viewed as (B, T, H, d) with H = 4. What's the new shape?

Pick an answer above to see the rest

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)
Predict

qh[0, 0] and kh[0, 0] are both (5, 3). What shape is qh[0, 0] @ kh[0, 0].T?

Pick one to see what it prints.
Pick an answer above to see the rest

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.

Watch · 1 min

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.

Splitting heads: view, then transpose · InterviewWhisperer Prep · Nov 2026Open
Part 2 done
Part 3 of 6about 15 min
The worked example

Label each number with where it came from

A small labeled tensor shows exactly what the split does.

Predict

Each number is 10 × position + channel. Where did 21 come from?

Pick an answer above to see the rest

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:

The split on twelve numbersInteractive
head 0
token 001token 11011token 22021
head 1
2312132223
transpose(1, 2) puts the heads first. Each head is now its own small grid with one row per token: every row has a single tens digit.

Row tt of each head is position tt, 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:

A bare reshape, on the same twelve numbers
"head 0" (3, 2)
row 001row 123row 21011
"head 1" (3, 2)
row 01213row 12021row 22223

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.

Which inputs each output depends on
view + transpose (3, 3)
in 0in 1in 2output 0xoutput 1xxoutput 2xxx
bare reshape (3, 3)
in 0in 1in 2output 0xxoutput 1xxxoutput 2xxx

x means the output depends on that input. Red is the future leaking in.

The causal mask trusts that row tt is position tt. 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:

Merge the heads backInteractive
(B, H, T, d). Every head's output at every position

After a transpose, view fails and reshape works

One call in the merge fails, and it's worth knowing why.

Predict

heads is (1, 2, 3, 2) and contiguous, with strides (12, 6, 2, 1). What are the strides of heads.transpose(1, 2)?

Pick an answer above to see the rest

Skip the transpose and the positions scramble, with no error

The quiet failure is worse: a merge without the transpose.

Predict

With no transpose, reshape(B, T, C) reads the memory of heads in order. What lands in position 0's row?

Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 10 min
Shapes and the mask

Every shape, from (B, T, C) in to (B, T, C) out

Here's the whole forward pass, one line per step.

StepShape, 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

d=C/Hd = C / H the whole way down. The scores are the only step with two TT 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.

Predict

C = 768 and H = 12. What do you divide each score by?

Pick an answer above to see the rest

Build the triangle once, then cut it to the input's length

The mask comes next, and it belongs to the module.

Predict

The mask is built once at block_size × block_size. A forward pass gets T = 4. Which part do you use?

Pick an answer above to see the rest

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.

Predict

Pass the triangle itself to masked_fill, not its flip. Which keys can token 0 read?

Pick an answer above to see the rest

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:

Predict

Keep the mask as a plain attribute, self.mask = torch.tril(...), instead. Is it saved in state_dict, and does it move with .to()?

Pick an answer above to see the rest

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 T×TT \times T 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.

Predict

Buffers are saved by default. How much does a 1024 × 1024 bool mask add to each layer of a checkpoint?

Pick an answer above to see the rest
Part 4 done
Part 5 of 6about 9 min
The check and the projection

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 d=C/Hd = C / H 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:

HeadChannels
00, 1, 2
13, 4, 5
26, 7, 8
none9

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 hdhd to (h+1)d−1(h+1)d - 1 hold head hh's output and nothing else. No head has seen another head's result yet.

self.proj = nn.Linear(C, C) is WOW_O, 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.

Predict

proj.weight is (C, C), stored out by in. Which part of it do head h's d channels of y meet?

Pick an answer above to see the rest
Part 5 done
Part 6 of 6about 19 min
Follow-ups

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.

Predict

Which layer holds about three quarters of the parameters?

Pick an answer above to see the rest

FLOPs: 8BTC² + 4BT²C, and H drops out again

Compute is the next number they ask for.

Predict

Count a multiply-add as 2 FLOPs. What does the qkv projection cost for B sequences of T tokens?

Pick an answer above to see the rest

Past T = 2C, attention costs more than the projections

The two terms grow at different rates.

Predict

A wide model, C = 12,288, reads T = 2,048 tokens. Which part of the layer costs more?

Pick an answer above to see the rest

The mask saves no compute

Hiding the future doesn't make the scores any cheaper.

T = 4: all 16 scores are computed, then 6 are thrown away
scores (4, 4)
s---ss--sss-ssss

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 T2T^2 scores and then throw away the T(T−1)/2T(T-1)/2 future ones, just under half: 523,776 of 1,048,576 at T=1024T = 1024.

Memory: the scores are the one cost with H in it

Memory is where the heads finally show up.

Predict

H = 12, T = 1,024, fp32. How much memory do one sequence's scores take, in one layer?

Pick an answer above to see the rest

A narrower head keeps its full T × T grid

That's why more heads cost memory but not compute.

C = 768, T = 1,02412 heads24 heads
head size d6432
parameters2,362,3682,362,368
matmul FLOPssamesame
score grids, each T × T1224
score memory, fp3248 MiB96 MiB

A head does 4T2d4T^2d FLOPs for its two matmuls and stores T2T^2 scores. Narrow the head and its compute shrinks, but its score grid doesn't: 1,048,576 scores, 4 MiB in fp32 at T=1024T = 1024, whether dd is 64 or 32.

So going from 12 heads to 24 at the same CC 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 T×TT \times T 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.

Predict

Grouped-query attention with 8 query heads and 2 key/value heads. How many query heads share each key/value head?

Pick an answer above to see the rest
Predict

H = 32 and d = 128. Grouped-query attention keeps 8 key/value heads. How much smaller is its cache than multi-head's?

Pick an answer above to see the rest
Predict

Which call turns the KV head numbers [0, 1] into [0, 0, 0, 0, 1, 1, 1, 1]?

Pick an answer above to see the rest

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.

Check yourself
5 questions
  1. 1.You split heads with q.reshape(B, n_head, T, C // n_head) and skip the transpose. What happens?

  2. 2.Your mask is torch.tril(torch.ones(T, T, dtype=torch.bool), diagonal=-1). What comes out for the first token?

  3. 3.CausalSelfAttention(10, 3) has no divisibility check. When does it fail?

  4. 4.You forgot the causal mask, and the training loss is dropping fast. What's going on?

  5. 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.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-25Source

Same screen: what attention is and exactly how Q, K and V are computed.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-10-10Source

Same April 2026 MLE report, ML debug round: fix a broken miniGPT in PyTorch until it generates correct text, then implement a KV cache.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-24Source

Practice

Sources (6)
  1. 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.”
  2. 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.”
  3. 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.”
  4. 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.”
  5. 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.”
  6. 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.”