Unified Flash Attention Backend Wrapper | Generated by AI

Home 2026.08

nanochat/flash_attention.py is a unified wrapper around three attention backends for this GPT-style training/inference codebase. Its purpose: expose a single API that matches FlashAttention-3’s interface exactly, and automatically pick the best available kernel.

What it does

Backend auto-detection (at import time):

  1. FA3 (_load_flash_attention_3) — tries to load a kernel package. On Hopper (sm90, major == 9) it prefers the varunneal/flash-attention-3 HF kernel; on other archs it tries kernels-community/flash-attn3. Returns None on any failure (no CUDA, import error, etc.).
  2. FA2 (_load_flash_attention_2) — imports the flash-attn pip package. Works on both NVIDIA CUDA and AMD ROCm.
  3. SDPA fallback — plain PyTorch scaled_dot_product_attention, works everywhere.

Selection logic (_resolve_impl):

Public API (exported as flash_attn, a SimpleNamespace):

_sdpa_attention is the interesting piece — it emulates FA semantics that SDPA doesn’t do natively:

_fa2_window_size — normalizes FA3’s (-1, -1) convention to what FA2 expects.

Where it’s used

nanochat/gpt.py imports flash_attn and calls flash_attn.flash_attn_func(...) (line 110, training) or flash_attn.flash_attn_with_kvcache(...) (line 114, generation), so the rest of the model code never needs to know which backend is running.

Possible issues worth noting


Generated by AI. Curating and sharing still takes effort. If you find it useful, feel free to donate. WeChat: @lzwjavaWeChat QR · X: @lzwjava · Say hi 👋

Back Donate