Implement the backward pass of one LSTM cell step

Why it matters Custom recurrent kernels and BPTT debugging need this step, and it explains why LSTMs fight vanishing gradients.

The LSTM's cell state gives gradients a nearly additive path. Writing one step's backward pass shows exactly how.

Write lstm_backward(x, h_prev, c_prev, W, b, dh, dc). x is (d,), h_prev and c_prev are (h,), W is (d + h, 4h), b is (4h,). Forward: z = concat(x, h_prev) @ W + b, split into four blocks of size h in the order i, f, g, o; i = sigmoid, f = sigmoid, g = tanh, o = sigmoid; c = f * c_prev + i * g; h_out = o * tanh(c). Given upstream gradients dh on h_out and dc on c (both (h,)), return a dict with "dx", "dh_prev", "dc_prev", "dW", "db".

Signaturedef lstm_backward(x, h_prev, c_prev, W, b, dh, dc)

Example

d = h = 1, x = [0], h_prev = [0], c_prev = [1], W = zeros((2, 4)), b = zeros(4), dh = [0], dc = [1] gives dc_prev [0.5], db [0, 0.25, 0.5, 0], and dx, dh_prev, dW all 0.

Understand the idea

The LSTM's cell state is like a conveyor belt: each step it is multiplied by the forget gate and something new is added. Because the update is mostly addition, the gradient flowing back along the belt is multiplied only by f, not squashed by a tanh at every step. That is the main reason LSTMs remember longer than plain RNNs.

Tiny example: all weights 0, so every sigmoid gate is 0.5 and g = 0. With c_prev = 1: c = 0.5. If only dc = 1 comes from above, dc_prev = dc * f = 0.5. The forget gate gets df = dc * c_prev = 1, times 0.5 * 0.5 = 0.25. The input gate gets di = dc * g = 0, and dg = dc * i = 0.5 passes through tanh'(0) = 1.

Rules: dc_total = dc + dh o (1 - tanh(c)^2); do = dh tanh(c); di = dc_total g; df = dc_total c_prev; dg = dc_total i; dc_prev = dc_total f.

Speech and handwriting LSTMs were trained with exactly these equations through time.

Shapes and data flow

concat (d+h,) @ W (d+h, 4h) -> z (4h,) -> i, f, g, o (h,); dW (d+h, 4h)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplelstm_backward([0.0], [0.0], [1.0], np.zeros((2, 4)), np.zeros(4), [0.0], [1.0])
  • Sample 2: random stepR(lstm_backward(X, HP, CP, W, B, DH, DC))