TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Training Sequence Models: Padding, Packing, Teacher Forcing

Training Sequence Models: Padding, Packing, Teacher Forcing

The RNN, LSTM and GRU cells of the last two lessons are the easy part. Real sequence data brings the engineering problems: sequences of different lengths must share a batch, a loss must ignore positions that do not exist, a model that writes a sequence must be trained without letting its early mistakes snowball, and a series of a million steps cannot be backpropagated in one piece. This lesson covers the standard answers, each in code: padding and masks (NumPy), pack_padded_sequence and bidirectional RNNs, an encoder-decoder trained with teacher forcing, gradient clipping, and truncated backpropagation through time (PyTorch, recorded).

Three shapes of sequence task

Task shape Input to output Example What the loss reads
many-to-one a sequence to one label sentiment of a review, the memory task of LSTM and GRU the state after the last real step
many-to-many, aligned one output per input step next-value prediction, part-of-speech tags every real step (masked)
sequence-to-sequence a sequence to another sequence of a different length translation, reversing a sequence, summarisation every step of the output sequence

The first two use one RNN with a head. The third needs an encoder that reads the input and a decoder that writes the output, one token at a time.

Padding and masks

A batch is a rectangular tensor, so shorter sequences are padded to the longest one, usually with zeros. Two things then go wrong unless you handle them: the RNN keeps running over the padding, so the state at the last position is not the state at the end of a short sequence; and a per-step loss averages over positions that do not exist. A mask, true on real steps, fixes both: gather each sequence's last real state by its length, and divide the masked loss by the number of real steps.

L=∑n,tmn,t ℓn,t∑n,tmn,t,hnlast=hn, lenn−1L = \frac{\sum_{n,t} m_{n,t}\, \ell_{n,t}}{\sum_{n,t} m_{n,t}}, \qquad h^{\text{last}}_n = h_{n,\, \text{len}_n - 1}
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
D, H = 2, 4
Wx, Wh, b = rng.normal(0, 0.5, (H, D)), rng.normal(0, 0.5, (H, H)), rng.normal(0, 0.1, H)
Wy = rng.normal(0, 0.5, (1, H))

def rnn(X):
    """X: (N, T, D) -> hidden states (N, T, H)."""
    h = np.zeros((X.shape[0], H)); out = []
    for t in range(X.shape[1]):
        h = np.tanh(X[:, t] @ Wx.T + h @ Wh.T + b)
        out.append(h)
    return np.stack(out, axis=1)

# Three sequences of lengths 5, 3 and 2, padded with zeros to length 5
lengths = np.array([5, 3, 2])
seqs = [rng.normal(size=(L, D)) for L in lengths]
X = np.zeros((3, 5, D))
for i, s in enumerate(seqs):
    X[i, :len(s)] = s
mask = np.arange(5)[None, :] < lengths[:, None]           # (N, T): True on real steps
print("mask:\n", mask.astype(int))

out = rnn(X)
last_naive = out[:, -1]                                   # step 5 for everyone: wrong for padded rows
last_real = out[np.arange(3), lengths - 1]                # gather each sequence's last real step
alone = np.stack([rnn(s[None])[0, -1] for s in seqs])     # each sequence run on its own
print("out[:, -1] == alone:", [bool(np.allclose(a, c)) for a, c in zip(last_naive, alone)])
print("gathered  == alone:", [bool(np.allclose(a, c)) for a, c in zip(last_real, alone)])

# Many-to-many loss: average only over real steps
targets = np.where(mask, 2.0 + rng.normal(size=(3, 5)), 0.0)   # padded with 0, like the inputs
err = ((out @ Wy.T)[..., 0] - targets) ** 2
print(f"naive mean over all 15 positions: {err.mean():.4f}")
print(f"masked mean over the {mask.sum()} real steps: {(err * mask).sum() / mask.sum():.4f}")
mask:
 [[1 1 1 1 1]
 [1 1 1 0 0]
 [1 1 0 0 0]]
out[:, -1] == alone: [True, False, False]
gathered  == alone: [True, True, True]
naive mean over all 15 positions: 3.3825
masked mean over the 10 real steps: 5.0635

