Pidoku

Attention Computation in Practice

Module 11 Lesson 11.f 1h 30m Difficulty 4/5

Prerequisites 10.g, 10.h, 11.c


Before you start: words you need#

WordPlain meaning
Score matrixThe table of q · k values: one row per query token, one column per key token. S × S for a prompt of S tokens.
MaterialiseActually write a whole intermediate tensor to GPU memory, rather than keeping it in pieces in fast on-chip storage.
Online softmaxComputing softmax in chunks with a running maximum and running sum, so the full row of scores is never needed at once (10.g).
Causal maskThe rule that a token may attend only to itself and earlier tokens.
GQAGrouped-query attention: several query heads share one key/value head (12.g).
Split-KVFor decode, cutting the key range into pieces that different SMs process in parallel, then merging the results.
Varlen“Variable length”: a kernel that takes many sequences packed end to end plus their start offsets, instead of a padded rectangle.
SRAMThe fast on-chip memory (shared memory and registers) inside each SM (4.d).

1. What is it?#

How attention is actually computed on a GPU, as opposed to how it is written in a paper.

The textbook formula, softmax(Q·Kᵀ/√d)·V, says to build the whole score matrix, normalise it and multiply by V. Every production implementation restructures that: it never stores the score matrix, it uses different kernels for prefill and decode, and it handles masks, GQA and paged KV caches inside the kernel.

This lesson is about those shapes and costs. The FlashAttention algorithm itself has its own lesson (13.l), the paged KV cache has 12.l, and how vLLM picks among attention kernels is 18.c.

Facts checked on 12 November 2026.


2. Why does it matter?#

Because the naive implementation has a fatal flaw. At 8,192 tokens, batch 8 and 32 heads, the score matrix for one layer is 34 GB in FP16. It does not fit, and even if it did, writing and reading it would take longer than the useful work.

And because attention is the one operator whose shape changes completely between phases:

  • Prefill: many queries against many keys. Compute bound, like a GEMM.
  • Decode: one query per sequence against a long cache. Memory bound, like a GEMV, and too small to fill the GPU unless you split it cleverly.

“Just call the library” is not enough here; you need to know which kernel you are getting and why.


3. Simple analogy#

A weighted average of a million items without writing down all the weights.

Naive: work out all million weights, write them on a long scroll, add them up, then go back and combine the items. You need a million-entry scroll.

Streaming: take the items a page at a time, keep a running total and a running “sum of weights”, and whenever a page contains a bigger weight than any before, rescale what you have so far. You need one page of scratch paper, and you get the same answer.

Split-KV is the same thing with eight friends: each takes an eighth of the items, does the streaming method, and at the end you combine their eight partial totals.


4. Tiny example: three implementations, one answer#

Go
// attention.go — three ways to compute the same attention, for one head:
// naive (store every score), tiled with an online softmax (the FlashAttention idea),
// and split-KV decode (the key range cut into chunks that run in parallel, then merged).
package main

import (
	"fmt"
	"math"
	"math/rand"
)

const S, D = 512, 64

type seq [S][D]float64

func dot(a, b *[D]float64) (s float64) {
	for i := range a {
		s += a[i] * b[i]
	}
	return s
}

// naive: for each query, store the whole row of scores, softmax it, then mix values.
func naive(q, k, v *seq) *seq {
	out, scale := new(seq), 1/math.Sqrt(D)
	for i := 0; i < S; i++ {
		scores := make([]float64, i+1) // row i of the (S, S) matrix; causal: only j <= i
		m := math.Inf(-1)
		for j := range scores {
			scores[j] = dot(&q[i], &k[j]) * scale
			m = math.Max(m, scores[j])
		}
		var sum float64
		for j := range scores {
			scores[j] = math.Exp(scores[j] - m)
			sum += scores[j]
		}
		for j, p := range scores {
			for c := 0; c < D; c++ {
				out[i][c] += p / sum * v[j][c]
			}
		}
	}
	return out
}

