All papersFoundationsClassic
Make attention fast by counting memory trips
Paper: FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré · arXiv · Posted · 24 min read · arXiv 2205.14135
- Transformers must read long inputs.
- The cost of Self-attention grows with the square of the length.
- Approximate methods cut the math but often not the clock time.
- The real cost is moving data in and out of slow memory.
3 timesfaster GPT-2 training with FlashAttention, with the same exact attention result.
- They train BERT-large, GPT-2 and long-range arena models.
- They compare with MLPerf 1.1, HuggingFace and Megatron-LM.
- They test long inputs, up to 64K tokens.
- They benchmark runtime and memory against many other methods.
- BERT-large trains 15% faster than the MLPerf 1.1 record.
- GPT-2 trains up to 3 times faster. Perplexity stays the same.
- Longer context gives 0.7 better perplexity on GPT-2.
- Transformers beat chance on Path-X and Path-256 for the first time.
FlashAttention trains GPT-2 about 3 times faster than HuggingFaceFrom Table 2HuggingFaceMegatron-LMFlashAttention
Hover, tap or focus a bar to read its exact value.
| Model | HuggingFace (days) | Megatron-LM (days) | FlashAttention (days) |
|---|
| GPT-2 small | 9.5 | 4.7 | 2.7 |
| GPT-2 medium | 21.0 | 11.5 | 6.9 |
- This is a 2022 paper. Newer GPUs and kernels exist.
- Each new attention form needs its own CUDA kernel.
- Speedup is lower with head size 128 and on T4 GPUs.
- Many numbers are for A100 GPUs only.
Jump to
Every detail from the paper
Cards follow the paper's own order. Dotted words link to Words to know. Numbers match the paper.
The problem
- Transformers are slow and hungry for memory on long inputs.
- The cost of self-attention grows with the square of the input length.
- This is quadratic growth in time and in memory.
Old fixes
- Approximate attention methods trade quality for less compute.
- But they often give no real speedup on a clock (wall-clock).
The idea
- The authors say a missing idea is to make attention IO-aware.
- That means counting reads and writes between levels of GPU memory.
- FlashAttention is an IO-aware exact attention algorithm.
- It uses Tiling to cut reads and writes between HBM and on-chip SRAM.
The analysis
- They analyze the IO cost of FlashAttention.
- It needs fewer HBM accesses than standard attention.
- It is optimal for a range of SRAM sizes.
- They also build block-sparse FlashAttention.
- It is approximate, and faster than any existing approximate method.
Faster training
- BERT-large (length 512): 15% faster end to end than the MLPerf 1.1 record.
- GPT-2 (length 1K): 3 times faster.
- Long-range arena (length 1K-4K): 2.4 times faster.
Better models
- Longer context gives better models.
- GPT-2 gets 0.7 better Perplexity.
- Long-document classification gets 6.4 points of lift.
- These are the first Transformers better than chance on Path-X (length 16K, 61.4% accuracy).
- They are also the first on Path-256 (length 64K, 63.1% accuracy).
The question
- Transformers are the most used design in language and image work.
- They have grown larger and deeper.
- Longer context is still hard.
- Self-attention has time and memory cost that grows with the square of the length.
- So: can faster, leaner attention fix runtime and memory limits on long inputs?
Why approximate methods fall short
- Many approximate methods try to cut the compute and memory of attention.
- They range from sparse approximation to low-rank approximation, and mixes of both.
- They cut compute to linear or near-linear in length.
- But many show no wall-clock speedup against standard attention.
- So they have not been widely adopted.
The reason
- They focus on FLOP reduction. FLOPs may not match real speed.
- They tend to ignore the cost of memory access (IO).
The missing idea
- The authors argue a missing idea is to be IO-aware.
- That means carefully counting reads and writes at fast and slow memory levels.
- For a GPU, fast memory is on-chip SRAM. Slow memory is HBM.
- Figure 1 (left) shows the levels.
| Memory | Speed | Size |
|---|
| GPU SRAM | 19 TB/s | 20 MB |
| GPU HBM | 1.5 TB/s | 40 GB |
| Main memory (CPU DRAM) | 12.8 GB/s | >1 TB |
Figure 1 (left): the memory levels of a GPU
Why IO matters
- On modern GPUs, compute speed has out-paced memory speed.
- Most Transformer operations wait on memory accesses.
- IO-aware algorithms are key for such memory-bound work.
- Examples: database joins, image processing and numerical linear algebra.
- But PyTorch and Tensorflow do not give fine control of memory access.
The goal
- FlashAttention computes exact attention with far fewer memory accesses.
- The main goal: never read or write the full attention matrix to HBM.
- This needs two things.
- (i) Compute the softmax without seeing the whole input.
- (ii) Do not store the large middle matrix for the backward pass.
The two techniques
- Technique 1, Tiling: split the input into blocks and make several passes.
- The softmax is then built up step by step.
- Technique 2: keep the softmax normalization factor from the forward pass.
- In the backward pass, use it to recompute attention on the chip.
- This is faster than reading the middle matrix back from HBM.
The implementation
- They write it in CUDA for fine control of memory access.
- They fuse all attention steps into one GPU Kernel.
- Recomputation adds FLOPs, yet the method runs faster, up to 7.6 times on GPT-2.
- It also uses memory that is linear in the length.
The IO cost
- They prove FlashAttention needs about N squared times d squared divided by M HBM accesses.
- N is the length, d is the head size and M is the SRAM size.
- Standard attention needs about N times d plus N squared.
- For typical d and M, this is many times fewer.
- It is up to 9 times fewer (Figure 2).
- A lower bound shows no exact method can beat this for all SRAM sizes.
The sparse extension
- FlashAttention can also help approximate methods.
- As proof, they build block-sparse FlashAttention.
- It is 2-4 times faster than FlashAttention, and scales to length 64k.
- Its IO cost is lower by a factor tied to the sparsity ratio.
- Section 5 lists more extensions. The code is open source.
What they show: speed
- Faster training. BERT-large (length 512) is 15% faster than the MLPerf 1.1 record.
- GPT2 (length 1K) is 3 times faster than HuggingFace and Megatron-LM baselines.
- Long-range arena (length 1K-4K) is 2.4 times faster.
What they show: quality
- Better models. Longer sequences improve quality.
- GPT-2 gains 0.7 in perplexity. Long-document classification gains 6.4 points.
- It enables the first Transformer better than chance on Path-X (length 16K).
- Block-sparse FlashAttention does the same on Path-256 (length 64K).
What they show: benchmarks
- Benchmarks. FlashAttention is up to 3 times faster than standard attention.
- This holds for common lengths from 128 to 2K. It scales up to 64K.
- Up to length 512, it is faster and leaner than any existing method.
- Beyond 1K, some approximate methods (for example Linformer) become faster.
- Block-sparse FlashAttention is faster than all approximate methods the authors know.
- This section covers how GPUs perform, and how standard attention works.
2.1 Hardware performance
GPU memory levels
- The paper focuses on GPUs. Other accelerators behave in a similar way.
- A GPU has several kinds of memory. Smaller memory is faster.
- Example: an A100 has 40-80GB of HBM, with 1.5-2.0TB/s bandwidth.
- It has 192KB of on-chip SRAM for each of 108 streaming multiprocessors.
- SRAM bandwidth is about 19TB/s.
- SRAM is an order of magnitude faster than HBM, but many orders smaller.
- Compute got faster than memory. So memory (HBM) accesses limit speed.
- So using fast SRAM matters more.
How a GPU runs work
- A GPU runs an operation with a huge number of threads.
- The operation is a Kernel.
- Each kernel loads inputs from HBM to registers and SRAM.
- It computes. Then it writes outputs to HBM.
Examples
- Compute-bound: math time is the main cost. HBM time is much smaller.
- Examples: matrix multiply with a large inner size, and convolution with many channels.
- Memory-bound: memory access time is the main cost. Math time is much smaller.
- Examples: activation, dropout, sum, softmax, batch norm and layer norm.
Kernel fusion
- Kernel fusion speeds up memory-bound work.
- If several operations use the same input, load it from HBM once.
- Compilers can fuse many elementwise operations.
- But in training, middle values must still be saved to HBM for the backward pass.
- That reduces the gain from naive fusion.
2.2 Standard attention
Standard attention, step by stepFrom Algorithm 0- Load Q and K from HBM
- Compute scores S, write to HBM
- Read S, compute softmax P
- Write P to HBM
- Load P and V, compute O
- Write O to HBM
S and P are N by N matrices. Each trip to HBM is slow.
The math
- The inputs are Q, K and V, each N by d.
- N is the sequence length. d is the head dimension.
- Step 1: S = Q times K-transpose. S is N by N.
- Step 2: P = softmax(S), row by row. P is N by N.
- Step 3: O = P times V. O is N by d.
The cost
- Standard code writes S and P to HBM.
- This takes memory that grows with N squared.
- Often N is much larger than d.
- For GPT2, N = 1024 and d = 64.
- Many steps are memory-bound, such as softmax. So the many accesses slow the clock time.
Extra steps
- Other elementwise steps make it worse, such as masking on S or dropout on P.
- People tried fusing steps, for example masking with softmax.
- Section 3.2 shows standard attention makes HBM accesses that grow with N squared.
- The goal: exact attention with fewer HBM reads and writes.
- It must not store large middle matrices for the backward pass.
- The result is faster in clock time and leaner in memory.
- They study the IO cost, and they extend it to block-sparse attention.
- This section covers the forward pass. Appendix B has the backward pass.
How FlashAttention runs, step by stepFrom Algorithm 1- Split Q, K, V into blocks
- Load K, V block to SRAM
- Load one Q block to SRAM
- Compute scores and softmax on chip
- Rescale and update the output
- Write output block to HBM
The outer loop runs over K and V blocks. The inner loop runs over Q blocks. The full N by N matrix never goes to HBM.
The main idea
- The inputs Q, K, V are in HBM. The goal is O, written to HBM.
- The goal is fewer HBM accesses, less than quadratic in N.
- They use two known techniques: tiling and recomputation.
- Main idea: split Q, K, V into blocks.
- Load them from slow HBM into fast SRAM.
- Compute the attention output for those blocks.
- Scale each block's output by the right factor before adding the blocks.
- Then the final result is correct.
Tiling
- Softmax couples the columns of K. So they split the big softmax with scaling.
- For numerical stability, the softmax of a vector x uses the largest value m(x).
- They compute f(x) = exp(x - m(x)) and l(x) = the sum of f(x).
- Then softmax(x) = f(x) / l(x).
Joining two parts
- Take two vectors x1 and x2, joined into one.
- The new maximum is the larger of the two maxima.
- The values f and l for the joined vector come from the parts.
- Each part is scaled by exp(old maximum - new maximum).
- So we keep two extra numbers, m(x) and l(x).
- With them, we can compute softmax one block at a time.
- This kind of joining is called algebraic aggregation.
In the algorithm
- Algorithm 1 splits the inputs into blocks (line 3).
- It computes softmax values and the extra numbers (line 10).
- It combines the results (line 12).
Recomputation
- A goal is to not store N squared middle values for the backward pass.
- The backward pass usually needs S and P, each N by N.
- It uses them to find gradients for Q, K and V.
- But they store the output O and the softmax numbers (m, l).
- Then they recompute S and P in the backward pass.
- They use blocks of Q, K and V in SRAM.
Why it is different
- This is a form of selective gradient checkpointing.
- Known versions of checkpointing trade speed for less memory.
- Here, recomputation adds FLOPs but makes the backward pass faster.
- The reason is fewer HBM accesses (Figure 2).
- Appendix B has the full backward pass.
Kernel fusion and Algorithm 1
One kernel
- Tiling lets them run the whole algorithm in one CUDA kernel.
- It loads input from HBM, then does every step, then writes the result back.
- Steps: matrix multiply, softmax, optional masking and dropout, matrix multiply.
- This avoids repeated reads and writes of inputs and outputs.
Algorithm 1 in words
- Set block sizes from the SRAM size M and the head size d.
- Start the output O, and the numbers l and m, in HBM.
- Split Q into row blocks. Split K and V into column blocks.
- Outer loop: for each K and V block, load it from HBM to SRAM.
- Inner loop: for each Q block, load Q, O, l and m to SRAM.
- On chip: compute the block of scores, then its maximum, exponents and sums.
- On chip: compute the new maximum and new sum.
- Write the updated output block, and the new l and m, to HBM.
What they prove
- Theorem 1. Algorithm 1 returns exactly softmax(Q K-transpose) times V.
- It uses about N squared times d FLOPs.
- It needs only about N extra memory beyond inputs and output.
- The proof is in Appendix C.
The aim
- They show FlashAttention needs far fewer HBM accesses than standard attention.
- They also give a lower bound.
- No exact attention algorithm can beat the HBM access count for all SRAM sizes.
- Proofs are in Appendix C.
The result
- Theorem 2. N is the length. d is the head size.
- M is the SRAM size, from d up to N times d.
- Standard attention needs about N times d plus N squared HBM accesses.
- FlashAttention needs about N squared times d squared divided by M.
In practice
- Typical d is 64-128. Typical M is around 100KB.
- So d squared is many times smaller than M.
- So FlashAttention needs many times fewer HBM accesses.
- This gives faster runs and lower memory. Section 4.3 checks it.
The idea of the proof
- Given SRAM size M.
- They load K and V blocks of size about M each (line 6).
- For each block, they loop over all Q blocks (line 8).
- That is about N times d divided by M passes over Q.
- Each pass loads about N times d numbers.
- In total: about N squared times d squared divided by M accesses.
- The backward pass has the same counts (Appendix B).
The lower bound
- Proposition 3. No exact attention algorithm can use fewer HBM accesses.
- This holds for all M from d up to N times d.
- Proof idea: for M near N times d, any algorithm needs
- about N times d accesses.
- Lower bounds over a range of M are common in streaming algorithm work.
- A tighter bound in terms of M is left as future work.
FlashAttention cuts memory reads and writes by about 9 timesFrom Figure 2 (left)Hover, tap or focus a bar to read its exact value.
| Method | HBM reads/writes (GB) |
|---|
| Standard attention | 40.3 |
| FlashAttention | 4.4 |
| Measure | Standard | FlashAttention |
|---|
| GFLOPs | 66.6 | 75.2 |
| HBM R/W (GB) | 40.3 | 4.4 |
| Runtime (ms) | 41.7 | 7.3 |
Figure 2 (left): forward and backward pass for GPT-2 medium on an A100
Length 1024, head size 64, 16 heads, batch size 64. HBM access is the main factor in runtime.
What the figure shows
- FlashAttention has more FLOPs, due to recomputation in the backward pass.
- But it has far fewer HBM accesses. So it runs much faster.
- In Figure 2 (middle).
- They vary the block size Bc. The tested sizes are 64, 128, 256 and 512.
- A bigger block size means fewer passes over the input.
- It also means fewer HBM accesses. Runtime falls.
- Beyond 256, other limits, such as math, set the runtime.
- Also, larger blocks do not fit in the small SRAM.
The idea
- They extend FlashAttention to approximate attention.
- The new method is block-sparse FlashAttention.
- Its IO cost is lower than FlashAttention by a factor tied to the sparsity.
The setup
- The inputs are Q, K and V, plus a mask matrix.
- The mask is N by N and holds zeros and ones.
- Scores are kept where the mask is 1.
- They are set to minus infinity where it is 0.
- The mask must be in block form, with one value per block.
The algorithm
- With a preset block mask, Algorithm 1 only needs to compute the nonzero blocks.
- The algorithm is the same, but it skips zero blocks.
- Algorithm 5 in Appendix B shows it.
The IO cost
- Proposition 4. Block-sparse FlashAttention needs fewer HBM accesses.
- It needs about N times d,
- plus N squared times d squared times s, over M.
- Here s is the share of nonzero blocks in the mask.
- So sparsity directly shrinks the larger term.
In practice
- For large N, s is often set to N to the power minus one half.
- Or it is set to log N divided by N.
- That gives an IO cost of about N times the square root of N.
- Or it gives about N log N.
- In their tests, they use a fixed butterfly sparsity pattern.
- It is known to approximate any sparsity pattern.
The check
- Figure 2 (right) checks this at length 4K.
- As sparsity grows, block-sparse runtime improves in proportion.
- On the LRA benchmark, it gives a 2.8 times speedup.
- It performs on par with standard attention (Section 4).
The plan
- They test the effect of FlashAttention on training Transformers.
- They check two claims: training time and model accuracy.
- They also report runtime and memory benchmarks.
- Appendix E has more experiment details.
Claim 1
- Training speed. It beats the MLPerf 1.1 record for BERT by 15%.
- It speeds up GPT-2 up to 3 times over HuggingFace and 1.8 times over Megatron.
- It speeds up the long-range arena (LRA) 2.4 times.
Claim 2
- Quality. It trains GPT-2 with context 4K faster than Megatron trains GPT-2 with context 1K.
- It also gets 0.7 better perplexity.
- Longer sequences give 6.4 points of lift on two long-document classification tasks.
- It gives the first Transformer better than random on Path-X (length 16K).
- Block-sparse FlashAttention gives the first sequence model they know of
- that is better than random on Path-256.
- Path-256 has length 64K.
Claim 3
- Benchmarks. They measure runtime and memory by sequence length.
- FlashAttention memory grows linearly with length.
- It is up to 3 times faster than standard attention.
- This holds for common lengths, up to 2K.
- Block-sparse FlashAttention runtime grows linearly.
- It is faster than all approximate baselines.
BERT
- FlashAttention gives the fastest single-node BERT training the authors know of.
- They train BERT-large on Wikipedia.
- The baseline is the Nvidia code that set the MLPerf 1.1 record.
- Their version is 15% faster.
| Implementation | Training time (minutes) |
|---|
| Nvidia MLPerf 1.1 | 20.0 ± 1.5 |
| FlashAttention (ours) | 17.4 ± 1.4 |
Table 1: BERT-large training time to reach 72.0% masked language modeling accuracy
Same start point from MLPerf. Average of 10 runs on 8 A100 GPUs.
GPT-2
- They train GPT-2 on the large OpenWebtext dataset.
- Baselines are the common HuggingFace and Megatron-LM versions.
- The text says up to 3 times faster than HuggingFace.
- The text says 1.7 times faster than Megatron-LM.
- Table 2 shows 3.5 times for GPT-2 small over HuggingFace.
- It shows 3.0 times for GPT-2 medium.
- Perplexity is the same, as the model definition does not change.
- Appendix E plots show the same training curves as the baselines.
FlashAttention trains GPT-2 about 3 times faster than HuggingFaceFrom Table 2HuggingFaceMegatron-LMFlashAttention
Hover, tap or focus a bar to read its exact value.
| Model | HuggingFace (days) | Megatron-LM (days) | FlashAttention (days) |
|---|
| GPT-2 small | 9.5 | 4.7 | 2.7 |
| GPT-2 medium | 21.0 | 11.5 | 6.9 |
| Model and implementation | Perplexity | Training time (speedup) |
|---|
| GPT-2 small, HuggingFace | 18.2 | 9.5 days (1.0x) |
| GPT-2 small, Megatron-LM | 18.2 | 4.7 days (2.0x) |
| GPT-2 small, FlashAttention | 18.2 | 2.7 days (3.5x) |
| GPT-2 medium, HuggingFace | 14.2 | 21.0 days (1.0x) |
| GPT-2 medium, Megatron-LM | 14.3 | 11.5 days (1.8x) |
| GPT-2 medium, FlashAttention | 14.3 | 6.9 days (3.0x) |
Table 2: GPT-2 on OpenWebText, perplexity and training time
Long-range arena
- They compare a vanilla Transformer with standard attention or FlashAttention.
- The test is the long-range arena (LRA) benchmark.
- They measure accuracy, throughput and training time.
- Each task has a length between 1024 and 4096.
- They follow the set-ups of Tay et al. and Xiong et al.
- FlashAttention is up to 2.4 times faster than standard attention.
- Block-sparse FlashAttention is faster than all approximate methods they tested.
A note
- LRA accuracy depends a lot on tuning.
- Their reproduced baselines do better than the numbers in the original comparison.
Table 3 in full
| Model | ListOps | Text | Retrieval |
|---|
| Transformer | 36.0 | 63.6 | 81.6 |
| FlashAttention | 37.6 | 63.9 | 81.4 |
| Block-sparse FlashAttention | 37.0 | 63.0 | 81.3 |
| Linformer | 35.6 | 55.9 | 77.7 |
| Linear Attention | 38.8 | 63.2 | 80.7 |
| Performer | 36.8 | 63.6 | 82.2 |
| Local Attention | 36.1 | 60.2 | 76.7 |
| Reformer | 36.5 | 63.8 | 78.5 |
| Smyrf | 36.1 | 64.1 | 79.0 |
Table 3: long-range arena results (part 1 of 3)
| Model | Image | Pathfinder | Avg |
|---|
| Transformer | 42.3 | 72.7 | 59.3 |
| FlashAttention | 43.5 | 72.7 | 59.8 |
| Block-sparse FlashAttention | 43.6 | 73.3 | 59.6 |
| Linformer | 37.8 | 67.6 | 54.9 |
| Linear Attention | 42.6 | 72.5 | 59.6 |
| Performer | 42.1 | 69.9 | 58.9 |
| Local Attention | 40.6 | 66.6 | 56.0 |
| Reformer | 39.6 | 69.4 | 57.6 |
| Smyrf | 39.6 | 70.5 | 57.9 |
Table 3: long-range arena results (part 2 of 3)
| Model | Speedup |
|---|
| Transformer | - |
| FlashAttention | 2.4x |
| Block-sparse FlashAttention | 2.8x |
| Linformer | 2.5x |
| Linear Attention | 2.3x |
| Performer | 1.8x |
| Local Attention | 1.7x |
| Reformer | 1.3x |
| Smyrf | 1.7x |
Table 3: long-range arena results (part 3 of 3)
Language modeling with long context
- FlashAttention allows 4 times more context for GPT-2.
- It is still faster than the Megatron-LM implementation.
- With context 4K, it is still 30% faster than Megatron with context 1K.
- It also gets 0.7 better perplexity.
| Model and implementation | Context | Perplexity | Training time (speedup) |
|---|
| GPT-2 small, Megatron-LM | 1k | 18.2 | 4.7 days (1.0x) |
| GPT-2 small, FlashAttention | 1k | 18.2 | 2.7 days (1.7x) |
| GPT-2 small, FlashAttention | 2k | 17.6 | 3.0 days (1.6x) |
| GPT-2 small, FlashAttention | 4k | 17.5 | 3.6 days (1.3x) |
Table 4: GPT-2 small, context length against perplexity and training time
Training on 8 A100 GPUs.
Long-document classification: data
- Longer sequences with FlashAttention improve results on MIMIC-III and ECtHR.
- MIMIC-III has intensive care discharge summaries, each with several labels.
- ECtHR has legal cases from the European Court of Human Rights.
- Each case maps to articles of the Convention that were allegedly violated.
Document length
- Both sets have very long documents.
- MIMIC: average 2,395 tokens. The longest has 14,562 tokens.
- ECtHR: average 2,197 tokens. The longest has 49,392 tokens.
- They lengthen a pretrained RoBERTa model, repeating the positional embeddings as in Beltagy et al.
Result
- Length 16K beats length 512 by 4.3 points on MIMIC.
- Length 8K beats length 512 by 8.5 points on ECtHR.
- The gap may come from small distribution shifts.
- MIMIC-III has specialized medical text.
- So it may react more to a change in document length.
- ECtHR has general language.
| Sequence length | MIMIC-III | ECtHR |
|---|
| 512 | 52.8 | 72.2 |
| 1024 | 50.7 | 74.3 |
| 2048 | 51.7 | 77.1 |
| 4096 | 54.6 | 78.6 |
| 8192 | 56.4 | 80.7 |
| 16384 | 57.1 | 79.2 |
Table 5: long-document performance (micro F1) at different lengths
Path-X and Path-256: the task
- Path-X and Path-256 are hard tests from the long-range arena.
- The task: decide if a path joins two points in an image.
- The image is black and white.
- The images are 128 by 128 (or 256 by 256).
- They go to the Transformer one pixel at a time.
- Earlier Transformers ran out of memory or scored at random level.
- People searched for other designs to handle such long context.
Path-X and Path-256: the result
- Here is the first result of Transformers solving Path-X and Path-256 (Table 6).
- They pretrain on Path-64, then move to Path-X by interpolating the positional embeddings in space.
- FlashAttention reaches 61.4 accuracy on Path-X.
- Block-sparse FlashAttention scales to length 64K and reaches 63.1 accuracy on Path-256.
- Path-256 needs longer sequences but has shorter paths than Path-X.
- So a higher score is easier.
| Model | Path-X | Path-256 |
|---|
| Transformer | fail | fail |
| Linformer | fail | fail |
| Linear Attention | fail | fail |
| Performer | fail | fail |
| Local Attention | fail | fail |
| Reformer | fail | fail |
| SMYRF | fail | fail |
| FlashAttention | 61.4 | fail |
| Block-sparse FlashAttention | 56.0 | 63.1 |
Table 6: the first Transformers with better-than-random results on Path-X and Path-256
In the paper, a cross mark shows a model that ran out of memory or scored at random level.
The set-up
- They vary the length and measure runtime and memory of FlashAttention and block-sparse FlashAttention.
- The test runs on one A100 GPU with 40 GB of HBM.
- It uses dropout and a padding mask.
- They compare with reference code for exact, approximate and sparse attention.
- The main text shows a subset of baselines. Appendix E has more.
Runtime (Figure 3, left)
- Runtime grows with the square of the length for exact attention.
- FlashAttention is much faster than exact baselines: up to 3 times faster than PyTorch.
- Many approximate and sparse methods grow linearly with length.
- Yet FlashAttention is faster than them for short lengths, due to fewer memory accesses.
- Approximate methods begin to cross over with FlashAttention between 512 and 1024.
- Block-sparse FlashAttention is faster than all known methods at all lengths.
At length 4096, block-sparse FlashAttention is the fastest of allFrom Table 11Hover, tap or focus a bar to read its exact value.
| Method | Runtime (ms) |
|---|
| PyTorch Attention | 124.19 |
| Reformer | 116.34 |
| Local Attention | 42.01 |
| Linformer | 8.04 |
| Smyrf | 71.68 |
| LSformer | 61.72 |
| Block Sparse | 39.19 |
| Longformer | 22.49 |
| BigBird | 23.89 |
| FlashAttention | 37.49 |
| Block-Sparse FlashAttention | 4.12 |
A note on the chart
- The chart leaves out Megatron. It supports no length above 2048.
- Table 11 has the numbers for every length.
Memory (Figure 3, right)
- FlashAttention and block-sparse FlashAttention have the same footprint. It grows linearly.
- FlashAttention is up to 20 times more memory-efficient than exact baselines.
- It is also more memory-efficient than approximate baselines.
- All other methods except Linformer run out of memory on an A100 before 64K.
- FlashAttention is still 2 times more efficient than Linformer.
Compiling to CUDA
- Compiling to CUDA. Each new attention form needs a new CUDA kernel.
- That means writing in a lower-level language than PyTorch, with real engineering effort.
- The code may not carry over to other GPU designs.
- So the authors want a way to write attention in a high-level language.
- It would compile to IO-aware CUDA, like Halide does for image processing.
IO-aware deep learning
- The IO-aware way can reach beyond attention.
- Attention is the heaviest memory user in Transformers.
- But every layer of a deep network touches GPU HBM.
- They hope this work inspires IO-aware versions of more modules.
- Appendix D discusses such extensions.
Many GPUs
- FlashAttention is optimal within constants on a single GPU.
- Attention may also run across several GPUs.
- That adds a new level to the IO analysis: data moves between GPUs.
- The authors hope for future work in this direction.
IO-aware runtime work
- The idea of fast and slow memory has a long history under many names.
- The closest link is the I/O complexity analysis of Aggarwal and Vitter.
- Others include the working set model, data locality, the Roofline model and scalability analyses.
- The authors hope the deep learning field uses these ideas in more places.
Structured matrices
- Matrix multiply is the core cost of most ML models.
- Structured matrices have fewer than quadratic parameters and runtime.
- Common types are sparse and low-rank matrices, and fast transforms such as Fourier.
- The butterfly pattern behind their block-sparse attention can express any structured matrix.
- It does so with almost optimal runtime and parameters.
- But structured matrices rarely give a real speedup, a case called the hardware lottery.
- Dense matrix multiply is already very well optimized.
Sparse training
- Block-sparse FlashAttention is a step towards faster sparse training.
- Sparse models can cut model size for inference (pruning).
- The lottery ticket idea says small sub-networks can match the dense network.
- Their method is like a fixed lottery ticket for attention.
- The sparsity pattern is fixed to butterfly.
- It does almost as well as dense FlashAttention on LRA.
Efficient Transformers
- Many methods attack the cost of attention that grows with length.
- Hashing: Reformer and Smyrf. Low-rank: Performer.
- Mixes of sparse and low-rank: Longformer, BigBird, Scatterbrain, Long-short transformer and Combiner.
- Others compress along the sequence, or attend over earlier sequences, like Transformer-XL.
- Other designs replace attention, such as HiPPO with S4, LambdaNetworks, AFT and FLASH.
Overview
- They derive forward and backward passes that need extra memory linear in the length.
- Naively, they still need quadratic HBM accesses, which is slow.
- FlashAttention does both passes on GPUs with fewer HBM accesses.
B.1 Memory-efficient forward pass
- The hard part is softmax, which couples the columns of K and V.
- The fix: compute the softmax normalization constant on its own, to decouple the columns.
- This known method shows attention needs no quadratic extra memory.
- But HBM accesses stay quadratic, so it is slow.
- For simplicity, this part omits the max-shifting step.
The two steps
- Step 1: compute the constant L for each row. This needs about N extra memory.
- Step 2: compute each output row by repeated sums. This needs about d extra memory.
- So the forward pass needs about N extra memory in total.
B.2 Memory-efficient backward pass
- Rabe and Staats suggest gradient checkpointing on the memory-efficient forward pass.
- The authors derive the backward pass directly instead.
- They apply the chain rule by hand to get dV, dP and dS.
- The softmax Jacobian is diag(y) minus y times y-transpose.
- They define D for each row.
- D is the dot product of dO and O for that row.
- Then dS = P times (dP minus D), element by element.
The four steps
- Step 1: compute dV from P and dO. It needs about d extra memory.
- Step 2: compute D for all rows. It needs about N extra memory.
- Step 3: compute dQ. It needs about d extra memory.
- Step 4: compute dK. It needs about d extra memory.
- So the backward pass needs about N extra memory too.
B.3 FlashAttention: forward pass in full
- The full version adds scaling tau, masking and dropout.
- tau is typically 1 divided by the square root of d.
- The mask sets some entries to minus infinity, for example for padded keys.
- Dropout sets each element to 0 with probability p.
- Otherwise it scales the element by 1 divided by (1 - p).
- Algorithm 2 is the full forward pass.
- It saves the output O, the numbers l and m.
- And the random number generator state R.
B.4 FlashAttention: backward pass in full
- Algorithm 3 is the standard backward pass.
- It moves dV, dP, dS, dQ and dK through HBM.
- Algorithm 4 is the FlashAttention backward pass.
- It is a block version of the B.2 math.
Two observations
- Observation 1. They need not store the dropout mask from the forward pass.
- That mask is N by N.
- They save the random generator state and re-make the mask in the backward pass.
- This keeps extra memory at about N.
- Observation 2. D equals the dot product of dO and O for a row.
- That product runs over d numbers.
- So they need no reduction over rows of size N.
- Such rows may not fit in SRAM.
Cost
- Like the forward pass, the backward pass does about N squared FLOPs.
- It needs only about N extra memory.
- Theorem 5. Standard backward needs about N times d plus N squared HBM accesses.
- FlashAttention backward needs about N squared times d squared divided by M.
Proof of Theorem 1
- The dominant FLOPs are matrix multiplies in the inner loop.
- Each one takes about Br times Bc times d FLOPs.
- The inner loops run Tc times Tr times.
- That is N squared divided by (Bc times Br).
- So total FLOPs are about N squared times d.
- The extra memory is about N, for the numbers (l, m).
- Correctness is proved by induction on the block index j.
Proof of Theorem 2
- Standard attention has 3 steps.
- Each step reads and writes N by N or N by d data.
- So it makes about N times d plus N squared accesses.
- FlashAttention: each element of K and V loads once.
- There are Tc passes over Q and O.
- That is about N times d times Tc accesses.
- Blocks must fit in SRAM.
- So Bc times d and Br times d are each about M or less.
- So is Br times Bc.
- So Bc is about M over d.
- And Br is about the smaller of M over d and d.
- Then Tc is about N times d over M.
- So the total is about N squared times d squared over M.
Proof of Proposition 3
- Assume an algorithm with fewer accesses than that for all M in the range.
- For M near N times d, that is fewer than N times d accesses.
- But Q, K, V and O have size N times d and start in HBM.
- So at least about N times d accesses are needed. This is a contradiction.
Proof of Theorem 5
- The backward proof is very like the forward proof.
- It first counts the accesses of standard backward, then those of FlashAttention backward.
D.1 Block-sparse FlashAttention
- Algorithm 5 is the same as Algorithm 2, but it skips zero blocks.
- For Proposition 4, only the nonzero blocks must be loaded.
- So accesses scale by s, the share of nonzero blocks.
- Even for small s, the output O must still be written.
- So the total is about N times d,
- plus N squared times d squared times s, over M.
D.2 Extensions: many GPUs
- Multi-GPU attention. Big models train on hundreds or thousands of GPUs.
- Attention is often split over 4-8 GPUs on one node.
- The HBM of other GPUs is another level of memory.
- For very long sequences, GPUs could cooperate with this level in mind.
D.2 Extensions: sparse MLP
- Sparse MLP layers. Dense MLP layers are compute-bound, not memory-bound.
- Sparse MLP layers can be more efficient. But many are memory-bound.
- So their speedup is often not in proportion to the sparsity.
- An IO-aware version could fix this.
D.2 Extensions: kernel methods
- Kernel machine learning. A kernel matrix is N by N.
- Each entry depends on two vectors of size d.
- Here d is much smaller than N.
- So blocks can be recomputed, as in FlashAttention.
- The KeOps library shows that fewer reads and writes can speed up kernel work.
E.1 BERT
- They follow the training recipe of the MLPerf 1.1 reference code.
- They use the LAMB optimizer with learning rate 3.75e-3 and batch size 448.
- Training runs for at most 7100 steps.
- It stops when masked language modeling validation accuracy hits 72.0%.
- They train in FP16 with Apex AMP (O2 level).
- They compare with the Nvidia speed reported to MLPerf 1.1.
- They use the same split and the same 10000 validation examples as that baseline.
- They train on 8 A100-80GB GPUs. Each run takes 16 to 19 minutes.
- They average 10 runs.
E.2 GPT-2
Set-up
- They use the standard GPT-2 code from HuggingFace and from Nvidia's Megatron-LM repo.
- They follow the Megatron-LM recipe.
- The effective batch size is 512, using gradient accumulation to fit in memory.
- They use AdamW, with learning rate 6e-4 for small and 1.5e-4 for medium.
- And weight decay 0.1.
- All models train for 400K steps with the same settings, in mixed precision (PyTorch AMP).
Data and time
- The data is OpenWebtext with the GPT-2 BPE tokenizer.
- A random 0.5% is the validation set. It is chosen once for all models.
- They train on 8 A100-40GB GPUs and time the run.
- GPT-2 small takes 2.7-9.5 days. GPT-2 medium takes 6.9-21.0 days.
- Figure 4: the validation perplexity curves of both versions almost match.
Long documents
- For MIMIC-III and ECtHR, they follow the hyperparameters of Dai et al.
E.3 Long-range arena details
- They follow the settings of the long-range arena paper and repo, and the Nystromformer reproduction.
- If they cannot reproduce a baseline on a task.
- They report the better of two published numbers.
- This is to be generous to the baselines.
- After tuning, almost all methods have similar accuracy on the five tasks.
- All methods use mixed precision, except Performer (not stable) and Local Attention (no FP16 support).
- The overall speedup is the geometric mean of the speedups over the five tasks.
Path-X and Path-256
- They follow the PathFinder-32 settings from the LRA paper.
- First they pretrain a model on Path-64. They take the checkpoint after 200 epochs.
- They upsample its positional embedding by copying it across the grid.
- They fine-tune for 200 epochs, with one epoch of linear warmup and cosine decay.
- For Path-X, they fine-tune the best checkpoint for 200 more epochs.
- This adds about 4 points of accuracy to FlashAttention on Path-X.
- After that, the model overfits.
E.4 Comparison with Apex FMHA
What FMHA is
- Apex FMHA was the fastest attention code they knew of when they began.
- It is made for short sequences, up to length 512.
- Almost all Nvidia MLPerf BERT entries use FMHA.
- It fuses attention into one CUDA kernel.
- But it stores the attention matrix in the forward pass. So it saves little memory.
- It only supports head size 64 and only runs on A100 GPUs.
What changed
- They started from FMHA code and added tiling and recomputation.
- They support lengths up to 64K.
- They support head sizes 16, 32, 64 and 128.
- They support all Turing and Ampere GPUs of the time.
| Method | 128 | 256 | 512 |
|---|
| Apex FMHA forward | 0.10 | 0.29 | 1.14 |
| FlashAttention forward | 0.08 | 0.22 | 0.81 |
| Apex FMHA backward | 0.17 | 0.52 | 1.81 |
| FlashAttention backward | 0.20 | 0.53 | 2.00 |
| Apex FMHA forward + backward | 0.27 | 0.81 | 2.95 |
| FlashAttention forward + backward | 0.28 | 0.75 | 2.81 |
Table 7: runtime (ms) of FlashAttention against FMHA
A100-SXM4-40GB, with masking and dropout. Batch size 64, 16 heads, head size 64.
Result
- FlashAttention is slightly faster in the forward pass.
- It is slightly slower in the backward pass, since it recomputes the attention matrix.
- Overall it is about 4% slower at length 128.
- It is 8% faster at length 256 and 5% faster at length 512.
E.5 Speedup on other hardware and settings
- Speedup changes with the GPU type, due to HBM bandwidth and SRAM size.
- A100 (batch 8, head size 64, 12 heads): generally 2-4 times speedup.
- There is more speedup with dropout and masking, due to kernel fusion.
- A100, head size 128 (batch 16, 12 heads): blocks must be smaller to fit SRAM.
- So there is less speedup.
- But it is up to 3 times with a causal mask.
- There, half the blocks are masked out.
- RTX 3090 (batch 12, 12 heads): 2.5-4.5 times speedup.
- Its memory bandwidth is lower: about 900 GB/s against 1.5 TB/s.
- T4: its SRAM is smaller, so blocks are smaller and speedup is lower.
- That matches the IO analysis in Section 3.2.
- T4 is used for inference, so they also report forward pass only.
E.6 Full benchmarking results
Baselines
- Exact baselines: PyTorch/HuggingFace and Megatron.
- Approximate baselines: Reformer, Local Attention, Linformer, Smyrf and LongShortFormer.
- Sparse baselines: Block-Sparse from OpenAI, Longformer and BigBird.
- For approximate and sparse methods, the compression ratio is 1/8, or length 256 if smaller.
Set-up
- They use 8 heads of size 64 and batch size 16.
- They use one A100 with 40 GB of HBM.
- Q, K and V are random.
- They do not time the projection from the hidden layer.
- Dropout is 0.1. The padding mask has random lengths between N and N minus 20.
- Runtime is the average of 100 calls. Memory is measured once.
- They use FP16, except Local Attention (FP32 only).
Limits of baselines
- Block Sparse, Longformer and BigBird could not run the backward pass with masking.
- The cause was a bug in outside libraries.
- So they were timed without masking, to be generous.
- Megatron does not support lengths above 2048.
- Block-Sparse (OpenAI) does not support lengths above 4096.
- Longformer and BigBird do not support lengths above 8092.
- Memory is measured on the combined pass, with no dropout or masking.
| Dropout | Masking | Pass | Table |
|---|
| Yes | Yes | Forward | Table 9 |
| Yes | Yes | Backward | Table 10 |
| Yes | Yes | Combined | Table 11 |
| No | Yes | Forward | Table 12 |
| No | Yes | Backward | Table 13 |
| No | Yes | Combined | Table 14 |
| Yes | No | Forward | Table 15 |
| Yes | No | Backward | Table 16 |
| Yes | No | Combined | Table 17 |
| No | No | Forward | Table 18 |
| No | No | Backward | Table 19 |
| No | No | Combined | Table 20 |
| No | No | Memory (combined) | Table 21 |
Table 8: pointers to the results tables
What is left out here
- Tables 9, 10 and 12 to 20 hold the same measures.
- They cover each pass and setting.
- They are in the original. This page shows Table 11 and Table 21 in full.
Table 11 in full: forward + backward runtime (ms), with dropout and masking
| Method | 128 | 256 | 512 |
|---|
| PyTorch Attention | 0.84 | 0.86 | 2.35 |
| Megatron | 0.87 | 0.89 | 1.33 |
| Reformer | 4.30 | 7.76 | 14.60 |
| Local Attention | 1.40 | 1.60 | 2.06 |
| Linformer | 1.57 | 1.49 | 1.55 |
| Smyrf | 3.41 | 5.08 | 9.35 |
| LSformer | 3.08 | 3.10 | 4.26 |
| Block Sparse | 2.54 | 2.52 | 3.71 |
| Longformer | 2.47 | 2.49 | 2.51 |
| BigBird | 2.51 | 2.49 | 2.52 |
| FlashAttention | 0.43 | 0.41 | 0.95 |
| Block-Sparse FlashAttention | 0.44 | 0.44 | 0.45 |
Table 11: runtime (ms) by sequence length (part 1 of 4)
A dash means the method ran out of memory or does not support that length.
| Method | 1024 | 2048 | 4096 |
|---|
| PyTorch Attention | 8.29 | 31.75 | 124.19 |
| Megatron | 4.21 | 16.50 | - |
| Reformer | 28.74 | 57.79 | 116.34 |
| Local Attention | 6.06 | 20.94 | 42.01 |
| Linformer | 1.60 | 4.19 | 8.04 |
| Smyrf | 18.18 | 36.03 | 71.68 |
| LSformer | 10.90 | 31.59 | 61.72 |
| Block Sparse | 5.44 | 13.29 | 39.19 |
| Longformer | 3.10 | 10.39 | 22.49 |
| BigBird | 3.40 | 10.97 | 23.89 |
| FlashAttention | 2.55 | 9.56 | 37.49 |
| Block-Sparse FlashAttention | 0.89 | 1.95 | 4.12 |
Table 11: runtime (ms) by sequence length (part 2 of 4)
A dash means the method ran out of memory or does not support that length.
| Method | 8192 | 16384 | 32768 |
|---|
| PyTorch Attention | - | - | - |
| Megatron | - | - | - |
| Reformer | 237.57 | - | - |
| Local Attention | 84.08 | 168.48 | 339.45 |
| Linformer | 15.71 | 30.92 | 61.47 |
| Smyrf | 143.04 | 285.87 | - |
| LSformer | 121.51 | 241.18 | - |
| Block Sparse | - | - | - |
| Longformer | 60.44 | - | - |
| BigBird | 63.28 | - | - |
| FlashAttention | 147.75 | 586.61 | 2339.11 |
| Block-Sparse FlashAttention | 7.64 | 16.60 | 32.73 |
Table 11: runtime (ms) by sequence length (part 3 of 4)
A dash means the method ran out of memory or does not support that length.
| Method | 65536 |
|---|
| PyTorch Attention | - |
| Megatron | - |
| Reformer | - |
| Local Attention | - |
| Linformer | - |
| Smyrf | - |
| LSformer | - |
| Block Sparse | - |
| Longformer | - |
| BigBird | - |
| FlashAttention | 9341.30 |
| Block-Sparse FlashAttention | 64.11 |
Table 11: runtime (ms) by sequence length (part 4 of 4)
A dash means the method ran out of memory or does not support that length.
Table 21 in full: memory use (MB), combined pass, no dropout or masking
| Method | 128 | 256 | 512 |
|---|
| PyTorch Attention | 36 | 104 | 336 |
| Megatron | 36 | 104 | 336 |
| Reformer | 377 | 754 | 1508 |
| Local Attention | 53 | 110 | 232 |
| Linformer | 25 | 52 | 114 |
| Smyrf | 217 | 434 | 868 |
| LSformer | 72 | 152 | 333 |
| Block Sparse | 33 | 82 | 228 |
| Longformer | 30 | 61 | 124 |
| BigBird | 33 | 66 | 131 |
| FlashAttention | 22 | 44 | 104 |
| Block-Sparse FlashAttention | 22 | 44 | 104 |
Table 21: memory use (MB) by sequence length (part 1 of 4)
A dash means the method ran out of memory or does not support that length.
| Method | 1024 | 2048 | 4096 |
|---|
| PyTorch Attention | 1184 | 4416 | 17024 |
| Megatron | 1184 | 4416 | - |
| Reformer | 3016 | 6033 | 12067 |
| Local Attention | 592 | 1696 | 3392 |
| Linformer | 287 | 832 | 1652 |
| Smyrf | 1737 | 3474 | 6947 |
| LSformer | 796 | 2540 | 5068 |
| Block Sparse | 408 | 910 | 2401 |
| Longformer | 277 | 681 | 1370 |
| BigBird | 294 | 708 | 1431 |
| FlashAttention | 209 | 418 | 836 |
| Block-Sparse FlashAttention | 209 | 418 | 836 |
Table 21: memory use (MB) by sequence length (part 2 of 4)
A dash means the method ran out of memory or does not support that length.
| Method | 8192 | 16384 | 32768 |
|---|
| PyTorch Attention | - | - | - |
| Megatron | - | - | - |
| Reformer | 24134 | - | - |
| Local Attention | 6784 | 13568 | 27136 |
| Linformer | 3292 | 6572 | 13132 |
| Smyrf | 13894 | 27788 | - |
| LSformer | 10125 | 20240 | - |
| Block Sparse | - | - | - |
| Longformer | 2748 | - | - |
| BigBird | 2872 | - | - |
| FlashAttention | 1672 | 3344 | 6688 |
| Block-Sparse FlashAttention | 1672 | 3344 | 6690 |
Table 21: memory use (MB) by sequence length (part 3 of 4)
A dash means the method ran out of memory or does not support that length.
| Method | 65536 |
|---|
| PyTorch Attention | - |
| Megatron | - |
| Reformer | - |
| Local Attention | - |
| Linformer | 26252 |
| Smyrf | - |
| LSformer | - |
| Block Sparse | - |
| Longformer | - |
| BigBird | - |
| FlashAttention | 13376 |
| Block-Sparse FlashAttention | 13384 |
Table 21: memory use (MB) by sequence length (part 4 of 4)
A dash means the method ran out of memory or does not support that length.
Words to know
- Arithmetic intensity: Math operations done per byte of memory moved.
- Block-sparse: A pattern where only some blocks of a matrix are computed.
- Compute-bound: Limited by math speed, not by memory speed.
- CUDA: Nvidia's language for writing code that runs on GPUs.
- FLOP: One math operation, such as an add or a multiply.
- GPU: A chip that does the heavy math for training and running models.
- Gradient checkpointing: Recompute some values later instead of storing them.
- HBM: High bandwidth memory. The large but slower main memory of a GPU.
- IO-aware: Designed to count and cut reads and writes between memory levels.
- Kernel: One program that runs on a GPU.
- Kernel fusion: Joining several steps into one kernel, to load data only once.
- Memory-bound: Limited by memory speed, not by math speed.
- Perplexity: How surprised a model is by text. Lower is better.
- Quadratic: Cost that grows with the square of the input size.
- Self-attention: A step where each token looks at all other tokens to get context.
- SRAM: Small, very fast memory on the GPU chip.
- Structured matrix: A matrix with a pattern that lets it use less memory and time.
- Tiling: Working on a big matrix one small block at a time.
- Transformer: The standard network design for language and many other models.
Ask AI about this paper
Stuck on a word or an idea? Ask in plain words. The answer comes from the write-up on this page.
Jump to