The challenge: transforming one sequence into another
Many problems in AI involve transforming one sequence into another of a different length. A few examples:
- Translation: "Le chat noir dort" β "The black cat sleeps" (4 words β 4 words, but it could have been 3 or 5)
- Summarization: a 500-word article β a 30-word summary
- Dialogue: a question β a response of unpredictable length
- Transcription: a 10-second audio sequence β an 8-word sentence
The fundamental problem: the input and output don't have the same length, and there is no obvious word-to-word correspondence. A standard Recurrent Neural Network (RNN, see RNN: sequences and memory) produces an output at each time step, which works when input and output are synchronized. But for translation? Word order changes, words are added or removed, grammar is different.
A new architecture was needed. Enter the sequence-to-sequence, or seq2seq, model.
The attention described here is the 2014 version: a module bolted onto an RNN. It is the direct ancestor of the transformer's attention, but it is not the same thing, the transformer dropped the RNN and had the attention apply from a sequence onto itself. That version is covered in Self-attention; this page does not re-explain it.

Encoder-Decoder: two networks, one bridge
The idea (2014, Sutskever, Vinyals and Le at Google)
Sequence to Sequence Learning with Neural Networks (Sutskever et al., 2014)The seq2seq architecture separates the problem into two distinct parts handled by two different networks:
The encoder: reads the source sequence word by word and compresses it into a fixed-size vector called the context vector. Concretely, this is the last hidden state of the encoder, an LSTM (Long Short-Term Memory, a gated RNN, see LSTM and GRU). This vector is supposed to capture the entire "meaning" of the source sentence.
The decoder: takes this context vector as a starting point and generates the target sequence autoregressively, that is, word by word, using each generated word as input to predict the next one.
Step-by-step walkthrough
Let's take a concrete example of French β English translation:
- The encoder (an LSTM) processes "Le chat noir dort" token by token, updating its hidden state at each word
- The encoder's final hidden state = the context vector = a compressed summary of the entire source sentence
- This vector initializes the decoder's hidden state
- The decoder receives a special <START> token as input
- It predicts the first word: "The"
- "The" is fed back as input, the decoder predicts "black"
- "black" β predicts "cat", "cat" β predicts "sleeps"
- The decoder stops when it predicts the <END> token
It's elegant: the encoder "understands" the source, the decoder "writes" the target. The two are connected by a single vector.
A detail that seems trivial but matters: the order in which you present data to a seq2seq model changes its performance. Vinyals and colleagues showed that even for tasks where the input is a set (a collection with no natural order, like a basket of items to sort), the order in which you present it counts. So the model is not order-agnostic, and picking a good ordering can weigh as much as the architecture itself.
Order Matters: Sequence to Sequence for Sets (Vinyals et al., 2015)Everything the encoder understood about "Le chat noir dort sous la grande table en bois massif" must fit into a single vector of 500 or 1000 dimensions. For a short sentence, that's fine. For an entire paragraph? The first words get "forgotten" in favor of the last ones. It's like trying to summarize an entire book in a single sentence: details are inevitably lost. This bottleneck is the fundamental problem of seq2seq without attention, and it's exactly what attention will solve.
Bahdanau Attention (2014)
The revolutionary insight
Bahdanau had a simple but profound idea: instead of forcing all the information through a single vector, let the decoder look directly at the source sequence at each generation step.
The metaphor is natural: when you translate a sentence, you don't memorize the entire sentence first before starting to write. You consult the source text as you go. To translate "noir", you look at the corresponding word in the source. To translate "dort", you look at a different place.
That's exactly what the attention mechanism does: at each word the decoder generates, it "looks at" all the encoder's hidden states and decides which ones are most relevant for its current prediction.
Neural Machine Translation by Jointly Learning to Align and Translate
Mathematics of attention
At each decoding step , the attention mechanism computes four things:
1. Alignment scores: for each source word , we compute a score indicating its relevance:
Every symbol: is the generation step (the output word currently being produced); indexes a word of the source sentence; is the decoder's state at the previous step; is the state the encoder produced when it read source word ; and is a small neural network, called the "attention model". The result is a single number. It answers the question: "how important is source word for the word I'm about to produce?"
2. Attention weights: raw scores are not comparable to each other, so we normalize them with a softmax:
Every symbol: (the Greek letter alpha) is the final weight given to source word ; is the exponential function, which makes every number positive while amplifying the gaps between them; is a dummy index running over all source words, so the in the denominator is the sum of the exponentials of all the scores.
In one sentence: make every score positive, then divide each one by their total, which guarantees the weights sum to exactly 1. What you get is an allocation of attention: "I'm looking 70% at the word 'noir', 20% at 'chat', 10% at 'dort'".
3. Context vector: compute an average of the encoder's states, weighted by those weights:
In one sentence: take a little of every source word, in proportion to the attention it gets, and add it all into a single vector. Since the weights sum to 1, if one weight is 1 and all others are 0, the context vector is exactly that one word's state.
This is a selective extraction: instead of compressing everything once and for all into a fixed vector, you build a context vector that is different at each step, focused on the relevant parts of the source. This is the heart of the innovation.
4. Prediction: the context vector is combined with the decoder state to predict the next word. The decoder now has a targeted view of the source, on top of its own internal state.
In everything above, exactly one thing is learned: the weights of the small network (spelled out just below). They are tuned during training, then frozen.
Everything else (the scores , the attention weights , the context vector , the states and ) is computed on the fly for the sentence being translated, then discarded. Put differently, the model does not learn "the word noir corresponds to the word black"; it learns a way of comparing two states, and it is that comparison, applied to the sentence at hand, that produces the alignment. Which is why the same model can align sentences it has never seen.
The attention weights naturally form a heatmap when displayed: one cell per (source word, produced word) pair, brighter the larger the weight. For translation, you can literally see the alignments: when the decoder generates "black", it looks at "noir"; when it generates "the", it looks at "le". And all of this without supervision: nobody ever gave it word correspondences, only sentence pairs. Bahdanau's paper presents exactly such maps and notes that the alignments obtained agree with intuition. These visualizations did a lot for attention's success: for the first time, you could "see" what the model was doing.
Bahdanau's additive attention
Bahdanau's specific implementation uses a small neural network to compute the scores:
Every symbol: and are two matrices that transform the decoder state and the encoder state respectively, bringing them into a common space where they are comparable; squashes the result between -1 and 1 and supplies the non-linearity that makes a genuine small network; is a vector, and the superscript means "transposed", which here has a precise effect: times a vector yields a single number, the score we were after.
Those three (, and ) are the learned parameters mentioned above, and the only ones in the whole mechanism.
This formula is called "additive" attention because the two transformations are added before the tanh rather than multiplied by one another. It's more expressive than a plain dot product, since the attention network has parameters of its own, but also more expensive: there is a matrix multiplication to do for every (source word, decoding step) pair.
Luong Attention (2015): simplified variants
A year after Bahdanau, Luong proposes simpler and faster variants.
Effective Approaches to Attention-based Neural Machine Translation (Luong et al., 2015)Dot-product attention
Just the dot product (its definition) between the decoder state and the encoder state: multiply the two vectors slot by slot and add it all up, which gives a number. No extra parameters, no dedicated attention network. Extremely fast. The intuition: two vectors pointing in the same direction have a high dot product, hence a high attention score. The similarity computation here is free, in the sense that it has nothing to learn, but for the same reason it cannot adapt.
General attention
A compromise: before the dot product, the encoder state passes through a learned weight matrix . More expressive than the bare dot product, less costly than Bahdanau's additive attention.
Bahdanau vs Luong
| Aspect | Bahdanau | Luong |
|---|---|---|
| Decoder state used | (previous step) | (current step) |
| Attention model | Additive (neural network) | Dot-product or general |
| Extra parameters | More numerous | Fewer |
| Speed | Slower | Faster |
In practice, performance is close. Luong is more efficient and simpler to implement, which explains its popularity. And it is this dot-product form that served as the basis for the transformer: its scaled dot-product attention is the same idea, with a division by the square root of the dimension to keep the values stable. The detail is in Self-attention.
Attention is the most influential contribution of this period. Its evolution:
- 2014: helper mechanism in a seq2seq model (Bahdanau), a complement to the RNN
- 2015: simplified variants (Luong), dot-product attention emerges
- 2017: central and sole mechanism of the transformer, no more RNN at all
The title of the transformer paper, "Attention Is All You Need", summarizes this trajectory. We went from "attention helps RNNs" to "attention replaces RNNs".
Pointer Networks: when the output vocabulary is the input itself
An elegant extension of attention in the seq2seq framework: Pointer Networks. Instead of generating words from a fixed vocabulary, the decoder uses the attention mechanism to point at a position in the input sequence. The attention weights no longer weight an average: they are the answer, since answering here means picking one input element. This is useful for combinatorial problems like sorting, shortest path search, or convex hull, where the "right answer" is a rearrangement of the input elements, not a dictionary word.
Pointer Networks (Vinyals et al., 2015)Global vs local attention
Global attention: the decoder looks at all the words of the source sequence at each step. This is the default approach. Write for the source sentence length and for the translation length. At every word produced you must compute one score for each of the source words, and there are words to produce: the number of scores to compute is therefore . The notation (read "on the order of times ") expresses that proportionality while ignoring constant factors (see Computational complexity). Doubling the length of both sentences quadruples the work.
Local attention: the decoder only looks at a window of words around an estimated position, instead of the whole source. Less expressive but faster, especially on long sequences. It's a precursor of the sliding window attention mechanisms found in architectures built for long documents, such as Longformer (see Context extension).
For sentences of reasonable length, global attention is enough. For documents of thousands of tokens, windowed variants become necessary.
Why this matters
Bahdanau attention is one of the most influential concepts in the history of deep learning. Understanding this mechanism gives you:
- The foundations of the transformer: its self-attention is a direct generalization of what is described here, see Self-attention.
- The "query, key, value" vocabulary: in Bahdanau attention the decoder state plays the query ("what I'm looking for"), and the encoder states serve as both keys ("what the query is compared against") and values ("what you retrieve when it matches"). The transformer merely separated those three roles explicitly.
- A general principle: "selectively looking at what's relevant" appears everywhere, spatial attention in vision, attention over graphs, cross-attention in multimodal models such as CLIP.
The legacy
- Machine translation: this is the starting point of neural translation as we know it. Watch the exact wording, which is often overstated: Bahdanau's paper claims quality comparable to the best phrase-based statistical system of the time, not better. The measure used is the BLEU score (BiLingual Evaluation Understudy), which automatically compares a produced translation against one or more reference translations by counting the word sequences they share, the higher the score, the closer the match. Clearly beating statistical systems came later, with the production neural systems deployed from 2016 onward.
- Self-attention: when a sequence applies attention to itself, you get the foundation of the transformer.
- Attention in other domains: spatial attention in computer vision, attention over graphs.
- Multimodal: cross-attention between text and images in CLIP and image generation models.
Before attention: "compress the entire input into a single vector, then generate from that summary". After attention: "consult the source directly at each step, focusing on what's relevant". This is a fundamental paradigm shift: from blind compression to selective access. That's why all modern models use attention in one form or another.
Final summary
Seq2seq = an encoder that understands the source, plus a decoder that generates the target. The problem: everything used to pass through a single vector, so long sentences were lost from the start. Attention solves this by letting the decoder consult the encoder at each step, weighting what it finds there. Bahdanau invented it in additive form, Luong simplified it to a dot product, and the transformer generalized it into self-attention. It's the fundamental building block of everything that transforms sequences today: translation, summarization, dialogue, code generation.
1. What is the fundamental problem of seq2seq without attention?
2. Concretely, what does Bahdanau's attention mechanism change compared to plain seq2seq?
3. In the attention mechanism, what exactly is learned during training?
4. Did Bahdanau's system beat the statistical translation systems of its day?
5. In the query/key/value vocabulary the transformer inherited, which role does the decoder state play in Bahdanau attention?