14 / 28 · Neural Sequence Models
Sequence-to-sequence models
An encoder conditions a decoder on an input sequence. Explicit traces separate teacher forcing, generation, search and BLEU, while a finite-bit example makes the context constraint precise.
On this page 6
A classifier maps an input sequence to one label. A language model predicts a continuation of its own prefix. An encoder–decoder combines these ideas to produce a new sequence conditioned on another sequence. The output can have a different length and vocabulary, and the model must decide when to stop.
Consider normalizing invented equipment commands. A source such as bring-back lamp should produce return lamp; take-out tripod should produce pickup tripod. These are newly specified examples for understanding the computation, not a translation corpus. We will follow one untrained encoder–decoder, separate its probabilities from a search decision, and calculate a small corpus-level text metric.
The task and its data#
Each observation is a pair of sequences: source and target . The tokenizer, target format and end marker are part of the task. An output omitting an item name may look fluent while violating the requested transformation. A normalized command therefore needs a semantic correctness criterion alongside any surface-form score.
In the worked example, source tokens are bring-back and lamp; target tokens are return, lamp and EOS. A separate BOS token initializes decoding. BOS is an input to the first decoder step, not a target to predict in this setup. EOS is a target and is included in the loss because termination must be learned.
A real training set would contain many pairs, with held-out examples selected at the unit where independence is plausible. Near-duplicate templates or commands about the same interaction may leak across a random row split. Here the sole numerical trace is deliberately unfitted, so it supports no held-out quality claim. Its purpose is to expose exactly what conditioning and teacher forcing mean.
Baseline: encoder–decoder with a context vector#
An encoder reads the source and returns a context . In the simplest recurrent design, that context is the encoder’s final valid state. A decoder initializes its state from the context and predicts the target one token at a time. This is the fixed-context encoder–decoder studied by Cho and colleagues and Sutskever, Vinyals and Le.
The conditional probability follows the chain rule:
Each factor depends on the preceding target prefix and the source context. Taking a negative logarithm turns the product into a sum of token losses. Averaging that sum over valid target tokens defines our training reduction. Padding positions must be excluded, while the actual EOS position remains included.
An LSTM can implement either recurrent component, carrying both its hidden and cell state. To make every number visible, our calculation instead uses scalar tanh transitions. Choose source values , zero initial encoder state and
The two encoder states are approximately and . The final one becomes context and initial decoder state . The first update therefore depends on the complete encoded source, even before any target token has been generated.
Define the decoder transition as
where is the embedding of the preceding target token. Supplying the context at every step is an explicit choice of this example; another design may use it only to initialize the state. Source and target embedding tables can differ because their symbols and roles differ.
All target-side parameters are specified here:
| Token | Input embedding | Output weight | Output bias |
|---|---|---|---|
pickup | 0.2 | 0.4 | 0.2 |
return | -0.3 | -0.3 | 0.1 |
lamp | 0.5 | 0.2 | -0.05 |
tripod | -0.4 | -0.1 | 0 |
EOS | 0 | 0.1 | -0.1 |
BOS has input embedding zero and is not in the output vocabulary. For token , the logit is . Softmax over the five logits gives its probability. These weights were chosen to make a transparent trace; no optimization has made them good command-normalization parameters.
During teacher forcing, the next step receives the preceding reference token. The trace for return lamp EOS is:
| Step | Previous input | Decoder state | Reference target | Target probability |
|---|---|---|---|---|
| 1 | BOS | 0.094353 | return | 0.205964 |
| 2 | return | -0.025528 | lamp | 0.182907 |
| 3 | lamp | 0.141579 | EOS | 0.175341 |
The mean negative log probability is approximately . The first factor has a low probability, but the second step still consumes the reference return. Consequently, teacher forcing evaluates the model on the reference prefix, even when its own first choice would have been different.
For generation, choose the largest-probability token after each update and feed it back. With these parameters, a fixed three-step trace consumes BOS, then pickup, then pickup; its states are approximately , and . The first state agrees with teacher forcing because both runs have the same prefix. Subsequent states differ because the inputs differ.
This is a trace for exactly three steps, not successful EOS-terminated generation. A practical decoder stops on EOS and also imposes a maximum length to avoid an unbounded run. Its treatment of empty output, invalid target syntax and length limits belongs in evaluation. Teacher-forced likelihood alone does not establish that generated outputs satisfy the task.
BLEU: measuring a translation#
Text generation often admits several correct phrasings. Exact string equality can be too strict, while unigram overlap can ignore order and reward repetition. BLEU combines clipped n-gram precision with a brevity penalty. Papineni and colleagues define the corpus-level calculation; our example uses only orders one and two with equal weights, explicitly called BLEU-2.
For each candidate sentence, count each n-gram. Its credited count is capped by the count in that sentence’s reference. Then sum credited counts and candidate counts across the corpus before dividing. Clipping prevents repeated occurrences from receiving credit beyond the available reference evidence. It does not make the metric a semantic equivalence test.
Use these independently supplied candidates and references:
| Candidate | Reference |
|---|---|
return lamp now | return lamp tomorrow |
collect tripod | collect tripod at desk |
Tokenization is case-sensitive whitespace splitting, with one reference per candidate and no smoothing. The first pair matches two unigrams out of three and one bigram out of two. The second matches two unigrams out of two and one bigram out of one. Aggregate precisions are therefore
The candidates contain five tokens altogether; the references contain seven. Let and denote the corpus candidate and reference lengths. The brevity penalty and BLEU-2 are
Here the penalty is , and the final score is approximately on the zero-to-one scale. A shortened output can retain high precision, so the length penalty matters. Averaging two sentence-level scores would perform a different aggregation from the specified corpus calculation.
The unsmoothed fixed-order score becomes zero if a required n-gram order has no credited matches. Our executable convention also returns zero when a required order has no candidate n-grams. Smoothing and effective-order variants make different choices and must be identified when reporting scores. Standard benchmark BLEU commonly uses four orders; this two-order classroom-sized calculation is not directly comparable to it.
More references can credit multiple formulations, but the one-reference case here remains narrow. Changing tomorrow to now alters the command while preserving most tokens. A paraphrase can do the reverse: preserve the intended action while changing many n-grams. For normalized equipment commands, exact action/item fields and error analysis would address failures that overlap alone misses.
Probability, search and observed results#
The model assigns probabilities; a decoding algorithm chooses a sequence using them. Picking the largest conditional probability at every step need not maximize the product over a complete sequence. To isolate this issue, use a separate hand-specified conditional tree. It is not the output of the neural parameters above.
| Prefix | Next pickup | Next return | Next EOS |
|---|---|---|---|
BOS | 11/20 | 2/5 | 1/20 |
pickup | 3/10 | 1/4 | 9/20 |
return | 1/20 | 1/20 | 9/10 |
Every row sums to one. Restrict the comparison to completed sequences of at most two emitted tokens, including EOS. Greedy decoding first chooses pickup, then EOS. Its sequence probability is
The alternative return EOS has probability
Immediate EOS has probability . Exhaustively enumerating these three completed candidates identifies return EOS as the best in the stated length bound. The example demonstrates a local-choice failure without claiming a global answer for arbitrarily long sequences.
Beam search retains several prefixes. With width two, the first step keeps pickup and return. Expanding those prefixes and keeping the two highest raw sequence probabilities gives return EOS and pickup EOS here. Completed hypotheses are retained without being expanded. The result agrees with exhaustive enumeration in this small tree. A finite beam can discard a prefix that would later become the best, so this agreement is not a general optimality guarantee.
Raw products decrease as additional factors at most one are multiplied. Comparing different lengths can therefore prefer short completions. A length-normalized search score can change that preference, but it also changes the objective being optimized. Record the search rule separately from model parameters and report whether probabilities or transformed scores selected the output.
What finite context can preserve#
A fixed context creates a specific information constraint: after encoding, the decoder has no direct access to the source positions. The encoder must preserve everything the target may later need. That is manageable for some tasks and difficult for others; merely having unequal input/output lengths does not prove failure.
A finite-capacity argument makes the assumption explicit. There are length-six strings over a four-symbol alphabet. An eight-bit context has only possible states. At least two source strings must share a context. If the required target must distinguish all source strings exactly, a decoder receiving only that context cannot always succeed.
This argument concerns a declared finite-bit representation. It is not a claim that a mathematical vector of infinitely precise real numbers can never encode many discrete strings. Nor does the task always require reconstructing the entire source: a yes/no label may intentionally identify many inputs with one output. The relevant question is which distinctions the target requires and whether the representation can preserve them reliably.
With learned finite-precision states, optimization and generalization introduce further difficulties beyond a counting bound. Distant source facts may be compressed together, and the decoder may need different facts at different steps. Keeping the sequence of encoder states and retrieving a weighted context at each output position provides another route; this motivates attention.
What changed#
A single final label became a conditional sequence with its own prefix and termination rule. Teacher forcing supplied target history during training; generation supplied model history. A text metric and a search algorithm added two decisions that are separate from the neural architecture. Their conventions can change reported behavior without changing the model weights.
Limitations#
The fixed context may lose source distinctions. Generated prefixes may depart from training prefixes. A search approximation may miss a high-probability completion, and a high-probability completion may still be wrong for the application. An overlap score may reward an output with the wrong action or timing. These failures require different diagnostics rather than one summary score.
Our numerical traces verify declared transitions, probabilities, search and metric arithmetic. There is no trained translation model or empirical claim about a language pair. For an actual task, preserve train/test boundaries, define semantic failure costs, inspect generated outputs and state the exact tokenizer, metric and decoding protocol.
What you should remember#
An encoder–decoder models a target sequence conditional on a source. EOS is a prediction target. Teacher forcing and generation feed different prefixes. Search and model probabilities are separate. BLEU needs a declared order, tokenization and aggregation. A fixed context’s adequacy depends on which source distinctions the target requires.
Reproducible example#
- The sequence-to-sequence calculation in the standalone script contains the chosen encoder/decoder parameters, both prefix traces, exact rational search tree with a width-two beam, exhaustive bounded comparison and corpus BLEU-2. Saved results separate the unfitted neural outputs from the independently specified search example. No external data or model download is used.
Next#
Attention before Transformers lets each decoder step consult all encoder states. We will derive the weighting operation and its gradients, then distinguish a useful alignment diagnostic from a causal explanation.
References#
- Kyunghyun Cho, Bart van Merriënboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, Yoshua Bengio. Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation, 2014, sections 2.1–2.2: conditional sequence probabilities and the fixed-context encoder–decoder.
- Ilya Sutskever, Oriol Vinyals, Quoc V. Le. Sequence to Sequence Learning with Neural Networks, 2014, section 2: encoder–decoder modeling with different sequence lengths and an end symbol. Paper datasets, reversals, examples and benchmark results are not reproduced.
- Kishore Papineni, Salim Roukos, Todd Ward, Wei-Jing Zhu. BLEU: a Method for Automatic Evaluation of Machine Translation. ACL, 2002, sections 2.1–2.3: clipped n-gram precision, corpus brevity penalty and geometric aggregation. The two-order case and strings above are newly specified.