Run a vanilla RNN over a sequence

Before transformers, language models read text one token at a time and carried a hidden state forward:

h_t = tanh(x_t @ Wx + h_{t-1} @ Wh + b)

Write rnn_forward(xs, h0, Wx, Wh, b) where xs has shape (T, d_in) and h0 has shape (d_h,). Return all hidden states stacked, shape (T, d_h).

Signaturedef rnn_forward(xs, h0, Wx, Wh, b)

Understand the idea

A vanilla RNN reads a sequence one step at a time and carries a hidden state, its memory, from step to step. At each step it mixes the current input with the previous hidden state and squashes the result with tanh. Like reading a sentence word by word while keeping a running summary in your head. The key detail is feeding the newest hidden state back in, not the starting one. Worked example with scalars: Wx = 1, Wh = 0.5, b = 0, h0 = 0, inputs [1, 0]. Step 1: h1 = tanh(1 x 1 + 0 x 0.5) = tanh(1) = 0.762. Step 2: h2 = tanh(0 x 1 + 0.762 x 0.5) = tanh(0.381) = 0.363. Even with input 0, step 2 is not zero because it remembers step 1. Output is the stack [[0.762], [0.363]]. Rule: h_t = tanh(x_t Wx + h_{t-1} Wh + b) for t = 1..T, returning all h_t with shape (T, d_h). RNNs powered early speech and translation systems before transformers.

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

Run checks the first 2 tests. Submit checks all 2.

  • Sample 1: statesrnn_forward(_xs, np.zeros(2), _Wx, _Wh, _b)
  • Sample 2: nonzero startrnn_forward(_xs, np.array([1.0, -1.0]), _Wx, _Wh, _b)[-1]