Algorithm Search⌘K

Algorithmcore

Scaled dot-product attention

Also called softmax attention, QKV attention.

Output softmax(Q K^T / sqrt(d_k)) V: each query gets a mix of the value vectors, weighted by how well each key matches it. Costs O(n^2 d) for n tokens.

Time
Θ(n m (d + e)) worst
Space
Θ(m) extra
Where
d = the size d_k of a query or key; e = the size d_v of a value; m = the number of keys and values; n = the number of queries
Properties
deterministicexactofflineiterative
Origin
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, 2017

Scaled dot-product attention lets each position of a sequence read from all other positions. Each query vector is compared with every key vector by a dot product. The scores are divided by dk\sqrt{d_k} and turned into weights by a softmax, and the output is the weighted sum of the value vectors. In matrix form the output is softmax⁡(QK⊤/dk) V\operatorname{softmax}(Q K^\top / \sqrt{d_k})\, V, with the softmax taken over each row. It is the only step of a transformer where positions exchange information, and multi-head attention runs several copies of it side by side. For nn tokens attending to each other it costs Θ(n2d)\Theta(n^2 d) time.

In plain words

Each word in a sentence asks a question, holds a label, and carries a piece of content. To update one word, compare its question with the label of every word, including itself. A good match gives a high score.

Turn the scores into shares that add up to one, so that the best matches get most of the share and poor matches get almost nothing. The new value of the word is the content of all the words, mixed in those shares.

The scores are first made smaller by a fixed amount that depends on the length of the vectors. Without this, long vectors give very large scores, one word takes almost the whole share, and learning slows down.

To stop a word from looking at the words after it, give those words a score so low that their share is zero.

The problem

The input is three matrices: the queries QQ of shape n×dkn \times d_k, the keys KK of shape m×dkm \times d_k and the values VV of shape m×dvm \times d_v, with row jj of VV belonging to key jj. An optional mask MM of shape n×mn \times m says which keys each query may see. The output is the n×dvn \times d_v matrix

O=softmax⁡ ⁣(QK⊤dk+B)V,Bij={0if Mij,−∞otherwise,O = \operatorname{softmax}\!\left(\frac{Q K^\top}{\sqrt{d_k}} + B\right) V, \qquad B_{ij} = \begin{cases} 0 & \text{if } M_{ij}, \\ -\infty & \text{otherwise,} \end{cases}

where the softmax of a row ss is softmax⁡(s)j=esj/∑j′esj′\operatorname{softmax}(s)_j = e^{s_j} / \sum_{j'} e^{s_{j'}} and e−∞=0e^{-\infty} = 0. Every query must see at least one key. In self-attention QQ, KK and VV are three linear maps of the same nn token vectors, so m=nm = n. The causal mask lets query ii see key jj only when j≤ij \le i; this is what causal language modeling needs.

Why divide by dk\sqrt{d_k}: Vaswani and colleagues note in a footnote that if the components of qq and kk are independent with mean 0 and variance 1, then q⋅k=∑tqtktq \cdot k = \sum_t q_t k_t has mean 0 and variance dkd_k. Dividing by dk\sqrt{d_k} gives the scores variance 1 whatever the size, which keeps the softmax away from the flat regions where its gradient is very small.

The algorithm

The rows of the output are independent, so the algorithm handles one query at a time. For each query it computes a row of scores, applies the mask, and takes a stable softmax: it subtracts the largest score before taking exponentials, as in the log-sum-exp trick.

  1. ATTENTION(Q, K, V, M) ▷ Q: n × d_k, K: m × d_k, V: m × d_v
  2. 1for i ← 1 to n do
  3. 2for j ← 1 to m do
  4. 3s_j ← (Q_i · K_j) / √d_k
  5. 4if not M_ij then s_j ← -∞
  6. 5μ ← max_j s_j ▷ finite, since query i sees a key
  7. 6p_j ← exp(s_j - μ) for every j; Z ← Σ_j p_j
  8. 7p_j ← p_j / Z for every j
  9. 8O_i ← Σ_j p_j V_j
  10. 9return O

Line L3 is one row of QK⊤Q K^\top, scaled. Line L4 adds the bias BB. Lines L5 to L7 are the softmax: every exponent at line L6 is at most 0, so no exponential overflows, and the largest one is exactly 1, so Z≥1Z \ge 1. Line L8 multiplies the weight row by VV. In practice the loops are matrix products: S=QK⊤/dkS = Q K^\top / \sqrt{d_k}, a row softmax, and PVP V.

