AI Logic

Architectures

Gated Recurrent Unit (GRU)

Updated:

Architecture of GRU. The top shows the overall flow with a GRU placed at each time step (passing the hidden state to the next time step). The bottom shows the inside of one time step: the update gate and reset gate, the computation of the candidate, and the mixing of the old hidden state and the candidate into the new hidden state

Background and overview

GRU (Gated Recurrent Unit) is an RNN (recurrent neural network) that uses two gates, the "update gate" and the "reset gate," to decide how much of the hidden state to keep and how much to renew. It was introduced in 2014 by Cho et al. as a new hidden unit in the paper that proposed an RNN encoder-decoder for machine translation (a kind of Sequence to Sequence model). The name "GRU" was used by Chung et al. in a paper the same year that compared this unit with LSTM, and it stuck.

A simple RNN such as the Elman network replaces the hidden state entirely with a new value at every time step. As a result, the error signal shrinks the further back in time it goes (vanishing gradient), and the network could not learn relationships between distant time steps. LSTM solved this with a memory cell and three gates, but it has many parts and heavier computation.

GRU takes inspiration from LSTM and simplifies it as follows.

  • No memory cell: a single hidden state hth_t serves as both memory and output.
  • Two gates: the roles of LSTM's forget gate and input gate are merged into one update gate. There is no output gate.
  • An added reset gate: it decides how much of the past hidden state to use when building a new candidate.

The original paper notes that a tanh unit without gates did not give meaningful results on the machine translation task.

Architecture: computation at one time step

At each time step tt, GRU takes the input xtx_t and the hidden state ht−1h_{t-1} from the previous time step, and outputs a new hth_t. The top of the figure at the beginning of the article shows the overall flow unrolled in time, and the bottom shows the inside of one time step.

The computation at one time step proceeds as follows.

  1. From xtx_t and ht−1h_{t-1}, compute the two gates (reset rtr_t and update ztz_t) with Sigmoid. Their values are between 0 and 1.
  2. From xtx_t and the past information multiplied by the reset gate, compute a candidate h~t\tilde{h}_t for the new hidden state with Tanh.
  3. Mix the old hidden state ht−1h_{t-1} in proportion ztz_t and the candidate h~t\tilde{h}_t in proportion 1−zt1 - z_t to get the new hidden state hth_t.

The equations of the original paper are as follows (⊙\odot is element-wise multiplication).

rt=σ(Wrxt+Urht−1)zt=σ(Wzxt+Uzht−1)h~t=tanh⁡(Wxt+U(rt⊙ht−1))ht=zt⊙ht−1+(1−zt)⊙h~t\begin{aligned} r_t &= \sigma(W_r x_t + U_r h_{t-1}) \\ z_t &= \sigma(W_z x_t + U_z h_{t-1}) \\ \tilde{h}_t &= \tanh\big(W x_t + U (r_t \odot h_{t-1})\big) \\ h_t &= z_t \odot h_{t-1} + (1 - z_t) \odot \tilde{h}_t \end{aligned}
ComponentSymbolRole
Update gateztz_tDecides how much of the old hidden state to keep (1 keeps it as is, 0 replaces it with the candidate)
Reset gatertr_tDecides how much of the old hidden state to use when building the candidate (0 ignores the past and builds it from the current input only)
Candidateh~t\tilde{h}_tThe new content to write

The update gate couples "how much to keep" and "how much to renew" through ztz_t and 1−zt1 - z_t. In LSTM, the forget gate and input gate are set independently, so it can "keep the old memory while also adding new content"; in GRU, increasing one decreases the other.

The update gate can be compared to "the fraction of a whiteboard to rewrite." If ztz_t is 1, the previous content is left as is; if it is 0, everything is erased and rewritten. The reset gate is "whether to refer to the previous content" when thinking up the new content.

PyTorch's nn.GRU computes the following (the biases are split into an input-side and a hidden-side term).

