[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6DBXB1Z6GNMCDQED1ZWMK9B":3,"skill-same:01M6DBXB1Z6GNMCDQED1ZWMK9B":84},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":62,"commitSha":63,"skillDirectory":64,"forksCount":65,"repositoryHtmlUrl":66,"repositoryHomepageUrl":6,"ownerHtmlUrl":67,"ownerBlogUrl":6,"ownerDescription":68,"updatedAt":69,"install":70,"resources":83},"01M6DBXB1Z6GNMCDQED1ZWMK9B","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.","zapabob\u002FSkills","zapabob","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F130830376?v=4","01M6DBMYZAGRTFQDSQYW3W764P","峯岸 亮","01M6DBMZ3GKDSJ01NZ9XTZD7JD",2,"MIT","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Farchive\u002Fskill-md-reviewed\u002Fsha256\u002F05\u002F05fb618f2939f16295bb36851a38fcc26755f8d1dce9897c2247a87d9ec7ef24\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"attention","optimizing attention flash","flash","FP8","tokens","speed","efficiency","use","context","Transformers","macos","Optimization","library","gpu","issues","training","pytorch","research","memory","linux","2026-11-10 10:12:30",false,"---\r\nname: optimizing-attention-flash\r\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.\r\nversion: 1.0.0\r\nauthor: Orchestra Research\r\nlicense: MIT\r\ndependencies: [flash-attn, torch, transformers]\r\nplatforms: [linux, macos]\r\nmetadata:\r\n  hermes:\r\n    tags: [Optimization, Flash Attention, Attention Optimization, Memory Efficiency, Speed Optimization, Long Context, PyTorch, SDPA, H100, FP8, Transformers]\r\n\r\n---\r\n\r\n# Flash Attention - Fast Memory-Efficient Attention\r\n\r\n## Quick start\r\n\r\nFlash Attention provides 2-4x speedup and 10-20x memory reduction for transformer attention through IO-aware tiling and recomputation.\r\n\r\n**PyTorch native (easiest, PyTorch 2.2+)**:\r\n```python\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\nq = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)  # [batch, heads, seq, dim]\r\nk = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\r\nv = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\r\n\r\n# Automatically uses Flash Attention if available\r\nout = F.scaled_dot_product_attention(q, k, v)\r\n```\r\n\r\n**flash-attn library (more features)**:\r\n```bash\r\npip install flash-attn --no-build-isolation\r\n```\r\n\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# q, k, v: [batch, seqlen, nheads, headdim]\r\nout = flash_attn_func(q, k, v, dropout_p=0.0, causal=True)\r\n```\r\n\r\n## Common workflows\r\n\r\n### Workflow 1: Enable in existing PyTorch model\r\n\r\nCopy this checklist:\r\n\r\n```\r\nFlash Attention Integration:\r\n- [ ] Step 1: Check PyTorch version (≥2.2)\r\n- [ ] Step 2: Enable Flash Attention backend\r\n- [ ] Step 3: Verify speedup with profiling\r\n- [ ] Step 4: Test accuracy matches baseline\r\n```\r\n\r\n**Step 1: Check PyTorch version**\r\n\r\n```bash\r\npython -c \"import torch; print(torch.__version__)\"\r\n# Should be ≥2.2.0\r\n```\r\n\r\nIf \u003C2.2, upgrade:\r\n```bash\r\npip install --upgrade torch\r\n```\r\n\r\n**Step 2: Enable Flash Attention backend**\r\n\r\nReplace standard attention:\r\n```python\r\n# Before (standard attention)\r\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F math.sqrt(d_k), dim=-1)\r\nout = attn_weights @ v\r\n\r\n# After (Flash Attention)\r\nimport torch.nn.functional as F\r\nout = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)\r\n```\r\n\r\nForce Flash Attention backend:\r\n```python\r\nwith torch.backends.cuda.sdp_kernel(\r\n    enable_flash=True,\r\n    enable_math=False,\r\n    enable_mem_efficient=False\r\n):\r\n    out = F.scaled_dot_product_attention(q, k, v)\r\n```\r\n\r\n**Step 3: Verify speedup with profiling**\r\n\r\n```python\r\nimport torch.utils.benchmark as benchmark\r\n\r\ndef test_attention(use_flash):\r\n    q, k, v = [torch.randn(2, 8, 2048, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\r\n\r\n    if use_flash:\r\n        with torch.backends.cuda.sdp_kernel(enable_flash=True):\r\n            return F.scaled_dot_product_attention(q, k, v)\r\n    else:\r\n        attn = (q @ k.transpose(-2, -1) \u002F 8.0).softmax(dim=-1)\r\n        return attn @ v\r\n\r\n# Benchmark\r\nt_flash = benchmark.Timer(stmt='test_attention(True)', globals=globals())\r\nt_standard = benchmark.Timer(stmt='test_attention(False)', globals=globals())\r\n\r\nprint(f\"Flash: {t_flash.timeit(100).mean:.3f}s\")\r\nprint(f\"Standard: {t_standard.timeit(100).mean:.3f}s\")\r\n```\r\n\r\nExpected: 2-4x speedup for sequences >512 tokens.\r\n\r\n**Step 4: Test accuracy matches baseline**\r\n\r\n```python\r\n# Compare outputs\r\nq, k, v = [torch.randn(1, 8, 512, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\r\n\r\n# Flash Attention\r\nout_flash = F.scaled_dot_product_attention(q, k, v)\r\n\r\n# Standard attention\r\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F 8.0, dim=-1)\r\nout_standard = attn_weights @ v\r\n\r\n# Check difference\r\ndiff = (out_flash - out_standard).abs().max()\r\nprint(f\"Max difference: {diff:.6f}\")\r\n# Should be \u003C1e-3 for float16\r\n```\r\n\r\n### Workflow 2: Use flash-attn library for advanced features\r\n\r\nFor multi-query attention, sliding window, or H100 FP8.\r\n\r\nCopy this checklist:\r\n\r\n```\r\nflash-attn Library Setup:\r\n- [ ] Step 1: Install flash-attn library\r\n- [ ] Step 2: Modify attention code\r\n- [ ] Step 3: Enable advanced features\r\n- [ ] Step 4: Benchmark performance\r\n```\r\n\r\n**Step 1: Install flash-attn library**\r\n\r\n```bash\r\n# NVIDIA GPUs (CUDA 12.0+)\r\npip install flash-attn --no-build-isolation\r\n\r\n# Verify installation\r\npython -c \"from flash_attn import flash_attn_func; print('Success')\"\r\n```\r\n\r\n**Step 2: Modify attention code**\r\n\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# Input: [batch_size, seq_len, num_heads, head_dim]\r\n# Transpose from [batch, heads, seq, dim] if needed\r\nq = q.transpose(1, 2)  # [batch, seq, heads, dim]\r\nk = k.transpose(1, 2)\r\nv = v.transpose(1, 2)\r\n\r\nout = flash_attn_func(\r\n    q, k, v,\r\n    dropout_p=0.1,\r\n    causal=True,  # For autoregressive models\r\n    window_size=(-1, -1),  # No sliding window\r\n    softmax_scale=None  # Auto-scale\r\n)\r\n\r\nout = out.transpose(1, 2)  # Back to [batch, heads, seq, dim]\r\n```\r\n\r\n**Step 3: Enable advanced features**\r\n\r\nMulti-query attention (shared K\u002FV across heads):\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# q: [batch, seq, num_q_heads, dim]\r\n# k, v: [batch, seq, num_kv_heads, dim]  # Fewer KV heads\r\nout = flash_attn_func(q, k, v)  # Automatically handles MQA\r\n```\r\n\r\nSliding window attention (local attention):\r\n```python\r\n# Only attend to window of 256 tokens before\u002Fafter\r\nout = flash_attn_func(\r\n    q, k, v,\r\n    window_size=(256, 256),  # (left, right) window\r\n    causal=True\r\n)\r\n```\r\n\r\n**Step 4: Benchmark performance**\r\n\r\n```python\r\nimport torch\r\nfrom flash_attn import flash_attn_func\r\nimport time\r\n\r\nq, k, v = [torch.randn(4, 4096, 32, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\r\n\r\n# Warmup\r\nfor _ in range(10):\r\n    _ = flash_attn_func(q, k, v)\r\n\r\n# Benchmark\r\ntorch.cuda.synchronize()\r\nstart = time.time()\r\nfor _ in range(100):\r\n    out = flash_attn_func(q, k, v)\r\n    torch.cuda.synchronize()\r\nend = time.time()\r\n\r\nprint(f\"Time per iteration: {(end-start)\u002F100*1000:.2f}ms\")\r\nprint(f\"Memory allocated: {torch.cuda.max_memory_allocated()\u002F1e9:.2f}GB\")\r\n```\r\n\r\n### Workflow 3: H100 FP8 optimization (FlashAttention-3)\r\n\r\nFor maximum performance on H100 GPUs.\r\n\r\n```\r\nFP8 Setup:\r\n- [ ] Step 1: Verify H100 GPU available\r\n- [ ] Step 2: Install flash-attn with FP8 support\r\n- [ ] Step 3: Convert inputs to FP8\r\n- [ ] Step 4: Run with FP8 attention\r\n```\r\n\r\n**Step 1: Verify H100 GPU**\r\n\r\n```bash\r\nnvidia-smi --query-gpu=name --format=csv\r\n# Should show \"H100\" or \"H800\"\r\n```\r\n\r\n**Step 2: Install flash-attn with FP8 support**\r\n\r\n```bash\r\npip install flash-attn --no-build-isolation\r\n# FP8 support included for H100\r\n```\r\n\r\n**Step 3: Convert inputs to FP8**\r\n\r\n```python\r\nimport torch\r\n\r\nq = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\r\nk = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\r\nv = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\r\n\r\n# Convert to float8_e4m3 (FP8)\r\nq_fp8 = q.to(torch.float8_e4m3fn)\r\nk_fp8 = k.to(torch.float8_e4m3fn)\r\nv_fp8 = v.to(torch.float8_e4m3fn)\r\n```\r\n\r\n**Step 4: Run with FP8 attention**\r\n\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# FlashAttention-3 automatically uses FP8 kernels on H100\r\nout = flash_attn_func(q_fp8, k_fp8, v_fp8)\r\n# Result: ~1.2 PFLOPS, 1.5-2x faster than FP16\r\n```\r\n\r\n## When to use vs alternatives\r\n\r\n**Use Flash Attention when:**\r\n- Training transformers with sequences >512 tokens\r\n- Running inference with long context (>2K tokens)\r\n- GPU memory constrained (OOM with standard attention)\r\n- Need 2-4x speedup without accuracy loss\r\n- Using PyTorch 2.2+ or can install flash-attn\r\n\r\n**Use alternatives instead:**\r\n- **Standard attention**: Sequences \u003C256 tokens (overhead not worth it)\r\n- **xFormers**: Need more attention variants (not just speed)\r\n- **Memory-efficient attention**: CPU inference (Flash Attention needs GPU)\r\n\r\n## Common issues\r\n\r\n**Issue: ImportError: cannot import flash_attn**\r\n\r\nInstall with no-build-isolation flag:\r\n```bash\r\npip install flash-attn --no-build-isolation\r\n```\r\n\r\nOr install CUDA toolkit first:\r\n```bash\r\nconda install cuda -c nvidia\r\npip install flash-attn --no-build-isolation\r\n```\r\n\r\n**Issue: Slower than expected (no speedup)**\r\n\r\nFlash Attention benefits increase with sequence length:\r\n- \u003C512 tokens: Minimal speedup (10-20%)\r\n- 512-2K tokens: 2-3x speedup\r\n- >2K tokens: 3-4x speedup\r\n\r\nCheck sequence length is sufficient.\r\n\r\n**Issue: RuntimeError: CUDA error**\r\n\r\nVerify GPU supports Flash Attention:\r\n```python\r\nimport torch\r\nprint(torch.cuda.get_device_capability())\r\n# Should be ≥(7, 5) for Turing+\r\n```\r\n\r\nFlash Attention requires:\r\n- Ampere (A100, A10): ✅ Full support\r\n- Turing (T4): ✅ Supported\r\n- Volta (V100): ❌ Not supported\r\n\r\n**Issue: Accuracy degradation**\r\n\r\nCheck dtype is float16 or bfloat16 (not float32):\r\n```python\r\nq = q.to(torch.float16)  # Or torch.bfloat16\r\n```\r\n\r\nFlash Attention uses float16\u002Fbfloat16 for speed. Float32 not supported.\r\n\r\n## Advanced topics\r\n\r\n**Integration with HuggingFace Transformers**: See [references\u002Ftransformers-integration.md](references\u002Ftransformers-integration.md) for enabling Flash Attention in BERT, GPT, Llama models.\r\n\r\n**Performance benchmarks**: See [references\u002Fbenchmarks.md](references\u002Fbenchmarks.md) for detailed speed and memory comparisons across GPUs and sequence lengths.\r\n\r\n## Hardware requirements\r\n\r\n- **GPU**: NVIDIA Ampere+ (A100, A10, A30) or AMD MI200+\r\n- **VRAM**: Same as standard attention (Flash Attention doesn't increase memory)\r\n- **CUDA**: 12.0+ (11.8 minimum)\r\n- **PyTorch**: 2.2+ for native support\r\n\r\n**Not supported**: V100 (Volta), CPU inference\r\n\r\n## Resources\r\n\r\n- Paper: \"FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness\" (NeurIPS 2022)\r\n- Paper: \"FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning\" (ICLR 2024)\r\n- Blog: https:\u002F\u002Ftridao.me\u002Fblog\u002F2024\u002Fflash3\u002F\r\n- GitHub: https:\u002F\u002Fgithub.com\u002FDao-AILab\u002Fflash-attention\r\n- PyTorch docs: https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fgenerated\u002Ftorch.nn.functional.scaled_dot_product_attention.html\r\n","# Flash Attention - Fast Memory-Efficient Attention\r\n\r\n## Quick start\r\n\r\nFlash Attention provides 2-4x speedup and 10-20x memory reduction for transformer attention through IO-aware tiling and recomputation.\r\n\r\n**PyTorch native (easiest, PyTorch 2.2+)**:\r\n```python\r\nimport torch\r\nimport torch.nn.functional as F\r\n\r\nq = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)  # [batch, heads, seq, dim]\r\nk = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\r\nv = torch.randn(2, 8, 512, 64, device='cuda', dtype=torch.float16)\r\n\r\n# Automatically uses Flash Attention if available\r\nout = F.scaled_dot_product_attention(q, k, v)\r\n```\r\n\r\n**flash-attn library (more features)**:\r\n```bash\r\npip install flash-attn --no-build-isolation\r\n```\r\n\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# q, k, v: [batch, seqlen, nheads, headdim]\r\nout = flash_attn_func(q, k, v, dropout_p=0.0, causal=True)\r\n```\r\n\r\n## Common workflows\r\n\r\n### Workflow 1: Enable in existing PyTorch model\r\n\r\nCopy this checklist:\r\n\r\n```\r\nFlash Attention Integration:\r\n- [ ] Step 1: Check PyTorch version (≥2.2)\r\n- [ ] Step 2: Enable Flash Attention backend\r\n- [ ] Step 3: Verify speedup with profiling\r\n- [ ] Step 4: Test accuracy matches baseline\r\n```\r\n\r\n**Step 1: Check PyTorch version**\r\n\r\n```bash\r\npython -c \"import torch; print(torch.__version__)\"\r\n# Should be ≥2.2.0\r\n```\r\n\r\nIf \u003C2.2, upgrade:\r\n```bash\r\npip install --upgrade torch\r\n```\r\n\r\n**Step 2: Enable Flash Attention backend**\r\n\r\nReplace standard attention:\r\n```python\r\n# Before (standard attention)\r\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F math.sqrt(d_k), dim=-1)\r\nout = attn_weights @ v\r\n\r\n# After (Flash Attention)\r\nimport torch.nn.functional as F\r\nout = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)\r\n```\r\n\r\nForce Flash Attention backend:\r\n```python\r\nwith torch.backends.cuda.sdp_kernel(\r\n    enable_flash=True,\r\n    enable_math=False,\r\n    enable_mem_efficient=False\r\n):\r\n    out = F.scaled_dot_product_attention(q, k, v)\r\n```\r\n\r\n**Step 3: Verify speedup with profiling**\r\n\r\n```python\r\nimport torch.utils.benchmark as benchmark\r\n\r\ndef test_attention(use_flash):\r\n    q, k, v = [torch.randn(2, 8, 2048, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\r\n\r\n    if use_flash:\r\n        with torch.backends.cuda.sdp_kernel(enable_flash=True):\r\n            return F.scaled_dot_product_attention(q, k, v)\r\n    else:\r\n        attn = (q @ k.transpose(-2, -1) \u002F 8.0).softmax(dim=-1)\r\n        return attn @ v\r\n\r\n# Benchmark\r\nt_flash = benchmark.Timer(stmt='test_attention(True)', globals=globals())\r\nt_standard = benchmark.Timer(stmt='test_attention(False)', globals=globals())\r\n\r\nprint(f\"Flash: {t_flash.timeit(100).mean:.3f}s\")\r\nprint(f\"Standard: {t_standard.timeit(100).mean:.3f}s\")\r\n```\r\n\r\nExpected: 2-4x speedup for sequences >512 tokens.\r\n\r\n**Step 4: Test accuracy matches baseline**\r\n\r\n```python\r\n# Compare outputs\r\nq, k, v = [torch.randn(1, 8, 512, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\r\n\r\n# Flash Attention\r\nout_flash = F.scaled_dot_product_attention(q, k, v)\r\n\r\n# Standard attention\r\nattn_weights = torch.softmax(q @ k.transpose(-2, -1) \u002F 8.0, dim=-1)\r\nout_standard = attn_weights @ v\r\n\r\n# Check difference\r\ndiff = (out_flash - out_standard).abs().max()\r\nprint(f\"Max difference: {diff:.6f}\")\r\n# Should be \u003C1e-3 for float16\r\n```\r\n\r\n### Workflow 2: Use flash-attn library for advanced features\r\n\r\nFor multi-query attention, sliding window, or H100 FP8.\r\n\r\nCopy this checklist:\r\n\r\n```\r\nflash-attn Library Setup:\r\n- [ ] Step 1: Install flash-attn library\r\n- [ ] Step 2: Modify attention code\r\n- [ ] Step 3: Enable advanced features\r\n- [ ] Step 4: Benchmark performance\r\n```\r\n\r\n**Step 1: Install flash-attn library**\r\n\r\n```bash\r\n# NVIDIA GPUs (CUDA 12.0+)\r\npip install flash-attn --no-build-isolation\r\n\r\n# Verify installation\r\npython -c \"from flash_attn import flash_attn_func; print('Success')\"\r\n```\r\n\r\n**Step 2: Modify attention code**\r\n\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# Input: [batch_size, seq_len, num_heads, head_dim]\r\n# Transpose from [batch, heads, seq, dim] if needed\r\nq = q.transpose(1, 2)  # [batch, seq, heads, dim]\r\nk = k.transpose(1, 2)\r\nv = v.transpose(1, 2)\r\n\r\nout = flash_attn_func(\r\n    q, k, v,\r\n    dropout_p=0.1,\r\n    causal=True,  # For autoregressive models\r\n    window_size=(-1, -1),  # No sliding window\r\n    softmax_scale=None  # Auto-scale\r\n)\r\n\r\nout = out.transpose(1, 2)  # Back to [batch, heads, seq, dim]\r\n```\r\n\r\n**Step 3: Enable advanced features**\r\n\r\nMulti-query attention (shared K\u002FV across heads):\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# q: [batch, seq, num_q_heads, dim]\r\n# k, v: [batch, seq, num_kv_heads, dim]  # Fewer KV heads\r\nout = flash_attn_func(q, k, v)  # Automatically handles MQA\r\n```\r\n\r\nSliding window attention (local attention):\r\n```python\r\n# Only attend to window of 256 tokens before\u002Fafter\r\nout = flash_attn_func(\r\n    q, k, v,\r\n    window_size=(256, 256),  # (left, right) window\r\n    causal=True\r\n)\r\n```\r\n\r\n**Step 4: Benchmark performance**\r\n\r\n```python\r\nimport torch\r\nfrom flash_attn import flash_attn_func\r\nimport time\r\n\r\nq, k, v = [torch.randn(4, 4096, 32, 64, device='cuda', dtype=torch.float16) for _ in range(3)]\r\n\r\n# Warmup\r\nfor _ in range(10):\r\n    _ = flash_attn_func(q, k, v)\r\n\r\n# Benchmark\r\ntorch.cuda.synchronize()\r\nstart = time.time()\r\nfor _ in range(100):\r\n    out = flash_attn_func(q, k, v)\r\n    torch.cuda.synchronize()\r\nend = time.time()\r\n\r\nprint(f\"Time per iteration: {(end-start)\u002F100*1000:.2f}ms\")\r\nprint(f\"Memory allocated: {torch.cuda.max_memory_allocated()\u002F1e9:.2f}GB\")\r\n```\r\n\r\n### Workflow 3: H100 FP8 optimization (FlashAttention-3)\r\n\r\nFor maximum performance on H100 GPUs.\r\n\r\n```\r\nFP8 Setup:\r\n- [ ] Step 1: Verify H100 GPU available\r\n- [ ] Step 2: Install flash-attn with FP8 support\r\n- [ ] Step 3: Convert inputs to FP8\r\n- [ ] Step 4: Run with FP8 attention\r\n```\r\n\r\n**Step 1: Verify H100 GPU**\r\n\r\n```bash\r\nnvidia-smi --query-gpu=name --format=csv\r\n# Should show \"H100\" or \"H800\"\r\n```\r\n\r\n**Step 2: Install flash-attn with FP8 support**\r\n\r\n```bash\r\npip install flash-attn --no-build-isolation\r\n# FP8 support included for H100\r\n```\r\n\r\n**Step 3: Convert inputs to FP8**\r\n\r\n```python\r\nimport torch\r\n\r\nq = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\r\nk = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\r\nv = torch.randn(2, 4096, 32, 64, device='cuda', dtype=torch.float16)\r\n\r\n# Convert to float8_e4m3 (FP8)\r\nq_fp8 = q.to(torch.float8_e4m3fn)\r\nk_fp8 = k.to(torch.float8_e4m3fn)\r\nv_fp8 = v.to(torch.float8_e4m3fn)\r\n```\r\n\r\n**Step 4: Run with FP8 attention**\r\n\r\n```python\r\nfrom flash_attn import flash_attn_func\r\n\r\n# FlashAttention-3 automatically uses FP8 kernels on H100\r\nout = flash_attn_func(q_fp8, k_fp8, v_fp8)\r\n# Result: ~1.2 PFLOPS, 1.5-2x faster than FP16\r\n```\r\n\r\n## When to use vs alternatives\r\n\r\n**Use Flash Attention when:**\r\n- Training transformers with sequences >512 tokens\r\n- Running inference with long context (>2K tokens)\r\n- GPU memory constrained (OOM with standard attention)\r\n- Need 2-4x speedup without accuracy loss\r\n- Using PyTorch 2.2+ or can install flash-attn\r\n\r\n**Use alternatives instead:**\r\n- **Standard attention**: Sequences \u003C256 tokens (overhead not worth it)\r\n- **xFormers**: Need more attention variants (not just speed)\r\n- **Memory-efficient attention**: CPU inference (Flash Attention needs GPU)\r\n\r\n## Common issues\r\n\r\n**Issue: ImportError: cannot import flash_attn**\r\n\r\nInstall with no-build-isolation flag:\r\n```bash\r\npip install flash-attn --no-build-isolation\r\n```\r\n\r\nOr install CUDA toolkit first:\r\n```bash\r\nconda install cuda -c nvidia\r\npip install flash-attn --no-build-isolation\r\n```\r\n\r\n**Issue: Slower than expected (no speedup)**\r\n\r\nFlash Attention benefits increase with sequence length:\r\n- \u003C512 tokens: Minimal speedup (10-20%)\r\n- 512-2K tokens: 2-3x speedup\r\n- >2K tokens: 3-4x speedup\r\n\r\nCheck sequence length is sufficient.\r\n\r\n**Issue: RuntimeError: CUDA error**\r\n\r\nVerify GPU supports Flash Attention:\r\n```python\r\nimport torch\r\nprint(torch.cuda.get_device_capability())\r\n# Should be ≥(7, 5) for Turing+\r\n```\r\n\r\nFlash Attention requires:\r\n- Ampere (A100, A10): ✅ Full support\r\n- Turing (T4): ✅ Supported\r\n- Volta (V100): ❌ Not supported\r\n\r\n**Issue: Accuracy degradation**\r\n\r\nCheck dtype is float16 or bfloat16 (not float32):\r\n```python\r\nq = q.to(torch.float16)  # Or torch.bfloat16\r\n```\r\n\r\nFlash Attention uses float16\u002Fbfloat16 for speed. Float32 not supported.\r\n\r\n## Advanced topics\r\n\r\n**Integration with HuggingFace Transformers**: See [references\u002Ftransformers-integration.md](references\u002Ftransformers-integration.md) for enabling Flash Attention in BERT, GPT, Llama models.\r\n\r\n**Performance benchmarks**: See [references\u002Fbenchmarks.md](references\u002Fbenchmarks.md) for detailed speed and memory comparisons across GPUs and sequence lengths.\r\n\r\n## Hardware requirements\r\n\r\n- **GPU**: NVIDIA Ampere+ (A100, A10, A30) or AMD MI200+\r\n- **VRAM**: Same as standard attention (Flash Attention doesn't increase memory)\r\n- **CUDA**: 12.0+ (11.8 minimum)\r\n- **PyTorch**: 2.2+ for native support\r\n\r\n**Not supported**: V100 (Volta), CPU inference\r\n\r\n## Resources\r\n\r\n- Paper: \"FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness\" (NeurIPS 2022)\r\n- Paper: \"FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning\" (ICLR 2024)\r\n- Blog: https:\u002F\u002Ftridao.me\u002Fblog\u002F2024\u002Fflash3\u002F\r\n- GitHub: https:\u002F\u002Fgithub.com\u002FDao-AILab\u002Fflash-attention\r\n- PyTorch docs: https:\u002F\u002Fpytorch.org\u002Fdocs\u002Fstable\u002Fgenerated\u002Ftorch.nn.functional.scaled_dot_product_attention.html\r\n",{"name":5,"author":44,"license":15,"version":45,"metadata":46,"platforms":57,"description":7,"dependencies":58},"Orchestra Research","1.0.0",{"hermes":47},{"tags":48},[30,49,50,51,52,53,54,55,56,22,28],"Flash Attention","Attention Optimization","Memory Efficiency","Speed Optimization","Long Context","PyTorch","SDPA","H100",[38,29],[59,60,61],"flash-attn","torch","transformers","main","0d1434f89f4bc6b07e9d272accd8c1013768820f","archive\u002Fskill-md-reviewed\u002Fsha256\u002F05\u002F05fb618f2939f16295bb36851a38fcc26755f8d1dce9897c2247a87d9ec7ef24",0,"https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills","https:\u002F\u002Fgithub.com\u002Fzapabob","The Open University of JAPAN　2019-now\r\n\r\nTokyo University of Science　2007-2010","2026-10-26 16:29:01",{"source":8,"skillName":5,"commands":71,"prompt":81,"zipAvailable":82},[72,75,78],{"tool":73,"command":74},"npx","npx skills add zapabob\u002FSkills --skill optimizing-attention-flash",{"tool":76,"command":77},"bunx","bunx skills add zapabob\u002FSkills --skill optimizing-attention-flash",{"tool":79,"command":80},"pnpm","pnpm dlx skills add zapabob\u002FSkills --skill optimizing-attention-flash","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Farchive\u002Fskill-md-reviewed\u002Fsha256\u002F05\u002F05fb618f2939f16295bb36851a38fcc26755f8d1dce9897c2247a87d9ec7ef24\u002FSKILL.md",true,[],[85,108,132,154,177,193],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":39},"01M6GJTE1GESGGF9K028Y7753E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fxurl\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[87,92,29,93,94,38,95,96,97,98,99,100,101,102,103,104,62,105,106,107],"openclaw","cli","github","windows","official","search","https","social-media","api","Media","hermes","hermes agent","twitter","social","via","post",{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":39},"01M6GJT8S1PXQ8WPXT1HSNBWH2","writing-plans","Write implementation plans: bite-sized tasks, paths, code.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwriting-plans\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[115,116,117,118,29,119,38,120,95,121,122,123,124,125,126,127,128,129,130,131],"writing","writing plans","plans","design","review","workflow","documentation","tasks","development","code","planning","code-review","subagent","write","superpowers","paths","test-driven-development",{"skillNo":133,"name":134,"nameZh":6,"description":135,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":39},"01M6GJST0H5X7WHBJ3BZK0DVKH","whisper","OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwhisper\u002Fvariants\u002Fhermes-agent-optional\u002FSKILL.md",[],[134,29,38,139,140,141,28,142,143,144,145,146,26,147,148,149,150,151,152,153],"openai","speech","multimodal","ASR","Audio","text","model","speech recognition","general","multilingual","translation","english","identification","processing","Audio Processing",{"skillNo":155,"name":156,"nameZh":6,"description":157,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":158,"categories":159,"keywords":160,"publishedAt":39},"01M6GJSMRQ8EETZTYMG72P70EA","weights-and-biases","W&B: log ML experiments, sweeps, model registry, dashboards.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fweights-and-biases\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[161,29,162,163,95,35,164,165,166,167,168,145,169,170,171,172,173,174,175,176],"weights and biases","tensorflow","experiments","visualization","registry","real-time","tuning","dashboards","experiment","log","time","Experiment Tracking","Model Registry","Hyperparameter Tuning","WandB","Real-Time Visualization",{"skillNo":178,"name":179,"nameZh":6,"description":180,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":181,"categories":182,"keywords":183,"publishedAt":39},"01M6GJS19KDPRY112JTR326S06","watchers","Poll RSS, JSON APIs, and GitHub with watermark dedup.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fwatchers\u002Fvariants\u002Fhermes-agent-optional\u002FSKILL.md",[],[179,29,184,94,38,185,186,187,188,189,190,102,103,191,192],"terminal","automation","http","monitoring","cron","json","rss","devops","with",{"skillNo":194,"name":195,"nameZh":6,"description":196,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":197,"categories":198,"keywords":199,"publishedAt":39},"01M6GJRHJD2A6Q830SWF9W48BC","serving-llms-vllm","vLLM: high-throughput LLM serving, OpenAI API, quantization.","https:\u002F\u002Fgithub.com\u002Fzapabob\u002FSkills\u002Fblob\u002Fmain\u002Fregistry\u002Fskills\u002Fvllm\u002Fvariants\u002Fhermes-agent\u002FSKILL.md",[],[200,201,202,38,36,139,203,204,205,28,206,100,207,208,209,210,211,212,213,214],"llms","vLLM","serving llms vllm","openai api","tensor","Inference Serving","Production","llm serving","High Throughput","PagedAttention","Continuous Batching","Quantization","Tensor Parallelism","high-throughput","throughput"]