Algorithm Search⌘K

Algorithmcore

Additive attention

Also called Bahdanau attention.

At each decoder step score each encoder state by a small feedforward network of it and the decoder state, and take the softmax-weighted sum.

Time
Θ(J a d) worst
Space
Θ(J + a) extra
Where
J = the number of encoder states; a = the size of the attention layer; d = the size of the encoder and decoder states
Properties
deterministicexactofflineiterative
Origin
Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio, 2014

Additive attention lets the decoder of a recurrent encoder-decoder model look at all the encoder states at each output step, instead of one fixed vector. It scores each encoder state hjh_j against the previous decoder state ss by a small network with one hidden layer, ej=v⊤tanh⁡(Ws+Uhj)e_j = v^\top \tanh(W s + U h_j), turns the scores into weights by a softmax, and returns the weighted sum of the encoder states as the context. Bahdanau, Cho and Bengio (2015) introduced it in the RNNsearch model. It differs from scaled dot-product attention in its score: a learned network with a tanh, not a scaled dot product of a query and a key.

In plain words

A translation model reads the source sentence and keeps one vector for each source word. When it writes the next target word, it should look mostly at the source words that this target word translates.

Additive attention gives each source word a score. It takes the vector of the decoder (what has been written so far) and the vector of the source word, maps both into a common space, adds them, squashes the sum with tanh, and reads off one number with a learned vector.

The scores become weights that are positive and sum to 1. The decoder then gets the weighted average of the source vectors.

The weights act as a soft word alignment. They are learned together with the rest of the network, with no alignment data.

The problem

The input is a decoder state s∈Rdss \in \mathbb{R}^{d_s}, encoder states h1,…,hJ∈Rdhh_1, \ldots, h_J \in \mathbb{R}^{d_h}, and the parameters W∈Ra×dsW \in \mathbb{R}^{a \times d_s}, U∈Ra×dhU \in \mathbb{R}^{a \times d_h} and v∈Rav \in \mathbb{R}^{a}, where aa is the size of the attention layer. Some positions may be padding and are masked. The output is

ej=v⊤tanh⁡(Ws+Uhj),αj=exp⁡(ej)∑kexp⁡(ek),c=∑j=1Jαjhj,e_j = v^\top \tanh(W s + U h_j), \qquad \alpha_j = \frac{\exp(e_j)}{\sum_{k} \exp(e_k)}, \qquad c = \sum_{j=1}^{J} \alpha_j h_j,

with the sum over the positions that are not masked, and αj=0\alpha_j = 0 at a masked position. In RNNsearch, at output step ii the state is s=si−1s = s_{i-1}, the decoder state before the word yiy_i is emitted, and each hjh_j is the concatenation of the forward and the backward state of a bidirectional RNN (Section 3.2). The context cic_i then enters the next decoder state si=f(si−1,yi−1,ci)s_i = f(s_{i-1}, y_{i-1}, c_i) and the output distribution.

The algorithm

  1. ADDITIVE-ATTENTION(s, h_1 .. h_J, W, U, v)
  2. 1q ← W s
  3. 2for j ← 1 to J do
  4. 3k_j ← U h_j ▷ the same at every decoder step
  5. 4e_j ← vᵀ tanh(q + k_j)
  6. 5if position j is masked then e_j ← -∞
  7. 6α ← SOFTMAX(e_1, ..., e_J) ▷ subtract max_j e_j before exp
  8. 7c ← Σ_j α_j h_j
  9. 8return c, α

Line L1 is the query part, computed once per decoder step. Line L3 does not depend on the decoder, so an implementation computes all the keys kj=Uhjk_j = U h_j once per source sentence and reuses them at every output step. Line L4 is the network with one hidden layer of aa tanh units. Line L6 subtracts the largest score before the exponential, as in the log-sum-exp trick, so no exponential overflows. Line L7 is the context.

