Simple Algorithm
Deep Learning · Emergence · 28 min

FlashAttention in Depth

Tiling, the online softmax and partitioning work across a GPU.

In 2022 an attention kernel that did more arithmetic than the standard one ran several times faster, and its output was exact. The explanation is that attention's running time is set by the bytes moved between memory levels, not by its FLOPs. This lesson works that out: the GPU's memory hierarchy, the online softmax as an associative merge, the tiled algorithm, its IO complexity and the lower bounds that make it optimal, and how FlashAttention-2 and -3 split the work across a GPU, across a KV cache during decoding, and across devices.

What you’ll learn

  • Model a GPU as a small fast SRAM in front of a large slow HBM, and count the HBM traffic of standard attention.
  • Prove that the online-softmax state (m,ℓ,o~)(m,\ell,\tilde{\mathbf o}) merges associatively and commutatively, so blocks of keys can be processed in any order and in parallel.
  • Derive FlashAttention's Θ(T2d2/M)\Theta(T^2d^2/M) HBM accesses and its recomputing backward pass, and state the lower bounds that make it optimal for M≥d2M\ge d^2.
  • Explain how FlashAttention-2 and -3 partition the work and hide non-matmul costs, and how split-KV decoding and ring attention apply the same merge across a cache and across devices.

Bytes, not FLOPs

Two memories matter on a GPU. HBM, the main memory, holds tens of gigabytes. SRAM on the chip, the registers and shared memory of each streaming multiprocessor, holds a few hundred kilobytes per multiprocessor and tens of megabytes in total, with roughly ten times the bandwidth. For the A100 on which FlashAttention was developed, Dao et al. (2022) cite 40–80 GB of HBM at 1.5–2.0 TB/s against 192 KB of SRAM in each of 108 multiprocessors, with an estimated 19 TB/s. A kernel loads its inputs from HBM, computes in SRAM and registers, and writes its outputs back; an operation with few FLOPs per byte, such as a softmax, is limited by that traffic (The Roofline Model & Compute Efficiency).

Model this with two levels: a slow memory that holds everything and a fast memory of MM numbers where all arithmetic happens. The IO complexity of an algorithm is the number of values it moves between the two. Standard attention for one head, with Q,K,V∈RT×dQ,K,V\in\R^{T\times d} (in this lesson dd is the head size), runs three kernels:

text
STANDARD-ATTENTION(Q, K, V)                   // Q, K, V: T x d, in HBM
  S <- Q K^T / sqrt(d)     read 2Td,      write T^2     // kernel 1: a matrix product
  P <- softmax(S)          read T^2,      write T^2     // kernel 2: memory-bound
  O <- P V                 read T^2 + Td, write Td      // kernel 3: a matrix product
  keep P in HBM for the backward pass

Θ(Td+T2)\Theta(Td+T^2) HBM accesses per head, dominated by the T×TT\times T intermediates. Fusing the mask and the softmax into one kernel removes a pass, not the T2T^2.

MeasuredStandard attentionFlashAttention
FLOPs66.6 G75.2 G
HBM reads and writes40.3 GB4.4 GB
Runtime41.7 ms7.3 ms
Forward plus backward pass of GPT-2 medium's attention (T=1,024T=1{,}024, head size 64, 16 heads, batch 64) on one A100 (Dao et al., 2022). FlashAttention does 13% more FLOPs, because its backward pass recomputes the scores, moves 9 times fewer bytes, and runs 5.7 times faster.
Predict before you look

In 16-bit numbers, how many GiB does the T×TT\times T score matrix of a single head occupy at T=32,768T=32{,}768?

Show the answer

2 GiB

32,7682×2=23132{,}768^2\times2=2^{31} bytes =2=2 GiB, per head, per layer, per sequence: 64 GiB for the 32 heads of one layer. Standard attention writes it, reads it, writes PP, reads PP again and keeps PP for the backward pass. FlashAttention's per-row statistics for the same head take 128 KiB.

The online softmax is an associative merge

Tiling needs one fact: the softmax over a set of keys can be assembled from pieces computed over parts of the set. Milakov and Gimelshein (2018) introduced the one-pass version for a single vector, the online softmax: keep a running maximum mm and a running normalizer ℓ\ell, and for each new entry xx update ℓ←ℓ emold−mnew+ex−mnew\ell\leftarrow\ell\,e^{m_{\text{old}}-m_{\text{new}}}+e^{x-m_{\text{new}}}. That cut a numerically safe softmax from four memory accesses per element to three. Attention adds an output accumulator, and the update generalizes from one entry to a whole block.

