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)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. Worked example: 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.
Similar problems
Part of the advanced LLM architecture track.