AI Wiki中文/EN

Teacher forcing: train on the right prefix

Teacher forcing

Shift targets without leaking the answer, mask padding and differentiate the full recurrent computation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The previous answer is an input, not the answer being predicted

Consider the invented target sequence 0 1 0. To predict its second symbol, a training example can provide the first true symbol, 0. It must not provide the second symbol, 1, in the input used for that prediction. Teacher forcing means using the observed earlier target symbols as the decoder’s prefix during training. At generation time those target symbols are unavailable, so the decoder instead consumes its own outputs.

For this example the inputs are BOS 0 1 0, and the supervised targets are 0 1 0 EOS. BOS starts decoding; EOS is an output that ends it. There are four prediction losses, not three. A model that learns the words but never learns when to stop has not learned the complete sequence distribution. This shift follows the conditional sequence factorization used in neural sequence learning. Conditional generation, §2

Three implementation choices are separate: where the prefix tokens come from, which positions contribute to the loss, and how far gradients travel through the hidden states. Teacher forcing specifies the first. It does not mean ignoring padding incorrectly, seeing a future target, or detaching the hidden state after every token.

Shifted targets and padding masks keep the answer out of its own input. A separate training example compares loss endpoints and full versus detached recurrent gradients.
Shifted targets and padding masks keep the answer out of its own input. A separate training example compares loss endpoints and full versus detached recurrent gradients.

A likelihood of complete observed sequences

Let a target contain T content tokens, set y0=BOS and y(T+1)=EOS, and let x denote any source input. The chain rule gives:

Pθ(y1,…,yT,EOS∣x)=∏t=1T+1Pθ(yt∣y<t,x).P_\theta(y_1,\ldots,y_T,\mathrm{EOS}\mid x)=\prod_{t=1}^{T+1}P_\theta(y_t\mid y_{<t},x).

The prefix on the right is the observed prefix when evaluating the probability of this particular training sequence. Feeding a sampled replacement prefix while keeping the original next-token label generally evaluates a different objective. Bengio and colleagues make this training/inference difference explicit and propose scheduled sampling; that proposal should not be confused with the definition of ordinary likelihood. Training and prefix selection, §§2.2–2.4

For a padded batch, let the boolean mask m be one at every real target position, including EOS, and zero at padding. With N valid positions, the token-mean negative log likelihood is:

N=∑n,tmnt,L=−1N∑n,tmntlog⁡Pθ(ynt∣yn,<t,xn).N=\sum_{n,t}m_{nt},\qquad \mathcal L=-\frac1N\sum_{n,t}m_{nt}\log P_\theta(y_{nt}\mid y_{n,<t},x_n).

Padding must neither create a supervised token nor enlarge N. An empty content sequence still has one valid target, EOS. Dividing each sentence by its own length before averaging gives a different weighting from this token mean:

∑nℓn∑nNn≠1B∑nℓnNnin general.\frac{\sum_n\ell_n}{\sum_n N_n}\ne\frac1B\sum_n\frac{\ell_n}{N_n}\quad\text{in general}.

Here ell-n is the sentence’s summed negative log likelihood, N-n includes EOS, and B is the number of sentences. If two sentences have 3 and 1 valid tokens, their token-mean losses receive weights 3/4 and 1/4. Pick a reduction deliberately and use the same convention in reported measurements.

The program uses a small unconditional tanh RNN. E is a 5-by-H input embedding matrix, W is H-by-H, V is 3-by-H, and b and c are biases. Input IDs include BOS and PAD; the three output classes are the two content symbols and EOS. Starting from a zero hidden state:

ht=tanh⁡(Eut+Wht−1+b),zt=Vht+c,pt=softmax⁡(zt),ut=yt−1.h_t=\tanh(E_{u_t}+Wh_{t-1}+b),\quad z_t=Vh_t+c,\quad p_t=\operatorname{softmax}(z_t),\quad u_t=y_{t-1}.

For a valid token, softmax and cross-entropy give dz=(p−onehot)/N. The hidden derivative also receives contributions from later losses:

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

The final carry is zero. At earlier steps the W-transpose term is usually nonzero even though the input tokens are fixed observations. Removing it changes the gradient. The detach_history option below deliberately removes that term as a comparison; its returned gradient is then a truncated gradient, not the derivative of the full displayed loss.

There is no contradiction between correct likelihood training and possible generation-time distribution shift. For a normalized model Q over complete sequences, expected data negative log likelihood satisfies:

EY∼P[−log⁡Q(Y)]=H(P)+DKL(P∥Q).\mathbb E_{Y\sim P}[-\log Q(Y)]=H(P)+D_{\mathrm{KL}}(P\|Q).

This identity assumes the expectations exist, with infinite loss allowed when Q assigns zero mass to a possible data sequence. It does not guarantee that a finite model, dataset or optimizer recovers P. Nor does a low teacher-forced loss certify good free-running generation.

Make the shift and the gradient visible

