# FlashAttention explained: tiling, online softmax and why FA4 had to fight the exponential

FlashAttention computes exactly the same attention as the textbook formula, but never writes the huge score matrix to GPU memory. This article walks through the tiling and online softmax maths with numbers, then shows why FlashAttention-4 had to emulate the exponential function in software.

Almost every large language model you call today runs its attention layers through some version of FlashAttention. It arrived five years after the transformer and changed what context lengths are practical. It does not approximate anything. It computes the same numbers as the textbook formula, only in a different order, so that the large intermediate matrix never touches slow GPU memory.

The work is still moving. The FlashAttention-4 package for Hopper and Blackwell GPUs ships a new beta almost every week, and the most recent one landed on 11 November 2026. The FA4 paper from March 2026 also made a point that matters for anyone who reasons about GPU performance: on the newest chips, the matrix multiplications are no longer the slow part of attention. The exponential function is.

## What happened

### flash-attn-4 4.0.0b39 is published on PyPI (11 November 2026)

The FlashAttention-4 implementation is distributed as its own Python package, `flash-attn-4`, separate from the older `flash-attn` package. Version 4.0.0b39 was released on 11 November 2026, following b38 on 4 November, b37 on 28 October, b36 on 21 October and b35 on 14 October. It is still a pre-release. The package page describes it as "a CuTeDSL-based implementation of FlashAttention for Hopper and Blackwell GPUs", installed with `pip install flash-attn-4`.

### Sparse MLA kernels for DeepSeek V4 join the FA4 branch (June 2026)

The FA4 release notes on GitHub show a steady stream of features for current models. The beta19 notes, dated 24 June, add "sparse MLA (DeepSeek V4) backward kernels". Later betas add a learnable attention sink in the backward pass, paged KV cache bounds checks and FP8 tweaks. If you want the background on MLA itself, see our article on [multi-head latent attention and the KV cache](/articles/multi-head-latent-attention-kv-cache).

### The FlashAttention-4 paper and a FlexAttention backend (5 March 2026)

The paper "FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling" by Ted Zadouri, Markus Hoehnerbach, Jay Shah, Timmy Liu, Vijay Thakkar and Tri Dao appeared on arXiv on 5 March 2026. The authors report, on B200 GPUs in BF16, up to 1.3 times the speed of cuDNN 9.13, up to 2.7 times the speed of Triton, and up to 1613 TFLOPs/s, which they put at 71% utilisation. On the same day, the PyTorch team published a post showing that FlexAttention, PyTorch's API for custom attention variants, can now generate FA4 kernels on Hopper and Blackwell.

## The problem: attention is limited by memory, not maths

Attention for one head takes three matrices, queries Q, keys K and values V, each with N rows (tokens) and d columns (head dimension). The textbook computation has three steps:

1. Scores: S = Q Kᵀ / √d, an N by N matrix.
2. Probabilities: P = softmax(S), applied row by row.
3. Output: O = P V, back to N by d.

The trouble is the N by N matrix. Take N = 8,192 tokens. S has 8,192 × 8,192 = 67,108,864 entries. In 16-bit precision that is 134,217,728 bytes, or 128 MiB, for one head of one sequence. A layer with 32 heads needs 4 GiB just to hold S once, and the naive version writes S, reads it back, writes P, and reads P again.

A GPU has two very different kinds of memory. High-bandwidth memory (HBM) is large but comparatively slow to reach. On-chip SRAM (shared memory and registers) is tiny but very fast. The naive algorithm keeps shuttling the giant S and P matrices through HBM, so the arithmetic units sit idle waiting for data. The original FlashAttention paper (Dao, Fu, Ermon, Rudra and Ré, May 2022) named the missing principle: attention algorithms should be IO-aware, "accounting for reads and writes between levels of GPU memory."

An everyday analogy: to add up a pile of receipts, the naive approach photocopies every receipt, files the copies in another room and walks back and forth. FlashAttention keeps a running total on a notepad at your desk.

