Read Everything, Then Write

Recurrent NetworksMedium+20 XP+20

Read Everything, Then Write

A sequence-to-sequence model is two recurrent networks in a row. The encoder reads the whole input sequence and keeps only its final hidden state — the context vector. The decoder starts from that context and writes the output one value at a time, feeding each value it writes back in as its next input.

To keep the arithmetic visible, every token here is a single number instead of an embedding vector, so each sequence is just a list of numbers.

Both networks use the same plain RNN update, each with its own weights. With hidden size HHH, a single input number xxx and the previous hidden state hhh, the new hidden state is

hinew=tanh⁡(Wiin x+∑j=0H−1Wijh hj+bi),i=0,…,H−1h^{\text{new}}_i = \tanh\Big(W^{\text{in}}_i\, x + \sum_{j=0}^{H-1} W^{h}_{ij}\, h_j + b_i\Big), \qquad i = 0, \dots, H-1hinew​=tanh(Wiin​x+j=0∑H−1​Wijh​hj​+bi​),i=0,…,H−1

Each network arrives as a dict with "W_in" (a list of HHH numbers), "W_h" (an H×HH \times HH×H list of rows — row iii holds the weights feeding unit iii) and "b" (a list of HHH numbers). The decoder has one extra entry, "v" (a list of HHH numbers), which turns its hidden state sss into the value it writes:

y=∑i=0H−1vi siy = \sum_{i=0}^{H-1} v_i\, s_iy=i=0∑H−1​vi​si​

The forward pass

  1. The encoder starts from a hidden state of all zeros and applies its update once per input number, in order.
  2. Its final hidden state is the context. The decoder's hidden state sss starts equal to the context.
  3. At each output step, update sss with the decoder's weights, using as input xxx the value the decoder wrote at the previous step (000 at the very first step). Then write yyy from the new sss.

Task: write seq2seq(inputs, encoder, decoder, steps) and return a tuple (context, outputs): the context vector, and the list of the steps values the decoder writes. Round every number you return to 4 decimal places, but carry the unrounded values forward through the computation.

E
le
E
chat
E
noir
|
D
the
D
black
D
cat

The encoder reads the whole input sequence first, building up its memory.

Examples

inputs = [1.0, -0.5, 2.0]
encoder = {"W_in": [0.8, -0.5], "W_h": [[0.3, -0.2], [0.4, 0.6]], "b": [0.1, 0.0]}
decoder = {"W_in": [0.5, -0.3], "W_h": [[0.7, 0.1], [-0.2, 0.5]], "b": [0.0, 0.2], "v": [1.2, -0.9]}
steps = 3
returns ([0.9291, -0.6884], [0.9152, 1.0853, 1.2571])
inputs = [0.5]
encoder = {"W_in": [0.8, -0.5], "W_h": [[0.3, -0.2], [0.4, 0.6]], "b": [0.1, 0.0]}
decoder = {"W_in": [0.5, -0.3], "W_h": [[0.7, 0.1], [-0.2, 0.5]], "b": [0.0, 0.2], "v": [1.2, -0.9]}
steps = 2
returns ([0.4621, -0.2449], [0.3619, 0.4147])

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