Introduction
Many tasks take a sequence as input and produce a sequence as output, where the output need not have the same length as the input. Machine translation is the canonical example: the English sentence “I love you” is three tokens long, and the Spanish translation “te quiero” is two. The same applies to summarization (a long document to a short summary), dialogue (a question to an answer), and image captioning (an image to a sentence). Tasks of this kind are called sequence-to-sequence problems.
A sequence-to-sequence problem maps an input sequence to an output sequence. Many modern architectures solve these tasks with only a decoder block. The classical formulation used an encoder block to encode the input sequence and a decoder block to generate the output sequence, and that encoder-decoder architecture is the one we focus on here. The input is a sequence of $T$ tokens, $x_1, \dots, x_T$. Each block is a recurrent network formed by unrolling the same recurrent cell once per token, and we refer to this recurrent unit as the cell.
Encoder block. The encoder reads the input tokens one at a time. At each timestep it updates its hidden state from the current input token and the hidden state of the previous timestep, using the recurrent cell’s update rule:
$$ h_t = \mathrm{cell}(h_{t-1}, x_t) $$The encoder is unrolled over all $T$ tokens, so it produces a hidden state at every timestep, $h_1, \dots, h_T$. The hidden state of the final timestep, $h_T$, summarizes the whole input. It is passed to the decoder as the context vector $c = h_T$.
Decoder block. The decoder produces the output $y_1, \dots, y_{T_y}$ one token at a time, in an autoregressive manner: the token it produces at timestep $t-1$ becomes the input at timestep $t$. Its first hidden state is seeded from the context, $s_0 = c$. At each timestep it takes the context vector and the token produced at the previous timestep, and emits the next token:
$$ \begin{aligned} s_t &= \mathrm{cell}(s_{t-1}, \left[ y_{t-1}; c \right]) \\\\ p(y_t \mid y_{ \lt t}) &= \mathrm{softmax}(W_o s_t + b_o) \end{aligned} $$The decoder stops generating when it emits a special end-of-sequence token <EOS>. The encoder and the decoder use the same recurrent unit, but they do not share weights, since each block has its own parameters.
Two quantities cross the boundary from the encoder to the decoder:
- the initial decoder hidden state $s_0$, derived from the final encoder state,
- the context vector $c$, read at every decoding timestep.
In this setup the two quantities are the same vector. The context vector is the final encoder hidden state, $c = h_T$, and the initial decoder state is seeded from it, $s_0 = c$. The encoder’s final hidden state therefore serves two roles in the decoder: it sets the initial decoder state, and it is read as the fixed context at every step.
While this works for short sequences, for long sequences the entire input is compressed into a single context vector. It is unrealistic to expect one fixed-size vector to retain all the information in a long input sequence. The input has $T$ positions, and all of them must fit into $c$, which has a fixed dimensionality. Whether the input is a paragraph, a document, or a whole book, the model must compress arbitrarily long content into that fixed number of dimensions. The limitation concerns the input positions, not time: a recurrent unit already handles the sequential dimension by unrolling across the tokens, but it does not address compressing all $T$ positions into one vector.
To address this, the decoder computes a new context vector at every timestep instead of reusing one. The decoder builds a representation of the input that is specific to the token it is about to generate. Rather than compressing the whole input into one vector, it weights each hidden state of the encoder by its relevance to the current output and combines them into a fresh context vector. This weighting procedure is called the attention mechanism.
The attention mechanism
Given an input sequence of $T$ tokens, $x_1, \dots, x_T$, the encoder block processes the sequence one token at a time. At every input position it emits a hidden state, $h_1, \dots, h_T$, where each $h_i \in \mathbb{R}^{d_e}$. The final hidden state seeds the decoder’s first hidden state, $s_0 = h_T$.
The decoder generates the output one token at a time. At each timestep it consumes a context vector and the token it produced at the previous step, $y_{t-1} \in \mathbb{R}^{d_y}$. At the first timestep there is no previous token, so it reads a special start token instead. The context vector is fixed for the whole generation, so a single vector of fixed size must represent the entire input, and it cannot carry all the information in a long sequence. To remove that bottleneck, the decoder is augmented with an attention mechanism that recomputes a fresh context vector at each timestep, rather than reusing the one fixed vector from the encoder. The attention mechanism forms that context vector in three steps.
The alignment function
At each timestep the decoder must decide how much to rely on each position of the input sequence. The alignment function outputs, for every encoder hidden state $h_i$, a score that tells the decoder how relevant that input position is to the output token it is about to produce. Each score is computed against the decoder’s hidden state from the previous timestep, $s_{t-1}$, producing a scalar:
$$ e_{t,i} = f_{\mathrm{att}}(s_{t-1}, h_i) $$Here $t$ indexes the decoder timestep, the position of the token the decoder is about to produce, and $i$ indexes the positions of the input sequence, running over $i = 1, \dots, T$. The score $e_{t,i}$ therefore relates input position $i$ to the decoder step $t$: it is the relevance score that input position $i$ receives when the decoder is about to produce its $t$-th output token.
A common choice for $f_{\mathrm{att}}$ is a small fully-connected network. The additive form introduced by Bahdanau et al. is
$$ \begin{aligned} e_{t,i} &= v^{\mathsf{T}} \cdot \tanh\!\left(W \cdot h_i + U \cdot s_{t-1}\right) \end{aligned} $$with $W \in \mathbb{R}^{d_a \times d_e}$, $U \in \mathbb{R}^{d_a \times d}$ and $v \in \mathbb{R}^{d_a}$, where $d_a$ is the attention dimension, $d_e$ is the encoder hidden size and $d$ is the decoder hidden size. The product $W \cdot h_i$ projects the encoder state $h_i \in \mathbb{R}^{d_e}$ into the $d_a$-dimensional attention space, and $U \cdot s_{t-1}$ projects the decoder state $s_{t-1} \in \mathbb{R}^{d}$ into the same space, so the two combine. The $\tanh$ blends them, and $v^{\mathsf{T}}$ reduces the $d_a$-dimensional result to the scalar score $e_{t,i}$.
The alignment uses $s_{t-1}$, not the current state $s_t$. The context vector $c_t$ is needed to produce $s_t$, so it must be formed from the decoder state that already exists at the start of the timestep. For a given decoder timestep, one score $e_{t,i}$ is computed for each of the $T$ input positions, giving $T$ scores at that decoder step.
From scores to attention weights
Each score $e_{t,i}$ is a scalar produced by the alignment function, one for every input position. It measures how relevant input position $i$ is to the token the decoder is about to produce. The scores are unnormalized: nothing constrains their sign or magnitude, so each can take any real value. A softmax over the $T$ input positions converts them into weights:
$$ a_{t,i} = \frac{\exp(e_{t,i})}{\sum_{i'=1}^{T} \exp(e_{t,i'})} $$These weights $a_{t,i}$ lie in $(0, 1)$ and sum to $1$ over the input positions, so they form a probability distribution over the encoder states. The attention weight $a_{t,i}$ is the amount of encoder state $h_i$ that contributes to the context for the token at decoder step $t$. This is a normalized weighting of the input positions, not a probability over output tokens.
The context vector
The context vector is the weighted sum of the encoder hidden states:
$$ c_t = \sum_{i=1}^{T} a_{t,i} h_i $$Each $h_i$ is $d_e$-dimensional, and the weights are non-negative and sum to $1$, so $c_t \in \mathbb{R}^{d_e}$ is a convex combination of the encoder states. A different combination is built for each decoder timestep, so the decoder shifts its attention across the input as it generates the output.
The decoder with attention
The decoder cell updates its hidden state from its previous state and a concatenation of the previous output token and the context vector:
$$ s_t = \mathrm{cell}(s_{t-1}, \left[ y_{t-1}; c_t \right]) $$The original attention paper used a gated recurrent unit; the mechanism is independent of the cell.
Attention does not remove the sequential dependency of the decoder. It adds a second, indirect channel through which the decoder history shapes the current context. The context $c_t$ depends on $s_{t-1}$ through the alignment, and $s_{t-1}$ in turn depends on $c_{t-1}$, which depends on $s_{t-2}$, and so on. The decoder therefore still depends on its own past, and attention adds this dependency on top of the direct recurrence in the cell rather than removing it.
Learning the alignments
Everything above is differentiable. The alignment function, the softmax and the weighted sum all sit inside the computational graph, so the loss flows back through them into the parameters of the encoder, the decoder, and the attention network.
The model is not told which input positions to attend to. There is no supervision on the alignment weights. The whole network is optimized jointly toward the translation loss, and it discovers the alignments on its own. This is the essential point of the mechanism: it is a soft, learned, content-based selection, not a hard, supervised segmentation.
A side benefit is interpretability. Once trained, the attention weights for all (output, input) pairs form an alignment matrix that can be inspected. Reading it reveals which input words the model relied on for each output word, which makes the translation more understandable, and often reflects genuine linguistic correspondences.
Conclusion
Attention solves the problem that remains after the recurrent encoder-decoder. A recurrent model handles the temporal dimension but it doesn’t address the compression across positions. The encoder must still fit the whole input into one fixed vector, and the decoder reuses that vector at every time-step. Attention removes this. At each decoding step it builds a fresh context vector as a weighted sum of all encoder states, the weights being a softmax over a learned compatibility score between the current decoder state and each encoder state. Every input position becomes reachable in principle from any output position via a learned soft selection, so the input is no longer squeezed into a single vector, and the path from an output to an input position is direct rather than a chain through the full encoder recurrence.
This attention is a cross-attention between the decoder and the encoder, still built on a recurrent model. The encoder continues to run recurrently. Attention simply lets the decoder consult the full set of encoder states instead of a single summary vector. It sits between a Recurrent Network and the Transformer. From a recurrent network it keeps the recurrence and the sequential decoder. Recurrence is what handles the temporal dimension, and gated cells such as the LSTM and the GRU keep the gradient from vanishing along the sequence. What the recurrence does not address is the compression across positions, and that is what attention adds.
Attention also introduces the abstraction the Transformer builds on. The mechanism separates into a query, a set of keys and values, and a similarity function, all of which are independent of the recurrent cell. Carrying that abstraction further, the recurrence is removed entirely, a sequence attends to itself with self-attention, and attention becomes the primary computational building block on which all modern architectures depend. That is the Transformer.
References
- Justin Johnson, Lecture 13: Attention, EECS 498-007/598-005 Deep Learning for Computer Vision, University of Michigan (2020).
- Bahdanau, Cho & Bengio, Neural Machine Translation by Jointly Learning to Align and Translate (2014).
- Cho et al., Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation (2014).
- Sutskever, Vinyals & Le, Sequence to Sequence Learning with Neural Networks (2014).
- Vaswani et al., Attention Is All You Need (2017).
- Dive into Deep Learning, 11. Attention Mechanisms and Transformers.
- PyTorch
torch.nn.MultiheadAttention.