rt=σ(Wirxt+bir+Whrht−1+bhr)zt=σ(Wizxt+biz+Whzht−1+bhz)nt=tanh⁡(Winxt+bin+rt⊙(Whnht−1+bhn))ht=(1−zt)⊙nt+zt⊙ht−1\begin{aligned} r_t &= \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{t-1} + b_{hr}) \\ z_t &= \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{t-1} + b_{hz}) \\ n_t &= \tanh\big(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{t-1} + b_{hn})\big) \\ h_t &= (1 - z_t) \odot n_t + z_t \odot h_{t-1} \end{aligned}

Only the equation for the candidate ntn_t differs slightly from the original paper. The original paper multiplies ht−1h_{t-1} by the reset gate and then applies the weight UU, whereas PyTorch applies the reset gate to the already weighted Whnht−1+bhnW_{hn} h_{t-1} + b_{hn}. The PyTorch documentation describes this as an intentional difference for efficiency. Chung et al. compared the two formulations in preliminary experiments and reported similar performance.

Because all three (r,z,nr, z, n) use the same inputs xt,ht−1x_t, h_{t-1}, PyTorch stores the weights for the three in a single matrix (weight_ih_l0 has shape (3*hidden_size, input_size)). For the same hidden_size, the number of weights is about 3 times that of a simple RNN and about three quarters of an LSTM.

Training

Like other RNNs, GRU is trained with BPTT (Backpropagation Through Time), which applies backpropagation to the network unrolled in time.

  1. Read the sequence one time step at a time from the beginning, computing hth_t at each step. The initial h0h_0 is usually set to 0.
  2. Depending on the task, make predictions from hth_t at every time step or from hTh_T at the last step, and compute the loss (cross-entropy for classification).
  3. Compute the gradient of the loss by going back from the last time step to the first, and update the weights shared across all time steps.

In the comparison experiments by Chung et al., training used RMSProp, with gradient clipping at every update that rescales the gradient norm to 1 whenever it exceeds 1. Exploding gradients can still occur even with gates, so clipping is commonly used alongside them.

Why it can learn long-range dependencies

GRU can learn long-range dependencies because the hidden-state update is additive (a weighted average).

A simple RNN replaces the hidden state entirely at every step with ht=tanh⁡(Wxt+Uht−1)h_t = \tanh(W x_t + U h_{t-1}). Each step the error goes back, it is multiplied by UU and the derivative of tanh, and after going back dozens of steps, the error shrinks exponentially.

In GRU, ht=zt⊙ht−1+(1−zt)⊙h~th_t = z_t \odot h_{t-1} + (1 - z_t) \odot \tilde{h}_t, so the main term of the derivative of hth_t with respect to ht−1h_{t-1} is ztz_t. Chung et al. explain that this additive form has two advantages.

  • Features can be remembered for a long time: while the update gate is close to 1, the content of the hidden state is kept as is without being overwritten.
  • Shortcuts that skip over time steps: when the update gate is close to 1, the error travels into the past without passing repeatedly through weight matrices and activation derivatives, so it does not vanish quickly.

Also, because each unit has its own gates, different units can handle different time scales. The original paper states that units capturing short-term dependencies tend to have active reset gates, while units capturing long-term dependencies have update gates that are mostly close to 1.

This idea is the same as LSTM's cell-state update ct=ft⊙ct−1+it⊙gtc_t = f_t \odot c_{t-1} + i_t \odot g_t. GRU can be seen as replacing ftf_t and iti_t with ztz_t and 1−zt1 - z_t and merging the cell state and hidden state into one.

Experimental results

Chung et al. (2014) compared GRU, LSTM, and a gateless tanh unit with matched numbers of weights. The task was sequence modeling (predicting the distribution of the value at the next time step), using four polyphonic music datasets and two speech waveform datasets.

UnitWeights for the music tasksWeights for the speech tasks
tanh100 units (about 20.1k)400 units (about 168.4k)
GRU46 units (about 20.2k)227 units (about 168.9k)
LSTM36 units (about 19.8k)195 units (about 169.1k)

