AI Wiki中文/EN

Sequence-to-sequence learning: train a model that chooses its own stopping point

Seq2seq 学习

Follow gradients through an encoder and decoder, learn variable-length outputs, and compare greedy and beam decoding.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Reading the source is not the same computation as writing the answer

An invented sequence task asks for 0 1 1 to become 1 1 0. A per-position classifier that sees only the current input symbol cannot solve the reversal: the first output depends on the last input. A sequence model first reads the source, then produces its target one symbol at a time. It also needs to decide when the target is finished.

Sequence-to-sequence learning learns a mapping from an input sequence to an output sequence. The lengths and alignment need not be given token by token. Translation is one application; the small reversal task below makes the data and gradients inspectable. Its content lengths happen to match, but the decoder is not told the desired output length. It must learn to emit EOS.

The encoder–decoder article explains the architectural roles. Here the task is to train all the parameters, pass the target gradient back through the source computation, and inspect what the decoder returns. Sutskever, Vinyals and Le used multilayer LSTMs; this example deliberately substitutes a single-layer tanh RNN so every derivative fits in a short program. Their paper also discusses related encoder–decoder work by Cho and colleagues; this is not a claim of sole invention. Model, §2

A complete encoder-decoder learns 15 invented training reversals. The figure shows actual loss endpoints, three predictions and EOS status; length-4 generalization has not been measured.
A complete encoder-decoder learns 15 invented training reversals. The figure shows actual loss endpoints, three predictions and EOS status; length-4 generalization has not been measured.

One conditional distribution, two recurrent computations

For source x of length L, let its encoder states start at zero. With hidden size H, source embeddings E-s have one H-vector per source symbol, A is H-by-H and a is its bias:

s0=0,si=tanh⁡(Exis+Asi−1+a),i=1,…,L.s_0=0,\qquad s_i=\tanh(E^s_{x_i}+As_{i-1}+a),\quad i=1,\ldots,L.

The final source state initializes the decoder. Decoder embeddings E-t and recurrent matrix W are separate parameters. V maps an H-vector to the output vocabulary of size V-out, and c is an output bias:

h0=sL,ht=tanh⁡(Eutt+Wht−1+b),pt=softmax⁡(Vht+c).h_0=s_L,\qquad h_t=\tanh(E^t_{u_t}+Wh_{t-1}+b),\qquad p_t=\operatorname{softmax}(Vh_t+c).

At the first step u1=BOS. During training later inputs are the preceding true target tokens. During generation they are previously selected outputs. For M target content symbols, add y(M+1)=EOS and obtain:

Pθ(y1,…,yM,EOS∣x)=∏t=1M+1pt(yt),L=−1N∑n,tlog⁡pnt(ynt).P_\theta(y_1,\ldots,y_M,\mathrm{EOS}\mid x)=\prod_{t=1}^{M+1}p_t(y_t),\qquad \mathcal L=-\frac1N\sum_{n,t}\log p_{nt}(y_{nt}).

N counts all supervised target positions across the batch, including EOS. The source uses its explicit array length and has no learned source EOS. Empty source input gives a zero initial decoder state; an empty target still trains an EOS prediction. The implementation loops over each actual sequence, so it needs no padded positions. Vectorized implementations must mask padding without discarding real EOS targets.

For each target step define dz=(p−onehot)/N. With the carry from later decoder steps, the derivative before tanh is:

dat=(VTdzt+WTdat+1)⊙(1−ht2),dzt=(pt−eyt)/N.da_t=(V^Tdz_t+W^Tda_{t+1})\odot(1-h_t^2),\qquad dz_t=(p_t-e_{y_t})/N.

The last carry is zero. Accumulate outer products to update V and W, and add embedding gradients at the input token IDs. After the first decoder step, W-transpose times da1 is the derivative of the loss with respect to h0=sL. That derivative must enter the encoder, whose backward recurrence is:

dri=dsi⊙(1−si2),dsi−1=ATdri.dr_i=ds_i\odot(1-s_i^2),\qquad ds_{i-1}=A^Tdr_i.

The gradient of A adds dr-i times the previous source state transposed; the source embedding and bias receive dr-i. Cutting the connection at sL would train a decoder without teaching the encoder how to represent this task. Numerical differentiation below checks every parameter on both sides of that connection.

Decoding uses the same forward equations with selected tokens. A candidate’s raw score is:

