Unit 2 of 7 · about 5 hours · derive, implement
Scaled dot-product attention from scratch
Attention is a weighted read from permitted keys, not a framework black box. Correct shapes and masks make the decoder's causal information boundary testable.
You'll be able to
- Derive with explicit projection, score and output shapes.
- Implement stable softmax and combine causal and padding masks before normalization.
- Diagnose scale, mask-polarity and fully masked-row failures using a small explicit reference.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Attention scores and causal maskingModern LLM Notebook - decoder construction path
Sections 2, Scaled Dot-Product Attention, and 3, Causal Masking
- Trainable , and projectionsLLMs from Scratch companion - attention and GPT construction
Section 3.4.1, Computing the attention weights step by step
- Stable softmax and masked attention contractStanford CS336 Assignment 1 - model contract
Section 3.4.4, Scaled Dot-Product Attention, including problems (
softmax) and (scaled_dot_product_attention), printed pp. 23 to 25 - Mask shape and polarity referencePyTorch scaled dot product attention reference
Equivalent Python implementation, boolean-mask semantics note, and Parameters:
attn_maskandis_causalRead this after your explicit oracle works. Use the contract for padding-mask broadcasting; skip kernel selection.
Focus on
- For , and are , is , scores are , and the output is .
- With independent zero-mean unit-variance and components, their dot product has variance . Dividing by keeps the variance near one.
- Subtract each score row's maximum before exponentiating. Mask forbidden entries before softmax and normalize over keys.
- An allow mask combines with
valid_key[b,j]. Broadcast key validity as ; exclude padded query outputs separately and define a policy for rows with no valid key.
Common mistakes · 3
- Using after splitting into heads. The scale uses the query/key width of one head.
- Copying a boolean mask between APIs without checking polarity. CS336 and SDPA use
Truefor allowed entries;MultiheadAttentionpadding masks useTruefor blocked entries. - Assuming max subtraction fixes an all-negative-infinity row. It gives undefined subtraction; reject that row or explicitly return zero for an ignored padded query.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.If all allowed logits gain 1000, should the attention output change?Answer
No. Softmax is invariant to a common additive shift; max subtraction avoids overflow.
2.Why does replacing a forbidden score with zero fail?Answer
is one, so the forbidden key receives probability. Use negative infinity before softmax.
3.Does a causal mask remove padding keys?Answer
No. It only forbids future positions. A padding key earlier than the query is still causally permitted and needs a separate validity mask.
4.With , and , what are scores and output?Answer
Scores are , softmax runs over the five keys, and output is .
Practice
- CS336 Assignment 1:
softmaxProblem (
softmax), section 3.4.4; implementrun_softmaxintests/adapters.pyand passtest_softmax_matches_pytorch - CS336 Assignment 1:
scaled_dot_product_attentionProblem (
scaled_dot_product_attention), section 3.4.4; implementrun_scaled_dot_product_attentionand passtest_scaled_dot_product_attentionandtest_4d_scaled_dot_product_attentionWork in your own repository and respect the course AI policy. Add causal-plus-padding and fully masked-row tests; the public snapshots do not cover every mask edge case.
You're done when
The three named public tests pass, your explicit row matches the batched result, and changing a forbidden key or value cannot affect a valid query's output.
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 ofc_proj.weight, andGPT._init_weights. Contrast the depth-dependent residual initialization with CS336's component initialization; do not adopt the training or generation code.