Flash Attention
A memory-efficient attention computation algorithm
A memory-efficient attention computation algorithm
Flash Attention is an algorithm that performs the Transformer's self-attention operation in a memory-efficient way. Conventional attention uses memory proportional to the square of the sequence length (O(n^2)), but Flash Attention reduces this to linear (O(n)) using tiling and recomputation techniques.
Flash Attention, presented in 2022 by Tri Dao et al. of Stanford, is an IO-aware algorithm that takes the GPU memory hierarchy (HBM vs SRAM) into account. It performs computation in the GPU's high-speed SRAM and minimizes slow HBM accesses, improving speed and memory efficiency at the same time.
The core idea is to divide the attention matrix into small blocks (tiles) and compute them block by block, rather than storing the entire matrix in memory. The numerator and denominator of the softmax are accumulated online, and the values needed during backpropagation are recomputed (recomputation). It guarantees mathematically exact results while being 2 to 4 times faster.
Currently, almost all large LLMs, including GPT-4, Llama, and Claude, use Flash Attention. It saves 10x memory at a sequence length of 2K and 20x at 4K, making it a core technology for handling long contexts of 128K or more. Flash Attention 3 achieved an additional 1.5 to 2x speedup on the H100 GPU.
import torch
from torch.nn.functional import scaled_dot_product_attention
# PyTorch 2.0+에서 Flash Attention 자동 사용
# CUDA 11.6+, Ampere GPU (A100, RTX 30xx) 이상 필요
# 입력 텐서 준비 (batch, heads, seq_len, head_dim)
batch_size = 2
num_heads = 8
seq_len = 4096 # 긴 시퀀스
head_dim = 64
query = torch.randn(batch_size, num_heads, seq_len, head_dim,
device='cuda', dtype=torch.float16)
key = torch.randn(batch_size, num_heads, seq_len, head_dim,
device='cuda', dtype=torch.float16)
value = torch.randn(batch_size, num_heads, seq_len, head_dim,
device='cuda', dtype=torch.float16)
# scaled_dot_product_attention은 자동으로 Flash Attention 사용
# (조건 충족 시: CUDA, fp16/bf16, 적절한 텐서 shape)
with torch.backends.cuda.sdp_kernel(
enable_flash=True, # Flash Attention 활성화
enable_math=False, # 기본 수학 연산 비활성화
enable_mem_efficient=False # Memory Efficient Attention 비활성화
):
output = scaled_dot_product_attention(query, key, value)
print(f"Input shape: {query.shape}")
print(f"Output shape: {output.shape}")
# HuggingFace Transformers에서 Flash Attention 2 사용
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
torch_dtype=torch.float16,
attn_implementation="flash_attention_2", # Flash Attention 2 명시
device_map="auto"
)
# 메모리 사용량 비교
print(f"GPU Memory: {torch.cuda.max_memory_allocated() / 1e9:.2f} GB")
"Flash Attention is essential for handling a 32K context. With standard attention, you get OOM even on an A100 80GB, but with Flash Attention 2 you can also increase the batch size."
"Flash Attention is an IO-aware algorithm that divides the attention matrix into tiles, computes them in SRAM, and minimizes HBM accesses. It computes softmax online, reducing memory to O(n)."
"In HuggingFace, you can apply it with just one option, attn_implementation='flash_attention_2'. However, causal mask is the default, so you need to be careful with encoder-decoder models, and there's a downside that attention weights can't be visualized."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Flash Attention is supported only on NVIDIA Ampere (A100, RTX 30xx) or later. On V100 or RTX 20xx, errors occur or it falls back.
Flash Attention works only with FP16 or BF16. If you pass an FP32 tensor, it automatically falls back to the slower standard attention.
Use PyTorch 2.0+, cast to torch.float16 or torch.bfloat16, and verify an Ampere+ GPU. For HuggingFace, explicitly setting attn_implementation="flash_attention_2" is recommended.