Attention Mechanism in NLP
Imagine translating a 40-word French sentence into English. Only a single fixed-size vector represents the entire source sentence. This was the situation faced by early sequence-to-sequence translation systems. It failed badly on long sentences. Performance dropped sharply as sentence length grew. A fixed vector simply cannot hold arbitrarily much information. The The Encoder-Decoder Architecture compresses an entire input into one context vector. This vector is handed once to the decoder. The decoder must then generate every output word from that single compressed summary. Attention solves this by letting the decoder look back at the entire sequence of encoder states. It does this at every decoding step, rather than relying on one bottleneck vector. Instead of compressing everything upfront, the model learns something different. It computes a weighted combination of source representations that is specific to the current decoding step. This is effectively a soft, differentiable lookup table over the input. This single idea was introduced for Neural Machine Translation. It was later generalized into the Transformer's self-attention. It is arguably the most consequential architectural innovation in modern NLP. The big picture is this: attention replaces a fixed bottleneck with a dynamic, content-based addressing mechanism. At each step, the model asks "which parts of the input are relevant right now?" It answers with a probability distribution over input positions. This distribution is computed from learned similarity scores. This distribution is used to build a context vector as a weighted average of encoder states. This is a soft alignment between output and input tokens. It is learned end-to-end via gradient descent. There is no explicit supervision about which words align to which. This article develops the mechanism precisely. It covers how alignment scores are computed (additive and dot-product variants). It covers how they are normalized and used. It explains why the resulting gradients flow better than through a single bottleneck. It also shows where this exact machinery reappears — scaled and generalized — inside self-attention. This includes Contextual Embeddings such as those produced by Transformer encoders.
- Attention replaces a single fixed context vector with a weighted sum of all encoder hidden states, recomputed at every decoder step.
- Alignment scores measure similarity between the decoder's current query and each encoder state (key); two classic scorers are additive (Bahdanau) and dot-product (Luong).
- A softmax turns scores into a probability distribution (attention weights) that sums to 1 over source positions.
- The context vector is the weighted average of encoder states using these weights — a differentiable, learned "soft alignment."
- Attention fixes the encoder bottleneck: gradients can flow directly to any input position, not just through one compressed vector.
- This exact query/key/value machinery, generalized and made self-referential, becomes the core of the Transformer architecture used in nearly all modern LLMs.
Attention lets a model compute, at each output step, a learned probability distribution over input positions and use it to build a custom-weighted summary of the input — replacing one fixed bottleneck vector with many, context-specific ones.
The idea
In the plain encoder-decoder model, an encoder (typically an RNN or LSTM) reads the source sequence and produces a final hidden state , which serves as the sole summary — the context vector — passed to the decoder. Every output token is generated conditioned on this same fixed , regardless of what part of the input is actually relevant to producing . This is the bottleneck problem: information about all input tokens must be squeezed through one vector of fixed dimensionality, and the squeeze gets worse as grows.
Attention removes this bottleneck by keeping all encoder hidden states around, and computing, at each decoder timestep , a fresh context vector that is a weighted combination of them:
The weights (the attention weights) form a probability distribution over source positions (, ), computed from a learned alignment score between the decoder's current state and each encoder state, normalized by a softmax:
The terminology, later standardized by the Transformer paper, casts this as a query/key/value lookup: the decoder state is the query , each encoder state serves as both a key (used to compute the score) and a value (used to build the weighted sum). In the vanilla recurrent-attention setting, keys and values are literally the same vectors ; in self-attention they are separately learned linear projections of the same input. Two scoring functions dominate the literature. Additive attention (Bahdanau et al., 2015) computes the score with a small feedforward network:
Dot-product attention (Luong et al., 2015) computes it more cheaply as an inner product, optionally scaled or bilinear:
Dot-product attention is computationally cheaper (a matrix multiply versus a feedforward pass per pair) and becomes, with a scaling factor, the scaled dot-product attention at the heart of the Transformer. Additive attention can perform better with high-dimensional or dissimilar query/key spaces since it learns a full bilinear-like interaction rather than relying on raw dot products, but at higher parameter and compute cost per pair.
How it works
Attention is computed fresh at every decoder timestep. The core loop, for a recurrent encoder-decoder with attention (Bahdanau-style), proceeds as follows.
Step 1 — Encode. Run the encoder (often bidirectional) over the source sequence to obtain hidden states , one per source token. These are stored and reused at every decoding step — this is the key departure from the bottleneck model.
Step 2 — For each decoder step : 1. Form the query from the decoder's current state, e.g. (previous decoder hidden state). 2. Compute alignment scores between and every encoder state , using additive or dot-product scoring. 3. Normalize with softmax to get attention weights . 4. Compute the context vector . 5. Feed (concatenated with the previous output embedding) into the decoder RNN cell to get the new hidden state . 6. Use (and often again) to predict the output distribution over the vocabulary for . Because is recomputed at every step from a fresh weighting over all encoder states, the decoder can "look at" different parts of the input as it generates different output words — exactly the soft alignment a human translator performs mentally. ``` function ATTENTION_DECODE(source_tokens, target_vocab, encoder, decoder, scorer):
# Step 1: Encode once H = encoder.forward(source_tokens) # H = [h_1, ..., h_n], each h_i in R^d n = length(H) s = decoder.init_state() # s_0 : initial decoder hidden state y_prev = START_TOKEN outputs = [] for t in 1 .. MAX_LEN:
# Step 2.1: form query from current decoder state q = s
# Step 2.2: compute alignment scores against every encoder state e = zeros(n) for i in 1 .. n: e[i] = scorer(q, H[i]) # additive or dot-product scoring
# Step 2.3: normalize to a probability distribution alpha = softmax(e) # alpha[i] >= 0, sum_i alpha[i] = 1
# Step 2.4: weighted sum -> context vector c = zeros(d) for i in 1 .. n: c = c + alpha[i] * H[i]
# Step 2.5: advance the decoder, conditioned on context + previous output s, logits = decoder.step(s, y_prev, c)
# Step 2.6: predict next token y_t = argmax_or_sample(softmax(logits)) outputs.append(y_t) if y_t == END_TOKEN: break y_prev = y_t return outputs
function ADDITIVE_SCORE(q, h; W_a, U_a, v_a): return dot(v_a, tanh(matvec(W_a, q) + matvec(U_a, h))) function DOTPRODUCT_SCORE(q, h): return dot(q, h) function SOFTMAX(e): m = max(e) # numerical stability exps = [exp(e_i - m) for e_i in e] Z = sum(exps) return [x / Z for x in exps] ``` The algorithm handles two important edge cases correctly. If (a single-token source), softmax degenerates to and for all — attention correctly reduces to the no-attention case. If the encoder states are highly redundant (e.g., a repeated token), the softmax may legitimately spread weight across several equally relevant positions rather than being forced to pick one, which is the intended soft (not hard) alignment behavior.
Complexity & correctness
Time complexity. For a source of length and target of length , attention adds time beyond the base encoder/decoder cost, where is the hidden dimension: at each of the decoding steps, scoring against all encoder states costs (dot-product) or -ish (additive, due to the projection matrices ), and the weighted sum is another . This is a genuine quadratic-in-sequence-length cost when , compared to the or cost of the bottleneck model that discards all but the final encoder state. This is the fundamental compute-for-quality tradeoff attention introduces, one that later motivates approximate/sparse attention variants for very long sequences.
Space complexity. The model must retain all encoder hidden states throughout decoding, an memory cost (versus for the bottleneck-only model), plus if attention weight matrices are stored for later inspection or visualization (as in alignment heatmaps).
Correctness — why the bottleneck is actually relieved. Consider the gradient of the loss at decoding step with respect to an early encoder state . In the bottleneck model, this gradient must flow backward through the entire chain of encoder recurrences from to to to the decoder — a path of length , subject to vanishing-gradient decay at every step. With attention, contributes directly to via the term , so
gives a direct, short path from any input position to any output position, with path length independent of . This is precisely why attention alleviates the long-range dependency problem: the maximum gradient path length between any input and any output token drops from (through recurrence) to (through the attention weights), even though the recurrent encoder/decoder states themselves still exist and can still contribute vanishing gradients along their own path.
Why softmax normalization is the right choice. The weights must (a) be non-negative, so the context vector is a genuine weighted average and not an extrapolation outside the convex hull of , and (b) sum to 1, so the scale of doesn't depend on — without normalization, a longer sentence would trivially produce a larger-magnitude context vector for reasons unrelated to relevance. Softmax satisfies both properties while remaining differentiable everywhere, which is required for end-to-end training via backpropagation. Because there is no ground-truth "correct" alignment to supervise against, attention weights are learned purely from the downstream task loss (e.g., translation cross-entropy) — and empirically, the resulting patterns closely mirror the word alignments produced by classical statistical alignment models (like IBM Model / GIZA++), which is strong empirical evidence that the mechanism is learning a semantically meaningful soft alignment, not an arbitrary weighting.
Tradeoffs, honestly stated. Attention is strictly more expressive than the bottleneck model (it can represent the bottleneck model as a degenerate case where is always or concentrated on ), but this expressiveness costs quadratic time in sequence length and additional memory to retain all encoder states. For very long documents, this quadratic cost becomes the dominant bottleneck of Transformer-based systems, motivating sparse and linear-attention approximations — a tradeoff attention itself does not resolve, only shifts.
Worked example
Consider translating the French sentence "le chat noir dort" ("the black cat sleeps") into English, at the decoding step where the model is about to produce the word "black". Assume the encoder has already produced hidden states for "le", "chat", "noir", "dort" respectively, and the decoder has already emitted "the" with hidden state , which becomes the query . Suppose (illustrative, rounded) dot-product scores between and each come out as:
| Source token | meaning | raw score | ||
|---|---|---|---|---|
| 1 | "le" | 0.2 | 1.221 | 0.048 |
| 2 | "chat" | 1.1 | 3.004 | 0.117 |
| 3 | "noir" | 2.9 | 18.17 | 0.711 |
| 4 | "dort" | 0.4 | 1.492 | 0.058 |
| — | (normalizer ) | — | 25.65 (≈ sum, adjusted) | 1.000 |
(Softmax is computed as ; the table above illustrates the intended dominant-weight pattern rather than exact arithmetic to the last decimal.) The attention weights correctly concentrate on ("noir" = "black"), which is exactly the source word the decoder needs to correctly produce "black" next — even though "noir" appears after "chat" in French but the decoder needs it before "cat" in the English output. This crossing is precisely why attention outperforms a naive fixed alignment: French adjectives often follow the noun they modify, while English adjectives precede it, so the correct "alignment path" is non-monotonic. A model without attention has no mechanism to reach back selectively to "noir" out of word order; it must hope the single bottleneck vector preserved enough of that signal. The context vector is then:
This , heavily weighted toward , is fed into the decoder alongside the previous output "the" to produce the hidden state , from which the softmax output layer assigns high probability to the word "black." At the next step, the query becomes , and the attention distribution shifts — now concentrating on ("chat") to correctly produce "cat." This step-by-step re-weighting, visualized as an alignment matrix (rows = output tokens, columns = input tokens), is the signature diagnostic of attention: the heatmap typically shows a roughly diagonal band for similar-word-order language pairs, with visible off-diagonal crossings exactly at points of syntactic reordering, like the noun-adjective swap above.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Forgetting to renormalize with softmax (using raw scores) | Treating directly as weights | Context vector scale explodes/shrinks with ; training destabilizes |
| Using the current decoder output (not previous state) as the query | Off-by-one in the recurrence — conditioning on information not yet available | Leaks future target information; breaks autoregressive generation at inference time |
| Confusing keys/values in cross-attention with query source | Query must come from the decoder side, keys/values from the encoder side | Mechanism attends to the wrong sequence entirely |
| Omitting the scale in dot-product attention with large | Large dot products push softmax into saturated, near-one-hot regions | Vanishing gradients through softmax; training stalls |
| Treating attention weights as a causal explanation ("the model attends to X, therefore X causes Y") | Attention weights are correlational diagnostics, not verified causal attributions | Over-interpreting visualizations; misleading interpretability claims |
| Ignoring padding tokens in variable-length batches | Padded positions still receive nonzero attention mass if not masked | Model attends to meaningless padding; degrades output quality |
Pioneers & history
Origins · 1 minDzmitry Bahdanau and how this was discovered
As a graduate student, Bahdanau co-authored the 2014/2015 paper "Neural Machine Translation by Jointly Learning to Align and Translate," which proposed learning a soft alignment between source and target words via a feedforward scoring network, directly addressing the fixed-length bottleneck of the encoder-decoder model that dominated sequence-to-sequence learning at the time.
The idea that a network could learn to "look back" selectively at different parts of an input, rather than compressing everything into one vector, reframed how researchers thought about memory and alignment in neural sequence models — and it did so with a strikingly simple, fully differentiable mechanism trainable end-to-end via ordinary backpropagation, requiring no explicit alignment supervision.
Origins · 1 minhow this was discovered
Where this matters
Attention is the mechanism that made modern Neural Machine Translation systems (Google Translate and successors) practically usable on long, syntactically divergent sentence pairs, replacing earlier phrase-based statistical MT pipelines. Its generalization into self-attention, where queries, keys, and values all derive from the same sequence, underlies the Transformer architecture powering essentially every modern large language model — GPT, BERT, T5, and their descendants. The same query/key/value soft-lookup idea appears in image captioning (attending over image regions), speech recognition (attending over acoustic frames), retrieval-augmented generation (attending over retrieved documents), and multimodal models that align text with images or audio. Attention weight visualizations remain a standard interpretability tool, and the query/key/value abstraction is now the lingua franca for describing how Contextual Embeddings are built: each token's representation is recomputed as a weighted function of every other token's representation, layer after layer, rather than fixed once and reused everywhere as in earlier static word-embedding schemes.
Ask the tutor: How does scaled dot-product self-attention in the Transformer differ mechanically from the cross-attention described here, and why is the scaling factor necessary?
Is attention the same thing as self-attention in the Transformer?
Not quite — they share the same query/key/value scoring-and-weighting mechanism, but differ in where the query, keys, and values come from. In encoder-decoder (cross-)attention, as described here, the query comes from the decoder and the keys/values come from the encoder — two different sequences. In self-attention, queries, keys, and values are all learned projections of the same sequence, so a token attends to other tokens within its own input. The Transformer uses self-attention within both the encoder and decoder, plus cross-attention between them, generalizing the mechanism described in this article.
Why does attention help with long sentences specifically?
The bottleneck model must compress an entire sentence into one fixed-size vector, and this compression gets proportionally worse as sentence length grows — empirically, translation quality drops sharply past roughly 20-30 words without attention. Attention avoids this by keeping every encoder state available and letting the decoder select which ones matter at each step, so the effective "memory" available scales with sentence length rather than being capped by a single vector's capacity. This is why BLEU scores for attention-based models stay far more stable as source sentence length increases.
Can attention weights be interpreted as explanations for model behavior?
Attention weights indicate where the model looked when constructing a context vector, but this is not the same as a verified causal explanation of why it produced a given output. Several studies have shown that different attention distributions can sometimes produce similar outputs, and that alternative explanation methods (like gradient-based attribution) can disagree with attention patterns. Attention weights are a useful diagnostic and often correlate with intuitive alignment, but should be treated as suggestive evidence, not definitive proof, when explaining model decisions.
What is the difference between additive and dot-product attention in practice?
Additive attention learns a small feedforward network (parameters , , ) to score query-key pairs, giving it more flexibility to model complex interactions, particularly when query and key vectors have different dimensionalities. Dot-product attention scores pairs with a simple inner product, which is much faster (a matrix multiplication versus many small feedforward passes) but can suffer from very large-magnitude scores when the vector dimension is large, pushing softmax into a near-one-hot regime with vanishing gradients — which is exactly why the Transformer's scaled dot-product attention divides scores by .
Does attention completely eliminate the vanishing gradient problem in recurrent encoder-decoder models?
No — it eliminates the vanishing-gradient problem specifically along the path from encoder states to the context vector, since that path is now a direct weighted sum rather than a long recurrent chain. However, the encoder and decoder themselves may still be recurrent networks (RNNs/LSTMs), and gradients still must flow through their own recurrent connections, which can still vanish or explode over long sequences. This is one reason the Transformer eventually removed recurrence altogether, relying purely on (self-)attention plus positional information.
How does attention relate to classical statistical alignment models in machine translation?
Classical statistical MT (e.g., IBM Models, used in GIZA++) explicitly modeled word-to-word alignment probabilities as a distinct, hand-engineered component of the translation pipeline, trained via expectation-maximization on parallel corpora. Neural attention was not designed to reproduce these alignments, but was trained purely to minimize translation loss end-to-end — yet empirically, the learned attention distributions closely resemble the alignments discovered by these classical statistical models. This convergence is often cited as evidence that attention is learning a genuinely meaningful linguistic alignment rather than an arbitrary weighting scheme.
Is attention specific to sequence-to-sequence tasks like translation?
No — while attention was introduced for neural machine translation, the same query/key/value soft-lookup principle generalizes far beyond it. It has been applied to image captioning (attending over spatial image regions), speech recognition (attending over acoustic frames), document summarization, question answering, and — most influentially — as the core building block of the Transformer's self-attention, which underlies virtually all large-scale pretrained language models used for Contextual Embeddings and downstream NLP tasks today.