Inference Engineering

Lesson 9: FlashAttention · Workbook

FlashAttention: the workbook

The full working behind lesson 9. Standard attention's memory traffic, online softmax, tiling and its byte counts, why the answer is exact, FlashAttention-2 and -3, Flash-Decoding, and seven exercises to check yourself.

A transformer’s attention layer compares every token with every other token. For a sequence of NN tokens, that is an N×NN \times N table of scores per head. The straightforward implementation writes that table to the GPU’s main memory (HBM), reads it back to apply a softmax, writes the result, and reads it back again to multiply by the values. At 8,192 tokens, one head’s table alone is 134 MB in BF16.

FlashAttention (Dao et al., 2022) computes exactly the same output, to the last few bits of rounding, without ever storing that table. It cuts the sequence into blocks small enough to fit in the fast on-chip memory of one streaming multiprocessor, finishes all the work on each block there, and keeps only a few running numbers per row. This lesson builds the softmax trick that makes this possible, counts the bytes it saves, and follows the idea through FlashAttention-2, FlashAttention-3 and Flash-Decoding.

What standard attention does

For one head, the inputs are three matrices QQ, KK and VV, each N×dN \times d: one row per token, with dd the head dimension (128 in Llama 3.1 8B). The output is

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

with the softmax applied to each row of SS, and SS scaled by 1/d1/\sqrt{d} first. SS and PP are N×NN \times N. OO is N×dN \times d, the same size as the inputs.

The FlashAttention paper writes the standard implementation as three steps (its Algorithm 0), each a separate GPU kernel that starts and ends in HBM:

  1. Read QQ and KK, compute SS, write SS.
  2. Read SS, compute PP, write PP.
  3. Read PP and VV, compute OO, write OO.

Count the elements that cross the memory bus. The four N×dN \times d matrices contribute 4Nd4Nd. The two N×NN \times N matrices are each written once and read once, which adds 4N24N^2:

standard HBM traffic=4Nd+4N2 elements.\htmlClass{c-memory}{\text{standard HBM traffic} = 4Nd + 4N^2 \text{ elements}} .

When NN is much larger than dd, the N2N^2 term is almost all of it. For one head of Llama 3.1 8B at 8,192 tokens in BF16 (2 bytes per element), the total is 545 MB, of which 537 MB is spent writing and reading SS and PP. The arithmetic, two matrix multiplies of 2N2d2N^2d FLOPs each, is 34.4 GFLOP.

Put those on the roofline from lesson 1. The intensity is 63 FLOPs per byte, far below the H100’s ridge of 295. On an H100 the memory floor is 163 µs against 34.7 µs of compute. Standard attention is memory-bound, and its traffic is dominated by a matrix that is only an intermediate result. Growing NN does not help: both the FLOPs and the dominant bytes grow as N2N^2, so the intensity stays near 4N2d/(4N2×2)=d/24N^2 d / (4N^2 \times 2) = d/2 FLOPs per byte (64 for d = 128), however long the sequence.

There is a second cost. SS and PP must exist somewhere while the kernels run. For all 32 query heads of one layer at 8,192 tokens, SS alone is 4.29 GB. That memory competes with the KV cache (lesson 4) and the batch (lesson 6).

The obstacle: softmax needs the whole row

A GPU has two kinds of memory that matter here. HBM is large (80 GB on an H100) and comparatively slow. Each streaming multiprocessor (SM), one of the GPU’s many independent cores, also has a small, much faster on-chip memory called shared memory or SRAM: 228 KiB per SM on an H100, according to the FlashAttention-3 paper. The FlashAttention paper puts on-chip SRAM bandwidth roughly an order of magnitude above HBM’s.

The goal is to fuse the three steps into one kernel that loads a block of QQ, KK and VV into SRAM, does all the work there, and writes only OO. The matrix multiplies split into blocks easily. Softmax does not. For a row of scores s1,…,sNs_1, \dots, s_N, the numerically safe softmax is

