Skip to content
Inference Academy

Attention kernels for serving: MLA, split-KV decoding and FlashAttention 3 and 4

Why decode attention is memory-bound for most models and nearly compute-bound for MLA, how weight absorption lets DeepSeek-style models attend directly over a compressed latent, how split-KV (flash-decoding) keeps a GPU busy at small batch and long context, what FlashAttention 3 and 4, FlashInfer and FlashMLA add, and how to check which attention backend your engine picked. Every number comes from code you can run.

By

18 min · verified 2026-113 animated diagramsPro
Share

The attention optimisations lesson covered what modern attention does: FlashAttention tiling, GQA and MLA to shrink the cache, paged memory. This lesson goes one level down, to the kernels that run during serving and the reasons engines pick different ones for prefill and decode, for different models and for different GPUs.

You need Python 3 and numpy.

#Decode attention is a bandwidth problem, until it is not

During decode, each new token's query reads the whole cache for its sequence. The cost that matters is FLOPs per byte of cache read. For each cached token, every query head that shares that KV head does a dot product with the key and a weighted sum of the value:

python
import numpy as np

# 1. Arithmetic intensity of decode attention: FLOPs per byte of KV cache read
def decode_intensity(q_heads, kv_heads, d_qk, d_v, kv_bytes_per_token):
    flops = q_heads * 2 * (d_qk + d_v)       # QK dot product and PV product, per cached token
    return flops / kv_bytes_per_token

designs = {
    "MHA (64 q, 64 kv)":    decode_intensity(64, 64, 128, 128, 64 * 2 * 128 * 2),
    "GQA (64 q, 8 kv)":     decode_intensity(64, 8, 128, 128, 8 * 2 * 128 * 2),
    "MQA (64 q, 1 kv)":     decode_intensity(64, 1, 128, 128, 1 * 2 * 128 * 2),
    "MLA absorbed (128 q)": decode_intensity(128, 1, 576, 512, 576 * 2),
}
print("1. Decode attention, FLOPs per byte of cache read (BF16)")
for k, v in designs.items():
    print(f"  {k:22} {v:6.0f}")
print(f"  H100 balance point: {989e12 / 3.35e12:.0f} FLOPs/byte")
text
1. Decode attention, FLOPs per byte of cache read (BF16)
  MHA (64 q, 64 kv)           1
  GQA (64 q, 8 kv)            8
  MQA (64 q, 1 kv)           64
  MLA absorbed (128 q)      242
  H100 balance point: 295 FLOPs/byte

The intensity is simply how many query heads share each cached byte. Classic multi-head attention is hopelessly memory-bound: one FLOP per byte. GQA helps eightfold. MLA, used by DeepSeek-V3, Kimi K2 and K3 and others, reaches 242, close to the point where an H100 stops waiting on memory (roofline). Batching does not raise this number, because each sequence has its own cache. Only the attention design does.

How many FLOPs does decode attention do per byte of cache?
Interactive
H100 balance ≈ 295
1101001,000 FLOPs/byte

FLOPs per byte

8

Cache per token, per layer

4.00 KiB

Verdict

memory-bound

Eight query heads share each KV head, so each byte is used eight times.

Decode attention, BF16 cache, dense BF16 tensor-core peak. Log scale. Batching does not move this point; only the attention design does.

Two consequences:

  • For GQA models, decode attention speed is set by cache bytes. Shrinking them (FP8 KV cache) speeds attention almost proportionally.
  • For MLA models, the decode kernel must also be compute-efficient: tensor cores, good tiling and FP8 maths matter, which is why MLA has dedicated kernels such as FlashMLA.

#MLA and weight absorption

MLA caches one compressed latent per token (512 numbers in DeepSeek-V3, plus a 64-number positional key) instead of separate keys and values for each head. Each head's key and value are up-projections of that latent: kh=c⋅Wuk[h]k_{h} = c \cdot W_{\text{uk}} [h], vh=c⋅Wuv[h]v_{h} = c \cdot W_{\text{uv}} [h].

