Unit 5 of 10 · about 5 hours · derive, implement

Backward attention state and recomputation

This optional unit connects inference-style tiling to training. Recomputing scores can save memory, but correctness depends on preserving the forward scale and mask.

You'll be able to

  • Derive attention input gradients from the rowwise softmax Jacobian.
  • Reconstruct probabilities from saved logsumexp rather than a saved probability matrix.
  • Implement the optional backward path and check masks, scale and gradient accumulation ownership.

Covers

Backward attention state and recomputation
1

Read

In this order, only the parts listed

0 of 2 done

  1. FlashAttention backward derivation, arXiv:2205.14135v2FlashAttention

    Appendix B.2, Memory-efficient backward pass, and Appendix B.4, Algorithms 3 and 4 (pp. 18 to 21)

    Use the no-dropout case. Defer random-mask regeneration and a fused GPU backward kernel.

  2. CS336 backward with recomputationCS336 Assignment 2 - Section 4 FlashAttention-2 in Triton

    Section 4.2.2, Backward pass with recomputation, equations 13 to 19 (p. 24), and problem flash_backward (p. 28)

    Implement the requested PyTorch backward and compile it. Stop before optional Section 4.2.3. A dense recomputed backward is a learning step, not a memory-efficient tiled backward.

2

Focus on

  • With scaled and masked scores , save . Reconstruct allowed probabilities as . Logarithm and exponential bases must agree.
  • For output cotangent , compute , and . Then , and .
  • Saving inputs, output and one statistic per query row avoids saved quadratic probabilities. A dense backward may still allocate quadratic temporary scores and probabilities; tiled recomputation is needed to remove that peak workspace.
  • Query-block owners can accumulate query gradients, while key-block owners accumulate key/value gradients. Shared gradient destinations require a reduction or atomics; GQA also sums key/value gradients across query heads in each group.
Common mistakes · 3
  • Dropping the score scale in query and key gradients. The softmax score derivative is not yet the derivative of the unscaled dot product.
  • Using tile-local logsumexp instead of the full row's saved statistic. Reconstructed tile probabilities then normalize independently.
  • Advertising the compiled dense backward as FlashAttention's tiled memory guarantee. Compilation alone does not prove which quadratic temporaries disappear.
3

Try it yourself

Closed-book, before checking anything

From a blank file, implement the no-dropout gradient equations for seed 0 standard-normal torch.float64 inputs with batch size 2, 17 queries, 19 keys and width 7, and a random output cotangent generated after those inputs. Compare all three gradients against dense PyTorch 2.14.1 autograd on CPU with rtol=1e-12, atol=1e-12. Then add causal masking using absolute positions and confirm masked probabilities and their score gradients are zero.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Why can the row correction be computed from output and its gradient?Answer

    Expanding the output as a probability-weighted sum of values shows that its dot product with the output cotangent equals the probability-weighted sum of probability cotangents. It is one scalar per query row.

  2. 2.Must recomputation make backward slower?Answer

    No. It adds arithmetic but can remove expensive memory movement. Whether it wins depends on hardware, shape and the actual backward schedule.

  3. 3.What happens to a shared KV head's gradients under GQA?Answer

    Its key and value gradients are sums of contributions from every query head that uses it, not just one head's contribution.

5

Practice

  • CS336 Assignment 2: flash_backward

    test_flash_backward_pytorch and both is_causal settings of test_flash_backward_triton; run pytest tests/test_attention.py -k test_flash_backward

    Use the adapter name get_flashattention_autograd_function_triton; the forward handout abbreviates it incorrectly. The public tests check three input gradients on fixed 128 by 128 attention, not peak memory or GQA. Add double-precision small-case checks and mask regressions in kernellab.

You're done when

All public backward cases pass, your independent small-case gradient checks pass, and you distinguish saved-state memory from backward peak workspace.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 11 more in the 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.

  • 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) and flash_backward against tests/test_attention.py. Run flash_benchmarking on sizes that fit your GPU instead of the handout's B200 sweep.

Also in this 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.

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

  • 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.compile and Using SDPA with attn_bias subclasses. Correct the tutorial's evaluation-time causal flag before integration.

  • Triton 3.8.0 Layer NormalizationTriton Project · required

    Motivations and _layer_norm_fwd_fused in 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.