Run this complete original program with Python 3.12 and NumPy 1.26.4. It trains on two invented sequences, 0 1 0 and 1 0 1. The model has H=3, seed 7, and takes 400 gradient steps at learning rate 0.2. This is a training demonstration, not a language benchmark or a reproduction of a paper’s LSTM.

"""Original NumPy RNN: shifted teacher inputs, masked token NLL and full BPTT.

Tokens 0/1 are invented symbols; EOS=2, BOS=3 and PAD=4. This is a
small unconditional language model, not a reproduction of a translation model.
"""
import json
import numpy as np

EOS, BOS, PAD = 2, 3, 4


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


def initialize(hidden=3, seed=7):
    hidden = integer(hidden, 1, 16)
    rng = np.random.default_rng(integer(seed, 0, 2**32-1))
    return dict(E=rng.normal(0, .25, (5, hidden)), W=rng.normal(0, .25, (hidden, hidden)),
                V=rng.normal(0, .25, (3, hidden)), b=np.zeros(hidden), c=np.zeros(3))


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


def pack(sequences, pad_to=None):
    integer(len(sequences), 1, 32)
    sequences = [list(s) for s in sequences]
    for s in sequences:
        integer(len(s), 0, 63)
        for token in s:
            integer(token, 0, 1)
    width = max(len(s)+1 for s in sequences)
    width = width if pad_to is None else integer(pad_to, width, 64)
    x = np.full((len(sequences), width), PAD, dtype=int)
    y = np.full_like(x, -1)
    mask = np.zeros(x.shape, dtype=bool)
    for row, s in enumerate(sequences):
        n = len(s)+1
        x[row,:n], y[row,:n], mask[row,:n] = [BOS]+s, s+[EOS], True
    return x, y, mask


def batch(x, y, mask):
    x, y, mask = np.asarray(x), np.asarray(y), np.asarray(mask)
    if x.ndim != 2 or x.shape != y.shape or x.shape != mask.shape:
        raise ValueError('Batch arrays must have the same two-dimensional shape')
    integer(x.shape[0], 1, 32); integer(x.shape[1], 1, 64)
    if x.dtype.kind not in 'iu' or y.dtype.kind not in 'iu' or mask.dtype.kind != 'b':
        raise ValueError('Integer tokens and a boolean mask are required')
    for a, b, m in zip(x, y, mask):
        n = int(m.sum())
        if n < 1 or not m[:n].all() or m[n:].any():
            raise ValueError('Only nonempty contiguous valid prefixes are supported')
        if a[0] != BOS or b[n-1] != EOS or ((b[:n-1]<0)|(b[:n-1]>1)).any():
            raise ValueError('Use BOS, content symbols and one final EOS')
        if not np.array_equal(a[1:n], b[:n-1]) or (a[n:] != PAD).any() or (b[n:] != -1).any():
            raise ValueError('Inputs must be shifted targets followed by padding')
    return x, y, mask


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


def loss_grad(p, x, y, mask, detach_history=False):
    """Token-mean loss; detach_history is an intentionally truncated-gradient control."""
    p = parameters(p); x, y, mask = batch(x, y, mask)
    if not isinstance(detach_history, bool):
        raise ValueError('detach_history must be boolean')
    grad = {k: np.zeros_like(v) for k,v in p.items()}
    probs = np.zeros((*x.shape, 3)); total = int(mask.sum()); loss = 0.
    for row in range(len(x)):
        states = [np.zeros(len(p['b']))]
        n = int(mask[row].sum())
        for t in range(n):
            h = np.tanh(p['E'][x[row,t]] + p['W'] @ states[-1] + p['b'])
            lp = logsoftmax(p['V'] @ h + p['c'])
            probs[row,t] = np.exp(lp); loss -= lp[y[row,t]]
            states.append(h)
        carry = np.zeros(len(p['b']))
        for t in range(n-1, -1, -1):
            dz = probs[row,t].copy(); dz[y[row,t]] -= 1; dz /= total
            grad['V'] += np.outer(dz, states[t+1]); grad['c'] += dz
            dh = p['V'].T @ dz + carry
            da = dh * (1-states[t+1]**2)
            grad['E'][x[row,t]] += da; grad['W'] += np.outer(da, states[t]); grad['b'] += da
            carry = np.zeros_like(carry) if detach_history else p['W'].T @ da
    return float(loss/total), grad, probs


def generate(p, max_steps=16):
    """Greedy decoding; the cap returns a truncated prefix, never a fabricated EOS."""
    p = parameters(p); max_steps = integer(max_steps, 1, 64)
    h = np.zeros(len(p['b'])); token = BOS; output = []; logp = 0.
    for _ in range(max_steps):
        h = np.tanh(p['E'][token] + p['W'] @ h + p['b'])
        lp = logsoftmax(p['V'] @ h + p['c']); token = int(np.argmax(lp))
        output.append(token); logp += float(lp[token])
        if token == EOS:
            return dict(tokens=output, terminated=True, log_probability=logp)
    return dict(tokens=output, terminated=False, log_probability=logp)