DerivationProof: addition in disguise
  1. ψ(m,ℓ,o~)=(ℓ em, o~ em)=(∑j∈Besj, ∑j∈Besjvj)\psi(m,\ell,\tilde{\mathbf o})=\big(\ell\,e^{m},\ \tilde{\mathbf o}\,e^{m}\big)=\Big(\textstyle\sum_{j\in\mathcal B}e^{s_j},\ \sum_{j\in\mathcal B}e^{s_j}\mathbf v_j\Big)

    Map a state to the two unnormalized sums it encodes, Z=∑jesjZ=\sum_je^{s_j} and U=∑jesjvj\mathbf U=\sum_je^{s_j}\mathbf v_j:

  2. ψ(σ1⊕σ2)=(em(em1−mℓ1+em2−mℓ2), …)=(em1ℓ1+em2ℓ2, …)=ψ(σ1)+ψ(σ2)\psi(\sigma_1\oplus\sigma_2)=\Big(e^{m}\big(e^{m_1-m}\ell_1+e^{m_2-m}\ell_2\big),\ \dots\Big)=\big(e^{m_1}\ell_1+e^{m_2}\ell_2,\ \dots\big)=\psi(\sigma_1)+\psi(\sigma_2)

    Under ψ\psi the merge becomes plain addition, because each factor emi−me^{m_i-m} cancels against eme^{m}:

  3. (σ1⊕σ2)⊕σ3=σ1⊕(σ2⊕σ3)=σ(B1∪B2∪B3)(\sigma_1\oplus\sigma_2)\oplus\sigma_3=\sigma_1\oplus(\sigma_2\oplus\sigma_3)=\sigma(\mathcal B_1\cup\mathcal B_2\cup\mathcal B_3)

    So σ(B1)⊕σ(B2)\sigma(\mathcal B_1)\oplus\sigma(\mathcal B_2) and σ(B1∪B2)\sigma(\mathcal B_1\cup\mathcal B_2) encode the same sums and carry the same first coordinate, the largest score in the union. Given mm, a state is determined by its sums (ℓ=Ze−m\ell=Ze^{-m}, o~=Ue−m\tilde{\mathbf o}=\mathbf Ue^{-m}), so the two are equal. Associativity and commutativity are inherited from max⁡\max and ++:

  4. o~ℓ=∑jesjvj∑jesj=∑jsoftmax⁡(s)j vj\frac{\tilde{\mathbf o}}{\ell}=\frac{\sum_je^{s_j}\mathbf v_j}{\sum_je^{s_j}}=\sum_j\softmax(\mathbf s)_j\,\mathbf v_j

    Dividing recovers attention. The state is a floating-point representation of (Z,U)(Z,\mathbf U) with a shared exponent mm chosen from the data, which is why it stays finite where ZZ itself would overflow, for any score above about 88 in FP32:

Every later step uses associativity. Folding key blocks in from left to right gives FlashAttention's inner loop; computing them in parallel and merging along a tree gives split-KV decoding; holding them on different devices gives ring attention. For the backward pass one number per query row is enough: with L=m+log⁡ℓL=m+\log\ell, any weight Ptj=exp⁡(stj−Lt)P_{tj}=\exp(s_{tj}-L_t) can be recomputed from qt\mathbf q_t and kj\mathbf k_j alone.

Check your understanding

A query has folded in a first block of keys with scores 22 and 00, so its state has m=2m=2. The next block contains one key with score 33. Before adding the new block's terms, by what factor must the old ℓ\ell and o~\tilde{\mathbf o} be multiplied?

  1. e−1≈0.37e^{-1}\approx0.37
  2. e1≈2.72e^{1}\approx2.72
  3. 11: earlier terms never change
  4. e−3≈0.05e^{-3}\approx0.05
Show the answer

A. e−1≈0.37e^{-1}\approx0.37

The old terms were stored relative to e2e^{2} and must be re-expressed relative to the new maximum e3e^{3}: multiply by emold−mnew=e−1e^{m_{\text{old}}-m_{\text{new}}}=e^{-1}. With values 11, 00 and 22 for the three keys, the merged state gives ℓ=e−1(1+e−2)+1≈1.418\ell=e^{-1}(1+e^{-2})+1\approx1.418 and output (e−1⋅1+2)/1.418≈1.670(e^{-1}\cdot1+2)/1.418\approx1.670, the exact softmax average.

Tiling and its IO complexity