How it differs from the other attention pages. Scaled dot-product attention scores a query qq and a key kk by q⊤k/dkq^\top k / \sqrt{d_k}: a product of two vectors, scaled, with no hidden layer. Its scores for many queries are one matrix product QK⊤Q K^\top, which is fast on hardware, and it needs the factor 1/dk1/\sqrt{d_k} because a dot product grows with the size of the vectors. The additive score passes the sum q+kjq + k_j through tanh, so it is bounded by ∥v∥1\|v\|_1 whatever the size of the vectors, and it needs no scale. It cannot be written as one matrix product, because the tanh comes between the query and the key. Multiplicative attention of Luong et al. is the dot or bilinear score in recurrent models, and it uses the current decoder state hth_t instead of the previous one.

Example

Take a=2a = 2, ds=dh=2d_s = d_h = 2, W=U=IW = U = I, v=(1,1)v = (1, 1), the decoder state s=(1,0)s = (1, 0) and three encoder states h1=(1,0)h_1 = (1, 0), h2=(0,1)h_2 = (0, 1), h3=(−1,0)h_3 = (-1, 0). Then q=(1,0)q = (1, 0) and:

jj q+Uhjq + U h_j eje_j αj\alpha_j
1 (2, 0) tanh 2 = 0.9640 0.3194
2 (1, 1) 2 tanh 1 = 1.5232 0.5588
3 (0, 0) 0 0.1218

The context is c=0.3194 (1,0)+0.5588 (0,1)+0.1218 (−1,0)=(0.1976,0.5588)c = 0.3194\,(1, 0) + 0.5588\,(0, 1) + 0.1218\,(-1, 0) = (0.1976, 0.5588).

The largest weight goes to h2h_2, although s⊤h2=0s^\top h_2 = 0 is smaller than s⊤h1=1s^\top h_1 = 1. A dot-product score would rank h1h_1 first. Here the tanh saturates: the first coordinate of q+Uh1q + U h_1 is already 2, and doubling it adds little, while h2h_2 raises both coordinates.

Correctness

The claim is that the procedure returns the weights and the context of the definition, that the weights are non-negative and sum to 1, and that the masked positions get weight 0. Subtracting the maximum score at line L6 does not change the softmax, because it multiplies the numerator and the denominator by the same factor. So cc is a convex combination of the encoder states that are not masked. Each score satisfies ∣ej∣≤∥v∥1|e_j| \le \|v\|_1, so every unmasked weight is at least e−2∥v∥1/Je^{-2\|v\|_1}/J. The gradients of a loss g⊤cg^\top c with respect to ss, hjh_j, WW, UU and vv follow from the chain rule and tanh⁡′=1−tanh⁡2\tanh' = 1 - \tanh^2. These are theorems; the full proof is in the proofs file. That the weights look like a word alignment is an observation on trained models (a measurement), not a property of the formula.

Proof: Additive attention returns a convex combination of the encoder states, and its gradients are as statedfull

Fix the decoder state s∈Rdss \in \mathbb{R}^{d_s}, the encoder states h1,…,hJ∈Rdhh_1, \ldots, h_J \in \mathbb{R}^{d_h} with J≥1J \ge 1, the parameters W∈Ra×dsW \in \mathbb{R}^{a \times d_s}, U∈Ra×dhU \in \mathbb{R}^{a \times d_h} and v∈Rav \in \mathbb{R}^a, and a mask M⊆{1,…,J}M \subseteq \{1, \ldots, J\} of the kept positions, not empty. The definition of Bahdanau et al. (2015) is

ej=v⊤tanh⁡(Ws+Uhj),αj=exp⁡(ej)∑k∈Mexp⁡(ek) (j∈M),αj=0 (j∉M),c=∑jαjhj.e_j = v^\top \tanh(W s + U h_j), \qquad \alpha_j = \frac{\exp(e_j)}{\sum_{k \in M} \exp(e_k)} \ (j \in M), \qquad \alpha_j = 0 \ (j \notin M), \qquad c = \sum_j \alpha_j h_j.

Lemma 1 (the stable softmax). For any real mm, exp⁡(ej−m)/∑k∈Mexp⁡(ek−m)=αj\exp(e_j - m) / \sum_{k \in M} \exp(e_k - m) = \alpha_j for j∈Mj \in M. With m=max⁡k∈Mekm = \max_{k \in M} e_k, every exponent is at most 0 and the denominator is at least 1.

