Foundations to Frontier
Tests
E. Deep Learning › E11 Recurrent and Sequence Models

Sequence-to-sequence (encoder–decoder)

A sequence-to-sequence model (Sutskever, Vinyals and Le, 2014; Cho and colleagues, 2014) maps an input sequence to an output sequence of different length. An encoder RNN reads the input into a fixed vector, and a decoder RNN generates the output one token at a time, conditioned on that vector and its previous tokens. It made neural machine translation competitive and set the pattern for speech recognition, summarisation and dialogue. This page covers the architecture, training with teacher forcing, decoding, the fixed-vector bottleneck and the source-reversal trick. In the exercises you build an encoder and decoder and check they define a proper distribution. You then reproduce the reversal trick on a toy task: at length 8, reversing the target order raises accuracy from 0.908 to 0.950, although the average source-to-output distance stays at 7 steps.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Read, then write

To translate a sentence, a sequence-to-sequence model first reads the whole sentence with one recurrent network (the encoder), squeezing it into a single list of numbers. A second network (the decoder) then writes the translation one word at a time, each time looking at that summary and the words it has already written. Input and output can have different lengths and different vocabularies. The demo’s beam-search mode shows how the decoder chooses among possible outputs.

Sequence-model lab
ABB0.1155
Best sequence ABB with probability 0.1155; greedy search gives ABB (0.1155). Greedy picks A first (0.55) and misses the better path through B.
Why engineers care

Encoder–decoders turn one kind of sequence into another: speech into text, sensor histories into forecasts, commands into action sequences.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The encoder…
  2. 2. The decoder produces the output…
  3. 3. Input and output lengths…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Model:
    • h = Enc(x₁ … x_S) is the encoder’s final state;
    • the decoder starts from s₀ = h and computes sₜ = f(sₜ₋₁, yₜ₋₁) and p(yₜ | y₁…yₜ₋₁, x) = softmax(sₜWₒ + bₒ);
    • generation starts with a ⟨start⟩ token and stops at ⟨end⟩.
  • Likelihood: log p(y | x) = Σₜ log p(yₜ | y₁…yₜ₋₁, x). Three tokens at 0.5 each give 3 log 0.5 = −2.08. The perplexity exp(−log p / n) is 2.
  • Training: teacher forcing feeds the true previous token. At test time the model feeds its own predictions (E11-14).
  • Parameters: for vocabularies of 1000 each, embeddings 64, hidden 128 and tanh RNNs: 64,000·2 + 2·24,704 + 129,000 = 306,408.
  • The bottleneck:
    • everything about the source must pass through one h-dimensional vector;
    • a random length-8 sequence over 6 symbols holds 8 log₂ 6 = 20.7 bits, easily within capacity, but the network must learn to pack it;
    • accuracy falls with length (Cho et al., 2014), which motivated attention (E11-9).
  • Source reversal (Sutskever et al.): for copy-like tasks, reading the source backwards puts the first source tokens next to the first outputs.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Perplexity of three tokens at probability 0.5:
  2. 2. Teacher forcing feeds the decoder…
  3. 3. Bits in a random length-8 sequence over 6 symbols:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Seq2seq in code

Exercise 1.

  • The encoder’s vector depended on the source order.
  • The decoder’s probabilities over all length-2 outputs summed to 1 (to 10⁻⁹), so it defines a proper distribution.

Practice.

  • Batch sequences of similar length; pad and mask the loss on padding.
  • Use separate encoder and decoder LSTMs or GRUs, usually several layers. Pass the final (h, c) of every layer to initialise the decoder.
  • Sutskever et al. used 4-layer LSTMs with 1000 units, reversed sources and beam search. They reached 34.8 BLEU on WMT’14 English→French with an ensemble, and 36.5 when rescoring a phrase-based system’s outputs.
  • Decode with beam search (E11-14) and length normalisation, since raw log-probabilities favour short outputs.
