Run a bidirectional RNN on padded sequences of different lengths

Why it matters Bidirectional LSTMs and GRUs for tagging and speech use packed sequences for exactly this reason.

A bidirectional RNN reads left to right and right to left. With padding, the backward pass must start at each sequence's last REAL token, not at the padded end.

Write birnn(x, lengths, Wf, Uf, bf, Wb, Ub, bb). x is (B, T, d), lengths is (B,) with 1 <= length <= T. Both directions are tanh RNNs h = tanh(x_t @ W + h @ U + b) starting from h = 0, with W (d, h), U (h, h), b (h,). The forward direction runs t = 0..L-1; the backward direction runs t = L-1 down to 0 for a sequence of length L. Return (out, final): out is (B, T, 2h) with [forward h_t, backward h_t] at each real step and zeros at padded steps; final is (B, 2h) = [forward state after step L-1, backward state after step 0].

Signaturedef birnn(x, lengths, Wf, Uf, bf, Wb, Ub, bb)

Example

x = [[[1], [0]]], lengths = [1], all weights 1 (d = h = 1), biases 0 gives out [[[0.7616, 0.7616], [0, 0]]] and final [[0.7616, 0.7616]].

Understand the idea

A forward RNN at word t knows only the words before it. A backward RNN reads from the end, so at word t it knows the words after it. Stacking both gives every position context from both sides. With padding, the backward reader must start at the real last word, otherwise it first reads a run of padding and starts with a polluted memory, like reading a letter from the end but beginning in the blank space below the signature.

Tiny example: one sequence of length 1, x = 1, all weights 1. Forward: tanh(1) = 0.7616. Backward starts at the same step: tanh(1) = 0.7616. The padded step stays [0, 0].

Rules: forward t = 0..L-1, backward t = L-1..0, out_t = [h_fwd_t, h_bwd_t], zeros for t >= L.

Named entity tagging, speech recognition encoders and ELMo use bidirectional RNNs.

Shapes and data flow

x (B,T,d) -> fwd, bwd (B,T,h) -> out (B,T,2h); final (B,2h)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplebirnn([[[1.0], [0.0]]], [1], [[1.0]], [[1.0]], [0.0], [[1.0]], [[1.0]], [0.0])
  • Sample 2: padded batchR(birnn(X, [3, 1], Wf, Uf, bf, Wb, Ub, bb))