Unit 3 of 10 · about 5 hours · implement
Causal and padding masks and MHA, GQA and MQA grouping
A fast attention kernel with the wrong mask or head map computes a different model. These bugs often survive square, unpadded tests.
You'll be able to
- Implement causal, padding and explicit allowed-entry masks using logical token positions.
- Map query heads to shared KV heads without materializing repeated keys and values.
- Diagnose diagonal-tile, mask-polarity and rectangular decode errors.
Covers
Read
In this order, only the parts listed
0 of 3 done
- FlashAttention-2 mask and head-grouping discussionFlashAttention-2
Causal masking (p. 6) and Multi-query attention and grouped-query attention (p. 7), unnumbered paragraphs within Section 3.1
Correct the reversed inequality in Causal masking item 2: a fully allowed tile has every key position no greater than every query position. The rendered v1 page says the opposite.
- PyTorch 2.14 SDPA mask and GQA contractPyTorch SDPA contracts and integration tutorial
Equivalent implementation, boolean mask note, GQA constraints, and parameters
attn_mask,is_causalandenable_gqa - FlashInfer packed arbitrary masksFlashInfer
Commit f2794d5: Mask Layout (2D Ragged Tensor), through the bit-packing description
Use the layout description, not its stale
begin_forwardAPI example. The pinned implementation usesplanandrun.
Focus on
- Build one allowed-entry predicate from query validity, key validity, request identity, causal positions and any custom mask. Apply it before the maximum and exponential reductions.
- For aligned square self-attention, allowed keys satisfy . For a suffix query block with past length , the rule is . Do not infer absolute positions from a tile-local index.
- For divisible head counts, group size is and KV head is . MHA has ; MQA has one KV head. Cache storage falls with KV heads, but query-head arithmetic remains.
- In SDPA, a boolean
Truemeans allowed. Its rectangularis_causal=Trueuses upper-left alignment, not automatically the suffix alignment needed by cached decode. Use an explicit mask withis_causal=Falsefor the latter.
Common mistakes · 3
- Treating zero-padded keys as masked. Zero logits still receive probability mass, and padded queries also need an output policy.
- Skipping diagonal masking or using strict inequality. A token is allowed to attend to itself in ordinary causal self-attention.
- Using the handout's finite sentinel
-1e6as a universal mask. It is adequate for its random tests, not arbitrary logits; use negative infinity and explicit all-masked handling.
Try it yourself
Closed-book, before checking anything
torch.float64 inputs and query positions 3 and 4. Map heads as [0, 0, 1, 1], mask keys after each query position, and compare with PyTorch 2.14.1 SDPA using attn_mask and enable_gqa=True at rtol=1e-12, atol=1e-12. Change one future value and show that the earlier query's output is unchanged.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.When can a causal tile be skipped completely?Answer
When its smallest valid key position is greater than its largest valid query position. A fully allowed tile has its largest key position no greater than its smallest query position. Other tiles need elementwise masks.
2.Does four query heads sharing two KV heads halve all attention FLOPs?Answer
No. Each query head still has its own scores and weighted output. KV-cache capacity is halved relative to four KV heads; traffic savings depend on reuse.
3.Why is
is_causal=Truedangerous for a one-row cached-decode query in SDPA?AnswerUpper-left alignment permits only the first key for that row. If the query is the newest token and all cached keys are valid past tokens, it should attend to the entire cache instead.
Practice
- TensorTonic: Causal Grouped-Query Attention
Implement
causal_gqawithout repeating key or value heads: query head uses KV head , with a causal mask over aligned positions; pass the single-head, multi-query and two-group public casesA free CPU reference problem. Pass it before the GPU kernel, then add your own suffix-position and all-masked cases, which it does not test.
- LeetGPU 53: Causal Self-Attention
reference_impl, example and four functional cases; preserve the challenge'ssolvesignatureRun equivalent generated cases and reference comparisons in your own local harness, as in challenge 6; the remote helper is not a local grader. Then complete CS336
flash_forward(c) and pass bothis_causalsettings oftest_flash_forward_pass_triton. The section mini-project covers GQA, padding, arbitrary masks, suffix positions and all-masked rows; the public challenge does not.
You're done when
The TensorTonic GQA cases, challenge 53 and both CS336 Triton forward settings pass, and your own GQA, suffix-mask, padding and all-masked tests demonstrate the declared semantics.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 10 more in the section
- FlashAttention-2Tri Dao · required
Study reduced non-matmul work, sequence parallelism and warp work partitioning. Compare the schedule with the first paper and predict which shapes benefit before checking measurements.
- FlashInferFlashInfer Project · support
Inspect the attention, sampling and serving-kernel interfaces. Reconstruct one dispatch path and compare its layout and workspace contracts with your reduced kernel instead of copying the optimized implementation.
- PyTorch SDPA contracts and integration tutorialPyTorch · reference
The PyTorch 2.14 SDPA API page gives mask polarity, rectangular causal alignment, GQA and backend limitations. The SDPA tutorial (https://docs.pytorch.org/tutorials/intermediate/scaled_dot_product_attention_tutorial.html, read 2026-10-13) gives Explicit Dispatcher Control, Causal Self Attention, Using SDPA with
torch.compileand Using SDPA withattn_biassubclasses. Correct the tutorial's evaluation-time causal flag before integration.
Also in this section
- FlashAttentionTri Dao and collaborators · primary
Read the IO-awareness argument, exact attention algorithm and complexity analysis. Derive the online state and block dataflow, then implement a reduced forward kernel or trace a trusted implementation across at least causal and noncausal cases.
- Online Normalizer Calculation for SoftmaxOnline Softmax Authors · required
Re-derive the recurrence inside tiled attention and prove rescaling correctness. Add extreme-logit, all-masked, odd-head and partial-tile tests before any performance comparison.
- CS336 Assignment 2 - Section 4 FlashAttention-2 in TritonStanford University · required
Do the weighted-sum warm-up, then
flash_forward(a PyTorch tiled version and the Triton kernel) andflash_backwardagainsttests/test_attention.py. Runflash_benchmarkingon sizes that fit your GPU instead of the handout's B200 sweep. - TensorTonic Language Modeling from Scratch - Blockwise Online SoftmaxTensorTonic · support
Solve it before the tiled attention kernel as a check on the rescaling recurrence.
- LeetGPU - Attention and Transformer ChallengesAlphaGPU · required
Solve 6 Softmax Attention and 12 Multi-Head Attention or 53 Causal Attention. Then choose two of 50 RMS Normalization, 54 SwiGLU, 61 RoPE, 80 Grouped Query Attention, 83 Fused Residual Add RMS Norm and 84 SwiGLU MLP Block. Keep correctness tests beyond the hosted score.
- GPU MODE - Attention and Fused KernelsGPU MODE · support
Use Lectures 12, 13, 18, 36 and 40 for FlashAttention, Ring Attention, fusion, FlashAttention-3 and FlashInfer. Reproduce one schedule or fusion idea under the stage shape matrix and a strong baseline.
- FlashAttention-3FlashAttention Authors · depth
Study Hopper-specific asynchronous execution and low-precision design after the portable kernel. Implement only with the required architecture, and separate algorithmic from hardware-specific gains.
- Modern GPU Programming for MLSys - Flash Attention 4MLC · depth
Read the complete Blackwell attention chapter, including two MMAs, online softmax, causal masking and GQA. Run it only on compatible sm_100a hardware with the pinned TIRx stack; otherwise use the code for architecture reconstruction.
- Triton 3.8.0 Layer NormalizationTriton Project · required
Motivations and
_layer_norm_fwd_fusedin tutorial 05, pinned to v3.8.0. Study centered variance, float32 reductions, valid-column masks and the forward wrapper's supported-width guard. Defer backward and the benchmark sweep. - vLLM serving latency and goodput definitionsvLLM Project · reference
vLLM v0.31.0: Benchmark CLI, Understanding the Latency Metrics and Load Pattern Configuration; serving benchmark CLI, goodput service-level objectives. Use definitions to translate kernel evidence into request metrics, not as a required serving-engine installation.