Batchify a token stream for truncated backprop through time
Why it matters Classic word-level language models on Penn Treebank and WikiText were trained with this batching.
Language model RNNs train on one long token stream split into parallel streams and cut into short windows for truncated BPTT.
Write tbptt_batches(tokens, batch_size, seq_len). Let L = len(tokens) // batch_size. Trim to the first batch_size * L tokens and reshape to (batch_size, L) so each row is a contiguous stream. Then for i = 0, seq_len, 2 * seq_len, ... while i < L - 1, let n = min(seq_len, L - 1 - i) and yield x = data[:, i:i + n], y = data[:, i + 1:i + 1 + n]. Return the list of (x, y) pairs as integer arrays.
def tbptt_batches(tokens, batch_size, seq_len)Example
tbptt_batches(list(range(10)), 2, 2) gives x [[0, 1], [5, 6]] with y [[1, 2], [6, 7]], then x [[2, 3], [7, 8]] with y [[3, 4], [8, 9]].
Understand the idea
An RNN language model reads text as one long stream. To use a GPU well we cut the stream into B equal pieces and read them side by side, like B people each reading a different chapter of the same book. Each step we take a short window from every piece, train on it, and carry the hidden state into the next window, cutting the gradient at the window edge (truncated backprop).
Tiny example: tokens 0 to 9, B = 2, so L = 5 and the rows are [0..4] and [5..9]. Window 1: x = [[0, 1], [5, 6]], y = [[1, 2], [6, 7]]. Window 2: x = [[2, 3], [7, 8]], y = [[3, 4], [8, 9]].
Rules: data = tokens[:B L].reshape(B, L); x = data[:, i : i + n], y = data[:, i + 1 : i + 1 + n].
Stateful RNN training in Keras and the classic PyTorch word language model example use this layout.
Shapes and data flow
tokens (N,) -> data (B, L) -> x, y (B, n) per window