Bahdanau Attention › The Attention Mechanism: From Intuition to Formulas
Language AI HandbookAll chapters Bahdanau Attention › The Attention Mechanism: From Intuition to FormulasOne section · Sections in this chapter3 / 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
With the alignment problem clearly defined, we can now develop the mathematical machinery that Bahdanau attention uses to solve it. Our journey will take us through three interconnected concepts: computing relevance scores, converting those scores to probabilities, and aggregating information based on those probabilities. Each piece builds naturally on the previous one, culminating in a mechanism that allows the decoder to "look back" at exactly the right parts of the input at each generation step.
The Challenge of Measuring Relevance
Attention addresses a simple question: when the decoder is about to generate output token , how relevant is each encoder position to that decision? If we could answer this question with a single number for each encoder position, we'd have a way to rank and weight the encoder states.
But what should this "relevance score" capture? Consider translating "The cat sat on the mat" to French. When generating "chat" (cat), the decoder needs to know:
- What the decoder is currently looking for (encoded in its hidden state )
- What information each encoder position offers (encoded in hidden states )
The relevance of position depends on both of these: what contains and whether that content matches what the decoder currently needs. This suggests we need a function that takes both the decoder state and an encoder state as inputs and produces a scalar score.
The Additive Score Function
Bahdanau and colleagues designed a solution called the additive (or concatenative) alignment model. Rather than directly comparing the decoder and encoder states, which might have different dimensions and represent different types of information, they project both into a shared "alignment space" where comparison becomes meaningful.
The alignment score between decoder position and encoder position is computed as:
where:
- : the alignment score, a scalar indicating how relevant encoder position is for generating output
- : the decoder hidden state at the previous timestep, encoding what the decoder "knows" and "needs"
- : the encoder hidden state at position , encoding information about input token and its context
- : a learnable weight matrix that projects the decoder state into the alignment space
- : a learnable weight matrix that projects encoder states into the same alignment space
- : a learnable vector that reduces the combined representation to a scalar
- : the dimension of the alignment space (a hyperparameter, typically matching the hidden dimensions)
This formula might look complex at first glance, but it follows a clear logic. Let's trace through it step by step to understand why each component is necessary:
Step 1: Project into alignment space. The decoder state and encoder state live in potentially different vector spaces with different dimensions. Before comparing them, we need to transform them into a common representation. The matrices and learn these transformations during training:
- produces a -dimensional vector representing "what the decoder is looking for"
- produces a -dimensional vector representing "what encoder position offers"
Step 2: Combine additively. With both vectors in the same space, we add them element-wise: . This additive combination allows the model to detect when the decoder's query and the encoder's content are compatible. If certain dimensions align well (both positive or both negative), they reinforce each other; if they conflict, they cancel out.
Step 3: Apply nonlinearity. The function serves two purposes. First, it bounds the values to , preventing any single dimension from dominating. Second, it introduces nonlinearity, enabling the model to learn complex, non-linear relationships between decoder queries and encoder contents. Without this nonlinearity, the entire alignment model would collapse to a simple linear function.


Step 4: Reduce to scalar. Finally, the dot product with compresses the -dimensional result into a single scalar score. The vector learns which dimensions of the alignment space are most important for determining relevance. Some dimensions might capture semantic similarity, others syntactic compatibility; learns to weight these appropriately.

Why "additive" rather than some other approach? Additive combination with separate projection matrices gives the model maximum flexibility. The decoder and encoder might have different hidden dimensions, and even if they're the same size, they encode different types of information. By learning separate projections and , the model can transform each representation into whatever form makes comparison most effective. Bahdanau and colleagues found this approach worked well in practice, and it became the foundation for subsequent attention mechanisms.
From Scores to Probabilities: The Softmax Transformation
We now have a way to compute alignment scores for each encoder position. But these raw scores can be any real number: positive, negative, or zero. To use them for weighting encoder states, we need to transform them into something more interpretable: a probability distribution over encoder positions.
This is where the softmax function enters the picture. Softmax takes a vector of arbitrary real numbers and converts it into a valid probability distribution where all values are positive and sum to 1:
where:
- : the attention weight for encoder position when generating output
- : the raw alignment score from our scoring function
- : the exponential function ()
- : the length of the source sequence
- : the normalizing constant that ensures weights sum to 1
The exponential function is the key to softmax's behavior. It has two essential properties that make it ideal for attention:
- Positivity: for all real , guaranteeing non-negative weights regardless of the input scores
- Monotonicity with amplification: larger scores produce exponentially larger values, which amplifies differences between scores
This second property is particularly important. Consider two scores: and . The difference looks modest, but after exponentiation, while , a 10x ratio. Softmax creates a "winner-take-most" dynamic where the highest-scoring positions dominate, while still allowing lower-scoring positions to contribute.
The attention weight has a clear interpretation: it represents the probability that encoder position contains the information most relevant for generating output token . When we compute attention, we're asking: "Given what the decoder currently needs, where in the input should it look?"