FlashAttention (Dao, Fu, Ermon, Rudra & Ré, 2022) fuses the whole computation into one kernel. Queries are cut into blocks of BrB_r rows, keys and values into blocks of BcB_c rows, small enough that a query block, a key–value block and their Br×BcB_r\times B_c tile of scores fit in SRAM together; with SRAM of MM numbers the paper takes Bc=⌈M/4d⌉B_c=\lceil M/4d\rceil and Br=min⁡(⌈M/4d⌉,d)B_r=\min(\lceil M/4d\rceil,d). For each pair of blocks the kernel forms the score tile, folds it into the query rows' states with ⊕\oplus, and moves on. The original algorithm looped over key–value blocks on the outside, re-reading and re-writing every query block's output state in HBM on each pass; FlashAttention-2 swapped the loops, an order first used in Phil Tillet's Triton implementation, so each query block's state stays on chip until it is finished (Dao, 2024):

python
import torch
import torch.nn.functional as F

def flash_forward(q, k, v, Br=64, Bc=64):
    """Exact attention for one head, block by block (FlashAttention-2 loop order). q, k, v: (T, d)."""
    T, d = q.shape
    out, lse = torch.empty_like(q), torch.empty(T)
    for i in range(0, T, Br):                       # query blocks are independent: one thread block each
        qi = q[i:i + Br] / d ** 0.5
        m = torch.full((qi.shape[0],), float('-inf'))   # running row maxima
        l = torch.zeros(qi.shape[0])                    # running sums of exp(s - m)
        acc = torch.zeros(qi.shape[0], d)               # running unnormalized outputs
        for j in range(0, T, Bc):                   # stream key/value blocks through fast memory
            s = qi @ k[j:j + Bc].T                  # a Br x Bc tile of scores, never stored in full
            m_new = torch.maximum(m, s.max(dim=1).values)
            p = torch.exp(s - m_new[:, None])
            scale = torch.exp(m - m_new)            # re-express the old state at the new maximum
            l = scale * l + p.sum(dim=1)
            acc = scale[:, None] * acc + p @ v[j:j + Bc]
            m = m_new
        out[i:i + Br] = acc / l[:, None]            # normalize once, at the end
        lse[i:i + Br] = m + torch.log(l)            # the one number per row the backward pass needs
    return out, lse

q, k, v = (torch.randn(256, 64) for _ in range(3))
o, L = flash_forward(q, k, v)
assert torch.allclose(o, F.scaled_dot_product_attention(q[None], k[None], v[None])[0], atol=1e-5)
assert torch.allclose(L, torch.logsumexp(q @ k.T / 64 ** 0.5, dim=1), atol=1e-5)

The algorithm, not the kernel: on a GPU each pass of the outer loop is a thread block and the inner loop runs out of SRAM and registers. The asserts check that the tiles reproduce PyTorch's attention and the row log-sum-exp to rounding error.

DerivationIO complexity (Dao et al., 2022)
  1. Θ(Td)⏟K,V once+TBc⋅Θ(Td)⏟one pass over Q, O=Θ(Td⋅TdM)=Θ(T2d2M)\underbrace{\Theta(Td)}_{K,V\text{ once}}+\frac{T}{B_c}\cdot\underbrace{\Theta(Td)}_{\text{one pass over }Q,\,O}=\Theta\Big(Td\cdot\frac{Td}{M}\Big)=\Theta\Big(\frac{T^2d^2}{M}\Big)

    Count HBM accesses for one head with d≤M≤Tdd\le M\le Td. A key–value block must fit, Bcd=O(M)B_cd=\order{M}, so take Bc=Θ(M/d)B_c=\Theta(M/d). In the original loop order every key and value is read once, and each of the T/BcT/B_c key–value blocks triggers one pass over all of QQ and the output state:

  2. Θ(T2)Θ(T2d2/M)=Θ(Md2)\frac{\Theta(T^2)}{\Theta(T^2d^2/M)}=\Theta\Big(\frac{M}{d^2}\Big)

    Swapping the loops exchanges the roles of the two block sizes and gives the same order; what it removes is the repeated reading and writing of the output state. Against the Θ(Td+T2)\Theta(Td+T^2) of standard attention the saving for long sequences is a factor of order M/d2M/d^2: from several to a few dozen for head sizes of 128 to 64 and on-chip memories of order 10510^5 numbers, before constant factors; the reduction measured above was ninefold.

  3. saved: O, L∈RT;recomputed per tile: Sij=QiKj⊤/d,Pij=exp⁡ ⁣(Sij−Li1⊤)\text{saved: }O,\ L\in\R^{T};\qquad\text{recomputed per tile: }S_{ij}=Q_iK_j^\top/\sqrt d,\quad P_{ij}=\exp\!\big(S_{ij}-L_i\mathbf 1^\top\big)

    The backward pass needs PP to form Sˉ=P⊙(Pˉ−D1⊤)\bar S=P\odot(\bar P-\mathbf D\mathbf 1^\top) with Dt=oˉt⋅otD_t=\bar{\mathbf o}_t\cdot\mathbf o_t (Deriving Backward Passes). FlashAttention saves only OO and the softmax statistics of each row (the original kept mm and ℓ\ell; FlashAttention-2 keeps just LL), recomputes each tile of SS and PP from blocks of QQ and KK, and pays one extra matrix product; its HBM traffic is again Θ(T2d2/M)\Theta(T^2d^2/M) against Θ(Td+T2)\Theta(Td+T^2), and its extra memory is O(T)\order{T}:

  4. Θ(Td+T2d2M s)\Theta\Big(Td+\frac{T^2d^2}{M}\,s\Big)

    A fixed block-sparse mask skips whole tiles: with a fraction ss of nonzero blocks the count becomes Θ(Td+T2d2s/M)\Theta(Td+T^2d^2s/M) (Dao et al., 2022). The causal mask is the commonest case: about half the tiles are skipped, and only those on the diagonal need an elementwise mask.