Example

Take dk=4d_k = 4, so dk=2\sqrt{d_k} = 2, three queries, three keys and values of size 2:

Q=(110000111010),K=(220011000011),V=(100111).Q = \begin{pmatrix} 1&1&0&0 \\ 0&0&1&1 \\ 1&0&1&0 \end{pmatrix}, \quad K = \begin{pmatrix} 2&2&0&0 \\ 1&1&0&0 \\ 0&0&1&1 \end{pmatrix}, \quad V = \begin{pmatrix} 1&0 \\ 0&1 \\ 1&1 \end{pmatrix}.

The state after each line, with no mask:

query L3 scores ss L5 μ\mu L6 pp before division ZZ L7 weights L8 output
1 (2, 1, 0) 2 (1, 0.367879, 0.135335) 1.503215 (0.66524, 0.24473, 0.09003) (0.75527, 0.33476)
2 (0, 0, 1) 1 (0.367879, 0.367879, 1) 1.735759 (0.21194, 0.21194, 0.57612) (0.78806, 0.78806)
3 (1, 0.5, 0.5) 1 (1, 0.606531, 0.606531) 2.213061 (0.45186, 0.27407, 0.27407) (0.72593, 0.54814)

Query 1 matches key 1 best, so its output is close to V1=(1,0)V_1 = (1, 0). With the causal mask, line L4 sets s2=s3=−∞s_2 = s_3 = -\infty for query 1 and s3=−∞s_3 = -\infty for query 2. Query 1 then has weights (1, 0, 0) and output (1, 0). Query 2 has weights (0.5, 0.5, 0) and output (0.5, 0.5). Query 3 sees all keys, so its row does not change.

Correctness

Line L6 subtracts the same μ\mu from every score of the row, and esj−μ/∑j′esj′−μ=esj/∑j′esj′e^{s_j - \mu} / \sum_{j'} e^{s_{j'} - \mu} = e^{s_j} / \sum_{j'} e^{s_{j'}}, so lines L5 to L7 give the softmax of the masked row exactly. A masked key gets e−∞=0e^{-\infty} = 0, so it has no effect on the output. The weights are non-negative and sum to 1, so each output row is a convex combination of the rows of VV that the query sees. The full proof also proves the variance lemma behind the factor 1/dk1/\sqrt{d_k}, and the two symmetry facts below.

Proof: Scaled dot-product attention returns the masked row softmax times V, its output rows are convex combinations of the visible values, it is permutation equivariant, and unit-variance inputs give scores of variance d_k before scalingfull

We use the notation of the page. QQ is n×dkn \times d_k, KK is m×dkm \times d_k, VV is m×dvm \times d_v and MM is an n×mn \times m mask. Write Ji={j:Mij}J_i = \{ j : M_{ij} \} for the keys that query ii sees, and assume Ji≠∅J_i \ne \emptyset for every ii. The target is

Oi=∑j∈JiπijVj,πij=exp⁡(aij)∑j′∈Jiexp⁡(aij′),aij=Qi⋅Kjdk,O_i = \sum_{j \in J_i} \pi_{ij} V_j, \qquad \pi_{ij} = \frac{\exp(a_{ij})}{\sum_{j' \in J_i} \exp(a_{ij'})}, \qquad a_{ij} = \frac{Q_i \cdot K_j}{\sqrt{d_k}},

with πij=0\pi_{ij} = 0 for j∉Jij \notin J_i. We work in the real RAM with e−∞=0e^{-\infty} = 0.

Lemma 1 (the scores). After the loop of lines L2 to L4 for query ii, sj=aijs_j = a_{ij} for j∈Jij \in J_i and sj=−∞s_j = -\infty for j∉Jij \notin J_i.

Proof. Line L3 sets sj=aijs_j = a_{ij} for every jj, and line L4 replaces it by −∞-\infty exactly when MijM_{ij} is false. □\square

Lemma 2 (the softmax). After line L7, pj=πijp_j = \pi_{ij} for every jj.

