Unit 8 of 10 · about 6 hours · implement
Stable RMSNorm and LayerNorm, and RoPE fusion
Normalization and rotation are small kernels with strict numerical and layout contracts. Fusion is useful only when it preserves their order, reduction domain and positions.
You'll be able to
- Implement stable forward RMSNorm and LayerNorm with explicit , reduction width and accumulation dtype.
- Implement half-split and interleaved RoPE with correct request positions.
- Choose a legal norm/RoPE fusion boundary and validate it against separate operations.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Triton 3.8.0 LayerNorm forwardTriton 3.8.0 Layer Normalization
Motivations,
_layer_norm_fwd_fused, andLayerNorm.forward(the autograd wrapper beforetest_layer_norm)Stop at the forward implementation and supported-width guard. Skip backward, Apex and the automatic benchmark sweep. Do not inherit the tutorial's unmeasured 'faster' claim.
- FlashInfer RMSNorm interfaceFlashInfer
Commit f2794d5:
rmsnormdocstring and_rmsnorm_impldispatchRead ordinary normalization, not quantized or architecture-specific variants. Pass explicitly when comparing libraries.
- FlashInfer RoPE positions and pairing layoutsFlashInfer
Commit f2794d5:
apply_ropedocstring, especiallyindptr,offsets,rotary_dimandinterleave
Focus on
- RMSNorm uses before the learned scale. LayerNorm subtracts the mean and uses population variance, not the sample-variance denominator. Neither is a substitute for the other.
- Promote low-precision inputs before squaring and reducing. Centered variance avoids subtracting nearly equal raw moments. Mask padded lanes out of both reductions and divide by the valid width, not the padded tile width.
- A RoPE pair maps to . Half-split pairs corresponding entries from two halves; interleaved pairs adjacent channels. Position offsets and frequency conventions are model parameters.
- A fused head-norm/RoPE kernel must finish the whole head reduction before rotating and storing pairs. Do not move a model's hidden-width pre-norm through its projection, or reorder learned channel scales and rotation. Test fusion against the exact original operation order.
Common mistakes · 3
- Using dtype-dependent default in one baseline and a fixed value in another. Pass the same explicit and affine parameters.
- Assuming the challenge's randomly generated
cosandsintables represent unit rotations. Its tests check the algebraic transform, not trigonometric identity or position generation. - Squaring large finite values without a range policy. Float32 promotion prevents many half-precision overflows, not every possible float32 overflow; test or reject inputs outside your supported numerical range.
Try it yourself
Closed-book, before checking anything
[3., 3., 3., 3.], unit weights, zero LayerNorm bias and eps=1e-5, LayerNorm returns zero while RMSNorm does not. For input [1., 2., 3., 4.], rotate half-split pairs by angles 0.3 and 0.7 radians using genuine sine/cosine tables; squared norm is preserved within rtol=1e-12, atol=1e-12 in PyTorch 2.14.1. Implement the forward GPU kernels and compare fused head-norm then RoPE with the separate reference order.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why can padding zeros corrupt LayerNorm even though their input contribution is zero?Answer
They change the denominator if counted as features. After mean subtraction their squared deviations are also nonzero unless explicitly masked.
2.Does norm preservation prove that a RoPE implementation uses the correct layout?Answer
No. Rotating the wrong pairs can still preserve norm. Compare the model's pairing layout, frequencies and absolute positions with an independent reference.
3.Can arbitrary learned channel scales commute with RoPE?Answer
No. A pair's two scales generally differ, so scaling before rotation and scaling after rotation produce different vectors. Preserve the prescribed order.
Practice
- LeetGPU 61: Rotary Positional Embedding
reference_impl,generate_example_testand all six cases ingenerate_functional_testUse your local harness and preserve
solveas in challenge 6. These are half-split even-width cases with supplied tables, including zero and mixed values. Skip the million-row performance case on a small GPU. The section mini-project covers forward norms, generated positions, interleaved pairing, partial rotary width and fused head-norm/RoPE checks. This is the first of the pool's two selected transformer challenges.
You're done when
Challenge 61 passes, both norm kernels match references with explicit on odd-width and constant rows, and your legal fused path matches the separate operation order across positions and layouts.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 11 more in the section
- 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.
- 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.
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.
- 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.
- 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. - 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.