AI Logic

Attention Mechanisms

Multiplicative Attention (Luong)

Updated:

Structure of multiplicative attention. Left: the computation flow (scores are computed from the current decoder state h_t and each input position h̄_s, turned into weights with softmax to build the context vector c_t, which is concatenated with h_t and passed through a linear layer and tanh to predict the next word). Right: a comparison of how scores are computed (multiplicative dot is just a dot product; general transforms h̄_s with a linear layer W_a before the dot product; additive's small MLP is shown for comparison)

What is multiplicative attention

Multiplicative attention is attention that scores where the decoder should look in the input sentence using a dot product, which multiplies two vectors together. In 2015, Luong, Pham, and Manning compared score functions for attention in translation models in the paper "Effective Approaches to Attention-based Neural Machine Translation" (EMNLP 2015) and showed that the dot-product form works well.

Additive attention (Bahdanau et al.), proposed a year earlier, computed scores with a network that has one hidden layer. Luong et al. tried simpler dot-product forms and list the following three score functions in Section 3.1 of the paper.

score(ht,hˉs)={ht⊤hˉsdotht⊤Wahˉsgeneralva⊤tanh⁡(Wa[ht;hˉs])concat\mathrm{score}(h_t, \bar{h}_s) = \begin{cases} h_t^\top \bar{h}_s & \text{dot} \\ h_t^\top W_a \bar{h}_s & \text{general} \\ v_a^\top \tanh\left(W_a [h_t; \bar{h}_s]\right) & \text{concat} \end{cases}
  • hth_t: the decoder state at time tt, when it is about to output a target word.
  • hˉs\bar{h}_s: the encoder state at position ss of the input sentence.
  • dot and general: since they multiply two vectors together, the Transformer paper called them "multiplicative attention". This article refers to dot and general together as multiplicative attention.
  • concat: the same form as additive attention.

The values used as weights are the scores normalized by the softmax function to sum to 1 (Eq. (7) of the paper).

at(s)=exp⁡(score(ht,hˉs))∑s′exp⁡(score(ht,hˉs′))a_t(s) = \frac{\exp\left(\mathrm{score}(h_t, \bar{h}_s)\right)}{\sum_{s'} \exp\left(\mathrm{score}(h_t, \bar{h}_{s'})\right)}

A dot product is larger the more two vectors point in the same direction. The idea is that the more "what is being looked for now" resembles "what is at that input position", the larger the weight it receives.

In the figure at the top of the article, the left side shows the computation flow and the right side shows how scores are computed. For comparison, additive attention is also shown on the right.

Computation steps

Luong et al.'s model uses an encoder and decoder with four stacked LSTM layers. When the decoder outputs the target word at time tt, it computes the following in order (Sections 3 and 3.1, Figure 2).

  1. Compute the decoder state: take the state hth_t at time tt from the top LSTM layer.
  2. Compute scores: compute a score with dot or general between hth_t and hˉs\bar{h}_s for every input position.
  3. Turn them into weights: apply the softmax function to get weights at(s)a_t(s) that sum to 1.
  4. Build the context vector: take the weighted average of hˉs\bar{h}_s with weights at(s)a_t(s) to get the context vector ctc_t.
  5. Combine the attention result with the state: concatenate ctc_t and hth_t and pass them through a linear layer and tanh to get h~t\tilde{h}_t (Eq. (5)).
  6. Predict the next word: pass h~t\tilde{h}_t through a linear layer and the softmax function to get the probabilities of the next word (Eq. (6)).

The equations for steps 5 and 6 are:

h~t=tanh⁡(Wc[ct;ht]),p(yt∣y<t,x)=softmax(Wsh~t)\tilde{h}_t = \tanh\left(W_c [c_t; h_t]\right), \qquad p(y_t \mid y_{<t}, x) = \mathrm{softmax}\left(W_s \tilde{h}_t\right)

The paper points out that its computation path is simpler than additive attention's.

  • Additive attention: computes scores from the previous state ht−1h_{t-1} and uses the context vector to produce the next state hth_t.
  • Multiplicative attention (Luong et al.): computes the current state hth_t first, then computes ht→at→ct→h~th_t \to a_t \to c_t \to \tilde{h}_t before predicting.

With dot, if Hˉ\bar{H} is the matrix of stacked encoder states, the scores for all input positions can be computed with a single matrix-vector product Hˉht\bar{H} h_t. The same holds for general if HˉWa\bar{H} W_a is precomputed for each input sentence. This "only matrix multiplications" property is what later makes scaled dot-product attention fast.