Proof. Since JiJ_i is not empty, Lemma 1 gives μ=max⁡j∈Jiaij\mu = \max_{j \in J_i} a_{ij}, a finite number. Line L6 sets pj=eaij−μp_j = e^{a_{ij} - \mu} for j∈Jij \in J_i and pj=e−∞=0p_j = e^{-\infty} = 0 otherwise. Every aij−μ≤0a_{ij} - \mu \le 0, and it equals 0 for some jj, so 1≤Z≤∣Ji∣1 \le Z \le |J_i|; in particular Z>0Z > 0 and the division at line L7 is defined. For j∈Jij \in J_i,

pjZ=eaije−μe−μ∑j′∈Jieaij′=πij,\frac{p_j}{Z} = \frac{e^{a_{ij}} e^{-\mu}}{e^{-\mu} \sum_{j' \in J_i} e^{a_{ij'}}} = \pi_{ij},

and for j∉Jij \notin J_i the value is 0=πij0 = \pi_{ij}. □\square

Theorem 3 (correctness). ATTENTION returns OO.

Proof. The iterations of line L1 do not share state, so it suffices to look at one ii. By Lemma 2, line L8 sets Oi=∑jπijVj=∑j∈JiπijVjO_i = \sum_j \pi_{ij} V_j = \sum_{j \in J_i} \pi_{ij} V_j, the target row. Line L9 returns all nn rows. The loops are finite, so the algorithm stops. □\square

Corollary 4 (convex output). Each OiO_i is a convex combination of {Vj:j∈Ji}\{ V_j : j \in J_i \}, so each coordinate OicO_{ic} lies between the smallest and largest VjcV_{jc} over j∈Jij \in J_i.

Proof. By Lemma 2 the weights πij\pi_{ij} are non-negative, zero outside JiJ_i, and ∑jπij=∑jpj/Z=1\sum_j \pi_{ij} = \sum_j p_j / Z = 1. □\square

Theorem 5 (permutation equivariance). Take no mask. Let σ\sigma be a permutation of {1,…,n}\{1, \ldots, n\} and τ\tau one of {1,…,m}\{1, \ldots, m\}, and let Qi′=Qσ(i)Q'_i = Q_{\sigma(i)}, Kj′=Kτ(j)K'_j = K_{\tau(j)} and Vj′=Vτ(j)V'_j = V_{\tau(j)}. Then the output O′O' on (Q′,K′,V′)(Q', K', V') satisfies Oi′=Oσ(i)O'_i = O_{\sigma(i)}.

Proof. The score of query ii and key jj on the new input is aij′=Qσ(i)⋅Kτ(j)/dk=aσ(i)τ(j)a'_{ij} = Q_{\sigma(i)} \cdot K_{\tau(j)} / \sqrt{d_k} = a_{\sigma(i) \tau(j)}. The denominator ∑jeaij′=∑jeaσ(i)τ(j)\sum_{j} e^{a'_{ij}} = \sum_j e^{a_{\sigma(i) \tau(j)}} is a sum over all keys in another order, so it equals the denominator of row σ(i)\sigma(i). Hence πij′=πσ(i)τ(j)\pi'_{ij} = \pi_{\sigma(i) \tau(j)} and

Oi′=∑jπσ(i)τ(j)Vτ(j)=∑j′πσ(i)j′Vj′=Oσ(i),O'_i = \sum_j \pi_{\sigma(i) \tau(j)} V_{\tau(j)} = \sum_{j'} \pi_{\sigma(i) j'} V_{j'} = O_{\sigma(i)},

by the change of index j′=τ(j)j' = \tau(j). □\square

With a causal mask Theorem 5 does not hold for general σ\sigma, because the mask is tied to the positions. Instead, by Lemma 1 the row of query ii depends only on KjK_j and VjV_j with j≤i+(m−n)j \le i + (m - n), so changing later keys or values does not change it.

Lemma 6 (the variance of a dot product). Let q1,…,qd,k1,…,kdq_1, \ldots, q_{d}, k_1, \ldots, k_{d} be independent random variables with mean 0 and variance 1. Then q⋅kq \cdot k has mean 0 and variance dd, and q⋅k/dq \cdot k / \sqrt{d} has variance 1.

