Luong Attention › Attention Score Functions

Michael BrenndoerferMay 18, 202512 min read
Language AI HandbookAll chapters
Part 12 of 67Sequence-to-Sequence
Chapter 88Luong Attention › Attention Score Functions
Reading section 2 of 11 · Attention Score Functions · 12 minSection 2 of 11 · 12 min

Book contents

Section 2 of 11 · 12 min read

Luong Attention › Attention Score FunctionsOne section · Sections in this chapter2 / 11 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

At the heart of any attention mechanism lies a fundamental question: how do we measure the relevance of each encoder state to the current decoding step? This measurement, called the alignment score or compatibility score, determines which parts of the input sequence the decoder should focus on when generating each output token.

Think of it this way: when translating "The cat sat on the mat" to French, and you're about to generate the word "chat" (cat), you need a way to identify that the English word "cat" is the most relevant source word. The score function quantifies this relevance for every source position, producing a set of numbers that attention will convert into a probability distribution.

Bahdanau attention introduced an additive score function with learned parameters. Luong et al. asked: can we achieve similar results with simpler approaches? Their answer was three alternative score functions, each representing a different trade-off between simplicity, expressiveness, and computational cost.

Dot Product Attention

The simplest approach to measuring relevance is to ask: how similar are the decoder and encoder representations? If the encoder has learned to represent "cat" in a particular way, and the decoder has learned to look for that same pattern when generating "chat", then similar representations should yield high scores.

The dot product provides exactly this similarity measure. Given a decoder hidden state hth_t and an encoder hidden state hˉs\bar{h}_s, the dot product attention score is:

score(ht,hˉs)=ht⊤hˉs\text{score}(h_t, \bar{h}_s) = h_t^\top \bar{h}_s

where:

  • ht∈Rdh_t \in \mathbb{R}^{d}: the decoder hidden state at timestep tt, encoding what the decoder is "looking for"
  • hˉs∈Rd\bar{h}_s \in \mathbb{R}^{d}: the encoder hidden state at source position ss, encoding what that position "contains"
  • ht⊤hˉsh_t^\top \bar{h}_s: the inner product of the two vectors, yielding a scalar score
  • dd: the hidden dimension, which must be equal for both encoder and decoder

Why does the dot product capture similarity? Consider what happens geometrically. When two vectors point in the same direction, their dot product is large and positive, indicating high compatibility. When they point in opposite directions, the dot product is large and negative. Orthogonal vectors, sharing no common direction, yield zero.

This geometric interpretation has a powerful implication: the encoder and decoder can learn complementary representations. The encoder learns to place semantically similar words in similar directions in the hidden space. The decoder learns to "query" for specific semantic content by producing hidden states that point toward the relevant encoder representations.

The elegance of dot product attention lies in its simplicity. No learned parameters are needed for the score function itself. All the learning happens in the encoder and decoder, which discover representations where raw similarity is a good proxy for alignment. This makes dot product attention computationally efficient and easy to implement.

However, this simplicity comes with a constraint: the decoder and encoder hidden states must have the same dimensionality. If ht∈Rdhh_t \in \mathbb{R}^{d_h} and hˉs∈Rdh\bar{h}_s \in \mathbb{R}^{d_h}, the dot product is well-defined. If they have different dimensions, you cannot compute a dot product directly, which motivates our next score function.

General (Bilinear) Attention

What if the encoder and decoder have different hidden dimensions? Or what if raw similarity isn't the right measure, and we want the model to learn a more specific notion of relevance?

The general score function addresses both concerns by introducing a learnable weight matrix WaW_a that transforms the encoder states before computing similarity:

score(ht,hˉs)=ht⊤Wahˉs\text{score}(h_t, \bar{h}_s) = h_t^\top W_a \bar{h}_s

where:

  • ht∈Rdhh_t \in \mathbb{R}^{d_h}: the decoder hidden state at timestep tt
  • hˉs∈Rdhˉ\bar{h}_s \in \mathbb{R}^{d_{\bar{h}}}: the encoder hidden state at source position ss
  • Wa∈Rdh×dhˉW_a \in \mathbb{R}^{d_h \times d_{\bar{h}}}: a learned weight matrix that projects encoder states into the decoder's space
  • ht⊤Wahˉsh_t^\top W_a \bar{h}_s: a scalar score computed by first applying WaW_a to hˉs\bar{h}_s, then taking the dot product with hth_t

To understand what WaW_a does, trace through the computation step by step. First, WahˉsW_a \bar{h}_s converts the encoder state into a dhd_h-dimensional vector. Then ht⊤h_t^\top takes the dot product with this transformed vector. The matrix WaW_a effectively learns which aspects of the encoder representation are most relevant for each dimension of the decoder state.

This formulation is called bilinear attention because the score is a bilinear function of the two input vectors: linear in hth_t when hˉs\bar{h}_s is fixed, and linear in hˉs\bar{h}_s when hth_t is fixed. The weight matrix WaW_a serves two purposes:

  • Dimension matching: When encoder and decoder have different hidden dimensions, WaW_a bridges the gap by projecting encoder states into the decoder's space
  • Learned similarity: Rather than relying on raw vector similarity, the matrix learns what aspects of encoder states are most relevant for alignment, potentially discovering non-obvious relationships

