Attention & Transformer Foundations

Attention must be understood as shape-correct weighted communication with explicit masking and cost. This is the foundation for later LLM work, not a compressed LLM specialization.

Section 7 of 8 · 7 units · about 28 hours

0/7

By the end you can Derive attention and its cost for a stated shape, implement a general multi-head block, and prove with interventions that neither future nor padded tokens affect valid causal outputs.

Units

Build it

Mini project · about 10 to 14 hours

General multi-head block with an intervention battery

Implement a pre-norm transformer block with multi-head attention, masks and positions from tensor operations, derive its cost for a stated shape, and prove with interventions that future and padded tokens cannot change valid causal outputs.

  1. 1Implement scaled dot-product attention with a stable softmax and boolean causal and padding masks. Pass Deep-ML 490 and the CS231n Assignment 3 MultiHeadAttention and PositionalEncoding checks in Transformer_Captioning.ipynb.
  2. 2Build multi-head attention with an explicit split, transpose and merge, self- and cross-attention through one module, and valid lengths repeated per head in batch-major order.
  3. 3Assemble a pre-norm block (norm, attention, add, norm, gated MLP, add) with sinusoidal or learned positions. Check shapes across depths, batch sizes and sequence lengths, and identical eval-mode outputs after saving and reloading the state_dict.
  4. 4Run the intervention battery on the composed block: changing future tokens leaves earlier outputs unchanged, changing padded content leaves valid outputs unchanged, and permuting the batch permutes the outputs. Show that sequence permutation passes without mask or positions and fails with the causal mask.
  5. 5Differential-test forward and backward against torch.nn.functional.scaled_dot_product_attention on the math backend, within tolerance, with noncontiguous inputs and variable lengths, excluding fully masked rows. Pin your fully-masked-row convention in a separate test.
  6. 6Derive parameters, forward FLOPs and score memory for , , in fp32, then measure the score tensor bytes and a profiler FLOP count and reconcile them under stated conventions.
What you hand in
  • The attention and block package with masks, positions and the gated MLP.
  • The test suite: oracle checks, the intervention battery, the SDPA differential tests and the fully-masked-row convention test.
  • A cost sheet for the stated shape with measured numbers beside derived ones.
How to check it
How it's graded

Attention correctness

Pass: Deep-ML 490 and the CS231n attention checks pass.

Great: Forward and backward match the SDPA math backend in float64 on noncontiguous inputs.

Masks and causality

Pass: Future-token and padding interventions leave valid outputs unchanged.

Great: The battery passes on shapes you did not tune for, and the causal sequence-permutation test fails as it should.

Head handling

Pass: Split, transpose and merge match a loop over heads.

Great: A test shows that tiling valid lengths with repeat masks the wrong heads while repeat_interleave masks the right ones.

Block

Pass: Shapes hold across depths, and eval-mode outputs survive a save and reload.

Great: You compare pre-norm and post-norm on a short training run and report gradient norms per layer.

Cost accounting

Pass: Parameters, FLOPs and score bytes are derived for the stated shape.

Great: Measured score bytes and profiler FLOPs agree with the derivation, with each convention stated, such as multiply-adds versus FLOPs and MiB versus MB.

Resources

  • Understanding Deep Learning - TransformersSimon J. D. Prince

    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

    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.

  • TrenTorch - attention and block questionsTrenTorch

    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.

  • Deep-ML candidate - attention problemsDeep-ML

    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.

  • PyTorch - scaled dot product attentionPyTorch

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