// partial walks keys j0..j1-1 for query i in blocks, keeping a running max m,
// a running denominator l and an unnormalised output acc. No score row is stored.
func partial(q, k, v *seq, i, j0, j1, block int) (m, l float64, acc [D]float64) {
	m, scale := math.Inf(-1), 1/math.Sqrt(D)
	for b0 := j0; b0 < j1; b0 += block {
		b1 := min(b0+block, j1)
		var s [256]float64
		mNew := m
		for j := b0; j < b1; j++ {
			s[j-b0] = dot(&q[i], &k[j]) * scale // a small tile of scores
			mNew = math.Max(mNew, s[j-b0])
		}
		alpha := math.Exp(m - mNew) // rescale what was summed under the old max
		l *= alpha
		for c := range acc {
			acc[c] *= alpha
		}
		for j := b0; j < b1; j++ {
			p := math.Exp(s[j-b0] - mNew)
			l += p
			for c := range acc {
				acc[c] += p * v[j][c]
			}
		}
		m = mNew
	}
	return m, l, acc
}

func tiled(q, k, v *seq, block int) *seq {
	out := new(seq)
	for i := 0; i < S; i++ {
		_, l, acc := partial(q, k, v, i, 0, i+1, block) // causal: keys 0..i
		for c := range acc {
			out[i][c] = acc[c] / l
		}
	}
	return out
}

// splitKV computes the LAST query (a decode step) as `splits` independent pieces
// of the key range, then merges them. On a GPU each piece runs on its own SM.
func splitKV(q, k, v *seq, splits int) [D]float64 {
	i, n := S-1, S
	type piece struct {
		m, l float64
		acc  [D]float64
	}
	var ps []piece
	for s := 0; s < splits; s++ {
		m, l, acc := partial(q, k, v, i, s*n/splits, (s+1)*n/splits, 64)
		ps = append(ps, piece{m, l, acc})
	}
	M := math.Inf(-1)
	for _, p := range ps {
		M = math.Max(M, p.m)
	}
	var L float64
	var out [D]float64
	for _, p := range ps {
		w := math.Exp(p.m - M) // bring every piece to the same max
		L += p.l * w
		for c := range out {
			out[c] += p.acc[c] * w
		}
	}
	for c := range out {
		out[c] /= L
	}
	return out
}

func main() {
	rng := rand.New(rand.NewSource(42))
	q, k, v := new(seq), new(seq), new(seq)
	for i := 0; i < S; i++ {
		for c := 0; c < D; c++ {
			q[i][c], k[i][c], v[i][c] = rng.NormFloat64(), rng.NormFloat64(), rng.NormFloat64()
		}
	}
	a, b := naive(q, k, v), tiled(q, k, v, 128)
	d := splitKV(q, k, v, 8)
	var diffTiled, diffSplit float64
	for i := range a {
		for c := range a[i] {
			diffTiled = math.Max(diffTiled, math.Abs(a[i][c]-b[i][c]))
		}
	}
	for c := range d {
		diffSplit = math.Max(diffSplit, math.Abs(a[S-1][c]-d[c]))
	}
	fmt.Printf("tiled vs naive, all %d queries: max diff %.1e\n", S, diffTiled)
	fmt.Printf("split-KV (8 pieces) vs naive, last query: max diff %.1e\n", diffSplit)
	fmt.Printf("textbook attention stores an S x S score matrix: %d numbers; tiled keeps one tile of %d\n", S*S, 128)
}

Output:

tiled vs naive, all 512 queries: max diff 6.7e-16
split-KV (8 pieces) vs naive, last query: max diff 2.5e-16
textbook attention stores an S x S score matrix: 262144 numbers; tiled keeps one tile of 128

All three agree to the last bits of a float64. The tiled version is exact, not an approximation; it just never holds more than one tile of scores. The split-KV version shows the merge rule decode kernels use: each piece returns its own maximum m, denominator l and unnormalised output, and the pieces are rescaled to a common maximum and added.


5. Technical explanation#

What attention costs#

Per layer, for S query tokens attending to T key tokens, h query heads of size d_head:

FLOPs   ≈ 4 · h · d_head · (number of query-key pairs)
          causal prefill: pairs ≈ S²/2   →  FLOPs ≈ 2 · S² · h · d_head
          decode:         pairs = T      →  FLOPs ≈ 4 · T · h · d_head
