3.5.13Sequence Models

Teacher forcing

3,160 words14 min readdifficulty · medium3 backlinks

Think of it like learning to ride a bike with training wheels versus without. With training wheels (teacher forcing), you get stable support at every moment. Without them, one woble compounds into the next. Teacher forcing is the training wheels for sequence models.

Figure — Teacher forcing

Why This Matters

The Problem: Sequence models are autoregressive—each prediction depends on previous predictions. During inference, we have no choice but to use our own outputs as inputs for the next step. But during training, we do have the correct answer (the training data). This creates a fundamental question about how to train.

Two Approaches:

  1. Teacher Forcing (using ground truth): Fast, stable training but exposure bias
  2. Free Running (using model predictions): Matches inference but slow, unstable training

Formal Definition: Given sequence y=(y1,y2,...,yT)y = (y_1, y_2, ..., y_T), at training time:

  • With teacher forcing: p(yty1:t1,x)pθ(yty1:t1,x)p(y_t | y_{1:t-1}, x) \approx p_\theta(y_t | y_{1:t-1}, x) where y1:t1y_{1:t-1} are ground truth
  • Without teacher forcing: p(yty^1:t1,x)pθ(yty^1:t1,x)p(y_t | \hat{y}_{1:t-1}, x) \approx p_\theta(y_t | \hat{y}_{1:t-1}, x) where y^1:t1\hat{y}_{1:t-1} are model predictions

Derivation: Why Teacher Forcing Works

The Sequence Prediction Objective

Let's derive this from first principles. We want to model the probability of a sequence y=(y1,..,yT)y = (y_1, .., y_T) given input xx:

p(yx)=t=1Tp(yty1:t1,x)p(y|x) = \prod_{t=1}^{T} p(y_t | y_{1:t-1}, x)

Why this factorization? Chain rule of probability: p(A,B,C)=p(A)p(BA)p(CA,B)p(A,B,C) = p(A)p(B|A)p(C|A,B). We're just applying it to sequences.

The Training Objective is to maximize log-likelihood:

L=logp(yx)=t=1Tlogpθ(yty1:t1,x)\mathcal{L} = \log p(y|x) = \sum_{t=1}^{T} \log p_\theta(y_t | y_{1:t-1}, x)

Why log? Because products become sums (easier optimization), and it's the negative cross-entropy (our actual loss function).

Two Ways to Compute This

At timestep tt, we need to compute pθ(yty1:t1,x)p_\theta(y_t | y_{1:t-1}, x). But what is y1:t1y_{1:t-1}?

Option 1: Teacher Forcing y1:t1=ground truth from training datay_{1:t-1} = \text{ground truth from training data}

Why this helps: Every timestep gets the correct context. The model learns: "Given the right history, predict the next token." Gradients flow cleanly because we're not backpropagating through previous predictions.

