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.

Key takeaways
  • 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.
The core insight

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 x1,…,xnx_1, \dots, x_n and produces a final hidden state hnh_n, which serves as the sole summary — the context vector cc — passed to the decoder. Every output token yty_t is generated conditioned on this same fixed cc, regardless of what part of the input is actually relevant to producing yty_t. This is the bottleneck problem: information about all nn input tokens must be squeezed through one vector of fixed dimensionality, and the squeeze gets worse as nn grows.

Attention removes this bottleneck by keeping all encoder hidden states h1,…,hnh_1, \dots, h_n around, and computing, at each decoder timestep tt, a fresh context vector ctc_t that is a weighted combination of them:

ct=∑i=1nαt,i hic_t = \sum_{i=1}^{n} \alpha_{t,i}\, h_i

The weights αt,i\alpha_{t,i} (the attention weights) form a probability distribution over source positions (∑iαt,i=1\sum_i \alpha_{t,i} = 1, αt,i≥0\alpha_{t,i} \ge 0), computed from a learned alignment score et,ie_{t,i} between the decoder's current state and each encoder state, normalized by a softmax:

αt,i=exp⁡(et,i)∑j=1nexp⁡(et,j)\alpha_{t,i} = \frac{\exp(e_{t,i})}{\sum_{j=1}^{n} \exp(e_{t,j})}

The terminology, later standardized by the Transformer paper, casts this as a query/key/value lookup: the decoder state is the query qtq_t, each encoder state serves as both a key kik_i (used to compute the score) and a value viv_i (used to build the weighted sum). In the vanilla recurrent-attention setting, keys and values are literally the same vectors hih_i; 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:

et,i=va⊤tanh⁡(Waqt+Uahi)e_{t,i} = v_a^\top \tanh(W_a q_t + U_a h_i)

Dot-product attention (Luong et al., 2015) computes it more cheaply as an inner product, optionally scaled or bilinear:

et,i=qt⊤hi(dot)et,i=qt⊤Wahi(general/bilinear)e_{t,i} = q_t^\top h_i \quad \text{(dot)} \qquad e_{t,i} = q_t^\top W_a h_i \quad \text{(general/bilinear)}

Dot-product attention is computationally cheaper (a matrix multiply versus a feedforward pass per pair) and becomes, with a 1/dk1/\sqrt{d_k} 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 h1,…,hnh_1, \dots, h_n, 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 tt: 1. Form the query from the decoder's current state, e.g. qt=st−1q_t = s_{t-1} (previous decoder hidden state). 2. Compute alignment scores et,ie_{t,i} between qtq_t and every encoder state hih_i, using additive or dot-product scoring. 3. Normalize with softmax to get attention weights αt,i\alpha_{t,i}. 4. Compute the context vector ct=∑iαt,ihic_t = \sum_i \alpha_{t,i} h_i. 5. Feed ctc_t (concatenated with the previous output embedding) into the decoder RNN cell to get the new hidden state sts_t. 6. Use sts_t (and often ctc_t again) to predict the output distribution over the vocabulary for yty_t. Because ctc_t 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 n=1n = 1 (a single-token source), softmax degenerates to αt,1=1\alpha_{t,1} = 1 and ct=h1c_t = h_1 for all tt — 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.

Figure
Attention as a weighted lookup over encoder states at one decoder timestep
Encoder hidden states (keys = values) h₁ "le" h₂ "chat" h₃ "noir" h₄ "dort" query qₜ = sₜ₋₁ score(q,hᵢ) → softmax attention weights αₜ,ᵢ (sum = 1): 0.05 0.62 0.08 0.25 context vector cₜ = Σ αᵢ hᵢ weighted sum feeds into decoder step

Complexity & correctness

Time complexity. For a source of length nn and target of length mm, attention adds O(m⋅n⋅d)O(m \cdot n \cdot d) time beyond the base encoder/decoder cost, where dd is the hidden dimension: at each of the mm decoding steps, scoring against all nn encoder states costs O(n⋅d)O(n \cdot d) (dot-product) or O(n⋅d2)O(n \cdot d^2)-ish (additive, due to the projection matrices Wa,UaW_a, U_a), and the weighted sum is another O(n⋅d)O(n \cdot d). This is a genuine quadratic-in-sequence-length cost when m≈nm \approx n, compared to the O(n⋅d)O(n \cdot d) or O(m⋅d)O(m \cdot d) 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 nn encoder hidden states throughout decoding, an O(n⋅d)O(n \cdot d) memory cost (versus O(d)O(d) for the bottleneck-only model), plus O(m⋅n)O(m \cdot n) 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 tt with respect to an early encoder state hih_i. In the bottleneck model, this gradient must flow backward through the entire chain of encoder recurrences from hih_i to hnh_n to cc to the decoder — a path of length O(n)O(n), subject to vanishing-gradient decay at every step. With attention, hih_i contributes directly to ctc_t via the term αt,ihi\alpha_{t,i} h_i, so

