Profile

Settings

Loading…

← Papers

Help

FAQ

Which features require signing in?

You can read the commentary, paper info, Model Structure and related papers of public papers without signing in. Sign in to manage your account or contact us about your inquiries.

Can I upload a PDF file?

Upload papers with an arXiv or DOI link; the commentary is public to everyone. Papers whose source and terms of use can't be verified, so the commentary can't be made public, can't be uploaded. Uploading PDF files and keeping papers private are for subscribers only, and a paper uploaded as a file is saved as private only. Searching for official info by title runs only when you press the button.

Are the figures and AI commentary accurate?

Figures come only from the original paper, and only those whose terms of use are verified are shown. The commentary is written by AI and may be wrong. Check important claims, numbers and figure context against the evidence in the original paper.

I want to report a copyright issue.

Terms of use and the source of the original paper are on the Paper info tab. If there's a problem, choose "Paper content, figures and copyright" under Contact us and send the paper link, the part in question, and evidence that you hold the rights. Receiving your report doesn't confirm any rights or remove anything right away. You can see the result of the review under My inquiries.

I forgot my password.

If you signed up with email, use Forgot password in the sign-in window to reset it with your verified email. If you signed up with Google, Naver or Kakao, change your password with that service.

What should I include in an inquiry?

Tell us which screen you were on and what you were doing when the problem happened, along with the paper link. Don't include personal information such as passwords, API keys, verification codes or phone numbers. Inquiries and replies are stored in Refivu and you can see them under My inquiries.

How do I delete my account?

In Settings, under My account, press Delete account. Review what will be deleted and complete identity verification to delete your account. For other requests, choose "Account" under Contact us.

Paper commentary

FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness

  • Problem Exact attention costs grow quadratically with sequence length, and on GPUs the wall-clock time is often set by moving the N × N attention matrix between HBM and on-chip SRAM rather than by arithmetic.
  • Method FlashAttention computes exact attention block by block, keeps only the output and softmax statistics for the backward pass, and fuses the steps into one GPU kernel so the attention matrix is never written to HBM.
  • Results BERT-large training reached the target accuracy 15% faster than the MLPerf 1.1 record (17.4 against 20.0 minutes on 8×A100 GPUs), and GPT-2 small trained up to 3× faster than the HuggingFace implementation.

Why FLOP savings did not give wall-clock speed

The self-attention module of a Transformer needs time and memory that grow with the square of the sequence length, which makes long contexts costly. Many approximate attention methods reduce the arithmetic to a linear or near-linear function of sequence length, yet many of them did not run faster in wall-clock time and gained little adoption.

The explanation given is that these methods optimize floating-point operation counts, which correlate poorly with run time, and they largely ignore the cost of moving data.

The proposed remedy is to make attention IO-aware, which means counting the reads and writes between the small, fast on-chip SRAM of the GPU and the larger, slower high bandwidth memory (HBM). The gap in speed between compute and memory has widened on GPUs, so operations that are limited by memory traffic, such as softmax and dropout, take a large share of the runtime.

Where standard attention spends its memory traffic

For Q, K and V in \(\mathbb{R}^{N\times d}\), standard attention forms \(S = QK^\top\), applies a row-wise softmax to obtain \(P = \mathrm{softmax}(S)\), and returns \(O = PV\). Both S and P are materialized in HBM, which requires \(O(N^2)\) memory. Since N is usually much larger than d, for example N = 1024 and d = 64 for GPT-2, the N × N matrices dominate the traffic.

Masking applied to S and dropout applied to P add further elementwise passes over the attention matrix. Earlier efforts fused some of these elementwise steps, such as masking with softmax, but the matrix still had to be stored between the stages.

Computing softmax one block at a time

Tiling splits Q, K and V into blocks and makes several passes over them, so that the softmax reduction is built up incrementally. Algorithm 1 chooses its block sizes from the SRAM size M and the head dimension d, and each block is loaded from HBM into SRAM before its computation.

For a vector x of length B, the maximum is \(m(x)=\max_i x_i\), the shifted exponentials are \(f(x)=[e^{x_1-m(x)},\dots,e^{x_B-m(x)}]\), the normalizer is \(\ell(x)=\sum_i f(x)_i\), and \(\mathrm{softmax}(x)=f(x)/\ell(x)\). The shift by the maximum keeps the exponentials numerically stable.

