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

The attention formula, explained term by term

The core of every Transformer layer. Each token builds a weighted average of the other tokens' values, with the weights set by how well its query matches their keys.

Attention⁡(Q,K,V)=softmax⁡(QK⊤dk)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

Open in the decoder →

Term by term

  1. Q,K,VQ, K, V

    The queries, keys and values: matrices with one row per token, made from the input by learned projections (Q=XWQQ = XW^Q and so on). The paper writes them unbolded.

  2. QK⊤QK^\top

    Every query dotted with every key: entry (i,j)(i, j) is qi⋅kj\mathbf{q}_i \cdot \mathbf{k}_j, how well token ii's query matches token jj's key. The transpose makes the shapes line up.

  3. dk\sqrt{d_k}

    dkd_k is the length of each key (and query) vector; the subscript is a label, not an index. Dividing by its square root keeps the scores' variance near 1, so the softmax does not saturate.

  4. QK⊤dk\frac{QK^\top}{\sqrt{d_k}}

    The scaled scores, one row per query.

  5. softmax⁡(⋅)\operatorname{softmax}(\cdot)

    Applied to each row separately, it turns that query's scores into weights that are positive and sum to 1.

  6. (…) V(\ldots)\,V

    Multiplying the weights by VV makes each output row a weighted average of the value rows.

Shapes

A small worked example

One query q=(1,0)\mathbf{q} = (1, 0), two keys k1=(1,0)\mathbf{k}_1 = (1, 0) and k2=(0,1)\mathbf{k}_2 = (0, 1), dk=2d_k = 2. Scores: (1,0)/2=(0.71,0)(1, 0)/\sqrt{2} = (0.71, 0). Softmax: (0.67,0.33)(0.67, 0.33). The output is 0.67 v1+0.33 v20.67\,\mathbf{v}_1 + 0.33\,\mathbf{v}_2: mostly the first value, because the query matched the first key.

In code

import numpy as np

def attention(Q, K, V):
    d_k = Q.shape[-1]
    scores = Q @ K.T / np.sqrt(d_k)              # (n, m)
    w = np.exp(scores - scores.max(-1, keepdims=True))
    w = w / w.sum(-1, keepdims=True)             # softmax over each row
    return w @ V                                 # (n, d_v)

Every symbol in it

Q,K,VQ, K, VQ, K, V (query, key, value)W∈Rm×n\mathbf{W} \in \mathbb{R}^{m \times n}Bold uppercase (matrix)x⊤y\mathbf{x}^\top \mathbf{y}Transposedk\sqrt{d_k}Square rootxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)ab\frac{a}{b}Fractionsoftmax⁡(z)i=ezi∑jezj\operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_j e^{z_j}}Softmax

Other equations