The padded batch holds lengths 5, 3 and 2. Taking out[:, -1] is right only for the full-length sequence: the two shorter ones have run 2 and 3 extra steps on zeros. Gathering at lengths - 1 reproduces exactly what each sequence gives when run alone. The naive loss averages over 15 positions, including 5 padded ones where the target is the pad value 0, and reports 3.3825; the correctly masked loss over the 10 real steps is 5.0635. The naive number is not just off, it rewards the model for predicting the padding.

pack_padded_sequence

Running the RNN over padding wastes compute and, for an RNN that reads right to left, would start from the padding. PyTorch's packed sequences avoid both. pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False) stores the batch so that at each time step only the sequences still running are processed; the RNN modules accept it directly, and pad_packed_sequence turns the output back into a padded tensor. A bidirectional RNN runs a second RNN from the end to the start and concatenates the two outputs at every step, so each position sees both its past and its future (useful for tagging and for encoders; not for predicting the next value, where the future is what you are predicting). The recorded run (CPU):

python · try it yourself
import torch
from torch import nn
from torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence

torch.manual_seed(0)
gru = nn.GRU(input_size=2, hidden_size=4, batch_first=True)
seqs = [torch.randn(L, 2) for L in (5, 3, 2)]
lengths = torch.tensor([len(s) for s in seqs])
X = pad_sequence(seqs, batch_first=True)                  # (3, 5, 2), zeros after each end
print("padded batch:", tuple(X.shape))

with torch.no_grad():
    alone = torch.stack([gru(s[None])[1][0, 0] for s in seqs])          # h_n of each sequence alone
    _, h_pad = gru(X)                                                   # padding fed as real input
    packed = pack_padded_sequence(X, lengths, batch_first=True, enforce_sorted=False)
    out_packed, h_packed = gru(packed)
    out, out_lengths = pad_packed_sequence(out_packed, batch_first=True)

diff = lambda a, b: f"{(a - b).abs().max().item():.1e}"
print("padded, no packing: max |h_n - alone| =", diff(h_pad[0], alone))
print("packed:             max |h_n - alone| =", diff(h_packed[0], alone))
print("unpacked output", tuple(out.shape), "lengths", out_lengths.tolist(),
      "| padded positions are zero:", bool((out[2, 2:] == 0).all()))

# Bidirectional: a forward and a backward GRU, outputs concatenated
bi = nn.GRU(2, 4, batch_first=True, bidirectional=True)
with torch.no_grad():
    out_bi, h_bi = bi(pack_padded_sequence(X, lengths, batch_first=True, enforce_sorted=False))
    out_bi, _ = pad_packed_sequence(out_bi, batch_first=True)
print("bidirectional output", tuple(out_bi.shape), " h_n", tuple(h_bi.shape))
print("forward h_n == output at the last real step:",
      torch.allclose(h_bi[0], out_bi[torch.arange(3), lengths - 1, :4]))
print("backward h_n == output at step 0:", torch.allclose(h_bi[1], out_bi[:, 0, 4:]))
padded batch: (3, 5, 2)
padded, no packing: max |h_n - alone| = 7.7e-01
packed:             max |h_n - alone| = 6.0e-08
unpacked output (3, 5, 4) lengths [5, 3, 2] | padded positions are zero: True
bidirectional output (3, 5, 8)  h_n (2, 3, 4)
forward h_n == output at the last real step: True
backward h_n == output at step 0: True

Without packing, the final state of the padded batch differs from the per-sequence states by up to 0.77. With packing, the difference is 6.0×10−86.0 \times 10^{-8}, float32 rounding: h_n is each sequence's state at its own last real step, and the unpacked output is zero on the padded positions. The bidirectional GRU's output has 2H=82H = 8 features per step and h_n has shape (2,N,H)(2, N, H): the forward direction's final state is its output at the last real step, and the backward direction's final state is its output at step 0, where it finished reading. For a many-to-one classifier with a bidirectional encoder, concatenate h_n[0] and h_n[1] rather than reading output[:, -1], which for the backward half is the state after one step.

Encoder-decoder and teacher forcing

GRU 3 GRU 1 GRU 4 GRU 1 h GRU sos 1 GRU 1 4 GRU 4 1 GRU 1 3 encoder: reads the input input sequence decoder input: sos + true previous tokens (at inference: its own previous predictions) predicted: the input reversed

