Algorithmcore
Multiplicative attention
Also called Luong attention, bilinear attention.
Score each encoder state by its dot product, or bilinear form, with the current decoder state, then take the softmax-weighted sum, over all states or a local window.
- Time
- Θ(S d + d²) worst
- Space
- Θ(S + d) extra
- Where
- D = the half width of the local window; S = the number of source states; d = the size of the states
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Minh Thang Luong, Hieu Pham, Christopher D. Manning, 2015
Multiplicative attention lets the decoder of a recurrent encoder-decoder model look at the source states at each output step. It scores each source state against the current decoder state by a product: the dot product or the bilinear form . A softmax turns the scores into weights, and the weighted sum of the source states is the context. Luong, Pham and Manning (2015) defined it with a global form over all source states and a local form over a window. It differs from scaled dot-product attention in two ways: it has no factor , and it compares the decoder state with the source states directly, with no separate query, key and value projections.
In plain words
A translation model keeps one vector for each source word. At each output step, the decoder has a vector for what it is about to write.
Multiplicative attention measures how well each source vector matches the decoder vector by multiplying them coordinate by coordinate and adding the results. The general form first passes the source vector through a learned matrix. A large product means a good match.
The scores become weights that are positive and sum to 1, and the decoder takes the weighted average of the source vectors. It mixes this average with its own state to choose the next word.
The local form looks only at a window of source words around a predicted position. This saves work on long sentences and makes the weights focus on one place.
The problem
The input is the decoder state at output step , the source states , a score function and the parameters it needs. The score is one of
Global attention uses all positions . Local attention uses the window , where for local-m (monotonic) and for local-p (predictive). The output is the weights , the context , and the attentional state , from which the model computes the output distribution .
The state is the top layer of the decoder after step , so the path is . Additive attention of Bahdanau et al. uses the previous state and feeds the context into the next recurrent step instead.
The algorithm
MULTIPLICATIVE-ATTENTION(h_t, h̄_1 .. h̄_S, score, local, D)- 1
if local is none then K ← {1, ..., S} - 2
else p ← t (local-m) or S · sigmoid(v_pᵀ tanh(W_p h_t)) (local-p); K ← {s : |s - p| ≤ D, 1 ≤ s ≤ S} - 3
for each s in K do - 4
e_s ← h_tᵀ h̄_s (dot), h_tᵀ W_a h̄_s (general) or v_aᵀ tanh(W_a [h_t; h̄_s]) (concat) - 5
a ← SOFTMAX(e_s over s in K) ▷ subtract the maximum before exp - 6
if local is p then a_s ← a_s · exp(-(s - p)² / (2 σ²)) with σ = D / 2 - 7
c ← Σ_{s in K} a_s h̄_s ▷ a_s = 0 outside K - 8
h̃ ← tanh(W_c [c; h_t]) - 9
return c, a, h̃
Lines L1 and L2 choose the positions. For local-p, is a real number in , so the window has up to positions and is cut at the ends of the sentence. Line L4 is the score. For the general score, an implementation computes once per source sentence and reuses it at every output step. Line L5 is a softmax over the window with the log-sum-exp trick. Line L6 multiplies the weights of local-p by a Gaussian centred at . As in the paper, the weights are not normalized again, so they sum to less than 1. Line L8 combines the context with the decoder state.
How it differs from the other attention pages. Scaled dot-product attention computes with , and the values produced by separate learned projections, and it runs many queries at once as one matrix product. The general score with gives exactly scaled dot-product attention for one query whose keys and values are the source states (a theorem). Without the scale, dot products of large vectors are large, and the softmax becomes very sharp. Additive attention puts a tanh between the decoder state and the source state, so its scores are bounded but cannot be computed as one matrix product. The concat score here is the additive score with in place of .
Example
Take the dot score, and three source states , , , the same states as on the additive attention page.
| 1 | 1 | 2.7183 | 0.6652 |
| 2 | 0 | 1 | 0.2447 |
| 3 | -1 | 0.3679 | 0.0900 |
The context is . The largest weight goes to , which points in the same direction as . With the additive score and , , the largest weight went to instead, because the tanh saturates.
With local-m at and , the window is , and all the weight goes to whatever the scores.
Correctness
The claim is that the procedure returns the weights, the context and the attentional state of the definition. For global attention and local-m the weights are non-negative and sum to 1, so is a convex combination of the states in the window. For local-p each weight is at most its softmax value, and the sum is at most 1. Subtracting the maximum at line L5 multiplies the numerator and the denominator by the same factor, so it does not change the softmax. The general score with is the dot score, and the concat score is the additive form . The gradients of a loss for the general score follow from the chain rule and the softmax Jacobian. These are theorems; the full proof is in the proofs file. That the weights look like a word alignment is a measurement on trained models.
Proof: Global and local multiplicative attention return the stated weights, and the gradients of the general score are as statedfull
Fix the decoder state and the source states with . The score is one of , and . The window is for global attention, and for local attention, with (local-m) or (local-p), where is the logistic function. Luong et al. (2015) define
with for , the context and the attentional state .
Theorem 1 (the output). If is not empty, lines L1 to L9 return , and of the definition. For global attention and local-m, and , so is a convex combination of the states in the window. For local-p, and , with equality only if the window is the single position . For local-p, .
Proof. Lines L1 and L2 build . Lines L3 and L4 compute for . Line L5 computes the softmax over with the maximum subtracted first, which multiplies the numerator and the denominator by the same positive factor, so it equals . Line L6 applies the Gaussian factor for local-p. Line L7 forms , with outside , and line L8 forms .
The softmax values are positive and sum to 1 over , which gives the claim for global attention and local-m. For local-p, the Gaussian factor is in and equals 1 only at , so and the sum is at most 1. It equals 1 only if every has , that is . The logistic function maps into , and in floating point into , so .
Theorem 2 (relations between the scores). (a) The dot score is the general score with . (b) Global attention with the general score and returns the output of scaled dot-product attention for the single query , with the keys and the values both equal to the source states. (c) The concat score equals , where is split by columns, which is the additive score of Bahdanau et al. with the current state in place of .
Proof. (a) . (b) , and the softmax and the weighted sum of the values are the same operations in both definitions. (c) by the rules of block matrix products.
Theorem 3 (the gradients of the general score). For global attention with the general score and , let , and , split into the first and the last entries. With , and ,
Proof. gives , and is linear in and in , which gives the first formula and the vector . The context gives the term for , and . The softmax Jacobian gives . Finally has the derivatives in , in and in . The term is the direct path from to .
The tests compare these gradients with central finite differences, and they check Theorem 2 (b) against a separate implementation of scaled dot-product attention.
Remark (local-p is differentiable almost everywhere). The window changes only when some crosses . Between these points is fixed and is a smooth function of , so of and . So gradient training works almost everywhere, and the sets of measure zero where the window changes do not matter in practice (a heuristic).
Remark (complexity). For global attention with the dot score, one step costs ; with the general score, precomputing once per sentence leaves per step. Local attention costs per step plus for and for the general product. Line L8 costs .
Complexity
In the real RAM model, one global step with the dot score costs for the scores and the context, and line L8 costs , so a step costs . The general score costs per step if is computed each time, and once per sentence plus per step if it is kept. The concat score with a hidden size costs per step. Local attention replaces by and adds for in local-p. The extra space is for the scores, the weights and the context. A target sentence of words costs times one step, so global attention makes score evaluations, and local attention makes .
Properties
- Weights are a distribution. For global attention and local-m (a theorem). For local-p the sum is at most 1.
- Unbounded scores. The dot and general scores grow with the size of the vectors, so the softmax can become very sharp. The additive score is bounded by .
- Same sizes. The dot score needs and of the same size. The general score allows different sizes through .
- Fast. The dot scores of all source states are one product of a matrix and a vector, and the scores of all output steps in a batch are a product of two matrices.
- Differentiable. All lines are smooth except the window edges of local-p, which change only on a set of measure zero.
- Current state. The score uses , so attention comes after the recurrent step, and the decoder needs input feeding to see the past contexts.
Variants and improvements
- Input feeding. Luong et al. feed into the decoder input at step , so the model knows its past attention decisions (Section 3.3). In Table 1 this added 1.3 BLEU to global attention (a measurement).
- Location-based score. The paper also tries , which ignores the source states and predicts the weights from the decoder state alone.
- Scaled dot product. The transformer divides the dot product by and uses separate projections for queries, keys and values, in multi-head attention.
- Additive score. Additive attention uses a network with one hidden layer, and its scores are bounded.
- Monotonic and sparse attention. Later work replaces the window of local attention by learned monotonic alignments or sparse weights; these are outside the scope of this page.
When to use it
Use the dot or general score in a recurrent encoder-decoder when speed matters and the states have a moderate size. Use the general score when the decoder and encoder states have different sizes. Use local attention for long inputs where the alignment is roughly monotonic. In a transformer, use scaled dot-product attention, which adds the scale and the projections.
Pitfalls
- No scale with large states. With large the dot products can be large, and the softmax puts nearly all weight on one position, which gives small gradients. Divide by or use the general score with a well-scaled .
- Renormalizing local-p. The paper does not normalize the weights again after the Gaussian. An implementation that does gives a different model.
- Positions from 0 or 1. The window depends on whether positions start at 0 or at 1. Choose one and keep it.
- An empty window. For local-m with the window is empty. Clip or fall back to global attention.
- Previous against current state. Mixing the conventions of Bahdanau et al. ( before the step) and Luong et al. ( after the step) gives a model that matches neither paper.
Implementations
The code takes the decoder state, the source states and the weight matrices as given and implements the scores, the global and local weights, the context, the attentional state and the gradients of the general score; it 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
# Part of https://algorithm.tamnd.com/multiplicative-attention/. The authors are listed in prov/E826M9.jsonl.
"""Global and local attention of Luong, Pham and Manning (2015), for one decoder step.
The decoder state h_t of the current step is compared with the source states
hs_1 .. hs_S by one of three scores:
dot h_t . hs_s
general h_t^T W_a hs_s
concat v_a^T tanh(W_a [h_t; hs_s])
The weights are the softmax of the scores, the context is c = sum_s a_s hs_s,
and the attentional state is h~ = tanh(W_c [c; h_t]).
Local attention looks only at the source positions s with |s - p| <= D, where
the positions are numbered 1 .. S. local-m uses p = t. local-p uses
p = S * sigmoid(v_p^T tanh(W_p h_t)) and multiplies each weight by the
Gaussian exp(-(s - p)^2 / (2 sigma^2)) with sigma = D / 2. As in the paper,
the weights are not normalized again after this product.
The states and the weights are given (outputs and parameters of a network);
this module does not train them. Vectors are lists of floats and a matrix is
a list of rows.
"""
import math
from typing import List, Optional, Sequence, Tuple
from nlslog import softmax
Vector = List[float]
Matrix = Sequence[Sequence[float]]
def matvec(a: Matrix, x: Sequence[float]) -> Vector:
"""Return the product of the matrix a and the vector x."""
return [math.fsum(r * y for r, y in zip(row, x)) for row in a]
def dot(x: Sequence[float], y: Sequence[float]) -> float:
"""Return the dot product of x and y."""
return math.fsum(a * b for a, b in zip(x, y))
def score(kind: str, ht: Sequence[float], hs: Sequence[float], Wa: Optional[Matrix] = None,
va: Optional[Sequence[float]] = None) -> float:
"""Return the score of the source state hs for the decoder state ht."""
if kind == "dot":
return dot(ht, hs)
if kind == "general":
return dot(ht, matvec(Wa, hs))
if kind == "concat":
return dot(va, [math.tanh(x) for x in matvec(Wa, list(ht) + list(hs))])
raise ValueError("kind must be 'dot', 'general' or 'concat'")
def sigmoid(x: float) -> float:
"""Return 1 / (1 + exp(-x)) without overflow."""
if x >= 0:
return 1.0 / (1.0 + math.exp(-x))
z = math.exp(x)
return z / (1.0 + z)
def aligned_position(ht: Sequence[float], S: int, Wp: Matrix, vp: Sequence[float]) -> float:
"""Return p = S * sigmoid(v_p^T tanh(W_p h_t)), a real number in [0, S]."""
return S * sigmoid(dot(vp, [math.tanh(x) for x in matvec(Wp, ht)]))
def attention(ht: Sequence[float], Hs: Sequence[Sequence[float]], kind: str = "dot",
Wa: Optional[Matrix] = None, va: Optional[Sequence[float]] = None,
local: Optional[str] = None, t: Optional[int] = None, D: int = 10,
Wp: Optional[Matrix] = None, vp: Optional[Sequence[float]] = None
) -> Tuple[Vector, Vector, Optional[float]]:
"""Return (context c, weights a over all S positions, aligned position p or None).
local is None (global attention), "m" (local-m, needs t) or "p" (local-p,
needs Wp and vp). Positions outside the window get the weight 0.
"""
S = len(Hs)
if S == 0:
raise ValueError("attention needs at least one source state")
p = None
if local is None: # @line L1
window = list(range(1, S + 1))
else:
if local == "m": # @line L2
p = float(t)
elif local == "p":
p = aligned_position(ht, S, Wp, vp)
else:
raise ValueError("local must be None, 'm' or 'p'")
window = [s for s in range(1, S + 1) if abs(s - p) <= D]
if not window:
raise ValueError("the window holds no source position")
e = []
for s in window: # @line L3
e.append(score(kind, ht, Hs[s - 1], Wa, va)) # @line L4
w = softmax(e) # @line L5
if local == "p": # @line L6
sigma = D / 2
w = [x * math.exp(-((s - p) ** 2) / (2 * sigma * sigma)) for x, s in zip(w, window)]
a = [0.0] * S
for x, s in zip(w, window):
a[s - 1] = x
c = [math.fsum(a[j] * Hs[j][i] for j in range(S)) for i in range(len(Hs[0]))] # @line L7
return c, a, p
def attentional_state(c: Sequence[float], ht: Sequence[float], Wc: Matrix) -> Vector:
"""Return h~ = tanh(W_c [c; h_t])."""
return [math.tanh(x) for x in matvec(Wc, list(c) + list(ht))] # @line L8
def step(ht, Hs, Wc, **kw) -> Tuple[Vector, Vector, Vector]:
"""Return (h~, c, a) for one decoder step."""
c, a, _ = attention(ht, Hs, **kw)
return attentional_state(c, ht, Wc), c, a # @line L9
def backward_general(g: Sequence[float], ht: Sequence[float], Hs: Sequence[Sequence[float]],
Wa: Matrix, Wc: Matrix):
"""Return the gradients (d h_t, d Hs, d W_a, d W_c) of L = g . h~ for global general attention."""
c, a, _ = attention(ht, Hs, "general", Wa)
x = list(c) + list(ht)
ht_tilde = attentional_state(c, ht, Wc)
dz = [gi * (1 - y * y) for gi, y in zip(g, ht_tilde)]
dWc = [[dzi * xj for xj in x] for dzi in dz]
dx = [math.fsum(Wc[i][j] * dz[i] for i in range(len(dz))) for j in range(len(x))]
dh = len(Hs[0])
dc, dht = dx[:dh], dx[dh:]
gamma = [dot(dc, hs) for hs in Hs]
mean = math.fsum(ai * gi for ai, gi in zip(a, gamma))
de = [ai * (gi - mean) for ai, gi in zip(a, gamma)]
dHs = [[a[s] * v for v in dc] for s in range(len(Hs))]
WtH = [matvec(Wa, hs) for hs in Hs] # W_a hs_s
WTh = [math.fsum(Wa[i][j] * ht[i] for i in range(len(ht))) for j in range(dh)] # W_a^T h_t
for s in range(len(Hs)):
for i in range(len(ht)):
dht[i] += de[s] * WtH[s][i]
for j in range(dh):
dHs[s][j] += de[s] * WTh[j]
dWa = [[math.fsum(de[s] * ht[i] * Hs[s][j] for s in range(len(Hs))) for j in range(dh)]
for i in range(len(ht))]
return dht, dHs, dWa, dWc
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_multiplicative_attention.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiplicative-attention/. The authors are listed in prov/E826M9.jsonl.
import math
import random
import pytest
from multiplicative_attention import aligned_position, attention, attentional_state, backward_general, step
def rand_mat(rng, rows, cols):
return [[rng.uniform(-1, 1) for _ in range(cols)] for _ in range(rows)]
def rand_vec(rng, n):
return [rng.uniform(-1, 1) for _ in range(n)]
def eye(n, scale=1.0):
return [[scale if i == j else 0.0 for j in range(n)] for i in range(n)]
def scaled_dot_product(q, K, V):
"""softmax(q K^T / sqrt(d)) V for one query, with plain exp."""
d = len(q)
e = [math.exp(sum(x * y for x, y in zip(q, k)) / math.sqrt(d)) for k in K]
z = sum(e)
return [sum(e[j] / z * V[j][i] for j in range(len(K))) for i in range(len(V[0]))]
def test_page_example():
ht, Hs = [1.0, 0.0], [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]]
c, a, _ = attention(ht, Hs, "dot")
assert [round(x, 4) for x in a] == [0.6652, 0.2447, 0.0900]
assert [round(x, 4) for x in c] == [0.5752, 0.2447]
def test_dot_general_and_scaled():
rng = random.Random(1508)
for _ in range(40):
d, S = rng.randint(1, 5), rng.randint(1, 6)
ht, Hs = rand_vec(rng, d), [rand_vec(rng, d) for _ in range(S)]
c1, a1, _ = attention(ht, Hs, "dot")
c2, a2, _ = attention(ht, Hs, "general", eye(d))
assert all(abs(x - y) < 1e-14 for x, y in zip(a1 + c1, a2 + c2))
# general with W_a = I / sqrt(d) is scaled dot-product attention with keys = values = Hs
c3, a3, _ = attention(ht, Hs, "general", eye(d, 1 / math.sqrt(d)))
want = scaled_dot_product(ht, Hs, Hs)
assert all(abs(x - y) < 1e-12 for x, y in zip(c3, want))
assert abs(sum(a1) - 1) < 1e-12 and min(a1) >= 0
def test_concat_is_additive_form():
rng = random.Random(7)
d, S, n = 3, 4, 5
ht, Hs = rand_vec(rng, d), [rand_vec(rng, d) for _ in range(S)]
Wa, va = rand_mat(rng, n, 2 * d), rand_vec(rng, n)
_, a, _ = attention(ht, Hs, "concat", Wa, va)
e = []
for hs in Hs:
z = [sum(Wa[r][i] * ht[i] for i in range(d)) + sum(Wa[r][d + i] * hs[i] for i in range(d))
for r in range(n)]
e.append(sum(va[r] * math.tanh(z[r]) for r in range(n)))
z = sum(math.exp(x) for x in e)
assert all(abs(x - math.exp(y) / z) < 1e-12 for x, y in zip(a, e))
def test_local_m_window():
rng = random.Random(11)
S, d = 30, 2
ht, Hs = rand_vec(rng, d), [rand_vec(rng, d) for _ in range(S)]
_, a, p = attention(ht, Hs, "dot", local="m", t=15, D=10)
assert p == 15.0
assert all(a[s - 1] == 0.0 for s in range(1, S + 1) if abs(s - 15) > 10)
assert sum(1 for x in a if x > 0) == 21
assert abs(sum(a) - 1) < 1e-12
# near the start the window is cut at position 1
_, a2, _ = attention(ht, Hs, "dot", local="m", t=2, D=10)
assert sum(1 for x in a2 if x > 0) == 12
# local-m with a window that covers everything is global attention
_, a3, _ = attention(ht, Hs, "dot", local="m", t=15, D=40)
_, a4, _ = attention(ht, Hs, "dot")
assert all(abs(x - y) < 1e-15 for x, y in zip(a3, a4))
def test_local_p():
rng = random.Random(25)
S, d = 20, 3
ht, Hs = rand_vec(rng, d), [rand_vec(rng, d) for _ in range(S)]
Wp, vp = rand_mat(rng, 4, d), rand_vec(rng, 4)
_, a, p = attention(ht, Hs, "dot", local="p", D=4, Wp=Wp, vp=vp)
assert 0 <= p <= S and p == aligned_position(ht, S, Wp, vp)
window = [s for s in range(1, S + 1) if abs(s - p) <= 4]
# the softmax over the window, times the Gaussian with sigma = D / 2, and not renormalized
e = [sum(x * y for x, y in zip(ht, Hs[s - 1])) for s in window]
z = sum(math.exp(x) for x in e)
for s, x in zip(window, e):
want = math.exp(x) / z * math.exp(-((s - p) ** 2) / 8)
assert abs(a[s - 1] - want) < 1e-14
assert sum(a) < 1
def test_errors():
with pytest.raises(ValueError):
attention([1.0], [], "dot")
with pytest.raises(ValueError):
attention([1.0], [[1.0]], "cosine")
with pytest.raises(ValueError):
attention([1.0], [[1.0], [2.0]], "dot", local="m", t=10, D=2)
def test_gradients_by_finite_differences():
rng = random.Random(2015)
eps = 1e-6
for _ in range(4):
d, S = 3, 4
ht, Hs = rand_vec(rng, d), [rand_vec(rng, d) for _ in range(S)]
Wa, Wc, g = rand_mat(rng, d, d), rand_mat(rng, d, 2 * d), rand_vec(rng, d)
def loss():
h, _, _ = step(ht, Hs, Wc, kind="general", Wa=Wa)
return sum(x * y for x, y in zip(g, h))
dht, dHs, dWa, dWc = backward_general(g, ht, Hs, Wa, Wc)
cells = [(ht, i, dht[i]) for i in range(d)]
cells += [(Hs[s], i, dHs[s][i]) for s in range(S) for i in range(d)]
cells += [(Wa[i], j, dWa[i][j]) for i in range(d) for j in range(d)]
cells += [(Wc[i], j, dWc[i][j]) for i in range(d) for j in range(2 * d)]
for vec, i, grad in cells:
old = vec[i]
vec[i] = old + eps
up = loss()
vec[i] = old - eps
down = loss()
vec[i] = old
assert abs((up - down) / (2 * eps) - grad) < 1e-6
def test_attentional_state_shape():
h = attentional_state([0.0, 0.0], [0.0, 0.0], [[1.0] * 4, [0.5] * 4, [0.0] * 4])
assert h == [0.0, 0.0, 0.0]
History
Minh-Thang Luong, Hieu Pham and Christopher D. Manning published the paper at EMNLP 2015, a few months after additive attention. They simplified the attention path to , compared the dot, general and concat scores and a location-based score, and proposed local attention as a mix of the soft attention of Bahdanau et al. and the hard attention of image captioning. Their models had 4 LSTM layers with 1000 cells, a vocabulary of 50,000 words, and (Section 4.1). On WMT'14 English to German newstest2014, with tokenized BLEU, global attention with the location score raised the baseline with reversal and dropout from 14.0 to 16.8 BLEU, input feeding raised it to 18.1, and local-p attention with the general score reached 19.0, a gain of 5.0 over the non-attentional baseline. Unknown word replacement gave 20.9, and an ensemble of 8 models gave 23.0 (Table 1, measurements). The multiplicative form became the common choice in recurrent models, and the transformer of 2017 added the scale and the projections.
References
- Minh-Thang Luong, Hieu Pham and Christopher D. Manning, Effective Approaches to Attention-based Neural Machine Translation, EMNLP 2015, Section 3 (the attentional state h~ = tanh(W_c [c; h_t])), Section 3.1 (global attention and the dot, general and concat scores), Section 3.2 (local-m and local-p, sigma = D/2), Section 3.3 (input feeding), Section 4.1 (D = 10) and Table 1 (WMT'14 English to German)
- Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio, Neural Machine Translation by Jointly Learning to Align and Translate, ICLR 2015, Section 3.1 and Appendix A.2.2 (the additive score with the previous decoder state)
- Vaswani et al. 2017, Section 3.2.1 (scaled dot-product attention and the factor 1/sqrt(d_k))
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 E826M9 Edit this page History Report an error Markdown