AI Logic

Attention Mechanisms

Additive Attention (Bahdanau)

Updated:

Structure of additive attention. The left shows the computation flow (scores are computed from the previous decoder state s_{iāˆ’1} and each input position h_j, turned into weights by a softmax, and used to form the weighted sum of h_j, the context vector, which is passed to the decoder RNN). The right compares how scores are computed (additive: a small MLP that adds the outputs of two linear layers, applies tanh, and reduces to a single value with the linear layer v_a; multiplicative: just a dot product)

What is additive attention

Additive attention is a mechanism that uses a small network to decide, each time a translated word is produced, which words of the input sentence to look at and how much. Bahdanau, Cho, and Bengio proposed it in 2014 in the paper "Neural Machine Translation by Jointly Learning to Align and Translate" (ICLR 2015). It is the starting point of today's attention mechanisms.

Earlier encoder-decoder translation models (Sequence to Sequence) packed the entire input sentence into a single fixed-length vector and generated the translation from it. The paper argued that this single vector becomes a bottleneck, so translation quality drops as sentences get longer. Additive attention keeps the input sentence as a sequence of per-word vectors and pulls out the parts it needs each time it emits a word.

The context vector cic_i used to emit the target word yiy_i is computed as follows (Eqs. (5) and (6) in the paper).

ci=āˆ‘j=1Txαijhj,αij=exp⁔(eij)āˆ‘k=1Txexp⁔(eik)c_i = \sum_{j=1}^{T_x} \alpha_{ij} h_j, \qquad \alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k=1}^{T_x} \exp(e_{ik})}

The score eije_{ij} is computed by an MLP with one hidden layer (Appendix A.1.2 of the paper).

eij=a(siāˆ’1,hj)=va⊤tanh⁔(Wasiāˆ’1+Uahj)e_{ij} = a(s_{i-1}, h_j) = v_a^\top \tanh\left(W_a s_{i-1} + U_a h_j\right)
  • hjh_j: the vector of the jj-th word of the input sentence (the encoder output). TxT_x is the length of the input sentence.
  • siāˆ’1s_{i-1}: the previous decoder state. It represents "what is about to be translated."
  • Wa,Ua,vaW_a, U_a, v_a: learned weights. Because Wasiāˆ’1W_a s_{i-1} and UahjU_a h_j are added before passing through tanh, the mechanism is called "additive" attention.
  • αij\alpha_{ij}: the weight on the jj-th input word when emitting the ii-th target word. It sums to 1 over jj.

This resembles a human translator who glances back at the source text after writing each word and focuses on the area around the part currently being translated. Where to look is decided while translating.

The left side of the figure at the top of the article shows the computation flow, and the right side shows how the score is computed. On the right, it is placed next to multiplicative attention, proposed later, which computes the score with a dot product alone.

Computation steps

In the paper's model (RNNsearch), each time one target word is emitted, the computation proceeds in the following order (Section 3.1 and Appendix A.2).

  1. Turn the input sentence into a sequence of vectors with the encoder: a bidirectional RNN reads the input sentence forward and backward, and the two hidden states are concatenated into hjh_j. The resulting vector contains information about both the preceding and following words.
  2. Compute the scores: for every pair of the previous decoder state siāˆ’1s_{i-1} and the hjh_j at each input position, compute the score eije_{ij}.
  3. Turn them into weights: apply the softmax function to ei1,…,eiTxe_{i1}, \dots, e_{iT_x} to obtain weights αij\alpha_{ij} that sum to 1.
  4. Build the context vector: sum the hjh_j weighted by αij\alpha_{ij} to obtain the context vector cic_i.
  5. Advance the decoder by one step: compute the next state sis_i from the previous state siāˆ’1s_{i-1}, the previous target word yiāˆ’1y_{i-1}, and the context vector cic_i, then output the probability of the next target word yiy_i.

The inside of the score computation (step 2) is shown on the right of the figure at the top of the article.

  • Wasiāˆ’1W_a s_{i-1} and UahjU_a h_j are each transformed into vectors of length n′n'.
  • The two are added and passed through tanh.
  • Multiplying by va⊤v_a^\top reduces the result to a single value (the score).

The shapes of the weights in the paper's setting are as follows (Appendices A.2.2 and A.2.3).

WeightShapeValue in the paper
WaW_an′×nn' \times nn=1000n = 1000 (length of the decoder hidden state)
UaU_an′×2nn' \times 2nhjh_j concatenates the forward and backward states, so its length is 2n=20002n = 2000
vav_an′n'n′=1000n' = 1000 (length of the hidden layer of the score MLP)

UahjU_a h_j does not depend on the target index ii. The paper notes that UahjU_a h_j for all positions can be precomputed once the input sentence has been read, which saves computation. Only the Wasiāˆ’1W_a s_{i-1} part needs to be recomputed for each target word.