The amount of arithmetic does not change. The forward pass of one head still needs about 4N²d floating point operations, two matrix multiplications of 2N²d each. For N = 8,192 and d = 128 that is about 34.4 GFLOP per head. What changes is how much data moves. You can watch how attention weights form in our [attention simulation](/ai-simulations/attention), and the [attention mechanism](/tools/attention-mechanism) page covers the basics.

## Tiling and the online softmax, step by step

FlashAttention splits Q into row blocks and K and V into column blocks small enough to fit in SRAM. For one block of queries, it loops over the blocks of keys and values, computes a small tile of scores, uses it immediately, and throws it away. The only obstacle is softmax. A softmax row needs the maximum of the whole row (for numerical stability) and the sum of all its exponentials (for normalisation). When you see the first block of keys, you do not know either value yet.

The fix is the online softmax. For each query row, keep three running quantities: the largest score seen so far, m; the running sum of exponentials, l, measured relative to m; and an unnormalised output accumulator, O. When a new block of scores Sⱼ arrives:

- m_new = max(m, rowmax(Sⱼ))
- α = exp(m − m_new), the correction factor for everything accumulated so far
- P̃ⱼ = exp(Sⱼ − m_new)
- l = α · l + rowsum(P̃ⱼ)
- O = α · O + P̃ⱼ Vⱼ

After the last block, divide: O_final = O / l. The correction factor α is the key. If the maximum grows, all earlier exponentials were computed against a smaller reference and are too large by a factor of exp(m_new − m). Multiplying by α fixes them in one step, without revisiting old blocks.

### A worked example with four scores

Take one query row whose scores are [1, 3, 2, 5], split into two blocks of two.

Block 1 is [1, 3]. The maximum is m = 3. The sum is l = e^(1−3) + e^(3−3) = 0.1353 + 1 = 1.1353.

Block 2 is [2, 5]. The new maximum is m_new = 5, so α = e^(3−5) = 0.1353. The new sum is l = 1.1353 × 0.1353 + e^(2−5) + e^(5−5) = 0.1536 + 0.0498 + 1 = 1.2034.

Computing the sum directly against the true maximum gives e^(−4) + e^(−2) + e^(−3) + e^(0) = 1.2034, the same value. The final softmax is [0.0152, 0.1125, 0.0414, 0.8310], identical to the one-shot version. The output accumulator O is corrected by the same α at every step, so it ends exactly where the textbook formula ends.

### Runnable check

The short NumPy program below implements the tiled loop and compares it with the textbook version on random data. The largest difference we measured was about 4.7 × 10⁻¹⁶, which is floating point rounding.

```python
import numpy as np
d = 128
def full(Q, K, V):
    S = Q @ K.T / np.sqrt(d)
    P = np.exp(S - S.max(1, keepdims=True))
    return (P / P.sum(1, keepdims=True)) @ V

def tiled(Q, K, V, Bc=64):
    n = Q.shape[0]
    m = np.full(n, -np.inf); l = np.zeros(n); O = np.zeros((n, V.shape[1]))
    for j in range(0, K.shape[0], Bc):
        S = Q @ K[j:j+Bc].T / np.sqrt(d)
        m_new = np.maximum(m, S.max(1))
        a = np.exp(m - m_new)          # correction for earlier blocks
        P = np.exp(S - m_new[:, None])
        l = a * l + P.sum(1)
        O = a[:, None] * O + P @ V[j:j+Bc]
        m = m_new
    return O / l[:, None]

Q, K, V = (np.random.randn(512, d) for _ in range(3))
print(np.abs(full(Q, K, V) - tiled(Q, K, V)).max())   # about 1e-16
```

### The backward pass recomputes instead of storing

Training needs gradients, and the textbook backward pass uses P. FlashAttention does not store P. It stores only the output O and one number per row, the log-sum-exp statistic, then recomputes each tile of S and P on the fly during the backward pass. The extra arithmetic costs less than the memory traffic it saves. It is the same trade as [gradient checkpointing](/tools/gradient-checkpointing), applied inside one kernel. The memory held per sequence grows with N instead of N², which is what made long training contexts affordable.

