Unit 3 of 7 · about 4 hours · implement

Self-attention, cross-attention and multi-head shapes

Heads are parallel representation subspaces, and cross-attention is the bridge between sequences. Shape errors here run without error and fail silently as wrong mixing.

You'll be able to

  • Distinguish self-attention from cross-attention by which tensors supply queries, keys and values.
  • Implement head splitting, per-head attention, concatenation and output projection with exact shapes.
  • Explain why fixing total width while varying head count holds parameters and compute flat.

Covers

Self-attention versus cross-attentionMulti-head shapes, concatenation and output projection
1

Read

In this order, only the parts listed

0 of 6 done

  1. Multi-head self-attentionUnderstanding Deep Learning - Transformers

    Section 12.3.3 (pp. 214 to 215): per-head equations 12.10 and 12.11, sizing, and concatenation with output projection in equation 12.12

  2. Cross-attention for encoder-decoder modelsUnderstanding Deep Learning - Transformers

    Section 12.8 with Figure 12.14 (pp. 226 to 227): queries from decoder embeddings, keys and values from encoder embeddings

  3. Notebook 12.2: multi-head self-attentionUnderstanding Deep Learning - Transformers

    The complete notebook, referenced in the margin of the multi-head derivation

  4. Multi-head attention implementationD2L - attention and transformer implementation route

    Section 11.5: the head equations with set to num_hiddens over num_heads, transpose_qkv and transpose_output, the valid_lens repeat per head, and the num_hiddens 100 with num_heads 5 shape check

  5. Self-attention call and decoder cross-attentionD2L - attention and transformer implementation route

    Section 11.6 Self-Attention: the attention(X, X, X, valid_lens) toy with batch 2, 4 queries and width 100

    Stop before the CNN, RNN and self-attention comparison and before Positional Encoding; both belong to later units.

  6. Decoder self versus encoder-decoder attentionD2L - attention and transformer implementation route

    TransformerDecoderBlock: attention1 over (X, key_values, key_values) with dec_valid_lens versus attention2 over (Y, enc_outputs, enc_outputs) with enc_valid_lens

2

Focus on

  • D2L sets per-head width to num_hiddens over num_heads, so all four projections stay num_hiddens by num_hiddens. The head count changes mixing, not size.
  • Heads fold into the batch axis: (batch, steps, heads, width) becomes (batch times heads, steps, width) for the shared attention call, then unfolds back. valid_lens must repeat once per head to stay aligned.
  • Cross-attention reuses the identical math with different sources: queries from the decoder state, keys and values from encoder outputs, with padding-only lengths.
  • UDL Problem 12.5 is the cost intuition: narrow heads at fixed total width keep the implementation efficient.
Common mistakes · 3
  • Folding heads with one reshape. Going straight from (batch, steps, hidden) to (batch times heads, steps, hidden/heads) runs without error but gives each head a mix of positions. Split hidden into (heads, head width), move the head axis next to batch, then merge, as transpose_qkv does.
  • Repeating valid_lens in the wrong order. D2L folds batch-major, so lengths need repeat_interleave ([l0, l0, l1, l1]). Tiling with repeat ([l0, l1, l0, l1]) has the right length and silently masks heads with another example's length. Dropping the repeat fails loudly in masked_softmax.
  • Assuming cross-attention needs a new formula. Only the sources change; calling self-attention with (Y, encoder outputs, encoder outputs) is the whole difference.
3

Try it yourself

Closed-book, before checking anything

Closed-book, walk shapes for batch 2, 4 queries, width 100, 5 heads: projections stay (2, 4, 100), folded per-head tensors are (10, 4, 20), concatenation restores (2, 4, 100). State BERT per-head width 64 from 1024 over 16 heads.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.BERT uses width 1024 with 16 heads. What is the per-head width, and what shape are its per-head query matrices?Answer

    64. Each per-head query, key and value matrix is .

  2. 2.Why does fixing total width while varying head count hold parameters and compute flat?Answer

    All four projections stay num_hiddens by num_hiddens regardless of head count, so QKVO parameters stay 4 times width squared and per-head matmuls sum back to the same total.

  3. 3.In the D2L decoder block, which tensors supply queries, keys and values to the second attention call, and which lengths mask it?Answer

    Queries come from the decoder state Y after self-attention; keys and values come from encoder outputs. Only encoder padding lengths mask it; there is no causal mask on this call.

  4. 4.The valid_lens repeat per head is deleted. What breaks?Answer

    The folded batch has batch times heads rows but only batch lengths, so D2L masked_softmax fails with a mask shape error. The silent form of the bug is tiling with repeat instead of repeat_interleave: the count matches, but heads use another example's length.

5

Practice

  • TrenTorch: Multi-Head Attention, splitting into heads

    Implement split_heads and multi_head_attention_per_head; the tests check consecutive chunks per head, a match with a per-head loop, and masking

    TrenTorch keeps heads on their own axis, (batch, heads, seq, ); D2L folds them into the batch, (batch x heads, seq, ). Walk the reproduce shapes through both layouts.

  • D2L Multi-Head Attention: Exercise 1 (visualize heads)

    Exercises in Section 11.5: visualize attention weights of multiple heads in the toy experiment

    Plot one head per panel on the same input and confirm different heads attend differently; identical panels expose a split bug.

You're done when

Your multi-head block returns (2, 4, 100) on the D2L toy, per-head weights match a manual single-head call, and masking with valid lengths [3, 2] zeroes the same key slots in every head.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 3 more in the section
  • Understanding Deep Learning - TransformersSimon J. D. Prince · primary

    Use Chapter 12.1-12.11 and the matching notebooks for dot-product self-attention, extension to transformers, transformer layers and vision transformers.

  • D2L - attention and transformer implementation routeD2L authors · required

    Use queries-keys-values, attention-scoring-functions, multihead-attention, self-attention-and-positional-encoding, transformer and vision-transformer. Implement masked single-head attention, multi-head attention and one pre-normalized block before comparing with PyTorch.

Also in this section

  • PyTorch - scaled dot product attentionPyTorch · reference

    Use the official function documentation as a differential oracle for shapes, masks, dropout and backend behavior after the manual version passes intervention tests.

  • Deep-ML candidate - attention problemsDeep-ML · optional

    Use 490 Scaled Dot-Product Attention as the fifth platform admission sample. If the judge catches a seeded masking error, use at most one of 490, 491, 53, 904 or 905 as a changed-prompt drill.

  • TrenTorch - attention and block questionsTrenTorch · support

    Solve the multi-head split, sinusoidal positional encoding, causal mask and pre-norm versus post-norm questions the units name, then carry the same checks into your own block.