SystemsFlashAttention
Grouped Query Attention
PremiumAdd GQA/MQA support so multiple query heads share KV, reducing KV cache memory.
Get code accessIn 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 1Head index mapping:
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.