9.4 Bidirectional RNN with length-aware reversal
Your LSTM and GRU read a sentence left to right, so the state at word 3 knows words 0 to 3 and nothing after. For a language model that is the point: it must not see the future. For an encoder it is a handicap. When Encoder-decoder with teacher forcing encodes a source sentence to translate it, the representation of “bank” should already know whether “river” or “account” follows. Reading the sentence in both directions and concatenating gives every position both contexts.
Concepts from other sections (4)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Gated recurrent unit (GRU): a recurrent cell with one state and two gates, . Read more: 9.3 GRU (torch gate order)
- Prefix sum: the running total of an array up to each position, so any subarray sum is the difference of two prefix sums; with a hash map of the prefix sums seen so far, it counts the subarrays that sum to in . Read more: Chapter 3: Arrays and hashing in Programming and Algorithms
- Fixed point: a value with . Read more: 15.5 Fixed-point iteration and fast inverse square root in C in Mathematics
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs in Mathematics
The idea is one line; the bug is in the batching. Sentences in a batch have different lengths and are padded at the end, and the backward direction must start at each sentence’s last real word, not at the padding. In this section you build the length-aware reversal once, check it against torch’s packed sequences and against a per-sentence loop, and so give the seq2seq model its encoder. Together with the LSTM, the GRU, and the RNN language model, this completes the recurrent part of the book.
The two directions are the LSTM and GRU modules of the previous sections. The reversal is a Tensor getitem, and the halves are joined with F.concat from the op library. The tests are property tests in the style of Property-based tests with Hypothesis in Software Engineering. The solution is bi.py, with reversal_index, reverse_padded, and bidirectional; its contract is bi.pyi and its property tests are test_bi.py.
Learning objectives
- Build the per-sequence reversal index that mirrors each sequence inside its own length and leaves padding in place.
- Explain why
x[::-1]is wrong for a padded batch even when the RNN masks steps past the length.- Compose two single-direction modules into a bidirectional layer whose halves match torch’s
bidirectional=True.- State and test the properties (involution, mirror-and-fix, per-sequence equivalence, inert padding) that make the batched computation trustworthy.
Reversal inside each length
Section titled “Reversal inside each length”The notation:
| Symbol | Meaning | Type / shape |
|---|---|---|
| padded length, batch size | integers | |
| a padded batch, time first | [T, B, D] | |
| the real length of sequence ; steps are padding | integer in | |
| the reversal index: for , else | integer in | |
| the length-aware reversal, | [T, B, ...] | |
| , | forward and backward states at position | [B, H_f], [B, H_b] |
For sequence the real tokens are . Reading them backward means position takes token for ; positions past the length keep their padding. That map is a permutation of that mirrors the first positions and fixes the rest, so applying it twice gives the identity: .
One integer index array of shape holds all permutations, and the gather x[idx, arange(B)] applies them at once. On a Tensor it is getitem, whose backward scatters each gradient back to where its value came from, which is the same permutation again.
Why not x[::-1]
Section titled “Why not x[::-1]”It is tempting to flip the padded batch. Flipping reverses every sequence over all steps: a sequence of length 2 in a batch of length 5 becomes three padding steps followed by its two real tokens. The backward RNN would start from padding. The LSTM’s and GRU’s lengths mask does make them ignore steps past the length, but after a full flip the padding is no longer past the length; it is at the front. The state would be garbage before the first real token.
The layer
Section titled “The layer”With fwd and bwd single-direction modules that honor lengths (output 0 and carry the state past each length), the layer is
is in reversed time (its row is the backward state after reading ), so it is reversed back before the concatenation; padded positions are 0 in both halves because fixes them. The forward half comes first, as in torch’s bidirectional=True, whose *_l0 weights are the forward module and *_l0_reverse weights the backward one. Each direction’s final state is in out: the forward one at (its last real step) and the backward one at (it ends on the first token).
Working it by hand
Section titled “Working it by hand”Take and three sequences with lengths : “abc”, “d”, “ef”. The padded batch, with a dot for padding:
| seq 0 () | seq 1 () | seq 2 () | |
|---|---|---|---|
| 0 | a | d | e |
| 1 | b | . | f |
| 2 | c | . | . |
The permutations are , (a one-token sequence is its own reverse, and both padding steps stay), and . As a array, reversal_index([3, 1, 2], 3) , and the reversed batch reads “cba”, “d..”, “fe.”. x[::-1] would read “cba”, “..d”, “.fe”.
To see the whole layer at work, take as both modules a running sum: output is the sum of the inputs up to , 0 past the length. For the sequence the forward half is the prefix sums . The backward module reads , outputs , and reversing that back gives : the suffix sums, so position holds the sum from to the end. For a second sequence padded with two 99s, both halves are : the 99s never enter.
A correct solution must reproduce both of these exactly.
Designing the interface
Section titled “Designing the interface”Three functions, from the index to the layer:
def reversal_index(lengths, T: int) -> NDArray # int64 [T, B]def reverse_padded(x, lengths) # Tensor or ndarray [T, B, ...], same kind backdef bidirectional(fwd: Module, bwd: Module, x: Tensor, lengths=None) -> Tensor # [T, B, H_f + H_b]Six properties pin the solution down. The model suite writes them as Hypothesis property tests in test_bi.py:
- Involution. For random and lengths in ,
reverse_padded(reverse_padded(x, n), n)equalsx. - Mirror and fix. For each , the first rows of
reverse_padded(x, n)[:, b]arex[:ℓ_b, b]reversed and the rest equalx[ℓ_b:, b]. - Plain flip. With
lengths=None, the result isx[::-1]. - Per-sequence equivalence. With two
GRUs,bidirectionalequals running each sequence alone: the forward half fromfwd(x[:ℓ_b, b]), the backward half frombwdon the reversed sequence, reversed back; padded rows are 0. - Padding is inert. Changing the values in the padding changes no output.
- Bad lengths raise.
The model tests import only tinyllm.rnn.bi, tinyllm.rnn.gru and tinyllm.autograd.tensor, so they test the contract, not the implementation.
Building it step by step
Section titled “Building it step by step”The reasoning comes first.
- The backward direction must see real tokens in reverse order and nothing else. The single-direction LSTM and GRU already handle padding correctly if it is at the end: past they output 0 and carry the state unchanged. So the job is to produce, for each sequence, an input where the real tokens are reversed and the padding is still at the end. Then
bwdcan be called exactly likefwd, with the samelengths. - That input is a per-column permutation of time. Sequence needs on and beyond. Different columns need different permutations, so no slice can do it; a gather with an index array of shape can, in one vectorized operation.
- The permutation is its own inverse. Mirroring twice is the identity, and fixed points stay fixed. So the same function that builds the backward input also restores the backward outputs to time order. In the worked example,
bwdproduced in reversed time and one more reversal gave the suffix sums . - Gradients come for free. If the gather is
Tensor.__getitem__with integer arrays, its backward scatters each upstream gradient to the source position. Because every position is used exactly once (it is a permutation), the gradient is just the same permutation, and padding receives gradient only from padded outputs, which are constant 0. - Order of the halves is a convention fixed by torch. Concatenating
[forward ; backward]on the last axis matchesbidirectional=True, so weights loaded from torch line up with the halves the decoder reads. - Validate lengths once, at the boundary. Lengths outside or non-integers would silently produce a wrong permutation (negative indices wrap around in NumPy). Rejecting them up front turns a silent wrong answer into an error.
The reversal index
Section titled “The reversal index”reversal_index builds all permutations at once by broadcasting a time column against a lengths row:
def reversal_index(lengths: ArrayLike, T: int) -> NDArray: n = np.asarray(lengths) # Integer 1-D only: a float length like 2.0 would "work" and hide a batcher bug. if n.ndim != 1 or not np.issubdtype(n.dtype, np.integer): raise ValueError(f"lengths must be a 1-D integer array, got {n.dtype} {n.shape}") # 0 would mean "mirror nothing" and index -1; > T would index past the end. if (n < 1).any() or (n > T).any(): raise ValueError(f"lengths must lie in 1..{T}, got {n.tolist()}") t = np.arange(T, dtype=np.int64)[:, None] # [T, 1] n = n.astype(np.int64)[None, :] # [1, B] # Inside the length: mirror around the sequence's own middle. Padding: stay. return np.where(t < n, n - 1 - t, t) # [T, B]For lengths and this returns exactly the array of the hand example, .
Applying the permutation
Section titled “Applying the permutation”reverse_padded applies the permutation. It works on both ndarray and Tensor because it only uses .ndim, .shape and getitem:
def reverse_padded(x: Any, lengths: Optional[ArrayLike]) -> Any: if x.ndim < 2: raise ValueError(f"x must be [T, B, ...], got shape {x.shape}") T, B = x.shape[0], x.shape[1] if lengths is None: # No padding: every sequence has length T, and the index is a plain flip. lengths = np.full(B, T, dtype=np.int64) if np.asarray(lengths).shape != (B,): raise ValueError(f"lengths must have {B} entries, got shape {np.asarray(lengths).shape}") idx = reversal_index(lengths, T) # x[idx[t, b], b]: a gather with two integer index arrays; for a Tensor # the getitem backward scatters the gradient back to the same places. return x[idx, np.arange(B)[None, :]]The second index np.arange(B)[None, :] broadcasts against idx, so output [t, b] reads x[idx[t, b], b]: each column is permuted only within itself. Trailing feature axes are carried along untouched.
The layer
Section titled “The layer”bidirectional is then three lines, one per equation of the layer:
def bidirectional(fwd, bwd, x, lengths=None): if not isinstance(x, Tensor): x = Tensor(np.asarray(x)) out_f, _ = fwd(x, lengths=lengths) # forward, padding -> 0 out_r, _ = bwd(reverse_padded(x, lengths), lengths=lengths) # backward, in reversed time # Reverse back to time order (the involution), then forward half first, like torch. return F.concat([out_f, reverse_padded(out_r, lengths)], axis=-1)Both directions receive lengths; that is what keeps padded outputs at 0 and stops each direction’s state from reading padding. The final states the modules return are discarded because they are recoverable from out (at and ).
The full solution is bi.py.
Why this design
Section titled “Why this design”The reversal is index work plus one gather of ; the two recurrences dominate at each. Running both directions doubles the RNN cost, nothing more.
Consider the alternatives. A Python loop over sequences, slicing x[:ℓ_b, b][::-1] per sequence, is obviously correct but serializes the batch into separate RNN runs. The gather keeps one batched call per direction, and the per-sequence loop survives as the differential check. Packing (pack_padded_sequence) skips padded steps entirely, saving compute when lengths vary a lot, but needs sorting and a variable-batch RNN kernel. Here padding costs some wasted steps, which the lengths mask makes harmless; simplicity wins at this scale. And x[::-1] is cheaper to write and correct only when there is no padding; with padding it puts the padding first. The lengths=None path shows that the plain flip is just the special case .
What can go wrong
Section titled “What can go wrong”The checks a correct solution passes:
| Case | Kind of check | Checks | Why it matters downstream |
|---|---|---|---|
| hand example: reversal | unit | the index array and “cba”, “d..”, “fe.” | the reversal is pinned to a case you can compute |
| hand example: running sums | unit | prefix sums forward, suffix sums backward, padding 0, forward half first | the layer is pinned to a case you can compute |
| involution that keeps padding | property | ; padding fixed; the Tensor gradient is the same permutation | the backward outputs come back in order; gradients reach the right tokens |
| no lengths is a plain flip | unit | without padding, x[::-1] | the unpadded special case |
matches torch bidirectional=True | golden | GRU and LSTM over packed batches: outputs and every gradient | the seq2seq model loads torch encoders |
| matches a per-sequence loop | differential | the batch equals each sequence run alone, both directions | batching changes nothing |
| padding never reaches either direction | boundary | garbage padding changes no output, gets no gradient; final states at and 0 | encoder states for the decoder |
| bad lengths | boundary | length 0, longer than , wrong count, floats | errors at the batcher |
Four mistakes are common.
Warning: Reversing the padded batch with
x[::-1], or mirroring the padding too, makes the backward direction read padding before the sentence, so short sentences get worse encodings than long ones.reversal_indexmirrors only and leaves padding fixed (np.where(t < n, n - 1 - t, t)).
Warning: Not reversing the backward outputs back means position ‘s backward half describes position .
bidirectionalappliesreverse_paddedtoout_rbefore concatenating.
Warning: Concatenating the backward half first lets torch encoders load, but their output halves are swapped for the decoder. The solution writes
F.concat([out_f, ...]): forward half first, as in torch.
Warning: Running a direction without
lengthsmakes padded outputs nonzero, and the backward state at the end of a short sequence has read padding. Bothfwdandbwdare called withlengths=lengths.
Where this leads
Section titled “Where this leads”This section composed the LSTM and GRU, each with lengths, as the two directions, with the reversal as a Tensor getitem on two integer index arrays and F.concat from the op library joining the halves. Next, the seq2seq encoder in Encoder-decoder with teacher forcing is a bidirectional GRU over the source sentence, whose final states initialize the decoder, and Bahdanau additive attention reads the encoder’s per-position outputs, both halves.
Production equivalents:
| This piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
reverse_padded | torch.nn.utils.rnn.pack_padded_sequence | no padded step is computed at all: sequences are sorted by length and the batch shrinks as they end | torch/nn/utils/rnn.py |
bidirectional | torch.nn.LSTM(bidirectional=True) and cuDNN | both directions in one call, sharing the input GEMM | aten/src/ATen/native/RNN.cpp |
| a bidirectional encoder | BERT (BERT: the bidirectional encoder and masked language modeling) | bidirectional context by attention instead of recurrence, every position at once | transformers/models/bert/modeling_bert.py |
| reversal index | Keras go_backwards with masking | the same mask-aware reversal for masked sequences | keras/layers/rnn/bidirectional.py |
Further reading
Section titled “Further reading”- Schuster and Paliwal, “Bidirectional Recurrent Neural Networks” (1997).
- Graves and Schmidhuber, “Framewise phoneme classification with bidirectional LSTM” (2005).
- The
torch.nn.utils.rnndocumentation.
Key terms
Section titled “Key terms”- Bidirectional layer: two recurrent modules, one reading left to right and one right to left, with outputs concatenated per position.
- Length-aware reversal : the per-sequence permutation that mirrors positions and fixes the padding.
- Involution: a map that is its own inverse, .
- Gather: indexing with integer arrays, here
x[idx, arange(B)], whose backward scatters gradients to the source positions.
Summary
Section titled “Summary”- A bidirectional layer is two recurrent modules: one reads left to right, the other right to left, and their outputs are concatenated, forward half first, so position sees the whole sentence.
- With padding, “right to left” means from each sequence’s own last real token: reverse inside each length with the index and leave the padding where it is; a plain
x[::-1]makes the backward RNN read padding first. - The reversal is an involution, so the same gather puts the backward outputs back in time order, and on a Tensor its gradient is the same permutation.
- The batched computation equals running every sequence alone, unpadded, which is the property that makes it trustworthy.
Review questions
Section titled “Review questions”- Why can the same function both prepare the backward input and restore the backward output?
Answer
The per-sequence map mirrors positions $0..\ell_b-1$ and fixes the rest, so applying it twice is the identity. Reversing the output of an RNN that read reversed input puts row $t$ back at time $t$. - The LSTM and GRU modules already ignore steps past the length. Why is that not enough to make
bwd(x[::-1])correct?Answer
The mask ignores steps at indices $\ge \ell_b$. After a full flip, the padding sits at indices $0..T-\ell_b-1$, which are *before* the length, so the mask treats it as real input and the backward state is corrupted before the first real token. - Where in
outis the backward direction’s final state, and why there?Answer
At $[0, b, H_f:]$. The backward RNN ends on the first token, and after reversing its outputs back to time order its last real step lands at position 0. - Why does the gather give correct gradients without any custom backward?
Answer
Getitem's backward scatters each output gradient to the position it was read from. A permutation reads each position exactly once, so the scatter is the inverse permutation, which here is the same permutation, and padded positions receive only the zero gradient of their zero outputs. - What goes wrong if a length of 0 is allowed through?
Answer
The mirror index $\ell_b - 1 - t$ is $-1$ at $t = 0$, which NumPy reads as the last row: a padded value would be silently copied in. The solution rejects lengths outside $1..T$ instead.