Proof. Multiply the numerator and the denominator by eme^{m}. With mm the maximum, each ej−m≤0e_j - m \le 0, and the term of a maximizing kk is e0=1e^0 = 1, so the sum of non-negative terms is at least 1. Positions outside MM have the score −∞-\infty, and exp⁡(−∞)=0\exp(-\infty) = 0, so they add nothing and get the weight 0. □\square

So line L6 computes α\alpha without overflow, and the division never divides by a number below 1.

Theorem 1 (the output). Lines L1 to L8 return cc and α\alpha of the definition, with αj≥0\alpha_j \ge 0, ∑jαj=1\sum_j \alpha_j = 1 and αj=0\alpha_j = 0 for j∉Mj \notin M. Hence cc lies in the convex hull of {hj:j∈M}\{h_j : j \in M\}. Moreover ∣ej∣≤∥v∥1|e_j| \le \|v\|_1 for every jj, so the weights satisfy αj≥e−2∥v∥1/∣M∣\alpha_j \ge e^{-2\|v\|_1} / |M| for j∈Mj \in M.

Proof. Line L1 computes q=Wsq = W s once, and lines L3 and L4 compute ej=v⊤tanh⁡(q+Uhj)e_j = v^\top \tanh(q + U h_j), which is the definition because Ws+Uhj=q+UhjW s + U h_j = q + U h_j. Line L5 sets the score of a masked position to −∞-\infty. By Lemma 1, line L6 gives the weights of the definition. They are non-negative and sum to 1 because the numerators are the terms of the denominator. Line L7 forms cc. A combination with non-negative weights that sum to 1 is a convex combination.

Each coordinate of tanh⁡\tanh is in (−1,1)(-1, 1), so ∣ej∣≤∑t∣vt∣=∥v∥1|e_j| \le \sum_t |v_t| = \|v\|_1. For j∈Mj \in M, exp⁡(ej)≥e−∥v∥1\exp(e_j) \ge e^{-\|v\|_1} and each term of the denominator is at most e∥v∥1e^{\|v\|_1}, which gives the bound on αj\alpha_j. □\square

The bound says that additive attention cannot put all of its weight on one position unless ∥v∥\|v\| is large: the score is bounded by the size of vv, not by the size of ss and hjh_j. A dot-product score has no such bound.

Theorem 2 (the gradients). Let L=g⊤cL = g^\top c for a fixed g∈Rdhg \in \mathbb{R}^{d_h}, and write zj=Ws+Uhjz_j = W s + U h_j, uj=tanh⁡(zj)u_j = \tanh(z_j) and γj=g⊤hj\gamma_j = g^\top h_j. Then, with γˉ=∑kαkγk\bar\gamma = \sum_k \alpha_k \gamma_k, δj=αj(γj−γˉ)\delta_j = \alpha_j (\gamma_j - \bar\gamma) and rj=δj (v⊙(1−uj⊙uj))r_j = \delta_j \, (v \odot (1 - u_j \odot u_j)),

∂L∂v=∑jδjuj,∂L∂W=(∑jrj)s⊤,∂L∂s=W⊤∑jrj,∂L∂U=∑jrjhj⊤,∂L∂hj=αjg+U⊤rj,\frac{\partial L}{\partial v} = \sum_j \delta_j u_j, \quad \frac{\partial L}{\partial W} = \Bigl(\sum_j r_j\Bigr) s^\top, \quad \frac{\partial L}{\partial s} = W^\top \sum_j r_j, \quad \frac{\partial L}{\partial U} = \sum_j r_j h_j^\top, \quad \frac{\partial L}{\partial h_j} = \alpha_j g + U^\top r_j,

where δj=0\delta_j = 0 and rj=0r_j = 0 for a masked jj.

