Implement one step of an LSTM cell

An LSTM adds a cell state and three gates so information can survive many steps.

Write lstm_step(x, h, c, W, b) where x is (d_in,), h and c are (d_h,), W is (d_in + d_h, 4 d_h) and b is (4 d_h,). Compute z = concat(x, h) @ W + b and split z into four equal chunks in the order i, f, g, o:
i, f, o = sigmoid of their chunks; g = tanh of its chunk
c_new = f * c + i * g
h_new = o * tanh(c_new)
Return (h_new, c_new).

Signaturedef lstm_step(x, h, c, W, b)

Understand the idea

An LSTM cell adds a separate cell state that acts like a conveyor belt, plus three gates that decide what to forget, what to write and what to show. Gates use sigmoid, so they are between 0 and 1, like valves. Compute one big vector z = concat(x, h) W + b and cut it into four equal chunks in the order i, f, g, o. Worked example with d_h = 1: suppose z = [0, 2, 1, 0] and old c = 1. Then i = sigmoid(0) = 0.5, f = sigmoid(2) = 0.881, g = tanh(1) = 0.762, o = sigmoid(0) = 0.5. New cell c = 0.881 x 1 + 0.5 x 0.762 = 1.262. New hidden h = 0.5 x tanh(1.262) = 0.5 x 0.852 = 0.426. Rule: i, f, o = sigmoid of their chunks, g = tanh of its chunk; c_new = f * c + i * g; h_new = o * tanh(c_new). Forgetting the tanh on c lets h grow without limit. LSTMs were the standard for speech recognition and translation before transformers.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: one step hlstm_step([1.0, -1.0, 0.5], [0.2, -0.3], [0.5, 1.5], _W, _b)[0]
  • Sample 2: one step clstm_step([1.0, -1.0, 0.5], [0.2, -0.3], [0.5, 1.5], _W, _b)[1]