Bidirectional RNNs: align both directions
双向循环网络
Inspect future context, endpoint summaries and the input Jacobian of a complete bidirectional recurrence.
bidirectional-rnnA word can change meaning after you read the next one
“The seal was damaged” leaves open whether we are discussing an animal or a closure. A later phrase may settle the question. If a labeling system receives the complete sentence before answering, using that later context is legitimate. A system that must answer before the next word arrives has a different information budget.
D2L Section 10.4 constructs a bidirectional layer from two separately parameterized recurrences and aligns their outputs before concatenation. Deep Learning Section 10.3 places both temporal directions in one prediction graph. The crucial distinction is which inputs the output can use, not whether the diagram contains twice as many arrows.
Reverse the computation, then restore the positions
Use zero boundary states at positions zero and T+1. For one scalar unit in each direction:
Compute the forward recurrence in the order 1,2,…,T and the backward recurrence in the order T,…,2,1. Backward here describes a forward evaluation over reversed inputs. It is not backpropagation, does not take a derivative, and does not reverse the flow of physical time. Training still needs derivatives through both computations.
Store a backward state at the position of the input that produced it. Concatenating an unreversed list of backward outputs with forward outputs would incorrectly pair positions t and T+1−t. For aligned token features z, a whole-sequence endpoint summary s, and vector layers of input width D and hidden width H:
P counts transition parameters for two independent directions, each with one combined bias; an output head adds its own parameters. The endpoint summary uses the forward state at T and backward state at 1. The last aligned token row instead contains the backward state at T, which has processed only the final input. Both are valid objects, but they answer different questions.
The program also propagates each state’s derivative with respect to every input. The forward sensitivity obeys:
The indicator is one only when j=t. Start sensitivities at zero; for the backward derivative replace the previous state by the next state and use the backward parameters. Forward sensitivities to future inputs vanish. Backward sensitivities to earlier inputs vanish. Concatenated states can therefore depend on both sides. A zero derivative at a particular parameter setting is not a general architectural guarantee.
Change the last input and inspect the first output
This complete Python 3.12 / NumPy 1.26.4 program computes scalar tanh recurrences with independent parameters, aligned outputs, whole-sequence endpoints and the complete input Jacobian. It deliberately rejects empty sequences because its endpoint summary would be undefined.
import numpy as np
def birnn(sequence,forward=(.5,.25,0),backward=(-.4,.5,.1)):
x=np.array(sequence,dtype=np.float64,copy=True)
weights=np.array([forward,backward],dtype=np.float64)
if x.ndim!=1 or not 1<=len(x)<=32:raise ValueError('one to 32 scalar inputs required')
if weights.shape!=(2,3):raise ValueError('each direction needs input weight, recurrent weight, bias')
if not np.isfinite(x).all() or not np.isfinite(weights).all():raise ValueError('finite inputs and weights required')
if np.any(np.abs(x)>8) or np.any(np.abs(weights)>8):raise ValueError('magnitude limit is 8')
n=len(x);states=np.zeros((n,2));jac=np.zeros((n,2,n))
for direction,order in enumerate((range(n),range(n-1,-1,-1))):
a,r,b=weights[direction];h=0.;sensitivity=np.zeros(n)
for t in order:
h=float(np.tanh(a*x[t]+r*h+b))
sensitivity=r*sensitivity
sensitivity[t]+=a
sensitivity*=1-h*h
states[t,direction]=h
jac[t,direction]=sensitivity
endpoints=np.array([states[-1,0],states[0,1]])
return states,endpoints,jac
if __name__=='__main__':
x=[1,0,-1,2];states,endpoints,jac=birnn(x)
changed,_,_=birnn([1,0,-1,3])
print('aligned states:',np.round(states,9).tolist())
print('whole-sequence endpoints:',np.round(endpoints,9).tolist())
print('last aligned row:',np.round(states[-1],9).tolist())
print('change in first row from future input:',np.round(changed[0]-states[0],9).tolist())
print('first-row input Jacobian:',np.round(jac[0],9).tolist())
Actual output:
aligned states: [[0.462117157, -0.199726768], [0.115018028, 0.195104093], [-0.4392051, 0.195275608], [0.711491872, -0.604367777]]
whole-sequence endpoints: [0.711491872, -0.199726768]
last aligned row: [0.711491872, -0.604367777]
change in first row from future input: [0.0, -0.022216411]
first-row input Jacobian: [[0.393223866, 0.0, 0.0, 0.0], [-0.384043687, -0.184712416, -0.088834429, -0.028193364]]
Changing only the last input leaves the first forward feature unchanged and changes its backward feature. That is a direct information-access test. The two printed summaries expose a second error: using the last row as if both directions had finished reading the complete sequence.
The scalar forward computation takes O(T) work. Saving all input sensitivities takes O(T²) work and memory, an extra audit cost rather than a requirement for normal inference. With H-dimensional states and D-dimensional inputs, ordinary two-direction evaluation costs O(T(HD+H²)); holding aligned outputs costs O(TH). We do not fit a classifier here.
Information must be available at the time of prediction
For offline sequence tagging, an entire observed sequence can be a legitimate input. For an autoregressive next-token objective, placing the target token in the backward encoder’s observed inputs gives away the answer. Shuffling examples or using a chronological train/test split cannot remove leakage inside an individual example.
Bidirectional processing is not categorically forbidden in forecasting: an encoder may read a fully observed historical window in both directions to predict a later target. The cutoff is the prediction time. For streaming applications, waiting for the whole segment adds latency; a bounded lookahead window or chunked model changes the context available and needs separate evaluation.
A padded suffix is not automatically ignored by the reverse recurrence. The true end of each sequence, state reset policy and alignment must be explicit. Our example uses one complete sequence with no padding, masking, stacking or carried external state. Two directions also do not guarantee better accuracy; that requires a task, training and a fair comparison with the same available information.
Trace the information path
- Is the backward recurrence the backward pass of automatic differentiation?
Answer 1: No. It is a forward evaluation over inputs visited in reverse temporal order.
- Which backward state belongs in a whole-sequence endpoint summary?
Answer 2: The state at original position 1, after the backward recurrence has processed all inputs.
- Can a bidirectional encoder read yesterday’s complete measurements to predict tomorrow?
Answer 3: Yes, if every encoder input was available at the prediction cutoff and no target information entered preprocessing.
- Why does changing the last input affect the first backward state?
Answer 4: The backward recurrence processes that last input first and carries its influence toward position 1.
A direction is an information contract
The cited textbook sections establish the two-direction computation. Our endpoint comparison, sensitivity audit and cutoff examples are original. No upstream code or trained benchmark was reproduced. Read RNN for state carry and BPTT for training gradients; the distinction between the two meanings of “backward” is essential before combining them.
Make a prediction, then check
Which state summarizes all inputs in the backward direction?
Learning objectives
- Align backward outputs to original positions.
- Audit the prediction-time information boundary.
Prerequisites & connections
Explore related knowledge →References
- Bidirectional Recurrent Neural Networks — Dive into Deep Learning 1.0.3
D2L authors · 2023 - Deep Learning — Chapter 10: Sequence Modeling: Recurrent and Recursive Nets
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Bidirectional alignment/Jacobians, injected network faults, exhaustive learning curves and stochastic paths, exact momentum trajectories, Nesterov reparameterization and a smooth accelerated bound instance are checked. Bidirectional RNN/debugging use NumPy1.26.4; the other four use the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Bidirectional Recurrent Neural Networks — Dive into Deep Learning 1.0.3 · Section10.4 Eqs10.4.1–10.4.2 and10.4.1 opening: independent directions and aligned concatenation.
- Deep Learning — Chapter 10: Sequence Modeling: Recurrent and Recursive Nets · Section10.3 printed388–390, Figure10.11: past/future context in the prediction graph.
Related topics