## Four generations, four hardware bottlenecks

Each version of FlashAttention responded to a different limit in the hardware of its day. The table summarises what each paper reports.

| Version | Date | Target GPU | Main idea | Reported result |
|---|---|---|---|---|
| FlashAttention | May 2022 | A100 era | Tiling, online softmax, recomputation | 3× speedup on GPT-2 at sequence length 1K; 2.4× on Long Range Arena |
| FlashAttention-2 | July 2023 | A100 | Better work split across threads, fewer non-matmul operations | About 2× faster than v1; 50 to 73% of peak FLOPs/s on A100 |
| FlashAttention-3 | July 2024 | H100 | Warp specialisation, overlapping matmul and softmax, FP8 | 1.5 to 2.0× on H100; FP16 up to 740 TFLOPs/s (75%) |
| FlashAttention-4 | March 2026 | B200 and Hopper | Software exponential, conditional rescaling, tensor memory, 2-CTA MMA | Up to 1613 TFLOPs/s (71%) on B200 in BF16 |

FlashAttention-2 (Tri Dao, July 2023) cut operations that are not matrix multiplies, which run far slower than tensor cores, and split the work better between threads.

FlashAttention-3 (Shah and co-authors, July 2024) targeted the [H100](/tools/nvidia-h100), whose tensor cores and data-movement engine (TMA) work asynchronously. Groups of threads (warps) specialise in loading or multiplying, and one block's softmax overlaps the next block's matrix multiply. FA3 also added FP8 support and reported 2.6 times lower numerical error than a baseline FP8 attention, using block quantisation and a trick called incoherent processing. Our article on [NVFP4 and MXFP4](/articles/nvfp4-mxfp4-microscaling-4-bit-formats) explains how block-scaled low-precision formats work.

## Why FA4 had to fight the exponential

The FA4 paper starts from a hardware fact. From Hopper to Blackwell, tensor core throughput doubled, but other units did not keep pace. The paper gives these numbers per streaming multiprocessor (SM) per clock:

- BF16 tensor core work: 8,192 operations on B200, up from 4,096 on Hopper.
- Exponential unit (called MUFU): 16 operations on B200, the same as on Hopper.
- Shared memory reads: 128 bytes.

Now compute what this means for one tile. Take a block of 128 queries, a block of 128 keys and head dimension 128. The two matrix multiplies, Q Kᵀ and P V, cost 2 × (2 × 128 × 128 × 128) = 8,388,608 operations. At 8,192 per clock that is 1,024 clocks. The softmax needs one exponential per score, 128 × 128 = 16,384 of them. At 16 per clock that is also 1,024 clocks. On the [B200](/tools/nvidia-b200), the exponentials take as long as the matrix multiplies. On Hopper, the same tile needed 2,048 clocks of matmul against 1,024 of exponentials, so the exponentials could hide behind the maths. On Blackwell they cannot.

It is like a kitchen that doubles its chefs but keeps one oven: every dish still waits for the oven.

FA4 attacks this from three sides.

**Emulating part of the exponential in software.** Instead of sending every exponential to the slow MUFU unit, FA4 computes some of them with a polynomial approximation of 2ˣ on the ordinary fused multiply-add (FMA) units, which have plenty of spare capacity. The paper uses this for roughly 10 to 25% of the entries in each softmax row and sends the rest to MUFU. Splitting the work between two units raises the combined rate.

**Rescaling only when it matters.** In the online softmax, every new block may change the row maximum and force a rescale of the output accumulator. FA4 skips the rescale unless the maximum grows by more than a threshold τ, set to log₂(256) = 8 in the base-2 exponent the kernel uses. A stale maximum is harmless as long as the values stay within floating point range: with this threshold the unnormalised exponentials can be at most 256 times larger than they would be with the exact maximum, which 32-bit floating point handles easily. The final division by l removes the effect, so the result is still exact up to rounding. In our NumPy version of the same rule on random data, only the first block of each row triggered a rescale, so 7 of every 8 row updates skipped it.

