QuiddityML

By · 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.

The encoder turns source tokens w1, w2, w3 up to wT into hidden states h1, h2, h3 up to hT. Only hT becomes the context vector c that the decoder reads, and h1, h2 and h3 are marked unused.

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.

Four encoder states h_1 to h_4 all feed into an attention box, together with the current decoder state. Attention hands a different context, c_1, c_2 and c_3, to each decoder step.

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.

For the source the cat chased the mouse, decoder step 1 producing the subject cat reads mostly from the cat state, and decoder step 2 producing the verb chased reads mostly from the chased state. Both steps read all six states, and only the weights change.

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.

Top: a hard choice picks h3 alone with argmax. Bottom: soft attention gives h1 to h5 the weights 0.05, 0.10, 0.65, 0.15 and 0.05, which sum to 1.00, so every position contributes and larger weights contribute more.

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].

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.

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".

Raw scores 1, 2 and 3 for the, red and cat pass through softmax and become the attention weights 0.090, 0.245 and 0.665, with cat highlighted.

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.

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].

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:

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.

Output quality against source sentence length. The fixed context vector curve falls steeply as sentences get longer, and the with-attention curve stays higher and falls slowly.

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.

Decoder step 100 links to encoder position 1 in one hop through the weight alpha(100, 1), and the gradient flows straight back along the same link.

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.

Five RNN cells in a chain, each waiting for the hidden state of the one before. A timing chart shows the steps h1 to h5 running one after another with no overlap.

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:

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.