Exercises — Transformer block
Comprehension and code-reading exercises
← Back to the guided tour: Bloc Transformer
Check your understanding
With
d=16andH=2, which columns ofqdoes head 1 read?Why is
attendedallocated withnp.empty_like(x)instead of zeros?In the pre-LN attention branch, what roles do Q, K, V, and the output projection O play? From which stream are they computed, and where does the residual connection enter?
Show answers and reasoning
Columns 8 to 15 (
slice(8, 16)): every column belongs to exactly one head, and the split is contiguous.Every cell of
attendedis written exactly once by the loop (each(b, h)pair writes its slice for all positions); no cell is read before being written, so zero-initialization would be wasted work.Q and K determine compatibility scores between positions; the softmax of those scores weights V, which carries the aggregated information. Q, K, and V are projected from the same normalized stream. The O projection mixes the head outputs; its result is added to the original residual stream. Normalization stays inside the branch, not on the direct residual path.
A block has 32 Q heads. Compare the number of KV heads in MHA, MQA, and GQA with 8 groups. With all dimensions equal, what are the ratios between their KV-cache sizes?
Do a 256-token sliding window and GQA with 8 KV heads optimize the same factor? Explain what changes in each case.
Show answers and reasoning
MHA: 32 KV heads; MQA: 1; GQA: 8. With context length, layer count, head dimension, and precision held fixed, K/V cache size is proportional to the number of KV heads: GQA uses 1/4 of MHA’s cache, and MQA 1/32.
No. GQA shares K/V states across multiple Q heads and reduces the number of KV heads stored. A window limits which historical positions are attended to and changes the connectivity pattern. The two mechanisms can be combined; their effects do not add up to one universal factor.