Algorithm Search⌘K

Algorithmresearch

FlashAttention

Also called IO-aware exact attention.

Exact attention computed in tiles that fit in fast on-chip memory with an online softmax, so the n by n score matrix is never written out.

Time
Θ(N^2 d) worst
Space
Θ(N) extra
Where
M = the size of the fast memory in numbers; N = the sequence length; d = the head size
Properties
deterministicexactofflineiterative
Origin
Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré, 2022

FlashAttention computes exactly the same output as scaled dot-product attention, softmax⁡(QK⊤/d) V\operatorname{softmax}(Q K^\top / \sqrt{d})\, V, but never stores the N×NN \times N score matrix. It cuts QQ, KK and VV into blocks small enough to fit in the fast on-chip memory of a GPU, and for each query row it keeps only a running maximum, a running sum and a running output. When a new block of keys arrives, it rescales what it has so far to the new maximum. This is the online softmax. The arithmetic stays Θ(N2d)\Theta(N^2 d), but the number of transfers to and from the slow main memory drops from Θ(Nd+N2)\Theta(N d + N^2) to Θ(N2d2/M)\Theta(N^2 d^2 / M), where MM is the size of the fast memory, and the extra memory drops from Θ(N2)\Theta(N^2) to Θ(N)\Theta(N). Attention on a GPU is usually limited by memory traffic, not by arithmetic, so this makes it faster as well as smaller.

In plain words

Plain attention first writes a huge table of scores, one for every pair of words, then reads it back to turn the scores into weights, then reads it again to mix the values. For long texts the table is too big to keep close to the processor, so most of the time goes into moving it.

FlashAttention never builds the table. It reads a small group of words, computes their scores in fast memory, uses them at once, and throws them away. To do this it keeps three running numbers per word: the highest score seen so far, a running total, and a running answer. When a higher score turns up, it shrinks the old total and answer so that everything is measured against the new highest score. At the end the answer is exactly what plain attention gives.

The problem

The input is QQ of shape N×dN \times d and KK, VV of shape N×dN \times d (more generally n×dkn \times d_k, m×dkm \times d_k and m×dvm \times d_v), stored in slow memory, and an optional causal mask. The output is O=softmax⁡(QK⊤/d+B)VO = \operatorname{softmax}(Q K^\top / \sqrt{d} + B) V in slow memory, with BB the mask bias as on the page of scaled dot-product attention.

The cost model has two levels: a slow memory of unbounded size (the GPU high-bandwidth memory, HBM) and a fast memory of MM numbers (on-chip SRAM), with d≤M≤Ndd \le M \le N d. Arithmetic happens only on data in fast memory. The cost to minimize is the number of numbers moved between the two levels, as in the external memory model with block size 1, or the red-blue pebble game. Standard attention writes S=QK⊤S = Q K^\top to slow memory, reads it to compute P=softmax⁡(S)P = \operatorname{softmax}(S), writes PP, and reads it again to compute PVP V: (n+m)dk+4nm+mdv+ndv(n + m) d_k + 4 n m + m d_v + n d_v transfers.

The algorithm

