At each time step t, GRU takes the input xt and the hidden state ht−1 from the previous time step, and outputs a new ht. 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.
- From xt and ht−1, compute the two gates (reset rt and update zt) with Sigmoid. Their values are between 0 and 1.
- From xt and the past information multiplied by the reset gate, compute a candidate h~t for the new hidden state with Tanh.
- Mix the old hidden state ht−1 in proportion zt and the candidate h~t in proportion 1−zt to get the new hidden state ht.
The equations of the original paper are as follows (⊙ is element-wise multiplication).
rtzth~tht=σ(Wrxt+Urht−1)=σ(Wzxt+Uzht−1)=tanh(Wxt+U(rt⊙ht−1))=zt⊙ht−1+(1−zt)⊙h~t
| Component | Symbol | Role |
|---|
| Update gate | zt | Decides how much of the old hidden state to keep (1 keeps it as is, 0 replaces it with the candidate) |
| Reset gate | rt | Decides 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) |
| Candidate | h~t | The new content to write |
The update gate couples "how much to keep" and "how much to renew" through zt and 1−zt. 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 zt 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).
rtztntht=σ(Wirxt+bir+Whrht−1+bhr)=σ(Wizxt+biz+Whzht−1+bhz)=tanh(Winxt+bin+rt⊙(Whnht−1+bhn))=(1−zt)⊙nt+zt⊙ht−1
Only the equation for the candidate nt differs slightly from the original paper. The original paper multiplies ht−1 by the reset gate and then applies the weight U, whereas PyTorch applies the reset gate to the already weighted Whnht−1+bhn. 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,n) use the same inputs xt,ht−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.