7 routes42 sections324 units

Unit 7.3 · about 4 h

216 / 324

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.

  • implement

You can now

  • 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-attention
  • Multi-head shapes, concatenation and output projection

Study, in this order

6 steps

  1. Multi-head self-attention
    Understanding Deep Learning - Transformers

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

  2. Cross-attention for encoder-decoder models
    Understanding 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-attention
    Understanding Deep Learning - Transformers

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

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

    Section 11.5: the head equations with \(p\) 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-attention
    D2L - 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

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

  6. Decoder self versus encoder-decoder attention
    D2L - 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

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.

Reproduce closed-book

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.

Traps

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

Practice

TrenTorch: Multi-Head Attention, splitting into heads

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

TrenTorch keeps heads on their own axis, (batch, heads, seq, \(d_k\)); D2L folds them into the batch, (batch x heads, seq, \(d_k\)). 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.

Self-test

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

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

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

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

Completion criterion

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

Mark passed, then open 7.4 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • Understanding Deep Learning - Transformers
    Simon J. D. Princeprimarytheory
    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 route
    D2L authorsrequiredimplementation
    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 attention
    PyTorchreferencereference
    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 problems
    Deep-MLoptionalpractice
    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 questions
    TrenTorchsupportpractice
    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.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels