Techniqueresearch
Grouped-query attention
Also called GQA, multi-query attention.
Let groups of query heads share one key head and one value head, which shrinks the key-value cache with little loss in quality.
Grouped-query attention, GQA, is multi-head attention in which the query heads are split into groups, and all query heads of a group use the same key head and the same value head. So the layer computes query projections but only key and value projections. With it is multi-head attention, and with it is the multi-query attention of Shazeer, with one key head and one value head for all queries. The point is generation: a decoder keeps the keys and values of all past tokens in a key-value cache, and reading that cache at each step limits the speed. GQA makes the cache times smaller. Ainslie and colleagues introduced it in 2023 and showed that a multi-head model can be converted to GQA with a short extra training.
In plain words
In multi-head attention, each head asks its own question and also keeps its own copy of what every past word offers. When a model writes text one word at a time, it must keep all those copies in memory and read them again for each new word. That reading is slow.
GQA lets several heads share one copy. The heads still ask different questions, but a group of them looks things up in the same notes. With 8 heads in groups of 4, the model keeps 2 copies instead of 8, so it reads a quarter as much at each step.
One copy for all heads is fastest but can lose quality. A few groups keep nearly all the quality of separate copies and most of the speed.
When it applies
- Decoder-only and encoder-decoder models that generate text with a key-value cache, where memory traffic per step, and not arithmetic, limits the speed.
- Long contexts or large batches, where the cache is a large part of the memory.
- Converting an existing multi-head checkpoint to faster decoding, by mean pooling and a short uptraining.
- It is not needed where all tokens are processed at once with no cache; Ainslie and colleagues do not apply it to the encoder self-attention layers (Section 2.2).
The template
Let query heads, groups with dividing , head sizes and , and weights , , and . Query head (from 0) uses group :
GQA(X_q, X_kv, W^Q, W^K, W^V, W^O, h, g) ▷ g divides h- 1
for s ← 0 to g - 1 do - 2
K_s ← X_kv W^K_s; V_s ← X_kv W^V_s - 3
for r ← 0 to h - 1 do - 4
s ← floor(r / (h/g)) - 5
Q_r ← X_q W^Q_r - 6
head_r ← ATTENTION(Q_r, K_s, V_s) - 7
return Concat(head_0, ..., head_{h-1}) W^O
ATTENTION is scaled dot-product attention, with a causal mask in a decoder.
Equal to multi-head attention with copied weights (theorem). Build from by giving each query head a copy of the column block , and in the same way. Then GQA with equals multi-head attention with , since each head sees the same three matrices. So GQA is multi-head attention with a constraint on the weights: the heads of a group must have equal key and value maps. The full proof gives the details.
Cache size. Per layer and token, the cache holds numbers instead of , a factor . The parameters of the key and value maps shrink by the same factor; the query and output maps are unchanged.
Uptraining. To convert a multi-head checkpoint, replace the key and value maps of each group by the mean of the maps of its heads (mean pooling), then continue pre-training for a fraction of the original steps; Ainslie and colleagues used . If the heads of a group already have equal maps, mean pooling changes nothing.
Classic examples
A worked layer. Let , heads, groups and head sizes 1, so heads 0 and 1 use group 0 and heads 2 and 3 use group 1. Take , , , and the tokens , , with a causal mask. Token 0 sees only itself, and the heads give , so the output is 0. For token 1, head 0 has the scores 2 and 4 on the values 1 and 2 and gives , head 2 has the scores 1 and 2 on and and gives , and heads 1 and 3 have query 0 and give the means and . The output is , where is the logistic function.
Cache sizes. For a model with 32 layers, 32 query heads of size 128, and 4096 cached tokens in 16-bit numbers:
| layout | key-value heads | cache |
|---|---|---|
| multi-head | 32 | 2 GiB |
| GQA | 8 | 512 MiB |
| multi-query | 1 | 64 MiB |
T5 XXL. In Table 1 of Ainslie and colleagues, uptrained T5 XXL models on summarization, translation and question answering scored on average 47.2 with multi-head attention at 1.51 s per sample, 47.1 with GQA with 8 groups at 0.28 s, and 46.6 with one key-value head at 0.24 s (a measurement). Multi-head T5 Large scored 46.0 at 0.37 s.
Decoder-only models. Many recent decoder-only GPT-style models use GQA in every layer, often with rotary position embedding applied to the queries and the shared keys.
Variations
- One group. gives the smallest cache, at some loss in quality: 46.6 against 47.2 in Table 1 (a measurement).
- Number of groups. Figure 6 of the GQA paper shows that the time per sample grows slowly from and faster near ; they chose 8 groups.
- Conversion choices. Mean pooling worked better than keeping the first head of each group, which worked better than a random start (Figure 4, a measurement).
- Training from scratch. A model can be trained with GQA from the start, with no conversion.
- Larger models. Section 2.2 notes that the cache grows with the model dimension while the parameters and the arithmetic grow with its square, so large models suffer relatively less from the memory traffic of attention. The authors argue that GQA is a good trade-off for them.
Pitfalls
- Wrong head-to-group map. The heads of a group must be the ones whose weights were pooled. Code that groups heads with while the checkpoint uses , or the reverse, runs without error and gives wrong outputs.
- Copying the cache. Repeating the key-value heads times before attention gives the right output but loses the memory saving if the copies are stored. Index the shared heads instead.
- not dividing . The groups must have equal sizes in the usual layout.
- Expecting a speedup without a cache. In training or in the first pass over a prompt, the cost is dominated by the score computation, which is the same for all . The gain is in the decoding steps.
- Counting parameters. Only the key and value maps shrink. The query and output maps keep and weights.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grouped-query-attention/. The authors are listed in prov/VQPZ6C.jsonl.
"""Grouped-query attention (GQA) of Ainslie et al.
h query heads share g key-value heads, with g dividing h. Query head r uses
key-value head s = floor(r / (h / g)), so each group of h / g consecutive
query heads reads the same keys and values. g = h is multi-head attention,
g = 1 is multi-query attention.
Shapes, with named sizes:
X_q is n x d, X_kv is M x d (X_kv = X_q for self-attention),
W_Q is d x (h d_k), W_K is d x (g d_k), W_V is d x (g d_v),
W_O is (h d_v) x d.
With causal=True, query i sees key j when j <= i + (M - n).
mean_pool_heads turns the key or value weights of an h-head model into those
of a g-group model by averaging the columns of the heads in each group, the
first step of uptraining.
Precondition: 1 <= g <= h, g divides h, all shapes agree, and every query
sees at least one key.
Cost: Theta(n d h d_k + M d g (d_k + d_v) + h n M (d_k + d_v) + n h d_v d)
operations. The key-value cache holds 2 M g d_k numbers per layer when
d_v = d_k, a factor g / h of the multi-head cache.
The code takes the inputs and the weights as given. It does not train a network.
"""
import math
from typing import List, Sequence
Matrix = List[List[float]]
NEG_INF = float("-inf")
def matmul(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]]) -> Matrix:
"""The product of an a x b and a b x c matrix."""
if len(A[0]) != len(B):
raise ValueError("inner sizes do not match")
cols = len(B[0])
return [[math.fsum(row[t] * B[t][c] for t in range(len(B))) for c in range(cols)] for row in A]
def columns(A: Sequence[Sequence[float]], lo: int, hi: int) -> Matrix:
"""The columns lo to hi - 1 of A."""
return [list(row[lo:hi]) for row in A]
def attention(Q: Matrix, K: Matrix, V: Matrix, causal: bool = False) -> Matrix:
"""softmax(Q K^T / sqrt(d_k)) V for one head, with a stable softmax."""
n, M, dk = len(Q), len(K), len(K[0])
shift = M - n
out = []
for i in range(n):
s = [
math.fsum(Q[i][t] * K[j][t] for t in range(dk)) / math.sqrt(dk) if not (causal and j > i + shift) else NEG_INF
for j in range(M)
]
mu = max(s)
if mu == NEG_INF:
raise ValueError(f"query {i} sees no key")
p = [math.exp(x - mu) for x in s]
z = math.fsum(p)
out.append([math.fsum(p[j] * V[j][c] for j in range(M)) / z for c in range(len(V[0]))])
return out
def group_of(r: int, h: int, g: int) -> int:
"""The key-value head used by query head r."""
return r // (h // g)
def grouped_query_attention(
X_q: Sequence[Sequence[float]],
X_kv: Sequence[Sequence[float]],
W_Q: Sequence[Sequence[float]],
W_K: Sequence[Sequence[float]],
W_V: Sequence[Sequence[float]],
W_O: Sequence[Sequence[float]],
h: int,
g: int,
causal: bool = False,
) -> Matrix:
"""Return Concat(head_0, ..., head_(h-1)) W_O, an n x d matrix."""
if not (1 <= g <= h) or h % g:
raise ValueError("need 1 <= g <= h with g dividing h")
d = len(X_q[0])
if len(X_kv[0]) != d or len(W_Q) != d or len(W_K) != d or len(W_V) != d:
raise ValueError("the input size d does not match the weights")
if len(W_Q[0]) % h or len(W_K[0]) % g or len(W_V[0]) % g:
raise ValueError("the projection sizes must be multiples of h and g")
dk, dv = len(W_Q[0]) // h, len(W_V[0]) // g
if len(W_K[0]) // g != dk:
raise ValueError("queries and keys must have the same head size")
if len(W_O) != h * dv:
raise ValueError("W_O must have h d_v rows")
if causal and len(X_kv) < len(X_q):
raise ValueError("a causal mask needs at least as many keys as queries")
Ks: List[Matrix] = []
Vs: List[Matrix] = []
for s in range(g): # @line L1
Ks.append(matmul(X_kv, columns(W_K, s * dk, (s + 1) * dk))) # @line L2
Vs.append(matmul(X_kv, columns(W_V, s * dv, (s + 1) * dv))) # @line L2
heads: List[Matrix] = []
for r in range(h): # @line L3
s = group_of(r, h, g) # @line L4
Q_r = matmul(X_q, columns(W_Q, r * dk, (r + 1) * dk)) # @line L5
heads.append(attention(Q_r, Ks[s], Vs[s], causal)) # @line L6
H = [[x for head in heads for x in head[i]] for i in range(len(X_q))]
return matmul(H, W_O) # @line L7
def mean_pool_heads(W: Sequence[Sequence[float]], h: int, g: int) -> Matrix:
"""Average the column blocks of the h heads in each of the g groups: d x (h c) to d x (g c)."""
if not (1 <= g <= h) or h % g or len(W[0]) % h:
raise ValueError("need g dividing h and h dividing the column count")
c = len(W[0]) // h
k = h // g
return [
[math.fsum(row[(s * k + t) * c + u] for t in range(k)) / k for s in range(g) for u in range(c)]
for row in W
]
def kv_cache_entries(layers: int, tokens: int, g: int, d_k: int, d_v: int) -> int:
"""The numbers stored in the key-value cache: one key and one value per group, token and layer."""
return layers * tokens * g * (d_k + d_v)
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
test_grouped_query_attention.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/grouped-query-attention/. The authors are listed in prov/VQPZ6C.jsonl.
import math
import random
import pytest
from grouped_query_attention import grouped_query_attention, group_of, kv_cache_entries, mean_pool_heads
from nlslog import softmax
def rand_matrix(rng, rows, cols, scale=1.0):
return [[rng.gauss(0, scale) for _ in range(cols)] for _ in range(rows)]
def oracle(Xq, Xkv, WQ, WK, WV, WO, h, g, causal=False):
"""Multi-head attention written entry by entry, where head r reads the key and value columns of group r // (h // g)."""
d = len(Xq[0])
dk, dv = len(WQ[0]) // h, len(WV[0]) // g
n, M = len(Xq), len(Xkv)
out = [[0.0] * len(WO[0]) for _ in range(n)]
for r in range(h):
s = r * g // h
def proj(X, W, size, i, a):
return [sum(X[i][t] * W[t][a * size + c] for t in range(d)) for c in range(size)]
for i in range(n):
q = proj(Xq, WQ, dk, i, r)
visible = [j for j in range(M) if not causal or j <= i + M - n]
scores = [sum(a * b for a, b in zip(q, proj(Xkv, WK, dk, j, s))) / math.sqrt(dk) for j in visible]
p = softmax(scores)
head = [sum(p[t] * proj(Xkv, WV, dv, j, s)[c] for t, j in enumerate(visible)) for c in range(dv)]
for c in range(dv):
for e in range(len(WO[0])):
out[i][e] += head[c] * WO[r * dv + c][e]
return out
def close(A, B, tol=1e-9):
return all(abs(a - b) <= tol * (1 + abs(b)) for ra, rb in zip(A, B) for a, b in zip(ra, rb))
def random_case(rng):
g = rng.choice([1, 2, 3])
h = g * rng.choice([1, 2, 3])
d, dk, dv = rng.randint(1, 5), rng.randint(1, 3), rng.randint(1, 3)
M = rng.randint(1, 5)
n = rng.randint(1, M)
return dict(
Xq=rand_matrix(rng, n, d),
Xkv=rand_matrix(rng, M, d),
WQ=rand_matrix(rng, d, h * dk),
WK=rand_matrix(rng, d, g * dk),
WV=rand_matrix(rng, d, g * dv),
WO=rand_matrix(rng, h * dv, d),
h=h,
g=g,
)
def repeat_heads(W, h, g):
"""Copy the column block of each group to every query head in it: d x (g c) to d x (h c)."""
c = len(W[0]) // g
return [[row[(r // (h // g)) * c + u] for r in range(h) for u in range(c)] for row in W]
def test_worked_example():
# h = 4 query heads, g = 2 groups, d = d_k = d_v = 1 per head; tokens 0 and 1
X = [[1.0], [2.0]]
WQ = [[1.0, 0.0, 1.0, 0.0]]
WK = [[1.0, 0.5]]
WV = [[1.0, -1.0]]
WO = [[1.0], [1.0], [1.0], [1.0]]
assert [group_of(r, 4, 2) for r in range(4)] == [0, 0, 1, 1]
O = grouped_query_attention(X, X, WQ, WK, WV, WO, 4, 2, causal=True)
# token 0 sees key 0 only: heads give 1, 1, -1, -1
assert round(O[0][0], 6) == 0.0
# token 1: head 0 has scores 2 and 4 on values 1 and 2, head 2 has 1 and 2 on -1 and -2,
# heads 1 and 3 have query 0 and give the means 1.5 and -1.5
sig = lambda x: 1 / (1 + math.exp(-x))
assert O[1][0] == pytest.approx((1 + sig(2)) + 1.5 - (1 + sig(1)) - 1.5)
assert round(O[1][0], 6) == 0.149738
# without the mask, token 0 also sees key 1
O = grouped_query_attention(X, X, WQ, WK, WV, WO, 4, 2)
assert O[0][0] == pytest.approx(sig(1) - sig(0.5))
assert round(O[0][0], 6) == 0.108599
@pytest.mark.parametrize("seed", range(12))
def test_against_oracle(seed):
rng = random.Random(seed)
c = random_case(rng)
causal = rng.random() < 0.5
got = grouped_query_attention(c["Xq"], c["Xkv"], c["WQ"], c["WK"], c["WV"], c["WO"], c["h"], c["g"], causal)
assert close(got, oracle(c["Xq"], c["Xkv"], c["WQ"], c["WK"], c["WV"], c["WO"], c["h"], c["g"], causal))
@pytest.mark.parametrize("seed", range(8))
def test_equals_multi_head_with_repeated_keys_and_values(seed):
rng = random.Random(100 + seed)
c = random_case(rng)
h, g = c["h"], c["g"]
got = grouped_query_attention(c["Xq"], c["Xkv"], c["WQ"], c["WK"], c["WV"], c["WO"], h, g)
WK, WV = repeat_heads(c["WK"], h, g), repeat_heads(c["WV"], h, g)
mha = grouped_query_attention(c["Xq"], c["Xkv"], c["WQ"], WK, WV, c["WO"], h, h)
assert close(got, mha)
@pytest.mark.parametrize("seed", range(5))
def test_mean_pool_keeps_a_model_whose_group_heads_agree(seed):
rng = random.Random(200 + seed)
c = random_case(rng)
h, g = c["h"], c["g"]
WK, WV = repeat_heads(c["WK"], h, g), repeat_heads(c["WV"], h, g)
assert close(mean_pool_heads(WK, h, g), c["WK"])
assert close(mean_pool_heads(WV, h, g), c["WV"])
# pooling to h groups changes nothing, pooling to 1 group averages all heads
assert mean_pool_heads(WK, h, h) == WK
one = mean_pool_heads(c["WK"], g, 1)
dk = len(c["WK"][0]) // g
assert close(one, [[sum(row[s * dk + u] for s in range(g)) / g for u in range(dk)] for row in c["WK"]])
def test_cache_size():
# 8 query heads of size 128: MHA, GQA with 2 groups, MQA
assert kv_cache_entries(32, 4096, 8, 128, 128) == 2 * 32 * 4096 * 8 * 128
assert kv_cache_entries(32, 4096, 2, 128, 128) * 4 == kv_cache_entries(32, 4096, 8, 128, 128)
assert kv_cache_entries(32, 4096, 1, 128, 128) * 8 == kv_cache_entries(32, 4096, 8, 128, 128)
def test_errors():
X = [[1.0]]
with pytest.raises(ValueError):
grouped_query_attention(X, X, [[1.0] * 4], [[1.0] * 3], [[1.0] * 3], [[1.0]] * 4, 4, 3)
with pytest.raises(ValueError):
grouped_query_attention(X, X, [[1.0] * 4], [[1.0] * 2], [[1.0] * 2], [[1.0]] * 4, 4, 0)
with pytest.raises(ValueError):
grouped_query_attention(X, X, [[1.0] * 4], [[1.0] * 4], [[1.0] * 2], [[1.0]] * 4, 4, 2)
with pytest.raises(ValueError):
grouped_query_attention([[1.0], [1.0]], X, [[1.0] * 2], [[1.0]], [[1.0]], [[1.0]] * 2, 2, 1, causal=True)
with pytest.raises(ValueError):
mean_pool_heads([[1.0] * 6], 3, 2)
Exercises
- Prove that GQA equals multi-head attention with copied key and value maps, and conclude that the set of functions of GQA- is contained in that of GQA- when divides .
- Show that if the heads of each group have equal key and value maps, mean pooling returns those maps, so the converted model computes the same function.
- For , , , compute the parameters of one attention layer for .
- Compute the cache in bytes for 80 layers, 64 query heads of size 128, , 8192 tokens and 16-bit numbers, and compare with .
- Explain why the time per decoding step depends on mostly through the bytes of cache read, and not through the arithmetic.
Proof: GQA returns Concat(head_0, ..., head_(h-1)) W^O with head r reading group floor(r / (h/g)), it equals multi-head attention with copied key and value maps, and mean pooling keeps a model whose group heads agreefull
We use the notation of the page. divides , is the group size, and for . For a matrix with columns per head, is its column block . The target output is
where Att is scaled dot-product attention, with or without the causal mask, the same for all heads.
Lemma 1 (the map is onto the groups). maps onto , and each group receives exactly the heads .
Proof. Write with (division with remainder). Then , and gives . Conversely each and gives a head .
Lemma 2 (the procedure). GQA returns .
Proof. The loop at line L1 runs for , and line L2 stores and ; these are not changed later. The loop at line L3 runs for each head ; line L4 sets , which by Lemma 1 is a stored index, line L5 forms , and line L6 sets . Line L7 concatenates the heads in the order and multiplies by , which is .
Theorem 3 (multi-head attention with copied maps). Let have the column blocks for , and likewise. Then GQA with equals multi-head attention with , that is, GQA with .
Proof. With the map is , so head of the second layer is , which is head of the first layer. The concatenation and are the same. Apply Lemma 2 to both.
Corollary 4. If divides and divides , every function computed by GQA with groups is computed by GQA with groups.
Proof. Let and . Given with blocks, define for , and likewise. For a head , and , by the rule for a positive integer . So both layers give head the same key and value maps, and by Lemma 2 they compute the same function.
Theorem 5 (mean pooling). Let a multi-head layer have key maps with whenever . Mean pooling sets . Then for every , and with the same for the values, the GQA layer computes the same function as the multi-head layer.
Proof. By Lemma 1 the heads , , are exactly the heads of group , and they all equal for any in the group. The mean of equal matrices is that matrix. The claim then follows from Theorem 3.
Cache size. For each layer and token, GQA stores the rows of and , that is numbers, against for multi-head attention: a factor .
References
- Joshua Ainslie, James Lee-Thorp, Michiel de Jong, Yury Zemlyanskiy, Federico Lebrón and Sumit Sanghai, GQA: training generalized multi-query transformer models from multi-head checkpoints, EMNLP 2023, pages 4895-4901, arXiv:2305.13245, Section 2.1 (uptraining, mean pooling), Section 2.2 (GQA-G, GQA-1 and GQA-H, not applied to the encoder, the cache against model size), Section 3.1 (T5.1.1 Large and XXL, alpha = 0.05), Table 1 in Section 3.2, Section 3.3 (Figure 4 checkpoint conversion, Figure 6 number of groups)
- Shazeer 2019, the multi-query attention layer, with one key head and one value head for all query heads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VQPZ6C Edit this page History Report an error Markdown