Encoder–decoder models
编码器—解码器
Separate source encoding from conditional generation, align teacher-forced inputs and targets, and distinguish end tokens from length limits.
encoder-decoderRead a source, then produce an answer of another length
A four-word request can require a ten-word answer. Assigning one output label to each input position is not enough when the output length and alignment are unknown. An encoder turns the source into a representation; a decoder uses that representation to produce an output sequence.
The representation may be one vector, a sequence of vectors, or another structured memory. “Encoder–decoder” describes the division of roles, not a requirement to compress every source into one fixed vector. The decoder is conditional on the source and, in the autoregressive case, on its previous output tokens. D2L, Section 10.6
Factor the output probability in generation order
Let encode the source. Include an end-of-sequence token in target . An autoregressive decoder models:
The probability factorization follows the chain rule; the architecture parameterizes each conditional. A recurrent encoder can update and pass its final state to a recurrent decoder. Sutskever, Vinyals, and Le’s 2014 sequence-to-sequence work used multilayer LSTMs with a fixed-dimensional source representation. That particular implementation is not the definition of every encoder–decoder. Original paper
With attention, the decoder can instead query a sequence of encoder states at each output step. Bahdanau and colleagues proposed this to address limitations of a single source summary in their translation models. It changes access to source information while preserving conditional sequence generation. Original attention paper, Sections 2–3
During teacher forcing, the decoder receives the true previous target token. For target A, B, EOS, the alignment is:
| Step | Decoder input | Target to predict |
|---|---|---|
| 1 | BOS | A |
| 2 | A | B |
| 3 | B | EOS |
BOS is a beginning marker; EOS is an ending marker. Feeding the current target as its own input would leak the answer. At inference, the previous generated token replaces the true previous token. Errors can therefore change later inputs. Padding positions should not contribute to the training objective; normalization should count valid target positions.
Trace a tiny recurrent forward computation
The complete program below implements a scalar recurrent encoder and decoder with fixed, untrained weights. It scores a teacher-forced target and performs greedy generation. It is a wiring demonstration, not a trained translator. Its intentionally limited behavior makes two checks visible: changing the source changes output probabilities, and a model can reach a length limit without generating EOS.
import math
TOKENS = ('A','B','EOS')
EMBED = {'BOS':0.0,'A':1.0,'B':-1.0,'EOS':0.0}
def encode(source):
h = 0.0
for x in source:
if not math.isfinite(x):
raise ValueError("finite source values required")
h = math.tanh(0.5*h+x)
return h
def step(previous, state, context):
state = math.tanh(0.4*state+0.3*EMBED[previous]+0.6*context)
logits = [state,-state,0.2]
m = max(logits)
weights = [math.exp(z-m) for z in logits]
total = sum(weights)
return {t:w/total for t,w in zip(TOKENS,weights)},state
def teacher_loss(source,target):
if not target or target[-1] != 'EOS' or 'EOS' in target[:-1]:
raise ValueError("target must have exactly one final EOS")
if any(t not in TOKENS for t in target):
raise ValueError("unknown target token")
context, state, previous, loss = encode(source),0.0,'BOS',0.0
for actual in target:
probabilities,state = step(previous,state,context)
loss -= math.log(probabilities[actual])
previous = actual
return loss
def generate(source, limit=5):
if type(limit) is not int or limit < 1:
raise ValueError("positive integer length limit required")
context, state, previous, output = encode(source),0.0,'BOS',[]
for _ in range(limit):
probabilities,state = step(previous,state,context)
previous = max(probabilities,key=probabilities.get)
if previous == 'EOS':
return output,True
output.append(previous)
return output,False
assert encode([1,0]) != encode([0,1])
assert step('BOS',0,encode([1]))[0] != step('BOS',0,encode([-1]))[0]
assert math.isfinite(teacher_loss([1,0],['A','B','EOS']))
assert generate([0]) == ([],True)
assert generate([1],3) == (['A','A','A'],False)
assert math.isclose(sum(step('BOS',0,encode([1]))[0].values()),1)
For source length , target length , and vocabulary size , this scalar implementation takes time. Greedy output storage is , with constant recurrent state and temporary probabilities. Larger hidden matrices and source-attention memory add their own costs. During generation, each next token depends on a prior choice, so output steps are sequential even if operations inside a step are parallelized.
A decoder cannot recover distinctions the encoder removed
If two sources map to exactly the same encoder representation, the same decoder and output prefix assign them the same next-token distribution. This follows directly from its inputs. If the task requires different outputs, that representation is insufficient. For example, a count-only encoding merges “A B” and “B A”; it cannot support order-sensitive copying without additional information.
A fixed-width real vector is not a simple proof of an absolute information limit under unlimited precision. Practical limitations involve finite precision, training, architecture, and data. Avoid replacing those issues with the claim that a vector can mathematically hold only a particular number of words.
Greedy decoding maximizes each immediate next-token probability, not necessarily the probability of the whole sequence. Beam search explores more candidates but remains a search approximation with its own length and scoring choices. Reaching a maximum length is an external stop condition, not evidence that the model believes the sequence is complete.
Check the interface between the two halves
- Must source and target lengths agree? Answer: no; the decoder determines the output sequence length through its generation process and stopping rule.
- What should precede the first target token during teacher forcing? Answer: a beginning marker or equivalent initial decoder input, not the first target itself.
- Does a final-state recurrent encoder exhaust the encoder–decoder design space? Answer: no. A decoder can access a sequence or other structured encoder memory.
- Two distinct inputs receive identical encodings. Can this deterministic decoder distinguish them with the same output prefix? Answer: no; its available inputs are identical.
Separate architecture, training, and decoding
Encoder–decoder structure appears in translation, summarization, speech recognition, and image-conditioned generation. A seq2seq training procedure, an attention mechanism, and a decoding search rule answer different design questions. Report them separately so that an improvement in output quality can be connected to a specific change rather than to an ambiguous architecture label.
Make a prediction, then check
For target A, B, EOS, what are the teacher-forced decoder inputs?
Learning objectives
- Factor conditional sequence probabilities and align teacher-forced inputs and targets.
- Run a small recurrent forward computation and distinguish EOS, length limits, and representation loss.
Prerequisites & connections
Explore related knowledge →References
- Dive into Deep Learning — The Encoder–Decoder Architecture
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023 - Sequence to Sequence Learning with Neural Networks
Ilya Sutskever; Oriol Vinyals; Quoc V. Le · 2014 - Neural Machine Translation by Jointly Learning to Align and Translate (v7; first preprint 2014, ICLR 2015)
Dzmitry Bahdanau; Kyunghyun Cho; Yoshua Bengio · 2014
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Independently unrolled three recurrent steps and matched the target-probability product to teacher-forced negative log-likelihood; checked source order, source conditioning, EOS, and length limits.
- Labeled the example as fixed untrained wiring; checked shifted targets, fixed vectors versus state sequences, and indistinguishability under identical encodings.
- Compared bilingual arguments, conditions, examples, and exercise answers; structural checks separately compare formulas, code, sections, and references. No independent human peer review.
Source locations checked:
- Dive into Deep Learning — The Encoder–Decoder Architecture · §10.6: encoder/decoder interfaces and conditional generation
- Sequence to Sequence Learning with Neural Networks · Abstract and submission history: multilayer LSTM encoder and decoder with fixed-dimensional source representation
- Neural Machine Translation by Jointly Learning to Align and Translate (v7; first preprint 2014, ICLR 2015) · v7 §§2–3: conditional sequence factorization and dynamic access to source annotations
Related topics