Cut the keys and values into Tc=⌈m/Bc⌉T_c = \lceil m / B_c \rceil blocks of BcB_c rows and the queries into blocks of BrB_r rows. Algorithm 1 of the paper uses Bc=⌈M/4d⌉B_c = \lceil M / 4d \rceil and Br=min⁡(⌈M/4d⌉,d)B_r = \min(\lceil M / 4d \rceil, d), so that a block of KK, a block of VV, a block of QQ, a block of OO and a Br×BcB_r \times B_c score tile fit in fast memory together. For each query row rr the slow memory holds the output row OrO_r, the running sum ℓr\ell_r and the running maximum mrm_r.

  1. FLASH-ATTENTION(Q, K, V, B_r, B_c)
  2. 1O ← 0; ℓ ← 0; m ← -∞ ▷ n × d_v, n and n numbers in slow memory
  3. 2for each block K_J, V_J of B_c keys do ▷ read into fast memory
  4. 3for each block Q_I, O_I, ℓ_I, m_I of B_r queries do ▷ read into fast memory
  5. 4S ← Q_I K_J^T / √d_k, masked entries set to -∞ ▷ B_r × B_c, in fast memory
  6. 5for each row r of the block with a finite score in S_r do
  7. 6m̃ ← max_c S_rc; p_c ← exp(S_rc - m̃); ℓ̃ ← Σ_c p_c
  8. 7m' ← max(m_r, m̃)
  9. 8ℓ' ← e^(m_r - m') ℓ_r + e^(m̃ - m') ℓ̃
  10. 9O_r ← (e^(m_r - m') ℓ_r O_r + e^(m̃ - m') Σ_c p_c V_c) / ℓ'
  11. 10m_r ← m'; ℓ_r ← ℓ' ▷ O_I, ℓ_I, m_I written back to slow memory
  12. 11return O

Lines L6 to L10 are the online softmax. Line L6 is a local softmax of the tile row, stable because m~\tilde m is its maximum. Lines L7 and L8 rescale the old sum and the new one to the common maximum m′m' and add them. Line L9 does the same for the output: ℓrOr\ell_r O_r is the unnormalized output so far, it is rescaled, the new block's unnormalized output is added, and the sum is divided by the new total. A real kernel computes lines L4 to L10 for the whole block at once with matrix products in fast memory. In the backward pass FlashAttention does not store PP either: it keeps ℓ\ell and mm and recomputes the tiles of SS and PP from QQ, KK and VV.

Example

One query, d=1d = 1, so the scale is 1: q=1q = 1, keys k=(1,3,2,0)k = (1, 3, 2, 0), so the scores are (1,3,2,0)(1, 3, 2, 0), and values v=(10,20,30,40)v = (10, 20, 30, 40). Blocks of Bc=2B_c = 2 keys.

step block scores m~\tilde m pp ℓ~\tilde\ell m′m' ℓ′\ell' OO
L1 −∞-\infty 0 0
block 1 (1, 3) 3 (0.135335, 1) 1.135335 3 1.135335 18.807971
block 2 (2, 0) 2 (1, 0.135335) 1.135335 3 1.553002 22.138557

After block 1, O=(0.135335⋅10+1⋅20)/1.135335O = (0.135335 \cdot 10 + 1 \cdot 20) / 1.135335, the attention of the query over the first two keys alone. At block 2 the maximum stays 3, so the old part keeps the factor e0=1e^0 = 1 and the new part gets e2−3=0.367879e^{2 - 3} = 0.367879: ℓ′=1.135335+0.367879⋅1.135335\ell' = 1.135335 + 0.367879 \cdot 1.135335 and O=(1.135335⋅18.807971+0.367879⋅(30+0.135335⋅40))/1.553002=22.138557O = (1.135335 \cdot 18.807971 + 0.367879 \cdot (30 + 0.135335 \cdot 40)) / 1.553002 = 22.138557. The direct computation, ∑jesjvj/∑jesj\sum_j e^{s_j} v_j / \sum_j e^{s_j}, gives the same value.

Correctness

The invariant, for each query row rr: after the key blocks 1,…,J1, \ldots, J, mrm_r is the largest visible score among those keys, ℓr=∑cesrc−mr\ell_r = \sum_c e^{s_{rc} - m_r} over them, and OrO_r is the attention output of row rr over those keys alone. Lines L7 to L10 keep it, because the old and the new parts are put on the common scale e−m′e^{-m'} before they are added. After the last block the invariant is exactly the output of attention over all keys. Every exponent at lines L6, L8 and L9 is at most 0 and one of the two factors at line L8 is 1, so in the floating-point model nothing overflows and ℓ′≥1\ell' \ge 1. The full proof gives the induction, the masked case, and the count of transfers.

Proof: FlashAttention returns softmax(Q K^T / sqrt(d_k) + B) V, takes no exponential of a positive number, and moves n (d_v + 2) + m (d_k + d_v) + T_c n (d_k + 2 d_v + 4) numbers between slow and fast memoryfull

We use the notation of the page. QQ is n×dkn \times d_k, KK is m×dkm \times d_k and VV is m×dvm \times d_v. For a query row rr and a key cc, write src=Qr⋅Kc/dks_{rc} = Q_r \cdot K_c / \sqrt{d_k} if key cc is visible to row rr and src=−∞s_{rc} = -\infty otherwise. Every row sees at least one key. The target is

Or∗=∑cesrcVc∑cesrc.O^\ast_r = \frac{\sum_c e^{s_{rc}} V_c}{\sum_c e^{s_{rc}}}.

The key blocks K1,…,KTc\mathcal{K}_1, \ldots, \mathcal{K}_{T_c} partition {1,…,m}\{1, \ldots, m\} in order. Write CJ=K1∪⋯∪KJ\mathcal{C}_J = \mathcal{K}_1 \cup \cdots \cup \mathcal{K}_J, and for a row rr let VJ(r)={c∈CJ:src>−∞}\mathcal{V}_J(r) = \{ c \in \mathcal{C}_J : s_{rc} > -\infty \}. We use e−∞=0e^{-\infty} = 0.

Invariant. After the outer loop at line L2 has handled the blocks K1,…,KJ\mathcal{K}_1, \ldots, \mathcal{K}_J, for every row rr:

  1. if VJ(r)=∅\mathcal{V}_J(r) = \emptyset, then mr=−∞m_r = -\infty, ℓr=0\ell_r = 0 and Or=0O_r = 0;
  2. otherwise mr=max⁡c∈VJ(r)srcm_r = \max_{c \in \mathcal{V}_J(r)} s_{rc}, ℓr=∑c∈CJesrc−mr\ell_r = \sum_{c \in \mathcal{C}_J} e^{s_{rc} - m_r}, and Or=1ℓr∑c∈CJesrc−mrVcO_r = \frac{1}{\ell_r} \sum_{c \in \mathcal{C}_J} e^{s_{rc} - m_r} V_c.

Initialization (J=0J = 0). C0\mathcal{C}_0 is empty, and line L1 sets mr=−∞m_r = -\infty, ℓr=0\ell_r = 0 and Or=0O_r = 0, which is case 1.

Maintenance. Assume the invariant for J−1J - 1 and look at block KJ\mathcal{K}_J. The inner loop at line L3 visits every query block once, and the rows are updated independently, so fix a row rr. Line L4 sets Src=srcS_{rc} = s_{rc} for c∈KJc \in \mathcal{K}_J.

If no key of KJ\mathcal{K}_J is visible to rr, line L5 skips the row. Then VJ(r)=VJ−1(r)\mathcal{V}_J(r) = \mathcal{V}_{J-1}(r), the new keys add e−∞=0e^{-\infty} = 0 to both sums, and the invariant for JJ is the one for J−1J - 1.

Otherwise line L6 computes m~=max⁡c∈KJsrc\tilde m = \max_{c \in \mathcal{K}_J} s_{rc}, a finite number, pc=esrc−m~p_c = e^{s_{rc} - \tilde m} and ℓ~=∑c∈KJpc≥1\tilde\ell = \sum_{c \in \mathcal{K}_J} p_c \ge 1. Line L7 sets m′=max⁡(mr,m~)m' = \max(m_r, \tilde m), which is finite and equals max⁡c∈VJ(r)src\max_{c \in \mathcal{V}_J(r)} s_{rc} in both cases of the hypothesis (in case 1, mr=−∞m_r = -\infty and m′=m~m' = \tilde m). Let a=emr−m′a = e^{m_r - m'} and b=em~−m′b = e^{\tilde m - m'}; both exponents are at most 0, so 0≤a,b≤10 \le a, b \le 1. In case 1, a=0a = 0. Line L8 gives

ℓ′=aℓr+bℓ~=∑c∈CJ−1esrc−mremr−m′+∑c∈KJesrc−m~em~−m′=∑c∈CJesrc−m′,\ell' = a \ell_r + b \tilde\ell = \sum_{c \in \mathcal{C}_{J-1}} e^{s_{rc} - m_r} e^{m_r - m'} + \sum_{c \in \mathcal{K}_J} e^{s_{rc} - \tilde m} e^{\tilde m - m'} = \sum_{c \in \mathcal{C}_J} e^{s_{rc} - m'},

