Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Speed up long-sequence transformer training and inference.
.claude/skills/nousresearch-optimizing-attention-flash/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 281% | 0% |
| case-05 | ✗→✓ | ▲ Improved | 110% | 0% |
| case-14 | ✗→✓ | ▲ Improved | 293% | 0% |
| case-16 | ✗→✓ | ▲ Improved | 103% | 0% |
| case-19 | ✗→✓ | ▲ Improved | 333% | 0% |
Flash Attention provides 2-4x speedup and 10-20x memory reduction for transformer attention through IO-aware tiling and recomputation.
PyTorch native (easiest, PyTorch 2.2+):
pythonimport torch import torch.nn.functional as F q = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16) # [batch, heads, seq, dim] k = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16) v = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16) # Automatically uses Flash Attention if available out = F.scaled_dot_product_attention(q, k, v)
flash-attn library (more features):
bashpip install flash-attn --no-build-isolation
pythonfrom flash_attn import flash_attn_func # q, k, v: [batch, seqlen, nheads, headdim] out = flash_attn_func(q, k, v, dropout_p=0.0, causal=True)
Copy this checklist:
Flash Attention Integration:
- [ ] Step 1: Check PyTorch version (≥2.2)
- [ ] Step 2: Enable Flash Attention backend
- [ ] Step 3: Verify speedup with profiling
- [ ] Step 4: Test accuracy matches baselineStep 1: Check PyTorch version
bashpython -c "import torch; print(torch.__version__)" # Should be ≥2.2.0
If <2.2, upgrade:
bashpip install --upgrade torch
Step 2: Enable Flash Attention backend
Replace standard attention:
python# Before (standard attention) attn_weights = torch.softmax(q @ k.transpose(-2, -1) / math.sqrt(d_k), dim=-1) out = attn_weights @ v # After (Flash Attention) import torch.nn.functional as F out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
Force Flash Attention backend (torch.backends.cuda.sdp_kernel is deprecated; use torch.nn.attention.sdpa_kernel with SDPBackend):
pythonfrom torch.nn.attention import SDPBackend, sdpa_kernel with sdpa_kernel(SDPBackend.FLASH_ATTENTION): out = F.scaled_dot_product_attention(q, k, v)
Step 3: Verify speedup with profiling
pythonimport torch.utils.benchmark as benchmark def test_attention(use_flash): q, k, v = [torch.randn(2, 8, 2048, 64, device='cuda', dtype=torch.float16) for _ in range(3)] if use_flash: from torch.nn.attention import SDPBackend, sdpa_kernel with sdpa_kernel(SDPBackend.FLASH_ATTENTION): return F.scaled_dot_product_attention(q, k, v) else: attn = (q @ k.transpose(-2, -1) / 8.0).softmax(dim=-1) return attn @ v # Benchmark t_flash = benchmark.Timer(stmt='test_attention(True)', globals=globals()) t_standard = benchmark.Timer(stmt='test_attention(False)', globals=globals()) print(f"Flash: {t_flash.timeit(100).mean:.3f}s") print(f"Standard: {t_standard.timeit(100).mean:.3f}s")
Expected: 2-4x speedup for sequences >512 tokens.
Step 4: Test accuracy matches baseline
python# Compare outputs q, k, v = [torch.randn(1, 8, 512, 64, device='cuda', dtype=torch.float16) for _ in range(3)] # Flash Attention out_flash = F.scaled_dot_product_attention(q, k, v) # Standard attention attn_weights = torch.softmax(q @ k.transpose(-2, -1) / 8.0, dim=-1) out_standard = attn_weights @ v # Check difference diff = (out_flash - out_standard).abs().max() print(f"Max difference: {diff:.6f}") # Should be <1e-3 for float16
For multi-query attention, sliding window, or H100 FP8.
Copy this checklist:
flash-attn Library Setup:
- [ ] Step 1: Install flash-attn library
- [ ] Step 2: Modify attention code
- [ ] Step 3: Enable advanced features
- [ ] Step 4: Benchmark performanceStep 1: Install flash-attn library
bash# NVIDIA GPUs (CUDA 12.0+) pip install flash-attn --no-build-isolation # Verify installation python -c "from flash_attn import flash_attn_func; print('Success')"
Step 2: Modify attention code
pythonfrom flash_attn import flash_attn_func # Input: [batch_size, seq_len, num_heads, head_dim] # Transpose from [batch, heads, seq, dim] if needed q = q.transpose(1, 2) # [batch, seq, heads, dim] k = k.transpose(1, 2) v = v.transpose(1, 2) out = flash_attn_func( q, k, v, dropout_p=0.1, causal=True, # For autoregressive models window_size=(-1, -1), # No sliding window softmax_scale=None # Auto-scale ) out = out.transpose(1, 2) # Back to [batch, heads, seq, dim]
Step 3: Enable advanced features
Multi-query attention (shared K/V across heads):
pythonfrom flash_attn import flash_attn_func # q: [batch, seq, num_q_heads, dim] # k, v: [batch, seq, num_kv_heads, dim] # Fewer KV heads out = flash_attn_func(q, k, v) # Automatically handles MQA
Sliding window attention (local attention):
python# Only attend to window of 256 tokens before/after out = flash_attn_func( q, k, v, window_size=(256, 256), # (left, right) window causal=True )
Step 4: Benchmark performance
pythonimport torch from flash_attn import flash_attn_func import time q, k, v = [torch.randn(4, 4096, 32, 64, device='cuda', dtype=torch.float16) for _ in range(3)] # Warmup for _ in range(10): _ = flash_attn_func(q, k, v) # Benchmark torch.cuda.synchronize() start = time.time() for _ in range(100): out = flash_attn_func(q, k, v) torch.cuda.synchronize() end = time.time() print(f"Time per iteration: {(end-start)/100*1000:.2f}ms") print(f"Memory allocated: {torch.cuda.max_memory_allocated()/1e9:.2f}GB")
For maximum performance on Hopper GPUs (H100).
> Important: The pip package flash-attn (2.8.x) ships FlashAttention-2 only — it does > not contain FA3 or FP8 H100 kernels, and flash_attn_func does not auto-use FP8. > FlashAttention-3 is a separate beta build compiled from source from the repo's hopper/ > directory, exposed via the flash_attn_interface module. FA3 supports FP16/BF16 forward+backward > and FP8 forward only.
FP8 Setup:
- [ ] Step 1: Verify Hopper (H100) GPU available
- [ ] Step 2: Build & install FlashAttention-3 from source (hopper/)
- [ ] Step 3: Use the FA3 interface (FP8 forward)Step 1: Verify H100 GPU
bashnvidia-smi --query-gpu=name --format=csv # Should show "H100" or "H800"
Step 2: Build & install FlashAttention-3 from source
FA3 is NOT included in pip install flash-attn. Build it from the hopper/ subdirectory:
bashgit clone https://github.com/Dao-AILab/flash-attention.git cd flash-attention/hopper python setup.py install # (compilation is heavy and requires a CUDA toolchain + Hopper GPU)
Step 3: Use the FA3 interface (FP8 forward)
FA3 exposes its own module flash_attn_interface (distinct from the FA2 flash_attn). FP8 is a forward-only path and expects float8_e4m3fn inputs:
pythonimport torch from flash_attn_interface import flash_attn_func # FA3 (hopper build), not `flash_attn` # q, k, v: [batch, seqlen, nheads, headdim] q = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16) k = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16) v = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16) # FP8 forward (inference / forward-only): cast to float8_e4m3fn q_fp8 = q.to(torch.float8_e4m3fn) k_fp8 = k.to(torch.float8_e4m3fn) v_fp8 = v.to(torch.float8_e4m3fn) out = flash_attn_func(q_fp8, k_fp8, v_fp8, causal=True) # FP16/BF16 forward+backward is also supported by the FA3 interface.
Use Flash Attention when:
Use alternatives instead:
Issue: ImportError: cannot import flash_attn
Install with no-build-isolation flag:
bashpip install flash-attn --no-build-isolation
Or install CUDA toolkit first:
bashconda install cuda -c nvidia pip install flash-attn --no-build-isolation
Issue: Slower than expected (no speedup)
Flash Attention benefits increase with sequence length:
Check sequence length is sufficient.
Issue: RuntimeError: CUDA error
Verify GPU supports Flash Attention:
pythonimport torch print(torch.cuda.get_device_capability()) # Should be ≥(7, 5) for Turing+
Flash Attention requires:
Issue: Accuracy degradation
Check dtype is float16 or bfloat16 (not float32):
pythonq = q.to(torch.float16) # Or torch.bfloat16
Flash Attention uses float16/bfloat16 for speed. Float32 not supported.
Integration with HuggingFace Transformers: See references/transformers-integration.md for enabling Flash Attention in BERT, GPT, Llama models.
Performance benchmarks: See references/benchmarks.md for detailed speed and memory comparisons across GPUs and sequence lengths.
Not supported: V100 (Volta), CPU inference
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→pass | 5,892 | 7,371 | +25% | 1 | 1 | 0% | 1,297 | 4,938 | +281% | 0 | 0 | — |
case-02 | pass→pass | 4,446 | 4,493 | +1% | 1 | 1 | 0% | 727 | 4,126 | +468% | 0 | 0 | — |
case-03 | pass→pass | 4,520 | 4,533 | +0% | 1 | 1 | 0% | 933 | 4,379 | +369% | 0 | 0 | — |
case-04 | pass→pass | 16,189 | 11,725 | -28% | 1 | 1 | 0% | 2,759 | 5,619 | +104% | 0 | 0 | — |
case-05 | fail→pass | 13,280 | 9,108 | -31% | 1 | 1 | 0% | 2,355 | 4,943 | +110% | 0 | 0 | — |
case-06 | pass→pass | 14,839 | 10,413 | -30% | 1 | 1 | 0% | 2,363 | 5,152 | +118% | 0 | 0 | — |
case-07 | pass→pass | 15,164 | 11,435 | -25% | 1 | 1 | 0% | 2,893 | 5,556 | +92% | 0 | 0 | — |
case-08 | pass→pass | 9,326 | 4,234 | -55% | 1 | 1 | 0% | 1,853 | 4,270 | +130% | 0 | 0 | — |
case-09 | pass→pass | 6,021 | 3,673 | -39% | 1 | 1 | 0% | 1,145 | 4,198 | +267% | 0 | 0 | — |
case-10 | pass→pass | 11,346 | 6,889 | -39% | 1 | 1 | 0% | 1,959 | 4,688 | +139% | 0 | 0 | — |
case-11 | pass→pass | 6,663 | 4,462 | -33% | 1 | 1 | 0% | 1,329 | 4,299 | +223% | 0 | 0 | — |
case-12 | pass→pass | 9,524 | 8,029 | -16% | 1 | 1 | 0% | 1,764 | 5,013 | +184% | 0 | 0 | — |
case-13 | pass→pass | 10,652 | 5,262 | -51% | 1 | 1 | 0% | 1,886 | 4,458 | +136% | 0 | 0 | — |
case-14 | fail→pass | 5,311 | 3,168 | -40% | 1 | 1 | 0% | 1,015 | 3,984 | +293% | 0 | 0 | — |
case-15 | fail→fail | 13,037 | 11,077 | -15% | 1 | 1 | 0% | 2,254 | 5,478 | +143% | 0 | 0 | — |
case-16 | fail→pass | 12,380 | 6,387 | -48% | 1 | 1 | 0% | 2,280 | 4,638 | +103% | 0 | 0 | — |
case-17 | pass→pass | 12,723 | 10,643 | -16% | 1 | 1 | 0% | 2,379 | 5,417 | +128% | 0 | 0 | — |
case-18 | pass→pass | 3,200 | 2,874 | -10% | 1 | 1 | 0% | 518 | 3,825 | +638% | 0 | 0 | — |
case-19 | fail→pass | 21,811 | 6,987 | -68% | 1 | 1 | 0% | 1,085 | 4,695 | +333% | 0 | 0 | — |
case-20 | pass→pass | 11,749 | 9,859 | -16% | 1 | 1 | 0% | 2,168 | 5,404 | +149% | 0 | 0 | — |
case-21 | pass→pass | 17,795 | 12,821 | -28% | 1 | 1 | 0% | 3,030 | 5,471 | +81% | 0 | 0 | — |
case-22 | pass→pass | 7,648 | 5,556 | -27% | 1 | 1 | 0% | 1,395 | 4,491 | +222% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted, and 21 counted toward the lift figure. The other 1 produced results that are not comparable between the two arms, so they are excluded from the headline rather than averaged into it. The headline lift of +23 percentage points is the difference between those two pass rates over the 21 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.