Option 2: Free Running y^1:t1=argmax of model’s previous outputs\hat{y}_{1:t-1} = \text{argmax of model's previous outputs}

Why this is hard: If we make a mistake at t=5t=5, then at t=6t=6 we're conditioning on a wrong input. The error compounds. Gradients must flow through the entire sequence of previous argmax operations (non-differentiable!).

The Mathematical Trade-off

Teacher Forcing Loss (what we actually optimize): LTF=t=1Tlogpθ(yty1:t1,x)\mathcal{L}_{TF} = \sum_{t=1}^{T} \log p_\theta(y_t | y_{1:t-1}, x)

Inference Reality (what we actually do): Linference=t=1Tlogpθ(yty^1:t1,x)\mathcal{L}_{inference} = \sum_{t=1}^{T} \log p_\theta(y_t | \hat{y}_{1:t-1}, x)

These are different distributions! Exposure bias is the gap between them.

Why this matters mathematically: The model never sees its own mistakes during training. At test time, one error can cascade because the model is in a state (receiving its own wrong prediction) it never trained for.

Input:

  • Model fθf_\theta with parameters θ\theta
  • Training sequence (x,y)(x, y) where y=(y1,...,yT)y = (y_1, ..., y_T)
  • Teacher forcing ratio ϵ[0,1]\epsilon \in [0, 1]

For each training step:

initialize hidden state h₀
total_loss = 0

for t = 1 to T:
    if random() < ε:  // Teacher forcing
        input_t = y_{t-1}  // Use ground truth
    else:              // Free running
        input_t = argmax(output_{t-1})  // Use prediction
    
    output_t, h_t = f_θ(input_t, h_{t-1})
    loss_t = CrossEntropy(output_t, y_t)
    total_loss += loss_t

backpropagate(total_loss)
update(θ)

Why each component:

  • ϵ=1.0\epsilon = 1.0: Pure teacher forcing (standard)
  • ϵ=0.0\epsilon = 0.0: Pure free running (hard to train)
  • 0<ϵ<10 < \epsilon < 1: Scheduled sampling (compromise)

Worked Examples

Task: Train RNN to generate "HELLO" character by character.

Setup:

  • Vocabulary: {H, E, L, O , }
  • Input sequence: <START> H E L L O
  • Target sequence: H E L L O <END>

Training with Teacher Forcing (ε=1.0):

Step True Input Model Output True Target Loss
t=1 <START> [H:0.7, E:0.2, L:0.1] H log(0.7)=0.36-\log(0.7) = 0.36
t=2 H (truth) [E:0.8, H:0.1, L:0.1] E log(0.8)=0.22-\log(0.8) = 0.22
t=3 E (truth) [L:0.9, E:0.05, H:0.05] L log(0.9)=0.11-\log(0.9) = 0.11
t=4 L (truth) [L:0.85, O:0.1, E:0.05] L log(0.85)=0.16-\log(0.85) = 0.16
t=5 L (truth) [O:0.95, L:0.03, E:0.02] O log(0.95)=0.05-\log(0.95) = 0.05

Why this step? At t=2, even though the model predicted H with only 70% confidence at t=1, we still feed it the true 'H' at t=2. This keeps the model on track.

Total Loss: 0.36+0.22+0.11+0.16+0.05=0.900.36 + 0.22 + 0.11 + 0.16 + 0.05 = 0.90

Training without Teacher Forcing (ε=0.0):

Step Model Input Model Output True Target Loss
t=1 <START> [H:0.7, E:0.2, L:0.1] H 0.36
t=2 H (pred) [E:0.8, H:0.1, L:0.1] E 0.22
t=3 E (pred) [L:0.6, E:0.3, H:0.1] L 0.51

Wait! At t=3, the model is less confident (0.6vs 0.9) because at t=2 it saw its own prediction of H (which was slightly wrong). Now let's say it predicts L with argmax, but:

| t=4 | L (pred from t=3) | [O:0.4, L:0.35, E:0.25] | L | log(0.35)=1.05-\log(0.35) = 1.05 |

Why this step? At t=4, the model wrongly predicts O (argmax=0.4) when it should predict L. Now at t=5:

| t=5 | O (wrong pred!) | [E:0.5, L:0.3, O:0.2] | O | log(0.2)=1.61-\log(0.2) = 1.61 |

The model is confused because it's never been in this state before (having just output O). The loss explodes: 0.36+0.22+0.51+1.05+1.61=3.750.36 + 0.22 + 0.51 + 1.05 + 1.61 = 3.75 (4× worse!).

Key Insight: Without teacher forcing, one error cascades. With teacher forcing, each step gets a clean slate.

The Compromise: Start with ϵ=1.0\epsilon = 1.0 (pure teacher forcing), then gradually decay:

ϵk=max(0.5,1.0k0.01)\epsilon_k = \max(0.5, 1.0 - k \cdot 0.01)

where kk is the epoch number.

Why this works:

  • Early training: Model learns basic patterns with stable inputs (ϵ1\epsilon \approx 1)
  • Late training: Model learns to recover from its own errors (ϵ0.5\epsilon \approx 0.5)

Epoch 1 (ϵ=1.0\epsilon = 1.0):

Input:  [<START>, H,     E,     L,     L    ]  ← all ground truth
Output: [H,       E,     L,     L,     O    ]
Loss:   [0.36,    0.22,  0.11,  0.16,  0.05 ] = 0.90

Epoch 50 (ϵ=0.5\epsilon = 0.5):

Step 1: input=<START> → predict H (use truth: H)
Step 2: input=H       → predict E (flip coin: use prediction E)
Step 3: input=E       → predict L (flip coin: use truth L)
Step 4: input=L       → predict L (flip coin: use prediction L)
Step 5: input=L       → predict O

The model now trains on a mix of perfect and imperfect histories, bridging the train-test gap.

Task: Translate "Je suis" → "I am"

Encoder-Decoder with Teacher Forcing:

Encoder: [Je, suis] → context vector c

Decoder Training (with teacher forcing):
t=1: input =<START>, context = c
     → output = [I:0.9, You:0.05, ...] 
     → target = I
     → loss = -log(0.9) = 0.11

t=2: input = I (ground truth!), context = c
     → output = [am:0.85, are:0.1...]
     → target = am
     → loss = -log(0.85) = 0.16

t=3: input = am (ground truth!), context = c
     → output = [<END>:0.95, ...]
     → target = <END>
     → loss = -log(0.95) = 0.05

Why this step (t=2)? Even if the model only had 90% confidence on "I" at t=1, we feed it the correct "I" at t=2. This prevents the decoder from spiraling into "You is" or other nonsense.

At Inference (no teacher, must free-run):

t=1: input = <START> → output = I (confident)
t=2: input = I (our own prediction) → output = am (still okay)
t=3: input = am → output = <END>
Result: "I am" ✓

But if t=1 had predicted "You" by mistake:

t=1: input = <START> → output = You (mistake!)
t=2: input = You (wrong!) → output = are (the model learned "You are" together)
Result: "You are" ✗

This is exposure bias: the model never trained on the state "I just wrongly said 'You', now what?"

Common Mistakes

Why this feels right: If we always feed the model the correct answer, isn't it just copying?

Why it's wrong: The model doesn't see the next token; it only sees previous tokens as input. At each step, it still has to predict the next token given the context. Teacher forcing provides the correct context, not the answer.

Example: At t=3 in "HELLO", we feed the model "HE" (correct context), but it must still learn to output "L". The model isn't told "the answer is L"—it must learn the pattern H→E→L from the loss signal.

The fix: Understand that teacher forcing stabilizes inputs but the model still learns outputs through backpropagation of prediction errors.

Why this feels right: If teacher forcing works, why not use it 100% of the time?

Why it's wrong: Pure teacher forcing creates exposure bias. The model never experiences its own errors during training, so it can't learn to recover from them at test time.

Example: A chatbot trained with ϵ=1.0\epsilon = 1.0 might:

  • Training: "How are you?" → "I am fine" (perfect, every time)
  • Test: "How are you?" → "I ma fine" (typo) → "fine you are how" (spiral!)

The model never learned what to do when it makes a typo, so it compounds the error.

The fix: Use scheduled sampling. Start with ϵ=1.0\epsilon = 1.0 for stable early training, then decay to ϵ=0.5\epsilon = 0.5 or even 0.0. The model learns both correct patterns AND error recovery.

Why this feels right: Any sequence model predicts one token at a time, right?

Why it's wrong: Teacher forcing only applies to autoregressive models (where the model's output becomes its input). It doesn't apply to:

  • Encoder-only models (BERT): No generation, so no sequential dependencies
  • Non-autoregressive models (parallel generation): All tokens predicted simultaneously
  • Sequence labeling (POS tagging): Input and output are the same length and independent