pj=esj−mℓ,m=max⁡ksk,ℓ=∑kesk−m.p_j = \frac{e^{s_j - m}}{\ell}, \qquad m = \max_k s_k, \qquad \ell = \sum_k e^{s_k - m} .

Subtracting the maximum mm keeps the exponentials from overflowing. But both mm and ℓ\ell depend on every score in the row, and the row is NN long. It seems you must see the whole row before you can produce any probability.

Online softmax: fix it up as you go

The way out is to keep a running max and a running sum, and correct old work whenever the max changes. Milakov and Gimelshein (2018) published this “online normalizer” for softmax alone. FlashAttention applies it to attention.

Read the row one chunk at a time. Keep mm, the largest score seen so far, and ℓ\ell, the sum of es−me^{s - m} over the scores seen so far. When a new chunk arrives with scores sjs_j:

mnew=max⁡ ⁣(m, max⁡jsj),ℓnew=e m−mnew ℓ  +  ∑je sj−mnew.m_{\text{new}} = \max\!\left(m,\ \max_j s_j\right), \qquad \ell_{\text{new}} = e^{\,m - m_{\text{new}}}\,\ell \;+\; \sum_j e^{\,s_j - m_{\text{new}}} .

The factor em−mnewe^{m - m_{\text{new}}} is the correction. Every term already in ℓ\ell was computed as es−me^{s - m}, and multiplying by em−mnewe^{m - m_{\text{new}}} turns each one into es−mnewe^{s - m_{\text{new}}}, as if the new max had been known from the start. If the max did not change, the factor is 1.

A small example. Take the row [2,5,1,3][2, 5, 1, 3] in chunks of two. After [2,5][2, 5], the max mm is 5 and ℓ=e−3+e0\ell = e^{-3} + e^{0}, which is 1.0498. After [1,3][1, 3] the max stays 5, so no correction is needed and ℓ\ell becomes 1.2034. The probability of the score 5 is 1/ℓ1/\ell, or 0.8310, the same as a one-pass softmax gives (0.8310).

Attention needs one more running quantity: the output itself. For one query row, keep an accumulator oo, a vector of length dd, holding ∑esj−m vj\sum e^{s_j - m}\, v_j over the keys seen so far. It gets the same correction:

onew=e m−mnew o  +  ∑je sj−mnew vj,output=ofinalℓfinal.o_{\text{new}} = e^{\,m - m_{\text{new}}}\, o \;+\; \sum_j e^{\,s_j - m_{\text{new}}}\, v_j , \qquad \text{output} = \frac{o_{\text{final}}}{\ell_{\text{final}}} .

That is the whole algorithm for one row. Per row, the state is two numbers and one vector of length dd, no matter how long the sequence is. Dividing by ℓ\ell once at the end, rather than after every block, is one of FlashAttention-2’s changes; the original rescaled the normalized output each time.

Tiling: one block of work at a time

Now apply this to blocks of rows. Split QQ into blocks of BB rows and KK, VV into blocks of BB rows. (The paper lets the query and key block sizes differ, as the next section shows; the toy uses square blocks for simplicity.) A tile is one query block against one key block: a B×BB \times B piece of SS that is computed in SRAM, used to update the running state of those BB query rows, and thrown away.

The walkthrough below runs this on a toy head with 16 tokens and head dimension 4, using FlashAttention-2’s loop order: for each query block, sweep across all key blocks. Shaded tiles are parts of SS that have been computed and discarded, never stored. The side panel follows one query row’s mm, ℓ\ell and output, which land on the exact answer after the last key block. The teal bars count elements moved to and from HBM.

The table, one tile at a time

Numbers moved to and from GPU memory

The obvious way1,280
Flash, so far0

Row 7: its sticky note

highest score m–
running total l–
answer so far–
exact answer–

One head with 16 tokens and head dimension 4, seeded random inputs. Standard attention's traffic is fixed by the formula 4Nd + 4N². FlashAttention's grows tile by tile: Q and O move once per query block, and K and V are re-read once per query block. Change the block size to see the trade: bigger blocks need more SRAM and re-read K and V fewer times.