Proof. For each tt, qtq_t and ktk_t are independent, so E[qtkt]=E[qt] E[kt]=0\mathbb{E}[q_t k_t] = \mathbb{E}[q_t]\, \mathbb{E}[k_t] = 0 and E[(qtkt)2]=E[qt2] E[kt2]=1\mathbb{E}[(q_t k_t)^2] = \mathbb{E}[q_t^2]\, \mathbb{E}[k_t^2] = 1. So Var⁡(qtkt)=1\operatorname{Var}(q_t k_t) = 1. For t≠ut \ne u the products qtktq_t k_t and qukuq_u k_u are functions of disjoint sets of independent variables, so they are independent and their covariance is 0. The variance of the sum is the sum of the variances, dd, and its mean is 0. Dividing by d\sqrt{d} divides the variance by dd. ■\blacksquare

Lemma 6 is about the inputs at the start of training. It does not say that the scores of a trained network have variance 1; the factor 1/dk1/\sqrt{d_k} is a choice made so that the softmax starts in a region where its gradient is not small.

Complexity

Line L3 runs nmn m times at Θ(dk)\Theta(d_k) each, and line L8 runs nn times at Θ(mdv)\Theta(m d_v) each. Lines L4 to L7 are Θ(m)\Theta(m) per query. The total is Θ(nm(dk+dv))\Theta(n m (d_k + d_v)) arithmetic operations in the real RAM, with the same bound in floating point. For self-attention with m=nm = n and dk=dv=dd_k = d_v = d this is Θ(n2d)\Theta(n^2 d). The algorithm keeps one row of mm scores at a time, so the extra memory is Θ(m)\Theta(m) beside the n×dvn \times d_v output; the front matter counts only this row, not the score matrix. A matrix library usually forms the full n×mn \times m score matrix, which is Θ(nm)\Theta(n m) memory; for long sequences this matrix, not the arithmetic, is often the limit. FlashAttention computes the same output without storing it.

Properties

  • Permutation equivariance (theorem). Permuting the queries permutes the output rows in the same way. Permuting the key-value pairs together does not change the output. So without a mask, attention does not see word order; a positional encoding adds it.
  • Convex output (theorem). Each output row lies in the convex hull of the visible value rows.
  • Shift invariance (theorem). Adding a constant to all scores of a row does not change the weights. Adding a vector uu to every key adds q⋅u/dkq \cdot u / \sqrt{d_k} to the whole row, so it has no effect.
  • No parameters. The learned weights live in the maps that produce QQ, KK and VV.
  • Differentiable. The output is a smooth function of QQ, KK and VV, so the network is trained by backpropagation.

Variants and improvements

  • Additive attention (Bahdanau, Cho and Bengio) scores with a small network, v⊤tanh⁡(Wq+Uk)v^\top \tanh(W q + U k). Vaswani and colleagues report that it does better than unscaled dot products for large dkd_k, which is what the scaling fixes.
  • Multiplicative attention (Luong and colleagues) uses q⊤kq^\top k or q⊤Wkq^\top W k without the scaling.
  • Multi-head attention runs hh attentions on learned projections of size d/hd/h and concatenates them.
  • Masks and biases. The causal mask, a padding mask, and learned or fixed biases such as ALiBi all enter as the matrix BB.
  • FlashAttention gives the same output with an online softmax over blocks of keys and fewer memory transfers.
  • Key-value cache. During generation one new query attends to all stored keys and values, n=1n = 1, at Θ(m(dk+dv))\Theta(m (d_k + d_v)) per step.

When to use it

Use it when every position may need information from any other position at distance 1 in the network, and nn is small enough that n2n^2 scores fit the time budget. A recurrent layer costs Θ(nd2)\Theta(n d^2) but needs nn sequential steps; attention needs one parallel step. For very long inputs, consider a sparse or local mask, a selective state space model with cost linear in nn, or at least the memory-saving schedule of FlashAttention.

Pitfalls

  • Missing scale. Writing sj←Qi⋅Kjs_j \leftarrow Q_i \cdot K_j at line L3 makes the softmax nearly one-hot for large dkd_k, and its gradients nearly zero. Divide by dk\sqrt{d_k}, not by dkd_k and not by the model size dd.
  • Unstable softmax. Taking exp⁡(sj)\exp(s_j) at line L6 without subtracting μ\mu overflows for scores above about 709 in double precision, and much earlier in half precision. Subtract the row maximum first.
  • Mask by a large finite number. Using −109-10^9 instead of −∞-\infty at line L4 is fine in floating point only while real scores are much smaller; in half precision it overflows. With −∞-\infty, a row where every key is masked gives μ=−∞\mu = -\infty and exp⁡(−∞−(−∞))\exp(-\infty - (-\infty)) is undefined, so check that each query sees a key, as line L5 assumes.
  • Mask after the softmax. Setting masked weights to 0 after line L7 leaves rows that do not sum to 1. Apply the mask to the scores, before line L5.
  • Wrong axis. The softmax at lines L6 and L7 is over the keys jj for a fixed query ii, that is over each row of QK⊤Q K^\top, not over each column.