General attention is more expressive than dot product attention but requires additional parameters. For encoder and decoder dimensions of 512, WaW_a adds 512×512=262,144512 \times 512 = 262{,}144 parameters. This is modest compared to the total model size but can matter for smaller models or when memory is constrained.

Concat Attention

The most expressive score function takes a fundamentally different approach. Rather than computing a form of similarity between two vectors, it asks: given both the decoder state and an encoder state, what score should a neural network assign?

The concat score function concatenates the two states and passes them through a small neural network:

score(ht,hˉs)=va⊤tanh⁡(Wa[ht;hˉs])\text{score}(h_t, \bar{h}_s) = v_a^\top \tanh(W_a [h_t; \bar{h}_s])

Let's unpack this formula piece by piece:

  1. Concatenation [ht;hˉs][h_t; \bar{h}_s]: We stack the decoder and encoder states into a single vector of dimension dh+dhˉd_h + d_{\bar{h}}. This gives the network access to all information from both states.

  2. Linear projection Wa[ht;hˉs]W_a [h_t; \bar{h}_s]: The weight matrix Wa∈Rn×(dh+dhˉ)W_a \in \mathbb{R}^{n \times (d_h + d_{\bar{h}})} projects the concatenated vector to an intermediate space of dimension nn. This allows the network to learn arbitrary linear combinations of the input features.

  3. Nonlinearity tanh⁡(⋅)\tanh(\cdot): The hyperbolic tangent activation introduces nonlinearity, enabling the network to learn complex, non-linear relationships between decoder and encoder states.

  4. Scalar projection va⊤v_a^\top: Finally, the weight vector va∈Rnv_a \in \mathbb{R}^n projects the intermediate representation to a single scalar score.

where:

  • ht∈Rdhh_t \in \mathbb{R}^{d_h}: the decoder hidden state at timestep tt
  • hˉs∈Rdhˉ\bar{h}_s \in \mathbb{R}^{d_{\bar{h}}}: the encoder hidden state at source position ss
  • [ht;hˉs]∈Rdh+dhˉ[h_t; \bar{h}_s] \in \mathbb{R}^{d_h + d_{\bar{h}}}: the concatenated vector of both states
  • Wa∈Rn×(dh+dhˉ)W_a \in \mathbb{R}^{n \times (d_h + d_{\bar{h}})}: a learned projection matrix
  • va∈Rnv_a \in \mathbb{R}^n: a learned weight vector that collapses the intermediate representation to a scalar
  • nn: the intermediate dimension, a hyperparameter typically set equal to the hidden dimension

This formulation is similar to Bahdanau attention, with one key difference: Bahdanau uses the previous decoder state ht−1h_{t-1}, while Luong's concat uses the current decoder state hth_t. This seemingly small change has clear implications for the overall architecture, which we'll explore in the section on attention placement.

Out[4]:
Visualization
Three diagrams showing dot product, general, and concat attention score computation flows.
Comparison of three Luong attention score functions. Dot product (left) is parameter-free and requires matching dimensions. General attention (center) uses a learned weight matrix to enable flexible bilinear scoring. Concat attention (right) uses a two-layer network with tanh nonlinearity, making it the most expressive but also the most computationally expensive.

Computational Comparison

The three score functions differ significantly in their computational requirements. For a sequence of length SS with hidden dimension dd:

Computational comparison of Luong attention score functions.
Score FunctionTime ComplexityParametersNotes
Dot ProductO(Sd)O(Sd)0Fastest, requires dh=dhˉd_h = d_{\bar{h}}
GeneralO(Sd2)O(Sd^2)dh×dhˉd_h \times d_{\bar{h}}Matrix multiplication dominates
ConcatO(Snd)O(Snd)n(dh+dhˉ)+nn(d_h + d_{\bar{h}}) + nTwo-step transformation

As shown in Table score-functions, dot product attention is most efficient but requires matching dimensions. General attention adds a single matrix, while concat attention requires two sets of parameters (WaW_a and vav_a).

Out[5]:
Visualization
Log-scale line plot showing computational cost scaling with sequence length for three attention methods.
Computational cost (MFLOPs) at increasing sequence lengths, with hidden dimension fixed at 256. Dot product scales linearly while general and concat scale quadratically with hidden dimension, creating a large gap at longer sequences.
Bar chart comparing parameter counts across hidden dimensions for three attention methods.
Parameter count (thousands) by hidden dimension for each score function. Dot product requires zero parameters, general attention scales as d squared, and concat attention scales similarly, making dot product the most memory-efficient choice.

For modern hardware with efficient matrix operations, dot product attention is significantly faster because it can be fully parallelized as a single matrix multiplication across all encoder states simultaneously. This efficiency advantage is why transformers adopt scaled dot-product attention as their core mechanism.