Example: In BERT, we mask "The cat sat on the ___", and predict "mat". There's no previous token to feed as input—we're doing masked prediction, not sequential generation.

The fix: Understand that teacher forcing is specifically for autoregressive generation (GPT, RNN language models, seq2seq decoders).

Practical Considerations

When to use Teacher Forcing:

  • ✓ RNN/LSTM/GRU language models
  • ✓ Seq2seq decoders (translation, summarization)
  • ✓ Autoregressive Transformers (GPT-style)
  • ✓ Early training stages (always stable)

When to reduce or avoid:

  • ✗ Late training (need to see own errors)
  • ✗ Tasks where errors compound badly (long-form generation)
  • ✗ When you have a curriculum learning strategy

Scheduled Sampling Strategies:

  1. Linear decay: ϵk=max(ϵmin,1.0k/K)\epsilon_k = \max(\epsilon_{min}, 1.0 - k/K)
  2. Exponential decay: ϵk=ϵmin+(1ϵmin)ek/τ\epsilon_k = \epsilon_{min} + (1 - \epsilon_{min}) \cdot e^{-k/\tau}
  3. Inverse sigmoid: ϵk=kk+ek/τ\epsilon_k = \frac{k}{k + e^{k/\tau}}

Why decay matters: It's a form of curriculum learning. Start easy (stable inputs), progress to hard (noisy inputs that match test time).

Recall Explain to a 12-year-old

Imagine you're learning to write a story one word at a time. You write "Once," then your teacher tells you the next word should be "upon," then "a," then "time."

Teacher forcing is like having your teacher tell you the correct previous words as you write each new word. Even if you wrote "Once upan" (ops, typo!), the teacher corrects it to "upon" before you write the next word. This helps you learn the right patterns without getting confused by your own mistakes.

Without teacher forcing is like writing the whole story alone. If you misspell "upan," then you might get confused and write "upan the tiem"—your mistakes pile up!

The smart way (scheduled sampling) is: First, let the teacher help a lot (so you learn the basic story flow). Then gradually let you write more on your own (so you learn to catch your own mistakes). By the end, you can write full stories without help!

That's exactly how we train AI to write sentences: start with training wheels (teacher), then gradually remove them so AI can write on its own.

The teacher forces you to stay on track during training, but at test time you're on your own—so you need to gradually learn to handle your own mistakes (reduce epsilon over time).