The obvious implementation expands the latent into full keys and values for every cached token at every step. That throws away the saving. The trick, called weight absorption, uses associativity: qh⋅kh⊤=qh⋅(c⋅Wuk[h])⊤=(qh⋅Wuk[h]⊤)⋅c⊤q_{h} \cdot k_{h}^{\top} = q_{h} \cdot (c \cdot W_{\text{uk}} [h])^{\top} = (q_{h} \cdot W_{\text{uk}} [h]^{\top}) \cdot c^{\top}. Fold WukW_{\text{uk}} into the query once per step and score directly against the latent. The value side folds WuvW_{\text{uv}} into the output projection the same way.

python
# 2. MLA weight absorption gives the same scores without expanding the latent
rng = np.random.default_rng(0)
d_model, d_latent, d_head, heads, T = 256, 64, 32, 4, 50
W_dkv = rng.normal(size=(d_model, d_latent)) / 16          # compress hidden state to the cached latent
W_uk = rng.normal(size=(heads, d_latent, d_head)) / 8       # expand latent to each head's key
W_q = rng.normal(size=(heads, d_model, d_head)) / 16
X = rng.normal(size=(T, d_model))
c = X @ W_dkv                                              # the cache: T x d_latent
q = np.einsum("d,hde->he", X[-1], W_q)                      # query for the newest token, per head

naive = np.einsum("he,hte->ht", q, np.einsum("tl,hle->hte", c, W_uk))   # expand K for every cached token
q_abs = np.einsum("he,hle->hl", q, W_uk)                                 # fold W_uk into the query instead
absorbed = np.einsum("hl,tl->ht", q_abs, c)                              # score directly against the latent
print(f"\n2. Max difference between naive and absorbed scores: {np.abs(naive - absorbed).max():.1e}")

# cost per decode step at 32K context for a DeepSeek-V3-sized layer (128 heads, latent 512, head dim 128)
H, L, Dh, N = 128, 512, 128, 32768
naive_flops = 2 * N * L * Dh * H * 2 + 2 * H * N * (Dh + 64 + Dh)   # re-expand K and V for every cached token, then attend
absorbed_flops = 2 * H * L * Dh * 2 + 2 * H * N * (L + 64 + L)      # absorb into q and output once, attend over the latent
print(f"  expand K and V every step: {naive_flops/1e9:,.0f} GFLOPs per layer")
print(f"  absorbed:                  {absorbed_flops/1e9:,.1f} GFLOPs per layer")
text
2. Max difference between naive and absorbed scores: 8.9e-15
  expand K and V every step: 1,102 GFLOPs per layer
  absorbed:                  9.2 GFLOPs per layer

Same scores, 120 times less work per decode step at 32K context. After absorption, MLA decode looks like multi-query attention with 128 heads and a 576-wide key: one shared "KV head" read by every query head, which is where the 242 FLOPs per byte comes from.

MLA weight absorption: attend to the latent, never expand it
Animated

Cache (8 tokens × 576)

Work per layer at 32K

–

FLOPs per cache byte

–

The cache holds one latent per token

Instead of keys and values for 128 heads, MLA stores a 512-number latent (plus a 64-number positional key) per token. Here: 8 cached tokens.

Blue rows: cached latents. Amber: expanded per-head keys (naive path). Violet: the absorbed query.

Prefill is the opposite. Thousands of queries in a prompt share one expansion, and attention over 128-wide heads is cheaper than over a 576-wide latent. So engines run MLA prefill in the expanded form and decode in the absorbed form, with different kernels for each. When a new MLA model ships without an absorbed decode kernel for your GPU, expect slow decode until one lands.

MLA has a serving side effect worth knowing: the latent is shared by all heads, so it cannot be split across tensor-parallel ranks by head. Every rank keeps a full copy, which is why large MLA deployments often use data-parallel attention (Kimi K3 case study).

Pro content

Keep reading with Inference Academy Pro

Unlock the rest of this lesson, including 1 animated diagram, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.

Still to come in this lesson

  1. Keeping the GPU busy: split-KV decoding
  2. The kernel families
  3. Which kernel did your engine pick?
  4. What you can now do
  5. Common mistakes
  6. Exercise
  7. Going deeper

You will be able to answer

  • Why is decode attention with grouped-query attention (64 query heads, 8 KV heads) memory-bound?
  • What does MLA weight absorption do?
  • Why does flash-decoding split the KV cache into chunks?
  • Why do engines use the expanded (non-absorbed) form of MLA for prefill?

Preparing for an interview?