Skip to content

← Model Architectures step 5 of 9

Medium End-to-End

RNN Sequence Forward Pass

A recurrent neural network carries a hidden state from one sequence position to the next. Each update combines the current input with the previous state, then applies tanh. Later states can therefore depend on earlier inputs.

Your task

Implement rnn_forward(x, W_xh, W_hh, b_h, h0) for a complete sequence:

  • x has shape (seq_len, input_dim).
  • W_xh has shape (input_dim, hidden_dim).
  • W_hh has shape (hidden_dim, hidden_dim).
  • b_h and h0 each have shape (hidden_dim,).

All arrays are floating-point and all dimensions are positive. There is no batch axis. Start with h = h0, then process rows of x from first to last:

h = tanh(x[t] @ W_xh + h @ W_hh + b_h)

The right-hand side uses the state from the previous step. Apply tanh elementwise and use the matrices in the supplied orientation. Reuse the same weights and bias at every step.

Return every updated state, stacked in order with shape (seq_len, hidden_dim). The first output row is the state after processing x[0]; do not prepend h0 or return only the final state. Keep inputs unchanged.

Example

For a one-feature sequence x = [[1], [1]], input weight 1, recurrent weight 0.5, bias 0 and initial state 0:

first state  = tanh(1 + 0.5 * 0)        = 0.761594
second state = tanh(1 + 0.5 * 0.761594) = 0.881130

Return approximately [[0.761594], [0.881130]]. The second step uses the new first state, not h0 again. If W_hh is all zeros, the previous state contributes nothing and each row depends only on that row's input and bias.