where in case 1 the first sum is 0 on both sides. In the same way, using ℓrOr=∑c∈CJ−1esrc−mrVc\ell_r O_r = \sum_{c \in \mathcal{C}_{J-1}} e^{s_{rc} - m_r} V_c from the hypothesis (and 00 in case 1), line L9 gives

ℓ′Ornew=aℓrOr+b∑c∈KJpcVc=∑c∈CJesrc−m′Vc.\ell' O_r^{\text{new}} = a \ell_r O_r + b \sum_{c \in \mathcal{K}_J} p_c V_c = \sum_{c \in \mathcal{C}_J} e^{s_{rc} - m'} V_c.

The division at line L9 is defined because ℓ′≥bℓ~\ell' \ge b \tilde\ell and the term of the key that reaches m′m' is e0=1e^0 = 1, so ℓ′≥1\ell' \ge 1. Line L10 stores m′m' and ℓ′\ell', so the invariant holds for JJ in case 2.

Termination. The loops are finite. After the last block, CTc\mathcal{C}_{T_c} is all keys and VTc(r)\mathcal{V}_{T_c}(r) is not empty by the precondition, so case 2 holds:

Or=∑cesrc−mrVc∑cesrc−mr=e−mr∑cesrcVce−mr∑cesrc=Or∗.O_r = \frac{\sum_c e^{s_{rc} - m_r} V_c}{\sum_c e^{s_{rc} - m_r}} = \frac{e^{-m_r} \sum_c e^{s_{rc}} V_c}{e^{-m_r} \sum_c e^{s_{rc}}} = O^\ast_r.

