1/42
Learn

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.