Training Recurrent Networks
Teacher forcing, exposure bias, truncated backpropagation and online gradients.
Gradient descent on a recurrent network hides three decisions that the loss function never mentions: what the network is fed while it learns (the truth or its own guesses), how far back each gradient may travel, and whether the gradient is computed after the sequence ends or while it is still arriving. Each decision trades bias against variance and memory, and each has a sharp theory behind it.
What you’ll learn
- Explain teacher forcing and exposure bias, state the compounding-error bound for learners trained on the expert's states, and show why scheduled sampling is not a consistent estimator.
- Write the truncated-BPTT gradient as the full gradient minus a dropped tail, bound the tail, and explain why the bias bites exactly when long memory is needed.
- Derive real-time recurrent learning as forward-mode differentiation, with time and memory per step for a fully connected network.
- Prove that UORO is unbiased, compare it with KF-RTRL, SnAp and e-prop, and explain why element-wise recurrence makes exact online gradients cheap.
Teacher forcing and exposure bias
An autoregressive model factorizes , and maximum likelihood maximizes with every factor conditioned on the true prefix . Feeding the ground truth as the next input is teacher forcing, a name introduced by Williams & Zipser (1989), who noted the technique was already in common use. Nothing is approximated: teacher forcing computes the exact gradient of the log-likelihood, and with a correct model class and unlimited data it recovers the true conditionals.
At generation time, though, the model conditions on its own samples. It has only ever been trained on prefixes drawn from the data, never on prefixes drawn from itself. Ranzato et al. (2016) named this train–test mismatch exposure bias. How badly can it hurt? Imitation learning, where a policy is trained to copy an expert's actions on the expert's own trajectories, gives a sharp answer.
The intuition is short. A first mistake happens with probability about per step, and it can take the learner to states its training never covered, where it may keep erring for the rest of the episode. Summing up to remaining steps over possible times of the first mistake gives order . Ross, Gordon & Bagnell recount a sequence-prediction example due to Kääriäinen (2006): a predictor with error rate when given the correct previous output makes, in expectation, mistakes when fed its own outputs, which is for small . With and that is about 9.4 mistakes, against if the errors stayed independent.
Think first Does the theorem show that teacher-forced language models must degrade quadratically with length?
No. It is a worst-case bound for a 0–1 notion of mistakes, and it is tight only on adversarially constructed problems. A language model's next-token distribution can put weight on many acceptable continuations, and a model that predicts well can often recover after an unusual token. The theorem identifies the mechanism, a shift from the data's prefixes to the model's own, not its size in any particular application.
Scheduled sampling and its critics
Scheduled sampling (Bengio, Vinyals, Jaitly & Shazeer, 2015) exposes the model to its own predictions during training. At each step it feeds the true previous token with probability and a token sampled from the model's own prediction with probability , where counts training iterations and decays from 1 toward 0 on a linear, exponential or inverse-sigmoid schedule. The target stays the true next token. It improved image captioning, parsing and speech recognition in the original experiments. Huszár (2015) then showed that the objective is improper: its optimum is not the data distribution, so the method is not a consistent estimator. The extreme case makes the problem visible.
Let be the prefix actually fed at step , a mixture of true and sampled tokens. The step- loss is the cross-entropy of the true under the model's prediction from (no gradient flows through the sampling):
With unlimited capacity, each conditional is fitted separately, and cross-entropy is minimized by the true conditional distribution of the target given what was fed:
At every fed token is the model's own sample, drawn independently of the true sequence given . The fed prefix then carries no information about , and the optimum is the marginal: the trained model generates every token independently, destroying all dependencies between output tokens.
For the model learns the true next token given a corrupted copy of the true prefix, which is still not the conditional that sampling needs. Only , plain teacher forcing, is consistent.
Two other responses change the objective rather than the inputs. Sequence-level training samples whole outputs from the model and optimizes a sequence metric such as BLEU with policy gradients, so training happens on the model's own prefixes (Ranzato et al., 2016). Professor forcing (Lamb et al., 2016) adds a discriminator that sees the sequence of hidden states from a teacher-forced run and from a free-running run; the RNN is trained to make the two indistinguishable, so its dynamics stay close to the teacher-forced regime when sampling. Lamb et al. report better likelihoods on character-level Penn Treebank and sequential MNIST, and better samples over long horizons.
Why is scheduled sampling not a consistent estimator, even with unlimited capacity and data?
- Its gradient is too noisy to converge
- The fed prefix may contain the model's own samples while the target is the true next token, so the optimum is the conditional of the true token given a corrupted prefix, not the data distribution's conditional
- It uses a decaying schedule, and any schedule introduces bias
- Sampling is not differentiable, so the gradient is wrong
Show the answer
B. The fed prefix may contain the model's own samples while the target is the true next token, so the optimum is the conditional of the true token given a corrupted prefix, not the data distribution's conditional
Cross-entropy is minimized by the true conditional of the target given whatever was fed. When the fed prefix is partly sampled, that conditional mixes information about the true prefix with noise; in the limit of all-sampled inputs it is the marginal . This is Huszár's (2015) improperness argument.
Long products: truncation and stabilization
Write for the direct gradient of the step- loss, for the Jacobian product of Recurrent Neural Networks, and for the immediate derivative of with respect to (the parameters entering at step alone). Truncated BPTT with a window of steps keeps only the recent terms.
The exact gradient of sums over every step at which was used; truncation keeps the last :
The bias is the dropped tail. With the Jacobian bound , , and , it is a geometric series:
Read the bound both ways. If the dynamics contract quickly, the dropped tail is exponentially small in and truncation costs little, but then long-range gradient terms were negligible anyway. A network that actually carries information over more than steps has Jacobian products of norm near 1 over those spans; the bound no longer applies and the dropped terms are as large as the kept ones. Truncation removes precisely the signal that long-range learning needs.
Because is biased, stochastic gradient descent on it need not approach a stationary point of the true loss, and Tallec & Ollivier (2018) point out that this can even make training diverge. In practice the window is set to the dependency lengths one hopes to learn; for word-level LSTM language models, windows of a few dozen tokens were common.
The same long products explode when grows. Gradient clipping caps the update (Pascanu, Mikolov & Bengio, 2013). A more structural fix keeps the recurrent matrix exactly norm-preserving: the unitary RNN of Arjovsky, Shah & Bengio (2016) builds from a product of cheap unitary factors (diagonal phases, reflections, a permutation and Fourier transforms), so every eigenvalue has modulus 1. A norm-preserving has its own cost: such a network cannot easily forget, and the nonlinearity's slopes still multiply in, as the widget shows.
Real-time recurrent learning
BPTT is an offline algorithm: it waits for the sequence to end and stores every state. A robot, a trading system or a model reading an endless stream needs a gradient now, with memory that does not grow with time. Real-time recurrent learning (RTRL; Williams & Zipser, 1989) gets one by running differentiation forward alongside the network, in forward mode. Write the network as with parameters, and carry the influence matrix .
Differentiate the recurrence: affects through and directly. With and the immediate derivative :
Unrolling gives , so contains exactly the terms of BPTT, summed in a different order. Each loss's gradient is available at the moment the loss is incurred, and the parameters can be updated at every step.
For a fully connected tanh RNN, , and the recurrent matrix alone contributes parameters. then has entries, and the product costs multiply-adds per step:
For a fully connected RNN with units, how many entries does the influence matrix have for the recurrent weights alone? Answer in millions.
Show the answer
2.1 million
, about 2.1 million numbers (8.4 MB in 32-bit floats), updated at every step with multiply-adds, while a step of the network itself costs about . Doubling multiplies RTRL's time per step by 16.
Why is forward mode so expensive here? It carries one tangent direction per parameter, of them, while reverse mode carries one cotangent per scalar output, and a loss is a single scalar. Reverse mode wins on arithmetic and loses on memory, because it must remember the past. One caveat applies to every online method: when changes at every step, mixes sensitivities computed under old parameters, so the gradient is exact only in the limit of small learning rates.
Cheaper online gradients
UORO (Unbiased Online Recurrent Optimization; Tallec & Ollivier, 2018) replaces by a random rank-one matrix with and , updated with a fresh vector of random signs at each step and positive scalars chosen to reduce the variance:
The update multiplies the state factor by the dynamics and injects noise; the parameter factor collects the noise's image under :
Expand the product. The 's cancel in the first and last terms:
The fresh signs are independent of the past, with and . The variance-minimizing depends on but is unchanged when flips sign, so the two cross terms, which are odd in , still vanish in expectation, and the last becomes . Since the RTRL recursion is affine in , induction from gives an unbiased estimate at every step:
The cost is one Jacobian–vector product () and one vector–Jacobian product () per step, about the price of running the network a few times, with memory . The price is variance: the noise injected at every step accumulates, and the estimate can be far from on any single run.
Later methods trade cost against noise. KF-RTRL (Mujika, Meier & Steger, 2018) keeps an unbiased Kronecker-factored estimate, at time and memory per step, with variance smaller than UORO's by a factor of order under their assumptions. SnAp (Menick et al., 2021) is biased but deterministic, so it adds no noise: it keeps only the entries of that a parameter can affect within a few steps of the network's sparsity pattern, and with a one-step pattern costs about as much as BPTT. e-prop (Bellec et al., 2020), designed for spiking networks, factors the gradient into a broadcast learning signal times local eligibility traces computed forward in time; its gradient is approximate, yet it approaches BPTT's performance on many tasks with only local, online computation.
| Method | Gradient | Memory | Time per step | Comment |
|---|---|---|---|---|
| BPTT | exact | offline: waits for the end | ||
| Truncated BPTT, window | biased | (amortized) | no signal beyond steps | |
| RTRL | exact | online | ||
| UORO | unbiased | rank one; high variance | ||
| KF-RTRL | unbiased | lower variance | ||
| SnAp-1 | biased | about BPTT's | sparse influence matrix | |
| e-prop | biased | local, for spiking networks |
When exact is cheap. If the recurrence is element-wise, so that each unit's new state depends only on its own previous state (a diagonal ), then each recurrent parameter influences only its own unit and has nonzero entries: exact RTRL costs about as much as running the network. Irie, Gopalakrishnan & Schmidhuber (2024) trained reinforcement-learning agents with element-wise LSTMs and exact RTRL on memory tasks, and stress the catch: in a stack of such layers, a lower layer's parameters influence every unit above it, and the cost returns. The diagonal recurrences of modern linear RNNs and state space models (Recurrence Returns: xLSTM & Parallel RNNs) have exactly this structure.
Key takeaways
- Teacher forcing is exact maximum likelihood for the autoregressive factorization; exposure bias is the shift to self-generated prefixes at test time. A learner with error on the expert's states can incur extra cost of order (Ross & Bagnell, 2010), and training on its own states (DAgger) can restore linear growth.
- Scheduled sampling is not consistent: cross-entropy is minimized by the true token's conditional given the fed, partly sampled prefix, and with all-sampled inputs that is the marginal. Sequence-level training and professor forcing change the objective instead.
- Truncated BPTT drops the tail , bounded by order when the dynamics contract; the bias is large exactly when long memories exist.
- RTRL carries forward: exact online gradients at memory and time per step. UORO (unbiased, rank one), KF-RTRL, SnAp and e-prop trade bias, variance and cost, and element-wise recurrence makes exact RTRL cheap for a single layer.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
What does teacher forcing compute when training an autoregressive RNN?
- An approximation to the likelihood gradient that ignores long-range terms
- The gradient of a sequence-level metric such as BLEU
- A gradient on the model's own samples, to prepare it for generation
- The exact gradient of the log-likelihood , with every factor conditioned on the true prefix
Show the answer
D. The exact gradient of the log-likelihood , with every factor conditioned on the true prefix
Maximum likelihood for the factorized model conditions each factor on the true prefix, which is exactly what teacher forcing feeds. The trouble is not the gradient but the shift at generation time, when prefixes come from the model itself.
When is the bias of truncated BPTT with window guaranteed to be small?
- When the Jacobian products contract quickly, well below 1, so the dropped tail is of order ; but then long-range terms were small anyway
- Whenever is larger than the hidden size
- When the network has learned long memories, since its gradients are then stable
- Never: truncated gradients point in a random direction
Show the answer
A. When the Jacobian products contract quickly, well below 1, so the dropped tail is of order ; but then long-range terms were small anyway
The dropped tail is bounded by with . Fast contraction makes it negligible, which is also the regime in which nothing beyond steps could be learned. Networks with long memories have Jacobian products near norm 1, and truncation then discards a large part of the gradient.
Why does exact RTRL cost per step for a fully connected RNN with units?
- Because it must store all past hidden states
- Because it runs BPTT from scratch at every step
- Because the influence matrix has entries for the recurrent weights, and each step multiplies it by the Jacobian
- Because it inverts the recurrent matrix at every step
Show the answer
C. Because the influence matrix has entries for the recurrent weights, and each step multiplies it by the Jacobian
RTRL carries forward via . With parameters, is , and costs multiply-adds. Its memory, , does not grow with .
UORO keeps a rank-one estimate of the influence matrix. What makes it unbiased?
- It recomputes the exact influence matrix every few steps
- The RTRL recursion is affine in , and fresh random signs with make the cross terms vanish in expectation, so by induction
- It uses a learning rate small enough that the bias disappears
- The influence matrix of any RNN has rank one
Show the answer
B. The RTRL recursion is affine in , and fresh random signs with make the cross terms vanish in expectation, so by induction
Expanding the update gives four terms; two contain a single and average to zero, and averages to . Unbiasedness says nothing about variance, which is UORO's weakness and the motivation for KF-RTRL.
Further reading
- R. J. Williams & D. Zipser, "A learning algorithm for continually running fully recurrent neural networks," Neural Computation 1(2), 270–280 (1989).
- S. Ross, G. J. Gordon & J. A. Bagnell, "A reduction of imitation learning and structured prediction to no-regret online learning," AISTATS (2011).
- S. Bengio, O. Vinyals, N. Jaitly & N. Shazeer, "Scheduled sampling for sequence prediction with recurrent neural networks," NeurIPS (2015).
- F. Huszár, "How (not) to train your generative model: Scheduled sampling, likelihood, adversary?," arXiv:1511.05101 (2015).
- C. Tallec & Y. Ollivier, "Unbiased online recurrent optimization," ICLR (2018).
- O. Marschall, K. Cho & C. Savin, "A unified framework of online learning algorithms for training recurrent neural networks," Journal of Machine Learning Research 21(135), 1–34 (2020).