So line L11 returns the attention output. □\square

No overflow. Every exponential the algorithm takes has the form ex−ye^{x - y} with yy the maximum of a set containing xx: src−m~s_{rc} - \tilde m at line L6, and mr−m′m_r - m' and m~−m′\tilde m - m' at lines L8 and L9. So every exponential is in [0,1][0, 1], and by the maintenance step ℓr≥1\ell_r \ge 1 after the first update. In the floating-point model the algorithm therefore never overflows when the scores themselves are finite. □\square

Convex updates. In case 2, line L9 writes Ornew=λOr+(1−λ)VˉO_r^{\text{new}} = \lambda O_r + (1 - \lambda) \bar V with λ=aℓr/ℓ′\lambda = a \ell_r / \ell' and Vˉ=∑c∈KJpcVc/ℓ~\bar V = \sum_{c \in \mathcal{K}_J} p_c V_c / \tilde\ell, a convex combination of the visible values of the block. Since aℓr+bℓ~=ℓ′a \ell_r + b \tilde \ell = \ell', λ∈[0,1]\lambda \in [0, 1], so each coordinate of OrO_r stays between the smallest and the largest coordinate of the visible values seen so far. □\square

Transfers. Count the numbers read from or written to slow memory, as the code does. Line L1 writes OO, ℓ\ell and mm: n(dv+2)n (d_v + 2). Over all iterations of line L2, each key and value row is read once: m(dk+dv)m (d_k + d_v). For each of the TcT_c key blocks, the inner loop reads every row of QQ, OO, ℓ\ell and mm once, n(dk+dv+2)n (d_k + d_v + 2), and line L10 writes every row of OO, ℓ\ell and mm once, n(dv+2)n (d_v + 2). The total is

n(dv+2)+m(dk+dv)+Tc n(dk+2dv+4).n (d_v + 2) + m (d_k + d_v) + T_c\, n (d_k + 2 d_v + 4).

With n=m=Nn = m = N, dk=dv=dd_k = d_v = d and Bc=⌈M/4d⌉B_c = \lceil M / 4d \rceil, Tc=⌈N/Bc⌉≤4Nd/M+1T_c = \lceil N / B_c \rceil \le 4 N d / M + 1, so the total is at most N(3d+2)+(4Nd/M+1)N(3d+4)=O(N2d2/M)N (3d + 2) + (4 N d / M + 1) N (3d + 4) = O(N^2 d^2 / M) for d≤M≤Ndd \le M \le N d, since then Nd≤N2d2/MN d \le N^2 d^2 / M. It is also at least TcN⋅3d≥(N/Bc)⋅3Nd=Ω(N2d2/M)T_c N \cdot 3d \ge (N / B_c) \cdot 3 N d = \Omega(N^2 d^2 / M) when Bc≤2M/4dB_c \le 2M / 4d, which holds for M≥4dM \ge 4d. ■\blacksquare

Complexity

  • Arithmetic. Each pair of a query and a key is handled once at lines L4 and L9, at Θ(d)\Theta(d) each, so Θ(N2d)\Theta(N^2 d), the same as standard attention (Theorem 1 of the paper).
  • Extra memory. ℓ\ell and mm take 2N2N numbers beside the output: Θ(N)\Theta(N) (Theorem 1). Standard attention stores SS and PP, Θ(N2)\Theta(N^2).
  • Transfers (theorem). KK and VV are read once, N⋅2dN \cdot 2d numbers. For each of the TcT_c key blocks, all of QQ, OO, ℓ\ell and mm are read and OO, ℓ\ell and mm written, N(3d+4)N (3d + 4) numbers. With Bc=⌈M/4d⌉B_c = \lceil M / 4d \rceil, Tc≈4Nd/MT_c \approx 4 N d / M, so the total is Θ(N2d2/M)\Theta(N^2 d^2 / M) (Theorem 2). Standard attention needs Θ(Nd+N2)\Theta(N d + N^2). For N=4096N = 4096, d=64d = 64 and M=100000M = 100000 the exact counts of the code are about 9.6 million against 68.2 million.
  • Lower bound (theorem). No exact attention algorithm has o(N2d2/M)o(N^2 d^2 / M) transfers for all MM in [d,Nd][d, N d] (Proposition 3 of the paper), so FlashAttention is optimal in this sense up to a constant.