Why long sentences can be translated

Additive attention works because it does not squeeze the information of the input sentence into a single vector; it can extract only what is needed for each target word. The encoder no longer has to summarize the whole sentence perfectly; it only needs to represent the information around each word correctly. The paper gives this as the reason for the improvement on long sentences.

The weight αij\alpha_{ij} can also be read as "the probability that the ii-th target word is translated from the jj-th input word." Conventional statistical translation obtained word-to-word correspondences (alignments) in a separate procedure, but the weights of additive attention are produced by the softmax function, so they are differentiable and can be learned directly from the translation loss.

The paper visualizes the learned weights as matrices and confirms the following behaviors (Section 5.2.1, Figure 3).

  • Reordering: when translating the English "European Economic Area" into the French "zone Ć©conomique europĆ©enne," the model put its weight on "Area," two words ahead, when emitting "zone," and then moved back one word at a time.
  • Non-one-to-one correspondence: when translating "the man" into "l' homme," the model looked at both "the" and "man" when emitting "l'." The form of the article (le, la, l') depends on the following noun, so both words must be considered.

The score function is an MLP so that the "fit" between siāˆ’1s_{i-1} and hjh_j can be expressed flexibly through learning. The two vectors are mapped to the same length n′n' by separate linear layers before being added, so siāˆ’1s_{i-1} and hjh_j can be compared directly even when their lengths differ (1000 and 2000 in the paper).

Experimental results

The paper compares additive attention with a conventional model without attention (RNNencdec) on English-to-French translation (WMT '14, tested on the 3003 sentences of news-test-2014). Both use a vocabulary of 30,000 words per language and 1000 hidden units. The numbers 30 and 50 are the maximum sentence length (in words) used for training. Values are BLEU scores (higher is better) (Table 1).

ModelAll sentencesSentences without unknown words
RNNencdec-30 (no attention)13.9324.19
RNNsearch-30 (additive attention)21.5031.44
RNNencdec-50 (no attention)17.8226.71
RNNsearch-50 (additive attention)26.7534.16
RNNsearch-50⋆ (trained longer)28.4536.15
Moses (conventional phrase-based translation)33.3035.63

The results show the following.

  • Adding attention brings a large improvement: among models trained on sentences of the same length, BLEU rises by 7 to 9 points. RNNsearch-30 even outperforms RNNencdec-50, which was trained on longer sentences.
  • On sentences without unknown words, it matches a conventional translation system: RNNsearch-50⋆ scores 36.15, above Moses at 35.63. Moses additionally uses a large monolingual corpus (418 million words) separate from the parallel data used for training.
  • Quality does not drop on long sentences: comparing BLEU by sentence length (Figure 2), RNNencdec drops sharply as sentences get longer, while RNNsearch-50 does not drop even on sentences of 50 words or more.

Translations are generated with beam search.

Practical considerations

Additive attention computes the scores of all input positions for every target word.

The scores must be computed for every pair of input length TxT_x and output length TyT_y, that is, TxƗTyT_x \times T_y times. The paper itself notes that this is not a problem for translation of sentences of about 15 to 40 words, but may limit its applicability to other tasks. For long inputs such as paragraphs or documents, computation and memory grow with the product of the lengths.

In implementations, keep the following in mind.

  • It tends to be slower than dot-product attention: each score builds a vector of length n′n' and passes it through tanh, so computing them in a batch creates an intermediate result of size TyƗTxƗn′T_y \times T_x \times n'. A dot product needs only one matrix multiplication, and the Transformer paper notes that although the theoretical complexity is similar, the dot product is much faster and more memory-efficient in practice.
  • The state used is the "previous" one: the score uses the decoder state siāˆ’1s_{i-1} before it is updated. Using the updated sis_i follows Luong et al.'s multiplicative attention. When reproducing the paper, make sure to use the same state.
  • Mask the padding: when batching sentences of different lengths, set the scores of the padded positions to āˆ’āˆž-\infty before the softmax function so their weights become 0 (masking).

Comparison with other methods

Ways of computing attention scores fall broadly into two families: "compute with a small MLP" and "compute with a dot product." Side by side on the same criteria:

MethodScore formulaWeights learned for the scoreHow it is computedCharacteristics
Additive attention (Bahdanau et al., 2014)va⊤tanh⁔(Was+Uah)v_a^\top \tanh(W_a s + U_a h)Wa,Ua,vaW_a, U_a, v_aAn MLP for each pairThe two vectors may differ in length. Slower than a dot product
Multiplicative attention, dot (Luong et al., 2015)ht⊤hˉsh_t^\top \bar{h}_sNoneOne matrix multiplicationFastest. The two vectors must have the same length
Multiplicative attention, general (Luong et al., 2015)ht⊤Wahˉsh_t^\top W_a \bar{h}_sWaW_aMatrix multiplicationLengths may differ. Keeps the speed of the dot product
Scaled dot-product attention (Vaswani et al., 2017)q⊤k/dkq^\top k / \sqrt{d_k}None (separate linear layers produce Q,KQ, K)One matrix multiplicationValues do not grow too large even for long vectors

The Transformer paper states that additive and dot-product attention perform similarly when the vector length dkd_k is small, and that for large dkd_k the unscaled dot product falls behind additive attention. Scaled dot-product attention closes this gap by dividing by dk\sqrt{d_k} while keeping the speed of the dot product.

Guidelines for choosing:

  • To reproduce the RNN translation model as in the paper: use additive attention.
  • To prioritize speed or build a Transformer-style model: use scaled dot-product attention inside multi-head attention. Almost all of today's large models take this route.
  • When the two vectors being compared differ in length and computation should stay light: as in the general variant of multiplicative attention, transform one side with a linear layer and then take the dot product.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class AdditiveAttention(nn.Module):
    """Additive attention of Bahdanau et al.: e_ij = v_aįµ€ tanh(W_a s_{i-1} + U_a h_j)
    PyTorch has no built-in version, so it is written exactly as in the paper (no dropout, so train / eval behave the same)"""

    def __init__(self, dec_dim=1000, enc_dim=2000, attn_dim=1000):
        super().__init__()
        self.W_a = nn.Linear(dec_dim, attn_dim, bias=False)  # n' Ɨ n
        self.U_a = nn.Linear(enc_dim, attn_dim, bias=False)  # n' Ɨ 2n
        self.v_a = nn.Linear(attn_dim, 1, bias=False)         # n'

    def precompute(self, h):
        # U_a h_j does not depend on the target index i, so compute it only once per input sentence
        return self.U_a(h)  # [B, T_x, n']

    def forward(self, s_prev, h, Uh, mask=None):
        """s_prev: [B, n] (previous decoder state), h: [B, T_x, 2n] (encoder output)
        Uh: result of precompute(h), mask: [B, T_x] booleans (True = padding, hidden)"""
        e = self.v_a(torch.tanh(self.W_a(s_prev).unsqueeze(1) + Uh)).squeeze(-1)  # scores [B, T_x]
        if mask is not None:
            e = e.masked_fill(mask, float("-inf"))
        alpha = torch.softmax(e, dim=-1)                  # weights (sum to 1) [B, T_x]
        c = torch.bmm(alpha.unsqueeze(1), h).squeeze(1)    # context vector c_i [B, 2n]
        return c, alpha


B, T_x = 2, 7
h = torch.randn(B, T_x, 2000)   # bidirectional RNN output (forward 1000 + backward 1000)
s_prev = torch.randn(B, 1000)   # previous decoder state s_{i-1}
pad = torch.zeros(B, T_x, dtype=torch.bool)
pad[1, 5:] = True               # the 2nd sentence has length 5 (the rest is padding)

attn = AdditiveAttention()
Uh = attn.precompute(h)         # only once, before translation starts
c, alpha = attn(s_prev, h, Uh, mask=pad)
print(c.shape, alpha.shape)     # torch.Size([2, 2000]) torch.Size([2, 7])
print(alpha.sum(dim=-1))        # every sentence sums to 1
print(alpha[1, 5:])             # weights at padded positions are 0

FAQ

Q. Why is it called "additive"?
A.

Because in the score formula va⊤tanh⁔(Wasiāˆ’1+Uahj)v_a^\top \tanh(W_a s_{i-1} + U_a h_j), the decoder state and the encoder output are each linearly transformed and then added. The name comes from the Transformer paper and contrasts with multiplicative attention, which multiplies the two vectors (takes their dot product). Luong et al.'s paper calls the same form "concat".

Q. Which performs better, additive attention or dot-product attention?
A.

It depends on the conditions. The Transformer paper states that they perform similarly when the vector length dkd_k is small, and that the unscaled dot product becomes worse when dkd_k is large. On the other hand, in Luong et al.'s translation experiments, concat (the same form as additive) in their implementation gave worse results than dot or general. Since the dot product has the advantage in speed, scaled dot-product attention is used in almost all cases today.

Q. Can additive attention be used in a Transformer?
A.

It can, by swapping out the score function, but it usually is not. A Transformer gets its speed by computing the scores of all position pairs with a single matrix multiplication. Additive attention passes each pair through tanh, which creates an NƗNƗn′N \times N \times n' intermediate result, so long sequences cost a lot of memory and time.

References

  1. D. Bahdanau, K. Cho, and Y. Bengio, "Neural Machine Translation by Jointly Learning to Align and Translate," ICLR, 2015.
  2. M.-T. Luong, H. Pham, and C. D. Manning, "Effective Approaches to Attention-based Neural Machine Translation," EMNLP, 2015.
  3. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.