def demo():
    p = initialize(); x,y,m = pack([[0,1,0], [1,0,1]])
    before, full, _ = loss_grad(p,x,y,m)
    _, truncated, _ = loss_grad(p,x,y,m,detach_history=True)
    difference = float(np.linalg.norm(full['E']-truncated['E']))
    for _ in range(400):
        _,g,_ = loss_grad(p,x,y,m)
        p = {k:v-.2*g[k] for k,v in p.items()}
    after,_,_ = loss_grad(p,x,y,m)
    return dict(symbols={'EOS':EOS,'BOS':BOS,'PAD':PAD}, teacher_inputs=x.tolist(),
                targets=y.tolist(), valid_tokens=int(m.sum()), initial_token_nll=before,
                final_token_nll=after, full_vs_detached_embedding_gradient_l2=difference,
                greedy=generate(p), steps=400, seed=7)


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

The initial token NLL is 1.090521; the final value is 0.205453. Greedy decoding returns 1 0 1 EOS, with complete-sequence log probability −0.820675. At initialization, full and detached embedding gradients differ by L2 distance 0.018125 even though their forward probabilities and loss are identical.

The tests differentiate every parameter numerically, change future labels while checking earlier predictions, and append padding while checking identical loss and gradients. These tests catch different failures: target leakage, bad normalization and broken backpropagation cannot be diagnosed by a declining training loss alone.

With B sequences, padded width T, hidden size H and output vocabulary V, recurrent work is proportional to the valid-token count times H²+VH. The implementation stores a B-by-T-by-V probability array and one sentence’s hidden states, in addition to parameters and gradients. Teaching bounds are B≤32, T≤64 including EOS, and H≤16. These bounds are for inspecting calculations, not recommended production dimensions.

Evaluate what the model does without the answer sheet

Evaluate held-out likelihood with correctly shifted true prefixes, then separately evaluate generation with the actual decoding policy. Report EOS failures, repeated output, task-specific correctness and length limits alongside any token loss. A cap returns an unfinished prefix; appending EOS afterward would invent an event the model did not choose. Positive EOS sampling probability also does not force greedy decoding to ever select it.

Padding here must form a trailing suffix. Packed or interleaved sequences require a different state/mask contract. The program uses plain gradient descent without batching optimizations, clipping or attention. Such engineering choices do not change the distinction between observed prefixes and gradient flow. For the recurrent derivative itself, see backpropagation through time; for source-conditioned architecture, see encoder–decoder models.

Locate the error before changing the optimizer

  1. The target is 1 0. Write the valid inputs and labels. How many loss terms are there?

Answer: Inputs BOS 1 0, labels 1 0 EOS, three terms. Providing 1 as the first input would reveal the first answer rather than the preceding symbol.

  1. Two sentences have 3 and 1 valid tokens, with mean losses 2 and 6. Compare token-mean and sentence-mean loss.

Answer: Token mean is (3×2+1×6)/4=3. Sentence mean is (2+6)/2=4. The difference is weighting, not floating-point noise.

  1. Does teacher forcing require setting the recurrent gradient carry to zero after every step?

Answer: No. The hidden state affects later predictions even when all inputs are observed tokens. Removing the carry discards those derivative paths; the program’s two gradient modes provide a numerical counterexample.

  1. A model’s validation NLL improves, but greedy output never emits EOS within the cap. Can the capped string be reported as a successful complete generation?

Answer: No. Keep the termination flag false and report the failure. Likelihood and free-running decoding answer different questions; test both before choosing a remedy.

Read the training objective and the sampling rule separately

Sutskever, Vinyals and Le’s sequence-learning paper supplies the conditional-generation setting. Bengio and colleagues spell out the change in prefix source and one proposed response. This article’s scalar losses, gradients and binary examples come from its own small program. No published benchmark scores or scheduled-sampling improvements are reproduced here.

Make a prediction, then check

Does teacher forcing require detaching hidden-state gradients after every token?

Choose one answer

Learning objectives

  • Shift targets so no current answer enters its own predictor.
  • Mask padding while retaining the EOS loss.
  • Distinguish teacher inputs from truncated recurrent gradients.
  • Interpret token-mean loss separately from generation quality.

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 conditional sequence likelihood and scoped scheduled-sampling training/inference discussion. Verified BOS shift, EOS loss, padding invariance, token-versus-sentence weighting, future-target nonleakage and every full BPTT derivative. Same forward pass but embedding gradient difference0.018125 demonstrates that teacher forcing does not imply hidden-state detachment. Likelihood identity and generation behavior retain their separate assumptions.

  • Single AI author checked six paired equations and four explained exercises against conditional sequence likelihood and scoped scheduled-sampling training/inference discussion. Verified BOS shift, EOS loss, padding invariance, token-versus-sentence weighting, future-target nonleakage and every full BPTT derivative. Same forward pass but embedding gradient difference0.018125 demonstrates that teacher forcing does not imply hidden-state detachment. Likelihood identity and generation behavior retain their separate assumptions.
  • 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.