By Sagi Shaier · 9 November 2026 · 8 min read
What is attention in deep learning? Explained from the seq2seq bottleneck
Why an encoder-decoder that squeezes the whole input into one vector loses information, how attention builds a fresh weighted blend of every input position instead, worked through with three tokens and four-number vectors, and what attention still does not fix.
Attention is a way for a neural network to build each output from a weighted blend of all its input positions, with the weights computed again for every output. It was introduced to fix a weak spot in sequence-to-sequence models, which read one sequence and write another, as translation and summarization do. The same recipe is the core operation of transformers, the architecture behind current large language models. Models read tokens, which can be whole words or pieces of words, and this post uses short words as tokens to keep the examples small.
The bottleneck in sequence-to-sequence models
The classic sequence-to-sequence model is an encoder-decoder built from two recurrent neural networks (RNNs). An RNN reads a sequence one token at a time and keeps a hidden state, a vector of numbers it updates after each token. The encoder RNN reads the source sentence and produces one hidden state per token: $\mathbf{h}_1$ after the first token, $\mathbf{h}_2$ after the second, up to $\mathbf{h}_T$ after the last of $T$ tokens.
The decoder RNN writes the output, and it receives only the last of those states. That single vector $\mathbf{c} = \mathbf{h}_T$ is called the context vector, and it is the only bridge from the source sentence into the decoder.

That vector has the same size whether the source has five tokens or fifty. As the encoder keeps updating its state, information from the earliest tokens gets overwritten by what follows, so the final state leans toward the last few tokens. The squeeze into one fixed-size vector is called the bottleneck, and it hurts most on long inputs.
The fix: keep every encoder state
The encoder already built a separate state for every source token, and the earlier ones still hold information the decoder may need. Attention gives the decoder the whole row, $\mathbf{h}_1$ through $\mathbf{h}_T$, instead of only the last one. This version was introduced in 2014 and is called Bahdanau attention.

The decoder does not read one fixed summary of that row. At every output step it builds a fresh context vector $\mathbf{c}_s$ for the token it is about to write, where $s$ counts the output steps. When the decoder is about to write a subject it may need the source noun, and on the next step it may need the verb. The encoder states stay the same, but the decoder's own state changes, so the useful source positions change too.

Each read has three parts: compare the decoder's current state with every encoder state, turn those comparisons into weights, then blend the encoder states using the weights.
Soft weights instead of one pick
Attention usually does not pick a single source position. It gives every position a weight between 0 and 1, and the weights add up to 1. A large weight means that encoder state contributes more to this output step, and a small weight means it contributes less. This is called soft attention.

