Welcome back. In the previous lesson, you separated weight quantization from KV-cache quantization and used memory and bandwidth budgets to decide which one addresses a serving bottleneck. FlashAttention tackles a related but distinct issue: rather than compressing tensors, it changes the order of computation so the GPU moves far less data between high-bandwidth memory (HBM) and fast on-chip memory.
This lesson focuses on the central claim behind FlashAttention: it computes ordinary softmax attention—without sparsity, low-rank approximation, or altered attention weights—while avoiding the costly materialization of the full score and probability matrices. You will see why this matters most for long-context training and prefill, how tiling and online softmax make it possible, and why doing more arithmetic can still make the kernel faster.
The performance problem is data movement, not the attention formula
For one attention head with sequence length and head dimension , standard scaled dot-product attention is
where , , and each have shape . A causal mask, padding mask, or other attention mask is normally incorporated before softmax; FlashAttention supports this while preserving the semantics.
The important shape difference is:
| Tensor | Shape | Size growth with sequence length |
|---|---|---|
| Linear in | ||
| Scores | Quadratic in | |
| Probabilities | Quadratic in |
A conventional decomposition of attention often executes these as separate kernels:
- Read and from HBM, compute , then write to HBM.
- Read , apply masking and softmax, then write to HBM.
- Read and , compute , then write to HBM.
The score and probability matrices are intermediate results, yet they are enormous. With and BF16 elements, one matrix occupies
per attention head. Writing and later reading both and alone costs roughly MiB of HBM traffic per head, before considering , , , output, batch size, or multiple heads.
HBM is extremely fast in absolute terms, but on-chip SRAM is much faster and much smaller. Therefore, a GPU kernel can be limited not by its floating-point units, but by the repeated movement of intermediate tensors to and from HBM.
Basic idea behind flash attention (V1) | Damek Davis’ Website
Read Damek Davis’ concise introduction to establish the I/O problem that FlashAttention solves. It connects the familiar attention equations to the GPU memory hierarchy and makes clear why the quadratic intermediate matrices are the issue.
In the opening section, start at the standard attention sequence. Read through the numbered HBM reads and writes, then continue through the paragraph that compares the quadratic traffic of S and P with the linear-sized Q, K, V, and O tensors. Focus on where each intermediate is written, rather than memorizing the asymptotic notation.
A useful distinction for system design is this:
- The mathematical work remains quadratic. Exact dense attention still evaluates all relevant query-key interactions, requiring arithmetic.
- The HBM traffic is reduced. FlashAttention’s innovation is I/O-aware scheduling, not a reduction in the fundamental dense-attention FLOP count.
- The peak intermediate-memory footprint drops sharply. The full score and probability matrices never exist in HBM.
That first point prevents a common interview mistake: FlashAttention is not “linear attention,” and it is not an approximation method.
FlashAttention’s core move: compute on tiles, not full matrices
The GPU cannot hold full or in SRAM. It can, however, hold small blocks of , , , and temporary results. FlashAttention divides these matrices into tiles and runs the computation for one query tile against one key-value tile while those tiles reside on chip.

