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
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré, 2022
FlashAttention computes exactly the same output as scaled dot-product attention, , but never stores the score matrix. It cuts , and 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 , but the number of transfers to and from the slow main memory drops from to , where is the size of the fast memory, and the extra memory drops from to . 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 of shape and , of shape (more generally , and ), stored in slow memory, and an optional causal mask. The output is in slow memory, with 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 numbers (on-chip SRAM), with . 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 to slow memory, reads it to compute , writes , and reads it again to compute : transfers.
The algorithm
Cut the keys and values into blocks of rows and the queries into blocks of rows. Algorithm 1 of the paper uses and , so that a block of , a block of , a block of , a block of and a score tile fit in fast memory together. For each query row the slow memory holds the output row , the running sum and the running maximum .
FLASH-ATTENTION(Q, K, V, B_r, B_c)- 1
O ← 0; ℓ ← 0; m ← -∞ ▷ n × d_v, n and n numbers in slow memory - 2
for each block K_J, V_J of B_c keys do ▷ read into fast memory - 3
for each block Q_I, O_I, ℓ_I, m_I of B_r queries do ▷ read into fast memory - 4
S ← Q_I K_J^T / √d_k, masked entries set to -∞ ▷ B_r × B_c, in fast memory - 5
for each row r of the block with a finite score in S_r do - 6
m̃ ← max_c S_rc; p_c ← exp(S_rc - m̃); ℓ̃ ← Σ_c p_c - 7
m' ← max(m_r, m̃) - 8
ℓ' ← e^(m_r - m') ℓ_r + e^(m̃ - m') ℓ̃ - 9
O_r ← (e^(m_r - m') ℓ_r O_r + e^(m̃ - m') Σ_c p_c V_c) / ℓ' - 10
m_r ← m'; ℓ_r ← ℓ' ▷ O_I, ℓ_I, m_I written back to slow memory - 11
return O
Lines L6 to L10 are the online softmax. Line L6 is a local softmax of the tile row, stable because is its maximum. Lines L7 and L8 rescale the old sum and the new one to the common maximum and add them. Line L9 does the same for the output: 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 either: it keeps and and recomputes the tiles of and from , and .
Example
One query, , so the scale is 1: , keys , so the scores are , and values . Blocks of keys.
| step | block scores | ||||||
|---|---|---|---|---|---|---|---|
| L1 | 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, , 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 and the new part gets : and . The direct computation, , gives the same value.
Correctness
The invariant, for each query row : after the key blocks , is the largest visible score among those keys, over them, and is the attention output of row over those keys alone. Lines L7 to L10 keep it, because the old and the new parts are put on the common scale 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 . 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. is , is and is . For a query row and a key , write if key is visible to row and otherwise. Every row sees at least one key. The target is
The key blocks partition in order. Write , and for a row let . We use .
Invariant. After the outer loop at line L2 has handled the blocks , for every row :
- if , then , and ;
- otherwise , , and .
Initialization (). is empty, and line L1 sets , and , which is case 1.
Maintenance. Assume the invariant for and look at block . The inner loop at line L3 visits every query block once, and the rows are updated independently, so fix a row . Line L4 sets for .
If no key of is visible to , line L5 skips the row. Then , the new keys add to both sums, and the invariant for is the one for .
Otherwise line L6 computes , a finite number, and . Line L7 sets , which is finite and equals in both cases of the hypothesis (in case 1, and ). Let and ; both exponents are at most 0, so . In case 1, . Line L8 gives
where in case 1 the first sum is 0 on both sides. In the same way, using from the hypothesis (and in case 1), line L9 gives
The division at line L9 is defined because and the term of the key that reaches is , so . Line L10 stores and , so the invariant holds for in case 2.
Termination. The loops are finite. After the last block, is all keys and is not empty by the precondition, so case 2 holds:
So line L11 returns the attention output.
No overflow. Every exponential the algorithm takes has the form with the maximum of a set containing : at line L6, and and at lines L8 and L9. So every exponential is in , and by the maintenance step after the first update. In the floating-point model the algorithm therefore never overflows when the scores themselves are finite.
Convex updates. In case 2, line L9 writes with and , a convex combination of the visible values of the block. Since , , so each coordinate of stays between the smallest and the largest coordinate of the visible values seen so far.
Transfers. Count the numbers read from or written to slow memory, as the code does. Line L1 writes , and : . Over all iterations of line L2, each key and value row is read once: . For each of the key blocks, the inner loop reads every row of , , and once, , and line L10 writes every row of , and once, . The total is
With , and , , so the total is at most for , since then . It is also at least when , which holds for .
Complexity
- Arithmetic. Each pair of a query and a key is handled once at lines L4 and L9, at each, so , the same as standard attention (Theorem 1 of the paper).
- Extra memory. and take numbers beside the output: (Theorem 1). Standard attention stores and , .
- Transfers (theorem). and are read once, numbers. For each of the key blocks, all of , , and are read and , and written, numbers. With , , so the total is (Theorem 2). Standard attention needs . For , and the exact counts of the code are about 9.6 million against 68.2 million.
- Lower bound (theorem). No exact attention algorithm has transfers for all in (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 always stays inside the range of the values seen.
- Memory linear in . 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 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 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 matrix would dominate memory and traffic. It changes nothing in the arithmetic, so when is too large for work, use a model with linear cost, such as a selective state space model, or an approximate attention.
Pitfalls
- Forgetting the old rescaling. Writing at line L8, or adding the new block to without the factor at line L9, gives wrong weights as soon as a later block has a larger maximum. Both old terms must be multiplied by .
- Unnormalized . Line L9 multiplies the stored by before adding, because is kept normalized. If the code keeps the unnormalized sum instead, as FlashAttention-2 does, it must not multiply by and must divide once at the end.
- Fully masked tiles. With a causal mask a tile row can have no visible key. Then and at line L6 is undefined. Skip such rows, as line L5 does, and start at with , so that 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 , and 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.
# 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
- 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)
- Milakov and Gimelshein 2018, the one-pass softmax that keeps a running maximum and a running sum
- Rabe and Staats 2021, attention by chunks of keys with a running maximum, in O(log n) or O(sqrt n) memory
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5X6J97 Edit this page History Report an error Markdown