Bahdanau Attention
Bahdanau Attention (also called additive attention) is a mechanism introduced in 2015 that allows a neural sequence-to-sequence model to dynamically focus on different parts of an input sequence when producing each output token, breaking the bottleneck of compressing an entire source sentence into a single fixed-size vector. It matters because it was the first successful attention mechanism in deep learning, directly inspiring the self-attention at the heart of every modern Transformer. The counterintuitive fact: the "attention" weights are not hand-designed or rule-based — they are learned end-to-end purely from translation loss, yet they spontaneously align with human-interpretable linguistic structure.
Before Bahdanau Attention, seq2seq models forced the encoder to compress an arbitrarily long sentence into a single fixed-length vector — a catastrophic information bottleneck for long sequences. The key insight is: instead of reading that single summary vector, the decoder at each step computes a soft, differentiable query over all encoder hidden states simultaneously, producing a weighted context vector that highlights the most relevant source positions. The weights are computed by a small neural network (the alignment model) that scores compatibility between the current decoder state and each encoder state. Because everything is differentiable, the whole system — encoder, alignment network, decoder — trains jointly with backpropagation.
How It Works
The Encoder
A bidirectional RNN (typically a BiGRU) reads the source sequence . At each position , the forward and backward hidden states are concatenated to form an annotation vector:
Explanation: Each annotation captures local context around position from both directions, giving a richer representation than a unidirectional encoder. Here is the forward hidden state, the backward, and denotes concatenation, so .
The Alignment Model
At decoder time step , before running the decoder RNN, an alignment score measures how well source position matches the decoder's current search query (the previous decoder hidden state):
Explanation: This is a single-hidden-layer MLP that scores compatibility between the decoder's query and each encoder annotation — the "additive" structure is why this is called additive attention. Symbols:
- — previous decoder hidden state (the query)
- — encoder annotation at position (the key/value, conflated here)
- , U_a \in \mathbb{R}^^{k \times 2n} — learned projection matrices
- — learned scoring vector; is the attention dimensionality (hyperparameter)
Attention Weights
The raw scores are normalized across all source positions via softmax to produce a proper probability distribution:
Explanation: The weights sum to 1 over and represent how much "attention" the decoder pays to each source position when generating the -th output token.
Context Vector
The context vector is the attention-weighted sum of all encoder annotations:
Explanation: This is a soft, differentiable lookup — instead of hard-selecting one encoder state, the decoder reads a convex combination of all of them, parameterized by the learned alignment.
Decoder Step
The decoder RNN receives the context vector concatenated with the previous output embedding :
Explanation: Every decoder state update is conditioned on the dynamically computed context , so each output token has access to a fresh, task-relevant summary of the entire source sequence. The output distribution over the vocabulary is then .
PyTorch Implementation Sketch
```python import torch import torch.nn as nn import torch.nn.functional as F class BahdanauAttention(nn.Module): def __init__(self, encoder_dim: int, decoder_dim: int, attn_dim: int): super().__init__()
# W_a projects decoder query self.W_a = nn.Linear(decoder_dim, attn_dim, bias=False)
# U_a projects encoder annotations self.U_a = nn.Linear(encoder_dim, attn_dim, bias=False)
# v_a produces scalar scores self.v_a = nn.Linear(attn_dim, 1, bias=False) def forward( self, s_prev: torch.Tensor, # (batch, decoder_dim) h: torch.Tensor, # (batch, src_len, encoder_dim) ):
# Expand query to match src_len for broadcasting query = self.W_a(s_prev).unsqueeze(1) # (batch, 1, attn_dim) keys = self.U_a(h) # (batch, src_len, attn_dim)
# Additive (Bahdanau) score energy = self.v_a(torch.tanh(query + keys)) # (batch, src_len, 1) energy = energy.squeeze(-1) # (batch, src_len) alpha = F.softmax(energy, dim=-1) # (batch, src_len)
# Weighted sum of encoder hidden states context = torch.bmm(alpha.unsqueeze(1), h) # (batch, 1, encoder_dim) context = context.squeeze(1) # (batch, encoder_dim) return context, alpha ```
Dzmitry Bahdanau completed his graduate work at Jacobs University Bremen and conducted the research leading to additive attention while at the Université de Montréal under Yoshua Bengio's group. His 2015 ICLR paper "Neural Machine Translation by Jointly Learning to Align and Translate" (co-authored with Kyunghyun Cho and Bengio) introduced the alignment mechanism that shattered the fixed-vector bottleneck and set the trajectory toward the Transformer. Remarkably, the paper was first posted to arXiv in September 2014 and went through substantial revision before the conference — the attention visualization figures, showing diagonal alignment matrices that mirror human intuitions about word order, became among the most reproduced figures in all of deep learning.
Intuition
Imagine you are a professional human interpreter translating a long speech in real time. Rather than memorizing the entire speech in your head before uttering a single word, you glance back at the transcript — and for each word you are about to say, your eyes naturally jump to the most relevant section of the source. Translating "le chat" (French for "the cat"), you glance at "the cat"; translating "s'est assis" (sat down), your gaze drifts to "sat down." You are doing soft lookup with dynamic focus. Bahdanau Attention formalizes exactly this: the alignment model is the "eye movement," the attention weights are your gaze distribution across the transcript at each moment, and the context vector is the weighted excerpt your brain actually reads. The beautiful part is that nobody told the model which words correspond to which — it discovered that alignment purely by minimizing translation loss. One more analogy: think of the encoder annotations as a row of labeled file folders on a shelf, and as a fuzzy search query. The alignment network is the search engine; are the relevance scores; and is a blended summary document assembled from the top-ranked folders — with every folder contributing a little, weighted by relevance.