Splitting x into two halves \(x^{(1)}\) and \(x^{(2)}\), the maximum of x is the larger of the two half maxima, and the normalizer is recombined as \(\ell(x)=e^{m(x^{(1)})-m(x)}\ell(x^{(1)})+e^{m(x^{(2)})-m(x)}\ell(x^{(2)})\).

Keeping a running maximum and a running normalizer for each row is enough to add blocks one at a time. In Algorithm 1, the outer loop runs over blocks of K and V and the inner loop over blocks of Q, so each partial product is rescaled by the change in the running maximum and then added into the output block O_i. The updated normalizer and maximum are written back alongside the output, so the next block can continue from them.

Theorem 1 states that Algorithm 1 returns \(O = \mathrm{softmax}(QK^\top)V\) using \(O(N^2 d)\) FLOPs, with \(O(N)\) additional memory beyond the inputs and output. Figure 1 (left) shows the same two-loop layout, with the N × N matrix kept off HBM.

Recomputing attention in the backward pass

The backward pass of standard attention needs S and P to compute gradients for Q, K and V. FlashAttention stores only the output O and the softmax statistics m and ℓ, and rebuilds the attention blocks in SRAM from blocks of Q, K and V when needed. This is a form of selective gradient checkpointing, and recomputation of this kind is usually paid for with slower runs, whereas here the extra FLOPs are offset by fewer HBM accesses.

In the table accompanying Figure 2 (left), FLOPs rise from 66.6 to 75.2 GFLOPs, while HBM reads and writes fall from 40.3 GB to 4.4 GB and runtime falls from 41.7 ms to 7.3 ms. This is a comparison of standard attention with FlashAttention for GPT-2 medium with sequence length 1024, head dimension 64, 16 heads and batch size 64 on an A100 GPU.

The forward and backward steps run within one CUDA kernel that loads inputs from HBM, performs matrix multiply, softmax, optional masking and dropout, and a second matrix multiply, and writes the result back. Fusing these steps means the intermediate values never travel to HBM, which is the kernel fusion idea applied to the whole attention block.

How many HBM accesses the method saves, and why it is near optimal

Theorem 2 states that standard attention needs \(\Theta(Nd + N^2)\) HBM accesses. Up to 9× fewer HBM accesses than standard attention are reached for typical values of d and M.

The saving depends on the ratio of \(d^2\) to M, and for typical d of 64 to 128 and M around 100KB, \(d^2\) is many times smaller than M.

The proof works at \(M = \Theta(Nd)\), and the lower bound is taken over this subrange of M, not at every single SRAM size. Lower bounds stated in terms of M as a parameter are left as future work.

Block-sparse FlashAttention and its IO cost

For inputs Q, K and V and a mask \(\tilde M \in \{0,1\}^{N\times N}\), entries of S with \(\tilde M_{kl}=1\) keep their value, while entries with \(\tilde M_{kl}=0\) are set to \(-\infty\) before the softmax. The mask must have block form, so that \(\tilde M_{kl}\) equals \(M_{ij}\) with \(i=\lfloor k/B_r\rfloor\) and \(j=\lfloor l/B_c\rfloor\) for a smaller mask M.

Given the block mask, the algorithm is the same as Algorithm 1, except that zero blocks are skipped. The sparsity therefore multiplies the larger term of the IO complexity.

Sparsity is often set to \(N^{-1/2}\) or \(N^{-1}\log N\), which gives \(\Theta(N\sqrt{N})\) or \(\Theta(N\log N)\) IO complexity for large N. The downstream experiments use the fixed butterfly sparsity pattern.

End-to-end training results

BERT-large was trained with FlashAttention on Wikipedia, starting from the MLPerf initialization, until the target accuracy of 72.0% on masked language modeling was reached. Averaged over 10 runs on 8×A100 GPUs, this took 17.4 ± 1.4 minutes, against 20.0 ± 1.5 minutes for the Nvidia MLPerf 1.1 implementation, which the authors report as 15% slower.

On OpenWebText, GPT-2 small with FlashAttention took 2.7 days, against 9.5 days for the HuggingFace implementation and 4.7 days for Megatron-LM, all on 8×A100 GPUs. For GPT-2 medium, FlashAttention took 6.9 days, against 21.0 days for HuggingFace and 11.5 days for Megatron-LM. Perplexity is 18.2 for all three small-model implementations, while the medium model reaches 14.3 with FlashAttention and Megatron-LM and 14.2 with HuggingFace.