**Using new Blackwell memory and pipelining.** Blackwell adds tensor memory (TMEM), 256 KB per SM, that holds matrix multiply results next to the tensor cores. FA4 computes two output tiles per thread block in a ping-pong schedule, so one tile's tensor core work overlaps the other tile's softmax, and a separate "correction" group of threads handles rescaling. In the backward pass, a mode that lets two thread blocks cooperate on one multiply (2-CTA MMA) cuts shared memory traffic and halves the global atomic additions for the query gradient. A deterministic backward mode, useful for reproducible training, reaches up to 75% of the speed of the non-deterministic version, according to the paper.

### Written in Python, compiled in seconds

FA4 is written entirely in CuTe-DSL, NVIDIA's Python-embedded language for CUTLASS kernels, with no CUDA C++. The paper reports forward-pass compile time falling from 55 seconds for FA3 to 2.5 seconds, and backward from 45 seconds to 1.4 seconds. That matters for FlexAttention. When you write a custom mask or score modification in Python, PyTorch generates CuTe-DSL code and compiles an FA4 kernel for it. The PyTorch post reports 1.2 to 3.2 times the speed of FlexAttention's Triton path on compute-bound workloads. You select it with `kernel_options={"BACKEND": "FLASH"}` on a compiled `flex_attention` call; the post notes this needs a recent PyTorch nightly and FlashAttention checkout, and warns that breaking changes are likely.

## What it means in practice

Most teams use FlashAttention indirectly, through PyTorch's scaled dot product attention, vLLM, SGLang or a vendor library. What you control is whether the fast path is taken: unusual head dimensions, custom masks or unsupported dtypes can silently push a model onto a slower path.

FlashAttention also clears up a common confusion about long context. It removes the N² memory of the score matrix during a forward pass. It does not shrink the KV cache that a server keeps between decoding steps. That cache still grows with the number of tokens, layers and heads, which is why techniques such as MLA, grouped query attention and quantised caches exist. Our [KV cache simulation](/ai-simulations/kv-cache) lets you size it, and the [serving stack article](/articles/llm-inference-serving-stack-cache-routing) shows where attention kernels sit in a production server.

FA4 is also a reminder that the best kernel depends on the hardware's ratio of compute, memory and special functions. The paper notes that B300 and GB300 double the exponential rate to 32 per clock per SM, which shifts the balance again.

## What to do now

1. **Check which attention backend you hit.** Profile one training or serving step and confirm that a flash-style kernel runs. A fallback to a math or memory-efficient path can cost a large factor without any error.
2. **Keep head dimensions kernel-friendly.** Check the kernel's support matrix before choosing an unusual head size.
3. **Use variable-length kernels for packed batches.** `flash_attn_varlen_func` handles sequences of different lengths without padding, which saves both memory and compute.
4. **Try FlexAttention for custom masks.** Sliding windows, document masks and ALiBi-style biases can be written in Python, and on Hopper or Blackwell the FA4 backend can compile them.
5. **Pin versions while FA4 is in beta.** The package ships roughly weekly pre-releases. Pin an exact version in production and test upgrades on a staging box.
6. **Measure, do not assume, speedups.** Reported numbers are for specific shapes and GPUs, so benchmark your own sequence lengths and masks.
7. **Turn on deterministic mode only when you need it.** Reproducible gradients are valuable for debugging, but the paper reports the deterministic backward at up to 75% of normal speed.
8. **Size the KV cache separately.** FlashAttention does not reduce it. Plan memory for decoding with the cache, not the attention kernel, in mind.

## Risks and open questions

**Pre-release software carries churn.** FA4 is still published as a beta, and the PyTorch post explicitly warns of breaking changes. Kernels that compile today may need code changes after an upgrade.

