Equations · Vaswani et al., “Attention Is All You Need” (2017)

The multi-head attention formula, explained term by term

Instead of one attention over the full vectors, a Transformer runs hh smaller attentions in parallel, each with its own learned projections, so different heads can attend to different things. Their outputs are concatenated and mixed by one more matrix.

MultiHead⁡(Q,K,V)=Concat⁡(head1,…,headh) WOwhere headi=Attention⁡(QWiQ,KWiK,VWiV)\begin{aligned} \operatorname{MultiHead}(Q, K, V) &= \operatorname{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h)\,W^O \\ \text{where}\ \mathrm{head}_i &= \operatorname{Attention}(QW_i^Q, KW_i^K, VW_i^V) \end{aligned}

Open in the decoder →

Term by term

  1. Q,K,VQ, K, V

    The queries, keys and values. In self-attention all three are the same input XX, one row per token.

  2. WiQ, WiK, WiVW_i^Q, \ W_i^K, \ W_i^V

    Head ii's projection matrices. The subscript is the head number; the superscripts QQ, KK, VV are labels, not powers.

  3. headi=Attention⁡(…)\mathrm{head}_i = \operatorname{Attention}(\ldots)

    Scaled dot-product attention, softmax⁡(QK⊤/dk)V\operatorname{softmax}(QK^\top/\sqrt{d_k})V, run on head ii's projected inputs.

  4. Concat⁡(head1,…,headh)\operatorname{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h)

    The hh head outputs placed side by side, along the feature axis.

  5. WOW^O

    The output projection: mixes the heads' results back into one vector per token. OO stands for output.

Shapes

A small worked example

The original Transformer: dmodel=512d_{\text{model}} = 512, h=8h = 8, so dk=dv=64d_k = d_v = 64. Each head attends in a 64-dimensional space; eight heads concatenated give 512 again, and WOW^O is 512×512512 \times 512. The total cost is about that of one full-width attention.

In code

import torch

def multi_head(X, Wq, Wk, Wv, Wo, h):
    # X: (n, d). Wq, Wk, Wv, Wo: (d, d); Wq holds all h of the W_i^Q side by side
    n, d = X.shape
    split = lambda M: M.view(n, h, d // h).transpose(0, 1)    # (h, n, d/h)
    Q, K, V = split(X @ Wq), split(X @ Wk), split(X @ Wv)
    w = torch.softmax(Q @ K.transpose(-2, -1) / (d // h) ** 0.5, dim=-1)
    heads = w @ V                                             # (h, n, d/h)
    return heads.transpose(0, 1).reshape(n, d) @ Wo           # concat, then W^O

Every symbol in it

Q,K,VQ, K, VQ, K, V (query, key, value)xi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)x2,  βt,  WQx^2,\; \beta^t,\; W^QSuperscript (power or label)W∈Rm×n\mathbf{W} \in \mathbb{R}^{m \times n}Bold uppercase (matrix)softmax⁡(z)i=ezi∑jezj\operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_j e^{z_j}}SoftmaxConcat⁡(head1,…,headh)WO\operatorname{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h) W^OConcatenationx1,…,xnx_1, \ldots, x_nDots (ellipsis)

Other equations