AI Logic

Architectures

Bidirectional RNN

Updated:

Structure of a bidirectional RNN. Inputs enter two RNNs from below, a forward one and a backward one; the forward RNN passes its hidden state from left to right, the backward RNN from right to left, and each time step's output is computed from both

Background and overview

A bidirectional RNN is a model that combines an RNN reading a sequence from past to future and an RNN reading it from future to past into one network, and computes the output at each time step from both. It was proposed by Schuster and Paliwal in 1997.

An ordinary RNN (such as the Elman network) determines the output at time tt only from the inputs up to tt. In tasks where the whole sequence is available in advance, such as sentences or speech, the inputs after tt are also clues to the answer. For example, the part of speech of a word in a sentence is often settled by the words that follow it.

Before this, two approaches were used to exploit future information:

  • Delay the output: the answer for tt is produced only after reading up to t+Mt+M. However, a larger MM increases the burden of remembering past inputs, and accuracy actually drops. The best MM can only be found by trial for each task.
  • Train two RNNs separately and merge the results: a forward and a backward RNN are trained separately and their outputs are averaged. However, two networks trained on the same data are not independent, so it is unclear how best to merge them.

The bidirectional RNN solved both problems by training the RNNs for the two directions simultaneously as a single network. The output does not need to be delayed, and the way of merging is learned.

The idea later became widely used as the bidirectional LSTM, combined with LSTM, in speech recognition, part-of-speech tagging, and encoders for machine translation (e.g. with additive attention).

Structure: computation at one time step

A bidirectional RNN splits the hidden state of an ordinary RNN into two parts: a "forward state" responsible for the positive time direction and a "backward state" responsible for the negative time direction. As in the figure at the top of the article, the input enters both states, and both states connect to the output at that time step.

The computation proceeds as follows:

  1. Run the forward RNN in order from t=1t = 1 to TT to compute the forward hidden states h→t\overrightarrow{h}_t.
  2. Run the backward RNN in reverse from t=Tt = T to 11 to compute the backward hidden states h←t\overleftarrow{h}_t.
  3. Compute the output yty_t at each time step from both h→t\overrightarrow{h}_t and h←t\overleftarrow{h}_t.
h→t=H(Wxh→ xt+Wh→h→ h→t−1+bh→)h←t=H(Wxh← xt+Wh←h← h←t+1+bh←)yt=Wh→y h→t+Wh←y h←t+by\begin{aligned} \overrightarrow{h}_t &= \mathcal{H}\big(W_{x\overrightarrow{h}}\, x_t + W_{\overrightarrow{h}\overrightarrow{h}}\, \overrightarrow{h}_{t-1} + b_{\overrightarrow{h}}\big) \\ \overleftarrow{h}_t &= \mathcal{H}\big(W_{x\overleftarrow{h}}\, x_t + W_{\overleftarrow{h}\overleftarrow{h}}\, \overleftarrow{h}_{t+1} + b_{\overleftarrow{h}}\big) \\ y_t &= W_{\overrightarrow{h}y}\, \overrightarrow{h}_t + W_{\overleftarrow{h}y}\, \overleftarrow{h}_t + b_y \end{aligned}

Here H\mathcal{H} is the hidden-layer function: tanh for a simple RNN, or the whole LSTM cell for an LSTM (the notation follows Graves et al., 2013).

Since h→t\overrightarrow{h}_t is the result of reading x1,…,xtx_1, \dots, x_t and h←t\overleftarrow{h}_t is the result of reading xt,…,xTx_t, \dots, x_T, yty_t is determined by the inputs of the entire sequence.

The structure follows these rules:

  • The two directions do not connect to each other: the outputs of the forward states are not inputs to the backward states, and vice versa. The weights are also separate.
  • Removing one direction gives an ordinary RNN: removing the backward states yields an ordinary forward RNN, and removing the forward states yields an RNN running backward in time.

It is like two people grading an exam paper: one reads from the first page, the other from the last page, and each page is graded by combining both people's notes. The grading of every page draws on information both before and after that page.

In PyTorch, passing bidirectional=True to nn.RNN, nn.LSTM, or nn.GRU makes it bidirectional. Each time step of output is the concatenation of h→t\overrightarrow{h}_t and h←t\overleftarrow{h}_t, so the size of the last dimension is 2 * hidden_size. Adding an nn.Linear after it gives the same computation as the yty_t equation above.

Training

Because there are no connections between the states of the two directions, a bidirectional RNN unrolled in time can be treated as an ordinary feedforward network. It can therefore be trained with BPTT (Backpropagation Through Time), the same as an ordinary RNN. However, instead of updating one time step at a time, the computation is done over the whole sequence at once.