With 4-row blocks, the toy moves 640 elements instead of 1,280, and 1,024 of standard attention’s elements were nothing but SS and PP going out and coming back. The flash count follows directly from the loop: QQ is read once and OO written once (2Nd2Nd), and all of KK and VV (2Nd2Nd) is read once for each of the T=⌈N/B⌉T = \lceil N/B \rceil query blocks:

FlashAttention-2 order: 2Nd+T⋅2Nd elements.\htmlClass{c-memory}{\text{FlashAttention-2 order: } 2Nd + T \cdot 2Nd \text{ elements}} .

How much traffic it saves

The block sizes are set by SRAM. For an SRAM of MM elements, line 1 of the paper’s Algorithm 1 sets the key/value block size to Bc=⌈M/4d⌉B_c = \lceil M / 4d \rceil, so that blocks of QQ, KK, VV and OO fit together, and caps the query block at Br=min⁡(⌈M/4d⌉,d)B_r = \min(\lceil M / 4d \rceil, d), so that the Br×BcB_r \times B_c tile of scores fits on chip as well. Real kernels tune these sizes; the FlashAttention-2 paper says it typically uses blocks of 64 or 128 on each side. Theorem 2 of the paper states the result: for SRAM size MM between dd and NdNd, standard attention needs Θ(Nd+N2)\Theta(Nd + N^2) HBM accesses and FlashAttention needs

Θ ⁣(N2d2M).\Theta\!\left(\frac{N^2 d^2}{M}\right).

Both are still quadratic in NN. What changes is the constant. Algorithm 1 makes Tc=⌈N/Bc⌉T_c = \lceil N / B_c \rceil passes over the queries, each moving about 3Nd3Nd elements, so about 3N2d/Bc3N^2 d / B_c in all. Substituting Bc=M/4dB_c = M/4d gives 12N2d2/M12 N^2 d^2 / M, which is Theorem 2’s form. Standard attention moves about 4N24N^2, so the saving is about M/(3d2)M / (3d^2): it grows with SRAM and shrinks quickly as the head dimension grows. For the H100 example below, M/d2M/d^2 is about 7.1, so the saving is about 2.3×. With d=64d = 64 on the same SRAM it is about 9×, the same order as the roughly 9× drop in traffic the paper measured for GPT-2 (also d=64d = 64), described below. The paper also proves that no exact attention algorithm can do asymptotically better across all SRAM sizes (its Proposition 3).

Back to one head of Llama 3.1 8B at 8,192 tokens on an H100. With 228 KiB of SRAM, MM is 228 × 1,024 / 2 = 116,736 BF16 elements, so BcB_c = ⌈116,736 / (4 × 128)⌉ = 228 rows. (That it equals the 228 in 228 KiB is a coincidence of d = 128 and 2-byte elements.) The query block is capped at BrB_r = 128. Algorithm 1 re-reads QQ and OO once per key block, 36 times; FlashAttention-2’s order re-reads KK and VV once per query block, 64 times:

ImplementationHBM trafficMemory floorIntensity (FLOPs/byte)
Standard (Algorithm 0)545 MB163 µs63
FlashAttention, original loop order (Algorithm 1)235 MB70.2 µs146
FlashAttention-2 loop order, query blocks of 128273 MB81.4 µs126

The compute floor for all three is 34.7 µs, since the FLOPs are the same. The original Algorithm 1 loops the other way: keys and values on the outside, so it must read and write each query block’s partial output and statistics to HBM on every outer step. That costs about 3Nd3Nd per pass instead of 2Nd2Nd. FlashAttention-2 swapped the loops, keeping each query block’s state on chip until it is finished. (The FlashAttention-2 paper credits Phil Tillet’s Triton implementation with that swap.) By this count the swap does not cut bytes: its passes are cheaper, but there are more of them (64 query blocks of 128 against 36 key blocks of 228), so the two orders land close together. FlashAttention-2’s speedup comes mainly from the changes described in the FlashAttention-2 section below, not from moving fewer bytes.

