[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71Q4SEVCNE7S7DAXWDB3KS6":3,"skill-same:01M71Q4SEVCNE7S7DAXWDB3KS6":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":13,"repositoryHtmlUrl":59,"repositoryHomepageUrl":6,"ownerHtmlUrl":60,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":61,"install":62,"resources":75},"01M71Q4SEVCNE7S7DAXWDB3KS6","optimizing-attention-flash",null,"Optimizes transformer attention with Flash Attention for 2-4x speedup and 10-20x memory reduction. Use when training\u002Frunning transformers with long sequences (>512 tokens), encountering GPU memory issues with attention, or need faster inference. Supports PyTorch native SDPA, flash-attn library, H100 FP8, and sliding window attention.","gjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN","gjbvsjjvgm-sketch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F278511911?v=4","01M71F3JXKZQ70H2KCHHTXKZDA","01M71PENEVFN19DBZFNHJPCHQ7",0,"MIT","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Foptional-skills\u002Fmlops\u002Fflash-attention\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"flash","optimizing attention flash","attention","Flash Attention","sequences","when","window","native","H100","SDPA","Speed Optimization","Memory Efficiency","Attention Optimization","memory","efficiency","Transformers","library","issues","training","pytorch","2026-11-10 13:02:02",false,"---\nname: optimizing-attention-flash\ndescription: Optimizes transformer attention with Flash Attention for 2-4x speedup and 10-20x memory reduction. Use when training\u002Frunning transformers with long sequences (>512 tokens), encountering GPU memory issues with attention, or need faster inference. Supports PyTorch native SDPA, flash-attn library, H100 FP8, and sliding window attention.\nversion: 1.0.0\nauthor: Orchestra Research\nlicense: MIT\ndependencies: [flash-attn, torch, transformers]\nmetadata:\n  hermes:\n    tags: [Optimization, Flash Attention, Attention Optimization, Memory Efficiency, Speed Optimization, Long Context, PyTorch, SDPA, H100, FP8, Transformers]\n\n---\n\n# Flash Attention - Fast Memory-Efficient Attention\n\n## Quick start\n\nFlash Attention provides 2-4x speedup and 10-20x memory reduction for transformer attention through IO-aware tiling and recomputation.\n\n**PyTorch native (easiest, PyTorch 2.2+)**:\n```python\nimport torch\nimport torch.nn.functional as F\n\nq = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)  # [batch, heads, seq, dim]\nk = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\nv = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\n\n# Automatically uses Flash Attention if available\nout = F.scaled_dot_product_attention(q, k, v)\n```\n\n**flash-attn library (more features)**:\n```bash\npip install flash-attn --no-build-isolation\n```\n\n```python\nfrom flash_attn import flash_attn_func\n\n# q, k, v: [batch, seqlen, nheads, headdim]\nout = flash_attn_func(q, k, v, dropout_p=0.0, causal=True)\n```\n\n## Common workflows\n\n### Workflow 1: Enable in existing PyTorch model\n\nCopy this checklist:\n\n```\nFlash Attention Integration:\n- [ ] Step 1: Check PyTorch version (≥2.2)\n- [ ] Step 2: Enable Flash Attention backend\n- [ ] Step 3: Verify speedup with profiling\n- [ ] Step 4: Test accuracy matches baseline\n```\n\n**Step 1: Check PyTorch version**\n\n```bash\npython -c \"import torch; print(torch.__version__)\"\n# Should be ≥2.2.0\n```\n\nIf \u003C2.2, upgrade:\n```bash\npip install --upgrade torch\n```\n\n**Step 2: Enable Flash Attention backend**\n\nReplace standard attention:\n```python\n# Before (standard attention)\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F math.sqrt(d_k), dim=-1)\nout = attn_weights @ v\n\n# After (Flash Attention)\nimport torch.nn.functional as F\nout = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)\n```\n\nForce Flash Attention backend:\n```python\nwith torch.backends.cuda.sdp_kernel(\n    enable_flash=True,\n    enable_math=False,\n    enable_mem_efficient=False\n):\n    out = F.scaled_dot_product_attention(q, k, v)\n```\n\n**Step 3: Verify speedup with profiling**\n\n```python\nimport torch.utils.benchmark as benchmark\n\ndef test_attention(use_flash):\n    q, k, v = [torch.randn(2, 8, 2048, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\n\n    if use_flash:\n        with torch.backends.cuda.sdp_kernel(enable_flash=True):\n            return F.scaled_dot_product_attention(q, k, v)\n    else:\n        attn = (q @ k.transpose(-2, -1) \u002F 8.0).softmax(dim=-1)\n        return attn @ v\n\n# Benchmark\nt_flash = benchmark.Timer(stmt='test_attention(True)', globals=globals())\nt_standard = benchmark.Timer(stmt='test_attention(False)', globals=globals())\n\nprint(f\"Flash: {t_flash.timeit(100).mean:.3f}s\")\nprint(f\"Standard: {t_standard.timeit(100).mean:.3f}s\")\n```\n\nExpected: 2-4x speedup for sequences >512 tokens.\n\n**Step 4: Test accuracy matches baseline**\n\n```python\n# Compare outputs\nq, k, v = [torch.randn(1, 8, 512, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\n\n# Flash Attention\nout_flash = F.scaled_dot_product_attention(q, k, v)\n\n# Standard attention\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F 8.0, dim=-1)\nout_standard = attn_weights @ v\n\n# Check difference\ndiff = (out_flash - out_standard).abs().max()\nprint(f\"Max difference: {diff:.6f}\")\n# Should be \u003C1e-3 for float16\n```\n\n### Workflow 2: Use flash-attn library for advanced features\n\nFor multi-query attention, sliding window, or H100 FP8.\n\nCopy this checklist:\n\n```\nflash-attn Library Setup:\n- [ ] Step 1: Install flash-attn library\n- [ ] Step 2: Modify attention code\n- [ ] Step 3: Enable advanced features\n- [ ] Step 4: Benchmark performance\n```\n\n**Step 1: Install flash-attn library**\n\n```bash\n# NVIDIA GPUs (CUDA 12.0+)\npip install flash-attn --no-build-isolation\n\n# Verify installation\npython -c \"from flash_attn import flash_attn_func; print('Success')\"\n```\n\n**Step 2: Modify attention code**\n\n```python\nfrom flash_attn import flash_attn_func\n\n# Input: [batch_size, seq_len, num_heads, head_dim]\n# Transpose from [batch, heads, seq, dim] if needed\nq = q.transpose(1, 2)  # [batch, seq, heads, dim]\nk = k.transpose(1, 2)\nv = v.transpose(1, 2)\n\nout = flash_attn_func(\n    q, k, v,\n    dropout_p=0.1,\n    causal=True,  # For autoregressive models\n    window_size=(-1, -1),  # No sliding window\n    softmax_scale=None  # Auto-scale\n)\n\nout = out.transpose(1, 2)  # Back to [batch, heads, seq, dim]\n```\n\n**Step 3: Enable advanced features**\n\nMulti-query attention (shared K\u002FV across heads):\n```python\nfrom flash_attn import flash_attn_func\n\n# q: [batch, seq, num_q_heads, dim]\n# k, v: [batch, seq, num_kv_heads, dim]  # Fewer KV heads\nout = flash_attn_func(q, k, v)  # Automatically handles MQA\n```\n\nSliding window attention (local attention):\n```python\n# Only attend to window of 256 tokens before\u002Fafter\nout = flash_attn_func(\n    q, k, v,\n    window_size=(256, 256),  # (left, right) window\n    causal=True\n)\n```\n\n**Step 4: Benchmark performance**\n\n```python\nimport torch\nfrom flash_attn import flash_attn_func\nimport time\n\nq, k, v = [torch.randn(4, 4096, 32, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\n\n# Warmup\nfor _ in range(10):\n    _ = flash_attn_func(q, k, v)\n\n# Benchmark\ntorch.cuda.synchronize()\nstart = time.time()\nfor _ in range(100):\n    out = flash_attn_func(q, k, v)\n    torch.cuda.synchronize()\nend = time.time()\n\nprint(f\"Time per iteration: {(end-start)\u002F100*1000:.2f}ms\")\nprint(f\"Memory allocated: {torch.cuda.max_memory_allocated()\u002F1e9:.2f}GB\")\n```\n\n### Workflow 3: H100 FP8 optimization (FlashAttention-3)\n\nFor maximum performance on H100 GPUs.\n\n```\nFP8 Setup:\n- [ ] Step 1: Verify H100 GPU available\n- [ ] Step 2: Install flash-attn with FP8 support\n- [ ] Step 3: Convert inputs to FP8\n- [ ] Step 4: Run with FP8 attention\n```\n\n**Step 1: Verify H100 GPU**\n\n```bash\nnvidia-smi --query-gpu=name --format=csv\n# Should show \"H100\" or \"H800\"\n```\n\n**Step 2: Install flash-attn with FP8 support**\n\n```bash\npip install flash-attn --no-build-isolation\n# FP8 support included for H100\n```\n\n**Step 3: Convert inputs to FP8**\n\n```python\nimport torch\n\nq = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\nk = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\nv = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\n\n# Convert to float8_e4m3 (FP8)\nq_fp8 = q.to(torch.float8_e4m3fn)\nk_fp8 = k.to(torch.float8_e4m3fn)\nv_fp8 = v.to(torch.float8_e4m3fn)\n```\n\n**Step 4: Run with FP8 attention**\n\n```python\nfrom flash_attn import flash_attn_func\n\n# FlashAttention-3 automatically uses FP8 kernels on H100\nout = flash_attn_func(q_fp8, k_fp8, v_fp8)\n# Result: ~1.2 PFLOPS, 1.5-2x faster than FP16\n```\n\n## When to use vs alternatives\n\n**Use Flash Attention when:**\n- Training transformers with sequences >512 tokens\n- Running inference with long context (>2K tokens)\n- GPU memory constrained (OOM with standard attention)\n- Need 2-4x speedup without accuracy loss\n- Using PyTorch 2.2+ or can install flash-attn\n\n**Use alternatives instead:**\n- **Standard attention**: Sequences \u003C256 tokens (overhead not worth it)\n- **xFormers**: Need more attention variants (not just speed)\n- **Memory-efficient attention**: CPU inference (Flash Attention needs GPU)\n\n## Common issues\n\n**Issue: ImportError: cannot import flash_attn**\n\nInstall with no-build-isolation flag:\n```bash\npip install flash-attn --no-build-isolation\n```\n\nOr install CUDA toolkit first:\n```bash\nconda install cuda -c nvidia\npip install flash-attn --no-build-isolation\n```\n\n**Issue: Slower than expected (no speedup)**\n\nFlash Attention benefits increase with sequence length:\n- \u003C512 tokens: Minimal speedup (10-20%)\n- 512-2K tokens: 2-3x speedup\n- >2K tokens: 3-4x speedup\n\nCheck sequence length is sufficient.\n\n**Issue: RuntimeError: CUDA error**\n\nVerify GPU supports Flash Attention:\n```python\nimport torch\nprint(torch.cuda.get_device_capability())\n# Should be ≥(7, 5) for Turing+\n```\n\nFlash Attention requires:\n- Ampere (A100, A10): ✅ Full support\n- Turing (T4): ✅ Supported\n- Volta (V100): ❌ Not supported\n\n**Issue: Accuracy degradation**\n\nCheck dtype is float16 or bfloat16 (not float32):\n```python\nq = q.to(torch.float16)  # Or torch.bfloat16\n```\n\nFlash Attention uses float16\u002Fbfloat16 for speed. Float32 not supported.\n\n## Advanced topics\n\n**Integration with HuggingFace Transformers**: See [references\u002Ftransformers-integration.md](references\u002Ftransformers-integration.md) for enabling Flash Attention in BERT, GPT, Llama models.\n\n**Performance benchmarks**: See [references\u002Fbenchmarks.md](references\u002Fbenchmarks.md) for detailed speed and memory comparisons across GPUs and sequence lengths.\n\n**Algorithm details**: See [references\u002Falgorithm.md](references\u002Falgorithm.md) for tiling strategy, recomputation, and IO complexity analysis.\n\n**Advanced features**: See [references\u002Fadvanced-features.md](references\u002Fadvanced-features.md) for rotary embeddings, ALiBi, paged KV cache, and custom attention masks.\n\n## Hardware requirements\n\n- **GPU**: NVIDIA Ampere+ (A100, A10, A30) or AMD MI200+\n- **VRAM**: Same as standard attention (Flash Attention doesn't increase memory)\n- **CUDA**: 12.0+ (11.8 minimum)\n- **PyTorch**: 2.2+ for native support\n\n**Not supported**: V100 (Volta), CPU inference\n\n## Resources\n\n- Paper: \"FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness\" (NeurIPS 2022)\n- Paper: \"FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning\" (ICLR 2024)\n- Blog: https:\u002F\u002Ftridao.me\u002Fblog\u002F2024\u002Fflash3\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002FDao-AILab\u002Fflash-attention\n- PyTorch docs: https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fgenerated\u002Ftorch.nn.functional.scaled_dot_product_attention.html\n\n\n\n","# Flash Attention - Fast Memory-Efficient Attention\n\n## Quick start\n\nFlash Attention provides 2-4x speedup and 10-20x memory reduction for transformer attention through IO-aware tiling and recomputation.\n\n**PyTorch native (easiest, PyTorch 2.2+)**:\n```python\nimport torch\nimport torch.nn.functional as F\n\nq = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)  # [batch, heads, seq, dim]\nk = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\nv = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\n\n# Automatically uses Flash Attention if available\nout = F.scaled_dot_product_attention(q, k, v)\n```\n\n**flash-attn library (more features)**:\n```bash\npip install flash-attn --no-build-isolation\n```\n\n```python\nfrom flash_attn import flash_attn_func\n\n# q, k, v: [batch, seqlen, nheads, headdim]\nout = flash_attn_func(q, k, v, dropout_p=0.0, causal=True)\n```\n\n## Common workflows\n\n### Workflow 1: Enable in existing PyTorch model\n\nCopy this checklist:\n\n```\nFlash Attention Integration:\n- [ ] Step 1: Check PyTorch version (≥2.2)\n- [ ] Step 2: Enable Flash Attention backend\n- [ ] Step 3: Verify speedup with profiling\n- [ ] Step 4: Test accuracy matches baseline\n```\n\n**Step 1: Check PyTorch version**\n\n```bash\npython -c \"import torch; print(torch.__version__)\"\n# Should be ≥2.2.0\n```\n\nIf \u003C2.2, upgrade:\n```bash\npip install --upgrade torch\n```\n\n**Step 2: Enable Flash Attention backend**\n\nReplace standard attention:\n```python\n# Before (standard attention)\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F math.sqrt(d_k), dim=-1)\nout = attn_weights @ v\n\n# After (Flash Attention)\nimport torch.nn.functional as F\nout = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)\n```\n\nForce Flash Attention backend:\n```python\nwith torch.backends.cuda.sdp_kernel(\n    enable_flash=True,\n    enable_math=False,\n    enable_mem_efficient=False\n):\n    out = F.scaled_dot_product_attention(q, k, v)\n```\n\n**Step 3: Verify speedup with profiling**\n\n```python\nimport torch.utils.benchmark as benchmark\n\ndef test_attention(use_flash):\n    q, k, v = [torch.randn(2, 8, 2048, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\n\n    if use_flash:\n        with torch.backends.cuda.sdp_kernel(enable_flash=True):\n            return F.scaled_dot_product_attention(q, k, v)\n    else:\n        attn = (q @ k.transpose(-2, -1) \u002F 8.0).softmax(dim=-1)\n        return attn @ v\n\n# Benchmark\nt_flash = benchmark.Timer(stmt='test_attention(True)', globals=globals())\nt_standard = benchmark.Timer(stmt='test_attention(False)', globals=globals())\n\nprint(f\"Flash: {t_flash.timeit(100).mean:.3f}s\")\nprint(f\"Standard: {t_standard.timeit(100).mean:.3f}s\")\n```\n\nExpected: 2-4x speedup for sequences >512 tokens.\n\n**Step 4: Test accuracy matches baseline**\n\n```python\n# Compare outputs\nq, k, v = [torch.randn(1, 8, 512, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\n\n# Flash Attention\nout_flash = F.scaled_dot_product_attention(q, k, v)\n\n# Standard attention\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F 8.0, dim=-1)\nout_standard = attn_weights @ v\n\n# Check difference\ndiff = (out_flash - out_standard).abs().max()\nprint(f\"Max difference: {diff:.6f}\")\n# Should be \u003C1e-3 for float16\n```\n\n### Workflow 2: Use flash-attn library for advanced features\n\nFor multi-query attention, sliding window, or H100 FP8.\n\nCopy this checklist:\n\n```\nflash-attn Library Setup:\n- [ ] Step 1: Install flash-attn library\n- [ ] Step 2: Modify attention code\n- [ ] Step 3: Enable advanced features\n- [ ] Step 4: Benchmark performance\n```\n\n**Step 1: Install flash-attn library**\n\n```bash\n# NVIDIA GPUs (CUDA 12.0+)\npip install flash-attn --no-build-isolation\n\n# Verify installation\npython -c \"from flash_attn import flash_attn_func; print('Success')\"\n```\n\n**Step 2: Modify attention code**\n\n```python\nfrom flash_attn import flash_attn_func\n\n# Input: [batch_size, seq_len, num_heads, head_dim]\n# Transpose from [batch, heads, seq, dim] if needed\nq = q.transpose(1, 2)  # [batch, seq, heads, dim]\nk = k.transpose(1, 2)\nv = v.transpose(1, 2)\n\nout = flash_attn_func(\n    q, k, v,\n    dropout_p=0.1,\n    causal=True,  # For autoregressive models\n    window_size=(-1, -1),  # No sliding window\n    softmax_scale=None  # Auto-scale\n)\n\nout = out.transpose(1, 2)  # Back to [batch, heads, seq, dim]\n```\n\n**Step 3: Enable advanced features**\n\nMulti-query attention (shared K\u002FV across heads):\n```python\nfrom flash_attn import flash_attn_func\n\n# q: [batch, seq, num_q_heads, dim]\n# k, v: [batch, seq, num_kv_heads, dim]  # Fewer KV heads\nout = flash_attn_func(q, k, v)  # Automatically handles MQA\n```\n\nSliding window attention (local attention):\n```python\n# Only attend to window of 256 tokens before\u002Fafter\nout = flash_attn_func(\n    q, k, v,\n    window_size=(256, 256),  # (left, right) window\n    causal=True\n)\n```\n\n**Step 4: Benchmark performance**\n\n```python\nimport torch\nfrom flash_attn import flash_attn_func\nimport time\n\nq, k, v = [torch.randn(4, 4096, 32, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\n\n# Warmup\nfor _ in range(10):\n    _ = flash_attn_func(q, k, v)\n\n# Benchmark\ntorch.cuda.synchronize()\nstart = time.time()\nfor _ in range(100):\n    out = flash_attn_func(q, k, v)\n    torch.cuda.synchronize()\nend = time.time()\n\nprint(f\"Time per iteration: {(end-start)\u002F100*1000:.2f}ms\")\nprint(f\"Memory allocated: {torch.cuda.max_memory_allocated()\u002F1e9:.2f}GB\")\n```\n\n### Workflow 3: H100 FP8 optimization (FlashAttention-3)\n\nFor maximum performance on H100 GPUs.\n\n```\nFP8 Setup:\n- [ ] Step 1: Verify H100 GPU available\n- [ ] Step 2: Install flash-attn with FP8 support\n- [ ] Step 3: Convert inputs to FP8\n- [ ] Step 4: Run with FP8 attention\n```\n\n**Step 1: Verify H100 GPU**\n\n```bash\nnvidia-smi --query-gpu=name --format=csv\n# Should show \"H100\" or \"H800\"\n```\n\n**Step 2: Install flash-attn with FP8 support**\n\n```bash\npip install flash-attn --no-build-isolation\n# FP8 support included for H100\n```\n\n**Step 3: Convert inputs to FP8**\n\n```python\nimport torch\n\nq = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\nk = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\nv = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\n\n# Convert to float8_e4m3 (FP8)\nq_fp8 = q.to(torch.float8_e4m3fn)\nk_fp8 = k.to(torch.float8_e4m3fn)\nv_fp8 = v.to(torch.float8_e4m3fn)\n```\n\n**Step 4: Run with FP8 attention**\n\n```python\nfrom flash_attn import flash_attn_func\n\n# FlashAttention-3 automatically uses FP8 kernels on H100\nout = flash_attn_func(q_fp8, k_fp8, v_fp8)\n# Result: ~1.2 PFLOPS, 1.5-2x faster than FP16\n```\n\n## When to use vs alternatives\n\n**Use Flash Attention when:**\n- Training transformers with sequences >512 tokens\n- Running inference with long context (>2K tokens)\n- GPU memory constrained (OOM with standard attention)\n- Need 2-4x speedup without accuracy loss\n- Using PyTorch 2.2+ or can install flash-attn\n\n**Use alternatives instead:**\n- **Standard attention**: Sequences \u003C256 tokens (overhead not worth it)\n- **xFormers**: Need more attention variants (not just speed)\n- **Memory-efficient attention**: CPU inference (Flash Attention needs GPU)\n\n## Common issues\n\n**Issue: ImportError: cannot import flash_attn**\n\nInstall with no-build-isolation flag:\n```bash\npip install flash-attn --no-build-isolation\n```\n\nOr install CUDA toolkit first:\n```bash\nconda install cuda -c nvidia\npip install flash-attn --no-build-isolation\n```\n\n**Issue: Slower than expected (no speedup)**\n\nFlash Attention benefits increase with sequence length:\n- \u003C512 tokens: Minimal speedup (10-20%)\n- 512-2K tokens: 2-3x speedup\n- >2K tokens: 3-4x speedup\n\nCheck sequence length is sufficient.\n\n**Issue: RuntimeError: CUDA error**\n\nVerify GPU supports Flash Attention:\n```python\nimport torch\nprint(torch.cuda.get_device_capability())\n# Should be ≥(7, 5) for Turing+\n```\n\nFlash Attention requires:\n- Ampere (A100, A10): ✅ Full support\n- Turing (T4): ✅ Supported\n- Volta (V100): ❌ Not supported\n\n**Issue: Accuracy degradation**\n\nCheck dtype is float16 or bfloat16 (not float32):\n```python\nq = q.to(torch.float16)  # Or torch.bfloat16\n```\n\nFlash Attention uses float16\u002Fbfloat16 for speed. Float32 not supported.\n\n## Advanced topics\n\n**Integration with HuggingFace Transformers**: See [references\u002Ftransformers-integration.md](references\u002Ftransformers-integration.md) for enabling Flash Attention in BERT, GPT, Llama models.\n\n**Performance benchmarks**: See [references\u002Fbenchmarks.md](references\u002Fbenchmarks.md) for detailed speed and memory comparisons across GPUs and sequence lengths.\n\n**Algorithm details**: See [references\u002Falgorithm.md](references\u002Falgorithm.md) for tiling strategy, recomputation, and IO complexity analysis.\n\n**Advanced features**: See [references\u002Fadvanced-features.md](references\u002Fadvanced-features.md) for rotary embeddings, ALiBi, paged KV cache, and custom attention masks.\n\n## Hardware requirements\n\n- **GPU**: NVIDIA Ampere+ (A100, A10, A30) or AMD MI200+\n- **VRAM**: Same as standard attention (Flash Attention doesn't increase memory)\n- **CUDA**: 12.0+ (11.8 minimum)\n- **PyTorch**: 2.2+ for native support\n\n**Not supported**: V100 (Volta), CPU inference\n\n## Resources\n\n- Paper: \"FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness\" (NeurIPS 2022)\n- Paper: \"FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning\" (ICLR 2024)\n- Blog: https:\u002F\u002Ftridao.me\u002Fblog\u002F2024\u002Fflash3\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002FDao-AILab\u002Fflash-attention\n- PyTorch docs: https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fgenerated\u002Ftorch.nn.functional.scaled_dot_product_attention.html\n\n\n\n",{"name":5,"author":43,"license":14,"version":44,"metadata":45,"description":7,"dependencies":52},"Orchestra Research","1.0.0",{"hermes":46},{"tags":47},[48,21,30,29,28,49,50,27,26,51,33],"Optimization","Long Context","PyTorch","FP8",[53,54,55],"flash-attn","torch","transformers","main","6746276ba18cb774853eb61b3b9399658bc9bc5c","core\u002Foptional-skills\u002Fmlops\u002Fflash-attention","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch","2026-04-28 17:01:03",{"source":8,"skillName":5,"commands":63,"prompt":73,"zipAvailable":74},[64,67,70],{"tool":65,"command":66},"npx","npx skills add gjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN --skill optimizing-attention-flash",{"tool":68,"command":69},"bunx","bunx skills add gjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN --skill optimizing-attention-flash",{"tool":71,"command":72},"pnpm","pnpm dlx skills add gjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN --skill optimizing-attention-flash","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Foptional-skills\u002Fmlops\u002Fflash-attention\u002FSKILL.md",true,[76,82],{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fbenchmarks.md","REFERENCE","参考文档",7129,"https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Foptional-skills\u002Fmlops\u002Fflash-attention\u002Freferences\u002Fbenchmarks.md",{"path":83,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Ftransformers-integration.md",7427,"https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Foptional-skills\u002Fmlops\u002Fflash-attention\u002Freferences\u002Ftransformers-integration.md",[87,130,155,172,191,210],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":109,"publishedAt":38},"01M71QG27G1R2H2ZWEG4S0WTZT","writing-plans","Write implementation plans: bite-sized tasks, paths, code.","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fsoftware-development\u002Fwriting-plans\u002FSKILL.md",[93,98,101,106],{"categoryNo":94,"categoryName":95,"taxonomyType":96,"taxonomyTypeDesc":97},"01JBSEEDCAT000000000000015","视觉设计","SCENARIO","使用场景",{"categoryNo":99,"categoryName":100,"taxonomyType":96,"taxonomyTypeDesc":97},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":102,"categoryName":103,"taxonomyType":104,"taxonomyTypeDesc":105},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",{"categoryNo":107,"categoryName":108,"taxonomyType":104,"taxonomyTypeDesc":105},"01JBSEEDCAT000000000000036","内容创作者",[110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129],"writing","writing plans","plans","test-driven","test-driven-development","superpowers","design","workflow","code","tasks","subagent","code-review","review","documentation","write","paths","planning","development","test","implementation",{"skillNo":131,"name":114,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":141,"publishedAt":38},"01M71QFZYRTJXMAE551MRAKZ14","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fsoftware-development\u002Ftest-driven-development\u002FSKILL.md",[135,138],{"categoryNo":136,"categoryName":137,"taxonomyType":96,"taxonomyTypeDesc":97},"01JBSEEDCAT000000000000007","代码审查",{"categoryNo":139,"categoryName":140,"taxonomyType":96,"taxonomyTypeDesc":97},"01JBSEEDCAT000000000000008","测试与质量",[142,127,128,143,144,145,146,115,110,147,118,120,148,149,150,151,152,112,153,154],"test driven development","driven","green","red-green-refactor","testing","debugging","systematic","refactor","systematic-debugging","enforce","tests","tdd","quality",{"skillNo":156,"name":150,"nameZh":6,"description":157,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":158,"categories":159,"keywords":161,"publishedAt":38},"01M71QFWR5Q8EYEQ6MCS3SM6MC","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fsoftware-development\u002Fsystematic-debugging\u002FSKILL.md",[160],{"categoryNo":139,"categoryName":140,"taxonomyType":96,"taxonomyTypeDesc":97},[162,147,148,113,163,164,114,115,110,120,165,166,127,167,112,168,128,169,170,171],"systematic debugging","problem","problem-solving","phase","bugs","root cause","root-cause","investigation","understand","hermes",{"skillNo":173,"name":174,"nameZh":6,"description":175,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":176,"categories":177,"keywords":183,"publishedAt":38},"01M71QFS9S04MD8JP747W5WM0N","subagent-driven-development","Execute plans via delegate_task subagents (2-stage review).","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fsoftware-development\u002Fsubagent-driven-development\u002FSKILL.md",[178,179,182],{"categoryNo":99,"categoryName":100,"taxonomyType":96,"taxonomyTypeDesc":97},{"categoryNo":180,"categoryName":181,"taxonomyType":96,"taxonomyTypeDesc":97},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":107,"categoryName":108,"taxonomyType":104,"taxonomyTypeDesc":105},[184,120,127,143,113,114,185,186,115,110,117,118,121,122,187,188,112,189,190,128],"subagent driven development","delegate","delegation","subagents","parallel","stage","task",{"skillNo":192,"name":193,"nameZh":6,"description":194,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":195,"categories":196,"keywords":199,"publishedAt":38},"01M71QFQ1DBCVAZ511MXFE6T2V","requesting-code-review","Pre-commit review: security scan, quality gates, auto-fix.","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fsoftware-development\u002Frequesting-code-review\u002FSKILL.md",[197,198],{"categoryNo":136,"categoryName":137,"taxonomyType":96,"taxonomyTypeDesc":97},{"categoryNo":102,"categoryName":103,"taxonomyType":104,"taxonomyTypeDesc":105},[200,201,118,122,113,114,202,203,115,204,110,205,206,120,121,207,208,127,209,112],"code review","requesting code review","fix","auto-fix","auto","security scan","commit","verification","security","scan",{"skillNo":211,"name":212,"nameZh":6,"description":213,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":214,"categories":215,"keywords":217,"publishedAt":38},"01M71QFM7KWM540YR67FRN807Q","python-debugpy","Debug Python: pdb REPL + debugpy remote (DAP).","https:\u002F\u002Fgithub.com\u002Fgjbvsjjvgm-sketch\u002FWORM_V2_SOVEREIGN\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fsoftware-development\u002Fpython-debugpy\u002FSKILL.md",[216],{"categoryNo":102,"categoryName":103,"taxonomyType":104,"taxonomyTypeDesc":105},[218,219,220,221,222,223,224,225,147,148,226,227,228,150,229,230,231,232,171,233],"debugpy","python debugpy","python","dap","inspect","post-mortem","pdb","remote","debugger","node","commands","debug","post","breakpoints","node-inspect","tui"]