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

Query, key and value projections with explicit shapesScaled dot-product attention and the scaling termStable softmax and causal mask constructionPadding masks versus causal masks
1

Read

In this order, only the parts listed

0 of 4 done

  1. Attention scores and causal maskingModern LLM Notebook - decoder construction path

    Sections 2, Scaled Dot-Product Attention, and 3, Causal Masking

  2. Trainable , and projectionsLLMs from Scratch companion - attention and GPT construction

    Section 3.4.1, Computing the attention weights step by step

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

  4. Mask shape and polarity referencePyTorch scaled dot product attention reference

    Equivalent Python implementation, boolean-mask semantics note, and Parameters: attn_mask and is_causal

    Read this after your explicit oracle works. Use the contract for padding-mask broadcasting; skip kernel selection.

2

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 True for allowed entries; MultiheadAttention padding masks use True for 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.
3

Try it yourself

Closed-book, before checking anything

From a blank file, compute one causal attention row with explicit dot products, max-subtracted exponentials and a weighted sum of . Match it with a batched implementation on a three-token example containing a masked key.
4

Quiz yourself

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

0 got · 0 missed

  1. 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. 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. 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. 4.With , and , what are scores and output?Answer

    Scores are , softmax runs over the five keys, and output is .

5

Practice

  • CS336 Assignment 1: softmax

    Problem (softmax), section 3.4.4; implement run_softmax in tests/adapters.py and pass test_softmax_matches_pytorch

  • CS336 Assignment 1: scaled_dot_product_attention

    Problem (scaled_dot_product_attention), section 3.4.4; implement run_scaled_dot_product_attention and pass test_scaled_dot_product_attention and test_4d_scaled_dot_product_attention

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