Skip to main content
LearnMLAcademy
Advanced10 min read

Sequence-to-Sequence Models and Attention

Understand encoder-decoder sequence modeling and Bahdanau attention alignments, with sequence diagrams, attention calculations, and model-code exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Sequence Models

See why one sequence may need to become another sequence, how an encoder and decoder cooperate, and how attention replaces one fixed source summary with a different weighted context for every output step.

The Problem: Transform One Sequence Into Another

A normal classifier converts an input into one label. A sequence-to-sequence (seq2seq) task needs an ordered output whose length may differ from the input. Translation is the clearest example: “the machine stopped” has three source tokens, while a valid French translation can have four target tokens.

An encoder reads the source and creates representations of its meaning. A decoder produces the target, using the source representation and target tokens already known. Special start and end tokens tell the decoder when generation begins and ends.

Sequence-to-sequence learning maps one ordered series to another

The input and output do not need the same number of tokens.

source sequence

x1thex2machinex3stopped

Encoder

↓

representations

→

Decoder

↓

one token at a time

target sequence

y1lay2machiney3s’esty4arrêtée
The encoder turns source tokens into useful representations. The decoder uses them plus the target tokens already available to predict the next target token.

Why One Fixed Context Vector Is a Bottleneck

Early recurrent encoder–decoder systems often compressed the complete source into one final hidden vector. The decoder had to recover every needed detail from that one container. As sentences grew, names, relationships and word order could be difficult to preserve.

Attention removes that single-vector restriction. The encoder keeps a representation for every source position. At each output step, the decoder scores those representations, converts the scores to weights, and forms a new weighted context. Predicting “voiture” can focus on “car”; predicting “rouge” can focus on “red.”

Attention creates a new source summary for each output step

While predicting the French word “voiture,” this illustrative decoder focuses most on “car.”

the
0.05
red
0.18
car
0.67
stopped
0.10
→

weighted context

ct = Σ αt,ivi

used to predict

voiture

Weights sum to 1. They are learned for the prediction context; they are useful to inspect but should not automatically be treated as a complete causal explanation.

Attention Is a Weighted Lookup

Modern dot-product attention gives every item three learned views. If one token representation is x, the model calculates q=xWQ, k=xWK and v=xWV. The token representation comes from the previous layer; the three W matrices are initialized and then learned during training; Q, K and V are recalculated from the current input on every forward pass.

A query states what the current position needs. A key advertises what a candidate position contains. A value carries the information to retrieve. Query–key similarity determines how much of each value enters the result.

Scaled dot-product attention

Attention(Q,K,V) = softmax(QKᵀ / √dk)V

1. Multiply QKᵀ
Dot products measure each query–key match.

2. Divide by √dk
Scaling controls score size as vector width grows.

3. Apply softmax
Exponentiate and divide by the row sum to get positive weights totalling 1.

4. Multiply by V
Scale each value by its weight and add the results.

One query chooses between two source values

For a calculation we can see completely, manually choose q=[1,0], k₁=[1,0], k₂=[0,1], v₁=[10,2] and v₂=[2,8]. Their two components make dk=2; it is calculated from vector width, not chosen separately.

1. Scores
q·k₁=1×1+0×0=1
q·k₂=1×0+0×1=0
scaled=[1/√2,0]=[0.707,0]

2. Softmax
e⁰·⁷⁰⁷≈2.028, e⁰=1
sum=3.028
weights≈[0.67,0.33]

3. Retrieve
[6.70,1.34]+[0.66,2.64]
≈ [7.36,3.98]

Interpretation: the query matches key 1 more strongly, so the output resembles v₁ while still mixing in v₂. Real q, k and v vectors are model-produced; the values—not the keys—are what get averaged.

A Short Bridge to Transformer Attention

Self-attention lets positions within one sequence exchange information: queries, keys and values come from that same sequence. Cross-attention connects two sequences: decoder queries retrieve keys and values created by the encoder. Attention removes the fixed-context bottleneck; the next lesson shows what happens when attention becomes the main architecture.

What to Carry Into the Next Lesson

  1. Seq2seq learning transforms one ordered sequence into another, possibly with a different length.
  2. A recurrent encoder summarizes source information and a decoder predicts target tokens from source context and target history.
  3. One final encoder state can become a bottleneck for long or detailed inputs.
  4. Attention forms a new weighted source summary for each decoder step.
  5. Self-attention and cross-attention extend the same weighted-lookup idea; the next lesson shows how Transformers organize them into a full architecture.

Continue Learning

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Sequence-to-Sequence Models and Attention"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What problem can one fixed encoder state create in long sequence-to-sequence tasks?
Question 2 of 5conceptual
What do attention weights at one decoder step do?
Question 3 of 5numerical/formula
If attention weights are [0.2,0.3,0.5], what must their sum be?
Question 4 of 5interpretation
How does cross-attention differ from self-attention?
Question 5 of 5practical selection
Why should an attention heatmap be interpreted cautiously?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What problem can one fixed encoder state create in long sequence-to-sequence tasks?▼

Correct Answer: An information bottleneck

Compressing every source detail into one vector can discard information needed by the decoder.

2What do attention weights at one decoder step do?▼

Correct Answer: Form a weighted source summary for that output

The decoder combines source representations according to their relevance for the current prediction.

3If attention weights are [0.2,0.3,0.5], what must their sum be?▼

Correct Answer: 1

Softmax-normalized attention weights sum to one across the attended positions.

4How does cross-attention differ from self-attention?▼

Correct Answer: Queries and key/value representations come from different sequences

Decoder cross-attention queries encoder outputs, while self-attention uses one sequence for all roles.

5Why should an attention heatmap be interpreted cautiously?▼

Correct Answer: Attention weight is not a complete causal explanation

Weights show one internal routing pattern but do not prove why the full model made a decision.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next