Implementations

The code takes the matrices QQ, KK and VV 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.

nlslog.pyI0RawGitHub
# 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
scaled_dot_product_attention.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/scaled-dot-product-attention/. The authors are listed in prov/YMRYDZ.jsonl.

"""Scaled dot-product attention, softmax(Q K^T / sqrt(d_k)) V, one query row at a time.

Shapes, with named sizes:
    Q is n x d_k (one row per query),
    K is m x d_k (one row per key),
    V is m x d_v (one row per value, the value of key j is row j).

A mask says which keys each query may see. mask[i][j] is True when query i
may see key j. With causal=True, query i sees key j when j <= i + (m - n),
so the last n keys belong to the n queries (m = n is the usual case; m > n
is the case of a key-value cache). A masked score is -inf and gets weight 0.

Precondition: n >= 1, m >= 1, d_k >= 1, d_v >= 1, all rows of a matrix have
the same length, and every query sees at least one key.

Cost: Theta(n m (d_k + d_v)) arithmetic operations and Theta(m) extra memory
for one row of scores at a time, plus the n x d_v output. The full n x m
weight matrix is stored only by attention_weights.

The code takes Q, K and V as given. It does not train a network.
"""

import math
from typing import List, Optional, Sequence, Tuple

Matrix = List[List[float]]
NEG_INF = float("-inf")


def _shape(name: str, a: Sequence[Sequence[float]]) -> Tuple[int, int]:
    if len(a) == 0 or len(a[0]) == 0:
        raise ValueError(f"{name} must have at least one row and one column")
    cols = len(a[0])
    for row in a:
        if len(row) != cols:
            raise ValueError(f"the rows of {name} must have the same length")
    return len(a), cols


def _check(
    Q: Sequence[Sequence[float]],
    K: Sequence[Sequence[float]],
    V: Sequence[Sequence[float]],
    mask: Optional[Sequence[Sequence[bool]]],
    causal: bool,
) -> Tuple[int, int, int, int]:
    n, dq = _shape("Q", Q)
    m, dk = _shape("K", K)
    mv, dv = _shape("V", V)
    if dq != dk:
        raise ValueError("Q and K must have the same number of columns")
    if mv != m:
        raise ValueError("K and V must have the same number of rows")
    if mask is not None:
        if len(mask) != n or any(len(r) != m for r in mask):
            raise ValueError("the mask must be n x m")
    if causal and m < n:
        raise ValueError("a causal mask needs at least as many keys as queries")
    return n, m, dk, dv


def _run(
    Q: Sequence[Sequence[float]],
    K: Sequence[Sequence[float]],
    V: Sequence[Sequence[float]],
    mask: Optional[Sequence[Sequence[bool]]],
    causal: bool,
    keep_weights: bool,
) -> Tuple[Matrix, Matrix]:
    n, m, dk, dv = _check(Q, K, V, mask, causal)
    scale = 1.0 / math.sqrt(dk)
    shift = m - n
    out: Matrix = []
    weights: Matrix = []
    for i in range(n):  # @line L1
        s = []
        for j in range(m):  # @line L2
            x = math.fsum(Q[i][t] * K[j][t] for t in range(dk)) * scale  # @line L3
            if (mask is not None and not mask[i][j]) or (causal and j > i + shift):
                x = NEG_INF  # @line L4
            s.append(x)
        mu = max(s)  # @line L5
        if mu == NEG_INF:
            raise ValueError(f"query {i} sees no key")
        p = [math.exp(x - mu) for x in s]  # @line L6
        z = math.fsum(p)  # @line L6
        p = [e / z for e in p]  # @line L7
        out.append([math.fsum(p[j] * V[j][c] for j in range(m)) for c in range(dv)])  # @line L8
        if keep_weights:
            weights.append(p)
    return out, weights  # @line L9


