Run a stacked (multi-layer) RNN over a sequence

Why it matters Production speech and translation RNNs typically stack 2 to 8 layers this way.

Deep RNNs stack layers in depth: layer 2 reads the whole output sequence of layer 1, step by step.

Write stacked_rnn(x, params). x is (T, d0). params is a list of (W, U, b) per layer with W (d_{l-1}, h_l), U (h_l, h_l), b (h_l,). Each layer is a tanh RNN starting from h = 0: h_t = tanh(inp_t @ W + h_{t-1} @ U + b). The input sequence of layer 1 is x and of layer l is the output sequence of layer l - 1. Return (top, finals): top is the (T, h_L) output of the last layer, finals is the list of each layer's last hidden state.

Signaturedef stacked_rnn(x, params)

Example

x = [[1], [1]], params = [([[1]], [[0]], [0]), ([[2]], [[0]], [0])] gives top about [[0.9093], [0.9093]] and finals [[0.7616], [0.9093]].

Understand the idea

One RNN layer turns a sequence into a sequence of memories. Stacking layers lets the second layer find patterns in the first layer's memories, the way a sentence is built from words and a paragraph from sentences. The time loop runs inside each layer; the layers run one after another.

Tiny example: two steps of x = 1. Layer 1 has weight 1 and no recurrence: tanh(1) = 0.7616 at both steps. Layer 2 has weight 2: tanh(2 * 0.7616) = tanh(1.523) = 0.9093 at both steps. Finals: [0.7616] and [0.9093].

Rule: h^l_t = tanh(h^{l-1}_t W_l + h^l_{t-1} U_l + b_l), with h^0_t = x_t.

Stacked LSTMs powered neural machine translation before transformers, and stacked GRUs are still used in on-device speech models.

Shapes and data flow

x (T,d0) -> layer1 (T,h1) -> layer2 (T,h2) -> ... -> top (T,hL)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplestacked_rnn([[1.0], [1.0]], [([[1.0]], [[0.0]], [0.0]), ([[2.0]], [[0.0]], [0.0])])
  • Sample 2: three layersstacked_rnn(X, P3)