S(y1:t)=∑j=1tlog⁡Pθ(yj∣y<j,x).S(y_{1:t})=\sum_{j=1}^{t}\log P_\theta(y_j\mid y_{<j},x).

If the last token is EOS, this is a complete-sequence log probability. Otherwise it is a prefix log probability. Greedy decoding keeps one extension at each step. Beam decoding retains several candidates, but still prunes paths and need not find a globally best sequence. Adding a length bonus would change the objective; the example uses none. Sequence decoding, beam-search paragraph

Train the complete computation, then inspect its outputs

The complete original program uses Python 3.12 and NumPy 1.26.4. All binary strings of content length 0 through 3 form 15 training examples; each target is the reversed source. H=8, seed=11, learning rate=0.3 and 700 full-batch updates are fixed. The EOS output ID and BOS input ID are both 2, but they have different roles in different input/output tables.

"""Original small tanh encoder-decoder trained to reverse binary symbol strings.

Separate encoder/decoder weights, full BPTT, token-mean teacher-forced loss,
greedy and beam decoding. This is not the multilayer LSTM in Sutskever et al.
Input lengths are explicit; output EOS=2 and decoder BOS=2 have separate roles.
"""
import itertools
import json
import math
import numpy as np

EOS, BOS = 2, 2


def integer(x,low,high):
    if isinstance(x,(bool,np.bool_)) or not isinstance(x,(int,np.integer)) or not low<=x<=high:
        raise ValueError(f'Expected integer in [{low},{high}]')
    return int(x)


def symbols(s):
    s=list(s);integer(len(s),0,32)
    for x in s:integer(x,0,1)
    return s


def initialize(hidden=8,seed=11):
    h=integer(hidden,1,16);rng=np.random.default_rng(integer(seed,0,2**32-1))
    shapes=dict(Es=(2,h),A=(h,h),a=(h,),Et=(3,h),W=(h,h),b=(h,),V=(3,h),c=(3,))
    return {k:rng.normal(0,.3,shape) if len(shape)==2 else np.zeros(shape) for k,shape in shapes.items()}


def parameters(p):
    if set(p)!={'Es','A','a','Et','W','b','V','c'}:raise ValueError('Unexpected parameter keys')
    p={k:np.asarray(v,dtype=float) for k,v in p.items()}
    if p['a'].ndim!=1:raise ValueError('Encoder bias must be a vector')
    h=integer(len(p['a']),1,16)
    shapes=dict(Es=(2,h),A=(h,h),a=(h,),Et=(3,h),W=(h,h),b=(h,),V=(3,h),c=(3,))
    if any(p[k].shape!=s or not np.isfinite(p[k]).all() or (abs(p[k])>100).any() for k,s in shapes.items()):
        raise ValueError('Invalid parameter shape, nonfinite value or magnitude above 100')
    return p


def logsoftmax(z):
    z=z-z.max()
    return z-np.log(np.exp(z).sum())


def encode(p,source):
    p=parameters(p);source=symbols(source);states=[np.zeros(len(p['a']))]
    for word in source:states.append(np.tanh(p['Es'][word]+p['A']@states[-1]+p['a']))
    return states


def step(p,h,previous):
    h=np.tanh(p['Et'][previous]+p['W']@h+p['b'])
    return h,logsoftmax(p['V']@h+p['c'])


def loss_grad(p,pairs):
    p=parameters(p);pairs=list(pairs);integer(len(pairs),1,64)
    pairs=[(symbols(x),symbols(y)) for x,y in pairs]
    total=sum(len(y)+1 for _,y in pairs);loss=0.;g={k:np.zeros_like(v) for k,v in p.items()}
    for source,target in pairs:
        enc=encode(p,source);states=[enc[-1]];probs=[];ys=target+[EOS];xs=[BOS]+target
        for prev,answer in zip(xs,ys):
            h,lp=step(p,states[-1],prev);states.append(h);probs.append(np.exp(lp));loss-=lp[answer]
        carry=np.zeros(len(p['a']))
        for t in range(len(ys)-1,-1,-1):
            dz=probs[t].copy();dz[ys[t]]-=1;dz/=total
            g['V']+=np.outer(dz,states[t+1]);g['c']+=dz
            da=(p['V'].T@dz+carry)*(1-states[t+1]**2)
            g['Et'][xs[t]]+=da;g['W']+=np.outer(da,states[t]);g['b']+=da
            carry=p['W'].T@da
        for t in range(len(source)-1,-1,-1):
            da=carry*(1-enc[t+1]**2)
            g['Es'][source[t]]+=da;g['A']+=np.outer(da,enc[t]);g['a']+=da
            carry=p['A'].T@da
    return float(loss/total),g


