One Cell, Once Per Token

Recurrent NetworksMedium+20 XP+20

One Cell, Once Per Token

Unrolling a plain RNN draws one copy of the same cell per time step. Each copy receives two things: its own token, and the hidden state handed over by the copy before it. Every copy uses the same weights.

Here the hidden state has nnn units, and each token has already been turned into a single number. At step ttt the cell reads the token xtx_txt​ and the previous hidden state ht−1h_{t-1}ht−1​:

ht=tanh⁡ ⁣(Wh ht−1+Wx xt+b)h_t = \tanh\!\left(W_h\, h_{t-1} + W_x\, x_t + b\right)ht​=tanh(Wh​ht−1​+Wx​xt​+b)

Task: write rnn_forward(tokens, W_h, W_x, b, h0), returning the hidden state after every step — the whole unrolled chain — with each number rounded to 4 decimal places.

argumentshapemeaning
tokenslist of TTT numbersone token per time step, in order
W_hn×nn \times nn×n list of listsW_h[r][c] is the weight from unit ccc of the previous state into unit rrr of the new one
W_xlist of nnn numbersW_x[r] multiplies the token on its way into unit rrr
blist of nnn numbersone bias per unit
h0list of nnn numbersthe hidden state before any token has been read
  • Return TTT hidden states, in order: [[...h_1...], [...h_2...], ...]. h0 is not part of the output.
  • Round only the returned values. The unrounded hidden state is what gets handed to the next step.
  • The same W_h, W_x and b are used at every step. Nothing in this function depends on the position.

Two of the test cases use identical weights and the same two tokens in the opposite order — and they disagree. That asymmetry is the whole point of recurrence: what a step remembers depends on what was read before it, so a sequence is not a bag of tokens.

t=0
RNN
the
→
t=1
RNN
cat
→
t=2
RNN
sat
→
t=3
RNN
down

Unrolled, the loop becomes a chain. Each copy receives its own word plus the memory from the copy before it.

Examples

tokens = [1.0, 2.0]
W_h = [[0.5, -0.3], [0.2, 0.4]]
W_x = [1.0, -1.0]
b = [0.0, 0.0]
h0 = [0.0, 0.0]
returns [[0.7616, -0.7616], [0.9892, -0.9733]]
tokens = [0.5, -1.0, 2.0]
W_h = [[0.6, 0.1], [-0.4, 0.8]]
W_x = [0.9, 0.3]
b = [0.1, -0.2]
h0 = [0.4, 0.7]
returns [[0.6963, 0.3364], [-0.3351, -0.4695], [0.9291, 0.1572]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run