Connections

  • 3.5.1-RNN-fundamentals: Teacher forcing stabilizes RNN training
  • 3.5.7-LSTM: LSTMs still need teacher forcing for autoregressive tasks
  • 3.5.14-Scheduled-sampling: The solution to exposure bias
  • 3.6.2-Seq2seq-architecture: Decoder training uses teacher forcing
  • 4.2.3-Autoregressive-models: Core concept for any autoregressive training
  • 5.3.8-Exposure-bias: The fundamental problem teacher forcing creates
  • 2.4.5-Curriculum-learning: Scheduled sampling as curriculum

#flashcards/ai-ml

What is teacher forcing? :: A training technique where at each timestep, we feed the model the true previous token from training data as input, rather than the model's own prediction.

Why does teacher forcing make training faster?
Because every timestep gets correct context, gradients flow cleanly without backpropagating through previous prediction errors, and the model doesn't compound mistakes during training.
What is exposure bias?
The gap between training (where the model sees ground truth previous tokens) and inference (where it sees its own predictions). The model never learns to recover from its own errors.
Teacher forcing ratioε = 1.0 means what?
Always use ground truth as input (pure teacher forcing). ε = 0.0 means always use model's own predictions (free running).

What is scheduled sampling? :: Gradually decreasing the teacher forcing ratio during training, starting with ε ≈ 1.0 (stable early training) and decaying towardε ≈ 0.5 or lower (learning error recovery).

Why can't we use pure free-running (ε = 0) from the start?
Because early in training, the model makes many errors. If we feed its own wrong predictions as inputs, errors compound and training becomes unstable with exploding losses.
Which models need teacher forcing?
Autoregressive models where output becomes input: RNN/LSTM language models, seq2seq decoders, GPT-style transformers. Not needed for: BERT (encoder-only), non-autoregressive models, sequence labeling.
What happens at inference time with a model trained using teacher forcing?
The model must free-run (use its own predictions as inputs) because no ground truth is available. If trained only withε = 1.0, it may struggle because it never saw its own errors.
Formula for linear decay of teacher forcing ratio?
ε_k = max(ε_min, 1.0 - k/K), where k is epoch number and K is total epochs. Ensures smooth transition from supervised to self-supervised.
What's the mathematical difference between teacher forcing and inference?
Training: p_θ(y_t | y_{1:t-1}, x) where y_{1:t-1} is ground truth. Inference: p_θ(y_t | ŷ_{1:t-1}, x) where ŷ_{1:t-1} are model predictions. Different input distributions!

Concept Map

are

predicts

training question

option 1

option 2

uses

uses

gives

causes

matches

but

derived from

Sequence Models

Autoregressive

Next Token from Previous

What input to feed

Teacher Forcing

Free Running

Ground Truth y sub t-1

Model Prediction y-hat sub t-1

Fast Stable Training

Exposure Bias

Inference Behavior

Slow Unstable Training

Chain Rule Factorization

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Chalo is concept ko simple tarike se samajhte hain. Jab hum sequence models train karte hain - jaise RNN, LSTM ya Transformers - tab har step pe humein next word ya token predict karna hota hai based on previous tokens. Ab sawaal ye aata hai ki training ke time, model ko apni khud ki predictions feed karein ya jo sahi answer hai (ground truth) wo feed karein? Teacher forcing ka matlab hai ki hum har timestep pe correct ground truth answer feed karte hain, chahe model ne pichle step pe galat prediction hi kyun na kiya ho. Bike sikhne wali example yaad rakho - teacher forcing training wheels ki tarah hai jo har moment pe stable support deta hai, jisse ek chhoti galti agli galti mein compound nahi hoti.

Ye important isliye hai kyunki sequence models autoregressive hote hain - matlab har prediction pichli predictions pe depend karti hai. Agar hum training mein model ki apni galat predictions feed karein, to ek chhoti si mistake pura sequence kharab kar sakti hai, aur training bahut slow aur unstable ho jaati hai. Teacher forcing se gradients cleanly flow karte hain aur training fast aur stable hoti hai, kyunki model ko hamesha sahi context milta hai seekhne ke liye. Mathematically, hum chain rule use karke sequence ki probability ko individual token probabilities ke product mein todte hain, aur phir log-likelihood maximize karte hain.

Lekin ek catch hai jise hum exposure bias kehte hain. Training ke time model hamesha sahi answers dekhta hai, lekin inference (test time) pe uske paas sirf apni khud ki predictions hoti hain. Ye do alag-alag situations hain! Model ko kabhi apni galtiyon se deal karna nahi sikhaya jaata, isliye test time pe ek galti cascade kar sakti hai kyunki model us state mein aa jaata hai jise usne kabhi train hi nahi kiya. Isiliye practical implementations mein log ek teacher forcing ratio use karte hain - kabhi ground truth, kabhi model ki apni prediction feed karke - taaki model dono situations handle karna seekh jaye. Ye trade-off samajhna zaroori hai jab aap real-world sequence models banaoge.

Go deeper — visual, from zero

Test yourself — Sequence Models

Connections