Treat these as rough counts, not predictions. They charge every reload of a KK or VV tile to HBM, but a GPU’s L2 cache sits between the SMs and HBM and can serve repeated loads, so measured traffic can be lower. They also ignore causal masking: in a decoder, a query never attends to later keys, so about half the tiles are fully masked and a good kernel skips them. The standard count is idealised the other way: 4Nd+4N24Nd + 4N^2 reads KK and VV only once, as if all of them fitted on chip at once. With an on-chip memory the size of FlashAttention’s, the obvious way would also re-read KK and VV for each block of rows, about 2(T−1)Nd2(T - 1)Nd elements more. The lesson’s figures use the paper’s count, which flatters the obvious way.

The paper’s own measurement is clearer. For GPT-2 medium (sequence length 1,024, head dimension 64, forward and backward pass) on an A100, the paper’s Figure 2 reports standard attention at 66.6 GFLOPs, 40.3 GB of HBM traffic and 41.7 ms, and FlashAttention at 75.2 GFLOPs, 4.4 GB and 7.3 ms. FlashAttention does more arithmetic and is still several times faster, because it moves an order of magnitude fewer bytes.

It is exact

FlashAttention is not an approximation. The rescaling is algebra, not estimation, so the only differences from standard attention are in the order of floating-point additions. The check below computes a 64-token, 16-dimension head both ways in your browser.

Seed 1: largest difference across all 1,024 outputs is 4.4e-16.

Row 1, columnStandard (S and P built)Tiled, online softmax
1-0.226212399-0.226212399
20.0211314010.021131401
30.0620836900.062083690
4-0.055285679-0.055285679
Both columns come from the same seeded inputs. In 64-bit floats the two methods agree to within rounding error. Switch to 32-bit arithmetic, closer to what a GPU does, and the differences grow to the size of 32-bit rounding error, still far below anything that matters. Change the block size or press New random inputs: the agreement holds for all of them.

For the default inputs, the largest difference is 4.4e-16 in 64-bit arithmetic and 1.8e-7 in 32-bit. Real kernels keep this kind of intermediate state in higher precision: FlashAttention-3, for example, keeps the softmax rescaling in FP32 even when its inputs are FP8.

Training: recompute instead of store

Training needs PP again in the backward pass to compute gradients. Standard attention keeps SS and PP in HBM for that. FlashAttention stores only the output OO and the per-row statistics mm and ℓ\ell, and recomputes the tiles of SS and PP from QQ and KK during the backward pass. That is the extra arithmetic in the GPT-2 measurement above. It still wins, because recomputing a tile on chip costs less than reading it from HBM. The extra memory attention needs becomes linear in NN instead of quadratic (the paper’s Theorem 1).

FlashAttention-2: keep the tensor cores busy

FlashAttention-1 cut HBM traffic, but the FlashAttention-2 paper (Dao, 2023) reports that it reached only 25–40% of an A100’s peak FLOP rate. The causes were inside the GPU, not in HBM. FlashAttention-2 made three changes:

The paper reports about a 2× speedup over FlashAttention, 50–73% of the A100’s theoretical peak, and up to 225 TFLOP/s per A100 when training GPT-style models end to end.

FlashAttention-3: overlap everything on Hopper

On the H100, FlashAttention-2 reached only 35% utilization, according to the FlashAttention-3 paper (Shah et al., 2024). Hopper GPUs added hardware that runs asynchronously: a Tensor Memory Accelerator (TMA) that copies tiles between HBM and SRAM by itself, and tensor-core instructions that run while other work continues. FlashAttention-3 uses three techniques:

The NeurIPS version of the paper reports up to 840 TFLOP/s in BF16, which it gives as 85% utilization (840 is 85% of the 989 TFLOP/s dense BF16 peak used on this site), and 1.3 PFLOP/s in FP8. The earlier arXiv preprint (July 2024) reported up to 740 TFLOP/s in FP16 (75%) and close to 1.2 PFLOP/s in FP8. At that utilization attention is limited by arithmetic, not by memory traffic. Quantization covers FP8 in general.

Decode: split the keys instead