def attention(
    Q: Sequence[Sequence[float]],
    K: Sequence[Sequence[float]],
    V: Sequence[Sequence[float]],
    mask: Optional[Sequence[Sequence[bool]]] = None,
    causal: bool = False,
) -> Matrix:
    """Return the n x d_v matrix softmax(Q K^T / sqrt(d_k)) V, with masked scores set to -inf."""
    return _run(Q, K, V, mask, causal, False)[0]


def attention_weights(
    Q: Sequence[Sequence[float]],
    K: Sequence[Sequence[float]],
    V: Sequence[Sequence[float]],
    mask: Optional[Sequence[Sequence[bool]]] = None,
    causal: bool = False,
) -> Tuple[Matrix, Matrix]:
    """Return (O, P): the output and the n x m weight matrix P. Each row of P sums to 1."""
    return _run(Q, K, V, mask, causal, True)
test_scaled_dot_product_attention.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/scaled-dot-product-attention/. The authors are listed in prov/YMRYDZ.jsonl.

import math
import random

import pytest

from nlslog import softmax
from scaled_dot_product_attention import attention, attention_weights

Q_EX = [[1, 1, 0, 0], [0, 0, 1, 1], [1, 0, 1, 0]]
K_EX = [[2, 2, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1]]
V_EX = [[1, 0], [0, 1], [1, 1]]


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(Q, K, V, visible):
    """Scores by the definition, weights from the shared softmax helper."""
    dk = len(K[0])
    out = []
    for i, q in enumerate(Q):
        idx = [j for j in range(len(K)) if visible(i, j)]
        scores = [sum(a * b for a, b in zip(q, K[j])) / math.sqrt(dk) for j in idx]
        p = softmax(scores)
        out.append([sum(p[t] * V[j][c] for t, j in enumerate(idx)) for c in range(len(V[0]))])
    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 test_worked_example():
    O, P = attention_weights(Q_EX, K_EX, V_EX)
    assert [round(x, 5) for x in P[0]] == [0.66524, 0.24473, 0.09003]
    assert [round(x, 5) for x in O[0]] == [0.75527, 0.33476]
    assert [round(x, 5) for x in O[1]] == [0.78806, 0.78806]
    assert [round(x, 5) for x in O[2]] == [0.72593, 0.54814]


def test_worked_example_causal():
    O, P = attention_weights(Q_EX, K_EX, V_EX, causal=True)
    assert P[0] == [1.0, 0.0, 0.0]
    assert P[1] == [0.5, 0.5, 0.0]
    assert [round(x, 5) for x in O[2]] == [0.72593, 0.54814]


@pytest.mark.parametrize("seed", range(20))
def test_against_oracle(seed):
    rng = random.Random(seed)
    n, m, dk, dv = rng.randint(1, 6), rng.randint(1, 6), rng.randint(1, 5), rng.randint(1, 4)
    Q, K, V = rand_matrix(rng, n, dk), rand_matrix(rng, m, dk), rand_matrix(rng, m, dv)
    assert close(attention(Q, K, V), oracle(Q, K, V, lambda i, j: True))
    mask = [[rng.random() < 0.6 for _ in range(m)] for _ in range(n)]
    for row in mask:
        row[rng.randrange(m)] = True
    assert close(attention(Q, K, V, mask=mask), oracle(Q, K, V, lambda i, j: mask[i][j]))
    if m >= n:
        shift = m - n
        assert close(attention(Q, K, V, causal=True), oracle(Q, K, V, lambda i, j: j <= i + shift))


@pytest.mark.parametrize("seed", range(10))
def test_weights_are_a_distribution_and_output_is_convex(seed):
    rng = random.Random(100 + seed)
    n, m = rng.randint(1, 5), rng.randint(1, 7)
    Q, K, V = rand_matrix(rng, n, 3, 2.0), rand_matrix(rng, m, 3, 2.0), rand_matrix(rng, m, 2)
    O, P = attention_weights(Q, K, V)
    for i in range(n):
        assert all(p >= 0 for p in P[i])
        assert abs(math.fsum(P[i]) - 1) < 1e-12
        for c in range(2):
            col = [V[j][c] for j in range(m)]
            assert min(col) - 1e-12 <= O[i][c] <= max(col) + 1e-12