The procedure in the paper is as follows:

  1. Forward pass: compute the forward states from t=1t = 1 to TT and the backward states from t=Tt = T to 11, then compute the output at each time step.
  2. Backward pass: compute the output errors and propagate them back through the forward states from t=Tt = T to 11 and through the backward states from t=1t = 1 to TT.
  3. Weight update: update the weights shared across all time steps.

At the ends of the sequence, there are no values for the forward state at t=0t = 0 or for the backward state at t=T+1t = T + 1. The paper sets these to a fixed value (0.5). In PyTorch, if no initial state is passed, they start from 0.

A bidirectional RNN must read the input to the end of the sequence before producing an output. It cannot be used as is for tasks where "the future input is not yet available," such as transcribing speech in real time or generating a sentence one word at a time.

Why accuracy improves

The advantage of a bidirectional RNN is that the burden of "remembering" and "combining" is shared between the two directions.

In a forward RNN whose output is delayed by MM time steps, the information in xtx_t must be remembered for MM time steps to produce the answer for tt. The paper explains that an RNN's capacity is split between "remembering past inputs" and "building an answer from the current inputs," and the larger MM is, the less capacity is left for the latter.

In a bidirectional RNN, the future information needed for the answer at tt already arrives at time tt, as the result of the backward state reading from xTx_T down to xtx_t. Each direction only needs to remember the context on its own side, and the output does not need to be delayed.

Also, unlike averaging the outputs of two separately trained RNNs, a bidirectional RNN is trained by propagating the output error to both directions simultaneously. This lets the two directions divide their roles so that each holds "information the other does not have."

Experimental results

The original paper compared the bidirectional RNN with other architectures on artificial data and on TIMIT, a dataset for classifying speech phonemes. For a fair comparison, every architecture had roughly the same number of weights (about 13,000 on TIMIT).

TIMIT phoneme classification (sequences in which each phoneme segment is one input; recognition rate on the test data)

ArchitectureContext usedRecognition rate
MLP (1 segment)That segment only59.67%
MLP (3 segments)1 segment on each side65.69%
MLP (5 segments)2 segments on each side64.32%
Forward RNNAll past63.2%
Backward RNNAll future61.91%
Forward RNN (output delayed by 1 segment)All past + 1 future segment65.83%
Forward RNN (output delayed by 2 segments)All past + 2 future segments63.27%
Merged forward and backward outputsAll past and future65.28%
Bidirectional RNNAll past and future68.53%

Delaying the output by 2 segments lowered the recognition rate even though more information was available. Merging two separately trained RNNs also fell short of the forward RNN delayed by 1 segment. The bidirectional RNN achieved the highest recognition rate with the same number of weights.

On artificial data as well (regression and classification tasks in which the target at a time step is a weighted sum of the inputs 10 steps to the left and 20 steps to the right, averaged over 100 runs), the bidirectional RNN gave clearly better results than a network merging separately trained forward and backward RNNs, with the number of weights matched.

Later, Graves et al. (2013) compared TIMIT phoneme recognition using a 3-layer LSTM with about 3.8 million weights, changing only the direction.

Architecture (trained with CTC, 3 layers, about 3.8M weights)Phoneme error rate
Forward LSTM19.6%
Bidirectional LSTM18.6%

The paper summarizes this difference as "a slight advantage of the bidirectional LSTM over the forward LSTM."

Practical notes

When using a bidirectional RNN, keep the following points in mind:

  • Computation and weights roughly double: with the same hidden_size, there are two RNNs, so the weights and computation are about twice as large. When comparing with other architectures, match the number of weights.
  • It cannot be used for generation: using a backward RNN on a task that "predicts the next word," such as language modeling, lets the model see the answer itself (the future words) in its input. Bidirectional models are only appropriate for tasks where the whole input may be seen (classification, tagging, translation encoders, and so on).
  • Watch out for padding: when sequences of different lengths are padded into a batch, the backward RNN starts reading from the padding. In PyTorch, use pack_padded_sequence so that only the true length is read.

With bidirectional=True, the second half of output[:, -1] is the value of the backward RNN after reading only the last time step. For a summary of the whole sequence, use output[:, -1, :H] for the forward direction and output[:, 0, H:] for the backward direction, or use h_n. The shape of h_n is (num_layers × 2, batch, hidden_size); the forward direction of the last layer is h_n[-2] and the backward direction is h_n[-1].

Comparison with other models

Comparing models by which range of inputs can be used at each time step of a sequence gives the following:

ModelInputs usable for the output at time ttOutput delayUsable for generation (word-by-word prediction)
Forward RNN (Elman network, LSTM, GRU)x1,…,xtx_1, \dots, x_tNoneYes
Forward RNN with output delayed by MMx1,…,xt+Mx_1, \dots, x_{t+M}MM time stepsNo
Bidirectional RNNx1,…,xTx_1, \dots, x_T (all)Waits until the end of the sequenceNo
Transformer encoder (BERT, etc.)x1,…,xTx_1, \dots, x_T (all)Waits until the end of the sequenceNo

