Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

7.4 Flash Attention 1, 2, 3

A 4,096-token attention head produces 4,09624,096^2 pairwise scores. Stored in FP32, that single matrix occupies 64 MiB. With a batch of two and eight heads, the score matrices alone occupy 1 GiB. Computing the scores is useful work; repeatedly writing and reading a full matrix that will soon be discarded is a separate cost.

FlashAttention changes the execution schedule of attention to reduce that memory traffic [1]. It processes tiles in fast on-chip memory and accumulates the output without storing the full score or probability matrix in GPU high-bandwidth memory (HBM). The dense computation still has quadratic arithmetic cost in sequence length. Try the four-key example to see which running sums let a tile go out of scope.

1. Count the Intermediate, Then the Whole Workload

For one head, let Q,K∈RL×dQ,K\in\mathbb R^{L\times d} and V∈RL×dvV\in\mathbb R^{L\times d_v}, where LL is sequence length, dd the query/key dimension and dvd_v the value dimension. Suppressing masks for now,

S=QK⊤/d,P=softmax⁡(S),O=PV.S=QK^\top/\sqrt d,\qquad P=\operatorname{softmax}(S),\qquad O=PV.

Softmax acts across each query’s keys. A straightforward implementation materializes SS and PP, each shaped [L,L][L,L]. For batch size BB, head count HH and ss bytes per element, one such allocation takes BHL2sBHL^2s bytes. At B=2B=2, H=8H=8, L=4096L=4096, s=4s=4, this is 1,073,741,8241,073,741,824 bytes, or 1 GiB. FP16 halves this particular allocation. If both matrices coexist, they need twice that amount; fusion and buffer reuse can change the actual peak.

This is not the model’s full footprint. Parameters, Q/K/V, other activations, outputs, temporary buffers and allocator reserve remain. Training also needs gradients and optimizer state, subject to sharding and recomputation. Removing an attention intermediate cannot guarantee that a model fits or that bandwidth is the bottleneck at every shape.

2. FlashAttention-1: Accumulate Without Saving Every Score

Online Softmax: Change the Reference Point Safely

Softmax is unchanged if the same constant is subtracted from all scores. Online normalization uses this property while processing scores in pieces [5]. For one query, let zjz_j be a scaled score and vjv_j its value vector. Maintain a maximum mm, denominator ℓ\ell and unnormalized output vector uu over processed keys. For a new tile TT,