Partitioning the work: FlashAttention-2 and -3

A GPU runs a kernel as a grid of thread blocks, each scheduled on one streaming multiprocessor and made of warps of 32 threads that share the block's SRAM; tensor cores carry out small matrix products. The first FlashAttention reached only 25–40% of the A100's peak throughput (Dao, 2024). FlashAttention-2 changed three things:

  1. Fewer non-matmul FLOPs. Tensor cores multiply matrices far faster than the rest of the chip does anything else: for the A100, Dao (2024) cites 312 TFLOP/s for 16-bit matrix products against 19.5 TFLOP/s for 32-bit arithmetic outside them, so every non-matmul FLOP costs as much time as 16 matmul FLOPs. The kernel keeps the output unnormalized, divides by ℓ\ell once at the end, and saves only L=m+log⁡ℓL=m+\log\ell for the backward pass.
  2. Parallelism over the sequence. The first version gave each (sequence, head) pair one thread block, so with long sequences, small batches and few heads, many of the 108 multiprocessors sat idle. Once the loops are swapped, query blocks are independent and each becomes its own thread block. The backward pass parallelizes over key blocks instead and accumulates Qˉ\bar Q with atomic additions.
  3. Work inside a block. The first version split KK and VV across four warps, which then had to write partial outputs to shared memory and add them up ("split-K"). FlashAttention-2 splits QQ across the warps instead: each warp owns its query rows and needs nothing from the others.

Together these roughly doubled the speed, reaching up to 73% of the A100's peak in the forward pass and 225 TFLOP/s per GPU (72% model FLOPs utilization) when training GPT-style models end to end (Dao, 2024).

FlashAttention-3 (Shah, Bikshandi, Zhang, Thakkar, Ramani & Dao, 2024) targets the H100, on which FlashAttention-2 reached about 35% of peak. Its starting point is a count. Each score costs 4d4d FLOPs in the two matrix products (2d2d for q⋅k\mathbf q\cdot\mathbf k, 2d2d for adding p vp\,\mathbf v) and one exponential, computed by a separate multi-function unit whose throughput on the H100 is about 256 times lower than the tensor cores' 16-bit rate:

texp⁡tmatmul=1/Rexp⁡4d/Rmm=Rmm/Rexp⁡4d≈2564×128=12\frac{t_{\exp}}{t_{\text{matmul}}}=\frac{1/R_{\exp}}{4d/R_{\text{mm}}}=\frac{R_{\text{mm}}/R_{\exp}}{4d}\approx\frac{256}{4\times128}=\frac12
Unhidden, the exponentials of a head of size 128 would take half as long as all its matrix products. In FP8 the matmul rate doubles while the exponential rate does not, and the ratio reaches 1.