Soft weights also make attention trainable with ordinary gradient descent. A hard pick of the top position would ignore small changes in the scores and then jump from one position to another, so the loss would give no useful gradient. A weighted average changes smoothly when the scores change, so gradients flow back through the weights into whatever produced the scores. No dataset has to label which source token each output should read, and the model learns the weights from the task's loss.
Computing attention step by step
Take the source "the red cat" and suppose the encoder produced these 4-number states:
$$\mathbf{h}_{\text{the}} = [1, 1, 0, 0], \quad \mathbf{h}_{\text{red}} = [0, 1, 1, 0], \quad \mathbf{h}_{\text{cat}} = [0, 0, 2, 1]$$
A decoder without attention would read only $\mathbf{c} = \mathbf{h}_{\text{cat}} = [0, 0, 2, 1]$, and anything about "the" or "red" would have to be packed into that one vector.
![The source tokens the, red and cat have encoder vectors [1, 1, 0, 0], [0, 1, 1, 0] and [0, 0, 2, 1]. A fixed-vector decoder receives only the last one, c = h_cat = [0, 0, 2, 1].](images/fixed_vector_tiny_example.png)
Now suppose the decoder's current state is $\mathbf{h}^{\text{dec}} = [1, 0, 2, -1]$.
Step 1: score each source token
A score function gives one number per source token that says how well that encoder state matches what the decoder needs now. The simplest one is the dot product: multiply the matching entries of two vectors and add the results.
$$e_{\text{the}} = 1\cdot1 + 0\cdot1 + 2\cdot0 + (-1)\cdot0 = 1$$
$$e_{\text{red}} = 1\cdot0 + 0\cdot1 + 2\cdot1 + (-1)\cdot0 = 2$$
$$e_{\text{cat}} = 1\cdot0 + 0\cdot0 + 2\cdot2 + (-1)\cdot1 = 3$$
![The decoder state [1, 0, 2, -1] is compared with each encoder vector, giving the raw scores e_the = 1, e_red = 2 and e_cat = 3.](images/dot_product_scoring_example.png)
These are raw scores. They can be any real number, negative or positive, and they do not add up to anything in particular.
Step 2: turn scores into weights with softmax
Softmax turns a list of scores $e_1, \ldots, e_T$ into weights that are positive and add up to 1. Each weight $\alpha_t$ is the exponential of its score divided by the sum of the exponentials of all the scores:
$$\alpha_t = \frac{\exp(e_t)}{\sum_{t'=1}^{T} \exp(e_{t'})}$$
For the scores $[1, 2, 3]$ the exponentials are about $2.72$, $7.39$ and $20.09$, which add up to $30.19$. Dividing each by the total gives:
$$\text{softmax}([1, 2, 3]) = [0.090, 0.245, 0.665]$$
At this decoder step, about 66.5% of the attention goes to "cat", 24.5% to "red" and 9.0% to "the".

Step 3: blend the encoder states
The context vector is the weighted sum of the encoder states:
$$\mathbf{c}_s = 0.090\,\mathbf{h}_{\text{the}} + 0.245\,\mathbf{h}_{\text{red}} + 0.665\,\mathbf{h}_{\text{cat}}$$
Going one entry at a time, the first entry is $0.090 \cdot 1 = 0.090$. The second is $0.090 \cdot 1 + 0.245 \cdot 1 = 0.335$ and the third is $0.245 \cdot 1 + 0.665 \cdot 2 = 1.575$. The fourth is $0.665 \cdot 1 = 0.665$:
$$\mathbf{c}_s = [0.090, 0.335, 1.575, 0.665]$$
![The weights 0.090, 0.245 and 0.665 multiply h_the, h_red and h_cat, and the sum is c_s = [0.090, 0.335, 1.575, 0.665], built one dimension at a time.](images/weighted_sum_tiny_attention_context.png)
Both decoders still receive one context vector. The fixed one is $[0, 0, 2, 1]$, the final state alone. The attention one leans toward "cat", which had the highest score, and also carries controlled contributions from "red" and "the".
![Left, without attention: the context vector is h_cat = [0, 0, 2, 1]. Right, with attention: the three states are weighted by 0.090, 0.245 and 0.665 and summed into [0.090, 0.335, 1.575, 0.665].](images/fixed_vs_attention_context_vectors.png)
For a source of any length $T$ at decoder step $s$, the three steps are:
$$e_{s,t} = \text{score}(\mathbf{h}^{\text{dec}}_s, \mathbf{h}_t)$$
$$\alpha_{s,t} = \frac{\exp(e_{s,t})}{\sum_{t'=1}^{T} \exp(e_{s,t'})}$$
$$\mathbf{c}_s = \sum_{t=1}^{T} \alpha_{s,t}\,\mathbf{h}_t$$
The decoder then combines $\mathbf{c}_s$ with its own state to predict the next token, moves one step forward and repeats the whole read.
The same attention step in PyTorch
In PyTorch the three steps are three lines once the tensors have the right shapes. Here torch.bmm is a batched matrix multiply, and the batch holds one example:
1import torch
2import torch.nn.functional as F
3
4# one decoder state and three encoder states for "the red cat", batch of 1
5decoder_state = torch.tensor([[[1., 0., 2., -1.]]]) # (1, 1, 4)
6encoder_states = torch.tensor([[[1., 1., 0., 0.], # the
7 [0., 1., 1., 0.], # red
8 [0., 0., 2., 1.]]]) # cat, (1, 3, 4)
9
10scores = torch.bmm(decoder_state, encoder_states.transpose(1, 2)) # (1, 1, 3)
11weights = F.softmax(scores, dim=-1) # (1, 1, 3)
12context = torch.bmm(weights, encoder_states) # (1, 1, 4)
13
14print(scores)
15print(weights.round(decimals=3))
16print(context.round(decimals=3))1tensor([[[1., 2., 3.]]])
2tensor([[[0.0900, 0.2450, 0.6650]]])
3tensor([[[0.0900, 0.3350, 1.5750, 0.6650]]])The first bmm takes the dot product of the decoder state with each encoder state, which is why the encoder states are transposed to shape (1, 4, 3). F.softmax(scores, dim=-1) normalizes over the last axis, the source positions. The second bmm multiplies the (1, 1, 3) weights by the (1, 3, 4) states, which is the weighted sum. If the weights do not add up to 1 per row, check the dim passed to softmax first.
Other ways to score
The dot product has no learned parameters and needs the decoder and encoder states to have the same width. Two other score functions are common:
- Bilinear (also called multiplicative): $e = \mathbf{h}^{\text{dec}} \mathbf{W} \mathbf{h}^{\text{enc}}$. The learned matrix $\mathbf{W}$ maps between the two spaces, so the two states can have different widths.
- Additive, the form in Bahdanau's original paper: $e = \mathbf{v}^\top \tanh(\mathbf{W}[\mathbf{h}^{\text{dec}}; \mathbf{h}^{\text{enc}}])$. It joins the two states into one longer vector, runs a small learned network on it and projects the result to one number.
After the scores, every version does the same softmax and weighted sum.
What attention fixes, and what it does not
Attention removes the single-vector bottleneck. Each decoder step can put weight on any source position, so early tokens stay directly reachable after the encoder has read the rest of the sentence. The gain shows most on long inputs.

