SKILL.md
SKILL.mdBrowse 3 files
3,058 tokens
10,648 bytes
Token encoding: o200k_base
Snapshot 24fd22b
1---2name: flash-attention3description: Speed up long-sequence transformer training and inference.4version: 1.0.15author: Orchestra Research6license: MIT7dependencies: [flash-attn, torch, transformers]8platforms: [linux, macos]9metadata:10 hermes:11 tags: [Optimization, Flash Attention, Attention Optimization, Memory Efficiency, Speed Optimization, Long Context, PyTorch, SDPA, H100, FP8, Transformers]12 13---14 15# Flash Attention - Fast Memory-Efficient Attention16 17## Quick start18 19Flash Attention provides 2-4x speedup and 10-20x memory reduction for transformer attention through IO-aware tiling and recomputation.20 21**PyTorch native (easiest, PyTorch 2.2+)**:22```python23import torch24import torch.nn.functional as F25 26q = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16) # [batch, heads, seq, dim]27k = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)28v = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)29 30# Automatically uses Flash Attention if available31out = F.scaled_dot_product_attention(q, k, v)32```33 34**flash-attn library (more features)**:35```bash36pip install flash-attn --no-build-isolation37```38 39```python40from flash_attn import flash_attn_func41 42# q, k, v: [batch, seqlen, nheads, headdim]43out = flash_attn_func(q, k, v, dropout_p=0.0, causal=True)44```45 46## Common workflows47 48### Workflow 1: Enable in existing PyTorch model49 50Copy this checklist:51 52```53Flash Attention Integration:54- [ ] Step 1: Check PyTorch version (≥2.2)55- [ ] Step 2: Enable Flash Attention backend56- [ ] Step 3: Verify speedup with profiling57- [ ] Step 4: Test accuracy matches baseline58```59 60**Step 1: Check PyTorch version**61 62```bash63python -c "import torch; print(torch.__version__)"64# Should be ≥2.2.065```66 67If <2.2, upgrade:68```bash69pip install --upgrade torch70```71 72**Step 2: Enable Flash Attention backend**73 74Replace standard attention:75```python76# Before (standard attention)77attn_weights = torch.softmax(q @ k.transpose(-2, -1) / math.sqrt(d_k), dim=-1)78out = attn_weights @ v79 80# After (Flash Attention)81import torch.nn.functional as F82out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)83```84 85Force Flash Attention backend (`torch.backends.cuda.sdp_kernel` is deprecated; use86`torch.nn.attention.sdpa_kernel` with `SDPBackend`):87```python88from torch.nn.attention import SDPBackend, sdpa_kernel89 90with sdpa_kernel(SDPBackend.FLASH_ATTENTION):91 out = F.scaled_dot_product_attention(q, k, v)92```93 94**Step 3: Verify speedup with profiling**95 96```python97import torch.utils.benchmark as benchmark98 99def test_attention(use_flash):100 q, k, v = [torch.randn(2, 8, 2048, 64, device='cuda', dtype=torch.float16) for _ in range(3)]101 102 if use_flash:103 from torch.nn.attention import SDPBackend, sdpa_kernel104 with sdpa_kernel(SDPBackend.FLASH_ATTENTION):105 return F.scaled_dot_product_attention(q, k, v)106 else:107 attn = (q @ k.transpose(-2, -1) / 8.0).softmax(dim=-1)108 return attn @ v109 110# Benchmark111t_flash = benchmark.Timer(stmt='test_attention(True)', globals=globals())112t_standard = benchmark.Timer(stmt='test_attention(False)', globals=globals())113 114print(f"Flash: {t_flash.timeit(100).mean:.3f}s")115print(f"Standard: {t_standard.timeit(100).mean:.3f}s")116```117 118Expected: 2-4x speedup for sequences >512 tokens.119 120**Step 4: Test accuracy matches baseline**121 122```python123# Compare outputs124q, k, v = [torch.randn(1, 8, 512, 64, device='cuda', dtype=torch.float16) for _ in range(3)]125 126# Flash Attention127out_flash = F.scaled_dot_product_attention(q, k, v)128 129# Standard attention130attn_weights = torch.softmax(q @ k.transpose(-2, -1) / 8.0, dim=-1)131out_standard = attn_weights @ v132 133# Check difference134diff = (out_flash - out_standard).abs().max()135print(f"Max difference: {diff:.6f}")136# Should be <1e-3 for float16137```138 139### Workflow 2: Use flash-attn library for advanced features140 141For multi-query attention, sliding window, or H100 FP8.142 143Copy this checklist:144 145```146flash-attn Library Setup:147- [ ] Step 1: Install flash-attn library148- [ ] Step 2: Modify attention code149- [ ] Step 3: Enable advanced features150- [ ] Step 4: Benchmark performance151```152 153**Step 1: Install flash-attn library**154 155```bash156# NVIDIA GPUs (CUDA 12.0+)157pip install flash-attn --no-build-isolation158 159# Verify installation160python -c "from flash_attn import flash_attn_func; print('Success')"161```162 163**Step 2: Modify attention code**164 165```python166from flash_attn import flash_attn_func167 168# Input: [batch_size, seq_len, num_heads, head_dim]169# Transpose from [batch, heads, seq, dim] if needed170q = q.transpose(1, 2) # [batch, seq, heads, dim]171k = k.transpose(1, 2)172v = v.transpose(1, 2)173 174out = flash_attn_func(175 q, k, v,176 dropout_p=0.1,177 causal=True, # For autoregressive models178 window_size=(-1, -1), # No sliding window179 softmax_scale=None # Auto-scale180)181 182out = out.transpose(1, 2) # Back to [batch, heads, seq, dim]183```184 185**Step 3: Enable advanced features**186 187Multi-query attention (shared K/V across heads):188```python189from flash_attn import flash_attn_func190 191# q: [batch, seq, num_q_heads, dim]192# k, v: [batch, seq, num_kv_heads, dim] # Fewer KV heads193out = flash_attn_func(q, k, v) # Automatically handles MQA194```195 196Sliding window attention (local attention):197```python198# Only attend to window of 256 tokens before/after199out = flash_attn_func(200 q, k, v,201 window_size=(256, 256), # (left, right) window202 causal=True203)204```205 206**Step 4: Benchmark performance**207 208```python209import torch210from flash_attn import flash_attn_func211import time212 213q, k, v = [torch.randn(4, 4096, 32, 64, device='cuda', dtype=torch.float16) for _ in range(3)]214 215# Warmup216for _ in range(10):217 _ = flash_attn_func(q, k, v)218 219# Benchmark220torch.cuda.synchronize()221start = time.time()222for _ in range(100):223 out = flash_attn_func(q, k, v)224 torch.cuda.synchronize()225end = time.time()226 227print(f"Time per iteration: {(end-start)/100*1000:.2f}ms")228print(f"Memory allocated: {torch.cuda.max_memory_allocated()/1e9:.2f}GB")229```230 231### Workflow 3: H100 FP8 optimization (FlashAttention-3)232 233For maximum performance on Hopper GPUs (H100).234 235> **Important:** The pip package `flash-attn` (2.8.x) ships **FlashAttention-2 only** — it does236> **not** contain FA3 or FP8 H100 kernels, and `flash_attn_func` does **not** auto-use FP8.237> FlashAttention-3 is a separate **beta** build compiled from source from the repo's `hopper/`238> directory, exposed via the `flash_attn_interface` module. FA3 supports FP16/BF16 forward+backward239> and **FP8 forward only**.240 241```242FP8 Setup:243- [ ] Step 1: Verify Hopper (H100) GPU available244- [ ] Step 2: Build & install FlashAttention-3 from source (hopper/)245- [ ] Step 3: Use the FA3 interface (FP8 forward)246```247 248**Step 1: Verify H100 GPU**249 250```bash251nvidia-smi --query-gpu=name --format=csv252# Should show "H100" or "H800"253```254 255**Step 2: Build & install FlashAttention-3 from source**256 257FA3 is NOT included in `pip install flash-attn`. Build it from the `hopper/` subdirectory:258 259```bash260git clone https://github.com/Dao-AILab/flash-attention.git261cd flash-attention/hopper262python setup.py install263# (compilation is heavy and requires a CUDA toolchain + Hopper GPU)264```265 266**Step 3: Use the FA3 interface (FP8 forward)**267 268FA3 exposes its own module `flash_attn_interface` (distinct from the FA2 `flash_attn`).269FP8 is a **forward-only** path and expects `float8_e4m3fn` inputs:270 271```python272import torch273from flash_attn_interface import flash_attn_func # FA3 (hopper build), not `flash_attn`274 275# q, k, v: [batch, seqlen, nheads, headdim]276q = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)277k = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)278v = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)279 280# FP8 forward (inference / forward-only): cast to float8_e4m3fn281q_fp8 = q.to(torch.float8_e4m3fn)282k_fp8 = k.to(torch.float8_e4m3fn)283v_fp8 = v.to(torch.float8_e4m3fn)284 285out = flash_attn_func(q_fp8, k_fp8, v_fp8, causal=True)286# FP16/BF16 forward+backward is also supported by the FA3 interface.287```288 289## When to use vs alternatives290 291**Use Flash Attention when:**292- Training transformers with sequences >512 tokens293- Running inference with long context (>2K tokens)294- GPU memory constrained (OOM with standard attention)295- Need 2-4x speedup without accuracy loss296- Using PyTorch 2.2+ or can install flash-attn297 298**Use alternatives instead:**299- **Standard attention**: Sequences <256 tokens (overhead not worth it)300- **xFormers**: Need more attention variants (not just speed)301- **Memory-efficient attention**: CPU inference (Flash Attention needs GPU)302 303## Common issues304 305**Issue: ImportError: cannot import flash_attn**306 307Install with no-build-isolation flag:308```bash309pip install flash-attn --no-build-isolation310```311 312Or install CUDA toolkit first:313```bash314conda install cuda -c nvidia315pip install flash-attn --no-build-isolation316```317 318**Issue: Slower than expected (no speedup)**319 320Flash Attention benefits increase with sequence length:321- <512 tokens: Minimal speedup (10-20%)322- 512-2K tokens: 2-3x speedup323- >2K tokens: 3-4x speedup324 325Check sequence length is sufficient.326 327**Issue: RuntimeError: CUDA error**328 329Verify GPU supports Flash Attention:330```python331import torch332print(torch.cuda.get_device_capability())333# Should be ≥(7, 5) for Turing+334```335 336Flash Attention requires:337- Ampere (A100, A10): ✅ Full support338- Turing (T4): ✅ Supported339- Volta (V100): ❌ Not supported340 341**Issue: Accuracy degradation**342 343Check dtype is float16 or bfloat16 (not float32):344```python345q = q.to(torch.float16) # Or torch.bfloat16346```347 348Flash Attention uses float16/bfloat16 for speed. Float32 not supported.349 350## Advanced topics351 352**Integration with HuggingFace Transformers**: See [references/transformers-integration.md](references/transformers-integration.md) for enabling Flash Attention in BERT, GPT, Llama models.353 354**Performance benchmarks**: See [references/benchmarks.md](references/benchmarks.md) for detailed speed and memory comparisons across GPUs and sequence lengths.355 356## Hardware requirements357 358- **GPU**: NVIDIA Ampere+ (A100, A10, A30) or AMD MI200+359- **VRAM**: Same as standard attention (Flash Attention doesn't increase memory)360- **CUDA**: 12.0+ (11.8 minimum)361- **PyTorch**: 2.2+ for native support362 363**Not supported**: V100 (Volta), CPU inference364 365## Resources366 367- Paper: "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness" (NeurIPS 2022)368- Paper: "FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning" (ICLR 2024)369- Blog: https://tridao.me/blog/2024/flash3/370- GitHub: https://github.com/Dao-AILab/flash-attention371- PyTorch docs: https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html372 373 374 375 Discovery context
Discovered by repository scan. No exact path reference found in the snapshot’s root AGENTS.md.