A sequence-to-sequence model encodes the input into a state hh and lets a decoder generate the output token by token, each step conditioned on the previous token. Training it the way it runs at inference (feeding back its own predictions) is slow and unstable early on, when the predictions are mostly wrong. Teacher forcing feeds the decoder the true previous token instead, which makes all output steps computable in one call (as for a language model) and gives the decoder clean inputs to learn from:

L=−∑t=1T′log⁡pθ(yt∣y1,…,yt−1, encoder(x))L = -\sum_{t=1}^{T'} \log p_\theta\big(y_t \mid y_1, \ldots, y_{t-1},\ \text{encoder}(x)\big)

with the true y1,…,yt−1y_1, \ldots, y_{t-1} as inputs. The cost is exposure bias: during training the decoder never sees its own mistakes, so at inference one wrong token puts it in a situation it never trained for, and errors can compound along the output.

The task: reverse a sequence of 8 random digits. The encoder and the decoder are GRUs with hidden size 64 and 16-dimensional embeddings; the decoder starts from the encoder's final state, with a start token (SOS) as its first input. Adam (learning rate 0.003), batches of 64, 1500 steps, and gradient clipping at norm 1 (clip_grad_norm_ returns the norm before clipping, printed below; see gradient clipping). Every 300 steps the model is measured on 1000 validation sequences, both teacher-forced and free-running with greedy decoding. The recorded run (CPU):

python · try it yourself
import torch
from torch import nn

torch.manual_seed(0)
V, SOS, L, E, H = 10, 10, 8, 16, 64       # digits 0-9, start token 10, length 8

def batch(n, gen):
    src = torch.randint(0, V, (n, L), generator=gen)
    return src, src.flip(1)                 # target: the sequence reversed

class Seq2Seq(nn.Module):
    def __init__(self):
        super().__init__()
        self.emb_src = nn.Embedding(V, E)
        self.emb_tgt = nn.Embedding(V + 1, E)          # + the start token
        self.encoder = nn.GRU(E, H, batch_first=True)
        self.decoder = nn.GRU(E, H, batch_first=True)
        self.out = nn.Linear(H, V)

    def forward(self, src, tgt):
        """Teacher forcing: the decoder reads <sos> + the TRUE previous tokens."""
        _, h = self.encoder(self.emb_src(src))         # h: (1, N, H), the summary of the input
        dec_in = torch.cat([torch.full_like(tgt[:, :1], SOS), tgt[:, :-1]], dim=1)
        out, _ = self.decoder(self.emb_tgt(dec_in), h)
        return self.out(out)                           # (N, L, V): all steps in one call

    @torch.no_grad()
    def generate(self, src):
        """Free running: the decoder reads its OWN previous prediction."""
        _, h = self.encoder(self.emb_src(src))
        tok = torch.full((src.shape[0], 1), SOS)
        preds = []
        for _ in range(L):
            out, h = self.decoder(self.emb_tgt(tok), h)
            tok = self.out(out).argmax(-1)             # greedy
            preds.append(tok)
        return torch.cat(preds, dim=1)

model = Seq2Seq()
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
gen = torch.Generator().manual_seed(1)
src_va, tgt_va = batch(1000, torch.Generator().manual_seed(2))
for step in range(1, 1501):
    src, tgt = batch(64, gen)
    loss = nn.functional.cross_entropy(model(src, tgt).reshape(-1, V), tgt.reshape(-1))
    opt.zero_grad(); loss.backward()
    norm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)   # returns the norm before clipping
    opt.step()
    if step % 300 == 0:
        model.eval()
        with torch.no_grad():
            tf_acc = (model(src_va, tgt_va).argmax(-1) == tgt_va).float().mean().item()
        gen_out = model.generate(src_va)
        model.train()
        print(f"step {step:4d}  loss {loss.item():.3f}  grad norm {norm.item():.2f}  "
              f"token acc: teacher-forced {tf_acc:.3f}, free-running {(gen_out == tgt_va).float().mean().item():.3f}  "
              f"whole sequence {(gen_out == tgt_va).all(1).float().mean().item():.3f}")

# Where do the errors fall? Teacher-forced vs free-running, per output position
model.eval()
with torch.no_grad():
    tf_pos = (model(src_va, tgt_va).argmax(-1) == tgt_va).float().mean(0)
