Skip to main content
CookLLM logoCookLLM Docs

Grouped Query Attention

Premium

Add GQA/MQA support so multiple query heads share KV, reducing KV cache memory.

Get code access

In previous chapters, we built a full Flash Attention kernel with arbitrary sequence length, multi-dim parallelism, and causal masking. Now we add the final key feature: Grouped Query Attention (GQA).

This is standard in Llama 2/3, Mistral, Falcon, etc. It can reduce KV cache memory by 4–8× with minimal quality loss.

Quick GQA Recap

GQA shares Key/Value heads across multiple Query heads:

# MHA: each Q head has its own K/V head
Q: (B, 8, N, D)
K: (B, 8, N, D)
V: (B, 8, N, D)

# GQA: multiple Q heads share KV heads (groups=4)
Q: (B, 8, N, D)
K: (B, 2, N, D)  # 2 KV heads → 4x memory reduction
V: (B, 2, N, D)

# Q heads 0-3 → KV head 0
# Q heads 4-7 → KV head 1

Head index mapping:

kv_head_idx(hq)=⌊hqHQ/HKV⌋\text{kv\_head\_idx}(h_q) = \left\lfloor \frac{h_q}{H_Q / H_{KV}} \right\rfloor

For concept, history, and tradeoffs, see Attention Mechanisms. This chapter focuses on zero-copy, zero-extra-memory GQA in Flash Attention.

Log in to continue reading

This is premium content. Please log in to access the full article.