Bytes   ≈ the K and V read for those pairs (from the KV cache, 12.f)

For Qwen3-8B (32 heads of 128, 36 layers):

Prefill, 2,000 tokens:  attention ≈ 1.2 TFLOP of 29 TFLOP total        ~4%
Prefill, 32,768 tokens: attention ≈ 317 TFLOP, the rest ≈ 455 TFLOP     ~41%
Decode, 32 requests × 32,768 context: 155 GB of KV read per step,
                        against 15 GB of weights → ~50 ms per step at 3 TB/s

Attention is a small share of short-prompt work and the dominant share of long-context work, in both phases. That is why long context (12.h, 14.i) is its own topic.

The four kernel shapes#

1. PREFILL (many queries, many keys)
   FlashAttention-style forward kernel: tiles over queries AND keys.
   Compute bound; tensor cores do the two matmuls.
   Causal masking lets it skip about half the tiles.

2. DECODE (one query per sequence, many keys)
   Memory bound: reads the whole KV cache of each sequence.
   Too few queries to fill the GPU, so it splits the KEY range (split-KV).

3. APPEND / MIXED (a few queries per sequence, many keys)
   Chunked prefill (12.k) and speculative verification (12.n).
   Varlen kernels: sequences packed end to end, with start offsets.

4. NON-CAUSAL (encoders, image tokens, cross-attention)
   Vision encoders and some multimodal prefixes attend in both directions.

Why decode needs split-KV. A decode step at batch 8 with 32 query heads has 256 query rows. Give each SM one (request, KV head) pair and you have 8 × 8 = 64 units of work for 132 SMs: half the GPU idles while the busy SMs each crawl through a long cache. Splitting each sequence’s key range into pieces gives every SM work, and a short second pass merges the pieces exactly as splitKV does above. This is the “Flash-Decoding” idea; 13.l has its measurements.

GQA inside the kernel#

With GQA, 32 query heads share 8 KV heads in groups of 4 (Qwen3-8B):

Wrong:  k = k.repeat_interleave(4, dim=heads)    ← copies K and V 4 times in memory
Right:  query head i reads KV head i // 4         ← index arithmetic, no copy

Better still, a decode kernel loads each KV head once and uses it for all 4 query heads in its group, so the cache is read once per group rather than once per query head. That is where GQA’s bandwidth saving actually comes from (12.g). An implementation that repeats K and V reads 4 times the bytes it needs; the first thing to check in any custom attention.

Masks, done by skipping#

Causal            j ≤ i
Sliding window    i − W < j ≤ i            gpt-oss: W = 128 on alternate layers
                                           Gemma 3: W = 1,024 on 5 of every 6 layers
Attention sinks   an extra learned logit per head joins the softmax denominator
                  (gpt-oss), so a head can attend to "nothing"
Bidirectional     over image tokens or a prompt prefix, causal elsewhere
Document masks    packed sequences may not see each other

Fused kernels apply masks by tiles, not by element:

for each (query tile, key tile):
    entirely in the masked region    → skip, no work at all
    entirely in the allowed region   → compute with no masking
    on the boundary (the diagonal)   → compute and mask element by element

This is why causal attention costs about half of full attention, and why a sliding window makes long-context attention cost grow with W instead of with T.

The paged KV cache in the kernel#

With a paged cache (12.l), a sequence’s keys and values live in fixed-size blocks scattered through one big pool. The kernel takes a block table per sequence and fetches block 17, then block 3, then block 92, and so on. The cost is one extra lookup per block and slightly worse memory access at block edges, a few percent of kernel time. The gain is no fragmentation and cheap sharing, which allows several times more concurrent requests.


6. Under the hood: the memory hierarchy#

HBM, 3.35 TB/s on H100          SRAM (shared memory + registers), per SM
────────────────────────        ──────────────────────────────────────────
Q, K, V, O                      a Q tile (e.g. 128 × d_head)
                                a K tile and a V tile (e.g. 128 × d_head each)
                                the score tile, 128 × 128   ← never leaves the SM
                                running max m and sum l     ← in registers