fr_pos = (model.generate(src_va) == tgt_va).float().mean(0)
print("by position, teacher-forced:", [round(a, 2) for a in tf_pos.tolist()])
print("by position, free-running:  ", [round(a, 2) for a in fr_pos.tolist()])
step  300  loss 0.446  grad norm 2.30  token acc: teacher-forced 0.824, free-running 0.630  whole sequence 0.156
step  600  loss 0.274  grad norm 2.19  token acc: teacher-forced 0.914, free-running 0.800  whole sequence 0.490
step  900  loss 0.165  grad norm 1.96  token acc: teacher-forced 0.956, free-running 0.887  whole sequence 0.695
step 1200  loss 0.155  grad norm 2.73  token acc: teacher-forced 0.962, free-running 0.905  whole sequence 0.720
step 1500  loss 0.126  grad norm 1.93  token acc: teacher-forced 0.954, free-running 0.901  whole sequence 0.666
by position, teacher-forced: [1.0, 0.99, 0.98, 0.98, 0.94, 0.93, 0.9, 0.92]
by position, free-running:   [1.0, 0.99, 0.97, 0.95, 0.91, 0.85, 0.79, 0.76]

The gap is exposure bias in numbers. At step 1500 the teacher-forced token accuracy is 0.954, the free-running one 0.901, and only 0.666 of the sequences are reversed entirely correctly (it was 0.720 at step 1200: single-run numbers move around). By position, the teacher-forced accuracy falls from 1.0 to 0.92; part of that is the task itself, since the later outputs are the earliest inputs, which the encoder's single state remembers worst. The free-running accuracy falls further, to 0.76 at the last position, and the extra drop (0.92 vs 0.76) is the compounding of the decoder's own earlier errors. The gradient norms before clipping were around 2, so clipping at 1 was active throughout; it caps the step size rather than changing the direction.

