Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
Origin
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, 2017

Multi-head attention runs hh 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 d/hd/h with its own learned matrices, so the heads can look for different kinds of match. The hh outputs are joined end to end and mapped back to size dd by one more matrix. With hdk=dh d_k = d 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 XqX_q of shape n×dn \times d and a key-value side XkvX_{kv} of shape m×dm \times d; in self-attention Xkv=XqX_{kv} = X_q and m=nm = n. The weights of head rr, for r=1,…,hr = 1, \ldots, h, are WrQW^Q_r and WrKW^K_r of shape d×dkd \times d_k and WrVW^V_r of shape d×dvd \times d_v, and the output map WOW^O has shape hdv×dh d_v \times d. Usually dk=dv=d/hd_k = d_v = d/h. The output is the n×dn \times d matrix

MultiHead⁡(Xq,Xkv)=Concat⁡(H1,…,Hh) WO,Hr=Attention⁡(XqWrQ,  XkvWrK,  XkvWrV),\operatorname{MultiHead}(X_q, X_{kv}) = \operatorname{Concat}(H_1, \ldots, H_h)\, W^O, \qquad H_r = \operatorname{Attention}(X_q W^Q_r,\; X_{kv} W^K_r,\; X_{kv} W^V_r),

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

  1. MULTI-HEAD(X_q, X_kv, W^Q, W^K, W^V, W^O, h, M)
  2. 1for r ← 1 to h do
  3. 2Q_r ← X_q W^Q_r ▷ n × d_k
  4. 3K_r ← X_kv W^K_r ▷ m × d_k
  5. 4V_r ← X_kv W^V_r ▷ m × d_v
  6. 5H_r ← ATTENTION(Q_r, K_r, V_r, M) ▷ n × d_v
  7. 6H ← [H_1 H_2 ... H_h] ▷ n × h d_v, heads side by side
  8. 7return H W^O ▷ n × d

Lines L2 to L4 are usually done as three products with d×hdkd \times h d_k matrices, whose columns are the heads in order, and the result is reshaped into hh blocks. The heads at line L5 are independent and run in parallel. Line L7 can also be read as a sum: split WOW^O into hh blocks of dvd_v rows, W1O,…,WhOW^O_1, \ldots, W^O_h, then HWO=∑rHrWrOH W^O = \sum_r H_r W^O_r. So each head writes its own contribution into the output, and the concatenation is only a way to do all hh products as one.

Example

Take d=4d = 4, h=2h = 2 and dk=dv=2d_k = d_v = 2, so the scale is 2\sqrt{2}. 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:

X=(200020020220).X = \begin{pmatrix} 2&0&0&0 \\ 2&0&0&2 \\ 0&2&2&0 \end{pmatrix}.

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 HrH_r, 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 WO=IW^O = I, 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 HrH_r by the definition, using the correctness of scaled dot-product attention at line L5, and lines L6 and L7 form the product with WOW^O. The full proof shows the identity Concat⁡(H1,…,Hh)WO=∑rHrWrO\operatorname{Concat}(H_1, \ldots, H_h) W^O = \sum_r H_r W^O_r, that one head with dk=dv=dd_k = d_v = d 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. XqX_q is n×dn \times d, XkvX_{kv} is m×dm \times d, WrQW^Q_r and WrKW^K_r are d×dkd \times d_k, WrVW^V_r is d×dvd \times d_v and WOW^O is hdv×dh d_v \times d. We split WOW^O into hh blocks of dvd_v consecutive rows, WO=(W1O⋮WhO)W^O = \begin{pmatrix} W^O_1 \\ \vdots \\ W^O_h \end{pmatrix}. The mask MM 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(Q,K,V,M)(Q, K, V, M) returns the row softmax of the masked scaled scores times VV.

Lemma 1 (the heads). After iteration rr of line L1, Hr=Attention⁡(XqWrQ,XkvWrK,XkvWrV)H_r = \operatorname{Attention}(X_q W^Q_r, X_{kv} W^K_r, X_{kv} W^V_r).

Proof. Lines L2 to L4 compute the three products of the definition, with the shapes n×dkn \times d_k, m×dkm \times d_k and m×dvm \times d_v 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 HrH_r is computed independently of the others. □\square

Theorem 2 (correctness). MULTI-HEAD returns Concat⁡(H1,…,Hh)WO\operatorname{Concat}(H_1, \ldots, H_h) W^O.

Proof. By Lemma 1 all hh heads are correct when the loop ends. Line L6 forms the n×hdvn \times h d_v matrix whose columns (r−1)dv+1(r - 1) d_v + 1 to rdvr d_v are HrH_r, which is the concatenation in the order of the heads. Line L7 multiplies it by WOW^O. □\square

Theorem 3 (sum of heads). Concat⁡(H1,…,Hh) WO=∑r=1hHrWrO\operatorname{Concat}(H_1, \ldots, H_h)\, W^O = \sum_{r=1}^{h} H_r W^O_r.

