Example

Find out which attention kernel actually ran

Ask PyTorch for FlashAttention, record that the kernel was unavailable here, and compare the CPU fallback without inventing a speedup.

FlashAttention is a family of attention implementations that avoid materialising the full score matrix in high-bandwidth memory. It is a mechanism, not a boolean property of a framework. Asking for it can fail, fall back, or run a different kernel, and the result object must say which happened.

This example probes three CUDA SDPA backends and a CPU fallback. On this machine CUDA was present, but the FlashAttention backend was not available: PyTorch returned No available kernel. Aborting execution. The math and memory-efficient backends ran, and the CPU SDPA path ran on the same inputs. The page records that absence instead of quoting a speedup from a kernel that did not execute. The chapter’s separate tiled implementation shows the online-softmax mechanism when the library kernel is unavailable.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch13/flash_attention.py --seq-len 64 --d-head 32 --json

Python 3.11 or later with PyTorch. The CPU fallback always runs; CUDA rows appear only when a GPU is available. No model download, network or credentials. It finishes in a few seconds, with some PyTorch deprecation warnings on stderr.

Implementation

The CPU path compares naive attention with scaled_dot_product_attention. On CUDA, run_backend enables exactly one backend at a time, synchronises around the timed call, and catches the exception that an unavailable kernel raises.

def run_backend(name: str, q, k, v, causal=True) -> BackendResult:
    if not torch.cuda.is_available():
        return BackendResult(backend=name, available=False, seconds=0.0, max_abs_error=0.0, metadata={"reason": "no cuda"})
    qd, kd, vd = q.cuda(), k.cuda(), v.cuda()
    ref = naive_attention(qd, kd, vd, causal=causal)
    available = True
    try:
        # Enable only requested backend.
        with torch.backends.cuda.sdp_kernel(enable_flash=(name == "flash"), enable_math=(name == "math"), enable_mem_efficient=(name == "mem_efficient")):
            torch.cuda.synchronize()
            start = time.perf_counter()
            out = F.scaled_dot_product_attention(qd, kd, vd, is_causal=causal)
            torch.cuda.synchronize()
            seconds = time.perf_counter() - start
        max_abs_error = float((ref - out).abs().max().item())
    except Exception as exc:
        available = False
        seconds = 0.0
        max_abs_error = 0.0
        return BackendResult(backend=name, available=available, seconds=seconds, max_abs_error=max_abs_error, metadata={"error": str(exc)})
    return BackendResult(backend=name, available=available, seconds=seconds, max_abs_error=max_abs_error, metadata={})


def run(seq_len: int, d_head: int, batch: int = 1, heads: int = 2, seed: int = 0) -> List[BackendResult]:
    torch.manual_seed(seed)
    q = torch.randn(batch, heads, seq_len, d_head)
    k = torch.randn(batch, heads, seq_len, d_head)
    v = torch.randn(batch, heads, seq_len, d_head)
    # CPU fallback: always run naive vs SDPA on CPU.
    ref = naive_attention(q, k, v)
    start = time.perf_counter()
    out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
    cpu_seconds = time.perf_counter() - start
    cpu_error = float((ref - out).abs().max().item())
    results = [BackendResult(backend="cpu-sdpa", available=True, seconds=cpu_seconds, max_abs_error=cpu_error, metadata={"device": "cpu"})]
    if torch.cuda.is_available():
        for name in ("flash", "math", "mem_efficient"):
            results.append(run_backend(name, q, k, v))
    return results

Expected outcome

Observed with the command above (exit 0). Selected stable fields:

    "backend": "cpu-sdpa",
    "available": true,
    "backend": "flash",
    "available": false,
    "metadata": {
      "error": "No available kernel. Aborting execution."
    }

The CPU SDPA path agreed with the naive reference to 4.17e-07. The math and memory-efficient backends also reported available: true, with errors of 4.77e-07 and 3.58e-07. The FlashAttention row is a genuine negative result: the code asked, the kernel refused, and the record says so. Timings are omitted because they vary and because the unavailable row has no time to report.

Mechanism and limitations

Documented: run always performs the CPU comparison. run_backend returns available: false when CUDA is absent, enables one SDPA backend at a time, and catches the kernel exception into metadata["error"]. The tests check that the CPU backend is present, its error is below 1e-5, the result serialises, and every availability flag is a boolean.

Observed: the command exited 0 with the availability and error fields above. The targeted tests.test_ch13_flash is part of the canonical suite; no independent test count is claimed here.

Not shown: a FlashAttention speedup, GPU memory saving, a production kernel version, or the reason this GPU/PyTorch combination refused the kernel. The page does not infer a cause from the error string. It also does not show the tiled online-softmax implementation; that is examples/ch13/tiled_attention.py, a separate source file with its own tests, and it was not the command run here.

Challenge this result

Run the command on a machine where the flash backend is available and compare the availability flags, not just the times. If flash is available, check that its output agrees with the naive reference before quoting any speedup. Then run the same command with --seq-len 1024 and explain why a kernel that is unavailable at 64 positions might become available, or fail differently, at a larger shape. Do not change the page’s negative result to a positive one without a new run.

Source and verification

Canonical source: examples/ch13/flash_attention.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch13_flash.py . Chapter: FlashAttention and Optimized Kernels . The run above is a fresh local execution on Windows 11 with Python 3.13.15 and PyTorch 2.6.0+cu124; the flash kernel was unavailable and no speedup is claimed.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.