Remedies for exposure bias include scheduled sampling (feed the model's own prediction with a probability that grows during training), beam search at inference, and, most effective for this task, attention: instead of squeezing the whole input into one vector hh, the decoder looks back at all encoder states at every step. That is the next section of the course, starting with attention from scratch.

Truncated backpropagation through time

A sensor stream or a long text cannot be backpropagated in one piece: memory grows with the number of steps. Truncated BPTT splits the sequence into chunks of kk steps, backpropagates within each chunk, and carries the hidden state from one chunk to the next with h.detach(): the value continues (the model still sees the past) but the graph is cut (gradients flow back at most kk steps). The Mathematics lesson on BPTT analyses what the truncation costs. The recorded run (CPU) trains a GRU on one series of 3000 steps (a sum of two sines plus noise with standard deviation 0.05) in chunks of 50, and measures next-value MSE on the following 1000 steps.

python · try it yourself
import torch
from torch import nn

torch.manual_seed(0)
# One long series (a sum of two sines plus noise): 4000 steps, predict the next value
t = torch.arange(4001, dtype=torch.float32)
series = torch.sin(0.07 * t) + 0.5 * torch.sin(0.31 * t) + 0.05 * torch.randn(4001)
x, y = series[:-1].reshape(1, -1, 1), series[1:].reshape(1, -1, 1)
x_tr, y_tr, x_va, y_va = x[:, :3000], y[:, :3000], x[:, 3000:], y[:, 3000:]

rnn, head = nn.GRU(1, 32, batch_first=True), nn.Linear(32, 1)
params = list(rnn.parameters()) + list(head.parameters())
opt = torch.optim.Adam(params, lr=5e-3)
chunk = 50                                         # backpropagate through 50 steps at a time

for epoch in range(1, 6):
    h = None
    for s in range(0, 3000, chunk):
        out, h = rnn(x_tr[:, s:s + chunk], h)      # start from the state left by the previous chunk
        loss = nn.functional.mse_loss(head(out), y_tr[:, s:s + chunk])
        opt.zero_grad(); loss.backward()
        nn.utils.clip_grad_norm_(params, 1.0)
        opt.step()
        h = h.detach()                             # keep the value, cut the graph
    with torch.no_grad():
        _, h_end = rnn(x_tr)                       # warm up on the training part, then predict on
        out, _ = rnn(x_va, h_end)
        va = nn.functional.mse_loss(head(out), y_va).item()
    print(f"epoch {epoch}  last chunk loss {loss.item():.4f}  val MSE {va:.4f}")
print("state after detach requires grad:", h.requires_grad, f"| noise floor {0.05 ** 2:.4f}")
epoch 1  last chunk loss 0.0078  val MSE 0.0083
epoch 2  last chunk loss 0.0062  val MSE 0.0068
epoch 3  last chunk loss 0.0058  val MSE 0.0063
epoch 4  last chunk loss 0.0057  val MSE 0.0061
epoch 5  last chunk loss 0.0055  val MSE 0.0060
state after detach requires grad: False | noise floor 0.0025

The validation MSE falls from 0.0083 after the first epoch to 0.0060 after five, against a floor of 0.0025 set by the noise in the targets. The detached state does not require grad, so each backward() stops at the chunk boundary; without the detach, the second chunk's backward pass would try to go through the first chunk's graph, which was already freed, and PyTorch raises an error. The chunk length is the longest dependency the gradient can teach; the hidden state can still carry information over longer spans, it just was not trained to.

Pitfalls

  • Unmasked losses and averages. Use ignore_index in nn.CrossEntropyLoss (for token targets padded with a special index) or multiply by the mask and divide by the mask's sum.
  • output[:, -1] with padding. It is the last padded step, not the last real one. Gather by length, or use packing and h_n.
  • Packing and lengths. lengths must be a CPU tensor or list; with enforce_sorted=True (the default) the batch must be sorted by decreasing length.
  • Bidirectional where the future is unknown. A bidirectional model cannot be used for streaming prediction or generation; it sees the answer.
  • Evaluating seq2seq only with teacher forcing. The teacher-forced accuracy overstates the real (free-running) performance; report the free-running one.
  • Forgetting to detach in truncated BPTT. Either an error ("backward through the graph a second time") or, with retain_graph=True, memory that grows without bound.

Practice

  1. Rewrite the masked loss of the NumPy example for token classification with nn.CrossEntropyLoss(ignore_index=-100): what value do the padded targets get?
  2. In the encoder-decoder, what does the decoder input look like for the target [7, 2, 9]?
  3. A bidirectional LSTM with hidden_size=128, 2 layers, batch_first=True reads a batch of shape (16, 40, 50). Give the shapes of output, h_n and c_n.
  4. Truncated BPTT with chunks of 50 steps: can the model learn that an event 120 steps ago matters now? Can it use such information if it happens to keep it in its state?
Answer
  1. Padded target positions are set to −100-100 (the ignore_index); the loss then averages over the real positions only, exactly the masked mean.
  2. [SOS, 7, 2]: the start token followed by the true target shifted right by one; the model must predict [7, 2, 9].
  3. output: (16, 40, 256), both directions concatenated. h_n and c_n: (4, 16, 128), num_layers ×\times num_directions first, never batch-first.
  4. Learn it: not directly, because no gradient connects a loss to inputs more than 50 steps back. Use it: yes, if the state carries the information for other reasons, the forward pass is not truncated, only the gradient.

Test yourself

A padded batch has lengths 5, 3 and 2 and is run through an RNN without packing. Which sequences get the right final state from output[:, -1]?

  1. All three
  2. Only the length-5 sequence
  3. Only the length-2 sequence
  4. None

What is teacher forcing?

  1. Clipping the gradients of the decoder
  2. Feeding the decoder the true previous token during training instead of its own prediction
  3. Training the encoder before the decoder
  4. Using a larger learning rate for the decoder

After 1500 steps the reversal model had 0.954 teacher-forced token accuracy and 0.901 free-running. What explains the gap?

  1. Overfitting to the validation set
  2. Exposure bias: at inference the decoder reads its own possibly wrong tokens, which it never saw in training
  3. The validation set is harder
  4. Gradient clipping

In truncated BPTT, what does h = h.detach() between chunks do?

  1. Resets the hidden state to zero
  2. Keeps the state's value but cuts the graph, so gradients stop at the chunk boundary
  3. Moves the state to the CPU
  4. Freezes the RNN weights

For a bidirectional GRU with packed input, where is the backward direction's final state h_n[1] found in the unpacked output?

  1. At the last real step, second half of the features
  2. At step 0, second half of the features
  3. At the last padded step
  4. It is not in the output