Average negative log-likelihood on test data (lower is better)

DatasettanhGRULSTM
Nottingham (music)3.133.233.20
JSB Chorales (music)9.108.548.67
MuseData (music)6.235.996.23
Piano-midi (music)9.038.829.03
Ubisoft A (speech)6.443.592.70
Ubisoft B (speech)7.620.881.26

On the music data, the three differed little, and GRU had the best value on all but Nottingham. On the speech waveform data, the gated GRU and LSTM greatly outperformed tanh. Which of GRU and LSTM was better flipped depending on the dataset.

The paper notes that gated units tend to converge faster and reach better final performance, and concludes that it cannot say whether GRU or LSTM is better; the choice likely depends on the dataset and task. On the music data, GRU progressed faster both in number of updates and in actual compute time.

Caveats in practice

When using GRU, keep the following points in mind.

  • It cannot be computed in parallel along time: the computation at time tt needs ht−1h_{t-1}, so it must be computed sequentially over the length of the sequence.
  • The amount of output cannot be controlled separately: GRU has no output gate, so the entire content of the hidden state is exposed at every time step. Unlike LSTM, it cannot "remember something but not output it right now."
  • Remove padding from sequences of different lengths with pack_padded_sequence: if the model reads the padding too, the final hTh_T is affected by it.
  • Add dropout along time by other means: nn.GRU(..., dropout=p) applies dropout only to the output of each layer except the last. For the recurrent connections, use Variational Dropout or Zoneout.

The direction of the update gate is reversed in some literature. The original paper and PyTorch use ht=zt⊙ht−1+(1−zt)⊙h~th_t = z_t \odot h_{t-1} + (1 - z_t) \odot \tilde{h}_t (zt=1z_t = 1 keeps the old state), whereas Chung et al. (2014) write ht=(1−zt)⊙ht−1+zt⊙h~th_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t (zt=1z_t = 1 renews it). Both can represent the same functions, but check which equation is in use when interpreting gate values or choosing initial bias values.

Comparison with other models

Comparing the main sequence models from the same angles gives the following.

ModelHow memory is heldGatesWeights for the same hidden_sizeLong-range dependencies
Elman network (simple RNN)Hidden state onlyNone1×Hard to learn due to vanishing gradients
GRUHidden state onlyTwo: update and resetAbout 3×Learnable through gating
LSTMCell state and hidden stateThree: forget, input, outputAbout 4×Learnable through the cell-state path
TransformerNone (looks at every position directly)None (attention)—Directly connected by a single attention step

The differences between GRU and LSTM come down to the following three points.

AspectGRULSTM
Memory and outputOne hidden state serves as bothSeparates the cell state (memory) and hidden state (output)
Amount kept and amount writtenCoupled through ztz_t and 1−zt1 - z_tSet separately by the forget gate and input gate
Use of the pastThe reset gate decides how much of the past goes into the candidateThe candidate uses the past hidden state as is

Rough guidelines for choosing are as follows.

  • To reduce weights and computation: try GRU. For the same hidden_size, it has about a quarter fewer weights than LSTM.
  • When performance comes first: which of GRU and LSTM is better depends on the task, so try both and compare on validation data.
  • To use context from both directions of the sequence: use bidirectional=True to make a bidirectional RNN.
  • To handle 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

"""
A task of remembering the first symbol of a sequence and answering it at the end (a small example that needs no data download)
Example: [A, 5, 2, 8, ..., 3] -> A, [B, 7, 1, 4, ..., 9] -> B. The symbols in between are noise
The same task as the example in the LSTM article, with nn.LSTM replaced by nn.GRU
"""

# Hyperparameters
seq_len = 50            # time gap to remember across
num_noise = 10          # kinds of noise symbols (0-9)
num_classes = 2         # kinds of first symbols (A=10, B=11)
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):
  label = torch.randint(0, num_classes, (n,))
  noise = torch.randint(0, num_noise, (n, seq_len - 1))
  x = torch.cat([(label + num_noise).unsqueeze(1), noise], dim=1)  # put the answer symbol first
  return x.to(device), label.to(device)