FlashAttention-3 therefore overlaps them, using the H100's asynchronous hardware:

  • Warp specialization. Producer warps issue asynchronous bulk copies from HBM to shared memory (through the Tensor Memory Accelerator); consumer warps run the matrix products, so loading the next blocks hides behind computing the current ones.
  • Ping-pong scheduling. Two groups of warps alternate, so that one group's softmax runs while the other group's matrix products occupy the tensor cores; within a group, the softmax of one block overlaps the matrix product of the next.
  • FP8 with less error. The E4M3 format keeps 3 mantissa bits, and outliers ruin a single scale per tensor. FlashAttention-3 keeps one scale per block of QQ, KK and VV, and multiplies QQ and KK by the same random orthogonal matrix RR before quantizing: (QR)(KR)⊤=QK⊤(QR)(KR)^\top=QK^\top, while each entry of QRQR mixes many entries of QQ and spreads the outliers out. RR is a Hadamard matrix times random signs, applied in O(dlog⁡d)\order{d\log d} operations (Number Formats & Mixed Precision covers the formats).

The result was 1.5–2.0 times FlashAttention-2's forward speed, up to 740 TFLOP/s (75% of peak) in FP16 and close to 1.2 PFLOP/s in FP8, with 2.6 times lower error than FP8 attention with per-tensor scaling on inputs with outliers (Shah et al., 2024).

One query, many keys: decoding and many devices

In decoding, a sequence brings one query per head, so parallelism over query blocks has nothing to split. When batch times heads is below the number of multiprocessors most of the GPU idles; at batch 1, FlashAttention used less than 1% of the GPU (Dao, Haziza, Massa & Sizov, 2023). Split-KV decoding, their Flash-Decoding, cuts the cached keys and values into chunks, lets separate thread blocks compute each chunk's partial output together with its log-sum-exp, and combines them in a second, small kernel: the ⊕\oplus of the merge theorem, applied along a tree. In the authors' benchmarks the attention kernel ran up to 50 times faster than FlashAttention at long contexts, and generation with CodeLlama-34B up to 8 times faster, at contexts up to 64K tokens.

Ring attention applies the same merge across devices (Liu, Zaharia & Abbeel, 2024). Each of nn devices holds a block of cc queries together with that block's keys and values. In each of nn rounds, every device folds the key–value block it currently holds into its queries' states, passes the block to its neighbor in a ring and receives the next one at the same time. After nn rounds every query has seen every key, the result is exact, and no device ever holds more than a few blocks, so the context that fits grows linearly with the number of devices. The communication hides behind the computation when attending to a block takes longer than sending it:

4c2dF⏟attend to one block ≥ 4cdB⏟send its K,V (16-bit)⟺c ≥ FB\underbrace{\frac{4c^2d}{F}}_{\text{attend to one block}}\ \ge\ \underbrace{\frac{4cd}{B}}_{\text{send its }K,V\ \text{(16-bit)}}\qquad\Longleftrightarrow\qquad c\ \ge\ \frac{F}{B}
FF is a device's FLOP/s, BB the link bandwidth in bytes per second, and dd here the model width. F/BF/B is a roofline ridge for the interconnect: the authors estimate blocks of about a thousand tokens per device over fast links inside a server, and tens of thousands over slower links between servers, for GPUs of the A100 generation. With a causal mask, a device holding early queries skips most blocks, so the work is unbalanced; giving each device tokens spread evenly through the sequence instead of one contiguous block evens it out (Striped Attention: Brandon et al., 2023).

Key takeaways

  • Standard attention moves Θ(Td+T2)\Theta(Td+T^2) values per head through HBM, mostly intermediates; because the softmax is memory-bound, time follows bytes. On GPT-2 medium FlashAttention did 13% more FLOPs, moved 9 times fewer bytes and ran 5.7 times faster.
  • The online-softmax state (m,ℓ,o~)(m,\ell,\tilde{\mathbf o}) encodes (∑es,∑esv)\big(\sum e^{s},\sum e^{s}\mathbf v\big) with a shared exponent; its merge is addition in disguise, hence associative, commutative and overflow-free.
  • Tiling gives Θ(T2d2/M)\Theta(T^2d^2/M) HBM accesses, optimal up to constants for M≥d2M\ge d^2 (Saha & Ye, 2024); recomputing tiles from the stored log-sum-exp keeps the backward pass at O(T)\order{T} extra memory.
  • FlashAttention-2 cut non-matmul work, parallelized over query blocks and split queries across warps; FlashAttention-3 overlaps exponentials with asynchronous matrix products and adds FP8 with block scaling and incoherent processing.
  • Split-KV decoding and ring attention apply the same merge across a cache and across devices; ring attention hides its communication when each device's block holds at least F/BF/B tokens.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