Everything so far assumes many query rows: prefill (lesson 3) or training. At decode, each sequence has exactly one new query row per head, and it must read the whole KV cache. FlashAttention parallelizes over batch, heads and query blocks. With one query row there is one query block, so a single sequence produces only one unit of work (a thread block: a group of warps that the GPU schedules onto a single SM) per head. The Flash-Decoding post (Dao, Haziza, Massa and Sizov, 2023) notes that when the batch size is smaller than the number of SMs (108 on an A100), FlashAttention uses only a small part of the GPU.

Flash-Decoding adds a parallel dimension along the keys. It splits the KV cache into chunks, computes each chunk’s partial output with its own mm and ℓ\ell in parallel, then runs a small reduction that combines the partials using the same rescaling rule. The online softmax is used twice: within each chunk, and again across chunks. The post reports up to 8× faster generation for very long sequences on CodeLlama 34B, with the attention kernel itself up to 50× faster than FlashAttention (the post’s baseline is FlashAttention v2 before 2.2). Flash-Decoding is in the FlashAttention package from version 2.2.

Decode attention stays memory-bound: it reads every cached key and value once per step. Flash-Decoding barely changes that byte count; it makes sure the whole GPU is pulling those bytes.

Check yourself

Work each one out before opening the answer. Every answer comes from the same functions as the figures above.

Exercise 1. A single head with sequence length 65,536 in BF16. How large is S? How large is it for all 32 query heads of one Llama 3.1 8B layer, and what does that say about standard attention at long context? Enter the one-layer figure in GB.

GB
Show the worked answer

One head: 65,536 × 65,536 scores at 2 bytes each is 8.59 GB. All 32 heads of one layer: 275 GB, more than 3 entire H100s of 80.0 GB each, before counting PP, the weights or the KV cache. Doubling the length from 32,768 quadrupled it. At this length, standard attention cannot even keep its intermediate results in memory. FlashAttention keeps two numbers and a dd-vector per row instead.

Exercise 2. The worked example read [2, 5, 1, 3] in chunks of two. Now run online softmax by hand on the same scores in the other chunk order, [1, 3] then [2, 5]. What are m and l after each chunk, what correction factor is applied, and what is the probability of the score 5? Enter that probability as a decimal.

Show the worked answer

After [1,3][1, 3]: mm is 3 and ℓ=e−2+1\ell = e^{-2} + 1, which is 1.1353. After [2,5][2, 5]: the max rises to 5, so the old sum is multiplied by the correction factor e3−5=e−2e^{3-5} = e^{-2}, then e−3+e0e^{-3} + e^{0} is added, making ℓ\ell equal to 1.2034. The probability of 5 is 1/ℓ1/\ell, or 0.8310, the same as in the worked example (0.8310). The order of the chunks changes the intermediate values, not the answer.

Exercise 3. A model with head dimension 64 (as in GPT-2) runs one 8,192-token head on an H100 with 228 KiB of SRAM per SM. What is B_c, how many passes does Algorithm 1 make, and is attention memory-bound or compute-bound with standard attention and with Algorithm 1? Enter B_c.

rows
Show the worked answer

MM is still 116,736 BF16 elements, so BcB_c = ⌈116,736 / (4 × 64)⌉ = 456, and Algorithm 1 makes 18 passes. Standard: intensity about 32 FLOPs per byte (about d/2 again), far below the ridge of 295, so memory-bound, floor 162 µs. Algorithm 1: 61.0 MB of traffic, intensity about 282, memory-bound by this count, floor 18.2 µs, about 8.9× faster than standard. Halving dd doubled BcB_c, halved the passes and halved the bytes per pass: that is the d2d^2 in Theorem 2. The count charges every reload to HBM; the L2 cache can serve some of them, so a real kernel can do better.

Exercise 4. Suppose a future GPU doubled SRAM per SM to 456 KiB. Using Algorithm 1's block rule, what happens to B_c and B_r, to Algorithm 1's HBM traffic, and to the FlashAttention-2-order count, for the same 8,192-token head with d = 128?

Show the answer