class GRUClassifier(nn.Module):
  def __init__(self):
    super().__init__()
    self.embed = nn.Embedding(num_noise + num_classes, embed_dim)
    # batch_first=True: input and output have shape [batch, time, features]
    self.gru = nn.GRU(input_size=embed_dim, hidden_size=hidden_size,
                      num_layers=1, batch_first=True)
    self.head = nn.Linear(hidden_size, num_classes)

  def forward(self, x):                      # x: [B, T]
    e = self.embed(x)                        # [B, T, embed_dim]
    output, h_n = self.gru(e)                # unlike LSTM, the only returned state is h_n (no cell state)
    # output: [B, T, hidden_size]  h_t of the last layer at every time step
    # h_n: [num_layers, B, hidden_size]  the batch stays on the second axis even with batch_first
    return self.head(h_n[-1])                # classify with the last layer's hidden state at the last time step


model = GRUClassifier().to(device)
# Compare the number of weights with LSTM (for the same size, GRU has about 3/4)
lstm = nn.LSTM(embed_dim, hidden_size)
print("GRU weights: ", sum(p.numel() for p in model.gru.parameters()))
print("LSTM weights:", sum(p.numel() for p in lstm.parameters()))

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop
model.train()
for step in tqdm(range(steps)):
  x, y = make_batch(batch_size)
  optimizer.zero_grad()
  loss = criterion(model(x), y)
  loss.backward()
  torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)  # rescale when the gradient norm exceeds 1
  optimizer.step()

# Evaluation (nn.GRU itself behaves the same in train/eval, but switch to eval in case dropout is used)
model.eval()
x, y = make_batch(1000)
with torch.no_grad():
  accuracy = (model(x).argmax(dim=1) == y).float().mean().item()
print(f"Accuracy: {accuracy * 100:.2f}%")

FAQ

Q. Should I use GRU or LSTM?
A.

Their performance is close on many tasks, and which is better depends on the data. In the comparison by Chung et al. (2014), GRU was better on the music data and LSTM on one of the speech datasets, so no conclusion was reached. For the same hidden_size, GRU needs only about three quarters of the weights, which makes it a good fit when you want lighter computation. If unsure, try both and compare on validation data.

Q. What are the reset gate and update gate each responsible for?
A.

The update gate ztz_t decides "how much of the old hidden state to keep," and the reset gate rtr_t decides "how much to refer to the old hidden state when building a new candidate." When rtr_t is close to 0, the candidate is built from the current input only, so the unit can discard the preceding context and start fresh. When ztz_t is close to 1, the candidate is barely used, and the old hidden state is passed to the next time step as is.

Q. Why does PyTorch's `nn.GRU` use a different equation from the paper?
A.

For computational efficiency. The original paper computes the candidate as tanh⁡(Wxt+U(rt⊙ht−1))\tanh(W x_t + U (r_t \odot h_{t-1})), while PyTorch computes it as tanh⁡(Winxt+bin+rt⊙(Whnht−1+bhn))\tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{t-1} + b_{hn})). With the latter, Whnht−1W_{hn} h_{t-1} can be computed together with the other gates' Whrht−1,Whzht−1W_{hr} h_{t-1}, W_{hz} h_{t-1} in a single matrix multiplication. Chung et al. reported that the two formulations performed about the same.

References

  1. Cho, K., van Merriënboer, B., Gulcehre, C., Bahdanau, D., Bougares, F., Schwenk, H., & Bengio, Y. (2014). Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation. EMNLP 2014. arXiv:1406.1078.
  2. Chung, J., Gulcehre, C., Cho, K., & Bengio, Y. (2014). Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling. NIPS 2014 Deep Learning and Representation Learning Workshop. arXiv:1412.3555.
  3. PyTorch. torch.nn.GRU.