FlashAttention's backward pass performs more FLOPs than that of standard attention, yet it runs faster. Why?

  1. It runs the backward pass in 8-bit arithmetic
  2. It approximates the softmax in the backward pass
  3. Attention is limited by HBM traffic, and recomputing score tiles on chip costs less time than writing and reading T×TT\times T matrices
  4. It skips the attention weights that are close to zero
Show the answer

C. Attention is limited by HBM traffic, and recomputing score tiles on chip costs less time than writing and reading T×TT\times T matrices

The softmax and the reads and writes of SS and PP are memory-bound. Recomputing SS and PP tile by tile from QQ, KK and the stored log-sum-exp adds one matrix product of tensor-core work and removes Θ(T2)\Theta(T^2) HBM traffic: on GPT-2 medium, 13% more FLOPs and 9 times fewer bytes gave a 5.7-fold speedup.

Question 2

In split-KV decoding, eight thread blocks each compute a partial result over a different chunk of one sequence's cache. Which combination gives the exact attention output?

  1. The plain average of the eight normalized outputs
  2. The ⊕\oplus-merge of their states (m,ℓ,o~)(m,\ell,\tilde{\mathbf o}), in any order
  3. The output of the chunk with the largest maximum score
  4. Only a merge in the original left-to-right order of the chunks
Show the answer

B. The ⊕\oplus-merge of their states (m,ℓ,o~)(m,\ell,\tilde{\mathbf o}), in any order

Each state encodes the sums (∑esj,∑esjvj)\big(\sum e^{s_j},\sum e^{s_j}\mathbf v_j\big) with a shared exponent, and ⊕\oplus adds them, so it is associative and commutative. Averaging normalized outputs would weight every chunk equally instead of by its share ℓiemi\ell_ie^{m_i} of the total normalizer.

Question 3

What do the known lower bounds say about FlashAttention's Θ(T2d2/M)\Theta(T^2d^2/M) HBM accesses?

  1. Dao et al. (2022) proved it optimal separately for each SRAM size MM
  2. It is optimal up to constants whenever M≥d2M\ge d^2, even against algorithms that use fast matrix multiplication; for M<d2M<d^2 a different tiling does better
  3. Exact attention can be done with O(Td)\order{Td} accesses for any MM
  4. No lower bound is known, so much better algorithms may exist in the practical regime
Show the answer

B. It is optimal up to constants whenever M≥d2M\ge d^2, even against algorithms that use fast matrix multiplication; for M<d2M<d^2 a different tiling does better

Saha and Ye (2024) showed Θ(min⁡{T2d/M,T2d2/M})\Theta(\min\{T^2d/\sqrt M,T^2d^2/M\}) for standard matrix multiplication and extended the bound for M≥d2M\ge d^2 to fast matrix multiplication. Dao et al.'s own bound only excluded beating T2d2/MT^2d^2/M at every MM simultaneously.

Question 4

What did FlashAttention-2 gain by putting the loop over query blocks outside and the loop over key–value blocks inside?

  1. Fewer FLOPs per score
  2. The ability to skip the causal mask
  3. An approximation of the softmax that needs no maximum
  4. Each query block's running state stays on chip until it is done, and the query blocks become independent units of parallel work
Show the answer

D. Each query block's running state stays on chip until it is done, and the query blocks become independent units of parallel work

In the original order every key–value block forced a re-read and re-write of all query blocks' (O,ℓ,m)(O,\ell,m) in HBM. With queries outside, a query block is loaded once, its state lives in SRAM and registers while all keys stream past, and different query blocks can run on different multiprocessors, which matters when batch times heads is small.

Further reading

  • T. Dao, D. Y. Fu, S. Ermon, A. Rudra & C. Ré, "FlashAttention: Fast and memory-efficient exact attention with IO-awareness," NeurIPS (2022).
  • T. Dao, "FlashAttention-2: Faster attention with better parallelism and work partitioning," ICLR (2024).
  • J. Shah, G. Bikshandi, Y. Zhang, V. Thakkar, P. Ramani & T. Dao, "FlashAttention-3: Fast and accurate attention with asynchrony and low-precision," NeurIPS (2024).
  • M. Milakov & N. Gimelshein, "Online normalizer calculation for softmax," arXiv:1805.02867 (2018).
  • B. Saha & C. Ye, "I/O complexity of attention, or how optimal is FlashAttention?," ICML (2024).
  • H. Liu, M. Zaharia & P. Abbeel, "RingAttention with blockwise transformers for near-infinite context," ICLR (2024).