Proof. By the chain rule. L=∑jαjγjL = \sum_j \alpha_j \gamma_j, so ∂L/∂αj=γj\partial L / \partial \alpha_j = \gamma_j, and hjh_j also enters directly with ∂L/∂hj=αjg\partial L / \partial h_j = \alpha_j g from this term. The softmax has ∂αk/∂ej=αk([k=j]−αj)\partial \alpha_k / \partial e_j = \alpha_k ([k = j] - \alpha_j) for j,k∈Mj, k \in M, so ∂L/∂ej=∑kγkαk([k=j]−αj)=αjγj−αjγˉ=δj\partial L / \partial e_j = \sum_k \gamma_k \alpha_k ([k = j] - \alpha_j) = \alpha_j \gamma_j - \alpha_j \bar\gamma = \delta_j. A masked score is the constant −∞-\infty and does not depend on the parameters, so it gives no term. From ej=v⊤uje_j = v^\top u_j: ∂ej/∂v=uj\partial e_j / \partial v = u_j and ∂ej/∂zj=v⊙(1−uj⊙uj)\partial e_j / \partial z_j = v \odot (1 - u_j \odot u_j), because tanh⁡′=1−tanh⁡2\tanh' = 1 - \tanh^2. So ∂L/∂zj=rj\partial L / \partial z_j = r_j. Finally zjz_j is linear: ∂zj/∂W\partial z_j / \partial W gives rjs⊤r_j s^\top, ∂zj/∂s\partial z_j / \partial s gives W⊤rjW^\top r_j, ∂zj/∂U\partial z_j / \partial U gives rjhj⊤r_j h_j^\top and ∂zj/∂hj\partial z_j / \partial h_j gives U⊤rjU^\top r_j. Summing over jj gives the formulas. □\square

The tests compare these gradients with central finite differences.

Remark (complexity). Line L1 costs O(ads)O(a d_s), line L3 costs O(adh)O(a d_h) per position, line L4 costs O(a)O(a) per position, and lines L6 and L7 cost O(J+Jdh)O(J + J d_h). One decoder step therefore costs O(ads+Jadh+Jdh)O(a d_s + J a d_h + J d_h). The keys UhjU h_j do not depend on the decoder step, so over II decoder steps they are computed once, and the total is O(Jadh+I(ads+Ja+Jdh))O(J a d_h + I (a d_s + J a + J d_h)).

Complexity

In the real RAM model with ds,dh≤dd_s, d_h \le d, line L1 costs Θ(ad)\Theta(a d), line L3 costs Θ(ad)\Theta(a d) per position, and lines L4 to L7 cost Θ(a+d)\Theta(a + d) per position. One decoder step from scratch costs Θ(Jad)\Theta(J a d). With the keys precomputed once, a step costs Θ(ad+Ja+Jd)\Theta(a d + J a + J d), and a target sentence of II words costs Θ(Jad+I(ad+Ja+Jd))\Theta(J a d + I (a d + J a + J d)). The extra space is Θ(J+a)\Theta(J + a) for the scores and the query, plus Θ(Ja)\Theta(J a) if the keys are kept. Over a whole sentence pair, attention costs Θ(IJ)\Theta(I J) score evaluations, which is the cost of letting every output step see every source word.

Properties

  • Weights are a distribution. Non-negative, summing to 1, with 0 at masked positions (a theorem).
  • Bounded scores. ∣ej∣≤∥v∥1|e_j| \le \|v\|_1 (a theorem). The weights can become sharp only if vv is large.
  • Different sizes. ss and hjh_j may have different sizes, because WW and UU map both into the same aa dimensions.
  • Differentiable. All steps are smooth, so the alignment is learned by backpropagation through time with the rest of the model.
  • Content based. The score uses only the vectors, not the positions. Position enters only through what the encoder writes into hjh_j.
  • Previous state. In RNNsearch the score uses si−1s_{i-1}, so the context is ready before the new state sis_i is computed.