def sequence_log_probability(p,source,target):
    p=parameters(p);target=symbols(target);h=encode(p,source)[-1];previous=BOS;value=0.
    for answer in target+[EOS]:
        h,lp=step(p,h,previous);value+=float(lp[answer]);previous=answer
    return value


def decode(p,source,width=1,max_steps=12):
    """Keep the top width candidates, including completed ones, at each depth.

    Raw log-probability ranking, lexicographic tie-breaks, no length bonus.
    Return the best retained candidate with an explicit termination flag.
    Width 1 is greedy; completed candidates are never expanded. This variant
    differs from keeping separate unlimited completed and active queues.
    """
    p=parameters(p);width=integer(width,1,64);max_steps=integer(max_steps,1,32)
    beam=[((),0.,encode(p,source)[-1],BOS,False)]
    for _ in range(max_steps):
        candidates=[]
        for tokens,score,h,prev,done in beam:
            if done:
                candidates.append((tokens,score,h,prev,done));continue
            next_h,lp=step(p,h,prev)
            for token in range(3):
                candidates.append((tokens+(token,),score+float(lp[token]),next_h,token,token==EOS))
        beam=sorted(candidates,key=lambda item:(-item[1],item[0]))[:width]
        if all(item[-1] for item in beam):break
    tokens,score,_,_,done=beam[0]
    return dict(tokens=list(tokens),log_probability=score,terminated=bool(done),beam_width=width)


def demo():
    pairs=[(list(x),list(reversed(x))) for n in range(4) for x in itertools.product((0,1),repeat=n)]
    p=initialize();before,_=loss_grad(p,pairs)
    for _ in range(700):
        _,g=loss_grad(p,pairs);p={k:v-.3*g[k] for k,v in p.items()}
    after,_=loss_grad(p,pairs);predictions=[]
    for source,target in pairs:
        greedy=decode(p,source);beam=decode(p,source,width=4)
        predictions.append(dict(source=source,target=target,greedy=greedy,beam=beam,
            training_exact=greedy['tokens']==target+[EOS] and greedy['terminated']))
    return dict(seed=11,hidden=8,steps=700,training_pairs=len(pairs),
        initial_token_nll=before,final_token_nll=after,
        training_exact_matches=sum(x['training_exact'] for x in predictions),
        predictions=predictions,conditions='All length 0..3 binary strings are training data; no held-out score')


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

Token NLL falls from 1.111693 to 0.002948, and greedy decoding exactly matches all 15 training targets including EOS. This demonstrates fitting the given examples, not generalization. There is no held-out accuracy in this output. Try length-4 sources as a new experiment, and report the 16 cases separately rather than folding them into the training score.

The decoder’s beam variant keeps the best B candidates in one pool containing both completed and active candidates. Completed candidates are not expanded; ties use token-sequence order. This differs from implementations with separate completed and active queues. Width 1 is greedy. At the step cap, the returned best retained item can still be an unfinished prefix, and its flag remains false. Do not silently add EOS or report it as the highest-probability complete sequence.

Checks compare every gradient to central differences, compare loss to complete-sequence probability products, handle empty inputs and different target lengths, and enumerate the entire finite candidate set to check a sufficiently wide beam. Passing the finite enumeration test does not prove that a small beam is exact on arbitrary inputs.

For one pair, training costs O(LH²+M(H²+V-out H)), with EOS adding one target step. Saved states and output probabilities use O((L+M)H+M V-out) space, in addition to parameters. Each decoding step evaluates up to B active states and sorts up to B V-out candidates. Python also copies growing token tuples, adding work proportional to their lengths. Bounds are source/target content length≤32, H≤16, batch≤64, beam≤64 and decoding steps≤32; the output vocabulary here has size three.

Fitting short reversals does not establish long-sequence competence

The single final source vector is a bottleneck, and a plain tanh recurrence can lose useful gradients over long paths. Attention can expose intermediate source representations to the decoder; gated recurrent networks change state and gradient dynamics. Those are changes to the model, not fixes justified solely by a larger training score. The pedagogical model here implements neither.