Tile sizes are chosen so these fit in an H100 SM’s 228 KB of shared memory and its registers. Each generation of kernel is rewritten for its hardware (4.f): FlashAttention-2 for Ampere-style MMA, FlashAttention-3 for Hopper’s TMA and wgmma with warp specialisation (some warps only load, others only compute) and FP8, and FlashAttention-4 for Blackwell, released in March 2026, reaching about 1.6 PFLOP/s in BF16 on a B200. 13.l walks through the algorithm.

What you use in practice:

LibraryWhere it shows up
FlashAttention 2 / 3 / 4PyTorch SDPA, vLLM’s FLASH_ATTN backend
FlashInfervLLM’s default on Blackwell data-centre GPUs; SGLang
FlashMLA and MLA kernelsDeepSeek-style latent attention (12.g)
cuDNN attentionPyTorch SDPA’s CUDNN_ATTENTION backend; TensorRT
Triton kernelsportable fallback; PyTorch FlexAttention for custom masks

7. Performance implications#

At prefill the naive version’s problem is memory, not speed: the score matrix grows with S², so past a few thousand tokens it simply does not fit. FlashAttention is first a feasibility fix, then a speed fix. At short lengths the difference is modest.

At decode, attention time grows with context × batch, while weight-reading time is fixed. With long contexts it becomes the larger cost per step (section 5). That is the motivation for KV quantization (13.h), GQA and MLA (12.g), sliding windows and sparse attention.


8. Production implications#

  • Never ship a hand-written naive attention. Use your engine’s backend (18.c), PyTorch’s scaled_dot_product_attention, or FlexAttention for custom masks.

  • Check which backend you got. SDPA silently falls back to its slow MATH backend when no fused kernel supports your data type, head size or mask. In tests, restrict it so a fallback fails loudly:

    Python
    from torch.nn.attention import sdpa_kernel, SDPBackend
    with sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.CUDNN_ATTENTION]):
        out = F.scaled_dot_product_attention(q, k, v, is_causal=True)

    (torch.backends.cuda.sdp_kernel, the older spelling, is deprecated.)

  • Head size matters. Fast kernels support specific head sizes (64, 128, 256 and a few others). A model with an unusual one may have no fast path on your GPU.

  • Confirm GQA is indexed, not repeated, in any custom model code.


9. Common mistakes#

  1. Materialising the score matrix. Fatal beyond a few thousand tokens.
  2. Silent backend fallback in SDPA or in your engine. Check the log or force the backend.
  3. repeat_interleave for GQA. Group-size times the KV bytes.
  4. Assuming one kernel serves prefill and decode. Their shapes are opposite.
  5. Masking by hand with a large negative number in FP16. -1e9 does not fit in FP16 (its largest value is 65,504) and becomes -inf; a row in which every key is masked then computes exp(-inf - (-inf)) and turns into NaN. Let the kernel apply the mask: it skips masked tiles and handles empty rows.
  6. Forgetting attention sinks or windows when porting a model. gpt-oss without its sinks, or Gemma 3 without its windows, loads fine and produces worse text.

10. Hands-on exercise#

  1. Run attention.go. Change the tile size to 1, 32 and 512. Does the answer change? Does the number of rescalings?
  2. Add a sliding window W to partial (skip blocks entirely below i − W). Check it against a windowed version of naive.
  3. Implement GQA in PyTorch two ways, with repeat_interleave and with index arithmetic. Check they agree, and count the KV bytes each reads.
  4. For several (data type, head size, mask) combinations, find which SDPA backend PyTorch picks on your GPU. Build a table.
  5. Measure causal against full attention at S = 4,096 with a fused kernel. Is the ratio 2:1? Why not exactly?
  6. Using section 5’s formulas, find the context length at which decode attention bytes equal weight bytes for Qwen3-8B at batch 1, 8 and 64.

11. Interview questions#

  1. Why can you not materialise the score matrix at long context? Give numbers.
  2. Why do prefill and decode need different attention kernels?
  3. What is split-KV, and how are the partial results merged exactly?
  4. How should GQA be implemented in a kernel, and where does its bandwidth saving come from?
  5. How is a causal mask implemented efficiently at tile level?
  6. What does a paged KV cache cost an attention kernel?
  7. At what context length does attention dominate a forward pass, and what can you do about it?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in