10.1 Encoder-decoder with teacher forcing
Every model in the book so far maps a sequence to the next token of the same sequence. Translation, summarization, and the dates task ("3 March 2021" to "2021-03-03") map one sequence to a different one, of a different length, in a different vocabulary. The encoder-decoder is the architecture that does that, and it is the setting where attention was invented. In this section you build the model both with and without attention, and its learning test measures the gap. Without attention the decoder sees the source only through one vector, and the bottleneck test shows what that costs on a task as simple as reversing six digits.
Concepts from other sections (13)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- attentional state: , what the output layer reads. Read more: 10.3 Luong attention and input feeding
- Gated recurrent unit (GRU): a recurrent cell with one state and two gates, . Read more: 9.3 GRU (torch gate order)
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- safetensors: a checkpoint format of an 8-byte header length, a JSON header, and raw little-endian row-major tensor bytes. Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- greedy decoding: taking the single most likely token at every step; a beam of size 1. Read more: 10.4 Beam search, generic over a step function
- beam search: keeping the best prefixes by summed log-probability, ranking all extensions together at each step. Read more: 10.4 Beam search, generic over a step function
- Padding mask: a per-step boolean that freezes a finished sequence’s state and zeros its output. Read more: 9.2 LSTM (torch gate order)
- registration order: the order layers are created in a
Module, which fixes both the state-dict keys and the order of random initialization draws. Read more: 8.2 Bengio’s neural probabilistic language model - Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay in Mathematics
- exact match: the fraction of hypotheses equal to their reference after stripping white space at both ends. Read more: 10.5 Sequence metrics: exact match, BLEU, chrF
- chrF: a recall-weighted F score over character n-grams of orders 1 to 6, white space removed. Read more: 10.5 Sequence metrics: exact match, BLEU, chrF
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- Span corruption: replacing whole spans of the input with sentinels and training the decoder to write the spans back. Read more: 12.4 T5: span corruption and relative position buckets
The pieces come from the previous chapter and the foundations. The encoder is the length-aware bidirectional RNN over two GRUs; the decoder cell is a GRUCell or the LSTM’s LSTMCell; the attention modules are Bahdanau additive attention (which also supplies length_mask) and Luong attention, the next two sections. Underneath sit Embedding and Linear from the module system, the op library, Tensor and no_grad from the tensor section, safetensors checkpoints, and the PCG32 generator from Modular arithmetic, hashing, and PCG32 in Mathematics. Training uses cross_entropy from Losses with a fused backward and AdamW. The vanilla RNN is useful background reading.
The solution lives in python/tinyllm/seq2seq/model.py: Seq2Seq (with encode, init_state, decode_step, forward, greedy), EncoderState, DecoderState, save_seq2seq, and load_seq2seq. The interface it implements is the contract course/contracts/py/tinyllm/seq2seq/model.pyi, and the oracle tests are in test_seq2seq.py.
Learning objectives
- Build an encoder, a bridge, and a decoder, and explain why the bridge reads the forward state at the last real token and the backward state at position 0.
- Train with teacher forcing as a loop over
decode_step, and add scheduled sampling with one random draw per step.- Plug in Bahdanau or Luong attention with one switch, and say exactly where each reads the source.
- Reproduce the zero-weights example by hand and show that padding never changes a sentence.
Notation
Section titled “Notation”The section uses the following symbols, with the shapes the code gives them.
| Symbol | Meaning | Type / shape |
|---|---|---|
| , | source ids, padded to , real length | int[B, S], int[B] |
decoder inputs tgt_in: bos then the target without its last token | int[B, T] | |
| decoder width; each encoder direction has | int (even) | |
| encoder output at source position (the keys) | float32[B, S, d_h] | |
| the bridge: the decoder’s first state | float32[B, d_h] | |
| decoder state after step | float32[B, d_h] | |
| , | context and Luong’s attentional state | float32[B, d_h] |
teacher_forcing, the probability of feeding the true token | float in |
Two networks and a bridge
Section titled “Two networks and a bridge”Different lengths and different vocabularies force two networks. The source is read once and in full, by the encoder; the target is written one token at a time, conditioned on what was written so far, by the decoder. The encoder can look both ways; the decoder cannot look ahead.
The encoder output at position should know the whole sentence, so the encoder is bidirectional over two GRUs of width : sees left context from the forward GRU and right context from the backward one. Two halves of make the concatenated output exactly wide, the decoder’s width, which is why must be even.
The decoder needs a starting state that summarizes the source. The two states that have read the whole sentence are the forward GRU’s state after the last real token (position ) and the backward GRU’s state after reading back to position 0. The bridge concatenates them and passes them through a Linear and a tanh, mapping them into the decoder’s state space. The decoder itself is a GRUCell (or an LSTMCell, with ) over target embeddings, and an output Linear gives logits over the target vocabulary.
One decoder step, three ways
Section titled “One decoder step, three ways”With the pieces named, a single decoder step from token and state depends on which attention, if any, is plugged in. The attention module’s query_from attribute picks the order:
| Attention | Step |
|---|---|
| none | , logits |
"previous" (Bahdanau) | ; ; logits |
"current" (Luong) | ; ; ; logits |
The only difference between Bahdanau and Luong in the step is when attention reads (with or with ) and what the output layer sees, so one switch is enough. Attention is a module passed to the constructor. The encoder computes attention.project_keys(o) once per sentence and stores it in the state, so the keys are projected once rather than at every step (the reason is worked out in Bahdanau additive attention). decode_step returns the attention weights too, which is what an alignment plot draws.
The parameters are registered in the order of the contract (src_emb, enc_fwd, enc_bwd, bridge, tgt_emb, cell, attention, out), and that order is the safetensors key list of a checkpoint.
Teacher forcing and scheduled sampling
Section titled “Teacher forcing and scheduled sampling”Training maximizes , and it should not depend on the model’s own mistakes. Teacher forcing feeds the true at step regardless of what the model predicted, so every step’s input is known in advance: all losses come from one forward pass, and the gradient at step does not depend on the model’s earlier choices. At inference the model must feed its own guesses, a mismatch called exposure bias.
Scheduled sampling (Bengio et al. 2015) trains with . Before each step after the first, one uniform is drawn for the whole batch; if the true token is fed, otherwise the argmax of the previous step’s logits, with no gradient through the choice. With nothing is drawn, so adding the option leaves a seeded run unchanged.
Targets are shifted by one: tgt_in is bos , and the loss compares step ‘s logits with (eos at the end). Padding in the target is ignored with ignore_index.
There is one more design principle hidden here: one step function should serve training, greedy decoding, and beam search. If forward is literally a loop over decode_step, then greedy decoding and beam search drive exactly the computation that was trained. greedy decodes all rows at once under no_grad, feeding back each row’s argmax and stopping a row at its first eos; beam search later replaces it, still calling decode_step.
Working it by hand
Section titled “Working it by hand”A zero-weights example pins down the data path. Take a GRU encoder-decoder with every GRU weight and bias 0. One GRU step gives and , so
From the encoder outputs 0 everywhere, whatever the source tokens. Let bridge.weight be 0 and bridge.bias . Then . Each decoder step halves it: , . With out.weight the first two rows of the identity and no bias, logits and logits, whatever the target tokens.
The example fixes the path encoder, bridge, decoder cell, output layer. Drop the bridge and the logits are zero. A correct solution reproduces these numbers exactly.
Designing the API
Section titled “Designing the API”The contract fixes two immutable state records and a model class:
class EncoderState(NamedTuple): keys; mask; proj; initclass DecoderState(NamedTuple): h; c; feed; keys; mask; projclass Seq2Seq(Module): def __init__(self, src_vocab, tgt_vocab, d_emb, d_h, cell="gru", attention=None, rng=None): ... def encode(self, src, src_lens) -> EncoderState: ... def init_state(self, enc: EncoderState) -> DecoderState: ... def decode_step(self, y_prev, state) -> tuple[Tensor, DecoderState, Optional[Tensor]]: ... def forward(self, src, src_lens, tgt_in, teacher_forcing=1.0, rng=None) -> Tensor: ... # [B, T, Vt] def greedy(self, src, src_lens, bos, eos, max_len) -> list[list[int]]: ...def save_seq2seq(model, dir) -> None: ...def load_seq2seq(dir) -> Seq2Seq: ...EncoderState holds the keys, the padding mask, the projected keys, and the bridge output. DecoderState adds the decoder’s h, an LSTM’s c, and Luong’s fed . Because both are NamedTuples updated with _replace, beam search can gather a state by parent index without aliasing. The loss is not part of the model: the caller computes cross_entropy against tgt_out with ignore_index for padding.
Building it step by step
Section titled “Building it step by step”The encoder and the bridge
Section titled “The encoder and the bridge”def encode(self, src, src_lens): s = _ints(src, "src", 2) n = _ints(src_lens, "src_lens", 1) B, S = s.shape # ... (lengths in 1..S) mask = length_mask(n, S) # [B, S], True on real tokens # Padding may hold any id; read it as 0 so the embedding lookup is valid. s = np.where(mask, s, 0) # ... (ids in range) out = bidirectional(self.enc_fwd, self.enc_bwd, self.src_emb(s.T), n) # [S, B, d_h] H2 = self.d_h // 2 rows = np.arange(B) # Forward state after each sequence's own last token; backward state # after reading it back to the first token (position 0). last_f = out[n - 1, rows][:, :H2] first_b = out[0][:, H2:] init = F.tanh(self.bridge(F.concat([last_f, first_b], axis=-1))) keys = F.transpose(out, 0, 1) # batch first for attention: [B, S, d_h] proj = self.attention.project_keys(keys) if self.attention is not None else None return EncoderState(keys, mask, proj, init)Replacing padding ids with 0 before the embedding is what lets callers pad with anything, even out-of-vocabulary ids. The padded embeddings never reach a real position, because bidirectional honors lengths and attention masks them with mask. Reading the final states at each row’s own length, rather than at the padded end , is what keeps short sentences from being summarized from padding.
The decoder step
Section titled “The decoder step”init_state adds what the decoder carries beyond : a zero for an LSTM cell, and a zero (feed) for Luong’s input feeding. Its is enc.init, the bridge output. The step then has one branch per row of the table above:
def decode_step(self, y_prev, state): y = _ints(y_prev, "y_prev", 1) # ... (ids in range) e = self.tgt_emb(y) att = self.attention if att is None: h, c = self._cell(e, state) # bottleneck: the source only via s_0 return self.out(h), state._replace(h=h, c=c), None if att.query_from == "previous": # Bahdanau: read the source with the state from BEFORE this step. ctx, a = att(state.h, state.keys, state.mask, state.proj) h, c = self._cell(F.concat([e, ctx], axis=-1), state) logits = self.out(F.concat([h, ctx], axis=-1)) # the output sees the context too return logits, state._replace(h=h, c=c), a # Luong: step first (input feeding), then read with the NEW state. h, c = self._cell(F.concat([e, state.feed], axis=-1), state) ctx, a = att(h, state.keys, state.mask, state.proj) feed = att.attentional(h, ctx) # h~ = tanh(W_c [c ; h]) return self.out(feed), state._replace(h=h, c=c, feed=feed), aThe shapes in __init__ follow from this code: the cell input is d_emb + d_h with attention (the context or the fed ), and the output layer is 2 * d_h wide only for Bahdanau.
Training as the step loop
Section titled “Training as the step loop”def forward(self, src, src_lens, tgt_in, teacher_forcing=1.0, rng=None): tgt = _ints(tgt_in, "tgt_in", 2) # ... (shape and id checks; rho in [0, 1]; an rng is required when rho < 1) state = self.init_state(self.encode(src, src_lens)) steps = [] y = tgt[:, 0] # bos for t in range(tgt.shape[1]): if t > 0: # rho = 1 short-circuits, so no draw is consumed. if teacher_forcing >= 1.0 or rng.uniform() < teacher_forcing: y = tgt[:, t] # the true previous token else: # The model's own guess: a choice, so no gradient through it. y = np.argmax(steps[-1].data, axis=-1) logits, state, _ = self.decode_step(y, state) steps.append(logits) return F.stack(steps, axis=1) # [B, T, Vt]One rng.uniform() per step decides for the whole batch. Using .data for the argmax makes the fed token a plain integer array, so the gradient never flows through the choice.
Greedy decoding and checkpoints
Section titled “Greedy decoding and checkpoints”greedy runs the same steps under no_grad, feeds back each row’s argmax, appends to a row until it emits eos, and stops early once every row is done. save_seq2seq writes config.json (sizes, cell, and the attention kind: none, bahdanau with tl_d_attn, or luong-<score>) and the state_dict in registration order; load_seq2seq rebuilds the matching attention module and loads strictly. The full solution is model.py.
Why this design
Section titled “Why this design”Encoding costs . Each decoder step is for the cell plus for attention, so a target of length costs . Projecting the keys once in encode removes an term.
A unidirectional encoder would not do. Its last state would know the whole sentence, but each would know only the left context, and attention reads the . The bidirectional encoder gives every key the full sentence.
Why a bridge, and not zeros or a copy? Zeros make the decoder depend on attention alone, or on nothing at all without attention. Copying the encoder state forces the decoder to live in the encoder’s state space. The learned Linear plus tanh decouples them at a cost of parameters.
Why teacher forcing at all? Free running would feed garbage tokens early in training and make the gradient depend on discrete choices. Teacher forcing gives a stable, parallel-in-time loss; the price is exposure bias, which scheduled sampling partly addresses.
The tradeoff accepted is that the decoder loop runs in Python, one step at a time, which is slow for long targets. That is what the transformer’s multi-head attention removes, by attending over the whole target in parallel during training.
Testing it
Section titled “Testing it”The model suite test_seq2seq.py uses the model’s own pieces, recombined by hand, as oracles. It runs enc_fwd and enc_bwd on one unpadded sentence at a time and checks init against ; recomputes one decoder step from cell, attention, and out and compares it with decode_step; and checks that forward equals the step loop and that free running feeds back the argmax. It adds the zero-weights example, padding with out-of-vocabulary ids, a greedy decode that must stop at once (a huge eos bias), and a save and load. It imports only contract modules.
The full set of behaviors a correct solution must have is easiest to see side by side:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| hand example zero weights | unit | the logits , | the data path through the bridge |
| matches torch | golden | logits and every gradient against torch’s bidirectional nn.GRU, GRUCell, LSTMCell, four attention configurations | the model computes what the papers describe |
| forward is the step loop | differential | forward equals decode_step over tgt_in | beam search and the zoo drive the same steps |
| teacher forcing ratio | unit | feeds the model’s argmax, one draw per step; draws nothing | scheduled sampling, reproducibly |
| bahdanau reads with the previous state | unit | the query is , then | Bahdanau’s order |
| luong reads with the new state and feeds input | unit | the query is the new state; reaches the next input; logits read | Luong’s order and input feeding |
| padding never changes a sentence | property | garbage padding (even out-of-vocabulary ids) changes nothing; a row alone equals it in a batch | batches of mixed lengths |
| gradient reaches the encoder | unit | every parameter gets a nonzero gradient | the encoder learns from the decoder’s loss |
| greedy matches step loop and stops at eos | unit | greedy equals its own step loop; eos ends a row | the decoder {tinyllm} translate runs |
| save and load roundtrip | unit | config, key order, identical logits for every attention | the zoo’s checkpoint contract |
| validation | boundary | odd , unknown cell, non-attention module, bad lengths and ids | caller bugs fail loudly |
| attention learns to reverse | learning | 150 steps of AdamW on reversal: exact match at the reference within 3 sd | the model trains |
| attention beats the bottleneck | learning | same budget without attention: at least 0.2 lower exact match | the lesson of this chapter |
The last two rows are the point of the chapter: with the same 150 steps, attention reverses digit strings almost perfectly and the bottleneck model does not.
What can go wrong
Section titled “What can go wrong”Most bugs in an encoder-decoder produce a model that trains, just not the model the papers describe. These are the ones to watch for:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| the decoder starts from zeros (bridge state dropped) | the source reaches the decoder only through attention, or not at all | init_state starts the decoder from enc.init, the bridge output |
teacher forcing fed tgt_in[:, t - 1] at step | the model is asked to copy its input; training loss falls, translation fails | forward feeds tgt[:, t] at step |
| final encoder states read at the padded end or the wrong position | short sentences are summarized from padding | encode reads out[n - 1, rows] forward and out[0] backward, inside each length |
| attention in the wrong place: Luong reading with the old state, Bahdanau’s query not , or its context left out of the output | a different model from the paper’s; golden values disagree | decode_step branches on query_from: att(state.h, ...) before the cell for Bahdanau, att(h, ...) after it for Luong; Bahdanau’s logits read [h ; ctx] |
| no input feeding | the next step never sees | the cell input is [e ; state.feed], and feed is replaced by each step |
| teacher forcing when | still feeds the truth | rng.uniform() < teacher_forcing feeds the truth |
Warning: The off-by-one in teacher forcing is the most insidious. Feeding
tgt_in[:, t - 1]at step asks the model to copy its input, so training loss falls nicely and translation fails completely.
Where this leads
Section titled “Where this leads”Beam search searches over decode_step, gathering DecoderState by parent, and sequence metrics (exact match, BLEU, chrF) grade its outputs. In the next part, the encoder-decoder Transformer keeps the encoder-decoder split and replaces both RNNs with attention. Later, the LM evaluation harness and the model zoo trains and evaluates seq2seq checkpoints on the dates task. At the end of this chapter, {tinyllm} train seq2seq followed by {tinyllm} translate --beam 5 runs this model end to end.
The production equivalents add a good deal on top of this model:
| This piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
Seq2Seq | OpenNMT-py, fairseq LSTM models | multi-layer stacks, dropout, copy attention, batched beam search | OpenNMT-py onmt/models/model.py; fairseq models/lstm.py |
| the bridge | bridge in OpenNMT | a learned map from encoder to decoder state per layer | OpenNMT-py onmt/encoders/rnn_encoder.py |
| teacher forcing ratio | scheduled sampling, professor forcing | curricula for , adversarial matching of free-running dynamics | Bengio et al. 2015; Lamb et al. 2016 |
| encoder-decoder RNN | T5, BART | the same split with transformer blocks and span corruption | T5 span corruption; Hugging Face T5ForConditionalGeneration |
Further reading
Section titled “Further reading”- Sutskever, Vinyals, and Le, “Sequence to Sequence Learning with Neural Networks” (2014).
- Cho et al., “Learning Phrase Representations using RNN Encoder-Decoder” (2014).
- Bengio et al., “Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks” (2015).
- Lamb et al., “Professor Forcing” (2016).
Key terms
Section titled “Key terms”- encoder: the network that reads the whole source once; here a bidirectional GRU whose output at each position sees the full sentence.
- decoder: the network that writes the target one token at a time from its previous token and state.
- bridge: the
Linearplustanhthat maps the encoder’s two final states to the decoder’s first state. - teacher forcing: feeding the true previous target token at every training step.
- exposure bias: the mismatch between training on true tokens and decoding on the model’s own guesses.
- scheduled sampling: training with probability of feeding the true token and of feeding the model’s argmax.
- input feeding: Luong’s practice of feeding the previous attentional state into the next decoder input.
Summary
Section titled “Summary”- An encoder reads the source, a bridge turns its two final states into the decoder’s first state, and the decoder writes the target one token at a time.
- Teacher forcing feeds the true previous token, so training is
decode_stepover the target, all steps in one graph; scheduled sampling sometimes feeds the model’s own guess instead. - Bahdanau attention reads with the state from before the step, Luong’s with the state after it, plus input feeding.
- Each row’s final encoder states are read at its own length, so padding never changes a sentence.
- With the same 150 steps, attention reverses digit strings almost perfectly and the bottleneck model does not.
Review questions
Section titled “Review questions”- Why is the forward half of the bridge read at
n - 1while the backward half is read at0?Answer
The forward GRU has read the whole sentence after its last real token, position $\ell_b - 1$. The backward GRU reads from $\ell_b - 1$ down to 0, so its complete state lands at position 0 once `bidirectional` puts its outputs back in time order. - What would the zero-weights example give if
init_statestarted the decoder from zeros?Answer
Every GRU step halves the state, and half of zero is zero, so every logit would be 0 regardless of the source. The example's nonzero logits $s_0/2$, $s_0/4$ exist only because $s_0$ comes from the bridge. - Why does Bahdanau’s output layer take
[h ; ctx]while Luong’s takes only ?Answer
In Bahdanau's model the context is computed before the step and joins both the cell input and the read-out. In Luong's model the context has already been folded into $\tilde h = \tanh(W_c [c ; h])$, so $\tilde h$ alone carries it. - Why is the argmax in scheduled sampling taken on
steps[-1].datarather than on the Tensor?Answer
Choosing a token is discrete and has no gradient. Taking it from `.data` makes that explicit: the next input is a plain id array, and the graph only connects through the decoder state. - Why must
forwardbe built fromdecode_steprather than a separate batched implementation?Answer
Greedy and beam search can only call `decode_step`. If training used different code, any difference (order of attention, input feeding, the output layer) would mean decoding runs a model that was never trained. - Why can callers pad the source with out-of-vocabulary ids?
Answer
`encode` replaces padded ids with 0 before the embedding lookup, `bidirectional` honors the lengths so padded positions never reach a real one, and attention masks them with `mask`.