Example

Compare naive attention with the library kernel

Compute attention twice at 64 positions, check the answers agree, and see which cost is quadratic in the sequence length.

Attention writes down a score for every query-key pair. At sequence length T that is T * T scores per head, before any masking. The arithmetic grows with T^2, even though the number of tokens grows only with T. That is the cost this chapter is about, and it is separate from which kernel computes it.

This example compares a hand-written naive attention with PyTorch’s scaled dot-product attention at 64 positions. The outputs agree to float32 rounding. The timings differ on this machine, but the more durable result is the shape of the work: two heads, 64 queries, 64 keys, 32 values per head. The page does not claim a CUDA speedup; the run used the CPU path and the library may select different kernels on another machine.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch08/attention.py --seq-len 64 --d-head 32 --json

Python 3.11 or later with PyTorch. CPU-only by default; no model download, network, GPU or credentials. It finishes in about a second. The CUDA peak-memory field is populated only when a GPU is available, but the comparison itself runs on CPU.

Implementation

The naive path materialises the full score matrix, applies the causal mask, and then multiplies by values. SDPA takes the same tensors and lets the library choose its kernel. The comparison seeds the tensors, so the two paths see identical inputs.

def naive_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, causal: bool = True) -> torch.Tensor:
    # q,k,v: [batch, heads, seq, d_head]
    d_head = q.shape[-1]
    scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(d_head)
    seq = q.shape[-2]
    if causal:
        mask = torch.triu(torch.ones(seq, seq, device=q.device, dtype=torch.bool), diagonal=1)
        scores = scores.masked_fill(mask, float("-inf"))
    weights = torch.softmax(scores, dim=-1)
    return torch.matmul(weights, v)


def sdpa_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, causal: bool = True) -> torch.Tensor:
    return F.scaled_dot_product_attention(q, k, v, is_causal=causal)


def run_comparison(seq_len: int, d_head: int, batch: int = 1, heads: int = 2, seed: int = 0) -> ComparisonResult:
    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)

    start = time.perf_counter()
    out_naive = naive_attention(q, k, v, causal=True)
    naive_seconds = time.perf_counter() - start

    start = time.perf_counter()
    out_sdpa = sdpa_attention(q, k, v, causal=True)
    sdpa_seconds = time.perf_counter() - start

    max_abs_error = float((out_naive - out_sdpa).abs().max().item())

Expected outcome

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

  "seq_len": 64,
  "d_head": 32,
  "max_abs_error": 4.172325134277344e-07,
  "causal": true,

The maximum difference is 4.17e-07, consistent with float32 arithmetic. In this run the naive path took about 0.00238 s and SDPA about 0.00041 s. Those times are a single CPU trace, not a kernel benchmark. The number of score entries was 1 batch * 2 heads * 64 queries * 64 keys = 8,192; doubling the sequence length to 128 would quadruple that count to 32,768.

Mechanism and limitations

Documented: naive_attention applies the causal mask before softmax and returns the weighted values. sdpa_attention delegates to torch.nn.functional.scaled_dot_product_attention with is_causal=True. The tests check output shape, the causal path, numerical agreement within 1e-5, rejection of a zero sequence length and JSON serialisation.

Observed: the command exited 0 with max_abs_error 4.172325134277344e-07 and causal: true. The targeted tests.test_ch08_attention is part of the canonical suite; no independent test count is claimed here.

Not shown: a GPU kernel’s performance; FlashAttention; memory traffic on a real accelerator; multi-batch or multi-head scaling beyond this fixture; or the quality effect of attention in a trained model. The timing is not evidence that SDPA is faster in production, and the peak_memory_bytes field is a CUDA allocator reading that is absent or irrelevant on a CPU-only run.

Challenge this result

Run --seq-len 128 and --seq-len 256. Compute the score-entry count for each before running. Then predict how the naive time should grow if arithmetic dominated, and compare with the measured times. If the growth is not quadratic, identify at least two reasons: Python and launch overhead, cache effects, or the library choosing a different kernel. Explain why a single timing cannot separate those causes.

Source and verification

Canonical source: examples/ch08/attention.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch08_attention.py . Chapter: Attention and Its Computational Cost . The run above is a fresh local execution on Windows 11 with Python 3.13.15 and PyTorch 2.6.0+cu124; it is a CPU trace, not a GPU benchmark.

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.