FlashAttention is a breakthrough because it realized that on modern GPUs, computation (FLOPs) is often faster than memory movement (HBM access). By “tiling” the attention matrix and using a clever mathematical trick (Online Softmax), it avoids ever writing the huge attention matrix to memory.
Here is the comprehensive derivation of FlashAttention-1, followed by the specific 2-block example and the distributed system extension.
I: Forward Pass
Part 1: The Core Math (Online Softmax)
To derive FlashAttention, we first need to derive Online Softmax.
Standard Softmax requires looking at the entire row to compute the denominator (normalization constant).
This seems to imply we must calculate all (the entire row of ) before we can finish the calculation. FlashAttention breaks this dependency using the Online Softmax trick, allowing us to compute Softmax block-by-block.
The “Safe” Softmax Update Rule
Let’s look at a single row of scores. Suppose we have two blocks of scores, vector and vector . We want to compute the softmax of the concatenated vector .
We track two statistics for any block :
- : The maximum value in the block (for numerical stability).
- : The sum of exponentials (row sum) for the block, normalized by .
For Block 1 ():
(This is the local output attending only to the first block).
Merging Block 2 ():
Now we process the second block. We need to update our running statistics to account for the new data without re-reading Block 1.
The new global max is simply:
The new global row sum must be adjusted because the old was scaled by , but now we need it scaled by .
Finally, the updated output combines the old output (rescaled) and the new block’s contribution:
This is the exact formula FlashAttention uses to fuse the kernel.
Part 2: Step-by-Step Derivation (2 Blocks, 8 Positions)
Let’s walk through your specific example.
- Total Sequence Length (): 16
- Block Size (): 8
- We have 2 Blocks of Keys/Values: (positions 0-7) and (positions 8-15).
- We focus on a single Query block (positions 0-7).
Step 0: Setup
We utilize Fast SRAM (on-chip memory) and Slow HBM (High Bandwidth Memory).
- In HBM: Full matrices . Initialize to zeros, to zeros, to .
- In SRAM: We will load small blocks of size .
Step 1: Processing Block 1 (Positions 0-7)
We load , , from HBM to SRAM.
-
Compute Scores ():
This contains the attention scores for tokens 0-7 attending to tokens 0-7.
-
Compute Local Statistics:
- Row-wise Max: (Vector of size 8)
- Row-wise Exp Sum:
-
Update Running Statistics (First block is trivial):
-
Write Back:
We write to HBM (or keep in SRAM if we loop immediately). Let’s call these .
Step 2: Processing Block 2 (Positions 8-15)
We load from HBM to SRAM. We still have and the accumulated accumulator () in SRAM/Registers.
-
Compute Scores ():
These are scores for tokens 0-7 attending to tokens 8-15.
-
Compute Local Statistics for Block 2:
- (Unnormalized Probabilities)
-
Merge and Update (The FlashAttention Magic):
We now merge Block 1 stats () with Block 2 stats ().
- New Max:
- New Denominator (Sum of Exps):
Note: One of the exponent terms will be depending on which max was larger.
- New Output ():
- New Max:
-
Result:
now contains the exact attention output for tokens 0-7 attending to the full sequence (0-15), computed without ever instantiating the full matrix.
Part 3: Extension with Data and Tensor Parallelism
Scenario: 8 GPUs total.
Configuration: Data Parallelism (DP) = 2, Tensor Parallelism (TP) = 4.
This means we have 2 replicas of the model. Each replica is split across 4 GPUs.
1. Data Parallelism (DP=2)
The Global Batch Size () is split into 2 micro-batches.
- GPUs 0-3: Handle Micro-batch 1 (Input rows to ).
- GPUs 4-7: Handle Micro-batch 2 (Input rows to ).
- Math: During the Forward/Backward pass, these groups are independent. At the very end (Backward pass), gradients are averaged (AllReduce) across DP groups (e.g., GPU 0 averages gradients with GPU 4).
2. Tensor Parallelism (TP=4)
Within a single DP group (e.g., GPUs 0-3), we split the Attention Heads.
FlashAttention is a “local” kernel; it operates on whatever query/key/value heads are present on the GPU.
- Total Heads (): Let’s say .
- Heads per GPU: heads per GPU.
- Sequence Parallelism: For FlashAttention v1 (Megatron-LM style), we usually do not split the sequence length across GPUs for the attention computation itself (though newer versions like Ring Attention do). We assume standard column/row parallel linear layers.
The Flow on GPU 0 (in DP Group 1):
-
Input: Local input tensor of shape .
-
QKV Projection (Column Parallel):
- GPU 0 holds weights only for Heads 0-3.
- are computed locally.
- Shape: .
-
FlashAttention Kernel (Local):
- GPU 0 runs the exact derivation from Part 2 on its local heads.
- It ignores the existence of other heads on GPUs 1, 2, 3.
- Output Shape: .
-
Output Projection (Row Parallel):
- is multiplied by the local slice of the Output Projection Matrix .
- All-Reduce: The results from GPUs 0, 1, 2, 3 are summed up (All-Reduce) to produce the final output for the next layer.
Summary Table: 8 GPUs (DP2, TP4)
| GPU ID | DP Group | TP Rank | Batch Indices | Head Indices | FlashAttn Operation |
|---|---|---|---|---|---|
| 0 | 1 | 0 | Local FlashAttn on Batch 1, Heads 0-3 | ||
| 1 | 1 | 1 | Local FlashAttn on Batch 1, Heads 4-7 | ||
| 2 | 1 | 2 | Local FlashAttn on Batch 1, Heads 8-11 | ||
| 3 | 1 | 3 | Local FlashAttn on Batch 1, Heads 12-15 | ||
| 4 | 2 | 0 | Local FlashAttn on Batch 2, Heads 0-3 | ||
| … | … | … | … | … | … |
II: Backward Pass
This derivation is significantly more complex than the forward pass because we did not store the attention matrix or the scores . In standard attention, you just read from memory to compute gradients. In FlashAttention, we must recompute on-the-fly using the statistics (max) and (sum) we saved during the forward pass.
Part 1: The Gradients (The Math)
Let be the loss function. We are given the gradient of the loss with respect to the output, . We need to find .
1. Standard Attention Gradients (Refresher)
Recall the forward pass:
The backward gradients (using chain rule) are:
- ? (Gradient through Softmax is tricky)
2. The Softmax Gradient Trick
The Jacobian of the Softmax function is complex. However, for the specific expression , the gradient is given by:
FlashAttention simplifies this computation by defining a term (often called D or delta in implementations):
(Note: This is the dot product of the output gradient and the output itself).
Substituting this back, we get a very clean scalar formula for the gradient of the scores:
Part 2: FlashAttention Backward Derivation (Block-wise)
We iterate differently than the forward pass. In the backward pass, it is more efficient to parallelize over Query blocks (outer loop) and iterate over Key/Value blocks (inner loop) to accumulate , but we also need to write and atomically.
Inputs:
- (in HBM)
- (in HBM)
- (Saved from Forward Pass in HBM)
- Buffers initialized to zero: (HBM). are usually accumulated in HBM using atomic adds or a separate reduction kernel (FlashAttention-1 style).
The Algorithm (Per Block)
Let’s look at Query Block and Key/Value Block .
-
Load from HBM to SRAM:
- (Forward statistics)
-
Recompute Attention ():
We don’t have . We recreate it exactly as we did in the forward pass, but now we have the global max and global sum ready.
Note: In the forward pass, we built incrementally. Here, we use the final to get the exact global probability immediately.
-
Compute (contribution from block ):
-
Compute (Gradient w.r.t probabilities):
-
Compute (Gradient w.r.t scores):
First, compute the correction term (can be done once per row ):
Then apply the softmax gradient formula:
-
Compute (Gradient w.r.t Queries):
-
Compute (Gradient w.r.t Keys):
Part 3: Step-by-Step Example (2 Blocks)
- Token positions: 0-15
- Block size: 8
- Setup: 2 Blocks ( and ).
- Focus: We will calculate the updates generated by Query Block 0 () interacting with both KV blocks.
Step 1: Pre-calculation (Global Correction)
Load (output for tokens 0-7) and (gradient for tokens 0-7).
Compute :
Step 2: Inner Loop (Attention to Block )
Load and stats .
-
Recompute P:
(This recovers the exact attention matrix for the first 8x8 block)
-
Backprop to V:
-
Backprop to S:
-
Backprop to Q and K:
Step 3: Inner Loop (Attention to Block )
Load . Crucially, we still use and .
-
Recompute P:
(Note: We use and from the query block 0. This scales the probabilities correctly relative to the WHOLE sequence).
-
Backprop to V:
-
Backprop to S:
(Using the same calculated in Step 1).
-
Backprop to Q and K:
Result: After iterating through all , is fully computed. and are partial sums and will be completed when the outer loop visits Query Block 1.
Part 4: Distributed Training Extension (Backward Pass)
System: 8 GPUs, DP=2, TP=4.
- DP Groups: {0,1,2,3} and {4,5,6,7}.
- TP Groups: {0,1,2,3} (and same for 4-7).
In the backward pass, gradients flow in the reverse order of the forward pass.
1. Backward through Output Projection (TP)
The output projection was Row Parallel.
- The loss gradient comes in.
- is split column-wise conceptually during backward? No, it’s Row Parallel forward, so Column Parallel backward.
- Communication: A
AllGather(orReduceScatterdepending on implementation) is needed here to construct the gradients for the input of the next layer. - Result: Each GPU gets its slice of (shape ).
2. Backward through FlashAttention (Local)
This happens purely locally on each GPU.
- GPU 0 holds Heads 0-3. It runs the FlashAttention Backward kernel derived above.
- It produces .
- No communication is needed inside the Attention kernel itself.
3. Backward through QKV Projection (TP)
We have for specific heads. We need to backpropagate into the weights .
- Since QKV projection was Column Parallel, the gradients for the weights () are computed locally.
- However, the gradient with respect to the input of the attention block () requires summing contributions from all heads.
- Communication (All-Reduce):
We perform an All-Reduce across the TP group (GPUs 0,1,2,3) to sum the gradients calculated by each GPU.
This synchronizes the gradient before it passes to the LayerNorm or MLP block.
4. Backward through Data Parallelism (DP)
At the very end of the backward pass (after all layers):
- Communication (All-Reduce):
Gradients for all learnable parameters (, etc.) must be averaged across DP groups.
- GPU 0 averages with GPU 4.
- GPU 1 averages with GPU 5, etc.
Summary Table: Gradient Synchronization
| Step | Operation | Parallelism | Communication Required? |
|---|---|---|---|
| 1 | Output Proj Backward | TP | All-Gather (reconstruct ) |
| 2 | FlashAttention Backward | None | None (Purely Local) |
| 3 | QKV Proj Backward | TP | All-Reduce (Sum across heads) |
| 4 | Weight Update | DP | All-Reduce (Average across replicas) |
Relevant Video:
Flash Attention derived and coded from first principles with Triton (https://www.youtube.com/watch?v=zy8ChVd_oTM)
It dedicates a significant section (Chapter 18) to strictly deriving the Jacobians and the backward pass math on “paper” before implementing it, which aligns perfectly with your request for rigorous math.