Unit 3 of 7 · about 4 hours · implement

Multi-head attention: split, merge and gradients

A reshape can preserve every tensor size while mixing tokens and heads. Forward and backward comparisons check that the batched code implements the intended operation.

You'll be able to

  • Implement head splitting, transposition, attention, merging and output projection without a high-level attention module.
  • Match outputs and input and projection-weight gradients against a per-head reference under identical weights.
  • Localize head-layout and scaling errors with a changed batch size, sequence length or head count.

Covers

Head split, transpose, merge and tensor layoutMulti-head attention forward and backward behavior
1

Read

In this order, only the parts listed

0 of 4 done

  1. Multi-head data flowModern LLM Notebook - decoder construction path

    Section 4, Multi-Head Attention, especially How Multi-Head Is Implemented in Code and Complete Data Flow

  2. Explicit head split and mergeLLMs from Scratch companion - attention and GPT construction

    Section 3.6.2, Implementing multi-head attention with weight splits, including the separate-head matrix multiplication example

  3. Causal MHA contractStanford CS336 Assignment 1 - model contract

    Section 3.4.5, Causal Multi-Head Self-Attention, printed pp. 25 to 26

    Implement the no-RoPE adapter here. Leave Applying RoPE and the with_rope adapter to the RoPE unit.

  4. Independent batched attention comparisonPyTorch scaled dot product attention reference

    Equivalent Python implementation, dropout warning, numerical backend note and Shape legend

    Compare only after the explicit per-head oracle passes. Set dropout_p=0.0; kernel tuning is outside this unit.

2

Focus on

  • With , split to , then transpose to . A reshape alone does not exchange and .
  • Each head normalizes its own score matrix. Concatenate head outputs before applying the output projection.
  • Reverse the transpose before merging. A transposed tensor may need contiguous storage or reshape rather than view.
  • Transfer identical weights into a per-head loop and the batched path. Backpropagate the same scalar contraction of outputs and compare gradients, not just shapes.
Common mistakes · 3
  • Comparing separately initialized modules. Different random weights do not test implementation equivalence.
  • Merging directly into . This silently scrambles head and token ordering.
  • Assuming eval() disables functional SDPA dropout. Its dropout_p argument must be zero explicitly.
3

Try it yourself

Closed-book, before checking anything

Implement causal two-head attention for , , . Reproduce its output and gradients with a loop over heads using sliced projection weights, then compare the attention core with SDPA at zero dropout.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.For , , and , what shapes enter attention and leave the merge?Answer

    , and are , scores are , and the merged output is .

  2. 2.At fixed , does doubling double the bias-free MHA projection parameter count?Answer

    No. Head width halves, so , , and output projections still total parameters.

  3. 3.Why compare projection-weight gradients as well as input gradients?Answer

    They check that each head uses and differentiates the intended weight slice. A forward-only or input-only comparison can miss a detached or incorrectly registered parameter.

5

Practice

  • CS336 Assignment 1: multihead_self_attention

    Problem (multihead_self_attention), section 3.4.5; implement run_multihead_self_attention in tests/adapters.py and pass test_multihead_self_attention

    The public test checks a forward snapshot, not gradients. Extend your own tests with a transferred-weight per-head oracle, input and all four projection gradients, and non-contiguous input.

You're done when

The named public test passes and your float64 forward and gradient comparisons agree within atol=1e-8 and rtol=1e-6 for one and multiple heads, with dropout disabled.

Only when you can do this without notes.

Leads to

Notes

Resources · 4 for this unit, 2 more in the section
  • Modern LLM Notebook - decoder construction pathWalking Labs · primary

    Work through English notebooks 03-embedding, 04-position-encoding, 05-transformer-block, 06-mini-gpt and the selected normalization, RoPE, GQA and SwiGLU comparisons in 08-gpt2-to-modern-models. Re-derive shapes and rerun with changed dimensions.

  • LLMs from Scratch companion - attention and GPT constructionSebastian Raschka · required

    Use the ch03 attention notebooks and ch04 model code. Rebuild the model without a high-level Transformer module and compare one forward and backward path with an independent small reference.

  • Stanford CS336 Assignment 1 - model contractStanford University · required

    Use the named linear, embedding, rmsnorm, positionwise_feedforward, rope, softmax, scaled_dot_product_attention, multihead_self_attention, transformer_block, transformer_lm and transformer_accounting specifications and public tests. Keep implementation independent and respect the course AI and honor-code boundary.

  • PyTorch scaled dot product attention referencePyTorch · support

    Use the functional contract only after the explicit attention oracle passes. Transfer identical weights and masks, compare outputs and gradients, and explain dtype, causal and dropout behavior from the documented semantics.

Also in this section

  • Deep-ML candidate - three transformer closing drillsDeep-ML · optional

    After the platform quality sample passes, attempt at most problems 490, 53 and 904 as changed-prompt drills for attention shapes and multi-head composition. Preserve independent tests; a judge result does not replace the section checkpoint.

  • nanoGPT - residual projection initializationAndrej Karpathy · support

    Read model.py: MLP, Block, GPT.__init__'s special scaled initialization of c_proj.weight, and GPT._init_weights. Contrast the depth-dependent residual initialization with CS336's component initialization; do not adopt the training or generation code.