What the Belt Keeps

Recurrent NetworksEasy+10 XP+10

What the Belt Keeps

A single LSTM unit is reading a sentence. At every step its three gates have already produced their values — in a real LSTM each gate is a small network that computes its own value from the current token and the previous hidden state, but here the numbers are handed to you so you can watch what they do to the memory.

Two things travel along the chain: the cell state ctc_tct​, the long-term memory that runs straight through with only small controlled edits, and the hidden state hth_tht​, this step's visible answer.

Each step supplies four numbers:

symbolnamejob
ftf_tft​forget gatehow much of the old cell state survives
iti_tit​input gatehow much of the candidate gets written in
gtg_tgt​candidatewhat this step could add to the memory
oto_tot​output gatehow much of the memory is revealed now

The memory is edited, then read out:

ct=ft ct−1+it gt,ht=ottanh⁡(ct)c_t = f_t\, c_{t-1} + i_t\, g_t, \qquad h_t = o_t \tanh(c_t)ct​=ft​ct−1​+it​gt​,ht​=ot​tanh(ct​)

Task: write lstm_run(gates, c0). gates is a list of [f, i, g, o], one entry per time step in order, and c0 is the cell state before the first token arrives. Return a list of [c_t, h_t] pairs, one pair per step, with every value rounded to 4 decimal places.

  • A gate is only ever multiplied by something. ftf_tft​ multiplies the old cell state; iti_tit​ multiplies the candidate.
  • gtg_tgt​ is a candidate, not a gate, so it is not confined to [0,1][0, 1][0,1] and may be negative.
  • The cell state itself is never squashed — it is a running quantity and can grow beyond 111.
  • Round only the numbers you return. The unrounded cell state is what carries into the next step.

Watch the third step of the first case: forget gate at 111, input gate at 000, and the cell state crosses that step completely untouched. That is the conveyor belt — and it is the reason an LSTM can hold something for hundreds of steps while a plain RNN's single memory is rewritten from scratch every time.

old cell state
0.80
-0.50
0.60
0.30
↓ × forget
0.80
-0.50
0.60
0.30
forget1.00

Near 1: keep everything.

Examples

gates = [[1.0, 1.0, 0.5, 1.0], [1.0, 1.0, 0.5, 1.0], [1.0, 0.0, 0.9, 0.5]]
c0 = 0.0
returns [[0.5, 0.4621], [1.0, 0.7616], [1.0, 0.3808]]
gates = [[0.9, 0.5, 2.0, 0.8], [0.0, 1.0, -1.0, 1.0], [1.0, 0.0, 5.0, 0.25]]
c0 = 1.5
returns [[2.35, 0.7856], [-1.0, -0.7616], [-1.0, -0.1904]]

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