**Reported numbers come from the authors.** The speedups and utilisation figures are the paper's own measurements on its chosen shapes. The paper's appendix also lists a "B100 180GB SXM6" and a benchmark date of "March 2025", while the main text says B200, so read the exact setup carefully before comparing.

**Approximate exponentials need numerical care.** The polynomial exponential is an approximation, so anyone extending the kernel to new formats should test accuracy as well as speed.

**Feature gaps remain.** The FlexAttention FA4 backend does not yet support captured buffers that need gradients, its backward pass is not yet deterministic with block sparsity, and its block sizes are fixed at 128 by 128 on Hopper and 256 by 128 on Blackwell.

**Watch next:** whether FA4 leaves beta and becomes the default path in PyTorch and the main serving engines, how its kernels adapt to B300's faster exponential unit, and how quickly sparse and latent attention variants, such as the DeepSeek V4 sparse MLA kernels, reach the same level of tuning as dense attention.

## Frequently asked questions

### Is FlashAttention an approximation of attention?

No. It computes exact attention. The online softmax and the correction factor reorder the arithmetic but produce the same result as the textbook formula, apart from ordinary floating point rounding. In our NumPy check the largest difference was about 10⁻¹⁶.

### Why is FlashAttention faster if it does more arithmetic in the backward pass?

Because attention on GPUs is usually limited by memory traffic, not arithmetic. Recomputing score tiles from Q and K in fast on-chip memory costs less time than writing and reading a full N by N matrix through high-bandwidth memory. Trading cheap compute for expensive data movement is the core idea.

### Does FlashAttention reduce the KV cache during inference?

No. It removes the need to store the score matrix while computing attention, but the keys and values of past tokens still have to be kept for decoding. KV cache size depends on layers, heads, head dimension, precision and tokens. Methods such as grouped query attention, MLA and cache quantisation address that separately.

### What is different about FlashAttention-4?

FA4 targets Blackwell, where tensor cores doubled in speed but the exponential unit did not. It computes part of the exponentials with a polynomial on spare FMA units, skips most softmax rescaling, and uses Blackwell's tensor memory and two-block multiply mode. It is also written in Python-embedded CuTe-DSL, which makes compilation much faster.

### Can I use FA4 on older GPUs such as the A100?

The `flash-attn-4` package states that it targets Hopper and Blackwell GPUs. For Ampere cards such as the A100, the older `flash-attn` package with FlashAttention-2 remains the usual choice.

## Summary

FlashAttention computes exact attention without ever storing the N by N score matrix in slow GPU memory. It does this by tiling Q, K and V into blocks that fit on chip, using the online softmax to keep a running maximum, sum and output with a correction factor, and recomputing tiles in the backward pass instead of saving them. Each version answered a new hardware bottleneck: memory traffic for v1, non-matmul work for v2, asynchrony on H100 for v3, and on Blackwell, for v4, the exponential function itself, whose unit did not speed up while tensor cores doubled. FA4 is still in weekly beta, with release 4.0.0b39 on 11 November 2026, so pin versions, check that your models actually use the fast path, and remember that the KV cache is a separate problem. More background is on our [FlashAttention](/tools/flashattention) page and in the [serving and cost](/topics/generative-ai-llms/serving-and-cost) topic.

## Sources

- [arXiv: FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://arxiv.org/abs/2205.14135)
- [arXiv: FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning](https://arxiv.org/abs/2307.08691)
- [arXiv: FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision](https://arxiv.org/abs/2407.08608)
- [arXiv: FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling](https://arxiv.org/html/2603.05451)
- [PyTorch: FlexAttention + FlashAttention-4: Fast and Flexible](https://pytorch.org/?p=46919)
- [PyPI: flash-attn-4](https://pypi.org/project/flash-attn-4/)
- [GitHub: Dao-AILab flash-attention releases](https://github.com/Dao-AILab/flash-attention/releases)