BcB_c grows from 228 to 456 rows, so Algorithm 1 makes 18 passes instead of 36, and its traffic drops from 235 MB to 121 MB, close to half. That is Theorem 2’s 1/M1/M dependence. BrB_r stays at 128, because it is capped at dd, so the FlashAttention-2-order count does not move: 273 MB either way. In that loop order the saving would need taller query tiles, and register and SRAM limits keep those near 128 rows in practice. This is one reason each GPU generation needs its own tuned kernel.

Exercise 5. Decoding one sequence with Llama 3.1 8B (32 query heads) on an A100 with 108 SMs. If attention gets one thread block per head, how many SMs can it use? With a 32,768-token cache split into 1,024-token chunks, how many?

Show the answer

Without splitting: at most 32 of 108 SMs, about 30%, and each of those few SMs must stream a whole head’s cache by itself. With Flash-Decoding’s split: 32 heads × 32 chunks gives 1,024 independent pieces of work, so all 108 SMs can be busy, with enough work to fill each several times over, followed by a small reduction that merges the partial outputs with the online-softmax rule. (This is an idealized count. Real kernels also group the query heads that share a KV head under grouped-query attention, covered in lesson 5.)

Exercise 6. From lesson 1: what is the H100's ridge point in BF16, the arithmetic intensity at which work stops waiting on memory? Standard attention for one Llama 3.1 8B head at 8,192 tokens runs at about 63 FLOPs per byte (near d/2 at any long length): which side of the ridge is that, and what does it say about where FlashAttention's speedup comes from?

FLOPs per byte
Show the worked answer

About 295 FLOPs per byte: 989 TFLOP/s of BF16 arithmetic divided by 3.35 TB/s of memory bandwidth. Standard attention’s 63 is far below it, so it is memory-bound: the tensor cores spend most of the time waiting for the score table to travel to and from HBM. That is why moving fewer bytes, not doing less arithmetic, is what makes FlashAttention faster. It even does extra arithmetic in training and still wins.

Exercise 7. From lesson 4: how much KV cache does one 32,768-token document take for Llama 3.1 8B in BF16? Compare it with the 68.7 GB score table that standard attention needs for one layer. Enter the KV cache in GB.

GB
Show the worked answer

4.29 GB: 131,072 bytes per token (2 × 32 layers × 8 KV heads × 128 × 2 bytes) times 32,768 tokens. One layer’s score table is about 16 times larger. That is the incident: the prototype ran out of memory inside attention long before the KV cache was anywhere near full, and FlashAttention removes the table without touching the cache.

Sources

  1. Dao, Fu, Ermon, Rudra, Ré (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS 2022. arXiv:2205.14135. Algorithm 0 (standard attention), Algorithm 1 (FlashAttention), Theorem 2 (IO complexity), Figure 2 (GPT-2 medium measurements)
  2. Dao (2023). FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. arXiv:2307.08691. Loop order, fewer non-matmul FLOPs, A100 utilization figures
  3. Shah, Bikshandi, Zhang, Thakkar, Ramani, Dao (2024). FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision. NeurIPS 2024. arXiv:2407.08608. NeurIPS version: 840 TFLOP/s BF16 (85%), 1.3 PFLOP/s FP8. The arXiv preprint (v2, July 2024) reported up to 740 TFLOP/s in FP16 (75%) and close to 1.2 PFLOP/s in FP8. Also the source for the H100's 228 KiB of SRAM per SM
  4. Milakov, Gimelshein (2018). Online normalizer calculation for softmax. arXiv:1805.02867. The online softmax trick
  5. Dao, Haziza, Massa, Sizov (2023). Flash-Decoding for long-context inference. Stanford CRFM blog, October 2023 (also on the PyTorch blog). Secondary source: a blog post, not a peer-reviewed paper. PyTorch copy: pytorch.org/blog/flash-decoding
  6. Rabe, Staats (2021). Self-attention does not need O(n²) memory. arXiv:2112.05682. Related work cited by FlashAttention for the chunked softmax

Back to lesson 9: FlashAttention