Skip to main content

Exercises — Transformer block

Comprehension and code-reading exercises

← Back to the guided tour: Bloc Transformer

Check your understanding

  1. With d=16 and H=2, which columns of q does head 1 read?

  2. Why is attended allocated with np.empty_like(x) instead of zeros?

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

  4. Columns 8 to 15 (slice(8, 16)): every column belongs to exactly one head, and the split is contiguous.

  5. Every cell of attended is 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.

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

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

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

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

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

Language: Français · English