Properties

  • Exact. It computes the same function as standard attention; in floating point the results differ only by rounding, since the sums are taken in a different order.
  • No overflow. All exponents are at most 0, as in the log-sum-exp trick.
  • Convex updates. Line L9 is a convex combination of the old output and the block's values, so OrO_r always stays inside the range of the values seen.
  • Memory linear in NN. This is what allows long sequences on a GPU.
  • Speed (measurement). Dao and colleagues report 15% faster end-to-end training of BERT-large at sequence length 512 than the MLPerf 1.1 record, 3 times faster training of GPT-2 at length 1K than the HuggingFace and Megatron-LM baselines, and 2.4 times on long-range arena at lengths 1K to 4K. These depend on the GPU and the baseline.

Variants and improvements

  • FlashAttention-2 (Dao 2023) puts the query blocks in the outer loop, so each output block is written once, divides by ℓ\ell only at the end, and splits the work over the sequence as well as over heads.
  • Memory-efficient attention (Rabe and Staats 2021) processes keys in chunks with the same running maximum, aiming at memory rather than at transfers.
  • Causal block skipping. With a causal mask, key blocks that lie entirely after a query block can be skipped without reading them, which removes about half of the work.
  • Decoding. With one query and a long key-value cache, the key blocks are split over many processors and the partial results (m,ℓ,O)(m, \ell, O) are merged at the end with the same rescaling as lines L7 to L9.
  • Block-sparse attention. Skipping blocks of a fixed sparse mask reduces transfers in proportion to the fraction of non-zero blocks.

When to use it

Use it whenever exact softmax attention runs on a GPU or another processor with a small fast memory, which today is almost always; many deep learning libraries use it when the shapes and the hardware allow. It helps most for long sequences, where the N2N^2 matrix would dominate memory and traffic. It changes nothing in the arithmetic, so when NN is too large for Θ(N2d)\Theta(N^2 d) work, use a model with linear cost, such as a selective state space model, or an approximate attention.