m′=max⁡(m,max⁡j∈Tzj),a=em−m′,pj=ezj−m′,ℓ′=aℓ+∑j∈Tpj,u′=au+∑j∈Tpjvj.\begin{aligned} m'&=\max\bigl(m,\max_{j\in T}z_j\bigr), & a&=e^{m-m'},\\ p_j&=e^{z_j-m'}, & \ell'&=a\ell+\sum_{j\in T}p_j,\\ u'&=au+\sum_{j\in T}p_jv_j. && \end{aligned}

Start with m=−∞m=-\infty, ℓ=0\ell=0 and u=0u=0; the final output is u/ℓu/\ell. When a later tile raises the maximum, aa rescales both old sums into the new reference frame. Even tiles with equal denominators at their own maxima can carry different weight once they use a common reference point.

Can two tile outputs be averaged?

One query reads four scalar values, [2,2,10,10][2,2,10,10]. The first two keys have score 1000 and the last two have score 1000+ln⁡31000+\ln 3. Each later key therefore gets three times the weight of an earlier key. The full-row output is (2+2+3×10+3×10)/(1+1+3+3)=8(2+2+3\times10+3\times10)/(1+1+3+3)=8.

Put two keys in each tile. Within either tile the scores tie, so each tile has local denominator 2 if measured at its own maximum. Their local outputs are 2 and 10. An equal vote for each tile gives 6. The second tile actually carries three times the mass of the first. When it arrives, its higher score changes the reference point. Multiply the old denominator 2 and the old numerator 4 by 1/31/3 before adding the new contributions.

Partition the four keys
State after each tile (rounded to three decimal places)
KeysRescale aSum ℓSum u
1–2024
3–40.3332.66721.333
Attention output u / ℓ
8
Unweighted mean of tile outputs
6

Keep the relative weight at 3× and set the tile width to three keys. The first tile’s local output becomes 6.8 and the last tile’s is 10. Their mean rises to 8.4. The full-row output stays at 8 across both partitions.

Deliberately simplified recurrence. This CPU FP64 example handles one query and finite, unmasked scores. It already stores that one score row so that the recurrence is easy to inspect. It is not a FlashAttention GPU implementation: it omits Q/K tiling, causal/padding masks, dropout, backward recomputation, scheduling and performance measurement. A fully masked tile/row needs explicit handling and is rejected here.

import math
import torch

@torch.no_grad()
def online_attention_row(scores, values, tile_size=2):
    """Finite CPU FP64 scores [keys], values [keys, value_dim]; no mask."""
    if scores.ndim != 1 or values.ndim != 2 or len(scores) != len(values):
        raise ValueError("expected scores[keys], values[keys,value_dim]")
    if len(scores) == 0 or tile_size <= 0:
        raise ValueError("need at least one key and a positive tile size")
    if scores.device.type != "cpu" or values.device.type != "cpu":
        raise ValueError("this teaching example is CPU-only")
    if scores.dtype != torch.float64 or values.dtype != torch.float64:
        raise ValueError("use FP64 to check the recurrence")
    if not torch.isfinite(scores).all() or not torch.isfinite(values).all():
        raise ValueError("masked/nonfinite entries are outside this example")
    maximum = scores.new_tensor(float("-inf"))
    denominator = scores.new_zeros(())
    numerator = values.new_zeros(values.shape[1])
    for start in range(0, len(scores), tile_size):
        block = scores[start:start + tile_size]
        new_maximum = torch.maximum(maximum, block.max())
        correction = torch.exp(maximum - new_maximum)
        weights = torch.exp(block - new_maximum)
        denominator = correction * denominator + weights.sum()
        numerator = correction * numerator + weights @ values[start:start + tile_size]
        maximum = new_maximum
    return numerator / denominator

scores = torch.tensor([1000., 1000., 1000. + math.log(3), 1000. + math.log(3)], dtype=torch.float64)
values = torch.tensor([[2.], [2.], [10.], [10.]], dtype=torch.float64)
expected = torch.softmax(scores, dim=0) @ values
for tile_size in (1, 2, 3, 4):
    actual = online_attention_row(scores, values, tile_size)
    torch.testing.assert_close(actual, expected, rtol=1e-12, atol=1e-12)
print(expected.item())  # approximately 8.0

The common offset 1000 makes direct exponentiation overflow in FP64. Subtracting the running maximum keeps all four tile widths finite. Width three exercises a final tile containing just one key.

Recomputation and the Meaning of “Exact”

FlashAttention retains the needed inputs, outputs and row statistics, then reconstructs probability tiles during backward instead of saving the full PP [1]. This trades extra arithmetic for less HBM traffic and storage. Whether the trade wins, and by how much, depends on the workload.

“Exact attention” means that the algorithm does not approximate attention by dropping keys or replacing softmax. It does not promise bitwise equality across floating-point implementations: accumulation order and precision can change rounding. FP8 quantization introduces an additional approximation and must be evaluated separately.

3. FlashAttention-2: Keep More Compute Busy

FlashAttention-2 changes how work is divided across thread blocks and warps [2]. It uses fewer non-matrix operations, parallelizes work within a head across query blocks, and reduces shared-memory communication between warps. These changes matter when batch/head parallelism alone leaves too few blocks to occupy the GPU.

The paper reports roughly twice the kernel speed of its FlashAttention baseline and 50–73% of theoretical peak FLOPs/s in its A100 experiments. Those are measured configurations, not a promise for every sequence length, dtype or GPU. A faster attention kernel also accelerates only the attention portion of an application.

4. FlashAttention-3: Schedule Around Hopper’s Asynchrony

FlashAttention-3 uses Hopper’s asynchronous data movement and matrix operations [3]. TMA moves tiles while other work proceeds; WGMMA enables asynchronous warpgroup matrix multiplication. The schedule overlaps data transfer with compute and interleaves matrix multiplication with softmax. It aims to hide more latency, not to eliminate all I/O stalls under every condition.

Its FP8 path also uses block quantization and incoherent processing to control numerical error. Lower error than a baseline FP8 attention implementation is not proof that all downstream model capabilities are unchanged. Validate numerical agreement and task quality separately from throughput.

The following table summarizes the papers’ mechanisms; it is not a current hardware-support matrix or a cross-hardware benchmark.

PaperMain changeWhat it does not establish
FlashAttention-1 (2022) [1]Tile attention and recompute intermediates.Linear arithmetic complexity or guaranteed freedom from OOM.
FlashAttention-2 (2023) [2]Improve parallel work division and reduce non-matmul work.The same speedup for every shape and application.
FlashAttention-3 (2024) [3]Overlap Hopper operations; add a carefully scaled FP8 path.Zero low-precision error or universal task-quality preservation.

5. PyTorch SDPA: Verify That Flash Is Actually Selected

As of 2026-11-18, the PyTorch 2.15 documentation describes backend selection through sdpa_kernel [4]. Selection depends on the installed stack, GPU, dtype, shapes and attention options. Enabling Flash globally does not prove that a particular operation used it.

CUDA dispatch example; not GPU-tested in this book’s CPU smoke run. It forces the Flash backend for fixed-length causal inference in FP16/BF16. It omits variable-length padding, training gradients, dropout and performance measurement. Unsupported inputs should raise rather than silently establish a performance claim.

import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

if not torch.cuda.is_available():
    raise RuntimeError("Flash SDPA requires a supported CUDA GPU")

device = torch.device("cuda")
dtype = torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
batch, heads, sequence, head_dim = 2, 8, 2048, 64

q = torch.randn(batch, heads, sequence, head_dim, device=device, dtype=dtype)
k = torch.randn_like(q)
v = torch.randn_like(q)

with torch.inference_mode(), sdpa_kernel(backends=[SDPBackend.FLASH_ATTENTION]):
    output = F.scaled_dot_product_attention(
        q, k, v,
        dropout_p=0.0,
        is_causal=True,
    )

assert output.shape == q.shape
assert output.dtype == dtype and torch.isfinite(output).all()
print(torch.backends.cuda.flash_sdp_enabled(), output.shape, output.dtype)

The printed flash_sdp_enabled() value is a configuration flag. Use profiler/kernel evidence for the actual execution. On small tensors, compare output and, for training, gradients with the math backend at a dtype-appropriate tolerance. Record the GPU, framework/CUDA versions, input shape, mask and precision with the result.

Set dropout_p explicitly: SDPA applies the supplied probability independently of module training mode. is_causal=True does not remove padding from a variable-length batch. Use a supported combined causal/padding or variable-length representation and check backend eligibility [4].

For timing, warm up, synchronize correctly, and compare the same input/mask and precision. Measure prefill and token-by-token decode separately; their query shapes and bottlenecks differ. Record latency, throughput and peak memory for the complete workload as well as the kernel. Keep a tested fallback when the intended kernel cannot handle a configuration.

Quizzes

Quiz 1: Why is the worked score allocation 1 GiB rather than 64 MiB? 64 MiB is one FP32 4096×40964096\times4096 matrix. Batch size two and eight heads produce 16 such matrices: 16×6416\times64 MiB = 1 GiB. This counts only one intermediate, not Q/K/V or the whole model.

Quiz 2: Why must a new running maximum rescale both the denominator and numerator? In the four-key example the first tile has denominator 2 and numerator 4. After the maximum rises by ln⁡3\ln 3, its contributions are 2/32/3 and 4/34/3. Rescaling only the denominator would give (4+20)/(2/3+2)=9(4+20)/(2/3+2)=9 instead of 8.

Quiz 3: Does exact attention imply bitwise equality or no FP8 error? No. Exact describes the attention algorithm, while floating-point reduction order can change rounding. Quantizing tensors to FP8 adds representation error. Numerical tolerances and downstream evaluations address different consequences of these changes.

Quiz 4: A single FP16 score matrix at 128,000 tokens takes 32.768 GB. Does FlashAttention guarantee that the workload fits? It avoids storing that full intermediate in HBM, but parameters, Q/K/V, outputs, other activations, workspaces and training state still consume memory. Dense attention still performs quadratic pairwise work. Measure the complete workload before setting a context limit.

Quiz 5: Does flash_sdp_enabled() == True prove a measured speedup came from Flash? No. It reports whether that backend is enabled. Force the intended backend where appropriate, verify the executed kernel, and compare matched workloads. A fallback, different mask or changed dtype can invalidate the comparison.

References

  1. Dao, T., Fu, D., Ermon, S., Rudra, A., & Ré, C. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135.
  2. Dao, T. (2023). FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. arXiv:2307.08691.
  3. Shah, J., Bikshandi, G., Zhang, Y., Thakkar, V., Ramani, P., & Dao, T. (2024). FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision. arXiv:2407.08608.
  4. PyTorch. Scaled Dot Product Attention. PyTorch 2.15 documentation.
  5. Milakov, M., & Gimelshein, N. (2018). Online Normalizer Calculation for Softmax. arXiv:1805.02867.