Coding tutorial · Build it from scratch

Build Attention From Scratch

We write attention by hand, one tensor at a time, and grow it into MHA, GQA, MLA and a tiled online softmax. The core layers are tested against trusted implementations, and every timing is a real run on a CPU.

AttentionKV cacheFlashAttention

A small attention library called attnzoo. One config describes the architecture (MHA, MQA, GQA, MLA, linear, cross). A separate setting picks the kernel that runs it (naive, SDPA, tiled, FlashAttention). A test suite proves the versions agree with each other, with PyTorch and with Hugging Face.

Time
A long afternoon, or one part per sitting
Hardware
Any CPU. MPS optional. A CUDA GPU only for the GPU runs in parts 8 and 12.
You need
Python 3.10+, PyTorch 2.5+, pytest, and PyTorch From First Principles
Package
attnzoo
Final repo tree c03-attention/
c03-attention/
├── README.md               # how to run everything, results table
├── attnzoo/
│   ├── core.py             # part 1: attention with every step visible
│   ├── masks.py            # part 2: every mask, by hand
│   ├── heads.py            # part 3: split, merge, repeat_kv
│   ├── mha.py              # part 3: MHA, fused QKV, MQA
│   ├── gqa.py              # part 3: the unified module
│   ├── rope.py             # part 4: RoPE
│   ├── kv_cache.py         # part 4: dynamic and static caches
│   ├── attention_window.py # part 5: chunked sliding window
│   ├── linear.py           # part 5: linear attention and Performer
│   ├── vision.py           # part 6: patches and windows
│   ├── pos2d.py            # part 6: 2D positions
│   ├── cross.py            # part 6: cross-attention and gates
│   ├── resampler.py        # part 6: Q-Former and Perceiver
│   ├── fusion.py           # part 6: VLM fusion patterns
│   ├── mla.py              # part 7: multi-head latent attention
│   ├── attention_naive.py  # part 8: the reference backend
│   ├── attention_sdpa.py   # part 8: the torch backend
│   ├── attention_tiled.py  # part 8: online softmax
│   ├── attention_flash.py  # part 8: GPU-only kernels
│   ├── backends.py         # part 8: one signature, many kernels
│   ├── stability.py        # part 9: QK-norm, soft-cap
│   ├── biases.py           # part 9: ALiBi, relative bias
│   ├── variants.py         # part 9: research variants
│   ├── config.py           # part 10: AttentionConfig
│   └── library.py          # part 10: build_attention
├── configs/                # Llama-like, DeepSeek-like, Mistral-like
├── scripts/                # one demo per part
├── benchmarks/             # KV memory, window, backends, zoo
├── results/                # the real outputs quoted in this post
└── tests/                  # 12 test files, run in seconds

The plan

Almost every speed and memory decision in a modern language model lives inside one small function. What does that function compute, tensor by tensor, and how do we know each faster version is still correct?

We answer by building it. We start with four lines of PyTorch. We add one idea at a time and test each one. By the end the same four lines run behind a config that covers the attention of Llama, DeepSeek and Swin.

The derivations live in the theory posts, so we link them and move on. Here we implement the idea and look at what happens.

The post has twelve parts. Each stands alone, so you can stop after any of them.

The twelve parts and what each one adds
PartWe buildMain check
1. Core attentionScaled dot-product, one head, cross-attentionEquals F.scaled_dot_product_attention
2. MasksCausal, padding, prefix, document, multimodalChanging the future does not change the past
3. Head sharingMHA, fused QKV, MQA, GQA in one moduleGQA equals MHA when HKV = HQ
4. RoPE and cacheRotations, offsets, dynamic and static cachesCached output equals the full forward; formula equals tensor bytes
5. Sparse and linearWindow masks, a chunked kernel, linear attentionChunked equals masked; recurrence equals parallel
6. Vision and multimodalViT, Swin windows, 2D RoPE, Q-Former, PerceiverOne big window equals global attention
7. Latent attentionMLA in four steps, then without materialising KAbsorbed equals explicit
8. BackendsSDPA, online softmax, FlashAttentionTiled equals naive
9. StabilityDropout, ALiBi, QK-norm, soft-cap, variantsLogits stay bounded as activations grow
10. LibraryAttentionConfig and build_attentionMHA, MQA, GQA and MLA on five CPU backends
11. TestsThe whole suite, in one runAll pass
12. BenchmarksTraining, prefill and decode for the whole zooReal CPU numbers, with the hardware named

Clone the repo once. Every command below runs from its root.

$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"

Every timing below came from one AMD EPYC 7R13 server CPU, limited to 8 threads, on PyTorch 2.15. Other jobs shared that machine. So read absolute times as rough, and trust the ratios and the scaling more. Cache byte counts and numerical errors do not depend on load. Peak memory figures are noisy.

The GPU numbers are separate. They came from one run on one NVIDIA H100 80GB HBM3, with PyTorch 2.15.0 built for CUDA 13.2, in bf16, and every GPU table says so. The CPU runs use fp32, so do not compare the two cell by cell. The flash-attn package was not installed. So Tri Dao’s own FlashAttention kernels are not measured. The flash backend ran PyTorch’s FlashAttention-2 through SDPA.

Part 01

Core attention: one function, one head

Goal Write attention with every intermediate tensor visible, and show it equals PyTorch’s version.

Attention takes three tensors. Queries ask. Keys answer how relevant they are. Values hold what gets passed along. Each output row is a weighted average of the value rows, and the weights come from query-key dot products.

