Algorithmcore
Multi-head attention
Also called multi-headed attention.
Run h attention heads in parallel on learned low-dimension projections of queries, keys and values, then concatenate and project the outputs.
- Time
- Θ(n^2 d + n d^2) worst
- Space
- Θ(n d) extra
- Where
- d = the model size; h = the number of heads; n = the number of tokens
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, 2017
Multi-head attention runs copies of scaled dot-product attention side by side. Each copy, called a head, first maps the queries, keys and values to a smaller size with its own learned matrices, so the heads can look for different kinds of match. The outputs are joined end to end and mapped back to size by one more matrix. With the cost is about the same as one attention of full size. It is the attention layer of every transformer, in self-attention and in cross-attention between the encoder and the decoder.
In plain words
One attention step lets each word take a weighted mix of the other words. But a word often needs several mixes at once: one that follows its grammar, one that finds the thing it refers to, one that looks at the word just before it.
So split the work into several small attention steps, the heads. Each head looks at the words through its own learned lens and makes its own mix. Because each head works with shorter vectors, all heads together cost about as much as one big step.
At the end, put the outputs of the heads next to each other and pass them through one more learned map, which combines what the heads found into a single vector per word.
The problem
The input is a query-side matrix of shape and a key-value side of shape ; in self-attention and . The weights of head , for , are and of shape and of shape , and the output map has shape . Usually . The output is the matrix
where Attention is the scaled dot-product attention with an optional mask, the same mask for every head. The weights are fixed inputs here; training sets them.
The algorithm
MULTI-HEAD(X_q, X_kv, W^Q, W^K, W^V, W^O, h, M)- 1
for r ← 1 to h do - 2
Q_r ← X_q W^Q_r ▷ n × d_k - 3
K_r ← X_kv W^K_r ▷ m × d_k - 4
V_r ← X_kv W^V_r ▷ m × d_v - 5
H_r ← ATTENTION(Q_r, K_r, V_r, M) ▷ n × d_v - 6
H ← [H_1 H_2 ... H_h] ▷ n × h d_v, heads side by side - 7
return H W^O ▷ n × d
Lines L2 to L4 are usually done as three products with matrices, whose columns are the heads in order, and the result is reshaped into blocks. The heads at line L5 are independent and run in parallel. Line L7 can also be read as a sum: split into blocks of rows, , then . So each head writes its own contribution into the output, and the concatenation is only a way to do all products as one.
Example
Take , and , so the scale is . Let every weight matrix be the identity: head 1 then sees the first two coordinates of each token and head 2 the last two. Self-attention on three tokens:
Tokens 1 and 2 are the same for head 1 and differ for head 2. The state after line L5, rounded:
| head | scores of token 1 | weights of token 1 | weights of token 2 | weights of token 3 | , rows 1 to 3 |
|---|---|---|---|---|---|
| 1 | (2.82843, 2.82843, 0) | (0.48565, 0.48565, 0.0287) | (0.48565, 0.48565, 0.0287) | (0.05286, 0.05286, 0.89429) | (1.94259, 0.05741), (1.94259, 0.05741), (0.21143, 1.78857) |
| 2 | (0, 0, 0) | (0.33333, 0.33333, 0.33333) | (0.05286, 0.89429, 0.05286) | (0.05286, 0.05286, 0.89429) | (0.66667, 0.66667), (0.10571, 1.78857), (1.78857, 0.10571) |
Head 1 cannot tell tokens 1 and 2 apart and gives them the same output. Head 2 sends token 2 mostly to itself. Lines L6 and L7, with , give the rows (1.94259, 0.05741, 0.66667, 0.66667), (1.94259, 0.05741, 0.10571, 1.78857) and (0.21143, 1.78857, 1.78857, 0.10571). Tokens 1 and 2 now have different outputs, although head 1 alone gave them the same one.
Correctness
The loop at line L1 computes each by the definition, using the correctness of scaled dot-product attention at line L5, and lines L6 and L7 form the product with . The full proof shows the identity , that one head with is plain attention on projected inputs, and that multi-head self-attention without a mask is permutation equivariant.
Proof: Multi-head attention returns Concat(H_1, ..., H_h) W^O, this equals the sum of the head outputs H_r W^O_r, one full-size head is plain attention on projected inputs, and unmasked self-attention is permutation equivariantfull
We use the notation of the page. is , is , and are , is and is . We split into blocks of consecutive rows, . The mask is the same for all heads, and every query sees at least one key. We use the correctness theorem of scaled dot-product attention: ATTENTION returns the row softmax of the masked scaled scores times .
Lemma 1 (the heads). After iteration of line L1, .
Proof. Lines L2 to L4 compute the three products of the definition, with the shapes , and that ATTENTION needs. Line L5 then returns the attention of these three matrices by the correctness of scaled dot-product attention. Iterations do not share state, so each is computed independently of the others.
Theorem 2 (correctness). MULTI-HEAD returns .
Proof. By Lemma 1 all heads are correct when the loop ends. Line L6 forms the matrix whose columns to are , which is the concatenation in the order of the heads. Line L7 multiplies it by .
Theorem 3 (sum of heads). .
Proof. Let . Entry of is . Split the index into the head and the place in the head, with . Then and , so
Corollary 4 (one head). For the output is , plain attention on projected inputs followed by a linear map.
Proof. Theorem 3 with a single term.
Theorem 5 (permutation equivariance). Take self-attention, , with no mask. Let be the matrix of a permutation , so . Then .
Proof. For each head, , and the same holds for and . So the inputs of head on are , and . By the permutation theorem of scaled dot-product attention, permuting the queries by permutes the output rows by , and permuting the keys and the values together by the same leaves the output unchanged. So head returns . Then
because acts on the rows and the concatenation acts on the columns.
With a causal mask Theorem 5 fails, since the mask depends on the positions. In its place, the row of token depends only on tokens : in every head, by the causal property of scaled dot-product attention, row of depends only on rows of and , which are functions of rows of ; and line L7 maps each row of on its own.
Complexity
Count multiply-adds with and . Lines L2 to L4 cost over all heads. Line L5 costs per head, in total. Line L7 costs . The sum is in the real RAM: the projections dominate when and the scores when . The projections and the heads take memory; the front matter counts these and one row of scores at a time. A library that stores all score matrices needs more, which is the reason for FlashAttention. The layer has weights, or with biases.
Properties
- Same cost as one head (theorem). With the arithmetic is the same as one head of size , up to the separate softmaxes.
- Sum of heads (theorem). The output is , so heads add their results; this is the form used to study what each head does.
- Permutation equivariance (theorem). Without a mask and without positional information, permuting the tokens permutes the output rows.
- Weights. for the four maps. The number of heads does not change it.
- Heads matter, but not too many (measurement). In Table 3 of Vaswani and colleagues, one head was 0.9 BLEU worse than the best setting on English to German, and quality also dropped with too many heads.
Variants and improvements
- Multi-query attention (Shazeer 2019) keeps query heads but one shared key head and one shared value head, which makes the key-value cache times smaller.
- Grouped-query attention shares each key-value head among query heads, between the two extremes.
- Positions inside the heads. Rotary position embedding rotates and after lines L2 and L3; ALiBi adds a different distance penalty to the scores of each head.
- Cross-attention. With the encoder output and the decoder state, the same algorithm is the encoder-decoder attention of the transformer.
- FlashAttention changes only how line L5 is computed.
When to use it
Use it wherever a transformer uses attention: in self-attention with a padding mask in an encoder such as BERT, with a causal mask in a decoder such as GPT, and in cross-attention. Prefer grouped-query attention when autoregressive decoding is limited by the memory traffic of the key-value cache. Use a single head only in very small models or for teaching.
Pitfalls
- Wrong split. At lines L2 to L4 each head must use its own block of consecutive columns, and line L6 must place the heads in the same order. Mixing up the reshape (heads as the slow index on one side and the fast index on the other) still runs, with wrong results.
- Wrong scale. Line L5 divides by , not by .
- Forgetting . Returning at line L7 without the product leaves each head's output in its own coordinates; the next layer then cannot mix them.
- Different masks per head. The causal or padding mask at line L5 must be applied to every head.
- not divisible by . Then is not an integer; choose to divide or set on its own.
Implementations
The code takes the inputs and the weight matrices as given and does not train a network.
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/multi-head-attention/. The authors are listed in prov/YXWRTE.jsonl.
"""Multi-head attention: h scaled dot-product attentions on learned projections, concatenated.
Shapes, with named sizes:
X_q is n x d (the query side, one row per token),
X_kv is m x d (the key and value side; X_kv = X_q for self-attention),
W_Q and W_K are d x (h d_k), W_V is d x (h d_v), W_O is (h d_v) x d.
Head r uses the columns r d_k to (r + 1) d_k - 1 of W_Q and W_K, the columns
r d_v to (r + 1) d_v - 1 of W_V, and the same rows of W_O.
With causal=True, query i sees key j when j <= i + (m - n).
Precondition: h >= 1, the column counts of W_Q, W_K and W_V are multiples of
h, all shapes agree, and every query sees at least one key.
Cost: Theta(n d h d_k + m d h (d_k + d_v) + h n m (d_k + d_v) + n h d_v d)
operations. With m = n and h d_k = h d_v = d this is Theta(n d^2 + n^2 d).
Extra memory Theta(n h d_v + m h (d_k + d_v)) for the projections and the
heads, plus Theta(m) for one row of scores at a time.
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 multi_head_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,
causal: bool = False,
) -> Matrix:
"""Return Concat(head_1, ..., head_h) W_O, an n x d matrix."""
if h < 1:
raise ValueError("h must be at least 1")
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]) != len(W_K[0]) or len(W_Q[0]) % h or len(W_V[0]) % h:
raise ValueError("the projection sizes must agree and be multiples of h")
if len(W_O) != len(W_V[0]):
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")
dk, dv = len(W_Q[0]) // h, len(W_V[0]) // h
heads: List[Matrix] = []
for r in range(h): # @line L1
Q_r = matmul(X_q, columns(W_Q, r * dk, (r + 1) * dk)) # @line L2
K_r = matmul(X_kv, columns(W_K, r * dk, (r + 1) * dk)) # @line L3
V_r = matmul(X_kv, columns(W_V, r * dv, (r + 1) * dv)) # @line L4
heads.append(attention(Q_r, K_r, V_r, causal)) # @line L5
H = [[x for head in heads for x in head[i]] for i in range(len(X_q))] # @line L6
return matmul(H, W_O) # @line L7
def parameter_count(d: int, h: int, d_k: int, d_v: int, bias: bool = False) -> int:
"""The number of weights: 2 d h d_k + 2 d h d_v, plus the biases if asked. 4 d^2 when h d_k = h d_v = d."""
count = 2 * d * h * d_k + 2 * h * d_v * d
if bias:
count += 2 * h * d_k + h * d_v + d
return count
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_multi_head_attention.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multi-head-attention/. The authors are listed in prov/YXWRTE.jsonl.
import math
import random
import pytest
from multi_head_attention import attention, multi_head_attention, parameter_count
from nlslog import softmax
X_EX = [[2, 0, 0, 0], [2, 0, 0, 2], [0, 2, 2, 0]]
I4 = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
def rand_matrix(rng, rows, cols, scale=1.0):
return [[rng.gauss(0.0, scale) for _ in range(cols)] for _ in range(rows)]
def oracle(Xq, Xkv, WQ, WK, WV, WO, h, causal=False):
"""Sum over heads of head_r times the rows of W_O that belong to head r, with every entry by its formula."""
n, m, d = len(Xq), len(Xkv), len(WO[0])
dk, dv = len(WQ[0]) // h, len(WV[0]) // h
out = [[0.0] * d for _ in range(n)]
for r in range(h):
def proj(X, W, size, i, a):
return sum(X[i][t] * W[t][r * size + a] for t in range(len(W)))
for i in range(n):
js = [j for j in range(m) if not (causal and j > i + m - n)]
scores = [
sum(proj(Xq, WQ, dk, i, a) * proj(Xkv, WK, dk, j, a) for a in range(dk)) / math.sqrt(dk) for j in js
]
p = softmax(scores)
head = [sum(p[t] * proj(Xkv, WV, dv, j, b) for t, j in enumerate(js)) for b in range(dv)]
for c in range(d):
out[i][c] += sum(head[b] * WO[r * dv + b][c] for b in range(dv))
return out
def close(A, B, tol=1e-9):
return len(A) == len(B) and 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):
h = rng.choice([1, 2, 3])
dk, dv = rng.randint(1, 3), rng.randint(1, 3)
d = rng.randint(1, 5)
n, m = rng.randint(1, 5), rng.randint(1, 5)
return (
rand_matrix(rng, n, d),
rand_matrix(rng, m, d),
rand_matrix(rng, d, h * dk),
rand_matrix(rng, d, h * dk),
rand_matrix(rng, d, h * dv),
rand_matrix(rng, h * dv, d),
h,
)
def test_worked_example():
out = multi_head_attention(X_EX, X_EX, I4, I4, I4, I4, 2)
got = [[round(x, 5) for x in row] for row in out]
assert got[0] == [1.94259, 0.05741, 0.66667, 0.66667]
assert got[1] == [1.94259, 0.05741, 0.10571, 1.78857]
assert got[2] == [0.21143, 1.78857, 1.78857, 0.10571]
@pytest.mark.parametrize("seed", range(20))
def test_against_per_head_sum(seed):
rng = random.Random(seed)
Xq, Xkv, WQ, WK, WV, WO, h = random_case(rng)
assert close(multi_head_attention(Xq, Xkv, WQ, WK, WV, WO, h), oracle(Xq, Xkv, WQ, WK, WV, WO, h))
if len(Xkv) >= len(Xq):
assert close(
multi_head_attention(Xq, Xkv, WQ, WK, WV, WO, h, causal=True),
oracle(Xq, Xkv, WQ, WK, WV, WO, h, causal=True),
)
@pytest.mark.parametrize("seed", range(5))
def test_one_head_is_attention_of_projections(seed):
rng = random.Random(50 + seed)
n, d = 4, 3
X = rand_matrix(rng, n, d)
WQ, WK, WV, WO = (rand_matrix(rng, d, d) for _ in range(4))
def mm(A, B):
return [[sum(A[i][t] * B[t][c] for t in range(len(B))) for c in range(len(B[0]))] for i in range(len(A))]
want = mm(attention(mm(X, WQ), mm(X, WK), mm(X, WV)), WO)
assert close(multi_head_attention(X, X, WQ, WK, WV, WO, 1), want)
@pytest.mark.parametrize("seed", range(10))
def test_self_attention_is_permutation_equivariant(seed):
rng = random.Random(100 + seed)
n, d, h = rng.randint(2, 5), 4, 2
X = rand_matrix(rng, n, d)
WQ, WK, WV, WO = (rand_matrix(rng, d, d) for _ in range(4))
out = multi_head_attention(X, X, WQ, WK, WV, WO, h)
perm = list(range(n))
rng.shuffle(perm)
Xp = [X[i] for i in perm]
assert close(multi_head_attention(Xp, Xp, WQ, WK, WV, WO, h), [out[i] for i in perm])
@pytest.mark.parametrize("seed", range(10))
def test_causal_rows_ignore_later_tokens(seed):
rng = random.Random(200 + seed)
n, d, h = rng.randint(2, 5), 4, 2
X = rand_matrix(rng, n, d)
WQ, WK, WV, WO = (rand_matrix(rng, d, d) for _ in range(4))
out = multi_head_attention(X, X, WQ, WK, WV, WO, h, causal=True)
t = rng.randrange(n)
Y = [row[:] if i <= t else [rng.gauss(0, 3) for _ in row] for i, row in enumerate(X)]
out2 = multi_head_attention(Y, Y, WQ, WK, WV, WO, h, causal=True)
assert close(out2[: t + 1], out[: t + 1], 1e-12)
def test_parameter_count():
assert parameter_count(512, 8, 64, 64) == 4 * 512 * 512
assert parameter_count(512, 8, 64, 64, bias=True) == 4 * 512 * 512 + 4 * 512
assert parameter_count(6, 3, 2, 1) == 2 * 6 * 6 + 2 * 3 * 6
def test_errors():
rng = random.Random(1)
X = rand_matrix(rng, 2, 4)
W = rand_matrix(rng, 4, 4)
with pytest.raises(ValueError):
multi_head_attention(X, X, W, W, W, W, 3)
with pytest.raises(ValueError):
multi_head_attention(X, X, W, W, W, W, 0)
with pytest.raises(ValueError):
multi_head_attention(X, X, W, W, W, rand_matrix(rng, 3, 4), 2)
with pytest.raises(ValueError):
multi_head_attention(X, X[:1], W, W, W, W, 2, causal=True)
History
Vaswani and colleagues (2017) introduced multi-head attention in the transformer, with heads of size for . They argued that one head averages over different kinds of relation, while several heads can attend to different subspaces at different positions. Shazeer (2019) shared the keys and values across heads to speed up decoding, and Ainslie and colleagues (2023) generalized this to grouped-query attention.
References
- Vaswani et al. 2017, Section 3.2.2 (the definition and the sizes h = 8, d_k = d_v = 64), Section 3.2.3 (the three uses in the model), Section 6.2 and Table 3 rows (A) (the number of heads)
- Shazeer 2019, the definition of multi-query attention and its memory traffic during incremental decoding
- Simon J. D. Prince, Understanding Deep Learning, MIT Press 2023, Chapter 12 (Transformers)
Where this leads
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YXWRTE Edit this page History Report an error Markdown