Variants and improvements

  • Multiplicative scores. Luong et al. replace the network by s⊤hjs^\top h_j or s⊤Wahjs^\top W_a h_j and use the current decoder state.
  • Scaled dot product. The transformer uses q⊤k/dkq^\top k / \sqrt{d_k} in multi-head attention. Vaswani et al. (2017) state that dot-product attention is much faster and more space-efficient in practice, and that additive attention does better than dot-product attention without the scale for larger dkd_k (a measurement they cite from other work).
  • Location-aware attention. In speech recognition, Chorowski et al. (2015) add features of the previous weights to the score, so the attention moves forward along the input. Listen, attend and spell uses content-based attention of this family.
  • Copying. The pointer-generator network uses the attention weights as a distribution to copy source words.
  • Coverage. Later models add a sum of the past weights to the score, so the model does not attend to the same word again and again.

When to use it

Use additive attention in a recurrent encoder-decoder, especially when the decoder and encoder states have different sizes or when the states are large and unscaled dot products would make the softmax too sharp. In a transformer or any model that runs many queries at once, use scaled dot-product attention, which is one matrix product and much faster on hardware.

Pitfalls

  • Recomputing the keys. Computing UhjU h_j again at every decoder step multiplies the cost by dd for no gain. Compute the keys once.
  • Masking with a large negative number. A score of −109-10^9 in place of −∞-\infty can leave a tiny weight on padding, and in low precision it can overflow. Use −∞-\infty and handle a row with every position masked as an error.
  • No max shift. Without line L6's subtraction, a large ∥v∥\|v\| makes exp⁡(ej)\exp(e_j) overflow.
  • The wrong state. Using sis_i instead of si−1s_{i-1} creates a loop: sis_i needs the context, and the context needs sis_i. Luong et al. avoid this by computing the context after sis_i and adding a separate output layer.
  • Reading the weights as alignments. The weights are trained for translation, not for alignment. They often look like an alignment, but they can be spread out or shifted, so they are not a replacement for a word alignment model.

Implementations

The code takes the encoder states, the decoder state and the weight matrices as given and implements the scores, the weights, the context and their gradients; 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.

additive_attention.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/additive-attention/. The authors are listed in prov/3X7CGK.jsonl.

"""Additive attention of Bahdanau, Cho and Bengio (2015), for one decoder step.

The score of the encoder state h_j for the decoder state s is

    e_j = v^T tanh(W s + U h_j),

the weights are alpha = softmax(e), and the context is c = sum_j alpha_j h_j.
The vectors and the parameters are given: s, h_j, W, U and v are the outputs
and the weights of a trained network, and this module does not train them.

Vectors are lists of floats and a matrix is a list of rows. With W of shape
(a, d_s), U of shape (a, d_h) and v of length a, the step costs
O(J a (d_s + d_h)) time, or O(J a + a d_s) when the keys U h_j are computed
once per source sentence and reused at every decoder step.

backward() returns the exact gradients of L = g . c for a given vector g,
so that the step can be tested against finite differences.
"""

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

from nlslog import NEG_INF, softmax

Vector = List[float]
Matrix = List[List[float]]