Derivation inHow attention moves information
def scaled_dot_product_attention(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    mask: torch.Tensor | None = None,
    scale: float | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Attention with every step visible.

    Shapes (any number of leading batch dims, usually B x H):
        q:    (..., Nq, d)
        k:    (..., Nk, d)
        v:    (..., Nk, dv)
        mask: bool, broadcastable to (..., Nq, Nk). True means "may attend".
    Returns:
        out:     (..., Nq, dv)
        weights: (..., Nq, Nk), each row sums to 1
    """
    d = q.size(-1)
    scale = 1.0 / math.sqrt(d) if scale is None else scale

    scores = q @ k.transpose(-2, -1)  # (..., Nq, Nk): one dot product per query-key pair
    scores = scores * scale  # keeps the logit variance near 1 when d grows
    if mask is not None:
        scores = scores.masked_fill(~mask, float("-inf"))  # exp(-inf) = 0 after softmax

    weights = torch.softmax(scores, dim=-1)  # normalise over keys
    out = weights @ v  # (..., Nq, dv): a weighted average of value rows
    return out, weights
Listing 1The reference. The highlighted lines are the whole algorithm.

Read the shapes in the docstring first. The leading dimensions are free, so the same function serves one head or many. The rows of scores are queries and the columns are keys. That is why the softmax runs on the last axis: each query spreads its attention over the keys.

The scale matters. If q and k have unit-variance entries, their dot product has variance d. Dividing by sqrt(d) brings it back to 1, so the softmax does not saturate as the head grows.

Run it on the smallest case that shows everything: two queries, three keys, four dimensions.

$ .venv/bin/python c03-attention/scripts/shapes.py
--- attention on raw q, k, v (B=1, Nq=2, Nk=3, d=4) ---
q          (1, 2, 4)            torch.float32
k          (1, 3, 4)            torch.float32
v          (1, 3, 4)            torch.float32
weights    (1, 2, 3)            torch.float32
out        (1, 2, 4)            torch.float32
weights row sums: tensor([[1.000, 1.000]])
weights:
 tensor([[0.328, 0.391, 0.281],
        [0.632, 0.211, 0.157]])

Figure 1One attention call, tensor by tensor, for B = 2, H = 4, N = 6, d = 8. The camera follows the data from the input to the merged output. The six-by-six grid holds real scores and weights from one head of scripts/export_figure_data.py. The other grids only show shapes.
Shapes in the core function
TensorShapeMeaning
q(B, H, Nq, d)One query vector per head and query position.
k, v(B, H, Nk, d)One key and one value per head and key position.
scores(B, H, Nq, Nk)Query i against key j in cell (i, j).
weights(B, H, Nq, Nk)Each row is a distribution over keys.
out(B, H, Nq, d)Same length as the queries, not the keys.

Self-attention: one sequence, three projections

Self-attention means q, k and v are all linear projections of one sequence. That is all a head is.

class SelfAttentionHead(nn.Module):
    """One attention head: project the same sequence into queries, keys and values.

    x: (B, N, d_model) -> out: (B, N, d_head)
    """

    def __init__(self, d_model: int, d_head: int, bias: bool = False) -> None:
        super().__init__()
        self.w_q = nn.Linear(d_model, d_head, bias=bias)
        self.w_k = nn.Linear(d_model, d_head, bias=bias)
        self.w_v = nn.Linear(d_model, d_head, bias=bias)

    def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
        q, k, v = self.w_q(x), self.w_k(x), self.w_v(x)  # each (B, N, d_head)
        out, _ = scaled_dot_product_attention(q, k, v, mask=mask)
        return out
Listing 2A single head. No masks, no positions, no tricks yet.

Cross-attention: two sequences

Cross-attention changes one thing. The queries come from one sequence, and the keys and values come from another. The output length follows the queries. The other sequence can have any length and even a different width.

class CrossAttention(nn.Module):
    """hidden_states (B, Nq, D), context (B, Ns, Dc) -> (B, Nq, D).

    No causal mask (every query may read the whole context) and no RoPE (the two
    sequences have unrelated positions). context_mask: (B, Ns) 1 = real, 0 = pad.
    """

    def __init__(self, config: AttentionConfig) -> None:
        super().__init__()
        self.config = config
        h, hkv, dh = config.num_heads, config.num_kv_heads, config.head_dim
        self.q_proj = nn.Linear(config.hidden_size, h * dh, bias=config.qkv_bias)
        self.k_proj = nn.Linear(config.context_size, hkv * dh, bias=config.qkv_bias)  # from the context width
        self.v_proj = nn.Linear(config.context_size, hkv * dh, bias=config.qkv_bias)
        self.o_proj = nn.Linear(h * dh, config.hidden_size, bias=False)

    def forward(self, hidden_states: torch.Tensor, context: torch.Tensor, context_mask: torch.Tensor | None = None) -> torch.Tensor:
        q = split_heads(self.q_proj(hidden_states), self.config.num_heads)  # (B, H, Nq, dh)
        k = split_heads(self.k_proj(context), self.config.num_kv_heads)  # (B, Hkv, Ns, dh)
        v = split_heads(self.v_proj(context), self.config.num_kv_heads)
        mask = padding_mask(context_mask) if context_mask is not None else None
        out = attend(q, k, v, mask, backend=self.config.backend, causal=False)  # (B, H, Nq, dh)
        return self.o_proj(merge_heads(out))
Listing 3The projections for keys and values start from the context width. Text to text, text to image, and learned latents to image are all this module.
--- cross-attention: the output length follows the queries ---
text -> text       query (2, 6, 32), context (2, 9, 48) -> (2, 6, 32)
text -> image      query (2, 6, 32), context (2, 196, 48) -> (2, 6, 32)
latents -> image   query (2, 8, 32), context (2, 729, 48) -> (2, 8, 32)

Checkpoint

  • shapes.py prints weight rows that sum to 1.
  • tests/test_core.py passes.
Part 02

Masks: deciding who may read whom

Goal Build every mask you will meet by hand, look at each one, and catch the two classic mask bugs.

A mask is a boolean tensor of shape (Nq, Nk). True means this query may read this key. We use the same convention as PyTorch’s SDPA. The most important mask is causal, and it has one detail that many first versions get wrong.

def causal_mask(nq: int, nk: int | None = None, device: torch.device | str | None = None) -> torch.Tensor:
    """Lower-triangular mask, aligned to the bottom-right corner. Shape (nq, nk).

    With a KV cache the queries are the *last* nq of nk positions, so query i
    sits at absolute position i + (nk - nq) and may see keys up to that position.
    """
    nk = nq if nk is None else nk
    offset = nk - nq
    q_pos = torch.arange(nq, device=device)[:, None] + offset
    k_pos = torch.arange(nk, device=device)[None, :]
    return k_pos <= q_pos
Listing 4The causal mask, built from absolute positions. It lines up with the bottom-right corner, which is what decoding with a cache needs. We return to this in part 4.

Padding is different. It belongs to keys, not to pairs. No query should read a pad token, so the mask has shape (B, 1, 1, Nk) and broadcasts over heads and queries.

def padding_mask(attention_mask: torch.Tensor) -> torch.Tensor:
    """Turn a tokenizer-style (B, Nk) 1/0 mask into a (B, 1, 1, Nk) key mask.

    Padding is a property of keys: no query should read a pad token.
    """
    return attention_mask.bool()[:, None, None, :]

Multimodal sequences need one more rule. Image patches have no reading order, so patches of one image may see each other in both directions. Text stays causal, and text after the image sees all of it.

def multimodal_mask(span_ids: torch.Tensor) -> torch.Tensor:
    """Causal everywhere, but tokens of one image see each other in both directions.

    span_ids: (B, N) with 0 for text tokens and k > 0 for tokens of the k-th image.
    Returns (B, 1, N, N). Text after an image sees the whole image (it is in the past);
    image patches see the full image they belong to, as most VLM decoders do.
    """
    n = span_ids.size(1)
    causal = causal_mask(n, device=span_ids.device)
    same_image = (span_ids[:, :, None] == span_ids[:, None, :]) & (span_ids[:, :, None] > 0)
    return (causal | same_image)[:, None]
Listing 5The multimodal mask is a causal mask plus one extra OR term.

Try them. Pick a type and move the sliders. The printed tensor is what the matching function in masks.py returns.

Allowed pairs0
Of all N×N0%
Keys per query0

          
Figure 2The mask builder. Rows are queries and columns are keys. Blue cells may attend. Orange marks the image span in the multimodal mask. Density is how many scores survive, but the dense path still computes them all, as part 5 shows.

The script prints every mask in ASCII, including two you will see again later. Here are a few of them.

$ .venv/bin/python c03-attention/scripts/show_masks.py
packed documents [0,0,0,1,1,2,2,2]  (15/64 pairs allowed)
#.......
##......
###.....
...#....
...##...
.....#..
.....##.
.....###
decoding: 2 queries, 8 keys (bottom-right aligned)  (15/16 pairs allowed)
#######.
########

Checkpoint

  • show_masks.py prints eleven masks and each one matches its definition.
  • tests/test_masks.py and the causality test pass.
Part 03

Head sharing: MHA, MQA and GQA

Goal Write multi-head attention, fuse its projections, then share keys and values across heads until one module covers all three.

Heads are a reshape

Multi-head attention does not add a separate network per head. It projects to the full width and cuts the result into H slices, so D = H * dh. Two helpers do the cutting and the gluing.

def split_heads(x: torch.Tensor, num_heads: int) -> torch.Tensor:
    """(B, N, H*d) -> (B, H, N, d).

    view() splits the last dim into (H, d); transpose() moves H next to B so that
    the matmuls in attention batch over (B, H) and contract over d.
    """
    b, n, _ = x.shape
    return x.view(b, n, num_heads, -1).transpose(1, 2)


def merge_heads(x: torch.Tensor) -> torch.Tensor:
    """(B, H, N, d) -> (B, N, H*d).

    After transpose() the memory is no longer laid out row by row, so view()
    would fail. contiguous() copies it into the order view() needs.
    """
    b, h, n, d = x.shape
    return x.transpose(1, 2).contiguous().view(b, n, h * d)
Listing 6Reshape, then move the head axis next to the batch axis so the matmuls batch over (B, H).

The contiguous() call is not decoration. After transpose, the elements are no longer in the order view needs, and view refuses to run. See the shape errors in the Break it box below.

class MultiHeadAttention(nn.Module):
    """x (B, N, D) -> (B, N, D), with D = num_heads * head_dim."""

    def __init__(self, hidden_size: int, num_heads: int, causal: bool = False, backend: str = "naive") -> None:
        super().__init__()
        if hidden_size % num_heads:
            raise ValueError("hidden_size must be divisible by num_heads")
        self.num_heads, self.causal, self.backend = num_heads, causal, backend
        self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
        self.k_proj = nn.Linear(hidden_size, hidden_size, bias=False)
        self.v_proj = nn.Linear(hidden_size, hidden_size, bias=False)
        self.o_proj = nn.Linear(hidden_size, hidden_size, bias=False)

    def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None = None) -> torch.Tensor:
        q = split_heads(self.q_proj(x), self.num_heads)  # (B, H, N, dh)
        k = split_heads(self.k_proj(x), self.num_heads)
        v = split_heads(self.v_proj(x), self.num_heads)
        out = attend(q, k, v, attn_mask, backend=self.backend, causal=self.causal)  # (B, H, N, dh)
        return self.o_proj(merge_heads(out))  # mix information across heads
Listing 7Multi-head attention. The output projection is what lets heads exchange information.

Fused projections

Three linear layers mean three matmuls. One wide layer does the same work in one call, and the output is split afterwards. The weight of the fused layer is the three weights stacked. So we can copy one into the other and check the outputs match.

class FusedQKVAttention(nn.Module):
    """One (D -> 3D) matmul instead of three (D -> D) ones: fewer kernel launches, same result."""

    def __init__(self, hidden_size: int, num_heads: int, causal: bool = False, backend: str = "naive") -> None:
        super().__init__()
        self.num_heads, self.causal, self.backend = num_heads, causal, backend
        self.qkv_proj = nn.Linear(hidden_size, 3 * hidden_size, bias=False)
        self.o_proj = nn.Linear(hidden_size, hidden_size, bias=False)

    def forward(self, x: torch.Tensor, attn_mask: torch.Tensor | None = None) -> torch.Tensor:
        q, k, v = self.qkv_proj(x).chunk(3, dim=-1)  # three (B, N, D) views of one (B, N, 3D) tensor
        q, k, v = (split_heads(t, self.num_heads) for t in (q, k, v))
        out = attend(q, k, v, attn_mask, backend=self.backend, causal=self.causal)
        return self.o_proj(merge_heads(out))
Listing 8One projection, then chunk.
--- three Linear layers against one fused Linear ---
separate params: 4096
fused params:    4096
max |separate - fused|: 0.0

Fusing does not change the maths or the parameter count. On this CPU it is usually slightly slower, and the spread between runs exceeds the gap. In six reruns of scripts/compare_heads.py, for the projections alone, fused was slower in five and faster in one: 32 to 45 ms per call fused against 29 to 36 ms separate. The saved run has 39.21 ms against 38.33 ms. The usual argument for fusing is about accelerators, where one big matmul should use the hardware better than three small launches. We have not measured that on a GPU. GPT-2 style code (c_attn) and nn.MultiheadAttention both fuse.

Sharing keys and values

Queries are used once and thrown away. Keys and values for past tokens stay in the cache for the whole decode. So the cache pays for KV width, while the queries do not. That asymmetry is the idea behind multi-query attention. Keep H query heads, but use a single shared key and value head.

class MultiQueryAttention(nn.Module):
    """H query heads, one K head and one V head (Shazeer, 2019). The cache shrinks H times."""

    def __init__(self, hidden_size: int, num_heads: int, causal: bool = True) -> None:
        super().__init__()
        self.num_heads, self.causal = num_heads, causal
        self.head_dim = hidden_size // num_heads
        self.q_proj = nn.Linear(hidden_size, hidden_size, bias=False)
        self.k_proj = nn.Linear(hidden_size, self.head_dim, bias=False)  # D -> dh, not D -> D
        self.v_proj = nn.Linear(hidden_size, self.head_dim, bias=False)
        self.o_proj = nn.Linear(hidden_size, hidden_size, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        q = split_heads(self.q_proj(x), self.num_heads)  # (B, H, N, dh)
        k = split_heads(self.k_proj(x), 1)  # (B, 1, N, dh)
        v = split_heads(self.v_proj(x), 1)
        # No copy needed: the size-1 head dim of k broadcasts against H in the matmul.
        mask = causal_mask(x.size(1), device=x.device) if self.causal else None
        out, _ = scaled_dot_product_attention(q, k, v, mask=mask)  # (B, H, N, dh)
        return self.o_proj(merge_heads(out))
Listing 9MQA. The shared K and V have one head of width dh, and broadcasting does the rest.

GQA sits between the two. Groups of n_rep = Hq / Hkv query heads share one KV head. The maths is the same once the KV heads are repeated to line up with the query heads.

def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
    """(B, Hkv, N, d) -> (B, Hkv*n_rep, N, d): give every query head its KV head.

    Query head h reads KV head h // n_rep. expand() is free (a stride-0 view);
    the reshape afterwards is where the copy happens.
    """
    if n_rep == 1:
        return x
    b, hkv, n, d = x.shape
    return x[:, :, None, :, :].expand(b, hkv, n_rep, n, d).reshape(b, hkv * n_rep, n, d)
Listing 10Query head h reads KV head h // n_rep.

Figure 3Eight query heads, sharing fewer and fewer KV heads. The query heads never change. The KV heads merge into groups, and the cache tensor below shrinks in step. The strip shows one layer of the cached keys. Values take the same space again.

One module for all three

Since the only difference is num_kv_heads, one class can cover all three. This is the module later tutorials reuse. C4 mirrors a trimmed copy.

class GroupedQueryAttention(nn.Module):
    """hidden_states (B, N, D) -> (B, N, D).

    Inside:  q (B, Hq, N, dh)   k, v (B, Hkv, N, dh)   cache (B, Hkv, T, dh)
    """

    def __init__(self, config: AttentionConfig, layer_idx: int = 0) -> None:
        super().__init__()
        self.config = config
        self.layer_idx = layer_idx
        self.num_heads, self.num_kv_heads, self.head_dim = config.num_heads, config.num_kv_heads, config.head_dim
        d, dh = config.hidden_size, config.head_dim
        self.q_proj = nn.Linear(d, self.num_heads * dh, bias=config.qkv_bias)
        self.k_proj = nn.Linear(d, self.num_kv_heads * dh, bias=config.qkv_bias)  # smaller than q_proj for GQA
        self.v_proj = nn.Linear(d, self.num_kv_heads * dh, bias=config.qkv_bias)
        self.o_proj = nn.Linear(self.num_heads * dh, d, bias=False)
        if config.qk_norm:
            self.q_norm, self.k_norm = RMSNorm(dh), RMSNorm(dh)
        if config.positional_encoding == "rope":
            self.rotary = RotaryEmbedding(dh, config.max_seq_len, config.rope_theta)
        if config.positional_encoding == "alibi":
            self.register_buffer("slopes", alibi_slopes(self.num_heads), persistent=False)
    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.Tensor | None = None,
        kv_cache=None,
    ) -> torch.Tensor:
        """attention_mask: (B, Nk) 1/0 padding mask, or a 4D bool/float mask (B|1, 1, Nq, Nk).
        position_ids: (B, N) absolute positions; default continues from the cache length.
        kv_cache: a KVCache / StaticKVCache, updated in place.
        """
        b, n, _ = hidden_states.shape
        q = split_heads(self.q_proj(hidden_states), self.num_heads)  # (B, Hq, N, dh)
        k = split_heads(self.k_proj(hidden_states), self.num_kv_heads)  # (B, Hkv, N, dh)
        v = split_heads(self.v_proj(hidden_states), self.num_kv_heads)  # (B, Hkv, N, dh)

        if self.config.qk_norm:  # normalise before RoPE, as in OLMo 2 and Qwen3
            q, k = self.q_norm(q), self.k_norm(k)

        past = kv_cache.get_seq_length(self.layer_idx) if kv_cache is not None else 0
        if position_ids is None:
            position_ids = torch.arange(past, past + n, device=hidden_states.device)[None].expand(b, n)
        if self.config.positional_encoding == "rope":
            cos, sin = self.rotary(position_ids)
            q, k = apply_rotary(q, k, cos, sin)  # keys are cached already rotated

        if kv_cache is not None:
            k, v = kv_cache.update(k, v, self.layer_idx)  # (B, Hkv, T, dh), T = past + N

        mask = padding_mask(attention_mask) if attention_mask is not None and attention_mask.dim() == 2 else attention_mask
        if self.config.positional_encoding == "alibi":
            bias = alibi_bias(self.slopes, n, k.size(-2)).to(q.dtype)
            if mask is not None and mask.dtype == torch.bool:
                bias = bias.masked_fill(~mask, float("-inf"))
            elif mask is not None:
                bias = bias + mask
            mask = bias

        out = attend(
            q,
            k,
            v,
            mask,
            backend=self.config.backend,
            causal=self.config.causal,
            window_size=self.config.window_size,
            softcap=self.config.softcap,
            dropout_p=self.config.dropout if self.training else 0.0,
        )  # (B, Hq, N, dh)
        return self.o_proj(merge_heads(out))
$ .venv/bin/python c03-attention/scripts/compare_heads.py
layer   Hq  Hkv  n_rep               q            k, v    params
MHA     32   32      1 (2, 32, 16, 16) (2, 32, 16, 16) 1,048,576
GQA     32    8      4 (2, 32, 16, 16)  (2, 8, 16, 16)   655,360
GQA     32    2     16 (2, 32, 16, 16)  (2, 2, 16, 16)   557,056
MQA     32    1     32 (2, 32, 16, 16)  (2, 1, 16, 16)   540,672

repeat_kv: which KV head does each query head read? (Hq = 8, Hkv = 2)
[0, 0, 0, 0, 1, 1, 1, 1]

The unified module against the separate classes, weights copied:
GQA(Hkv=32) vs MHA: max |diff| = 1.64e-07
GQA(Hkv=1)  vs MQA: max |diff| = 1.79e-07
Shapes in the unified module, with cached length T
TensorShapeMeaning
hidden_states(B, N, D)Input, N new tokens.
q(B, Hq, N, dh)Only for the new tokens. Never cached.
k, v (new)(B, Hkv, N, dh)The part GQA makes smaller.
k, v (with cache)(B, Hkv, T, dh)All tokens so far, T = past + N.
out(B, Hq, N, dh)One output per query head.
merged(B, N, Hq * dh)Input to the output projection.

Checkpoint

  • compare_heads.py prints differences near 1e-7 for both equivalences.
  • tests/test_heads.py passes.
Part 04

RoPE and the KV cache

Goal Put positions inside attention, stop recomputing history, and check the memory formula against real tensors.

RoPE inside attention

RoPE encodes position by rotating queries and keys. The rotation has a useful property: the dot product of a rotated query and a rotated key depends only on how far apart they are. We build the tables once.

Derivation inHow models know where they are
class RotaryEmbedding(nn.Module):
    """Precomputes cos/sin tables for positions 0..max_seq_len-1.

    inv_freq: (d/2,)   one rotation speed per pair of dimensions
    cos, sin: (max_seq_len, d)
    """

    def __init__(self, head_dim: int, max_seq_len: int = 4096, theta: float = 10_000.0) -> None:
        super().__init__()
        inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2, dtype=torch.float32) / head_dim))
        positions = torch.arange(max_seq_len, dtype=torch.float32)
        freqs = torch.outer(positions, inv_freq)  # (S, d/2): angle = position * speed
        emb = torch.cat([freqs, freqs], dim=-1)  # (S, d): both halves of a pair share an angle
        # Not saved in checkpoints: they are a pure function of the config.
        self.register_buffer("inv_freq", inv_freq, persistent=False)
        self.register_buffer("cos_cached", emb.cos(), persistent=False)
        self.register_buffer("sin_cached", emb.sin(), persistent=False)

    def forward(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        """position_ids: (B, N) absolute positions -> cos, sin: (B, N, d)."""
        if position_ids.max() >= self.cos_cached.size(0):
            raise ValueError(f"position {int(position_ids.max())} exceeds max_seq_len {self.cos_cached.size(0)}")
        return self.cos_cached[position_ids], self.sin_cached[position_ids]
Listing 11The frequencies and the cos and sin tables. Each pair of dimensions rotates at its own speed.
def rotate_half(x: torch.Tensor) -> torch.Tensor:
    """(x1, x2) -> (-x2, x1) on the two halves of the last dim: a 90 degree turn of every pair."""
    x1, x2 = x.chunk(2, dim=-1)
    return torch.cat([-x2, x1], dim=-1)


def rotate(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """Rotate x (B, H, N, d) by its positions. cos/sin: (B, N, d), broadcast over heads."""
    cos, sin = cos[:, None].to(x.dtype), sin[:, None].to(x.dtype)
    return x * cos + rotate_half(x) * sin


def apply_rotary(
    q: torch.Tensor, k: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """Rotate q (B, Hq, N, d) and k (B, Hkv, N, d) with the same tables. Values are never rotated."""
    return rotate(q, cos, sin), rotate(k, cos, sin)
Listing 12The rotation. Values are never rotated. Their job is content, not matching.

This layout pairs dimension i with dimension i + d/2. It is the Llama and Hugging Face convention, and matching it lets us test against their code directly.

Two modes of attention

Generation runs in two modes with very different shapes. Prefill processes the prompt: Nq = Nk = N. Decode processes one new token: Nq = 1, and Nk = T, the whole history. Past keys and values never change, so we store them.

Theory inThe mechanics of LLM inference
class KVCache:
    """Dynamic cache. Grows with torch.cat, so every step reallocates. Simple and fine for learning."""

    def __init__(self) -> None:
        self.keys: list[torch.Tensor] = []
        self.values: list[torch.Tensor] = []

    def get_seq_length(self, layer_idx: int = 0) -> int:
        return self.keys[layer_idx].size(-2) if layer_idx < len(self.keys) else 0

    def update(self, k: torch.Tensor, v: torch.Tensor, layer_idx: int = 0) -> tuple[torch.Tensor, torch.Tensor]:
        if layer_idx == len(self.keys):  # first call for this layer: prefill
            self.keys.append(k)
            self.values.append(v)
        else:  # decode: append along the sequence dim
            self.keys[layer_idx] = torch.cat([self.keys[layer_idx], k], dim=-2)
            self.values[layer_idx] = torch.cat([self.values[layer_idx], v], dim=-2)
        return self.keys[layer_idx], self.values[layer_idx]

    def nbytes(self) -> int:
        """Bytes actually held by the cache tensors."""
        return sum(t.numel() * t.element_size() for t in self.keys + self.values)
Listing 13The dynamic cache. The attention layer calls get_seq_length to find its position offset, and update to read the history.

Figure 4Prefill, then decode. Each decode step adds one query row against all keys so far. The rows above it were computed earlier and are not recomputed. The strips on the right are the cache, and the byte counts are the ones the demo prints for Hkv = 2, dh = 8, fp32.
$ .venv/bin/python c03-attention/scripts/kv_cache_demo.py
step        Nq  past  Nk   k in cache        bytes  max |cached - full|
prefill      8     0   8   (1, 2, 8, 8)           1,024    6.0e-08
decode       1     8   9   (1, 2, 9, 8)           1,152    6.0e-08
decode       1     9  10   (1, 2, 10, 8)          1,280    4.5e-08
decode       1    10  11   (1, 2, 11, 8)          1,408    7.5e-08
decode       1    11  12   (1, 2, 12, 8)          1,536    1.0e-07

formula 2 L B S Hkv dh b = 2*1*1*12*2*8*4 = 1,536 bytes; measured 1,536 bytes
Prefill and decode
TensorPrefillDecode at length T
q(B, Hq, N, dh)(B, Hq, 1, dh)
k, v used(B, Hkv, N, dh)(B, Hkv, T, dh)
scores(B, Hq, N, N)(B, Hq, 1, T)
position_ids0 to N-1T - 1 only

The dynamic cache reallocates at every step because of torch.cat. A static cache reserves the whole buffer up front and writes in place. The address never changes, which compiled graphs need.

    def update(self, k: torch.Tensor, v: torch.Tensor, layer_idx: int = 0) -> tuple[torch.Tensor, torch.Tensor]:
        start, n = self.lengths[layer_idx], k.size(-2)
        if start + n > self.k.size(3):
            raise RuntimeError(f"cache full: {start + n} > max_seq_len {self.k.size(3)}")
        self.k[layer_idx, :, :, start : start + n] = k
        self.v[layer_idx, :, :, start : start + n] = v
        self.lengths[layer_idx] = start + n
        # Views of the filled prefix. Production code returns the whole buffer plus a mask
        # so shapes stay fixed; slicing keeps this version easy to check.
        return self.k[layer_idx, :, :, : start + n], self.v[layer_idx, :, :, : start + n]
Listing 14The preallocated version writes into a slice. It has the same interface, so the attention layer does not know which one it holds.

The KV memory formula

The cache holds one key tensor and one value tensor per layer. So its size is:

M_KV = 2 * L * B * S * Hkv * dh * b

Here L is layers, B is batch, S is sequence length, and b is bytes per number. Do not trust a formula you have not measured. The benchmark fills the cache through real forward passes and compares byte counts. These rows ran on CPU. On a Mac the script also reads the MPS allocator.

$ .venv/bin/python c03-attention/benchmarks/bench_kv_memory.py
Part 1: measured on AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132. L = 2, B = 1, D = 1024, Hq = 16, dh = 64; GQA Hkv = 4; MLA r = 128, dr = 16.
layer       S     dtype  device       formula       tensors  equal   MPS alloc delta
MHA      1024      fp32     cpu    16,777,216    16,777,216   True                 -
MHA     16384      fp32     cpu   268,435,456   268,435,456   True                 -
GQA      1024      fp32     cpu     4,194,304     4,194,304   True                 -
GQA     16384      fp32     cpu    67,108,864    67,108,864   True                 -
MQA      1024      fp32     cpu     1,048,576     1,048,576   True                 -
MQA     16384      fp32     cpu    16,777,216    16,777,216   True                 -
MLA      1024      fp32     cpu     1,179,648     1,179,648   True                 -
MHA      1024      bf16     cpu     8,388,608     8,388,608   True                 -
GQA      1024      bf16     cpu     2,097,152     2,097,152   True                 -
MQA      1024      bf16     cpu       524,288       524,288   True                 -
MLA      1024      bf16     cpu       589,824       589,824   True                 -

Formula and tensors agree exactly in every row. The formula counts only the cache. A real process also holds weights, inputs and allocator overhead, so the machine needs a bit more.

The second half of that output applies the verified formula to a full-size layer stack. These numbers are computed, not measured.

Part 2: computed from the verified formula, not measured. L = 32, D = 4096, Hq = 32, dh = 128, B = 1, bf16 (b = 2).
layer             numbers per token     S = 8K   S = 128K     S = 1M
MHA Hkv=32                     8192     4.0 GiB    64.0 GiB   512.0 GiB
GQA Hkv=8                      2048     1.0 GiB    16.0 GiB   128.0 GiB
GQA Hkv=2                       512     0.2 GiB     4.0 GiB    32.0 GiB
MQA Hkv=1                       256     0.1 GiB     2.0 GiB    16.0 GiB
MLA r=512 dr=64                 576     0.3 GiB     4.5 GiB    36.0 GiB

A 128K-token context costs 64 GiB with MHA and 16 GiB with GQA at Hkv = 8, in bf16, before a single weight is loaded. That is why cache layout is an architecture decision. Try your own numbers.

Dimension0
GQA / MHA0
MLA / MHA0

          
Figure 5KV cache calculator. It uses the formulas in kv_cache.py, which the benchmark verified above. Bars are computed, not measured, and they share one linear scale. Defaults are L = 32, 128K tokens, 32 heads, with the MLA ranks of DeepSeek-V2.

Checkpoint

  • kv_cache_demo.py reports differences near 1e-7 at each decode step, and 1,536 bytes from both the formula and the tensors.
  • bench_kv_memory.py prints True in every row of part 1.
  • tests/test_rope_cache.py passes, including the Hugging Face comparison.
Part 05

Sparse, local and linear attention

Goal Show that a sparse mask saves nothing on a dense kernel, then build two kernels that really do save work.

A window mask, measured

A sliding window lets each query see only its last W keys. Part 2 already has that mask, so the first attempt is one flag: window_size=256. Most scores are now blocked, so this should be fast. Measure it first.

$ .venv/bin/python c03-attention/benchmarks/bench_window.py
AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132. Sliding window W = 256, H = 4, d = 32. ms per call.
      N   full causal  mask + naive   mask + sdpa   chunked   scores (mask)  scores (chunked)
   1024           3.8          15.8           3.6       2.3       1,048,576           523,264
   2048           6.5         104.2          13.3       4.3       4,194,304         1,046,528
   4096          18.0         361.9          57.9       7.9      16,777,216         2,093,056
   8192          63.0        1593.2         253.9      16.8      67,108,864         4,186,112
  16384         258.6        5984.2         958.7      31.5     268,435,456         8,372,224

The scores (chunked) column prints n(2W - 1), a round upper bound. The loop computes a little less, 457,984 at N = 1,024, because the first chunk has no chunk before it.

Read the mask + sdpa column against full causal. At N = 16,384 the window is about 98% sparse, yet the masked call takes 959 ms against 259 ms for the full causal call. The sparse version is about 3.7 times slower. The mask does not remove any work. It adds a dense (N, N) tensor to build and read, and it forces the kernel off its causal shortcut.

Make the kernel know about the window

The fix is to stop computing what we will discard. Cut the queries into chunks of W. A chunk can only reach its own positions and the W - 1 before them. So one small attention call per chunk covers every allowed pair.

def chunked_window_attention(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    attn_mask: torch.Tensor | None = None,
    *,
    causal: bool = True,
    window_size: int | None = None,
    scale: float | None = None,
    softcap: float | None = None,
    dropout_p: float = 0.0,
) -> torch.Tensor:
    """q (B, Hq, Nq, d), k/v (B, Hkv, Nk, d) -> (B, Hq, Nq, dv). The window is always causal."""
    if window_size is None:
        raise ValueError("backend='window_chunked' needs window_size")
    if attn_mask is not None or softcap is not None:
        raise ValueError("backend='window_chunked' supports neither attn_mask nor softcap")
    nq, nk, w = q.size(-2), k.size(-2), window_size
    offset = nk - nq  # queries are the last nq positions
    scale = 1.0 / math.sqrt(q.size(-1)) if scale is None else scale
    out = q.new_empty(q.size(0), q.size(1), nq, v.size(-1))

    for qs in range(0, nq, w):
        qe = min(qs + w, nq)
        ks = max(0, qs + offset - w + 1)  # the oldest key any query in this chunk can see
        ke = qe + offset  # one past the newest
        mask = positions_mask(qs, qe, ks, ke, offset, True, w, q.device)  # (qe - qs, ke - ks)
        out[:, :, qs:qe] = F.scaled_dot_product_attention(
            q[:, :, qs:qe],
            k[:, :, ks:ke],
            v[:, :, ks:ke],
            attn_mask=mask,
            dropout_p=dropout_p,
            scale=scale,
            enable_gqa=q.size(1) != k.size(1),
        )
    return out
Listing 15The chunked kernel. ks and ke are the only arithmetic that matters. A small mask still runs inside each chunk, because the rectangle holds a few pairs outside the band.
Scores computed0
Scores kept0
Largest tile0

Figure 6N = 16, W = 4. The dense path fills the whole grid, then a mask discards most of it. The chunked path visits one rectangle per chunk. The counts follow the loop in chunked_window_attention. This small grid shows the geometry, and the measured timings are in the table above.

The last column of the output is the result. At N = 16,384 the chunked kernel takes 31.5 ms, about 30 times faster than the masked call. It also scales linearly: each doubling of N roughly doubles its time. The dense columns roughly quadruple.

Local plus global

A pure window can never carry information far in one layer. Longformer adds a few global tokens to the band. A global token reads every position, and every position reads it.

def local_global_mask(
    n: int, window: int, global_positions: list[int], causal: bool = False, device: torch.device | str | None = None
) -> torch.Tensor:
    """Longformer-style mask: a local band plus a few global tokens. Shape (n, n).

    Global tokens attend to everything and everything attends to them.
    """
    pos = torch.arange(n, device=device)
    band = (pos[None, :] - pos[:, None]).abs() < window
    is_global = torch.zeros(n, dtype=torch.bool, device=device)
    is_global[global_positions] = True
    mask = band | is_global[:, None] | is_global[None, :]
    if causal:
        mask = mask & causal_mask(n, device=device)
    return mask
Listing 16Three boolean terms. Token 0 is global in the printed example below.

Block-sparse layouts

BigBird and similar designs think in blocks of tokens, not single tokens. Our version is for teaching: a local band of blocks plus a few global blocks, expanded to token level.

def block_sparse_layout(num_blocks: int, local_blocks: int = 1, global_blocks: int = 1, causal: bool = True) -> torch.Tensor:
    """A pedagogical BigBird-like block layout: local diagonal band + leading global blocks."""
    b = torch.arange(num_blocks)
    layout = (b[:, None] - b[None, :]).abs() < local_blocks
    layout[:, :global_blocks] = True
    layout[:global_blocks, :] = True
    if causal:
        layout = layout & (b[None, :] <= b[:, None])
    return layout
Listing 17A BigBird-like layout. It is a mask, so it runs on the dense path.
local + global (W = 2, token 0 global)  (34/64 pairs allowed)
########
###.....
####....
#.###...
#..###..
#...###.
#....###
#.....##

block-sparse (4 blocks of 2)  (28/64 pairs allowed)
##......
##......
####....
####....
##..##..
##..##..
##....##
##....##

Now push the density down and time the dense path. The layout goes from 51% to 3% of pairs, and the time does not move.

AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132. Block-sparse masks on the dense path, N = 4096, 64 blocks. ms per call.
layout                        density  naive ms   sdpa ms
full causal                     0.508     391.4      47.4
wide band                       0.232     379.0      50.5
narrow band                     0.076     349.2      46.1
near-diagonal                   0.031     403.6      45.6

This is why real speed-ups need a specialised kernel. BigBird on a GPU has to gather the allowed keys into a smaller tensor before the matmul. FlashAttention has to skip whole tiles. A mask alone can do neither, because a dense kernel has no way to act on it. We return to tile skipping in part 8.

Linear attention: change the kernel

The window approach keeps softmax and limits the keys. Linear attention takes the other route. It drops the exponential and uses a feature map phi, so that the score is a plain dot product phi(q) . phi(k). Then matrix multiplication can be reordered.

The same product in two orders, with a feature size of d
OrderIntermediateShapeCost
[phi(Q) phi(K)T] Vquery-key matrix(B, H, N, N)O(N² d)
phi(Q) [phi(K)T V]key-value summary(B, H, d, dv)O(N d²)
def linear_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
    """Non-causal. q, k: (B, H, N, d) already feature-mapped; v: (B, H, N, dv) -> (B, H, N, dv)."""
    kv = k.transpose(-2, -1) @ v  # (B, H, d, dv): the whole sequence summarised once
    z = k.sum(dim=-2)  # (B, H, d): normaliser
    num = q @ kv  # (B, H, N, dv)
    den = (q * z[:, :, None]).sum(-1, keepdim=True)  # (B, H, N, 1)
    return num / (den + eps)
Listing 18The whole sequence is summarised once in kv, and every query reads that summary. z is the normaliser, the part softmax would have provided.

Causal linear attention is a recurrence

Causality needs each query to see only a prefix. So the summary becomes a running sum: S_t = S_(t-1) + phi(k_t) v_t^T. Then y_t = phi(q_t) S_t, divided by the same product with z_t. That is an RNN whose hidden state is the matrix S.

def causal_linear_attention_recurrent(
    q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, state: tuple[torch.Tensor, torch.Tensor] | None = None, eps: float = 1e-6
) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
    """Causal, one step at a time. Returns outputs (B, H, N, dv) and the final state (S, z).

    S: (B, H, d, dv)   z: (B, H, d). Constant size, however long the sequence gets.
    """
    b, h, n, d = q.shape
    if state is None:
        s = q.new_zeros(b, h, d, v.size(-1))
        z = q.new_zeros(b, h, d)
    else:
        s, z = state
    outs = []
    for t in range(n):
        k_t, v_t, q_t = k[:, :, t], v[:, :, t], q[:, :, t]  # (B, H, d), (B, H, dv), (B, H, d)
        s = s + k_t[..., :, None] * v_t[..., None, :]  # outer product phi(k_t) v_t^T
        z = z + k_t
        num = (q_t[..., None, :] @ s).squeeze(-2)  # (B, H, dv)
        den = (q_t * z).sum(-1, keepdim=True)
        outs.append(num / (den + eps))
    return torch.stack(outs, dim=2), (s, z)
Listing 19The recurrence. Decoding one more token costs the same at position 10 and at position 10 million.
$ .venv/bin/python c03-attention/scripts/linear_demo.py
# AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132
max |phi(Q)[phi(K)^T V] - [phi(Q)phi(K)^T]V| = 2.4e-07
sizes: phi(K)^T V (1, 2, 8, 8) against phi(Q) phi(K)^T (1, 2, 10, 10)

The recurrence: state size stays fixed while the sequence grows
  t=0: S (1, 2, 8, 8), z (1, 2, 8), |S| = 15.980
  t=4: S (1, 2, 8, 8), z (1, 2, 8), |S| = 42.479
  t=9: S (1, 2, 8, 8), z (1, 2, 8), |S| = 63.308
max |recurrent - parallel| = 3.6e-07

The first line shows that the reordering is exact. The state stays (1, 2, 8, 8) while the sequence grows. The recurrent and parallel forms agree to 3.6e-07.

How far is elu+1 from softmax? It is a different kernel, not an approximation:
  mean |elu+1 - softmax| = 0.111, output std = 0.217

Performer-style random features (advanced)

This part is a research direction, not something current language models use, and our version is simplified for learning. Performer picks a random feature map whose dot product estimates the softmax kernel in expectation. More features mean a better estimate.

def performer_features(x: torch.Tensor, projection: torch.Tensor) -> torch.Tensor:
    """FAVOR+ positive random features (Choromanski et al., 2021). Advanced, for illustration.

    x: (..., N, d), projection: (m, d) with rows ~ N(0, I). Returns (..., N, m) with
    E[phi(q) . phi(k)] = exp(q . k / sqrt(d)). The approximation improves as m grows.
    """
    d = x.size(-1)
    x = x / d**0.25  # split the 1/sqrt(d) temperature between q and k
    wx = x @ projection.T  # (..., N, m)
    sq = (x**2).sum(-1, keepdim=True) / 2
    # Subtracting the global max is a constant factor that cancels in the normaliser; it prevents overflow.
    return torch.exp(wx - sq - wx.amax().detach()) / math.sqrt(projection.size(0))
Listing 20FAVOR+ positive random features. The output width is m, so a good approximation can make phi(K)^T V large again.
Performer random features do approximate softmax, and improve with m (advanced):
     m   mean |approx - softmax|
     16   0.0403
     64   0.0292
    256   0.0272
   1024   0.0153
   4096   0.0118

The error falls from 0.0403 to 0.0118 as m grows from 16 to 4,096. It falls slowly. The cost of the linear form is O(N m²), so large m cuts into the saving that motivated it.

Checkpoint

  • bench_window.py shows the mask columns growing fourfold per doubling, and the chunked column growing about twofold.
  • linear_demo.py prints 2.4e-07 for the reorder and 3.6e-07 for the recurrence.
  • tests/test_linear.py and the chunked tests in tests/test_backends.py pass.
Part 06

Attention over images, and between modalities

Goal Reuse the same module for image patches, make it local with windows, and connect images to text in the three common ways.

A ViT layer is MHA without a causal mask

Patches do not arrive in an order, so a ViT layer needs no causal mask. Cut the image into patches and flatten them, and you have the (B, N, D) tensor that attention already takes.

def patchify(images: torch.Tensor, patch: int) -> torch.Tensor:
    """(B, C, H, W) -> (B, N, C*p*p) with N = (H/p) * (W/p), patches in row-major order."""
    b, c, h, w = images.shape
    x = images.unfold(2, patch, patch).unfold(3, patch, patch)  # (B, C, H/p, W/p, p, p)
    return x.permute(0, 2, 3, 1, 4, 5).reshape(b, (h // patch) * (w // patch), c * patch * patch)


def vit_attention_config(hidden_size: int, num_heads: int, backend: str = "sdpa") -> AttentionConfig:
    """The ViT layer: bidirectional MHA, positions added to the patch embeddings beforehand."""
    return AttentionConfig("mha", hidden_size, num_heads, causal=False, positional_encoding="none", backend=backend)
Listing 21No new attention code. The config sets causal=False and leaves positions to the patch embeddings.

To see attention work on content, we skip the learned projections and use raw pixels as q, k and v. The image is a dark background with one bright square. Pick a query patch.

Query patch
Figure 7Patch-to-patch weights, multiplied by 100 and rounded down, for a 64 by 64 synthetic image with 8 by 8 patches. These are the real values printed by scripts/vision_demo.py, for raw-pixel attention at scale=3.0. The outlined patch is the query. The dashed box marks the bright square.

Query 29 is inside the square. Its weight lands on the square, mostly on two bright patches. Query 0 is in the background, and it spreads over the square too, because bright patches have the largest dot products with everything. Raw dot products favour large norms. Learned projections and QK-norm exist partly because of this.

Shapes for global attention over patches
TensorShapeExample
image(B, C, H, W)(1, 3, 64, 64)
patches(B, N, C p²)(1, 64, 192)
weights(B, H, N, N)(1, 1, 64, 64)

Windows: make it local, then let information cross

Global attention over patches costs N², and N grows with the square of the image side. Swin limits each patch to a small window. The key step is the reshape: each window becomes its own short sequence, and the windows move to the batch dimension.

def window_partition(x: torch.Tensor, window: int) -> torch.Tensor:
    """(B, H, W, C) -> (B * nW, w*w, C): each window becomes its own short sequence."""
    b, h, w, c = x.shape
    x = x.view(b, h // window, window, w // window, window, c)
    return x.permute(0, 1, 3, 2, 4, 5).reshape(-1, window * window, c)


def window_merge(windows: torch.Tensor, window: int, height: int, width: int) -> torch.Tensor:
    """(B * nW, w*w, C) -> (B, H, W, C), the exact inverse of window_partition."""
    c = windows.size(-1)
    x = windows.view(-1, height // window, width // window, window, window, c)
    return x.permute(0, 1, 3, 2, 4, 5).reshape(-1, height, width, c)
Listing 22Windows go into the batch dimension. Attention then runs on many short sequences with no code changes. window_merge is the exact inverse.
class WindowAttention(nn.Module):
    """Self-attention inside non-overlapping w x w windows. x (B, H, W, C) -> (B, H, W, C).

    Cost per layer is O(H W w^2) instead of O((H W)^2). shift = w // 2 on every other
    layer lets information cross window borders (Swin, Liu et al., 2021).
    """

    def __init__(self, hidden_size: int, num_heads: int, window: int, shift: int = 0, backend: str = "sdpa") -> None:
        super().__init__()
        self.window, self.shift = window, shift
        self.attn = GroupedQueryAttention(vit_attention_config(hidden_size, num_heads, backend))
        self.rel_bias = RelativePositionBias2D(window, num_heads)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        b, h, w, _ = x.shape
        if self.shift:
            x = torch.roll(x, shifts=(-self.shift, -self.shift), dims=(1, 2))
        windows = window_partition(x, self.window)  # (B*nW, w*w, C)
        bias = self.rel_bias().to(x.dtype)  # (1, heads, w*w, w*w)
        if self.shift:
            mask = shifted_window_mask(h, w, self.window, self.shift).to(x.device)  # (nW, w*w, w*w)
            mask = mask.repeat(b, 1, 1)[:, None]  # (B*nW, 1, w*w, w*w); windows are batch-major
            bias = bias.masked_fill(~mask, float("-inf"))
        out = self.attn(windows, attention_mask=bias)
        out = window_merge(out, self.window, h, w)
        if self.shift:
            out = torch.roll(out, shifts=(self.shift, self.shift), dims=(1, 2))
        return out
Listing 23Roll, partition, attend, merge, roll back. A mask stops wrapped patches from reading each other.

Figure 8A token’s reach through window layers on an 8 by 8 grid with window 4 and shift 2. The orange region is the set of positions that changed when token (0, 0) changed, as printed by scripts/vision_demo.py. Plain windows trap it in 4 by 4. One shifted layer extends it to 6 by 6.
$ .venv/bin/python c03-attention/scripts/vision_demo.py
Window partition (B=1, H=W=8, C=32, window 4):
  grid (1, 8, 8, 32) -> windows (4, 16, 32) -> merged (1, 8, 8, 32)
  scores per layer: global 4,096, windowed 1,024

A token's reach after each layer (non-zero change in the output when token (0,0) changes):
after one plain window layer:
####....
####....
####....
####....
........
........
........
........
after plain, then shifted:
######..
######..
######..
######..
######..
######..
........
........

Without the shift, a token could never leave its window, however many layers we stack. The cyclic shift has a side effect: a shifted window can now hold pixels from opposite image borders. They are not neighbours, so we block them.

def shifted_window_mask(height: int, width: int, window: int, shift: int) -> torch.Tensor:
    """(nW, w*w, w*w) bool. After a cyclic shift, a window can hold pixels from opposite
    image borders; label the regions and only let a token attend inside its own region."""
    region = torch.zeros(height, width, dtype=torch.long)
    cuts = (slice(0, -window), slice(-window, -shift), slice(-shift, None))
    label = 0
    for hs in cuts:
        for ws in cuts:
            region[hs, ws] = label
            label += 1
    ids = window_partition(region[None, :, :, None], window).squeeze(-1)  # (nW, w*w)
    return ids[:, :, None] == ids[:, None, :]
Listing 24Label each region. Two tokens may attend only if they carry the same label.
Shifted-window mask of the bottom-right window (8 x 8 grid, window 4, shift 2):
##..##..........
##..##..........
..##..##........
..##..##........
##..##..........
##..##..........
..##..##........
..##..##........
........##..##..
........##..##..
..........##..##
..........##..##
........##..##..
........##..##..
..........##..##
..........##..##

2D positions

A grid needs row and column information. We show three standard answers. The first adds absolute 2D sine and cosine features to the patches. The second learns a bias for each (dy, dx) offset inside a window, as in Swin. The third is axial 2D RoPE, which rotates half of each head by the row and the other half by the column.

def sincos_2d_embedding(height: int, width: int, dim: int) -> torch.Tensor:
    """(H*W, dim): half the channels encode the row, half the column."""
    rows, cols = torch.meshgrid(torch.arange(height), torch.arange(width), indexing="ij")
    return torch.cat([sincos_1d(rows.flatten(), dim // 2), sincos_1d(cols.flatten(), dim // 2)], dim=-1)
class RelativePositionBias2D(nn.Module):
    """Swin's bias: one learned scalar per head for each offset (dy, dx) in a w x w window.

    table: ((2w-1)^2, H). index: (w*w, w*w) maps each query-key pair to its table row.
    """

    def __init__(self, window: int, num_heads: int) -> None:
        super().__init__()
        self.table = nn.Parameter(torch.zeros((2 * window - 1) ** 2, num_heads))
        coords = torch.stack(torch.meshgrid(torch.arange(window), torch.arange(window), indexing="ij")).flatten(1)  # (2, w*w)
        rel = coords[:, :, None] - coords[:, None, :] + (window - 1)  # (2, w*w, w*w), shifted to >= 0
        self.register_buffer("index", rel[0] * (2 * window - 1) + rel[1], persistent=False)

    def forward(self) -> torch.Tensor:
        """Returns (1, H, w*w, w*w), ready to add to the logits."""
        return self.table[self.index].permute(2, 0, 1)[None]
class Rope2D(nn.Module):
    """Axial 2D RoPE: the score between two patches depends only on (dy, dx).

    The first half of each head is rotated by the row index, the second by the column.
    """

    def __init__(self, head_dim: int, max_side: int = 64, theta: float = 10_000.0) -> None:
        super().__init__()
        if head_dim % 4:
            raise ValueError("2D RoPE splits head_dim in two halves of rotated pairs: need head_dim % 4 == 0")
        self.rope = RotaryEmbedding(head_dim // 2, max_side, theta)

    def forward(self, x: torch.Tensor, rows: torch.Tensor, cols: torch.Tensor) -> torch.Tensor:
        """x (B, H, N, d), rows/cols (N,) integer grid coordinates -> rotated x."""
        x_row, x_col = x.chunk(2, dim=-1)
        cos_r, sin_r = self.rope(rows[None])
        cos_c, sin_c = self.rope(cols[None])
        return torch.cat([rotate(x_row, cos_r, sin_r), rotate(x_col, cos_c, sin_c)], dim=-1)
2D positions:
  sincos_2d_embedding(8, 8, 32): (64, 32)
  RelativePositionBias2D(window=4, heads=4): (1, 4, 16, 16) from a table of (49, 4)
  2D RoPE score (5,3)->(2,1): -1.9130
  2D RoPE score (15,13)->(12,11), same offset: -1.9130
  2D RoPE score (5,3)->(1,2), different offset: 0.4643

The two 2D RoPE scores with the same offset agree: -1.9130 for (5, 3) to (2, 1), and -1.9130 for (15, 13) to (12, 11). A different offset gives a different score. The 1D property from part 4 survives on the grid.

Learned queries: Q-Former and Perceiver

A language model should not pay for every image token. Cross-attention already gives us the tool: the output length follows the queries, so a fixed set of M learned queries gives M tokens for any image size. Q-Former and the Perceiver resampler differ in how the queries talk to each other.

class QFormerLayer(nn.Module):
    """queries <- queries + SelfAttn;  queries <- queries + CrossAttn(image);  queries <- queries + FFN."""

    def __init__(self, hidden_size: int, num_heads: int) -> None:
        super().__init__()
        cfg = AttentionConfig("mha", hidden_size, num_heads, causal=False, positional_encoding="none")
        self.norm1, self.norm2 = nn.LayerNorm(hidden_size), nn.LayerNorm(hidden_size)
        self.self_attn = GroupedQueryAttention(cfg)  # queries talk to each other
        self.cross_attn = CrossAttention(cfg)  # queries read the image
        self.ffn = FeedForward(hidden_size)

    def forward(self, queries: torch.Tensor, image: torch.Tensor, image_mask: torch.Tensor | None) -> torch.Tensor:
        queries = queries + self.self_attn(self.norm1(queries))
        queries = queries + self.cross_attn(self.norm2(queries), image, image_mask)
        return queries + self.ffn(queries)
class PerceiverResamplerLayer(nn.Module):
    """Latents query the concatenation [image; latents], so they also see each other."""

    def __init__(self, hidden_size: int, num_heads: int) -> None:
        super().__init__()
        cfg = AttentionConfig("mha", hidden_size, num_heads, causal=False, positional_encoding="none")
        self.norm_media, self.norm_latents = nn.LayerNorm(hidden_size), nn.LayerNorm(hidden_size)
        self.cross_attn = CrossAttention(cfg)
        self.ffn = FeedForward(hidden_size)

    def forward(self, latents: torch.Tensor, image: torch.Tensor, image_mask: torch.Tensor | None) -> torch.Tensor:
        lat = self.norm_latents(latents)
        kv = torch.cat([self.norm_media(image), lat], dim=1)  # (B, Nv + M, D)
        mask = None
        if image_mask is not None:  # latents are never padding
            mask = torch.cat([image_mask, image_mask.new_ones(latents.shape[:2])], dim=1)
        latents = latents + self.cross_attn(lat, kv, mask)
        return latents + self.ffn(latents)
Q-Former and Perceiver resampler in this code
AspectQ-FormerPerceiver resampler
Query self-attentionA separate attention layerNone. Latents join the keys.
Keys and valuesImage onlyImage and latents, concatenated
Output(B, M, D) for any Nv(B, M, D) for any Nv
Params (M = 32, D = 256)2,209,5361,685,760
$ .venv/bin/python c03-attention/scripts/resampler_demo.py
 image tokens Nv          Q-Former         Perceiver
             196      (1, 32, 256)      (1, 32, 256)
             576      (1, 32, 256)      (1, 32, 256)
            1369      (1, 32, 256)      (1, 32, 256)
params: Q-Former 2,209,536, Perceiver 1,685,760

What the language model pays per self-attention layer, with 30 text tokens:
  Nv= 196: early fusion    51,076 scores, after a 32-token resampler 3,844
  Nv= 576: early fusion   367,236 scores, after a 32-token resampler 3,844
  Nv=1369: early fusion 1,957,201 scores, after a 32-token resampler 3,844

Three fusion patterns

Early fusion puts image and text in one sequence, and the multimodal mask from part 2 does all the work. Cross-attention keeps them apart, and text reads the image in extra layers. Gated cross-attention adds a learned gate that starts closed, so a frozen language model is unchanged at the start of training.

def early_fusion_sequence(image_tokens: torch.Tensor, text_tokens: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """image (B, Nv, D), text (B, Nt, D) -> sequence (B, Nv + Nt, D), mask (B, 1, N, N).

    The image block is bidirectional, the text is causal and sees the whole image.
    """
    b, nv, _ = image_tokens.shape
    nt = text_tokens.size(1)
    span_ids = torch.cat([torch.ones(b, nv, dtype=torch.long), torch.zeros(b, nt, dtype=torch.long)], dim=1)
    return torch.cat([image_tokens, text_tokens], dim=1), multimodal_mask(span_ids.to(image_tokens.device))
class CrossAttentionFusionBlock(nn.Module):
    """Text self-attends causally, then reads the image through cross-attention. Image tokens never enter the text sequence."""

    def __init__(self, config: AttentionConfig) -> None:
        super().__init__()
        self.self_attn = GroupedQueryAttention(config)
        self.cross_attn = CrossAttention(AttentionConfig(**{**config.to_dict(), "positional_encoding": "none"}))
        self.norm1, self.norm2 = nn.LayerNorm(config.hidden_size), nn.LayerNorm(config.hidden_size)

    def forward(self, text_tokens: torch.Tensor, image_tokens: torch.Tensor) -> torch.Tensor:
        x = text_tokens + self.self_attn(self.norm1(text_tokens))
        return x + self.cross_attn(self.norm2(x), image_tokens)
class GatedCrossAttentionBlock(nn.Module):
    """Flamingo-style block inserted between frozen LM layers (Alayrac et al., 2022).

    x <- x + tanh(a_attn) * CrossAttn(LN(x), image)
    x <- x + tanh(a_ff)   * FFN(x)
    Both gates start at 0, so at initialisation the block is the identity and the
    frozen language model behaves exactly as before. Training opens the gates.
    """

    def __init__(self, config: AttentionConfig) -> None:
        super().__init__()
        self.norm = nn.LayerNorm(config.hidden_size)
        self.cross = CrossAttention(config)
        self.ffn = FeedForward(config.hidden_size)
        self.attn_gate = nn.Parameter(torch.zeros(1))
        self.ff_gate = nn.Parameter(torch.zeros(1))

    def forward(self, x: torch.Tensor, image_tokens: torch.Tensor, image_mask: torch.Tensor | None = None) -> torch.Tensor:
        x = x + torch.tanh(self.attn_gate) * self.cross(self.norm(x), image_tokens, image_mask)
        return x + torch.tanh(self.ff_gate) * self.ffn(x)
Early fusion mask, 4 image tokens then 4 text tokens:
####....
####....
####....
####....
#####...
######..
#######.
########

Early fusion:     (2, 10, 32) (the image joins the sequence)
Cross-attention:  (2, 6, 32) (text length is kept)
Gated at init:    max |output - input| = 0.0e+00 (gates closed)
Gated, gate open: max |output - input| = 0.376

The last two lines are the gate test in numbers. At initialisation the block returns its input exactly, with a difference of 0.0. Open the gate and the output moves by 0.376.

Checkpoint

  • vision_demo.py prints a 4 by 4 reach, then a 6 by 6 reach.
  • resampler_demo.py prints (1, 32, 256) for all three image lengths.
  • tests/test_vision.py and tests/test_multimodal.py pass.
Part 07

Multi-head latent attention

Goal Build DeepSeek-style MLA in four steps, and see what it pays for its small cache.

GQA shrinks the cache by sharing heads. MLA asks a different question: must we store per-head keys and values at all? It stores one small latent per token, and rebuilds per-head keys and values from it when they are needed.

Here are the projections. Each one belongs to a step below.

class MultiHeadLatentAttention(nn.Module):
    """hidden_states (B, N, D) -> (B, N, D).

    Cached per token: c_kv (r) and k_pe (d_r).   Per head: q, k have dn + dr dims, v has dv.
    """

    def __init__(self, config: AttentionConfig, layer_idx: int = 0) -> None:
        super().__init__()
        self.config, self.layer_idx = config, layer_idx
        h, d = config.num_heads, config.hidden_size
        self.dn, self.dr, self.dv, self.r = config.qk_nope_head_dim, config.qk_rope_head_dim, config.v_head_dim, config.kv_lora_rank
        if config.q_lora_rank:  # queries can be low-rank too; this saves activations, not cache
            self.q_down = nn.Linear(d, config.q_lora_rank, bias=False)
            self.q_norm = RMSNorm(config.q_lora_rank)
            self.q_up = nn.Linear(config.q_lora_rank, h * (self.dn + self.dr), bias=False)
        else:
            self.q_proj = nn.Linear(d, h * (self.dn + self.dr), bias=False)
        self.kv_down = nn.Linear(d, self.r, bias=False)  # step 1: W_DKV
        self.kv_norm = RMSNorm(self.r)
        self.kv_up = nn.Linear(self.r, h * (self.dn + self.dv), bias=False)  # step 2: [W_UK; W_UV]
        self.k_rope = nn.Linear(d, self.dr, bias=False)  # step 3: W_KR, one RoPE key for all heads
        self.o_proj = nn.Linear(h * self.dv, d, bias=False)
        self.rotary = RotaryEmbedding(self.dr, config.max_seq_len, config.rope_theta)
        self.scale = 1.0 / math.sqrt(self.dn + self.dr)
Listing 25The constructor. r is much smaller than H * dh. That single number is the idea.

Step 1: compress

c_kv = W_DKV h maps each hidden state to r numbers. This is what goes in the cache.

Step 2: reconstruct

[k_nope; v] = W_UKV c_kv expands the latent back into per-head keys and values on the fly. The two helper methods are short.

    def compress(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        """x (B, N, D) -> c_kv (B, 1, N, r), k_pe (B, 1, N, dr), before RoPE. These get cached."""
        c_kv = self.kv_norm(self.kv_down(x))[:, None]
        k_pe = self.k_rope(x)[:, None]
        return c_kv, k_pe

    def reconstruct(self, c_kv: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        """c_kv (B, 1, T, r) -> k_nope (B, H, T, dn), v (B, H, T, dv)."""
        kv = split_heads(self.kv_up(c_kv[:, 0]), self.config.num_heads)
        return kv.split([self.dn, self.dv], dim=-1)
Listing 26Compress and reconstruct. The latent has a head dimension of 1, so it fits in the same cache class as GQA.

Step 3: keep RoPE out of the latent

There is a catch. RoPE rotates keys by position. If we rotate the latent, the rotation cannot pass through the linear map W_UK. If we rotate the rebuilt key instead, we have to rotate the entire history again at every step, so the cache saves little compute. DeepSeek’s answer is to split the key in two. A large part has no position. A small part, k_pe, has RoPE and is shared by all heads. It is cached already rotated.

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: torch.Tensor | None = None,
        position_ids: torch.Tensor | None = None,
        kv_cache=None,
        absorb: bool = False,
    ) -> torch.Tensor:
        b, n, _ = hidden_states.shape
        q_nope, q_pe = self.queries(hidden_states)
        c_kv, k_pe = self.compress(hidden_states)

        past = kv_cache.get_seq_length(self.layer_idx) if kv_cache is not None else 0
        if position_ids is None:
            position_ids = torch.arange(past, past + n, device=hidden_states.device)[None].expand(b, n)
        cos, sin = self.rotary(position_ids)
        q_pe, k_pe = rotate(q_pe, cos, sin), rotate(k_pe, cos, sin)  # only the small RoPE parts

        if kv_cache is not None:  # the cache holds latents, not keys and values
            c_kv, k_pe = kv_cache.update(c_kv, k_pe, self.layer_idx)  # (B, 1, T, r), (B, 1, T, dr)

        mask = padding_mask(attention_mask) if attention_mask is not None and attention_mask.dim() == 2 else attention_mask
        if absorb:
            out = self._attend_absorbed(q_nope, q_pe, c_kv, k_pe, mask)
        else:
            k_nope, v = self.reconstruct(c_kv)
            k = torch.cat([k_nope, k_pe.expand(-1, self.config.num_heads, -1, -1)], dim=-1)  # (B, H, T, dn + dr)
            q = torch.cat([q_nope, q_pe], dim=-1)
            out = attend(
                q, k, v, mask, backend=self.config.backend, causal=self.config.causal,
                window_size=self.config.window_size, scale=self.scale,
            )  # (B, H, N, dv)
        return self.o_proj(merge_heads(out))
Listing 27The forward pass. Only the small RoPE parts rotate. The cache holds c_kv and k_pe, not keys and values.

Figure 9MLA for D = 256, H = 8, dh = 32, r = 32, dr = 8, as in scripts/mla_demo.py. Box widths are proportional to the numbers per token. The cached row is drawn in orange. The rebuilt row exists only during the forward pass.
MLA shapes for the demo, with T cached positions
TensorShapeCached?
c_kv(B, 1, T, r)Yes
k_pe(B, 1, T, dr)Yes, after rotation
k_nope(B, H, T, dn)No, rebuilt from c_kv
v(B, H, T, dv)No, rebuilt from c_kv
q(B, H, N, dn + dr)No
out(B, H, N, dv)No

Step 4: compare the cache

$ .venv/bin/python c03-attention/scripts/mla_demo.py
# AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132
Step 1, compress: this is all we store
  c_kv     (1, 1, 16, 32)
  k_pe     (1, 1, 16, 8)
Step 2, reconstruct per-head keys and values on the fly
  k_nope   (1, 8, 16, 32)
  v        (1, 8, 16, 32)
Step 3, RoPE lives only in the small shared key
  q_nope   (1, 8, 16, 32)
  q_pe     (1, 8, 16, 8)
  full query and key width: 32 + 8 = 40

Decoding, three ways:
  explicit K, V  max |cached - full| = 1.3e-07, cached tensors (1, 1, 16, 32) (1, 1, 16, 8)
  absorbed       max |cached - full| = 1.9e-07, cached tensors (1, 1, 16, 32) (1, 1, 16, 8)

Step 4, cache bytes per token for one layer (fp32):
  MHA           2048 bytes     1.0x smaller than MHA
  GQA Hkv=2      512 bytes     4.0x smaller than MHA
  MQA            256 bytes     8.0x smaller than MHA
  MLA r=32       160 bytes    12.8x smaller than MHA

An honest catch: MLA spends cache savings on parameters and compute.
  MHA          262,144 params
  GQA Hkv=2    163,840 params
  MQA          147,456 params
  MLA r=32     174,112 params

MLA caches 160 bytes per token per layer here, 12.8 times less than MHA and less than MQA. The last block of the output shows the cost. MLA has more parameters than GQA or MQA at this size. And the rebuild has a time cost, which part 12 measures.

Absorption: skip the rebuild

Rebuilding K for the whole history at each decode step looks wasteful, and we can avoid it. q_nope . (W_UK c) equals (W_UK^T q_nope) . c. So we can fold W_UK into the query and W_UV into the output, and run attention directly on the latents.

    def _attend_absorbed(
        self, q_nope: torch.Tensor, q_pe: torch.Tensor, c_kv: torch.Tensor, k_pe: torch.Tensor, mask: torch.Tensor | None
    ) -> torch.Tensor:
        """Attention on latents. q_nope . (W_UK c) = (W_UK^T q_nope) . c, so fold W_UK into q."""
        h = self.config.num_heads
        w = self.kv_up.weight.view(h, self.dn + self.dv, self.r)  # per head: rows of W_UK then W_UV
        w_uk, w_uv = w[:, : self.dn], w[:, self.dn :]  # (H, dn, r), (H, dv, r)

        q_lat = torch.einsum("bhnd,hdr->bhnr", q_nope, w_uk)  # (B, H, N, r): queries in latent space
        scores = (q_lat @ c_kv.transpose(-2, -1) + q_pe @ k_pe.transpose(-2, -1)) * self.scale  # (B, H, N, T)
        allowed = combine(structural_mask(q_nope.size(-2), c_kv.size(-2), self.config.causal, self.config.window_size, q_nope.device), mask)
        if allowed is not None:
            scores = scores.masked_fill(~allowed, float("-inf"))
        weights = torch.softmax(scores, dim=-1, dtype=torch.float32).to(q_nope.dtype)
        o_lat = weights @ c_kv  # (B, H, N, r): a weighted average of latents
        return torch.einsum("bhnr,hdr->bhnd", o_lat, w_uv)  # (B, H, N, dv): fold W_UV in last
Listing 28No K or V tensor is ever built. The history is touched only as r-wide latents.

Checkpoint

  • mla_demo.py prints 160 bytes per token for MLA and errors below 1e-6 for both decode paths.
  • tests/test_mla.py passes.
Part 08

SDPA, online softmax and FlashAttention

Goal Swap the kernel without changing the answer, then write the FlashAttention algorithm ourselves to see why it needs no score matrix.

SDPA: the trusted fast path

So far, the softmax layers have called one function, attend. Now we fill in what sits behind it. The first backend hands the work to PyTorch. Most of this function exists for one reason: the decode alignment bug from part 4.

def sdpa_attention(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    attn_mask: torch.Tensor | None = None,
    *,
    causal: bool = False,
    window_size: int | None = None,
    scale: float | None = None,
    softcap: float | None = None,
    dropout_p: float = 0.0,
    kernel: SDPBackend | None = None,
) -> torch.Tensor:
    """Shapes as in attention_naive. `kernel` pins one SDPA implementation (e.g. SDPBackend.MATH)."""
    if softcap is not None:
        raise ValueError("SDPA has no logit soft-capping; use backend='naive' (or 'flash' on CUDA).")

    is_causal = False
    nq, nk = q.size(-2), k.size(-2)
    if attn_mask is None and window_size is None and causal and nq == nk:
        is_causal = True  # lets the kernel skip future tiles instead of reading a mask
    elif attn_mask is None and window_size is None and causal and nq == 1:
        pass  # the newest token sees every key: no mask, so kernels that take none (CUDA FA2) can decode
    else:
        # SDPA's is_causal is aligned top-left, which is wrong when nq < nk (decoding
        # with a cache). Build the bottom-right mask ourselves and merge it in.
        struct = structural_mask(nq, nk, causal, window_size, device=q.device)
        if struct is not None:
            if attn_mask is None:
                attn_mask = struct
            elif attn_mask.dtype == torch.bool:
                attn_mask = attn_mask & struct
            else:
                attn_mask = attn_mask.masked_fill(~struct, float("-inf"))

    ctx = sdpa_kernel([kernel]) if kernel is not None else nullcontext()
    with ctx:
        return F.scaled_dot_product_attention(
            q,
            k,
            v,
            attn_mask=attn_mask,
            dropout_p=dropout_p,
            is_causal=is_causal,
            scale=scale,
            enable_gqa=q.size(1) != k.size(1),  # broadcast KV heads inside the kernel, no copy
        )
Listing 29SDPA with our masks. enable_gqa lets the kernel broadcast shared KV heads without a copy.

The IO problem

Look at what the naive backend does at N = 8,192. It writes every score to memory, then reads them all back for the softmax. On one head that is 67 million numbers. With four heads in fp32, the score matrix alone is about 1 GiB, before the softmax makes its copy.

The theory post on memory explains why this hurts more than the arithmetic does. Compute has grown much faster than memory bandwidth, so a kernel that moves a large matrix in and out of slow memory spends its time waiting. FlashAttention never writes that matrix to slow memory. It computes small tiles that fit in fast on-chip memory and keeps only running statistics.

Theory inWhy fast GPUs still wait for memory

Online softmax: normalising without the whole row

Tiling has one obstacle. Softmax needs a denominator over the whole row and the largest value of that row for stability, but a tile holds only part of a row. The answer is to keep running values and correct them. We keep three per query row:

The running statistics, for one tile of queries
NameShapeMeaning
m(B, H, bq, 1)The largest score seen so far in this row.
l(B, H, bq, 1)The sum of exp(s - m) so far: the denominator.
acc(B, H, bq, dv)The sum of exp(s - m) v so far: the numerator.

When a new tile raises the maximum from m to m_new, everything accumulated earlier was computed against the wrong base. Multiplying by exp(m - m_new) fixes it. Run it on one query and six keys, split into two tiles of three, and watch this happen.

$ .venv/bin/python c03-attention/scripts/online_softmax_demo.py
all six scores: tensor([ 0.112, -0.885, -0.679,  0.589, -0.600, -1.203])
true softmax:   tensor([0.239, 0.088, 0.108, 0.384, 0.117, 0.064])

tile 0: scores tensor([ 0.112, -0.885, -0.679])
  m: -inf -> 0.112   alpha = exp(m - m_new) = 0.000
  p = exp(s - m_new): tensor([1.000, 0.369, 0.453])
  l = 1.823   acc = tensor([-1.487,  0.064])

tile 1: scores tensor([ 0.589, -0.600, -1.203])
  m: 0.112 -> 0.589   alpha = exp(m - m_new) = 0.621
  p = exp(s - m_new): tensor([1.000, 0.305, 0.167])
  l = 2.603   acc = tensor([-0.407,  0.039])

acc / l:           tensor([-0.156,  0.015])
softmax @ v:       tensor([-0.156,  0.015])

In tile 1 the maximum rises from 0.112 to 0.589, so the old sums shrink by alpha = 0.621. At the end acc / l matches softmax @ v to every printed digit, and we never held all six scores at the same time in the running values.

The full function is two nested loops around those same lines.

    for qs in range(0, nq, block_q):
        qe = min(qs + block_q, nq)
        q_tile = q[:, :, qs:qe].float() * scale
        m = torch.full((b, h, qe - qs, 1), float("-inf"), device=q.device)
        l = torch.zeros(b, h, qe - qs, 1, device=q.device)
        acc = torch.zeros(b, h, qe - qs, v.size(-1), device=q.device)

        for ks in range(0, nk, block_k):
            ke = min(ks + block_k, nk)
            # Skip tiles the mask blocks entirely: this is where causal and local attention save work.
            future = (causal or window_size is not None) and ks > qe - 1 + offset
            too_old = window_size is not None and ke - 1 <= qs + offset - window_size
            if future or too_old:
                if trace is not None:
                    trace.append({"q": (qs, qe), "k": (ks, ke), "skipped": True})
                continue

            s = q_tile @ k[:, :, ks:ke].float().transpose(-2, -1)  # (B, H, bq, bk): one tile of scores
            if softcap is not None:
                s = softcap * torch.tanh(s / softcap)
            tile_mask = positions_mask(qs, qe, ks, ke, offset, causal, window_size, q.device)
            if attn_mask is not None and attn_mask.dtype == torch.bool:
                user = attn_mask[:, :, qs:qe, ks:ke]
                tile_mask = user if tile_mask is None else tile_mask & user
            elif attn_mask is not None:
                s = s + attn_mask[:, :, qs:qe, ks:ke].float()
            if tile_mask is not None:
                s = s.masked_fill(~tile_mask, float("-inf"))

            m_new = torch.maximum(m, s.amax(dim=-1, keepdim=True))
            m_safe = torch.where(torch.isinf(m_new), torch.zeros_like(m_new), m_new)  # rows with nothing visible yet
            p = torch.exp(s - m_safe)  # (B, H, bq, bk), unnormalised probabilities
            alpha = torch.exp(m - m_safe)  # how much the old max overestimated: rescale old sums
            l = alpha * l + p.sum(dim=-1, keepdim=True)
            acc = alpha * acc + p @ v[:, :, ks:ke].float()
            m = m_new
            if trace is not None:
                trace.append({"q": (qs, qe), "k": (ks, ke), "skipped": False, "m": m[0, 0, :, 0].tolist(), "l": l[0, 0, :, 0].tolist()})

        # Divide once at the end. Rows that never saw a key (l = 0) return zeros, like SDPA.
        out[:, :, qs:qe] = torch.where(l > 0, acc / l.clamp_min(1e-30), torch.zeros_like(acc)).to(q.dtype)
Listing 30The online softmax. The first highlight skips blocked tiles. The second is the running update. The whole block runs once per tile.

Figure 10One head, N = 12, tiles of 4, causal. Cell colours and the running m and l come from a real trace of tiled_attention, saved by scripts/export_figure_data.py. Only the outlined tile is in memory at any moment. Three tiles lie wholly in the future and are never computed.
Full function, causal, N = 512, tiles 64 x 64:
max |tiled - naive| = 7.15e-07
tiles: 64 total, 28 skipped because they lie wholly in the future
largest score tensor held: 64 x 64 per head = 4,096 entries, against 262,144 for naive

At N = 512 the output matches naive to 7.15e-07, and 28 of 64 tiles are skipped. Skipping is the second saving. The same two conditions in the loop cover causal masks and sliding windows, which is how FlashAttention gets the window speed-up that a dense mask cannot.

Measure every backend

Same inputs, same answer, different kernels. Each cell runs in a fresh process, so that one measurement cannot hide in another’s memory.

$ .venv/bin/python c03-attention/benchmarks/bench_backends.py
AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132: causal attention, H = 4, d = 32, fp32. ms per call / peak extra MB
backend                       512             1024             2048             4096             8192            16384
naive                    5.6 / 31         9.9 / 69      133.4 / 206      449.7 / 814    1852.9 / 3133   7201.7 / 12528
sdpa_math                7.4 / 14        27.8 / 39       61.4 / 191      282.3 / 676    1113.7 / 2570   4154.4 / 10257
sdpa                      1.2 / 0          2.4 / 8        10.8 / 10        29.2 / 10        110.1 / 6       300.0 / 12
sdpa_flash                0.8 / 0          2.8 / 8          9.9 / 9         24.7 / 9        74.3 / 11       282.4 / 12
tiled                    10.3 / 2         37.4 / 3        143.6 / 6        512.2 / 6       1919.2 / 4       7771.5 / 9

sdpa_efficient and flash: not yet measured. They need a CUDA GPU. On one, run this script with --flash.

Three things stand out. First, sdpa is about 17 times faster than our naive backend at N = 8,192, and its peak extra memory stays near 10 MB. Second, sdpa and sdpa_flash track each other: 300 ms and 282 ms at N = 16,384. On this machine sdpa_flash is PyTorch’s CPU flash kernel, and sdpa can pick that kernel by itself. Third, our tiled Python loop takes about as long as naive, 1,919 ms against 1,853 ms at N = 8,192, while the peak extra memory falls from about 3 GB to 4 MB. Python runs the loop over tiles here, so read this as the memory result of the algorithm, not as its speed.

The real kernels are GPU-only

Our tiled backend models the algorithm. We do not attempt a production kernel. The flash backend calls the real one, through the flash-attn package when it is installed, or through PyTorch’s built-in FlashAttention-2 kernel. The flash-attn package was not installed for the run below, so flash took the second route.

def flash_attention(
    q: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    attn_mask: torch.Tensor | None = None,
    *,
    causal: bool = False,
    window_size: int | None = None,
    scale: float | None = None,
    softcap: float | None = None,
    dropout_p: float = 0.0,
) -> torch.Tensor:
    """Shapes as in attention_naive: q (B, Hq, Nq, d), k/v (B, Hkv, Nk, d)."""
    if q.device.type != "cuda":
        raise RuntimeError("backend='flash' is GPU-only; use 'sdpa' or 'tiled' on CPU/MPS")
    if attn_mask is not None:
        # Flash kernels take no dense mask; padding goes through the varlen API (cu_seqlens).
        raise ValueError("flash backend takes no attn_mask; unpad and use flash_attn_varlen_func")
    try:
        from flash_attn import flash_attn_func
    except ImportError:
        if window_size is not None or softcap is not None:
            raise ValueError("window/softcap need the flash-attn package") from None
        return sdpa_attention(q, k, v, causal=causal, scale=scale, dropout_p=dropout_p, kernel=SDPBackend.FLASH_ATTENTION)

    # flash-attn wants (B, N, H, d). Its causal mask is aligned bottom-right, like ours.
    out = flash_attn_func(
        q.transpose(1, 2),
        k.transpose(1, 2),
        v.transpose(1, 2),
        dropout_p=dropout_p,
        softmax_scale=scale,
        causal=causal or window_size is not None,
        window_size=(window_size - 1, 0) if window_size is not None else (-1, -1),
        softcap=softcap or 0.0,
    )
    return out.transpose(1, 2)
Listing 31A thin adapter. The kernel wants (B, N, H, d). It takes no dense mask, because padding goes through its varlen API.

We ran this path once, on one NVIDIA H100 80GB HBM3 in bf16, with PyTorch 2.15.0 built for CUDA 13.2. The flash backend is PyTorch’s FlashAttention-2 through SDPA, the same kernel as sdpa_flash. The tests marked gpu come first.

$ .venv/bin/python -m pytest c03-attention -m gpu -rs
.......s                                                                 [100%]
=========================== short test summary info ============================
SKIPPED [1] c03-attention/tests/test_gpu.py:50: could not import 'flash_attn': No module named 'flash_attn'
7 passed, 1 skipped, 176 deselected in 2.52s

The skipped test is the window-and-decode test, which needs the flash-attn package. So Tri Dao’s kernels are not measured. The seven passing tests compare the PyTorch FlashAttention-2 and memory-efficient kernels with naive. Now the same backend table as before, on the GPU.

$ .venv/bin/python c03-attention/benchmarks/bench_backends.py --flash
NVIDIA H100 80GB HBM3, torch 2.15.0+cu132: causal attention, H = 4, d = 32, bf16. ms per call / peak extra MB
flash = PyTorch FA2 through SDPA, because the flash-attn package is not installed
backend                       512             1024             2048             4096             8192            16384
naive                    0.4 / 36         0.4 / 49        0.5 / 164        1.5 / 656       5.9 / 2624     21.0 / 10496
sdpa_math                0.4 / 40         0.5 / 62        0.6 / 164        1.7 / 648       6.4 / 2576     22.2 / 10272
sdpa_efficient            0.1 / 0          0.1 / 0          0.2 / 1          0.2 / 1          0.6 / 2          1.6 / 4
sdpa_flash                0.1 / 1          0.1 / 2          0.1 / 3          0.1 / 1          0.3 / 2          0.6 / 4
flash                     0.3 / 1          0.4 / 2          0.2 / 3          0.4 / 1          0.7 / 2          1.0 / 4
tiled                   19.6 / 32        65.8 / 33       260.1 / 33       970.0 / 33      3813.6 / 34     14758.9 / 36

This is one run and the hardware is a GPU in bf16, so do not set these cells beside the CPU table. At N = 16,384, sdpa_flash takes 0.6 ms with 4 MB of extra memory. naive takes 21.0 ms with 10,496 MB. That is 35 times faster and about 2,600 times less memory. sdpa_efficient takes 1.6 ms and sdpa_math 22.2 ms. Both flash and memory-efficient kernels keep extra memory near 4 MB, and the two unfused paths need more than 10 GB. This is the memory argument of the theory post, measured. Our tiled loop is far slower here, 14,759 ms, because it launches many tiny kernels from Python. It still holds its extra memory near 36 MB.

One result is only partly explained. The flash row takes 1.0 ms at N = 16,384, against 0.6 ms for sdpa_flash, and it is slower at every length although the kernel is the same. Our wrapper adds Python work on each call. A failed import flash_attn costs about 0.09 ms, measured on the CPU machine. That does not account for the whole gap, and we did not look further. Cells under 1 ms are also rough, since the table prints one decimal.

All the kernels sit behind one small table. A new kernel is one new line here, and no attention class changes.

BACKENDS: dict[str, Callable[..., torch.Tensor]] = {
    "naive": naive_attention,  # reference: materialises the (Nq, Nk) matrix
    "sdpa": sdpa_attention,  # torch picks the best fused kernel
    "sdpa_math": partial(sdpa_attention, kernel=SDPBackend.MATH),  # torch's unfused C++ path
    "sdpa_flash": partial(sdpa_attention, kernel=SDPBackend.FLASH_ATTENTION),  # CPU flash kernel or CUDA FA2
    "sdpa_efficient": partial(sdpa_attention, kernel=SDPBackend.EFFICIENT_ATTENTION),  # memory-efficient, CUDA only
    "tiled": tiled_attention,  # online softmax in Python, for learning
    "window_chunked": chunked_window_attention,  # sliding window, truly O(N W)
    "flash": flash_attention,  # flash-attn package on CUDA (GPU-only)
}
Listing 32The backend table. Architectures decide what q, k and v are. Backends decide how the softmax is computed.

Checkpoint

  • online_softmax_demo.py prints the same two numbers for acc / l and softmax @ v.
  • Without a GPU, bench_backends.py prints sdpa_efficient and flash: not yet measured. With --flash on a GPU, it measures them.
  • tests/test_backends.py passes. tests/test_gpu.py needs a GPU and is skipped otherwise. On one H100 it gave 7 passed and 1 skipped.
Part 09

Dropout, biases and bounded logits

Goal Add the small tricks that shape the logits, and look at the distribution each one produces.

Theory inWhy transformers do not explode

Attention dropout

Attention dropout removes whole query-key links, then rescales what is left so that the expected output does not change. PyTorch hides this inside SDPA. Here it is in the open.

def attention_dropout(weights: torch.Tensor, p: float) -> torch.Tensor:
    """Drop whole query-key links, then rescale so the expected output is unchanged.

    Rows no longer sum to 1 in a single sample; they sum to 1 on average.
    """
    keep = torch.rand_like(weights) >= p
    return weights * keep / (1.0 - p)
Listing 33Two lines. A row no longer sums to 1 in one sample. It does on average.
Dropout on one row of weights (p = 0.5): links vanish, survivors double
  before: tensor([0.052, 0.341, 0.057, 0.045, 0.121, 0.384]) sum 1.0
  after:  tensor([0.105, 0.000, 0.114, 0.090, 0.242, 0.000]) sum 0.55

A mask is a bias

Part 2 used masked_fill with minus infinity. That is one case of a broader idea: add any tensor to the logits before the softmax. Causal and window masks are biases that take only the values 0 and minus infinity. ALiBi uses a linear penalty on distance instead, with a different slope per head. Because the backends accept a float mask, all of these compose by addition.

def alibi_bias(slopes: torch.Tensor, nq: int, nk: int) -> torch.Tensor:
    """-slope_h * |distance| for every query-key pair. Returns (1, H, nq, nk).

    Nearby keys are barely penalised; far keys are pushed down linearly. Steep heads
    look locally, shallow heads look far. Queries are the last nq positions.
    """
    q_pos = torch.arange(nq, device=slopes.device)[:, None] + (nk - nq)
    k_pos = torch.arange(nk, device=slopes.device)[None, :]
    distance = (q_pos - k_pos).abs().float()
    return (-slopes[:, None, None] * distance)[None]
class RelativePositionBias(nn.Module):
    """A learned scalar per head for each clipped relative distance (T5/Swin style, 1D).

    table: (2 * max_distance + 1, H). Distances beyond max_distance share one entry.
    """

    def __init__(self, num_heads: int, max_distance: int = 64) -> None:
        super().__init__()
        self.max_distance = max_distance
        self.table = nn.Parameter(torch.zeros(2 * max_distance + 1, num_heads))

    def forward(self, nq: int, nk: int) -> torch.Tensor:
        """Returns (1, H, nq, nk)."""
        q_pos = torch.arange(nq, device=self.table.device)[:, None] + (nk - nq)
        k_pos = torch.arange(nk, device=self.table.device)[None, :]
        rel = (k_pos - q_pos).clamp(-self.max_distance, self.max_distance) + self.max_distance
        return self.table[rel].permute(2, 0, 1)[None]
def causal_bias(nq: int, nk: int, device: torch.device | str | None = None) -> torch.Tensor:
    """0 on and below the (bottom-right) diagonal, -inf above. Shape (nq, nk)."""
    return mask_to_bias(causal_mask(nq, nk, device=device))


def window_bias(nq: int, nk: int, window: int, device: torch.device | str | None = None) -> torch.Tensor:
    """0 inside the causal sliding window, -inf outside. Shape (nq, nk)."""
    return mask_to_bias(sliding_window_mask(nq, window, nk, device=device))
ALiBi for 8 heads: the slopes, and the bias of head 0 and head 7 for the last of 5 queries
  slopes: tensor([0.500, 0.250, 0.125, 0.062, 0.031, 0.016, 0.008, 0.004])
  head 0 (steep):  tensor([-2.000, -1.500, -1.000, -0.500, -0.000])
  head 7 (shallow): tensor([-0.016, -0.012, -0.008, -0.004, -0.000])

Head 0 charges 2.0 to read four tokens back. Head 7 charges 0.016 for the same distance. So some heads act locally and others read far, and no position table has a length limit.

QK-norm and soft-capping

Dot products grow with the square of the activation scale. If activations drift up during training, the logits grow fast and the softmax collapses onto one key. Two small changes bound the logits. QK-norm normalises q and k per head before the dot product. Soft-capping squashes the logits themselves.

        if self.config.qk_norm:  # normalise before RoPE, as in OLMo 2 and Qwen3
            q, k = self.q_norm(q), self.k_norm(k)
class RMSNorm(nn.Module):
    """x / rms(x) * gain over the last dim. Used as the per-head Q and K norm."""

    def __init__(self, dim: int, eps: float = 1e-6) -> None:
        super().__init__()
        self.eps = eps
        self.weight = nn.Parameter(torch.ones(dim))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x_f = x.float()
        x_f = x_f * torch.rsqrt(x_f.pow(2).mean(-1, keepdim=True) + self.eps)
        return (x_f * self.weight.float()).to(x.dtype)
def soft_cap(scores: torch.Tensor, cap: float) -> torch.Tensor:
    """s -> cap * tanh(s / cap). Near-identity for |s| << cap, never beyond +-cap."""
    return cap * torch.tanh(scores / cap)
$ .venv/bin/python c03-attention/scripts/stability_demo.py
Logits as activations grow. Uniform attention over 256 keys has entropy 5.55.
activation scale x1              max |s|       std     max p   entropy
  plain                      5.3      1.00     0.043      5.05
  QK-norm                    4.3      1.00     0.040      5.06
  soft-cap c=5               3.9      0.96     0.033      5.11
activation scale x4              max |s|       std     max p   entropy
  plain                     85.0     16.03     0.873      0.33
  QK-norm                    4.3      1.00     0.040      5.06
  soft-cap c=5               5.0      4.35     0.012      4.64
activation scale x16              max |s|       std     max p   entropy
  plain                   1360.5    256.51     0.992      0.02
  QK-norm                    4.3      1.00     0.040      5.06
  soft-cap c=5               5.0      4.96     0.008      4.84

Follow the plain rows. At 16 times the activation scale, the largest logit is 1,360, the top weight is 0.992, and the entropy is 0.02 against a uniform 5.55. Attention has become a hard pick. QK-norm does not move at all, because the norm removes the scale. Soft-cap keeps the logits below its cap of 5.

Simulated plain, largest |s|0
Simulated capped, largest |s|0
Simulated capped, near the cap0
Figure 11The effect of c * tanh(s / c) on a logit distribution. Logits here are simulated in your browser from a normal distribution whose standard deviation is the activation scale squared, which matches the std column above for the plain rows. The readouts are from this simulation, so they differ from the measured table above. Plain logits beyond the axis pile up in the end bins.

Research variants

Four short variants close this part. They are not equally mainstream, so please do not read this list as a menu of equals. Each one keeps the shape contract.

The variants in variants.py
VariantThe changeStatus
Normalised (cosine)Logits are a learned temperature times cos(q, k)Used in shipped vision models such as Swin V2
Talking-headsLearned mixing of heads before and after softmaxResearch
DifferentialThe difference of two softmax maps, so that shared noise cancelsResearch
GatedA sigmoid gate on each head’s outputRecent research
class CosineAttention(_QKV):
    """logits = tau * cos(q, k). Logits are bounded by tau, whatever the activation scale."""

    def __init__(self, config: AttentionConfig, init_tau: float = 10.0) -> None:
        super().__init__(config)
        self.log_tau = nn.Parameter(torch.full((config.num_heads, 1, 1), math.log(init_tau)))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        q, k, v = self.project(x)
        q, k = F.normalize(q, dim=-1), F.normalize(k, dim=-1)
        # tau differs per head, so fold it into q instead of passing a scalar scale.
        out = attend(q * self.log_tau.exp(), k, v, backend=self.config.backend, causal=self.config.causal, scale=1.0)
        return self.o_proj(merge_heads(out))
class TalkingHeadsAttention(_QKV):
    """Mix the H logit maps with a learned H x H matrix before softmax, and the H weight maps after."""

    def __init__(self, config: AttentionConfig) -> None:
        super().__init__(config)
        h = config.num_heads
        self.pre = nn.Parameter(torch.eye(h))  # identity at init: starts as plain MHA
        self.post = nn.Parameter(torch.eye(h))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        q, k, v = self.project(x)
        s = (q @ k.transpose(-2, -1)) / math.sqrt(q.size(-1))  # (B, H, N, N)
        s = torch.einsum("bhnm,gh->bgnm", s, self.pre)
        mask = self.mask(x.size(1), x.device)
        if mask is not None:
            s = s.masked_fill(~mask, float("-inf"))
        w = torch.einsum("bhnm,gh->bgnm", torch.softmax(s, dim=-1), self.post)
        return self.o_proj(merge_heads(w @ v))
class DifferentialAttention(_QKV):
    """A = softmax(Q1 K1^T) - lambda * softmax(Q2 K2^T); out = A V (simplified Diff Transformer).

    Each head splits its q and k into two halves. Noise that both maps share cancels.
    """

    def __init__(self, config: AttentionConfig, lambda_init: float = 0.8) -> None:
        super().__init__(config)
        self.lambda_init = lambda_init
        self.lam = nn.Parameter(torch.tensor(lambda_init))
        self.head_norm = RMSNorm(config.head_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        q, k, v = self.project(x)
        (q1, q2), (k1, k2) = q.chunk(2, dim=-1), k.chunk(2, dim=-1)
        scale = 1.0 / math.sqrt(q1.size(-1))
        mask = self.mask(x.size(1), x.device)
        maps = []
        for qi, ki in ((q1, k1), (q2, k2)):
            s = (qi @ ki.transpose(-2, -1)) * scale
            if mask is not None:
                s = s.masked_fill(~mask, float("-inf"))
            maps.append(torch.softmax(s, dim=-1))
        a = maps[0] - self.lam * maps[1]  # can be negative: it is no longer a distribution
        out = self.head_norm(a @ v) * (1.0 - self.lambda_init)
        return self.o_proj(merge_heads(out))
class GatedAttention(_QKV):
    """out_h <- out_h * sigmoid(x W_g)_h, elementwise, before the output projection.

    The gate lets a head output nothing, which removes the need for "attention sinks"
    (heads parking weight on token 0 to do nothing).
    """

    def __init__(self, config: AttentionConfig) -> None:
        super().__init__(config)
        self.gate = nn.Linear(config.hidden_size, config.num_heads * config.head_dim, bias=False)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        q, k, v = self.project(x)
        out = merge_heads(attend(q, k, v, backend=self.config.backend, causal=self.config.causal))
        return self.o_proj(out * torch.sigmoid(self.gate(x)))
Research variants, one forward pass each (hidden 64, 4 heads):
  GatedAttention          (1, 8, 64)     20,480 params
  CosineAttention         (1, 8, 64)     16,388 params
  DifferentialAttention   (1, 8, 64)     16,401 params
  TalkingHeadsAttention   (1, 8, 64)     16,416 params

We only run these. We do not train them, so nothing here says whether any of them is better. The tests check shape, causality and gradients.

Checkpoint

  • stability_demo.py prints a constant QK-norm row at all three scales.
  • tests/test_stability.py passes.
Part 10

The unified library

Goal Put every piece behind one config, and keep architecture separate from execution.

We now have many modules and many kernels. Their combination would be a mess if each module knew about each kernel. It does not, because part 8 already split them. The config writes that split down.

Two independent choices
Architecture: what q, k and v areExecution backend: how softmax runs
mha, mqa, gqa, mla, linear, crossnaive, sdpa, sdpa_math, sdpa_flash, sdpa_efficient, tiled, window_chunked, flash
@dataclass
class AttentionConfig:
    attention_type: str = "gqa"
    hidden_size: int = 256
    num_heads: int = 8
    num_kv_heads: int | None = None  # None: same as num_heads for mha/gqa, 1 for mqa
    head_dim: int | None = None  # None: hidden_size // num_heads
    causal: bool = True
    window_size: int | None = None  # sliding window: each query sees the last `window_size` keys
    positional_encoding: str = "rope"
    rope_theta: float = 10_000.0
    max_seq_len: int = 4096
    backend: str = "sdpa"  # naive | sdpa | sdpa_math | sdpa_flash | sdpa_efficient | tiled | window_chunked | flash
    qkv_bias: bool = False
    qk_norm: bool = False
    softcap: float | None = None  # logit soft-cap c: s -> c * tanh(s / c)
    dropout: float = 0.0
    # Multi-head latent attention (DeepSeek-V2 naming)
    kv_lora_rank: int = 64
    q_lora_rank: int | None = None
    qk_rope_head_dim: int = 16
    qk_nope_head_dim: int | None = None  # None: head_dim
    v_head_dim: int | None = None  # None: head_dim
    # Cross-attention
    context_size: int | None = None  # width of the sequence we attend to; None: hidden_size
    # Linear attention
    feature_map: str = "elu"
Listing 34One dataclass. The highlighted fields are the two independent choices. The rest describes the architecture.
ARCHITECTURES: dict[str, type[nn.Module]] = {
    "mha": GroupedQueryAttention,
    "mqa": GroupedQueryAttention,
    "gqa": GroupedQueryAttention,
    "mla": MultiHeadLatentAttention,
    "linear": LinearAttention,
    "cross": CrossAttention,
}


def build_attention(config: AttentionConfig, layer_idx: int = 0) -> nn.Module:
    """Instantiate the architecture named by config.attention_type."""
    cls = ARCHITECTURES[config.attention_type]
    return cls(config) if cls is CrossAttention else cls(config, layer_idx=layer_idx)


def make_cache(config: AttentionConfig) -> KVCache | LinearStateCache:
    """The decode-time state each architecture needs. MLA reuses KVCache to hold (c_kv, k_pe)."""
    return LinearStateCache() if config.attention_type == "linear" else KVCache()
Listing 35Config in, module out. make_cache returns the decode state that each architecture needs.

Real attention layers become a few lines of YAML. This one is the Llama-style layer. On a GPU machine, change its last line to backend: flash and nothing else moves.

# GQA as in Llama 3 8B: 32 query heads share 8 KV head groups.
attention_type: gqa
hidden_size: 4096
num_heads: 32
num_kv_heads: 8
causal: true
window_size: null
positional_encoding: rope
backend: sdpa
# MLA with the head settings of DeepSeek-V2 (hidden 5120, 128 heads, r = 512).
attention_type: mla
hidden_size: 5120
num_heads: 128
head_dim: 128
kv_lora_rank: 512
q_lora_rank: 1536
qk_rope_head_dim: 64
qk_nope_head_dim: 128
v_head_dim: 128
causal: true
positional_encoding: rope
backend: sdpa
# GQA with a sliding window, on the chunked backend that exploits it.
attention_type: gqa
hidden_size: 1024
num_heads: 16
num_kv_heads: 4
causal: true
window_size: 512
positional_encoding: rope
backend: window_chunked
$ .venv/bin/python c03-attention/scripts/library_demo.py
# AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132
attention_type  class                          params  cache/token
mha             GroupedQueryAttention         262,144          512
mqa             GroupedQueryAttention         147,456           64
gqa             GroupedQueryAttention         163,840          128
mla             MultiHeadLatentAttention      217,152           80
linear          LinearAttention               262,144            0

The same GQA weights on every backend (max |diff| against naive):
  sdpa        1.5e-07
  sdpa_math   1.5e-07
  sdpa_flash  1.5e-07
  tiled       1.3e-07

A window can change the backend's cost without changing the answer:
  sdpa + mask vs window_chunked: 7.5e-08

Configs in configs/ (built on the meta device: no memory is allocated):
  deepseek_like.yaml  MultiHeadLatentAttention     149,227,520 params,    576 cached numbers per token per layer
  llama_like.yaml     GroupedQueryAttention         41,943,040 params,   2048 cached numbers per token per layer
  mistral_like.yaml   GroupedQueryAttention          2,621,440 params,    512 cached numbers per token per layer

Decode-time state from make_cache:
  gqa     KVCache
  mla     KVCache
  linear  LinearStateCache

The middle block is the point of the design. The same GQA weights give the same output on the four backends it tries, to about 1e-7. The DeepSeek-like config has 149 million parameters and caches 576 numbers per token per layer. It builds on the meta device, so that line costs no memory.

Checkpoint

  • library_demo.py prints differences near 1e-7 for all four backends.
  • tests/test_library.py passes, with one documented skip.
Part 11

The test suite

Goal Know which property each test protects, and run them all in one command.

Every earlier part added tests. Here they are by property. Each test states something that must hold, rather than what the code happens to do.

What the suite protects
PropertyThe checkTest file
ShapesEvery tensor has the documented shape, and weight rows sum to 1test_core.py
CausalityChanging future tokens does not change past outputstest_rope_cache.py, test_library.py
Numerical equivalenceManual attention equals SDPA and nn.MultiheadAttentiontest_core.py, test_heads.py
MHA and GQAGQA with HKV = HQ equals MHA, using copied weightstest_heads.py
MQA and GQAGQA with HKV = 1 equals MQA, using copied weightstest_heads.py
KV cacheCached incremental output equals the full forwardtest_rope_cache.py, test_library.py, test_mla.py
Trusted implementationSame weights give the same output as Hugging Face’s LlamaAttentiontest_rope_cache.py
BackendsTiled, chunked and SDPA all match naivetest_backends.py
Gradient flowEvery parameter gets a finite, non-zero gradienttest_library.py
fp32 and bf16The bf16 error is small, and not zerotest_library.py

Two of these are worth reading. The gradient test catches a parameter that is created and never used. The precision test has a lower bound as well as an upper bound, so a model that silently stayed in fp32 fails it.

@pytest.mark.parametrize("t", CAUSAL_TYPES + ["cross"])
def test_gradients_flow_to_every_parameter(t):
    torch.manual_seed(0)
    m = build_attention(config(t))
    x = torch.randn(2, 10, 64, requires_grad=True)
    out = m(x, torch.randn(2, 7, 64)) if t == "cross" else m(x)
    out.pow(2).mean().backward()
    for name, p in m.named_parameters():
        assert p.grad is not None and torch.isfinite(p.grad).all() and p.grad.abs().sum() > 0, name
    assert x.grad.abs().sum() > 0
def test_fp32_vs_bf16(t):
    """bf16 keeps 8 mantissa bits (~3 significant digits): expect ~1e-2 relative error, not 1e-6."""
    torch.manual_seed(0)
    m = build_attention(config(t)).eval()
    x = torch.randn(2, 32, 64)
    ref = m(x)
    out = m.to(torch.bfloat16)(x.bfloat16()).float()
    rel = (out - ref).norm() / ref.norm()
    assert rel < 3e-2, rel
    assert rel > 1e-4  # it really did run in lower precision
$ .venv/bin/python -m pytest c03-attention -m "not slow and not gpu and not network" -rs
# AMD EPYC 7R13, tests capped at 2 threads, torch 2.15.0+cu132
# pytest c03-attention -m "not slow and not gpu and not network" -rs
........................................................................ [ 40%]
.....s.................................................................. [ 81%]
................................                                         [100%]
=========================== short test summary info ============================
SKIPPED [1] c03-attention/tests/test_library.py:22: flash kernels need equal q, k, v widths; MLA uses dn + dr for q, k and dv for v
175 passed, 1 skipped, 8 deselected in 16.43s

That run covers everything except the GPU file. The test_gpu.py tests compare the real flash kernels with naive, in bf16. On one H100 they gave 7 passed and 1 skipped, and the skip needs the flash-attn package, which was not installed. MLA and linear attention have no outside reference here. Their tests compare the code with itself: cached against full, absorbed against explicit, recurrent against parallel.

Checkpoint

  • The whole suite passes with one skip: MLA on sdpa_flash.
Part 12

Benchmark the zoo

Goal Measure training, prefill and decode for each architecture on one machine, and find out what each design really costs.

Part 8 compared kernels on fixed inputs. This benchmark compares whole attention layers. Every layer has D = 256, 8 query heads and B = 1, and every cell runs in a fresh process. The longest run is N = 16,384. GQA naive is the same layer as GQA on the naive kernel, and it keeps the score matrix for autograd, so its peak memory reaches about 25 GB at that length. A second run on one GPU follows the CPU analysis.

$ .venv/bin/python c03-attention/benchmarks/bench_zoo.py --device cpu
AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132. One layer, D = 256, Hq = 8, dh = 32, torch.float32.
layer               N    fwd ms    bwd ms  peak MB  prefill ms     tok/s  decode ms/tok  cache MB
MHA               512       4.0       6.6       24         3.6   141,764           0.42      1.03
MHA              1024       8.1      13.5       40         8.2   124,137           0.38      2.03
MHA              2048      15.8      34.4       67        17.8   114,839           0.41      4.03
MHA              4096      39.0      89.8      105        36.2   113,113           0.60      8.03
MHA              8192     175.1     423.9      179       177.9    46,052           1.26     16.03
MHA             16384     515.0    1333.3      325       507.6    32,279           2.13     32.03
GQA Hkv=2         512       4.4      12.4       14         4.0   129,422           0.31      0.26
GQA Hkv=2        1024       8.0      39.0       27         7.2   141,771           0.40      0.51
GQA Hkv=2        2048      19.8      76.6       41        19.6   104,394           0.43      1.01
GQA Hkv=2        4096      54.1     279.5       82        50.0    81,987           0.57      2.01
GQA Hkv=2        8192     145.3     922.7       40       119.7    68,419           1.16      4.01
GQA Hkv=2       16384     447.0    3763.2      212       680.2    24,086           2.85      8.01
MQA               512       4.6      19.3       10         3.7   139,949           0.33      0.13
MQA              1024       8.8      48.7       24         7.5   137,196           0.49      0.25
MQA              2048      16.2     158.5       17        13.7   148,986           0.62      0.50
MQA              4096      40.9     560.9       72        39.4   103,926           1.06      1.00
MQA              8192     124.2    1909.1      112       116.4    70,377           0.82      2.00
MQA             16384     380.1    6680.5      110       406.0    40,353           1.10      4.00
MLA r=64          512       9.4       9.6       59         7.6    67,411           0.86      0.15
MLA r=64         1024      26.0      36.2      134        26.2    39,034           0.94      0.29
MLA r=64         2048     110.9     139.1      460       119.3    17,166           1.48      0.57
MLA r=64         4096     423.7     461.7     1667       438.6     9,339           2.24      1.13
MLA r=64         8192    1383.9    1805.0     6193      1614.2     5,075           3.85      2.25
MLA r=64        16384    5632.0    7372.2    24757      8077.4     2,028          12.16      4.50
local mask        512       4.9      17.4       14         4.6   111,741           0.49      0.26
local mask       1024      10.7      39.5       26        10.3    99,242           0.65      0.51
local mask       2048      37.9     137.2       65        32.4    63,143           0.87      1.01
local mask       4096     115.1     579.8      206       140.1    29,245           0.89      2.01
local mask       8192     390.3    2156.4      356       512.4    15,986           1.39      4.01
local mask      16384    1428.7    8342.9     1334      1808.3     9,060           1.81      8.01
local chunked     512       4.6      12.0       14         4.0   126,647           0.48      0.26
local chunked    1024      10.3      24.0       28         9.9   103,830           0.45      0.51
local chunked    2048      15.0      38.0       46        12.6   162,043           0.36      1.01
local chunked    4096      28.2      98.2       86        22.3   183,419           0.39      2.01
local chunked    8192      55.2     216.1      128        54.1   151,548           0.48      4.01
local chunked   16384     102.6     469.7      328        80.1   204,642           1.44      8.01
linear            512       5.3       9.6       45        35.8    14,320           0.25      0.03
linear           1024      24.5      51.8      108        70.3    14,565           0.27      0.03
linear           2048      92.7     179.4      345       164.4    12,457           0.28      0.03
linear           4096     295.1     606.5     1214       262.5    15,602           0.23      0.03
linear           8192    1268.4    2741.0     4570       547.7    14,956           0.27      0.03
linear          16384    4758.4    9864.6    17665      1120.2    14,625           0.23      0.03
GQA naive         512       6.5       8.1       88         5.4    94,131           0.81      0.26
GQA naive        1024      62.8      95.5      127        80.0    12,794           0.76      0.51
GQA naive        2048     194.9     318.7      444       247.8     8,264           1.18      1.01
GQA naive        4096     756.0    1119.5     1676       861.9     4,753           1.54      2.01
GQA naive        8192    2788.3    4346.5     6321      3012.2     2,720           1.63      4.01
GQA naive       16384    9868.3   13914.6    25206     12260.0     1,336           4.09      8.01

That is a lot of numbers. The chart lets you read one metric at a time. Both axes are logarithmic, so a line with twice the slope grows twice as fast in powers of N.

Hover or tap a point to read its value.

Figure 12The attention zoo on one layer, measured by benchmarks/bench_zoo.py. The hardware line of the output above applies. Click a legend entry to hide or show a layer. The table above holds the same values.

Four patterns stand out at N = 8,192.

Why backward slows when KV heads are shared, at small batches

The backward column was a surprise, and bench_zoo.py uses B = 1 throughout. The profiler puts nearly all of the gap inside one PyTorch op, _scaled_dot_product_flash_attention_for_cpu_backward, where the time rises from MHA to GQA to MQA. Our layer reaches that op with enable_gqa=True, which hands the shared KV heads to SDPA without a copy. So bench_backward.py adds one more way to run the layer. It copies K and V up to 8 heads first, so the flag stays off.

def sdpa_repeat(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_mask: torch.Tensor | None = None, **kw) -> torch.Tensor:
    """The sdpa backend, with K and V copied up to Hq heads so that enable_gqa stays off."""
    n_rep = q.size(1) // k.size(1)
    return sdpa_attention(q, repeat_kv(k, n_rep), repeat_kv(v, n_rep), attn_mask, **kw)


BACKENDS["sdpa_repeat"] = sdpa_repeat  # local to this process; a new way to run attention is one dict entry
Listing 36The same layer without the flag. A new way to run attention is one dict entry, local to this process.
$ .venv/bin/python c03-attention/benchmarks/bench_backward.py
# AMD EPYC 7R13, 8 threads, torch 2.15.0+cu132. CPU flash kernel, fp32, causal.
# Load average at the start: 90. The machine is shared, so read the brackets.
# Median [fastest-slowest] of 5 calls after a warm-up, in ms. flag = enable_gqa=True, repeat = repeat_kv.
# bench_zoo.py also uses B = 1.

Part 1: the SDPA kernel alone, backward ms. B = 1, Hq = 8, N = 4096, d = 32.
path                           threads = 1             threads = 2             threads = 4             threads = 8  speed-up, 1 to 8
Hkv=8 (no flag)        474.0 [443.5-484.3]     242.9 [230.4-293.7]     128.1 [124.8-182.4]        78.7 [70.2-83.5]              6.03
Hkv=4 flag             460.3 [415.6-490.0]     232.1 [219.2-271.4]     134.9 [123.6-156.2]     124.7 [123.1-155.5]              3.69
Hkv=4 repeat           468.2 [449.1-490.9]     238.2 [224.2-281.6]     136.8 [123.6-158.3]       73.1 [68.7-109.6]              6.41
Hkv=2 flag             456.9 [433.5-469.3]     246.1 [225.1-274.3]     242.6 [223.8-255.5]     238.7 [224.3-250.9]              1.91
Hkv=2 repeat           459.4 [442.5-485.5]     243.5 [232.8-274.0]     140.6 [127.4-153.2]       76.8 [69.0-103.8]              5.98
Hkv=1 flag             462.2 [433.0-488.8]     382.6 [280.5-414.4]     651.8 [650.9-681.5]     514.0 [499.4-545.7]              0.90
Hkv=1 repeat           459.9 [424.7-473.3]     243.6 [221.9-253.0]     131.9 [122.9-136.6]       80.5 [72.7-104.0]              5.71

Part 2: one attnzoo layer, backward ms, by batch size. 8 threads, N = 2048, D = 256, Hq = 8.
  B  layer                              flag                      repeat  flag / repeat
  1  MHA                    31.5 [27.7-34.4]                     no flag              -
  1  GQA Hkv=2              85.9 [77.2-92.2]            35.2 [26.0-38.0]           2.44
  1  MQA                 168.4 [146.3-194.8]            38.0 [33.5-68.4]           4.43
  2  MHA                    62.8 [51.3-66.1]                     no flag              -
  2  GQA Hkv=2              83.3 [80.8-84.4]            52.7 [47.5-62.2]           1.58
  2  MQA                 145.9 [144.5-176.9]            65.7 [65.2-72.2]           2.22
  4  MHA                   97.6 [93.8-126.7]                     no flag              -
  4  GQA Hkv=2              90.6 [87.0-96.1]           97.3 [87.0-102.9]           0.93
  4  MQA                 158.9 [155.0-185.2]           92.6 [90.3-112.5]           1.72
  8  MHA                 199.3 [187.0-213.0]                     no flag              -
  8  GQA Hkv=2           181.5 [174.3-206.3]         180.5 [172.0-190.9]           1.01
  8  MQA                 214.1 [179.8-264.3]         189.5 [183.0-256.4]           1.13

Part 3: one attnzoo layer. B = 1, 8 threads, N = 8192, D = 256, Hq = 8.
layer      path                       forward ms                 backward ms
MHA        no flag           116.6 [111.5-125.8]         288.2 [274.4-318.5]
GQA Hkv=2  flag              109.8 [105.6-112.8]        954.1 [896.8-1005.5]
GQA Hkv=2  repeat            130.7 [122.1-146.5]         271.2 [261.2-299.6]
MQA        flag               101.5 [97.1-113.4]      1874.2 [1750.5-2006.6]
MQA        repeat            120.8 [114.9-129.4]         270.0 [258.3-331.4]

Same answer? One layer, B = 1, N = 1024, flag against repeat, max |difference|:
  GQA Hkv=2  output 0.0e+00, parameter gradients 3.6e-11
  MQA        output 0.0e+00, parameter gradients 8.7e-11

Start with part 3 of the output: one layer, B = 1, N = 8,192. MQA backward takes 1,874 ms with the flag and 270 ms with the repeat. GQA takes 954 ms and 271 ms. MHA, which has no flag, takes 288 ms. So the repeat brings both back to MHA’s level. Forward stays between about 100 and 130 ms. The last block shows the same output, with parameter gradients within 8.7e-11.

Part 1 shows that the flag does not add work. It loses parallel speed-up. At 1 thread every path takes about 460 to 470 ms. From 1 to 8 threads, the paths without the flag speed up about 6 times in this run, and load on this shared machine moves that figure. The flag paths speed up 3.69 times with 4 KV heads, 1.91 times with 2, and 0.90 times with 1. With one KV head, 8 threads are no faster than one.

Part 2 shows that batch size matters. At N = 2,048, the flag / repeat ratio for MQA falls from 4.43 at B = 1 to 2.22 at B = 2, 1.72 at B = 4 and 1.13 at B = 8. For GQA it goes 2.44, 1.58, 0.93 and 1.01. An earlier run of the same script gave 1.66 for MQA at B = 4, and 0.98 at B = 8. So the gap remains at B = 4 for MQA, and it closes once B × HKV reaches 8: at B = 4 for GQA and at B = 8 for MQA. Rows with the same product also have similar ratios: 2.44 and 2.22 at a product of 2, 1.58 and 1.72 at a product of 4.

These patterns fit one explanation: with the flag, this backward kernel runs in parallel only across batch × KV heads. That is an inference from the timings, because we did not read the kernel’s source. The memory cost of repeat_kv is not measured. All of this is CPU, in fp32, and it says nothing about a GPU. The attnzoo layers keep the flag, so the backward columns above include this cost.

The same zoo on one H100

This is a separate run: one NVIDIA H100 80GB HBM3, PyTorch 2.15.0 built for CUDA 13.2, bf16, B = 1, N = 16,384, one measured call after a warm-up. cuDNN attention is off, for a reason given below. The extra GQA flash row is the GQA layer on the flash backend. Do not compare these cells with the CPU table, which is fp32 on a server CPU.

One layer on one H100 (D = 256, 8 query heads, bf16, N = 16,384, one run)
LayerForward (ms)Backward (ms)Peak extra (MB)Prefill (ms)Decode (ms/token)Cache (MB)
MHA2.22.5831.62.6416.02
GQA Hkv=22.12.8752.11.474.00
MQA2.73.3714.22.422.00
MLA r=645.28.91245.02.802.25
local mask9.016.27919.21.594.00
local chunked22.321.39516.01.074.00
linear12.318.38,7923467.80.670.02
GQA naive41.956.133,05042.03.224.00
GQA flash2.55.8753.41.574.00

A GPU-only trap: cuDNN attention and new shapes

The first GPU zoo run used PyTorch’s default kernel choice. On this H100 that picked cuDNN attention, and the numbers looked wrong. Prefill took about 60 to 75 ms at every length on the plain SDPA rows, and one decoded token took about 50 to 90 ms. The table compares that first run, kept as results/gpu_bench_zoo_cudnn.txt, with the run above.

cuDNN attention on (first run) and off, one H100, bf16, B = 1, one run each
LayerNPrefill, cuDNN on (ms)Prefill, cuDNN off (ms)Decode, cuDNN on (ms/token)Decode, cuDNN off (ms/token)
MHA2,04871.91.273.801.92
MHA16,38461.31.648.172.64
local chunked16,384223.916.091.031.07

A direct probe of one SDPA call explained it. With one query and a cache of about 2,000 keys, the default choice took 78.84 ms when the cache length was new, and 0.144 ms when the same shape came again. With cuDNN excluded, the call took 0.05 ms either way. That probe script is not in the repo, and the numbers come from the code writer’s notes. So cuDNN seems to pay a setup cost of 60 to 80 ms for each new shape. Prefill and every decode step bring a new key length, so the first run timed that setup, not attention. That cause is an inference. We did not read the cuDNN or PyTorch source. Training was not affected, because a warm-up call ran on the same shape first.

The fix is in bench_zoo.py. On CUDA it turns cuDNN attention off unless you pass --cudnn. A server that pads its cache lengths to a few fixed sizes would pay the setup cost only a few times.

Checkpoint

  • bench_zoo.py prints one row per layer and length, and saves results/bench_zoo.json.
  • The cache column doubles with N and matches the formula from part 4.

The architectures compared

Rows are the designs we built. Columns are the aspects this post introduced. The first two columns are exact. The time columns come from the benchmark above, at N = 8,192, on the hardware it names. Read down the cache column, then read across to see who pays for a small cache, and how.

Attention designs in this tutorial (D = 256, 8 query heads, B = 1, fp32, CPU)
DesignCached numbers per token, per layerParamsForward (ms)Backward (ms)Prefill (tok/s)Decode (ms/token)Fused kernel hereQuality (not measured here)
MHA512262,14417542446,0521.26YesBaseline
GQA Hkv=2128163,84014592368,4191.16YesClose to MHA in Ainslie et al.
MQA64147,4561241,90970,3770.82YesCan fall below MHA in Ainslie et al.
MLA r=6472198,7201,3841,8055,0753.85No, unequal widthsUnknown
local chunked128, none evicted163,84055216151,5480.48Yes, per chunkDepends on W
linearNone, constant state262,1441,2682,74114,9560.27Not applicableDifferent kernel

The pattern to notice is that nothing is free. MQA and MLA have the smallest caches of the softmax designs, but their quality is an empirical question that these tests do not answer. At B = 1 on this CPU, GQA and MQA also pay in backward time, through the enable_gqa path, and the gap shrinks at larger batches. Linear attention has no growing cache at all, and at this length only MLA and the naive kernel have a slower forward pass. local chunked has the fastest prefill at this length, and it gives up long-range reads. Our chunked cache also keeps every key, even though only the last W can ever be read. Exercise 3 fixes that.

Run everything

The final folder, and every command that produced a number in this post.

c03-attention/ final tree
c03-attention/
├── README.md
├── attnzoo/
│   ├── core.py  masks.py  heads.py  mha.py  gqa.py
│   ├── rope.py  kv_cache.py  attention_window.py  linear.py
│   ├── vision.py  pos2d.py  cross.py  resampler.py  fusion.py
│   ├── mla.py
│   ├── attention_naive.py  attention_sdpa.py  attention_tiled.py
│   ├── attention_flash.py  backends.py
│   ├── stability.py  biases.py  variants.py
│   ├── config.py  library.py  device.py  __init__.py
├── configs/      llama_like.yaml  deepseek_like.yaml  mistral_like.yaml
├── scripts/      one demo per part, plus break_it.py
├── benchmarks/   bench_kv_memory.py  bench_window.py  bench_backends.py
│                 bench_zoo.py  bench_backward.py
├── results/      the real outputs quoted in this post
└── tests/        12 test files, one of them GPU-only
$ .venv/bin/python -m pytest c03-attention -m "not slow and not gpu and not network" -rs
$ .venv/bin/python c03-attention/scripts/shapes.py
$ .venv/bin/python c03-attention/scripts/show_masks.py
$ .venv/bin/python c03-attention/scripts/break_it.py
$ .venv/bin/python c03-attention/scripts/compare_heads.py
$ .venv/bin/python c03-attention/scripts/kv_cache_demo.py
$ .venv/bin/python c03-attention/scripts/linear_demo.py
$ .venv/bin/python c03-attention/scripts/vision_demo.py
$ .venv/bin/python c03-attention/scripts/resampler_demo.py
$ .venv/bin/python c03-attention/scripts/mla_demo.py
$ .venv/bin/python c03-attention/scripts/online_softmax_demo.py
$ .venv/bin/python c03-attention/scripts/stability_demo.py
$ .venv/bin/python c03-attention/scripts/library_demo.py
$ .venv/bin/python c03-attention/scripts/export_figure_data.py
$ .venv/bin/python c03-attention/benchmarks/bench_kv_memory.py
$ .venv/bin/python c03-attention/benchmarks/bench_window.py
$ .venv/bin/python c03-attention/benchmarks/bench_backends.py
$ .venv/bin/python c03-attention/benchmarks/bench_zoo.py --device cpu
$ .venv/bin/python c03-attention/benchmarks/bench_backward.py

On a CUDA GPU, four more commands run the real kernels. They ran once, on one H100, and their outputs are in results/gpu_*. Tri Dao’s flash-attn kernels are not measured.

$ .venv/bin/python -m pytest c03-attention -m gpu -rs
$ .venv/bin/python c03-attention/benchmarks/bench_backends.py --flash
$ .venv/bin/python c03-attention/benchmarks/bench_zoo.py --device cuda --out c03-attention/results/gpu_bench_zoo.json
$ .venv/bin/python c03-attention/benchmarks/bench_zoo.py --device cuda --cudnn --out /dev/null

Key insights and nuances

Exercises

  1. Convert an MHA checkpoint to GQAMedium Average the KV heads of each group to get the GQA weights, and measure how far the output moves as HKV falls from 32 to 1.
    Hint

    test_gqa_equals_mha_with_duplicated_kv_weights does the reverse. Reshape k_proj.weight into (Hkv, n_rep, dh, D) and take the mean over the repeat axis.

  2. Add a custom attention biasEasy Write a bias that favours the first token and the most recent tokens. Make it compose with the causal mask, and pass it on every backend that takes a float mask.
    Hint

    Copy the shape of alibi_bias. test_padding_and_float_bias shows how to check it against naive.

  3. Evict the window cacheMedium With window_size set, our cache still keeps every key. Trim it to the last W keys, keep the positions correct, and show that memory stops growing while cached == full still passes.
    Hint

    The trouble is the offset. get_seq_length must keep reporting the true position after the tensor is trimmed.

  4. Measure the absorbed MLA pathMedium Add absorb=True to the decode loop of bench_zoo.py. Does MLA now beat GQA per token? Report the N where it crosses, if any.
  5. Run the GPU benchmarkHard On your own CUDA GPU, run bench_backends.py --flash, in bf16. Compare the ratio of sdpa_math to sdpa_flash with ours: 22.2 ms against 0.6 ms at N = 16,384 on one H100, against 4,154 ms and 282 ms for the fp32 CPU run. Explain the difference using the theory post on memory. Then install flash-attn, which we did not, and see whether its kernels beat PyTorch’s.

Continue reading

References

Grouped by topic. Every entry links to its primary source.

Sparse and linear attention

Vision and multimodal attention

Code