_, (h, c) = encoder(src_emb)                         # final states of every layer
out, _ = decoder(tgt_emb_shifted, (h, c))            # teacher forcing: inputs are targets shifted right
loss = F.cross_entropy(proj(out).transpose(1, 2), tgt, ignore_index=PAD)
🐍 Exercise 1: encoder and decoder
Implement a tanh RNN encoder, greedy decoding and the sequence log-probability, and check the distribution sums to 1.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Sutskever et al.'s LSTMs had…
  2. 2. Raw log-probability decoding favours…
  3. 3. Loss on padding tokens should be…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Conditional language model. The decoder is a language model over outputs conditioned on h. The chain rule factorises p(y | x) exactly, so maximising the summed log-likelihood is maximum likelihood estimation.

The fixed-vector bottleneck.

  • The encoder must compress any input into h, whatever its length.
  • Information capacity is ample in principle, but learning to pack and unpack it through long recurrent paths is hard.
  • Cho et al. (2014) showed translation quality dropping sharply with sentence length.
  • Attention (E11-9) removes the bottleneck by letting the decoder look back at all encoder states.

Why reversal helps.

  • In copy order, every output is 7 steps from its source token at length 8.
  • Reversed, the distances are 0, 2, 4, …, 14: the average is the same, but the first outputs are now very close to their sources.
  • Sutskever et al. argued these short-lag pairs let gradient descent “establish communication” between encoder and decoder early, which then helps the long pairs too. Exercise 2 is consistent with this.
📝 Quick check (Level 3)
0/3 answered
  1. 1. The decoder is…
  2. 2. Reversal changes the average source-output distance?
  3. 3. The bottleneck was removed by…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Why does reversing the source help?

History.

  • N. Kalchbrenner and P. Blunsom (2013) built early continuous translation models.
  • K. Cho et al. introduced the RNN encoder–decoder with GRUs (EMNLP 2014).
  • I. Sutskever, O. Vinyals and Q. Le’s “Sequence to sequence learning with neural networks” (NeurIPS 2014) showed deep LSTMs competitive with phrase-based translation.
  • D. Bahdanau, K. Cho and Y. Bengio added attention (ICLR 2015).

Exercise 2.

  • Task: a tanh-RNN encoder–decoder (32 units, vocabulary 6) learns either to copy a random source sequence or to output it reversed.
  • Training: teacher forcing, 600 Adam steps, 2 seeds.
  • Measurement: greedy-decoding token accuracy, overall and by output position.
length task mean accuracy by output position
4 copy 1.000 1.0 everywhere
4 reverse 1.000 1.0 everywhere
8 copy 0.908 0.98, 0.96, 0.93, 0.90, 0.87, 0.88, 0.87, 0.86
8 reverse 0.950 1.00, 0.98, 0.98, 0.97, 0.94, 0.92, 0.90, 0.90

Reversing the target order is equivalent here to reversing the source for the copy task.

  • Reversal helps at length 8, by 4 points, even though the average distance from each source token to its output is 7 steps in both cases.
  • The gain appears where the lag is short. The first reversed outputs, 0–6 steps from their source tokens, are almost perfect, while copy accuracy drops steadily.
  • Both decline along the output, since greedy decoding compounds errors. Length 4 is easy for both.
🐍 Exercise 2 (research): why does reversing the source help?
Train an encoder–decoder to copy or reverse sequences and compare accuracy by output position.

Seq2seq in AI, robotics and aerospace

  • Speech and translation: encoder–decoders (later with attention) replaced pipeline systems.
  • Forecasting: encoders read sensor histories and decoders roll out multi-step forecasts of trajectories or loads.
  • Instruction following: robots map natural-language commands to action sequences with encoder–decoders.

References

  1. I. Sutskever, O. Vinyals, Q. V. Le (2014). “Sequence to sequence learning with neural networks.” Proc. NeurIPS.
  2. K. Cho et al. (2014). “Learning phrase representations using RNN encoder–decoder for statistical machine translation.” Proc. EMNLP.
  3. K. Cho, B. van Merriënboer, D. Bahdanau, Y. Bengio (2014). “On the properties of neural machine translation: encoder–decoder approaches.” Proc. SSST-8.
  4. N. Kalchbrenner, P. Blunsom (2013). “Recurrent continuous translation models.” Proc. EMNLP.