def matvec(a: Sequence[Sequence[float]], 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 keys(U: Sequence[Sequence[float]], H: Sequence[Sequence[float]]) -> List[Vector]:
    """Return the keys U h_j. They do not depend on the decoder step."""
    return [matvec(U, h) for h in H]  # @line L3


def additive_attention(s: Sequence[float], H: Sequence[Sequence[float]], W: Sequence[Sequence[float]],
                       U: Sequence[Sequence[float]], v: Sequence[float],
                       mask: Optional[Sequence[bool]] = None,
                       K: Optional[Sequence[Sequence[float]]] = None) -> Tuple[Vector, Vector, Vector]:
    """Return (context c, weights alpha, scores e) for the decoder state s.

    mask[j] = False marks a padding position, which gets the score -inf and
    the weight 0. K may hold the precomputed keys U h_j.
    """
    if not H:
        raise ValueError("attention needs at least one encoder state")
    q = matvec(W, s)  # @line L1
    if K is None:
        K = keys(U, H)
    e = []
    for j in range(len(H)):  # @line L2
        score = dot(v, [math.tanh(a + b) for a, b in zip(q, K[j])])  # @line L4
        if mask is not None and not mask[j]:  # @line L5
            score = NEG_INF
        e.append(score)
    alpha = softmax(e)  # @line L6
    c = [math.fsum(alpha[j] * H[j][t] for j in range(len(H))) for t in range(len(H[0]))]  # @line L7
    return c, alpha, e  # @line L8


def backward(g: Sequence[float], s: Sequence[float], H: Sequence[Sequence[float]],
             W: Sequence[Sequence[float]], U: Sequence[Sequence[float]], v: Sequence[float],
             mask: Optional[Sequence[bool]] = None):
    """Return the gradients (ds, dH, dW, dU, dv) of L = g . c."""
    q = matvec(W, s)
    K = keys(U, H)
    T = [[math.tanh(a + b) for a, b in zip(q, k)] for k in K]
    _, alpha, _ = additive_attention(s, H, W, U, v, mask, K)
    J, a_dim = len(H), len(v)
    gamma = [dot(g, h) for h in H]  # dL/d alpha_j
    mean = math.fsum(al * ga for al, ga in zip(alpha, gamma))
    de = [alpha[j] * (gamma[j] - mean) for j in range(J)]  # softmax backward; 0 where masked
    dH = [[alpha[j] * gt for gt in g] for j in range(J)]
    dv = [math.fsum(de[j] * T[j][t] for j in range(J)) for t in range(a_dim)]
    dz = [[de[j] * v[t] * (1 - T[j][t] ** 2) for t in range(a_dim)] for j in range(J)]
    dq = [math.fsum(dz[j][t] for j in range(J)) for t in range(a_dim)]
    dW = [[dq[t] * x for x in s] for t in range(a_dim)]
    ds = [math.fsum(W[t][i] * dq[t] for t in range(a_dim)) for i in range(len(s))]
    dU = [[math.fsum(dz[j][t] * H[j][i] for j in range(J)) for i in range(len(H[0]))] for t in range(a_dim)]
    for j in range(J):
        for i in range(len(H[0])):
            dH[j][i] += math.fsum(U[t][i] * dz[j][t] for t in range(a_dim))
    return ds, dH, dW, dU, dv
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_additive_attention.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/additive-attention/. The authors are listed in prov/3X7CGK.jsonl.

import math
import random

import pytest

from additive_attention import additive_attention, backward, keys


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 naive(s, H, W, U, v):
    """The formula written out with plain exp and no max shift."""
    e = []
    for h in H:
        z = [sum(W[t][i] * s[i] for i in range(len(s))) + sum(U[t][i] * h[i] for i in range(len(h)))
             for t in range(len(v))]
        e.append(sum(v[t] * math.tanh(z[t]) for t in range(len(v))))
    w = [math.exp(x) for x in e]
    alpha = [x / sum(w) for x in w]
    c = [sum(alpha[j] * H[j][t] for j in range(len(H))) for t in range(len(H[0]))]
    return c, alpha


def test_page_example():
    s, W, U, v = [1.0, 0.0], [[1.0, 0.0], [0.0, 1.0]], [[1.0, 0.0], [0.0, 1.0]], [1.0, 1.0]
    H = [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0]]
    c, alpha, e = additive_attention(s, H, W, U, v)
    assert abs(e[0] - math.tanh(2)) < 1e-15
    assert abs(e[1] - 2 * math.tanh(1)) < 1e-15
    assert e[2] == 0.0
    assert [round(x, 4) for x in alpha] == [0.3194, 0.5588, 0.1218]
    assert [round(x, 4) for x in c] == [0.1976, 0.5588]
    # the largest weight goes to h_2, though s . h_2 = 0 < s . h_1 = 1
    assert max(range(3), key=lambda j: alpha[j]) == 1


