Run one step of a GRU cell on a batch
The GRU is a gated RNN with two gates instead of the LSTM's three and no separate cell state. It is still common in small on-device speech and time-series models.
Write gru_step(x, h, W, U, b). x is (B, d), h is (B, H), W is (d, 3H), U is (H, 3H), b is (3H,). The 3H columns are ordered [z, r, n], each block H wide. With sigmoid s:
- z = s(x Wz + h Uz + bz) (update gate)
- r = s(x Wr + h Ur + br) (reset gate)
- n = tanh(x Wn + (r * h) Un + bn)
- h_new = (1 - z) * n + z * h
Return h_new with shape (B, H).
def gru_step(x, h, W, U, b)Example
with all weights and biases zero, z = 0.5 and n = 0, so h_new = 0.5 * h.
Understand the idea
A GRU updates its memory with two gates. The reset gate r decides how much of the old state to use when forming a new candidate n. The update gate z decides how much of the old state to keep. Worked example with one input and one hidden unit: x = 1, h = 1. Take all z and r weights and biases zero, so z = r = sigmoid(0) = 0.5. For the candidate let Wn = 1, Un = 2, bn = 0: n = tanh(1 * 1 + (0.5 * 1) * 2) = tanh(2) = 0.9640. Then h_new = (1 - 0.5) * 0.9640 + 0.5 * 1 = 0.9820. Rules with column blocks [z, r, n] of width H: z = sigmoid(x Wz + h Uz + bz), r = sigmoid(x Wr + h Ur + br), n = tanh(x Wn + (r * h) Un + bn), h_new = (1 - z) * n + z * h. Note r multiplies h before the Un projection, and z weights the OLD state. GRUs are still common in small on-device speech, keyword spotting and time series models.