Skip to main content
GW
HomeWorkAI appsPapersAboutNotesStackLabPilotPlan↗ (opens in a new tab)INVST↗ (opens in a new tab)
Govind Waghmare

Finance systems and AI. Building in public from NYC.

Resume (PDF)Book 20 minEmail
HomeNotesWorkAboutStackPapersLabFor founders
XLinkedInGitHubllms.txt
© 2026 · New York City

Keyboard shortcuts

?
Open this list
g then h
Go to Home
g then w
Go to Work
g then n
Go to Notes
g then a
Go to About
c
Ask the AI guide
Esc
Close this list
Original paperAbstract
Open in new tab (opens in a new tab)
All papers
FoundationsClassic

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 27 May 2022 · 24 min read · arXiv 2205.14135

Share this paper

LinkedIn (opens in a new tab)X (opens in a new tab)WhatsApp (opens in a new tab)EmailDownload PDFExplainer (PDF), 1.0 MB

  • 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 times

faster 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 2
HuggingFaceMegatron-LMFlashAttention
0510152025Training time on 8 A100 GPUs (days)GPT-2 small9.5 days4.7 days2.7 daysGPT-2 medium21.0 days11.5 days6.9 days

Hover, tap or focus a bar to read its exact value.

ModelHuggingFace (days)Megatron-LM (days)FlashAttention (days)
GPT-2 small9.54.72.7
GPT-2 medium21.011.56.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

  1. A The abstract
  2. 1 Introduction
  3. 2 Background: GPUs and standard attention
  4. 3 FlashAttention: algorithm, analysis, extensions
  5. 3.1 An efficient algorithm with tiling and recomputation
  6. 3.2 Analysis: IO complexity of FlashAttention
  7. 3.3 Extension: block-sparse FlashAttention
  8. 4 Experiments: overview
  9. 4.1 Faster models with FlashAttention
  10. 4.2 Better models with longer sequences
  11. 4.3 Benchmarking attention
  12. 5 Limitations and future directions
  13. A Appendix A: related work
  14. B Appendix B: algorithm details
  15. C Appendix C: proofs
  16. D Appendix D: extension details
  17. E Appendix E: full experimental results
  18. W Words to know

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.
MemorySpeedSize
GPU SRAM19 TB/s20 MB
GPU HBM1.5 TB/s40 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.

Two kinds of operation

  • Operations are either compute-bound or memory-bound.
  • Arithmetic intensity measures this: math operations per byte of memory access.

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
  1. Load Q and K from HBM
  2. Compute scores S, write to HBM
  3. Read S, compute softmax P
  4. Write P to HBM
  5. Load P and V, compute O
  6. 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
  1. Split Q, K, V into blocks
  2. Load K, V block to SRAM
  3. Load one Q block to SRAM
  4. Compute scores and softmax on chip
  5. Rescale and update the output
  6. 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)
01020304050HBM reads and writes (GB)Standard attention40.3 GBFlashAttention4.4 GB

Hover, tap or focus a bar to read its exact value.

MethodHBM reads/writes (GB)
Standard attention40.3
FlashAttention4.4
MeasureStandardFlashAttention
GFLOPs66.675.2
HBM R/W (GB)40.34.4
Runtime (ms)41.77.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.
ImplementationTraining time (minutes)
Nvidia MLPerf 1.120.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 2
HuggingFaceMegatron-LMFlashAttention
0510152025Training time on 8 A100 GPUs (days)GPT-2 small9.5 days4.7 days2.7 daysGPT-2 medium21.0 days11.5 days6.9 days

Hover, tap or focus a bar to read its exact value.

ModelHuggingFace (days)Megatron-LM (days)FlashAttention (days)
GPT-2 small9.54.72.7
GPT-2 medium21.011.56.9
Model and implementationPerplexityTraining time (speedup)
GPT-2 small, HuggingFace18.29.5 days (1.0x)
GPT-2 small, Megatron-LM18.24.7 days (2.0x)
GPT-2 small, FlashAttention18.22.7 days (3.5x)
GPT-2 medium, HuggingFace14.221.0 days (1.0x)
GPT-2 medium, Megatron-LM14.311.5 days (1.8x)
GPT-2 medium, FlashAttention14.36.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
ModelListOpsTextRetrieval
Transformer36.063.681.6
FlashAttention37.663.981.4
Block-sparse FlashAttention37.063.081.3
Linformer35.655.977.7
Linear Attention38.863.280.7
Performer36.863.682.2
Local Attention36.160.276.7
Reformer36.563.878.5
Smyrf36.164.179.0

Table 3: long-range arena results (part 1 of 3)

ModelImagePathfinderAvg
Transformer42.372.759.3
FlashAttention43.572.759.8
Block-sparse FlashAttention43.673.359.6
Linformer37.867.654.9
Linear Attention42.672.559.6
Performer42.169.958.9
Local Attention40.666.656.0
Reformer39.669.457.6
Smyrf39.670.557.9

Table 3: long-range arena results (part 2 of 3)

