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.