Pitfalls

  • Forgetting the old rescaling. Writing ℓ′←ℓr+ℓ~\ell' \leftarrow \ell_r + \tilde\ell at line L8, or adding the new block to OrO_r without the factor emr−m′e^{m_r - m'} at line L9, gives wrong weights as soon as a later block has a larger maximum. Both old terms must be multiplied by emr−m′e^{m_r - m'}.
  • Unnormalized OO. Line L9 multiplies the stored OrO_r by ℓr\ell_r before adding, because OrO_r is kept normalized. If the code keeps the unnormalized sum instead, as FlashAttention-2 does, it must not multiply by ℓr\ell_r and must divide once at the end.
  • Fully masked tiles. With a causal mask a tile row can have no visible key. Then m~=−∞\tilde m = -\infty and em~−m~e^{\tilde m - \tilde m} at line L6 is undefined. Skip such rows, as line L5 does, and start mm at −∞-\infty with ℓ=0\ell = 0, so that e−∞=0e^{-\infty} = 0 removes the empty start at the first real update.
  • Comparing to the wrong reference. Low-precision results differ from a float32 reference by rounding; compare with a tolerance, not for equality.

Implementations

The code takes QQ, KK and VV as given and does not train a network. It also returns the number of slow-memory transfers under the two-level model of the paper.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

flashattention.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flashattention/. The authors are listed in prov/5X6J97.jsonl.

"""FlashAttention: exact attention by blocks with an online softmax (Dao, Fu, Ermon, Rudra and Re 2022).

Shapes, with named sizes:
    Q is n x d_k, K is m x d_k, V is m x d_v.
The output is softmax(Q K^T / sqrt(d_k)) V, the same as plain attention up to
rounding. The keys are cut into T_c = ceil(m / B_c) blocks of at most B_c rows
and the queries into ceil(n / B_r) blocks of at most B_r rows. As in
Algorithm 1 of the paper, the outer loop is over key blocks and the inner
loop over query blocks; for each query row the slow memory keeps the output
row O_r, the running sum l_r and the running maximum m_r.

The function also counts the numbers moved between slow memory (HBM) and fast
memory (SRAM), under the model of the paper: every block is read from slow
memory when it is used, and O, l and m are written back after each update.

With causal=True, query i sees key j when j <= i + (m - n). A query row whose
block holds no visible key is not updated by that block.

Precondition: n, m, d_k, d_v, B_r, B_c >= 1, the shapes agree, and every
query sees at least one key.

Cost: Theta(n m (d_k + d_v)) operations, the same as plain attention.
Fast memory Theta(B_c (d_k + d_v) + B_r (d_k + d_v) + B_r B_c). Extra slow
memory Theta(n) for l and m beside the output. The number of slow-memory
transfers is io_count(n, m, d_k, d_v, B_c), which is Theta(n m d^2 / M) with
the block sizes of block_sizes(M, d).

The code takes Q, K and V as given. It does not train a network.
"""

import math
from typing import List, Sequence, Tuple

Matrix = List[List[float]]
NEG_INF = float("-inf")


def io_count(n: int, m: int, d_k: int, d_v: int, B_c: int) -> int:
    """Slow-memory transfers of flash_attention: init, K and V once, and per key block Q, O, l, m read and O, l, m written."""
    T_c = -(-m // B_c)
    return n * (d_v + 2) + m * (d_k + d_v) + T_c * n * (d_k + 2 * d_v + 4)


def standard_attention_io(n: int, m: int, d_k: int, d_v: int) -> int:
    """Slow-memory transfers of plain attention that writes S and P: read Q, K; write S; read S, write P; read P, V; write O."""
    return (n + m) * d_k + 4 * n * m + m * d_v + n * d_v


def block_sizes(M: int, d: int) -> Tuple[int, int]:
    """The block sizes (B_r, B_c) of Algorithm 1 for a fast memory of M numbers: B_c = ceil(M / 4d), B_r = min(B_c, d)."""
    if M < 1 or d < 1:
        raise ValueError("M and d must be positive")
    B_c = -(-M // (4 * d))
    return min(B_c, d), B_c


def flash_attention(
    Q: Sequence[Sequence[float]],
    K: Sequence[Sequence[float]],
    V: Sequence[Sequence[float]],
    B_r: int,
    B_c: int,
    causal: bool = False,
) -> Tuple[Matrix, int]:
    """Return (O, io): the n x d_v attention output and the number of slow-memory transfers."""
    n, m = len(Q), len(K)
    if n == 0 or m == 0 or len(V) != m:
        raise ValueError("Q and K must be non-empty and K and V must have the same number of rows")
    d_k, d_v = len(K[0]), len(V[0])
    if d_k == 0 or d_v == 0 or any(len(r) != d_k for r in Q) or any(len(r) != d_k for r in K):
        raise ValueError("the rows of Q and K must have the same positive length")
    if any(len(r) != d_v for r in V):
        raise ValueError("the rows of V must have the same length")
    if B_r < 1 or B_c < 1:
        raise ValueError("the block sizes must be positive")
    if causal and m < n:
        raise ValueError("a causal mask needs at least as many keys as queries")
    scale = 1.0 / math.sqrt(d_k)
    shift = m - n

    O = [[0.0] * d_v for _ in range(n)]  # @line L1
    ell = [0.0] * n  # @line L1
    mx = [NEG_INF] * n  # @line L1
    io = n * (d_v + 2)

    for j0 in range(0, m, B_c):  # @line L2
        cols = range(j0, min(j0 + B_c, m))
        io += len(cols) * (d_k + d_v)
        for i0 in range(0, n, B_r):  # @line L3
            rows = range(i0, min(i0 + B_r, n))
            io += len(rows) * (d_k + d_v + 2)
            for r in rows:
                S = [
                    math.fsum(Q[r][t] * K[c][t] for t in range(d_k)) * scale if not (causal and c > r + shift) else NEG_INF
                    for c in cols
                ]  # @line L4
                m_tilde = max(S)
                if m_tilde == NEG_INF:  # @line L5
                    continue
                p = [math.exp(s - m_tilde) for s in S]  # @line L6
                ell_tilde = math.fsum(p)  # @line L6
                m_new = max(mx[r], m_tilde)  # @line L7
                a = math.exp(mx[r] - m_new)  # 0 when mx[r] is -inf
                b = math.exp(m_tilde - m_new)
                ell_new = a * ell[r] + b * ell_tilde  # @line L8
                O[r] = [
                    (a * ell[r] * O[r][c] + b * math.fsum(p[k] * V[col][c] for k, col in enumerate(cols))) / ell_new
                    for c in range(d_v)
                ]  # @line L9
                mx[r], ell[r] = m_new, ell_new  # @line L10
            io += len(rows) * (d_v + 2)

    for r in range(n):
        if mx[r] == NEG_INF:
            raise ValueError(f"query {r} sees no key")
    return O, io  # @line L11
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Log-space arithmetic and semirings for the natural-language-and-speech pages.

Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.

The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:

    PROB      probabilities         plus = +        times = *   zero = 0       one = 1
    LOG       log probabilities     plus = log_add  times = +   zero = -inf    one = 0
    VITERBI   log probabilities     plus = max      times = +   zero = -inf    one = 0
    TROPICAL  costs -log p          plus = min      times = +   zero = +inf    one = 0
    LOG_COST  costs -log p          plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
    BOOLEAN   truth values          plus = or       times = and zero = False   one = True
    COUNTING  path counts           plus = +        times = *   zero = 0       one = 1

This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""

import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence

NEG_INF = float("-inf")
POS_INF = float("inf")


def safe_log(p) -> float:
    """Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
    if p < 0:
        raise ValueError("log of a negative number")
    if p == 0:
        return NEG_INF
    return math.log(p)


def log_add(a: float, b: float) -> float:
    """Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).

    log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
    """
    if a < b:
        a, b = b, a
    if b == NEG_INF or a == POS_INF:
        return a
    return a + math.log1p(math.exp(b - a))


def log_sum(xs: Iterable[float]) -> float:
    """Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
    xs = list(xs)
    if not xs:
        return NEG_INF
    m = max(xs)
    if m == NEG_INF or m == POS_INF:
        return m
    return m + math.log(math.fsum(math.exp(x - m) for x in xs))


def log_normalize(xs: Sequence[float]) -> List[float]:
    """Return the list x - log_sum(xs): log values whose exps sum to 1.

    Raise ValueError if every value is NEG_INF (nothing to normalize).
    """
    z = log_sum(xs)
    if z == NEG_INF:
        raise ValueError("every weight is zero")
    return [x - z for x in xs]


def log_softmax(xs: Sequence[float]) -> List[float]:
    """Return log softmax(xs): the logits xs turned into log probabilities."""
    return log_normalize(xs)


def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
    """Return the probabilities exp(x / temperature) / sum, computed stably.

    The temperature must be positive. Logits of NEG_INF get probability 0.
    """
    if not temperature > 0:
        raise ValueError("the temperature must be positive")
    m = max(xs)
    if m == NEG_INF:
        raise ValueError("every logit is -inf")
    es = [math.exp((x - m) / temperature) for x in xs]
    s = math.fsum(es)
    return [e / s for e in es]


def argmax(xs: Sequence[Any]) -> int:
    """Return the first index of a largest value. Raise ValueError if xs is empty."""
    if len(xs) == 0:
        raise ValueError("argmax of an empty sequence")
    best = 0
    for i in range(1, len(xs)):
        if xs[i] > xs[best]:
            best = i
    return best


@dataclass(frozen=True)
class Semiring:
    """A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""

    name: str
    plus: Callable[[Any, Any], Any]
    times: Callable[[Any, Any], Any]
    zero: Any
    one: Any
    idempotent: bool


def _add(a, b):
    return a + b


def _mul(a, b):
    return a * b


def _log_add_cost(a: float, b: float) -> float:
    return -log_add(-a, -b)


PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)


def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring sum of xs, and sr.zero for an empty input."""
    acc = sr.zero
    for x in xs:
        acc = sr.plus(acc, x)
    return acc


def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
    """Return the semiring product of xs, and sr.one for an empty input."""
    acc = sr.one
    for x in xs:
        acc = sr.times(acc, x)
    return acc
test_flashattention.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flashattention/. The authors are listed in prov/5X6J97.jsonl.

import math
import random

import pytest

from flashattention import block_sizes, flash_attention, io_count, standard_attention_io
from nlslog import softmax


def rand_matrix(rng, rows, cols, scale=1.0):
    return [[rng.gauss(0.0, scale) for _ in range(cols)] for _ in range(rows)]


def plain_attention(Q, K, V, causal=False):
    """The definition, with the whole row of scores at once and the shared softmax helper."""
    n, m, dk = len(Q), len(K), len(K[0])
    out = []
    for i in range(n):
        js = [j for j in range(m) if not (causal and j > i + m - n)]
        p = softmax([sum(a * b for a, b in zip(Q[i], K[j])) / math.sqrt(dk) for j in js])
        out.append([sum(p[t] * V[j][c] for t, j in enumerate(js)) for c in range(len(V[0]))])
    return out


def close(A, B, tol=1e-9):
    return len(A) == len(B) and all(abs(a - b) <= tol * (1 + abs(b)) for ra, rb in zip(A, B) for a, b in zip(ra, rb))


def test_worked_example():
    Q, K, V = [[1.0]], [[1.0], [3.0], [2.0], [0.0]], [[10.0], [20.0], [30.0], [40.0]]
    O1, _ = flash_attention(Q, K[:2], V[:2], 1, 2)
    assert round(O1[0][0], 4) == 18.808
    O, _ = flash_attention(Q, K, V, 1, 2)
    assert round(O[0][0], 6) == 22.138557
    assert close(O, plain_attention(Q, K, V))


@pytest.mark.parametrize("seed", range(25))
def test_matches_plain_attention(seed):
    rng = random.Random(seed)
    n, m = rng.randint(1, 9), rng.randint(1, 9)
    dk, dv = rng.randint(1, 4), rng.randint(1, 3)
    Q, K, V = rand_matrix(rng, n, dk, 2.0), rand_matrix(rng, m, dk, 2.0), rand_matrix(rng, m, dv)
    B_r, B_c = rng.randint(1, 4), rng.randint(1, 4)
    O, io = flash_attention(Q, K, V, B_r, B_c)
    assert close(O, plain_attention(Q, K, V))
    assert io == io_count(n, m, dk, dv, B_c)
    if m >= n:
        Oc, _ = flash_attention(Q, K, V, B_r, B_c, causal=True)
        assert close(Oc, plain_attention(Q, K, V, causal=True))


@pytest.mark.parametrize("B_r,B_c", [(1, 1), (2, 3), (5, 5), (8, 8), (3, 7)])
def test_block_sizes_do_not_change_the_result(B_r, B_c):
    rng = random.Random(42)
    Q, K, V = rand_matrix(rng, 7, 3), rand_matrix(rng, 7, 3), rand_matrix(rng, 7, 2)
    O, _ = flash_attention(Q, K, V, B_r, B_c, causal=True)
    assert close(O, plain_attention(Q, K, V, causal=True))


def test_large_scores_do_not_overflow():
    Q = [[30.0, 30.0]]
    K = [[-30.0, -30.0], [30.0, 30.0], [29.0, 29.0], [30.0, 29.5]]
    V = [[1.0], [2.0], [3.0], [4.0]]
    O, _ = flash_attention(Q, K, V, 1, 1)
    assert all(math.isfinite(x) for x in O[0])
    assert close(O, plain_attention(Q, K, V))


def test_io_formula_and_its_growth():
    d = 4
    n = 48
    rng = random.Random(3)
    Q, K, V = rand_matrix(rng, n, d), rand_matrix(rng, n, d), rand_matrix(rng, n, d)
    ios = []
    for M in (64, 128, 256, 512):
        B_r, B_c = block_sizes(M, d)
        _, io = flash_attention(Q, K, V, B_r, B_c)
        assert io == io_count(n, n, d, d, B_c)
        ios.append(io)
    assert ios == sorted(ios, reverse=True)
    # With B_c = M / 4d there are T_c = 4 n d / M key blocks, each moving n (3d + 4) numbers,
    # so the leading term is 12 n^2 d^2 / M, plus 16 n^2 d / M for l and m.
    M = 128
    _, B_c = block_sizes(M, d)
    assert B_c == M // (4 * d) and n % B_c == 0
    T_c = 4 * n * d // M
    assert io_count(n, n, d, d, B_c) == 12 * n * n * d * d // M + 4 * n * T_c + n * (d + 2) + 2 * n * d
    # Fewer transfers than plain attention once M is large compared with d^2.
    assert io_count(n, n, d, d, block_sizes(512, d)[1]) < standard_attention_io(n, n, d, d)


def test_block_sizes():
    assert block_sizes(100_000, 64) == (64, 391)
    assert block_sizes(64, 4) == (4, 4)
    with pytest.raises(ValueError):
        block_sizes(0, 4)


def test_errors():
    with pytest.raises(ValueError):
        flash_attention([[1.0]], [[1.0]], [[1.0]], 0, 1)
    with pytest.raises(ValueError):
        flash_attention([[1.0], [1.0]], [[1.0]], [[1.0]], 1, 1, causal=True)
    with pytest.raises(ValueError):
        flash_attention([[1.0, 2.0]], [[1.0]], [[1.0]], 1, 1)

History

Milakov and Gimelshein (2018) showed that the softmax normalizer can be computed in one pass with a running maximum. Rabe and Staats (2021) used this to compute attention in chunks with little memory. Dao, Fu, Ermon, Rudra and Ré (2022) counted the transfers between GPU memory levels, as Hong and Kung had done for other computations with the red-blue pebble game, proved matching upper and lower bounds, and wrote a fused GPU kernel for the forward and backward passes. FlashAttention-2 (2023) and later versions improved the use of the hardware.

References

  1. Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra and Christopher Ré, FlashAttention: fast and memory-efficient exact attention with IO-awareness, Advances in Neural Information Processing Systems 35 (NeurIPS 2022), arXiv:2205.14135, Section 3.1 and Algorithm 1 (tiling, the online softmax, the block sizes), Theorem 1 (correctness, O(N^2 d) FLOPs, O(N) extra memory), Theorem 2 (HBM accesses of standard attention and of FlashAttention), Proposition 3 (the lower bound), Section 4 (measured speed-ups)
  2. Milakov and Gimelshein 2018, the one-pass softmax that keeps a running maximum and a running sum
  3. Rabe and Staats 2021, attention by chunks of keys with a running maximum, in O(log n) or O(sqrt n) memory
  4. Dao 2023, the swapped loop order, the deferred division by the running sum, and parallelism over the sequence

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example