The visualization above shows this amplification in action. Position 4 has a raw score of 2.8, only about 2× higher than position 1's score of 0.8. But after softmax, position 4 receives about 4× the attention weight of position 1. This amplification helps the model make decisive choices about where to focus.
Beyond the mathematical properties, softmax has two important advantages for learning:
- Differentiability: Gradients flow smoothly through softmax, enabling end-to-end training with backpropagation.
- Soft selection: Unlike "hard" attention (which would pick exactly one position), soft attention maintains gradients to all positions, making optimization much easier.
The "softness" of attention can be controlled by scaling the scores before applying softmax. Dividing scores by a temperature parameter changes how sharply the attention focuses:



The entropy values in the figure quantify the "spread" of attention: lower entropy means more focused attention, higher entropy means more distributed. Standard Bahdanau attention uses , which provides a good balance between focusing on relevant positions and maintaining gradient flow to all positions during training.
The "sharpness" of the attention distribution depends on the magnitude of score differences. When scores are similar, attention spreads across many positions; when one score is much higher, attention concentrates sharply:


The entropy values quantify this difference: higher entropy indicates more spread-out attention, while lower entropy indicates more concentrated attention. A well-trained model learns to produce focused attention when one input position is clearly relevant (e.g., translating a content word) and spread attention when multiple positions contribute (e.g., translating a phrase that spans multiple source words).
Aggregating Information: The Context Vector
We've now computed attention weights that tell us how much the decoder should attend to each encoder position. The final step is to use these weights to create a single vector that summarizes the relevant information from the entire input sequence. This is the context vector.
The context vector for decoder position is simply a weighted sum of the encoder hidden states:
where:
- : the context vector, a -dimensional summary of the relevant input information
- : the attention weight for encoder position (how much to attend to that position)
- : the encoder hidden state at position
- : the length of the source sequence
This formula is simple, but its implications are significant. Because the attention weights sum to 1, the context vector is a convex combination of the encoder states. It lies somewhere "between" them in the vector space, closer to the states with higher weights.
Consider what happens in different scenarios:
- Focused attention: If and all other weights are near zero, then . The context vector copies the encoder state at position 2.
- Distributed attention: If weights are spread across multiple positions, the context vector blends information from all of them. This is useful when the decoder needs information from multiple parts of the input.
- Uniform attention: If all weights are equal (), the context vector is the simple average of all encoder states, similar to a mean-pooling operation.


This geometric interpretation helps build intuition: the context vector "moves" through the encoder state space based on attention weights, getting pulled toward whichever states receive more attention. The model learns to position the context vector where it captures the most relevant information for the current generation step.
The key insight is that each decoder step gets its own context vector , computed fresh based on the current decoder state . This is the main improvement over standard encoder-decoder models: instead of forcing all information through a single fixed-size bottleneck, we dynamically select and aggregate the relevant parts of the input at each generation step.

Putting It All Together: The Complete Attention Mechanism
We've now developed all three components of Bahdanau attention:
- Scoring: measures relevance
- Normalization: converts scores to probabilities
- Aggregation: creates a weighted summary
But how does this attention mechanism integrate with the decoder RNN? The context vector contains a summary of the relevant input information, but the decoder also needs to know what it has generated so far and maintain its own internal state.
In Bahdanau's formulation, these three sources of information are combined by feeding them into the decoder RNN:
where:
- : the new decoder hidden state after processing step
- : the previous decoder hidden state (the decoder's "memory")
- : the embedding of the previous output token
- : the context vector from attention
- : a recurrent cell function (typically GRU or LSTM)
In practice, and are concatenated into a single vector of dimension before being fed to the RNN. This combines information about the previous prediction with the attention-weighted summary of the input.
The complete decoding process at step follows this sequence:
- Compute alignment scores: For each encoder position , calculate
- Normalize to attention weights: Apply softmax to get
- Compute context vector: Calculate
- Update decoder state: Compute
- Generate output: Predict the next token using (and often as well)
One subtle but important detail: attention is computed using the previous decoder state , not the current state . This makes sense because we need to know what the decoder is looking for before we can compute the context, and we need the context before we can update the decoder state.