@pytest.mark.parametrize("seed", range(10))
def test_permutation_equivariance(seed):
    rng = random.Random(200 + seed)
    n, m = rng.randint(2, 5), rng.randint(2, 5)
    Q, K, V = rand_matrix(rng, n, 3), rand_matrix(rng, m, 3), rand_matrix(rng, m, 2)
    O = attention(Q, K, V)
    pq = list(range(n))
    rng.shuffle(pq)
    assert close(attention([Q[i] for i in pq], K, V), [O[i] for i in pq])
    pk = list(range(m))
    rng.shuffle(pk)
    assert close(attention(Q, [K[j] for j in pk], [V[j] for j in pk]), O)


@pytest.mark.parametrize("seed", range(10))
def test_causal_output_ignores_later_keys(seed):
    rng = random.Random(300 + seed)
    n = rng.randint(2, 6)
    Q, K, V = rand_matrix(rng, n, 3), rand_matrix(rng, n, 3), rand_matrix(rng, n, 2)
    O = attention(Q, K, V, causal=True)
    t = rng.randrange(n)
    K2 = [row[:] if j <= t else [rng.gauss(0, 5) for _ in row] for j, row in enumerate(K)]
    V2 = [row[:] if j <= t else [rng.gauss(0, 5) for _ in row] for j, row in enumerate(V)]
    O2 = attention(Q, K2, V2, causal=True)
    assert close(O2[: t + 1], O[: t + 1], 0.0)


def test_large_scores_do_not_overflow():
    Q = [[1000.0, 0.0]]
    K = [[1000.0, 0.0], [999.0, 0.0], [-1000.0, 0.0]]
    V = [[1.0], [2.0], [3.0]]
    O, P = attention_weights(Q, K, V)
    assert all(math.isfinite(p) for p in P[0])
    assert P[0][0] == pytest.approx(1.0)
    assert O[0][0] == pytest.approx(1.0)


def test_shift_invariance():
    rng = random.Random(7)
    Q, K, V = rand_matrix(rng, 1, 4), rand_matrix(rng, 5, 4), rand_matrix(rng, 5, 3)
    # Adding the same vector to every key adds q . u / sqrt(d) to every score of the row.
    u = [rng.gauss(0, 3) for _ in range(4)]
    K2 = [[a + b for a, b in zip(row, u)] for row in K]
    assert close(attention(Q, K2, V), attention(Q, K, V), 1e-9)


def test_dot_product_variance_is_d():
    rng = random.Random(11)
    d, trials = 64, 3000
    sq = 0.0
    for _ in range(trials):
        q = [rng.gauss(0, 1) for _ in range(d)]
        k = [rng.gauss(0, 1) for _ in range(d)]
        sq += sum(a * b for a, b in zip(q, k)) ** 2
    assert abs(sq / trials / d - 1) < 0.1


def test_errors():
    with pytest.raises(ValueError):
        attention([[1.0]], [[1.0], [2.0]], [[1.0]])
    with pytest.raises(ValueError):
        attention([[1.0, 2.0]], [[1.0]], [[1.0]])
    with pytest.raises(ValueError):
        attention([[1.0]], [[1.0]], [[1.0]], mask=[[False]])
    with pytest.raises(ValueError):
        attention([[1.0], [2.0]], [[1.0]], [[1.0]], causal=True)
    with pytest.raises(ValueError):
        attention([], [[1.0]], [[1.0]])

History

Bahdanau, Cho and Bengio (2015) introduced attention for neural machine translation: the decoder scored every encoder state with a small network and read a weighted sum. Luong, Pham and Manning (2015) compared simpler scores, among them the plain dot product. Vaswani and colleagues (2017) divided the dot product by dk\sqrt{d_k}, named the three inputs queries, keys and values, and built the transformer from attention alone, with no recurrence.

References

  1. Vaswani et al. 2017, Section 3.2.1 (the definition, equation 1, and the footnote on the variance of q . k), Section 3.2.3 (the mask that sets illegal scores to minus infinity), Section 4 and Table 1 (cost per layer)
  2. Luong, Pham and Manning 2015, the dot score among the score functions of global attention
  3. Simon J. D. Prince, Understanding Deep Learning, MIT Press 2023, Chapter 12 (Transformers), Section 12.2 (dot-product self-attention)

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