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
- 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
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 and turned into weights by a softmax, and the output is the weighted sum of the value vectors. In matrix form the output is , 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 tokens attending to each other it costs 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 of shape , the keys of shape and the values of shape , with row of belonging to key . An optional mask of shape says which keys each query may see. The output is the matrix
where the softmax of a row is and . Every query must see at least one key. In self-attention , and are three linear maps of the same token vectors, so . The causal mask lets query see key only when ; this is what causal language modeling needs.
Why divide by : Vaswani and colleagues note in a footnote that if the components of and are independent with mean 0 and variance 1, then has mean 0 and variance . Dividing by 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.
ATTENTION(Q, K, V, M) ▷ Q: n × d_k, K: m × d_k, V: m × d_v- 1
for i ← 1 to n do - 2
for j ← 1 to m do - 3
s_j ← (Q_i · K_j) / √d_k - 4
if not M_ij then s_j ← -∞ - 5
μ ← max_j s_j ▷ finite, since query i sees a key - 6
p_j ← exp(s_j - μ) for every j; Z ← Σ_j p_j - 7
p_j ← p_j / Z for every j - 8
O_i ← Σ_j p_j V_j - 9
return O
Line L3 is one row of , scaled. Line L4 adds the bias . 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 . Line L8 multiplies the weight row by . In practice the loops are matrix products: , a row softmax, and .
Example
Take , so , three queries, three keys and values of size 2:
The state after each line, with no mask:
| query | L3 scores | L5 | L6 before division | 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 . With the causal mask, line L4 sets for query 1 and 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 from every score of the row, and , so lines L5 to L7 give the softmax of the masked row exactly. A masked key gets , 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 that the query sees. The full proof also proves the variance lemma behind the factor , 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. is , is , is and is an mask. Write for the keys that query sees, and assume for every . The target is
with for . We work in the real RAM with .
Lemma 1 (the scores). After the loop of lines L2 to L4 for query , for and for .
Proof. Line L3 sets for every , and line L4 replaces it by exactly when is false.
Lemma 2 (the softmax). After line L7, for every .
Proof. Since is not empty, Lemma 1 gives , a finite number. Line L6 sets for and otherwise. Every , and it equals 0 for some , so ; in particular and the division at line L7 is defined. For ,
and for the value is .
Theorem 3 (correctness). ATTENTION returns .
Proof. The iterations of line L1 do not share state, so it suffices to look at one . By Lemma 2, line L8 sets , the target row. Line L9 returns all rows. The loops are finite, so the algorithm stops.
Corollary 4 (convex output). Each is a convex combination of , so each coordinate lies between the smallest and largest over .
Proof. By Lemma 2 the weights are non-negative, zero outside , and .
Theorem 5 (permutation equivariance). Take no mask. Let be a permutation of and one of , and let , and . Then the output on satisfies .
Proof. The score of query and key on the new input is . The denominator is a sum over all keys in another order, so it equals the denominator of row . Hence and
by the change of index .
With a causal mask Theorem 5 does not hold for general , because the mask is tied to the positions. Instead, by Lemma 1 the row of query depends only on and with , so changing later keys or values does not change it.
Lemma 6 (the variance of a dot product). Let be independent random variables with mean 0 and variance 1. Then has mean 0 and variance , and has variance 1.
Proof. For each , and are independent, so and . So . For the products and 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, , and its mean is 0. Dividing by divides the variance by .
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 is a choice made so that the softmax starts in a region where its gradient is not small.
Complexity
Line L3 runs times at each, and line L8 runs times at each. Lines L4 to L7 are per query. The total is arithmetic operations in the real RAM, with the same bound in floating point. For self-attention with and this is . The algorithm keeps one row of scores at a time, so the extra memory is beside the output; the front matter counts only this row, not the score matrix. A matrix library usually forms the full score matrix, which is 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 to every key adds to the whole row, so it has no effect.
- No parameters. The learned weights live in the maps that produce , and .
- Differentiable. The output is a smooth function of , and , so the network is trained by backpropagation.
Variants and improvements
- Additive attention (Bahdanau, Cho and Bengio) scores with a small network, . Vaswani and colleagues report that it does better than unscaled dot products for large , which is what the scaling fixes.
- Multiplicative attention (Luong and colleagues) uses or without the scaling.
- Multi-head attention runs attentions on learned projections of size 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 .
- 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, , at 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 is small enough that scores fit the time budget. A recurrent layer costs but needs 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 , or at least the memory-saving schedule of FlashAttention.
Pitfalls
- Missing scale. Writing at line L3 makes the softmax nearly one-hot for large , and its gradients nearly zero. Divide by , not by and not by the model size .
- Unstable softmax. Taking at line L6 without subtracting 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 instead of at line L4 is fine in floating point only while real scores are much smaller; in half precision it overflows. With , a row where every key is masked gives and 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 for a fixed query , that is over each row of , not over each column.
Implementations
The code takes the matrices , and 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
# 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 , named the three inputs queries, keys and values, and built the transformer from attention alone, with no recurrence.
References
- 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)
- Luong, Pham and Manning 2015, the dot score among the score functions of global attention
- 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.
| 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 YMRYDZ Edit this page History Report an error Markdown