ModelSpeedup
Transformer-
FlashAttention2.4x
Block-sparse FlashAttention2.8x
Linformer2.5x
Linear Attention2.3x
Performer1.8x
Local Attention1.7x
Reformer1.3x
Smyrf1.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 implementationContextPerplexityTraining time (speedup)
GPT-2 small, Megatron-LM1k18.24.7 days (1.0x)
GPT-2 small, FlashAttention1k18.22.7 days (1.7x)
GPT-2 small, FlashAttention2k17.63.0 days (1.6x)
GPT-2 small, FlashAttention4k17.53.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 lengthMIMIC-IIIECtHR
51252.872.2
102450.774.3
204851.777.1
409654.678.6
819256.480.7
1638457.179.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.
ModelPath-XPath-256
Transformerfailfail
Linformerfailfail
Linear Attentionfailfail
Performerfailfail
Local Attentionfailfail
Reformerfailfail
SMYRFfailfail
FlashAttention61.4fail
Block-sparse FlashAttention56.063.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 11
0306090120Forward + backward runtime at length 4096 (ms)PyTorch Attention124.19 msReformer116.34 msLocal Attention42.01 msLinformer8.04 msSmyrf71.68 msLSformer61.72 msBlock Sparse39.19 msLongformer22.49 msBigBird23.89 msFlashAttention37.49 msBlock-Sparse FlashAttention4.12 ms

Hover, tap or focus a bar to read its exact value.

MethodRuntime (ms)
PyTorch Attention124.19
Reformer116.34
Local Attention42.01
Linformer8.04
Smyrf71.68
LSformer61.72
Block Sparse39.19
Longformer22.49
BigBird23.89
FlashAttention37.49
Block-Sparse FlashAttention4.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.
Method128256512
Apex FMHA forward0.100.291.14
FlashAttention forward0.080.220.81
Apex FMHA backward0.170.521.81
FlashAttention backward0.200.532.00
Apex FMHA forward + backward0.270.812.95
FlashAttention forward + backward0.280.752.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.
DropoutMaskingPassTable
YesYesForwardTable 9
YesYesBackwardTable 10
YesYesCombinedTable 11
NoYesForwardTable 12
NoYesBackwardTable 13
NoYesCombinedTable 14
YesNoForwardTable 15
YesNoBackwardTable 16
YesNoCombinedTable 17
NoNoForwardTable 18
NoNoBackwardTable 19
NoNoCombinedTable 20
NoNoMemory (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
Method128256512
PyTorch Attention0.840.862.35
Megatron0.870.891.33
Reformer4.307.7614.60
Local Attention1.401.602.06
Linformer1.571.491.55
Smyrf3.415.089.35
LSformer3.083.104.26
Block Sparse2.542.523.71
Longformer2.472.492.51
BigBird2.512.492.52
FlashAttention0.430.410.95
Block-Sparse FlashAttention0.440.440.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.

Method102420484096
PyTorch Attention8.2931.75124.19
Megatron4.2116.50-
Reformer28.7457.79116.34
Local Attention6.0620.9442.01
Linformer1.604.198.04
Smyrf18.1836.0371.68
LSformer10.9031.5961.72
Block Sparse5.4413.2939.19
Longformer3.1010.3922.49
BigBird3.4010.9723.89
FlashAttention2.559.5637.49
Block-Sparse FlashAttention0.891.954.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.

Method81921638432768
PyTorch Attention---
Megatron---
Reformer237.57--
Local Attention84.08168.48339.45
Linformer15.7130.9261.47
Smyrf143.04285.87-
LSformer121.51241.18-
Block Sparse---
Longformer60.44--
BigBird63.28--
FlashAttention147.75586.612339.11
Block-Sparse FlashAttention7.6416.6032.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.

Method65536
PyTorch Attention-
Megatron-
Reformer-
Local Attention-
Linformer-
Smyrf-
LSformer-
Block Sparse-
Longformer-
BigBird-
FlashAttention9341.30
Block-Sparse FlashAttention64.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
Method128256512
PyTorch Attention36104336
Megatron36104336
Reformer3777541508
Local Attention53110232
Linformer2552114
Smyrf217434868
LSformer72152333
Block Sparse3382228
Longformer3061124
BigBird3366131
FlashAttention2244104
Block-Sparse FlashAttention2244104

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.

Method102420484096
PyTorch Attention1184441617024
Megatron11844416-
Reformer3016603312067
Local Attention59216963392
Linformer2878321652
Smyrf173734746947
LSformer79625405068
Block Sparse4089102401
Longformer2776811370
BigBird2947081431
FlashAttention209418836
Block-Sparse FlashAttention209418836

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.

Method81921638432768
PyTorch Attention---
Megatron---
Reformer24134--
Local Attention67841356827136
Linformer3292657213132
Smyrf1389427788-
LSformer1012520240-
Block Sparse---
Longformer2748--
BigBird2872--
FlashAttention167233446688
Block-Sparse FlashAttention167233446690

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.

Method65536
PyTorch Attention-
Megatron-
Reformer-
Local Attention-
Linformer26252
Smyrf-
LSformer-
Block Sparse-
Longformer-
BigBird-
FlashAttention13376
Block-Sparse FlashAttention13384

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.

Share this paper

LinkedIn (opens in a new tab)X (opens in a new tab)WhatsApp (opens in a new tab)EmailDownload PDFExplainer (PDF), 1.0 MB

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.

Read the original paper on arXiv: FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (opens in a new tab)

Jump to

One paper a week, in plain English

Every Monday: the new AI papers worth your time. Short lines, the key number, and what to do with it.

One email a week. Unsubscribe with one click. No spam.