Separate held-out teacher-forced loss from actual generation under the selected decoding policy. Bengio and colleagues describe the difference between supplying true earlier targets and consuming model outputs. That distinction survives whether the architecture uses tanh units, LSTMs or another decoder. Training versus inference, §§2.2–2.4

EOS is an output choice. Sampling and greedy decoding have different stopping behavior: this finite-parameter, bounded-hidden-state model gives EOS a uniformly positive sampling probability, hence eventual sampled termination with probability one in exact arithmetic, but greedy decoding can keep choosing another symbol forever. If the EOS probability is at least delta>0 at every step, the probability of surviving k further sampled steps is at most (1−delta)^k, which tends to zero. A practical cap still needs an explicit unfinished result. Numerical underflow and resource limits are implementation concerns, not grounds for inventing an EOS event.

If source/target roles, tokenization or sentence boundaries change, repeat the data checks. A model that reverses two symbols on short training strings has not learned translation, factual grounding or reliable extrapolation to longer inputs. Evaluate those claims with their own tasks and splits.

Trace the information and the stopping rule

  1. For source 0 1 and target 1 0, list the decoder training inputs and targets. Is the decoder given the target length at inference?

Answer: Inputs are BOS 1 0; targets are 1 0 EOS. At inference it receives the encoded source and its previous choices, not the desired target length. EOS must be selected.

  1. What happens to encoder learning if the gradient with respect to h0=sL is discarded?

Answer: The target loss supplies no gradient to the encoder through that connection. Updating decoder weights alone cannot teach the source representation to reduce this loss. Full backpropagation must continue into the source states.

  1. A width-1 decoder reaches its cap with [0,0,0] and no EOS. Does its score equal the probability of that complete output?

Answer: No. It is the probability of the selected prefix. The sequence has not terminated, so retain terminated=false; neither an unchosen EOS nor a complete-sequence claim may be added.

  1. All 15 length-0–3 training reversals are correct. How should you test whether the model handles length 4?

Answer: Evaluate the 16 binary length-4 sources without retraining, reporting exact matches including EOS and unfinished outputs separately. Keep this result distinct from the 15/15 training fit; only this new experiment addresses the new length.

Read the model together with its training and search procedures

The linked Sutskever paper is the December 2014 v3; the article uses its conditional sequence formulation, not its benchmark scores or exact LSTM architecture. Bengio and colleagues clarify how the input prefix changes between training and inference. The reversal corpus, tanh implementation, explicit beam variant and derivative checks are original teaching materials.

Make a prediction, then check

The decoder reaches its cap without EOS. What should be returned?

Choose one answer

Learning objectives

  • Train source and target recurrent computations together.
  • Trace target-loss gradients into the encoder.
  • Distinguish complete-sequence and prefix scores.
  • Evaluate a new length separately from training fit.

Prerequisites & connections

Explore related knowledge →

References

  1. Sequence to Sequence Learning with Neural Networks
    Ilya Sutskever, Oriol Vinyals, Quoc V. Le · 2014
  2. Scheduled Sampling for Sequence Prediction with Recurrent Neural Networks
    Samy Bengio, Oriol Vinyals, Navdeep Jaitly, Noam Shazeer · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Single AI author checked six paired equations and four explained exercises against scoped Sutskever v3 and Bengio prefix selection. Original tanh model distinguished from multilayer LSTM. Every source/target parameter checked by central differences, including unequal-length pairs; sequence probability, token weighting, empty input, finite exhaustive beam reference and EOS/cap distinction verified. Training15/15 is limited to15 invented strings; length4 remains an exercise, not measured generalization.

  • Single AI author checked six paired equations and four explained exercises against scoped Sutskever v3 and Bengio prefix selection. Original tanh model distinguished from multilayer LSTM. Every source/target parameter checked by central differences, including unequal-length pairs; sequence probability, token weighting, empty input, finite exhaustive beam reference and EOS/cap distinction verified. Training15/15 is limited to15 invented strings; length4 remains an exercise, not measured generalization.
  • Four computed SVGs bind exact bilingual MDX. The four-topic group passed eight numeric/encoding checks and24 isolated language/width cases with four fallback fonts; eight actual screenshots inspected by the AI author. Literal-prose AST checked before freezing. Full article browser acceptance is separate; no human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.