def test_against_naive_formula():
    rng = random.Random(1409)
    for _ in range(50):
        a, ds, dh, J = rng.randint(1, 4), rng.randint(1, 4), rng.randint(1, 4), rng.randint(1, 6)
        s, H = rand_vec(rng, ds), [rand_vec(rng, dh) for _ in range(J)]
        W, U, v = rand_mat(rng, a, ds), rand_mat(rng, a, dh), rand_vec(rng, a)
        c, alpha, _ = additive_attention(s, H, W, U, v)
        c2, alpha2 = naive(s, H, W, U, v)
        assert all(abs(x - y) < 1e-12 for x, y in zip(alpha, alpha2))
        assert all(abs(x - y) < 1e-12 for x, y in zip(c, c2))
        assert abs(sum(alpha) - 1) < 1e-12 and min(alpha) >= 0
        c3, _, _ = additive_attention(s, H, W, U, v, K=keys(U, H))
        assert c3 == c


def test_mask_and_degenerate_cases():
    rng = random.Random(3)
    s, H = rand_vec(rng, 3), [rand_vec(rng, 2) for _ in range(4)]
    W, U, v = rand_mat(rng, 5, 3), rand_mat(rng, 5, 2), rand_vec(rng, 5)
    c, alpha, e = additive_attention(s, H, W, U, v, mask=[True, False, True, False])
    assert alpha[1] == 0.0 and alpha[3] == 0.0 and e[1] == float("-inf")
    c2, alpha2, _ = additive_attention(s, [H[0], H[2]], W, U, v)
    assert abs(alpha[0] - alpha2[0]) < 1e-15 and all(abs(x - y) < 1e-15 for x, y in zip(c, c2))
    # v = 0 gives equal weights and the mean of the encoder states
    c0, alpha0, _ = additive_attention(s, H, W, U, [0.0] * 5)
    assert alpha0 == [0.25] * 4
    assert all(abs(c0[t] - sum(h[t] for h in H) / 4) < 1e-15 for t in range(2))
    with pytest.raises(ValueError):
        additive_attention(s, H, W, U, v, mask=[False] * 4)
    # large scores do not overflow
    _, big, _ = additive_attention(s, H, W, U, [1000.0 * x for x in v])
    assert abs(sum(big) - 1) < 1e-12


def test_gradients_by_finite_differences():
    rng = random.Random(2015)
    eps = 1e-6
    for _ in range(4):
        a, ds, dh, J = 3, 2, 3, 4
        s, H = rand_vec(rng, ds), [rand_vec(rng, dh) for _ in range(J)]
        W, U, v, g = rand_mat(rng, a, ds), rand_mat(rng, a, dh), rand_vec(rng, a), rand_vec(rng, dh)
        mask = [True, True, False, True]

        def loss():
            c, _, _ = additive_attention(s, H, W, U, v, mask)
            return sum(x * y for x, y in zip(g, c))

        ds_, dH, dW, dU, dv = backward(g, s, H, W, U, v, mask)
        cells = [(s, None, i, ds_[i]) for i in range(ds)] + [(v, None, t, dv[t]) for t in range(a)]
        cells += [(W[t], None, i, dW[t][i]) for t in range(a) for i in range(ds)]
        cells += [(U[t], None, i, dU[t][i]) for t in range(a) for i in range(dh)]
        cells += [(H[j], None, i, dH[j][i]) for j in range(J) for i in range(dh)]
        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

History

Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio posted the paper on arXiv in September 2014 and presented it at ICLR 2015. The earlier recurrent encoder-decoder had to compress the source into one vector, and its quality dropped on long sentences. Their RNNsearch model, with additive attention over the states of a bidirectional encoder, kept its quality on long sentences. On English to French newstest2014, with the Moses tokenizer and a vocabulary of 30,000 words, RNNsearch-50 reached 26.75 BLEU against 17.82 for the encoder-decoder without attention (Table 1, a measurement). Attention then spread to speech recognition, summarization and image captioning, and in 2017 the transformer replaced the recurrence by attention alone.

References

  1. Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio, Neural Machine Translation by Jointly Learning to Align and Translate, ICLR 2015, Section 3.1 (equations 5 and 6, the context and the weights), Section 3.2 (the bidirectional encoder), Table 1 (BLEU on newstest2014 English to French), Appendix A.2.2 (the alignment model) and A.2.3 (n = n' = 1000)
  2. Vaswani et al. 2017, Section 3.2.1 (the comparison of additive and dot-product 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
  • at least three sources
  • a scene preset for the example