2022-05-30 06:34:22 +08:00
# FlashAttention
2023-07-17 20:26:11 +08:00
This repository provides the official implementation of FlashAttention and
FlashAttention-2 from the
following papers.
2022-05-30 06:34:22 +08:00
2022-05-30 06:42:43 +08:00
**FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness**
2022-05-30 09:15:43 +08:00
Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré
2022-07-11 03:10:45 +08:00
Paper: https://arxiv.org/abs/2205.14135
IEEE Spectrum [article ](https://spectrum.ieee.org/mlperf-rankings-2022 ) about our submission to the MLPerf 2.0 benchmark using FlashAttention.
2022-05-30 06:39:17 +08:00

2022-05-30 06:34:22 +08:00
2023-07-17 20:26:11 +08:00
**FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning**
Tri Dao
2022-11-14 08:49:11 +08:00
2023-07-17 20:26:11 +08:00
Paper: https://tridao.me/publications/flash2/flash2.pdf
2022-11-14 08:49:11 +08:00
2023-07-17 20:26:11 +08:00

2022-11-29 20:13:51 +08:00
2023-07-17 20:26:11 +08:00
## Usage
2022-07-12 06:57:45 +08:00
2023-07-17 20:26:11 +08:00
We've been very happy to see FlashAttention being widely adopted in such a short
time after its release. This [page ](https://github.com/Dao-AILab/flash-attention/blob/main/usage.md )
contains a partial list of places where FlashAttention is being used.
2023-05-17 23:32:26 +08:00
2023-07-17 20:26:11 +08:00
FlashAttention and FlashAttention-2 are free to use and modify (see LICENSE).
Please cite and credit FlashAttention if you use it.
2022-07-12 06:57:45 +08:00
2023-04-12 14:32:35 +08:00
## Installation and features
2022-05-21 05:21:58 +08:00
2023-03-14 03:48:07 +08:00
Requirements:
2023-09-04 12:24:56 +08:00
- CUDA 11.6 and above.
2023-03-14 03:48:07 +08:00
- PyTorch 1.12 and above.
2023-10-06 05:00:45 +08:00
- Linux. Windows is not supported for now. If you have ideas on how to modify
the code to support Windows, please reach out via Github issue.
2023-03-14 03:48:07 +08:00
2023-05-20 00:40:21 +08:00
We recommend the
[Pytorch ](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch )
container from Nvidia, which has all the required tools to install FlashAttention.
2023-03-14 03:48:07 +08:00
To install:
2023-07-17 20:26:11 +08:00
1. Make sure that PyTorch is installed.
2. Make sure that `packaging` is installed (`pip install packaging`)
3. Make sure that `ninja` is installed and that it works correctly (e.g. `ninja
--version` then `echo $?` should return exit code 0). If not (sometimes `ninja
--version` then `echo $?` returns a nonzero exit code), uninstall then reinstall
2023-07-18 12:54:44 +08:00
`ninja` (`pip uninstall -y ninja && pip install ninja`). Without `ninja` ,
2023-07-17 20:26:11 +08:00
compiling can take a very long time (2h) since it does not use multiple CPU
cores. With `ninja` compiling takes 3-5 minutes on a 64-core machine.
4. Then:
2022-11-16 06:10:36 +08:00
```sh
2023-07-17 20:26:11 +08:00
pip install flash-attn --no-build-isolation
2022-11-16 06:10:36 +08:00
```
Alternatively you can compile from source:
2023-07-23 15:21:30 +08:00
```sh
2023-05-26 07:52:52 +08:00
python setup.py install
2022-05-21 05:21:58 +08:00
```
2023-07-18 14:17:47 +08:00
If your machine has less than 96GB of RAM and lots of CPU cores, `ninja` might
run too many parallel compilation jobs that could exhaust the amount of RAM. To
limit the number of parallel compilation jobs, you can set the environment
variable `MAX_JOBS` :
2023-07-23 15:21:30 +08:00
```sh
2023-07-18 14:17:47 +08:00
MAX_JOBS=4 pip install flash-attn --no-build-isolation
```
2023-07-17 20:26:11 +08:00
Interface: `src/flash_attention_interface.py`
2022-05-27 04:57:38 +08:00
2023-07-17 20:26:11 +08:00
FlashAttention-2 currently supports:
1. Ampere, Ada, or Hopper GPUs (e.g., A100, RTX 3090, RTX 4090, H100). Support for Turing
GPUs (T4, RTX 2080) is coming soon, please use FlashAttention 1.x for Turing
GPUs for now.
2. Datatype fp16 and bf16 (bf16 requires Ampere, Ada, or Hopper GPUs).
3. All head dimensions up to 256. Head dim > 192 backward requires A100/A800 or H100/H800.
2022-05-27 04:57:38 +08:00
2022-12-27 14:13:59 +08:00
## How to use FlashAttention
2023-07-17 20:26:11 +08:00
The main functions implement scaled dot product attention (softmax(Q @ K^T *
softmax_scale) @ V):
2023-07-23 15:21:30 +08:00
```python
2023-07-17 20:26:11 +08:00
from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
2022-12-27 14:13:59 +08:00
```
2023-07-23 15:21:30 +08:00
```python
2023-07-17 20:26:11 +08:00
flash_attn_qkvpacked_func(qkv, dropout_p=0.0, softmax_scale=None, causal=False):
"""dropout_p should be set to 0.0 during evaluation
If Q, K, V are already stacked into 1 tensor, this function will be faster than
calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation
of the gradients of Q, K, V.
Arguments:
qkv: (batch_size, seqlen, 3, nheads, headdim)
dropout_p: float. Dropout probability.
softmax_scale: float. The scaling of QK^T before applying softmax.
Default to 1 / sqrt(headdim).
causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
Return:
out: (batch_size, seqlen, nheads, headdim).
2023-07-23 15:21:30 +08:00
"""
2023-07-17 20:26:11 +08:00
```
2022-12-27 14:13:59 +08:00
2023-07-23 15:21:30 +08:00
```python
2023-07-17 20:26:11 +08:00
flash_attn_func(q, k, v, dropout_p=0.0, softmax_scale=None, causal=False):
"""dropout_p should be set to 0.0 during evaluation
Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads
2023-08-02 00:01:07 +08:00
than Q. Note that the number of heads in Q must be divisible by the number of heads in KV.
2023-07-17 20:26:11 +08:00
For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head
0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V.
Arguments:
q: (batch_size, seqlen, nheads, headdim)
k: (batch_size, seqlen, nheads_k, headdim)
v: (batch_size, seqlen, nheads_k, headdim)
dropout_p: float. Dropout probability.
softmax_scale: float. The scaling of QK^T before applying softmax.
Default to 1 / sqrt(headdim).
causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling).
Return:
out: (batch_size, seqlen, nheads, headdim).
2023-07-23 15:21:30 +08:00
"""
2022-12-27 14:13:59 +08:00
```
2023-07-17 20:26:11 +08:00
To see how these functions are used in a multi-head attention layer (which
includes QKV projection, output projection), see the MHA [implementation ](https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/modules/mha.py ).
2022-12-27 14:13:59 +08:00
2023-07-17 20:26:11 +08:00
## Upgrading from FlashAttention (1.x) to FlashAttention-2
2022-12-27 14:13:59 +08:00
2023-07-17 20:26:11 +08:00
These functions have been renamed:
- `flash_attn_unpadded_func` -> `flash_attn_varlen_func`
- `flash_attn_unpadded_qkvpacked_func` -> `flash_attn_varlen_qkvpacked_func`
- `flash_attn_unpadded_kvpacked_func` -> `flash_attn_varlen_kvpacked_func`
2022-12-27 14:13:59 +08:00
2023-07-17 20:26:11 +08:00
If the inputs have the same sequence lengths in the same batch, it is simpler
and faster to use these functions:
2023-07-23 15:21:30 +08:00
```python
2023-08-02 00:01:07 +08:00
flash_attn_qkvpacked_func(qkv, dropout_p=0.0, softmax_scale=None, causal=False)
2022-12-27 14:13:59 +08:00
```
2023-07-23 15:21:30 +08:00
```python
2023-07-17 20:26:11 +08:00
flash_attn_func(q, k, v, dropout_p=0.0, softmax_scale=None, causal=False)
2022-12-27 14:13:59 +08:00
```
2023-08-21 15:07:33 +08:00
## Changes in v2.1 (compared to v2.0)
If seqlen_q != seqlen_k and causal=True, the causal mask is aligned to the
bottom right corner of the attention matrix, instead of the top-left corner.
2023-08-25 14:53:15 +08:00
For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 =
masked out) is:
v2.0:
1 0 0 0 0
1 1 0 0 0
v2.1:
1 1 1 1 0
1 1 1 1 1
If seqlen_q = 5 and seqlen_k = 2, the causal mask is:
v2.0:
1 0
1 1
1 1
1 1
1 1
v2.1:
0 0
0 0
0 0
1 0
1 1
2023-08-21 15:07:33 +08:00
If the row of the mask is all zero, the output will be zero.
2022-12-27 14:13:59 +08:00
2023-07-17 20:26:11 +08:00
## Performance
2022-05-28 04:59:09 +08:00
2022-06-02 11:07:00 +08:00
We present expected speedup (combined forward + backward pass) and memory savings from using FlashAttention against PyTorch standard attention, depending on sequence length, on different GPUs (speedup depends on memory bandwidth - we see more speedup on slower GPU memory).
2022-06-05 08:27:51 +08:00
We currently have benchmarks for these GPUs:
* [A100 ](#a100 )
2023-07-17 20:26:11 +08:00
* [H100 ](#h100 )
<!-- * [RTX 3090 ](#rtx-3090 ) -->
<!-- * [T4 ](#t4 ) -->
2022-06-05 08:27:51 +08:00
2022-06-02 11:07:00 +08:00
### A100
2023-07-17 20:26:11 +08:00
We display FlashAttention speedup using these parameters:
* Head dimension 64 or 128, hidden dimension 2048 (i.e. either 32 or 16 heads).
* Sequence length 512, 1k, 2k, 4k, 8k, 16k.
* Batch size set to 16k / seqlen.
2022-05-28 04:59:09 +08:00
2022-06-02 11:07:00 +08:00
#### Speedup
2022-05-28 04:59:09 +08:00
2023-07-17 20:26:11 +08:00

2022-05-28 04:59:09 +08:00
2022-06-02 11:07:00 +08:00
#### Memory
2022-05-28 04:59:09 +08:00
2022-05-30 06:34:22 +08:00

2022-05-28 04:59:09 +08:00
We show memory savings in this graph (note that memory footprint is the same no matter if you use dropout or masking).
Memory savings are proportional to sequence length -- since standard attention has memory quadratic in sequence length, whereas FlashAttention has memory linear in sequence length.
We see 10X memory savings at sequence length 2K, and 20X at 4K.
As a result, FlashAttention can scale to much longer sequence lengths.
2022-05-27 04:57:38 +08:00
2023-07-17 20:26:11 +08:00
### H100
2022-06-02 11:07:00 +08:00
2023-07-17 20:26:11 +08:00

2022-06-02 11:07:00 +08:00
2023-07-17 20:26:11 +08:00
## Full model code and training script
2022-06-02 11:07:00 +08:00
2023-07-17 20:26:11 +08:00
We have released the full GPT model
[implementation ](https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/models/gpt.py ).
We also provide optimized implementations of other layers (e.g., MLP, LayerNorm,
cross-entropy loss, rotary embedding). Overall this speeds up training by 3-5x
compared to the baseline implementation from Huggingface, reaching up to 225
TFLOPs/sec per A100, equivalent to 72% model FLOPs utilization (we don't need
any activation checkpointing).
2022-06-05 08:27:51 +08:00
2023-07-17 20:26:11 +08:00
We also include a training
[script ](https://github.com/Dao-AILab/flash-attention/tree/main/training ) to
train GPT2 on Openwebtext and GPT3 on The Pile.
2022-06-05 08:27:51 +08:00
2023-07-17 20:26:11 +08:00
## Triton implementation of FlashAttention
2022-06-05 08:27:51 +08:00
2023-07-17 20:26:11 +08:00
Phil Tillet (OpenAI) has an experimental implementation of FlashAttention in Triton:
https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
2022-06-05 08:27:51 +08:00
2023-07-17 20:26:11 +08:00
As Triton is a higher-level language than CUDA, it might be easier to understand
and experiment with. The notations in the Triton implementation are also closer
to what's used in our paper.
2022-06-05 08:27:51 +08:00
2023-07-17 20:26:11 +08:00
We also have an experimental implementation in Triton that support attention
bias (e.g. ALiBi):
https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/flash_attn_triton.py
2022-06-05 08:27:51 +08:00
2022-07-23 05:54:09 +08:00
## Tests
We test that FlashAttention produces the same output and gradient as a reference
implementation, up to some numerical tolerance. In particular, we check that the
maximum numerical error of FlashAttention is at most twice the numerical error
of a baseline implementation in Pytorch (for different head dimensions, input
dtype, sequence length, causal / non-causal).
To run the tests:
2023-07-23 15:21:30 +08:00
```sh
2022-07-23 05:54:09 +08:00
pytest -q -s tests/test_flash_attn.py
```
2022-06-28 04:50:16 +08:00
## When you encounter issues
2023-07-18 12:54:44 +08:00
This new release of FlashAttention-2 has been tested on several GPT-style
2023-07-17 20:26:11 +08:00
models, mostly on A100 GPUs.
2022-06-28 04:50:16 +08:00
2023-07-18 12:54:44 +08:00
If you encounter bugs, please open a GitHub Issue!
2022-05-31 04:29:04 +08:00
## Citation
If you use this codebase, or otherwise found our work valuable, please cite:
```
2022-11-14 14:13:44 +08:00
@inproceedings {dao2022flashattention,
2022-11-22 18:12:22 +08:00
title={Flash{A}ttention: Fast and Memory-Efficient Exact Attention with {IO}-Awareness},
2022-05-31 04:29:04 +08:00
author={Dao, Tri and Fu, Daniel Y. and Ermon, Stefano and Rudra, Atri and R{\'e}, Christopher},
2022-11-14 14:13:44 +08:00
booktitle={Advances in Neural Information Processing Systems},
2022-05-31 04:29:04 +08:00
year={2022}
}
2023-07-17 20:26:11 +08:00
@article {dao2023flashattention2,
2023-08-30 02:15:33 +08:00
title={Flash{A}ttention-2: Faster Attention with Better Parallelism and Work Partitioning},
2023-07-17 20:26:11 +08:00
author={Dao, Tri},
year={2023}
}
2022-05-31 04:29:04 +08:00
```