FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning

Tri Dao

2023 · arXiv

FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning

Problem

Framing

FlashAttention removes quadratic memory traffic, but still leaves GPU throughput far below GEMM efficiency. FlashAttention-2 closes that gap with better work partitioning, fewer non-matmul operations, and sequence-parallel attention, reaching 50–73% of peak A100 FLOPs and 225 TFLOPs/s per GPU in GPT training.

Currently Used Methods

Foundational

Proposed Method

Architecture

The kernel keeps exact attention but changes how GPU work is assigned. It parallelizes a single head across sequence-length blocks and repartitions warps so QQ stays shared while KTK^T and VV tiles are split across warps, reducing shared-memory traffic.

Verified diagram: FlashAttention forward tiling with online softmax across key/value blocks, plus a warp-partition view where Q is shared and K^T/V are split across warps.

Verified diagram: intra-block warp partitioning where all warps access Q while K^T and V are sharded across four warps.

Loss / Objective

The method is an exact kernel rewrite.Its core forward update uses online softmax with fewer rescalings:

m(1)=rowmax(S(1)),(1)=rowsum ⁣(eS(1)m(1)),O~(1)=eS(1)m(1)V(1)\mathbf{m}^{(1)} = \operatorname{rowmax}(\mathbf{S}^{(1)}), \qquad \boldsymbol{\ell}^{(1)} = \operatorname{rowsum}\!\left(e^{\mathbf{S}^{(1)}-\mathbf{m}^{(1)}}\right), \qquad \tilde{\mathbf{O}}^{(1)} = e^{\mathbf{S}^{(1)}-\mathbf{m}^{(1)}} \mathbf{V}^{(1)} m(2)=max ⁣(m(1),rowmax(S(2))),(2)=em(1)m(2)(1)+rowsum ⁣(eS(2)m(2))\mathbf{m}^{(2)} = \max\!\left(\mathbf{m}^{(1)}, \operatorname{rowmax}(\mathbf{S}^{(2)})\right), \qquad \boldsymbol{\ell}^{(2)} = e^{\mathbf{m}^{(1)}-\mathbf{m}^{(2)}} \boldsymbol{\ell}^{(1)} + \operatorname{rowsum}\!\left(e^{\mathbf{S}^{(2)}-\mathbf{m}^{(2)}}\right) O(2)=diag ⁣(((2))1) ⁣(em(1)m(2)O~(1)+eS(2)m(2)V(2))\mathbf{O}^{(2)} = \operatorname{diag}\!\left((\boldsymbol{\ell}^{(2)})^{-1}\right)\!\left(e^{\mathbf{m}^{(1)}-\mathbf{m}^{(2)}} \tilde{\mathbf{O}}^{(1)} + e^{\mathbf{S}^{(2)}-\mathbf{m}^{(2)}} \mathbf{V}^{(2)}\right)

Sampling Rule / Algorithm

The exact attention target remains unchanged:

Attn(Q,K,V)=softmax ⁣(QKd)V\operatorname{Attn}(\mathbf{Q},\mathbf{K},\mathbf{V}) = \operatorname{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d}}\right)\mathbf{V}

FlashAttention-2 computes this by tiling over sequence blocks and parallelizing those blocks across thread blocks and warps.

Training Procedure

Evaluation

Datasets

Metrics

Headline results

Verified results plot: bar chart comparing PyTorch, FlashAttention, xFormers, FlashAttention Triton, and FlashAttention-2 throughput across sequence lengths; FlashAttention-2 is highest in every shown setting.

Ablations

Method Strengths and Weaknesses

Strengths

Weaknesses

Suggestions from the authors

Links

Prior Papers

Further Papers