Machine Learning

Seq2seq and Encoder-Decoder Attention

Compare a fixed encoder-decoder bottleneck with Bahdanau-style attention, then predict which source state a decoder step should look at.

status: reviewimportance: criticaldifficulty 4/5math: graduateread: 23mlive demo

Concept Structure

Seq2seq and Encoder-Decoder Attention

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
2next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseCompare a fixed encoder-decoder bottleneck with Bahdanau-style attention, then predict which source state a decoder step should look at.

This Machine Learning concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to Beam Search and Sequence Decoding (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources5 cited
Codeattached
Demolive
Reviewed2026-07-02
Updatedpage 2026-07-02

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptSeq2seq and Encoder-Decoder AttentionMachine Learning
5 sources attachedLocal snapshot ready
concept:machine-learning/seq2seq-encoder-decoder-attention
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

You have now seen why plain RNNs struggle across long corridors and why LSTM/GRU gates give recurrent models better memory routes. Seq2seq models ask those recurrent units to do something harder: read one whole sequence, then generate another sequence.

Machine translation is the classic example. The source might be

the cat sat on the mat\text{the cat sat on the mat}

and the decoder must produce a target sequence one token at a time.

The first encoder-decoder mental model is simple:

  1. The encoder reads every source token.
  2. The encoder compresses the source into one context vector.
  3. The decoder starts from that context and generates the target.

That one context vector is the bottleneck. For short sentences it can work. For long, reordered, or information-dense sentences, asking one final state to carry every relevant source detail is a lot like asking one sticky note to replace the whole source sentence.

Encoder-decoder attention changes the contract. The encoder no longer has to squeeze everything into one fixed vector. It can leave a state at each source position:

h1,,hT.h_1,\ldots,h_T.

At target step tt', the decoder state asks a question: "Which source states matter for the next target token?" Attention scores every source state, normalizes the scores into weights, and forms a step-specific context vector.

So the decoder receives a fresh source summary at each target step:

ct=t=1Tαt,tht.c_{t'}=\sum_{t=1}^{T}\alpha_{t',t}h_t.

That is the whole bridge. Fixed-context seq2seq says: "remember everything once." Attention says: "look back at the source each time you need to say something."

This is not the same as transformer self-attention. Encoder-decoder attention is asymmetric: decoder queries attend to encoder states. Transformer self-attention lets tokens inside the same sequence attend to one another. The shared idea is weighted lookup; the wiring and use case differ.

One more caveat matters. Attention weights are useful alignment diagnostics, especially in translation, but they are still model-internal weights. They can help you inspect what the decoder used, but they are not guaranteed ground-truth word alignments or causal explanations.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let the source sequence have length TT and the target sequence have length TT'. Let xtx_t be the source token at source position tt, and yty_{t'} be the target token at target position tt'.

A recurrent encoder maps source embeddings into hidden states:

ht=f(xt,ht1),htRd.h_t=f(x_t,h_{t-1}), \qquad h_t\in\mathbb R^d.

A fixed-context seq2seq model creates one context variable:

c=q(h1,,hT).c=q(h_1,\ldots,h_T).

A common simple choice is c=hTc=h_T, the final encoder state. The decoder then updates its hidden state with the previous target token, previous decoder state, and this fixed context:

st=g(yt1,st1,c).s_{t'}=g(y_{t'-1},s_{t'-1},c).

The next-token distribution is

p(yty<t,x1:T)=softmax(Wost+bo).p(y_{t'}\mid y_{<t'},x_{1:T})=\operatorname{softmax}(W_os_{t'}+b_o).

The bottleneck is visible in the conditioning path: the entire source reaches every decoder step through the same cc.

Bahdanau-style attention makes cc depend on the target step. Use the previous decoder state as a query and each encoder state as a key/value. Define an alignment score

et,t=a(st1,ht),e_{t',t}=a(s_{t'-1},h_t),

where aa is a learned scoring function. In additive attention, one standard form is

a(s,h)=vatanh(Wss+Whh+ba).a(s,h)=v_a^\top\tanh(W_s s+W_h h+b_a).

Normalize scores over source positions:

αt,t=exp(et,t)k=1Texp(et,k).\alpha_{t',t}= \frac{\exp(e_{t',t})}{\sum_{k=1}^{T}\exp(e_{t',k})}.

Then compute the dynamic context:

ct=t=1Tαt,tht.c_{t'}=\sum_{t=1}^{T}\alpha_{t',t}h_t.

Now the decoder recurrence becomes

st=g(yt1,st1,ct).s_{t'}=g(y_{t'-1},s_{t'-1},c_{t'}).

The alignment matrix ART×TA\in\mathbb R^{T'\times T} has entries At,t=αt,tA_{t',t}=\alpha_{t',t}. Each row sums to 11 because it is a softmax over source positions for one target step.

The distinction from self-attention is shape and direction:

encoder-decoder attention: Q=st1,K=V=[h1,,hT].\text{encoder-decoder attention: } Q=s_{t'-1},\quad K=V=[h_1,\ldots,h_T]. self-attention: Q,K,V all come from the same sequence representation.\text{self-attention: } Q,K,V \text{ all come from the same sequence representation.}

Both are weighted value lookups. Seq2seq attention is the historical bridge that made "look at the relevant tokens instead of carrying everything in one state" concrete.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt
import numpy as np

source = ["the", "cat", "sat", "on", "the", "mat"]
target = ["the", "cat", "sat", "on", "the", "mat"]

def softmax(x):
    x = x - x.max()
    ex = np.exp(x)
    return ex / ex.sum()

# Toy source annotations h_t and decoder queries s_{t'-1}
H = np.array([
    [1.0, 0.1], [0.8, 0.7], [0.1, 1.0],
    [-0.2, 0.9], [0.9, 0.0], [0.2, 0.8],
])
S = np.array([
    [1.0, 0.0], [0.8, 0.7], [0.1, 1.0],
    [-0.2, 0.9], [0.9, 0.0], [0.2, 0.8],
])

alignment = []
contexts = []
for query in S:
    scores = H @ query
    alpha = softmax(scores)
    context = alpha @ H
    alignment.append(alpha)
    contexts.append(context)

A = np.vstack(alignment)
print(np.round(A, 2))
print("top source tokens:", [source[i] for i in A.argmax(axis=1)])

This is a toy dot-product attention witness, not the full additive Bahdanau scoring network. It mirrors the invariant: each target step gets its own row of weights over source states, then uses a weighted source summary.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Use the Seq2Seq Attention Lab to compare two routes.

First choose a decoder step, then predict which source token should matter most for that target token.

  • Bottleneck: all source states are compressed into one final state before decoding.
  • Attention: the decoder query scores every source state and builds a target-step-specific context vector.

Before reveal, the alignment matrix and actual top source token are hidden. After reveal, inspect the attention row, the bottleneck's single-summary bias, and the caveat strip. If the target word is aligned correctly, say what changed: the decoder did not magically understand language; it gained a differentiable lookup over source states.

Live Concept Demo

Explore Seq2seq and Encoder-Decoder Attention

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 4/5graduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what Seq2seq and Encoder-Decoder Attention should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

Compare a fixed encoder-decoder bottleneck with Bahdanau-style attention, then predict which source state a decoder step should look at.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Seq2seq and Encoder-Decoder Attention should make visible.

Visual Inquiry

Make the image answer a mathematical question

Compare a fixed encoder-decoder bottleneck with Bahdanau-style attention, then predict which source state a decoder step should look at.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Seq2seq and Encoder-Decoder Attention easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

book · 2026Dive into Deep Learning: Sequence-to-Sequence Learning for Machine TranslationZhang, Lipton, Li, and Smola

Defines RNN encoder-decoder seq2seq, fixed-shape context variable, decoder recurrence, teacher forcing, and tensor shapes for encoder outputs.

Open source
book · 2026Dive into Deep Learning: The Bahdanau Attention MechanismZhang, Lipton, Li, and Smola

Explains fixed-context bottlenecks and defines Bahdanau attention as a decoder-state query over encoder hidden states with a dynamic context vector.

Open source
course-notes · 2019CS224N: Neural Machine Translation, Seq2seq and AttentionStanford CS224N

Course source for encoder-decoder context vectors, Bahdanau attention equations, attention vectors, context vectors, and alignment-table intuition.

Open source
paper · 2015Neural Machine Translation by Jointly Learning to Align and TranslateBahdanau, Cho, and Bengio

Primary source for fixed-length-vector bottleneck motivation, soft search over source annotations, attention weights, and qualitative soft-alignment analysis.

Open source
book · 2026Speech and Language Processing, Chapter 12: Machine TranslationJurafsky and Martin

Modern NLP textbook source for machine translation as conditional sequence generation and the encoder-decoder formulation.

Open source

Claim Review

Compare a fixed encoder-decoder bottleneck with Bahdanau-style attention, then predict which source state a decoder step should look at.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources5 references

d2l-2026-seq2seq, d2l-2026-bahdanau-attention, cs224n-2019-nmt-seq2seq-attention, bahdanau-2015-align-translate, jurafsky-martin-slp3-mt

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedEncoder-decoder attention replaces a single fixed seq2seq context bottleneck with a target-step-specific context vector, computed as attention weights over encoder hidden states; the weights can be inspected as soft alignments but are model-internal evidence, not ground truth.Claim metadata: source checked

D2L and CS224N support the fixed-context seq2seq architecture and attention context-vector equations; Bahdanau et al. support the bottleneck motivation, learned soft search, and alignment visualization; SLP3 supports machine translation as conditional encoder-decoder sequence generation.

Sources: Dive into Deep Learning: Sequence-to-Sequence Learning for Machine Translation, Dive into Deep Learning: The Bahdanau Attention Mechanism, CS224N: Neural Machine Translation, Seq2seq and Attention, Neural Machine Translation by Jointly Learning to Align and Translate, Speech and Language Processing, Chapter 12: Machine TranslationFinite hand-set alignment witness only; real attention weights are learned, may be diffuse, and are not guaranteed faithful explanations of causal model behavior.A bounded review summary is present; still check caveats and exact reference scope.

Checked D2L seq2seq and Bahdanau attention chapters, Stanford CS224N NMT notes, Bahdanau/Cho/Bengio 2015, and SLP3 machine-translation chapter for fixed-context encoder-decoder structure, bottleneck motivation, per-target context vectors, softmax attention weights, weighted sums over encoder states, and soft-alignment caveats. GPT Pro/Oracle publication critique remains pending because 127.0.0.1:51672 refused connection.

Reviewer: codex-local-primary-source-audit; reviewed 2026-07-02

Practice Loop

Try the idea before it explains itself

Compare a fixed encoder-decoder bottleneck with Bahdanau-style attention, then predict which source state a decoder step should look at.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in Seq2seq and Encoder-Decoder Attention.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptSeq2seq and Encoder-Decoder AttentionMachine Learning

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptMachine Learning

Seq2seq and Encoder-Decoder Attention

Attached question

What is the smallest example that makes Seq2seq and Encoder-Decoder Attention click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - Seq2seq and Encoder-Decoder Attention Selected item key: recorded for copy. Context: Machine Learning Page anchor: recorded for copy. Open question: What is the smallest example that makes Seq2seq and Encoder-Decoder Attention click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/machine-learning/seq2seq-encoder-decoder-attention concept:machine-learning/seq2seq-encoder-decoder-attention