Rough guidelines for choosing:

  • Labeling each time step after seeing the whole input (part-of-speech tagging, phoneme classification, named entity recognition, etc.): a bidirectional RNN is a good fit.
  • Real-time processing or word-by-word generation: use a forward RNN. If a small delay is acceptable, delaying the output by a few time steps is also an option.
  • Summarizing an input sentence, as in translation: a setup with a bidirectional RNN as the encoder and a forward RNN as the decoder (Sequence to Sequence with additive attention) was widely used.
  • Handling long contexts with large amounts of data: the Transformer is the mainstream choice.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm

"""
Task: at each time step, answer the last digit of the sum of the neighboring numbers (a small example that needs no data download)
y_t = (x_{t-1} + x_{t+1}) mod 10. It needs the future x_{t+1}, so a forward-only RNN cannot solve it
"""

# Hyperparameters
seq_len = 20
vocab = 10
embed_dim = 16
hidden_size = 64
batch_size = 64
steps = 2000
learning_rate = 1e-3

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


def make_batch(n):
  x = torch.randint(0, vocab, (n, seq_len))
  zero = torch.zeros(n, 1, dtype=torch.long)
  prev = torch.cat([zero, x[:, :-1]], dim=1)   # x_{t-1} (0 at the start)
  nxt = torch.cat([x[:, 1:], zero], dim=1)     # x_{t+1} (0 at the end)
  y = (prev + nxt) % vocab
  return x.to(device), y.to(device)


class Tagger(nn.Module):
  def __init__(self, bidirectional):
    super().__init__()
    self.embed = nn.Embedding(vocab, embed_dim)
    self.rnn = nn.LSTM(embed_dim, hidden_size, batch_first=True, bidirectional=bidirectional)
    d = 2 if bidirectional else 1
    self.head = nn.Linear(d * hidden_size, vocab)   # y_t = W [→h_t; ←h_t] + b

  def forward(self, x):                  # x: [B, T]
    output, (h_n, c_n) = self.rnn(self.embed(x))
    # output: [B, T, D * hidden_size]  forward and backward h_t concatenated at each time step
    #   forward = output[..., :hidden_size], backward = output[..., hidden_size:]
    # h_n: [num_layers * D, B, hidden_size]  last layer: forward is h_n[-2], backward is h_n[-1]
    return self.head(output)             # [B, T, vocab]


def train_and_eval(bidirectional):
  model = Tagger(bidirectional).to(device)
  criterion = nn.CrossEntropyLoss()
  optimizer = optim.Adam(model.parameters(), lr=learning_rate)
  model.train()
  for step in tqdm(range(steps)):
    x, y = make_batch(batch_size)
    optimizer.zero_grad()
    loss = criterion(model(x).reshape(-1, vocab), y.reshape(-1))
    loss.backward()
    optimizer.step()
  model.eval()
  x, y = make_batch(1000)
  with torch.no_grad():
    return (model(x).argmax(dim=-1) == y).float().mean().item()


print(f"Forward only:  {train_and_eval(False) * 100:.2f}%")   # low, since the future is not visible
print(f"Bidirectional: {train_and_eval(True) * 100:.2f}%")    # approaches 100%

FAQ

Q. How does a bidirectional RNN differ from training two RNNs separately and averaging their outputs?
A.

The difference is in how they are trained. A bidirectional RNN propagates the output error to both the forward and backward directions simultaneously and is trained as a single network. As a result, the two directions divide their roles, and the way of merging (the weights of the output layer) is also learned. In the TIMIT experiment of the original paper, with the number of weights matched, the separately trained and merged approach scored 65.28% and the bidirectional RNN 68.53%.

Q. BERT is also called "bidirectional." Is it the same mechanism?
A.

The goal of using context on both sides is the same, but the mechanism differs. A bidirectional RNN runs two RNNs, forward and backward, separately and combines them at the end. BERT is a Transformer encoder in which, through attention, each position directly refers to all positions on both sides from the start.

Q. How are bidirectional RNNs connected when stacking several layers?
A.

The concatenated forward and backward outputs of the lower layer become the input to both the forward and backward directions of the upper layer. Graves et al. (2013) call this a deep bidirectional LSTM. In PyTorch, nn.LSTM(..., num_layers=3, bidirectional=True) gives this form. The shape of weight_ih in the second and higher layers is (4 * hidden_size, 2 * hidden_size) because those layers receive the concatenation of both directions of the layer below.

References

  1. Schuster, M., & Paliwal, K. K. (1997). Bidirectional Recurrent Neural Networks. IEEE Transactions on Signal Processing, 45(11), 2673–2681.
  2. Graves, A., Mohamed, A., & Hinton, G. (2013). Speech Recognition with Deep Recurrent Neural Networks. ICASSP 2013. arXiv:1303.5778.
  3. PyTorch. torch.nn.LSTM.