Local attention and input-feeding

Besides score functions, Luong et al.'s paper proposes two ways of using attention. Both were used in combination with multiplicative scores.

Local attention looks only within a window rather than at every position of the input sentence (Section 3.2). The approach described so far, which looks at every position, is called "global attention".

  • For each target word, a focus position ptp_t in the input sentence is chosen, and weights are computed only within the window [pt−D, pt+D][p_t - D,\ p_t + D]. The paper uses D=10D = 10.
  • local-m sets pt=tp_t = t (assuming the input and output have roughly the same word order); local-p predicts ptp_t with a network and dampens the weights with a Gaussian centered at ptp_t.

Input-feeding feeds the attention result h~t\tilde{h}_t from the previous time step into the decoder's input at the next time step (Section 3.3). The goal is to let the model know where it has looked before, preventing it from translating the same part repeatedly or leaving parts untranslated.

Experimental results

The paper compares methods on English-to-German translation (4.5M sentence pairs of WMT '14 training data, tested on newstest2014). The values are perplexity (lower is better) and BLEU (higher is better).

First, a comparison of combinations of score functions and attention types (Table 4). "After unk replacement" is the BLEU after applying a technique from prior work that replaces out-of-vocabulary words (<unk>) based on the input words aligned by attention.

AttentionScorePerplexityBLEUAfter unk replacement
Globallocation (weights from hth_t alone)6.418.119.3
Globaldot6.118.620.5
Globalgeneral6.117.319.1
Local (local-m)general6.218.620.4
Local (local-p)dot6.618.019.6
Local (local-p)general5.919.020.9

The results show the following.

  • dot is best for global attention: its BLEU of 18.6 beats general (17.3).
  • general is better for local attention: the combination of local-p and general gives the best perplexity and BLEU.
  • concat (the same form as additive) did not do well: its perplexity was 6.7 for global and 7.1 for local. The paper suggests this may be because the part of matrix WaW_a corresponding to hˉs\bar{h}_s was simplified by fixing it to the identity matrix, so it cannot be concluded that additive attention itself is inferior.

The effect of adding attention is seen in comparison with the same model without attention (Table 1). Starting from a model with reversed source input and dropout (BLEU 14.0), adding global attention gives 16.8, input-feeding 18.1, and local-p with general 19.0, which is 5.0 above the model without attention. Unknown-word replacement then raises it to 20.9. An ensemble of 8 models reached 23.0, the best result at the time.

Practical considerations

The dot variant of multiplicative attention is cheap to compute, but it places conditions on the two vectors being compared.

The dot score ht⊤hˉsh_t^\top \bar{h}_s can only be computed when the two vectors have the same length (dimension). It cannot be used as is when, for example, the encoder is a bidirectional RNN (concatenating forward and backward states doubles the length) and the decoder is unidirectional. When the lengths differ, transform one of them with a linear layer WaW_a, as in general.

Also keep the following in mind.

  • Long vectors make values too large: the variance of a dot product grows with the vector length dd, so the softmax output concentrates on one position and the gradients become small. The Transformer paper notes that for large dd, unscaled dot products lose to additive attention, and adopted scaled dot-product attention, which divides by d\sqrt{d}.
  • Use the "current" state: Luong et al.'s score uses the updated decoder state hth_t. The additive attention paper (Bahdanau et al.) uses the previous state, so take care not to mix the two when reproducing them.
  • Mask padding: when batching sentences of different lengths, set the scores at padding positions to −∞-\infty before applying the softmax function (masking).

Comparison with other methods

Comparing score functions from the same angle gives the following.

MethodScore formulaWeights learned for scoringLengths of the two vectorsHow it is computed
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_aMay differA small MLP per pair
Multiplicative attention, dot (Luong et al., 2015)ht⊤hˉsh_t^\top \bar{h}_sNoneMust matchOne matrix multiplication
Multiplicative attention, general (Luong et al., 2015)ht⊤Wahˉsh_t^\top W_a \bar{h}_sWaW_aMay differMatrix multiplication
Scaled dot-product attention (Vaswani et al., 2017)q⊤k/dkq^\top k / \sqrt{d_k}None (separate linear layers produce Q,KQ, K)Must matchOne matrix multiplication

Mathematically, scaled dot-product attention can also be seen as an extension of general. Splitting general's WaW_a into two matrices as Wa=WQ⊤WKW_a = W^{Q\top} W^K makes the score (WQht)⊤(WKhˉs)(W^Q h_t)^\top (W^K \bar{h}_s), which is the same as the Transformer's form of "producing queries and keys with separate linear layers and then taking the dot product".

Rough guidelines for choosing:

  • An RNN translation model where both states have the same length: dot is the simplest, and it gave the best result with global attention in the paper.
  • Lengths differ, or you want to transform before comparing: use general.
  • Building a Transformer-style model: use scaled dot-product attention inside multi-head attention.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


class LuongAttention(nn.Module):
    """Luong et al.'s global attention. score is "dot" (h_tᵀ h̄_s) or "general" (h_tᵀ W_a h̄_s)
    PyTorch has no built-in module, so this follows the paper's equations (no dropout, so train / eval behave the same)"""

    def __init__(self, dec_dim=1000, enc_dim=1000, score="dot"):
        super().__init__()
        self.score = score
        if score == "dot":
            assert dec_dim == enc_dim, "dot requires h_t and h̄_s to have the same length"
        else:
            self.W_a = nn.Linear(enc_dim, dec_dim, bias=False)       # W_a
        self.W_c = nn.Linear(enc_dim + dec_dim, dec_dim, bias=False)  # W_c in Eq. (5)

    def forward(self, h_t, h_s, mask=None):
        """h_t: [B, T_y, d] (decoder state at each time step), h_s: [B, S, d_enc] (encoder states)
        mask: boolean [B, S] (True = padding, hidden)"""
        keys = h_s if self.score == "dot" else self.W_a(h_s)
        scores = h_t @ keys.transpose(1, 2)                   # [B, T_y, S] (one matrix multiplication)
        if mask is not None:
            scores = scores.masked_fill(mask[:, None, :], float("-inf"))
        a = torch.softmax(scores, dim=-1)                      # weights a_t(s)
        c = a @ h_s                                            # context vector c_t [B, T_y, d_enc]
        h_tilde = torch.tanh(self.W_c(torch.cat([c, h_t], dim=-1)))  # Eq. (5)
        return h_tilde, a


B, S, T_y, d = 2, 9, 4, 1000
h_s = torch.randn(B, S, d)
h_t = torch.randn(B, T_y, d)
pad = torch.zeros(B, S, dtype=torch.bool)
pad[1, 6:] = True

attn = LuongAttention(score="dot")
h_tilde, a = attn(h_t, h_s, mask=pad)
print(h_tilde.shape, a.shape)  # torch.Size([2, 4, 1000]) torch.Size([2, 4, 9])

# The dot score and weighted average equal unscaled dot-product attention.
# F.scaled_dot_product_attention multiplies by 1/√d by default, so passing scale=1.0 matches dot
# (in attn_mask, True means "attend", the opposite of nn.MultiheadAttention)
c_ref = F.scaled_dot_product_attention(h_t, h_s, h_s, attn_mask=~pad[:, None, :], scale=1.0)
print(torch.allclose(c_ref, a @ h_s, atol=1e-5))  # should be True

FAQ

Q. Are "multiplicative" and "dot-product" attention the same thing?
A.

The terms are used almost interchangeably. The Transformer paper wrote "dot-product (multiplicative) attention", calling dot-product attention multiplicative attention. Luong et al.'s paper does not use the name "multiplicative"; it uses the names dot and general. general inserts a linear layer WaW_a, and is often included under the name multiplicative attention.

Q. Should I use dot or general?
A.

If the two states have the same length, try dot first. It has no learned weights, and in the paper's global attention dot gave the best BLEU (18.6). Use general when the lengths differ or when combining it with local attention. In the paper, the combination of local attention (local-p) and general gave the best result.

Q. How does it differ from scaled dot-product attention?
A.

The difference is whether the score is divided by dk\sqrt{d_k}. Without the division, dot products become too large for long vectors, and the gradients of the softmax function become small. PyTorch's F.scaled_dot_product_attention multiplies by 1/d1/\sqrt{d} by default, so pass scale=1.0 to get the same result as unscaled dot.

References

  1. M.-T. Luong, H. Pham, and C. D. Manning, "Effective Approaches to Attention-based Neural Machine Translation," EMNLP, 2015.
  2. D. Bahdanau, K. Cho, and Y. Bengio, "Neural Machine Translation by Jointly Learning to Align and Translate," ICLR, 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.
  4. PyTorch Documentation, "torch.nn.functional.scaled_dot_product_attention."