Unit 2 of 10 · about 6 hours · derive, implement
Online softmax state, query and key-value tiling and output tolerance
Online softmax lets a query row consume keys in pieces. Rescaling both the denominator and weighted numerator is what makes those pieces one attention operation.
You'll be able to
- Derive the running maximum, normalizer and weighted numerator invariants.
- Implement a tiled forward pass that retains only query-tile state on chip.
- Validate accumulation and rescaling with an independent reference and a stated extreme-value policy.
Covers
Read
In this order, only the parts listed
0 of 2 done
- Online Normalizer Calculation, arXiv:1805.02867v2Online Normalizer Calculation for Softmax
Section 3, Algorithm 3 and its induction proof; Section 3.1, equations 3 and 4 (pp. 2 to 4)
Stop before Section 4. The proof assumes finite logits; its associativity is a real-arithmetic statement, not bitwise floating-point equivalence.
- CS336 Assignment 2: weighted sum and tiled forwardCS336 Assignment 2 - Section 4 FlashAttention-2 in Triton
Commit ca8bc81: Section 4.2.1, Example - Weighted Sum, forward pass (pp. 17 to 19); Section 4.2.2, Details of the FlashAttention forward pass and Algorithm 1 (pp. 24 to 25); problem
flash_forwardparts (a) and (b) (pp. 26 to 27)Read the weighted-sum forward example before attention; defer its backward kernel. Start with the public test sizes, not the B200 sweep. Add bounds checks beyond the handout's power-of-two contract.
Focus on
- For processed keys, keep , and . Output is . A rising maximum changes the scale of all old contributions.
- For new tile scores , use , , and . Normalize once at the end.
- Keep the query tile and row state while streaming key/value tiles. Accumulate reductions and weighted outputs in
tl.float32; record dot-product precision and casts separately from output dtype. - For finite inputs, compare with a dense double-precision reference using absolute and relative error. Handle empty tiles explicitly. Define all-masked rows as zero output and negative-infinite logsumexp, or reject them; reject NaN and infinite unmasked logits unless you implement another policy.
Common mistakes · 3
- Rescaling the denominator but leaving the old weighted numerator unchanged. A later larger maximum then changes the answer.
- Padding keys with zero scores. They still receive probability mass; invalid keys must contribute neither to the normalizer nor the numerator.
- Evaluating a difference of two negative infinities for an empty tile. Branch or use safe neutral-state handling rather than letting NaNs enter the recurrence.
Try it yourself
Closed-book, before checking anything
torch.tensor([0., 1., 2., 3.], dtype=torch.float64) and scalar values torch.tensor([1., 2., 3., 4.], dtype=torch.float64), split after the second entry. In PyTorch 2.14.1 the weighted output is approximately 3.492652734585769. Then implement query/key tiling for seed 0 standard-normal inputs of shapes 2 by 17 by 7 and 2 by 19 by 7, with scale . Both 4 by 5 and 8 by 8 tiles must match the double-precision dense reference within rtol=1e-12, atol=1e-12 on CPU.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why can you postpone normalization until the final tile?Answer
The numerator and denominator share the same running exponential scale. Their ratio is the normalized weighted sum over all keys processed so far.
2.Is merging tile states associative?Answer
For finite logits it is associative in exact real arithmetic: each state summarizes the same weighted exponential sums. Floating-point merge order can change rounding.
3.Does subtracting the maximum solve every extreme-value case?Answer
No. It controls exponential overflow for finite scores, but cannot repair overflow in the dot product or define softmax of an all-masked row. Those need separate contracts.
Practice
- CS336 Assignment 2:
flash_forward(a) and (b)Connect both attention classes through
tests/adapters.py; runpytest tests/test_attention.py -k "test_flash_forward_pass_pytorch or test_flash_forward_pass_triton[False]"now, and the full-k test_flash_forward_passafter adding causal support in the next unitFirst pass the PyTorch case and the noncausal Triton case. The public inputs use batch size 4, sequence length 128 and head width 64, and compare output and saved logsumexp with
rtol=1e-2, atol=1e-2. They do not check tails or extremes. Add those inkernellab; do not reuse the tiled algorithm as its own oracle.
You're done when
You derive the two-state merge, pass both noncausal forward tests, and your own partial-tile and extreme-finite tests pass a justified error budget.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 11 more in the section
- 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.
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.
- 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.
- 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.
- 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.
- 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.
- 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. - 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.