Course contents 14 / 28

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 x1:Tx_{1:T} and target y1:Uy_{1:U}. 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 cc. 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:

p(y1:U∣x1:T)=∏u=1Up(yu∣y1:u−1,c).p(y_{1:U}\mid x_{1:T}) =\prod_{u=1}^{U}p(y_u\mid y_{1:u-1},c).

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 (0.5,−0.25)(0.5,-0.25), zero initial encoder state and

ht=tanh⁡(0.5ht−1+0.4xt+0.1).h_t=\tanh(0.5h_{t-1}+0.4x_t+0.1).

The two encoder states are approximately 0.2913130.291313 and 0.1446350.144635. The final one becomes context c=0.144635c=0.144635 and initial decoder state s0=cs_0=c. The first update therefore depends on the complete encoded source, even before any target token has been generated.

Define the decoder transition as

su=tanh⁡(0.6su−1+0.3eu−1+0.4c−0.05),s_u=\tanh\bigl(0.6s_{u-1}+0.3e_{u-1}+0.4c-0.05\bigr),

where eu−1e_{u-1} 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:

TokenInput embeddingOutput weightOutput bias
pickup0.20.40.2
return-0.3-0.30.1
lamp0.50.2-0.05
tripod-0.4-0.10
EOS00.1-0.1

BOS has input embedding zero and is not in the output vocabulary. For token jj, the logit is wjsu+bjw_js_u+b_j. 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:

StepPrevious inputDecoder stateReference targetTarget probability
1BOS0.094353return0.205964
2return-0.025528lamp0.182907
3lamp0.141579EOS0.175341

The mean negative log probability is approximately 1.6732831.673283. 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 0.0943530.094353, 0.1238270.123827 and 0.1412010.141201. 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:

CandidateReference
return lamp nowreturn lamp tomorrow
collect tripodcollect 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

p1=2+23+2=45,p2=1+12+1=23.\begin{aligned} p_1&=\frac{2+2}{3+2}=\frac45,\\ p_2&=\frac{1+1}{2+1}=\frac23. \end{aligned}

The candidates contain five tokens altogether; the references contain seven. Let LcL_c and LrL_r denote the corpus candidate and reference lengths. The brevity penalty and BLEU-2 are

BP=exp⁡(min⁡(0,1−Lr/Lc)),BLEU2=BPp1p2.\begin{aligned} \mathrm{BP}&=\exp\bigl(\min(0,1-L_r/L_c)\bigr),\\ \mathrm{BLEU}_2&=\mathrm{BP}\sqrt{p_1p_2}. \end{aligned}

Here the penalty is exp⁡(−0.4)≈0.670320\exp(-0.4)\approx0.670320, and the final score is approximately 0.4895330.489533 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.

PrefixNext pickupNext returnNext EOS
BOS11/202/51/20
pickup3/101/49/20
return1/201/209/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

1120920=99400=0.2475.\frac{11}{20}\frac{9}{20}=\frac{99}{400}=0.2475.

The alternative return EOS has probability

25910=925=0.36.\frac25\frac9{10}=\frac9{25}=0.36.

Immediate EOS has probability 0.050.05. 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 46=40964^6=4096 length-six strings over a four-symbol alphabet. An eight-bit context has only 28=2562^8=256 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#