On the long-range arena, the standard Transformer averages 59.3, FlashAttention averages 59.8 with a 2.4× speedup, and block-sparse FlashAttention averages 59.6 with a 2.8× speedup. Each LRA task has a sequence length between 1024 and 4096, and the vanilla Transformer is run with either the standard or the FlashAttention implementation.

The approximate baselines in the same table average 54.9 for Linformer, 58.9 for Performer and 57.6 for Reformer. The block-sparse variant is faster than the approximate methods tested, and its accuracy stays close to the standard Transformer.

Longer sequences and new long-context results

GPT-2 small with FlashAttention at context length 4k reaches perplexity 17.5 in 3.6 days. Megatron-LM at context length 1k reaches perplexity 18.2 in 4.7 days, so the 4k run is described as 30% faster while achieving 0.7 better perplexity. At context length 2k with FlashAttention the model reaches perplexity 17.6 in 3.0 days.

Long document classification uses MIMIC-III and ECtHR, with a pretrained RoBERTa model whose positional embeddings are repeated to reach longer lengths. MIMIC-III averages 2,395 tokens per document, and ECtHR averages 2,197 tokens. On MIMIC-III, micro F1 rises from 52.8 at length 512 to 57.1 at length 16384, a gain of 4.3 points. On ECtHR, micro F1 rises from 72.2 at length 512 to 80.7 at length 8192, a gain of 8.5 points, and reaches 79.2 at length 16384.

The authors suggest the two datasets respond differently because MIMIC-III contains specialized medical text that may be more sensitive to changes in document length, whereas ECtHR contains general language.

On the Path-X and Path-256 tasks of the long-range arena, earlier Transformers either ran out of memory or stayed at random performance. Block-sparse FlashAttention reaches 63.1 accuracy on Path-256 at sequence length 64K, and 56.0 on Path-X.

Runtime and memory against attention baselines

FlashAttention runs up to 3× faster than the PyTorch attention implementation in forward plus backward runtime. Approximate attention runtimes cross over with FlashAttention between sequence lengths 512 and 1024.

Across the block sizes tested, the number of HBM accesses decides the forward runtime, which falls as the block size grows up to about 256. Beyond that point, other factors such as arithmetic operations take over, and larger blocks no longer fit in the small SRAM. Figure 2 (middle) and Figure 2 (right) show the block-size effect and the sparsity effect on runtime.

The memory footprint of FlashAttention and block-sparse FlashAttention grows linearly with sequence length. FlashAttention uses up to 20× less memory than exact attention baselines, and all baselines except Linformer run out of memory on the A100 before 64K. FlashAttention is 2× more memory-efficient than Linformer at the longest length tested.

Limitations

Each new IO-aware attention variant currently needs a new CUDA kernel written in a lower-level language than PyTorch, which takes substantial engineering effort. Implementations may not transfer across GPU architectures.

The authors propose a method that writes attention in a high-level language and compiles it to IO-aware CUDA, and extend the IO-aware view to other modules, since every layer of a deep network touches HBM.

The LRA accuracy results depend strongly on the tuning procedure, and the reproduced baselines are better than those in the original comparison. The long-document results cover one pretrained RoBERTa model with repeated positional embeddings and two datasets. The lower bound holds only over the stated range of M from d to Nd.

Paper info

Authors
Dao, Tri, Fu, Daniel Y., Ermon, Stefano, Rudra, Atri, Ré, Christopher
Venue
arXiv · Preprint
First published
2022-5-27
Added
2026-10-20
Updated
2022-6-23
Version
v2
arXiv
2205.14135
Original paper terms
arXiv non-exclusive 1.0
What we show
Paper info and commentary

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

Quote from the paper

Dao, Tri, Fu, Daniel Y., Ermon, Stefano, Rudra, Atri, Ré, Christopher (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135v2. https://arxiv.org/abs/2205.14135v2

BibTeX
@misc{tri2022flashattention,
  title = {{FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness}},
  author = {Dao, Tri and Fu, Daniel Y. and Ermon, Stefano and Rudra, Atri and Ré, Christopher},
  year = {2022},
  eprint = {2205.14135},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2205.14135v2}
}

See related papersBrowse other papers

Paper preview
Account security

Connect Google account

If you connect a Google account, you can sign in with it too.

Refivu

Delete account

Refivu
Refivu

Sign up