Proof. Let H=Concat⁡(H1,…,Hh)H = \operatorname{Concat}(H_1, \ldots, H_h). Entry (i,c)(i, c) of HWOH W^O is ∑t=1hdvHitWtcO\sum_{t=1}^{h d_v} H_{it} W^O_{tc}. Split the index tt into the head rr and the place bb in the head, t=(r−1)dv+bt = (r - 1) d_v + b with 1≤b≤dv1 \le b \le d_v. Then Hit=(Hr)ibH_{it} = (H_r)_{ib} and WtcO=(WrO)bcW^O_{tc} = (W^O_r)_{bc}, so

∑t=1hdvHitWtcO=∑r=1h∑b=1dv(Hr)ib(WrO)bc=∑r=1h(HrWrO)ic.□\sum_{t=1}^{h d_v} H_{it} W^O_{tc} = \sum_{r=1}^{h} \sum_{b=1}^{d_v} (H_r)_{ib} (W^O_r)_{bc} = \sum_{r=1}^{h} (H_r W^O_r)_{ic}. \qquad \square

Corollary 4 (one head). For h=1h = 1 the output is Attention⁡(XqWQ,XkvWK,XkvWV) WO\operatorname{Attention}(X_q W^Q, X_{kv} W^K, X_{kv} W^V)\, W^O, plain attention on projected inputs followed by a linear map.

Proof. Theorem 3 with a single term. □\square

Theorem 5 (permutation equivariance). Take self-attention, Xq=Xkv=XX_q = X_{kv} = X, with no mask. Let PP be the n×nn \times n matrix of a permutation σ\sigma, so (PX)i=Xσ(i)(P X)_i = X_{\sigma(i)}. Then MultiHead⁡(PX,PX)=PMultiHead⁡(X,X)\operatorname{MultiHead}(P X, P X) = P \operatorname{MultiHead}(X, X).

Proof. For each head, (PX)WrQ=P(XWrQ)(P X) W^Q_r = P (X W^Q_r), and the same holds for WrKW^K_r and WrVW^V_r. So the inputs of head rr on PXP X are PQrP Q_r, PKrP K_r and PVrP V_r. By the permutation theorem of scaled dot-product attention, permuting the queries by σ\sigma permutes the output rows by σ\sigma, and permuting the keys and the values together by the same σ\sigma leaves the output unchanged. So head rr returns PHrP H_r. Then

Concat⁡(PH1,…,PHh) WO=PConcat⁡(H1,…,Hh) WO,\operatorname{Concat}(P H_1, \ldots, P H_h)\, W^O = P \operatorname{Concat}(H_1, \ldots, H_h)\, W^O,

because PP acts on the rows and the concatenation acts on the columns. ■\blacksquare

With a causal mask Theorem 5 fails, since the mask depends on the positions. In its place, the row of token ii depends only on tokens 1,…,i1, \ldots, i: in every head, by the causal property of scaled dot-product attention, row ii of HrH_r depends only on rows j≤ij \le i of KrK_r and VrV_r, which are functions of rows j≤ij \le i of XX; and line L7 maps each row of HH on its own.

Complexity

Count multiply-adds with m=nm = n and hdk=hdv=dh d_k = h d_v = d. Lines L2 to L4 cost 3nd⋅d3 n d \cdot d over all heads. Line L5 costs n2(dk+dv)n^2 (d_k + d_v) per head, 2n2d2 n^2 d in total. Line L7 costs nd⋅dn d \cdot d. The sum is 4nd2+2n2d=Θ(n2d+nd2)4 n d^2 + 2 n^2 d = \Theta(n^2 d + n d^2) in the real RAM: the projections dominate when n<dn < d and the scores when n>dn > d. The projections and the heads take Θ(nd)\Theta(n d) memory; the front matter counts these and one row of scores at a time. A library that stores all score matrices needs Θ(hn2)\Theta(h n^2) more, which is the reason for FlashAttention. The layer has 4d24 d^2 weights, or 4d2+4d4 d^2 + 4 d with biases.

Properties

  • Same cost as one head (theorem). With dk=d/hd_k = d/h the arithmetic is the same as one head of size dd, up to the hh separate softmaxes.
  • Sum of heads (theorem). The output is ∑rHrWrO\sum_r H_r W^O_r, 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. 4d24 d^2 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 hh query heads but one shared key head and one shared value head, which makes the key-value cache hh times smaller.
  • Grouped-query attention shares each key-value head among h/gh/g query heads, between the two extremes.
  • Positions inside the heads. Rotary position embedding rotates QrQ_r and KrK_r after lines L2 and L3; ALiBi adds a different distance penalty to the scores of each head.
  • Cross-attention. With XkvX_{kv} the encoder output and XqX_q 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 dkd_k 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 dk=d/h\sqrt{d_k} = \sqrt{d/h}, not by d\sqrt{d}.
  • Forgetting WOW^O. Returning HH 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.
  • dd not divisible by hh. Then dk=d/hd_k = d/h is not an integer; choose hh to divide dd or set dkd_k 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.

multi_head_attention.pyI0RawGitHub
# 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 h=8h = 8 heads of size dk=dv=64d_k = d_v = 64 for d=512d = 512. 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

  1. 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)
  2. Shazeer 2019, the definition of multi-query attention and its memory traffic during incremental decoding
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example