486. Share keys and values across heads with grouped-query attention
Every attention head normally has its own keys and values, so the KV cache grows with the number of heads. Grouped-query attention (GQA) keeps many query heads but only a few key/value heads: each group of query heads shares one K and one V.
Write gqa(Q, K, V) where Q has shape (n_q_heads, seq, d) and K, V have shape (n_kv_heads, seq, d). n_q_heads is a multiple of n_kv_heads. Query head h uses key/value head h // (n_q_heads // n_kv_heads).
For each query head, compute causal attention (scores = q @ k.T / sqrt(d), mask j > i, row softmax, weights @ v). Return an array of shape (n_q_heads, seq, d).
With n_kv_heads == n_q_heads this is ordinary multi-head attention; with n_kv_heads == 1 it is multi-query attention.
def gqa(Q, K, V)Example 1
Input: gqa([[[1.0], [1.0]], [[1.0], [1.0]]], [[[0.0], [0.0]]], [[[1.0], [3.0]]])
Output: [[[1.0], [2.0]], [[1.0], [2.0]]]
Constraints
Qhas shape(n_q_heads, seq, d)Vhas shape(n_kv_heads, seq, d)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
group = n_q_heads // n_kv_heads.
Hint 2
Query head h reads K[h // group] and V[h // group]; the rest is ordinary causal attention.
Common mistakes
- Using h %
n_kv_headswould interleave heads into the wrong groups, which is the bug in the buggy version.
Understand the idea
In normal multi-head attention every query head has its own keys and values, so the KV cache grows with the head count. Grouped-query attention keeps many query heads but lets a group of them share one key head and one value head, like several students sharing one textbook. The group size is n_q_heads // n_kv_heads, and query head h reads key/value head h // group_size.
8 query heads, 2 KV heads, so group size is 4. Heads 0 to 3 use KV head 0, heads 4 to 7 use KV head 1. Head 5 uses 5 // 4 = 1. Using modulo instead is a bug: head 1 would get 1 % 2 = 1, but it belongs to group 0. After picking the right K and V, each head runs ordinary causal attention. The KV cache here is 4 times smaller than full multi-head. Llama 2 70B and many newer LLMs use GQA.
Companies3
- Anthropic a candidate reported this question LLM from scratch interview walkthrough (system-design-labs)
- DeepMind the topic appears in interview reports AI Engineering Interview Questions Company Wise (Outcome School)
- Mistral the topic appears in interview reports Mistral AI Interview Guide 2026: European Frontier Lab, Open-Weight Strategy, MoE, and La Plateforme
From public interview reports and guides. Not affiliated with or endorsed by these companies.