∂ct∂hi=αt,i⋅I+hi∂αt,i∂hi\frac{\partial c_t}{\partial h_i} = \alpha_{t,i} \cdot I + h_i \frac{\partial \alpha_{t,i}}{\partial h_i}

gives a direct, short path from any input position to any output position, with path length independent of ∣t−i∣|t - i|. 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 O(n)O(n) (through recurrence) to O(1)O(1) (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 αt,i\alpha_{t,i} must (a) be non-negative, so the context vector is a genuine weighted average and not an extrapolation outside the convex hull of {hi}\{h_i\}, and (b) sum to 1, so the scale of ctc_t doesn't depend on nn — 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 αt,i\alpha_{t,i} 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 αt,i\alpha_{t,i} is always 1/n1/n or concentrated on hnh_n), 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 h1,h2,h3,h4h_1, h_2, h_3, h_4 for "le", "chat", "noir", "dort" respectively, and the decoder has already emitted "the" with hidden state s1s_1, which becomes the query q2=s1q_2 = s_1. Suppose (illustrative, rounded) dot-product scores between q2q_2 and each hih_i come out as:

Source token iihih_i meaningraw score e2,ie_{2,i}exp⁡(e2,i)\exp(e_{2,i})α2,i\alpha_{2,i}
1"le"0.21.2210.048
2"chat"1.13.0040.117
3"noir"2.918.170.711
4"dort"0.41.4920.058
—(normalizer ZZ)—25.65 (≈ sum, adjusted)1.000

(Softmax is computed as α2,i=exp⁡(e2,i)/∑jexp⁡(e2,j)\alpha_{2,i} = \exp(e_{2,i}) / \sum_j \exp(e_{2,j}); the table above illustrates the intended dominant-weight pattern rather than exact arithmetic to the last decimal.) The attention weights correctly concentrate on h3h_3 ("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:

c2=0.048 h1+0.117 h2+0.711 h3+0.058 h4c_2 = 0.048\,h_1 + 0.117\,h_2 + 0.711\,h_3 + 0.058\,h_4

This c2c_2, heavily weighted toward h3h_3, is fed into the decoder alongside the previous output "the" to produce the hidden state s2s_2, from which the softmax output layer assigns high probability to the word "black." At the next step, the query becomes q3=s2q_3 = s_2, and the attention distribution shifts — now concentrating on h2h_2 ("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

PitfallWhy it happensConsequence
Forgetting to renormalize with softmax (using raw scores)Treating et,ie_{t,i} directly as weightsContext vector scale explodes/shrinks with nn; training destabilizes
Using the current decoder output (not previous state) as the queryOff-by-one in the recurrence — conditioning on information not yet availableLeaks future target information; breaks autoregressive generation at inference time
Confusing keys/values in cross-attention with query sourceQuery must come from the decoder side, keys/values from the encoder sideMechanism attends to the wrong sequence entirely
Omitting the 1/dk1/\sqrt{d_k} scale in dot-product attention with large ddLarge dot products push softmax into saturated, near-one-hot regionsVanishing 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 attributionsOver-interpreting visualizations; misleading interpretability claims
Ignoring padding tokens in variable-length batchesPadded positions still receive nonzero attention mass if not maskedModel attends to meaningless padding; degrades output quality

Pioneers & history

Origins · 1 minDzmitry Bahdanau and how this was discovered
DB
Dzmitry Bahdanau
b. 1990s · Introduced additive attention for neural machine translation

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
History
- 2014 — Bahdanau, Cho, and Bengio propose additive attention for neural machine translation, directly targeting the encoder bottleneck.
- 2015 — Luong, Pham, and Manning propose simpler dot-product and "general" (bilinear) attention variants, improving speed and competitive accuracy.
- 2015 — Xu et al. apply attention to image captioning, showing the mechanism generalizes beyond text to visual regions.
- 2017 — Vaswani et al. introduce the Transformer, built entirely on scaled dot-product self-attention, discarding recurrence altogether.
- 2018 onward — Attention-based Transformer encoders (BERT) and decoders (GPT) become the dominant architecture for contextual language representation.

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 1/dk1/\sqrt{d_k} 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 WaW_a, UaU_a, vav_a) 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 dd 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 dk\sqrt{d_k}.

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.

Before this

Where this leads