Conceptually, the algorithm proceeds as follows:
- Partition into query blocks and into corresponding key and value blocks.
- Load one block from HBM into SRAM.
- For each block, load that block and its current partial output into SRAM.
- Compute the block’s scores, masking, softmax contribution, and weighted value contribution entirely on chip.
- Update the partial output and a small amount of softmax state for that query block.
- Write only the updated output block and softmax state back to HBM.
The scheduling has a subtle trade-off. A key-value tile can be reused while it sits in SRAM, but each query block may be revisited as the kernel processes subsequent key-value tiles. That causes some re-reading of and partial output. This is acceptable because those tensors are , while the avoided matrices are .
In the original FlashAttention analysis, if denotes available SRAM measured in scalar elements, the conventional implementation has HBM traffic dominated by a quadratic term. FlashAttention’s leading tiled-access term is approximately
along with unavoidable linear-sized input and output traffic. A rough reduction factor is
when the SRAM capacity is large relative to one head’s working set.
For example, using BF16-equivalent elements and ,
This is a useful first-order intuition, not a promise that a specific GPU will be precisely times faster. Real block sizes are chosen around SRAM capacity, register pressure, tensor-core tile shapes, occupancy, masking requirements, and the details of the GPU architecture.
Why softmax does not prevent tiling
Matrix multiplication is naturally tiled, but attention has an apparent obstacle: softmax normalizes each row across all keys. If a query row’s scores are split across key tiles, how can a kernel normalize correctly before seeing every score?
The answer is online softmax. For a score row , the numerically stable softmax is based on:
Instead of retaining all of , FlashAttention retains only two running statistics for each query row:
- : the largest score seen so far;
- : the corresponding normalized exponential sum.
Suppose a row has already processed previous key tiles with state . For a new key tile, the kernel computes local statistics , where is the value-weighted result normalized within that tile.
The merged maximum is
The merged normalization constant is
The merged output is
The rescaling factors account exactly for the fact that an unexpectedly large score may appear in a later tile. Once all key blocks have been incorporated, the resulting is the same attention output that a full-row softmax would produce.
In other words, the algorithm does not compute independent softmaxes for each tile and concatenate them. That would be wrong. It computes each local contribution and then merges it with the correct normalization.
How FlashAttention Accelerates Generative AI Revolution
Watch “How FlashAttention Accelerates Generative AI Revolution” by Jia-Bin Huang for a visual derivation of online softmax and its extension to tiled attention.
Begin with online softmax. Focus on why subtracting a running maximum preserves numerical stability while allowing the normalization sum to be updated incrementally. Then watch tiled attention, which connects that recurrence to the Q, K, and V tiles. The essential point is that only a compact partial output and normalization state persist between tiles.
Kernel fusion: keeping intermediates on chip
Tiling enables the individual pieces of attention to be fused into one coordinated kernel:
- matrix multiplication for block scores;
- scaling and causal or padding masking;
- softmax statistics and exponentials;
- multiplication by the value tile;
- partial-output update.
A conventional implementation makes each operation a boundary at which a large intermediate may be written to and later read from HBM. FlashAttention makes SRAM the workspace for those intermediates. Only the final , plus small per-row softmax statistics needed during the computation or backward pass, must persist outside the kernel’s on-chip working set.
Basic idea behind flash attention (V1) | Damek Davis’ Website
Return to Damek Davis’ explanation for the tiled execution schedule, then use the backward-pass section to understand why FlashAttention is especially important during training.
Under “Flash attention (V1),” read the “Tiling” subsection. Start at the tiled setup, then continue through the discussion of repeated passes over Q and the SRAM-based reduction in traffic. Next, under “The Backward Pass and Recomputation,” read the recomputation explanation. Notice the deliberate trade: additional arithmetic replaces a large HBM read.
This is a broader GPU optimization pattern worth retaining:
When a workload is memory-bound, recomputing a value can be faster than storing it and fetching it later.
The statement is conditional. Recompute is beneficial only if its additional arithmetic is cheaper than the memory traffic it avoids. In attention’s backward pass, that condition often holds.
Training: recomputation replaces saved attention probabilities
During training, backpropagation needs information related to the attention probabilities . A conventional implementation saves , then reads it later during backward propagation. Since is , this is another major memory and HBM-traffic cost.
FlashAttention instead saves:
- the final attention output , with shape ;
- compact softmax statistics, typically one value or a small set of values per query row.
During the backward pass, it reloads relevant , , and blocks, recomputes the needed score and probability blocks in SRAM, and uses them to form gradients with respect to , , and .
This is selective recomputation, closely related in spirit to activation checkpointing. The difference is important:
| Approach | Saved state | Later cost | Typical motivation |
|---|---|---|---|
| Store full | Large probability matrix | HBM reads in backward pass | Minimize recomputation |
| FlashAttention | Output plus compact softmax statistics | Recompute score/probability tiles | Reduce HBM traffic and memory |
| General activation checkpointing | Selected activations | Recompute selected forward regions | Fit a larger training workload in memory |
FlashAttention may perform more FLOPs than a conventional attention backward pass. Yet its wall-clock time can be lower because the avoided HBM transfers dominate the extra arithmetic. This directly applies the roofline reasoning from earlier in the course: fewer FLOPs does not necessarily mean lower latency.
Exact attention does not mean bitwise-identical output
“Exact” in FlashAttention means it evaluates the same dense softmax-attention operation, rather than changing the mathematical operator through approximation.
It does not necessarily mean a bit-for-bit identical tensor compared with every other implementation. Floating-point arithmetic is not associative:
in general under finite precision. A tiled implementation changes reduction and accumulation order, and different kernels may use different internal precisions. Small numerical differences can therefore occur, just as they can across two ordinary matrix-multiply implementations.
The relevant distinction is:
| Method | Does every relevant query-key interaction contribute? | Changes attention mathematics? |
|---|---|---|
| FlashAttention | Yes | No |
| Sliding-window attention | No, distant positions excluded | Yes |
| Block-sparse attention | No, selected blocks excluded | Yes |
| Linear-attention approximation | Not evaluated as dense softmax attention | Yes |
| Low-rank approximation | Approximates the score or probability structure | Yes |
This is why FlashAttention is broadly deployable: it improves the standard attention primitive without requiring a model to be trained around a different attention mechanism.
Where FlashAttention helps in LLM systems
FlashAttention matters most when many query tokens are processed together:
- Training: forward and backward passes often process long sequences, so avoiding the full attention matrix substantially lowers memory use and HBM traffic.
- Prefill: a serving system processes all prompt tokens to establish the KV cache. Long prompts produce a large query-by-key attention region, making FlashAttention highly valuable for TTFT and memory feasibility.
- Decode: each active sequence typically has only one new query token at a step. There is no full intermediate to eliminate in the same way, although specialized attention kernels still matter. Decode remains strongly affected by reading model weights and growing KV caches.
This distinction connects FlashAttention to the serving metrics from earlier lessons:
| Serving phase | Main FlashAttention contribution |
|---|---|
| Prompt prefill | Reduces intermediate-memory pressure and HBM traffic for dense prompt attention; can improve TTFT |
| Autoregressive decode | Less direct benefit from avoiding an matrix; KV-cache and weight bandwidth remain primary concerns |
| Long-context workloads | Particularly valuable because conventional attention intermediates grow quadratically with prompt length |
Do not frame FlashAttention as a replacement for KV-cache quantization. They attack different traffic sources:
- FlashAttention avoids materializing ephemeral attention-score and probability matrices.
- KV-cache quantization shrinks the persistent per-request state that decoding repeatedly reads.
- Weight quantization reduces fixed model-residency memory and repeated weight movement.
A production serving stack commonly uses all three, subject to hardware and kernel support.
A concise architecture-review answer
For an interview or design review, a strong explanation can follow this structure:
Standard attention typically writes the score matrix and the probability matrix to HBM between separate operations. For long sequences, that HBM traffic and intermediate memory dominate runtime. FlashAttention tiles , , and , loads small blocks into fast SRAM, and fuses score computation, masking, softmax, and value aggregation. Online softmax maintains running maxima and normalization sums, so the output can be accumulated tile by tile with the same dense softmax-attention result. In training, it saves compact normalization statistics and recomputes attention blocks during backward propagation rather than storing the full probability matrix. It retains quadratic dense-attention computation, but substantially reduces HBM traffic and peak memory.
Key takeaways
FlashAttention is an I/O-aware exact-attention algorithm.
- Standard dense attention’s key bottleneck is often the HBM read/write traffic caused by materializing and , each of shape .
- FlashAttention tiles , , and , performs attention subcomputations in SRAM, and avoids storing the full score and probability matrices in HBM.
- Online softmax keeps only running maxima and normalization sums, allowing blockwise computation while preserving correct global softmax normalization.
- The algorithm still performs dense attention arithmetic; it reduces memory traffic and peak intermediate storage rather than changing the attention operator.
- In the backward pass, recomputation trades extra FLOPs for substantially lower HBM traffic, which is often faster for a memory-bound workload.
- The strongest serving benefit is generally during long-prompt prefill; decode has different dominant costs, especially model-weight and KV-cache reads.
Next, you will analyze speculative decoding and calculate when a draft model’s accepted tokens save enough verification work to improve generation latency and throughput.
Can't find a good explanation? Sign up and we'll make it for you
Sign up