It also shortens the path between distant positions. Without attention, source token 1 can affect output token 100 only through a long chain of recurrent updates. With attention, output step 100 can put weight on source position 1 directly, and during training the loss gets a short route back to that encoder state.

Attention does not remove the recurrence. The encoder and decoder are still RNNs, and each hidden state needs the one before it. A batch can process many sentences side by side, but inside one sentence the model still goes one position at a time, left to right.

Transformers take the next step: they drop the recurrence and let attention between positions do the work the recurrent chain used to do. How transformers work builds that architecture from here.
When attention helps, and common mistakes
Attention helps most when the output depends on specific parts of a long input, as in translating long sentences or summarizing documents. On short inputs a fixed context vector can hold enough, and the gain is smaller.
Mistakes that come up often:
- Using raw scores as weights. Scores can be negative and do not add up to 1. Softmax comes first.
- Running softmax over the wrong axis. The weights for one decoder step have to be normalized over the source positions, the last axis in the code above.
- Using dot-product scores with mismatched widths. A 512-number decoder state cannot be dotted with a 256-number encoder state. A bilinear or additive score handles different widths.
- Expecting attention to make an RNN parallel. It changes how each output step reads the source. The decoder still writes one token at a time.
Related concepts
Encoder-decoder models explains the architecture attention was added to, and recurrent neural networks explains the hidden state that gets overwritten. Text generation tasks covers translation and summarization, the tasks where the bottleneck showed first. In a transformer the same score, softmax and weighted-sum recipe runs between all positions of one sequence. That is called self-attention.
QuiddityML teaches attention over three concepts in the Intro to NLP track. The exercises on them include putting the three parts of an attention step in order, turning the softmax and weighted-sum equations into PyTorch, and writing the attention function from scratch.