Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 2

Recurrent Networks and Their Gates

Write one recurrent step by hand and match nn.RNN, read the output and state shapes of RNN, GRU and LSTM layers, measure how the gradient of a late loss fades with distance through time and how open LSTM and GRU gates keep it alive, then make a ReLU RNN explode and rescue it with gradient-norm clipping.

Contentsand lesson path

What you will learn

  • Explain vanishing and exploding gradients in recurrent networks, how gating and gradient clipping mitigate them, and why encoder-decoder attention was introduced.

Prerequisites: Deep Learning Fundamentals

01. Why it matters

A recurrent network reads a sequence one step at a time and keeps a summary of what it has read so far. That summary, the hidden state, is how it can connect "not" at the start of a review with "good" five words later, or a spike in sales with the same weekday a week on. In practice, plain recurrent networks often struggle to learn links that span more than a few dozen steps, and some training runs blow up into NaN without warning. Both problems come from the same place, the way gradients flow backwards through time, and the gated layers you will use in the next two lessons, the LSTM and the GRU, were designed around it.

This lesson builds that understanding from measurements. You need Python 3.12 and PyTorch 2 (CPU build); each script runs in a few seconds. Gradients and backward() were introduced in backpropagation and autograd. The last digit of the outputs can differ on other CPUs or library versions.

02. One recurrent step, by hand

A plain recurrent neural network (RNN) updates its hidden state with one formula at every step t: hₜ = tanh(Wₓ xₜ + Wₕ hₜ₋₁ + b). The input xₜ enters through Wₓ, the previous state through the recurrent weights Wₕ, and tanh squashes the result into (−1, 1). The same three tensors are used at every step, which is why one small layer can read sequences of any length. The script runs that loop by hand with the weights of an nn.RNN and compares the result.

Python · rnn_by_hand.py
import torch
from torch import nn

torch.manual_seed(0)
rnn = nn.RNN(input_size=3, hidden_size=2, batch_first=True)   # tanh by default
x = torch.randn(1, 4, 3)                                       # 1 sequence, 4 steps

W_x, W_h = rnn.weight_ih_l0, rnn.weight_hh_l0                  # (2, 3) and (2, 2)
b = rnn.bias_ih_l0 + rnn.bias_hh_l0
h = torch.zeros(2)                                             # h_0
with torch.no_grad():
    for t in range(4):
        h = torch.tanh(W_x @ x[0, t] + W_h @ h + b)    # same weights at every step
        print(f"step {t}: h = {h.numpy().round(4)}")
    output, h_n = rnn(x)
print("nn.RNN output[0, -1]:", output[0, -1].detach().numpy().round(4))
print("output shape:", tuple(output.shape), " h_n shape:", tuple(h_n.shape))
Terminal
python rnn_by_hand.py
Expected output
step 0: h = [-0.3186 -0.4919]
step 1: h = [-0.9046 -0.8301]
step 2: h = [-0.7949 -0.2354]
step 3: h = [-0.9334 -0.5626]
nn.RNN output[0, -1]: [-0.9334 -0.5626]
output shape: (1, 4, 2)  h_n shape: (1, 1, 2)

The hand-written loop and nn.RNN agree to four decimals. PyTorch stores two bias vectors, bias_ih and bias_hh, which the script adds together; mathematically they act as one. output holds the state after every step, here (1, 4, 2), and h_n holds only the final state.

03. RNN, GRU and LSTM layers and their shapes

All three PyTorch layers share one interface. With batch_first=True the input is (batch, time, features) and output is (batch, time, directions × hidden): the top layer's state at every step. The final state h_n keeps the layout (layers × directions, batch, hidden) whatever batch_first says, because batch_first only changes the input and output. An LSTM also returns c_n, its cell state, with the same shape as h_n. Stacking (num_layers=2) feeds one layer's outputs into the next; bidirectional=True adds a second pass that reads each sequence from the end.

Python · shapes.py
import torch
from torch import nn

torch.manual_seed(0)
x = torch.randn(8, 20, 16)                 # batch 8, 20 steps, 16 features per step
for cls in (nn.RNN, nn.GRU, nn.LSTM):
    layer = cls(input_size=16, hidden_size=32, num_layers=2,
                bidirectional=True, batch_first=True)
    out, state = layer(x)
    h_n = state[0] if cls is nn.LSTM else state    # LSTM returns (h_n, c_n)
    n_params = sum(p.numel() for p in layer.parameters())
    print(f"{cls.__name__:4s} output {tuple(out.shape)}  h_n {tuple(h_n.shape)}"
          f"  parameters {n_params}")
# h_n is (num_layers * directions, batch, hidden): row -2 is the top layer forward,
# row -1 the top layer backward. The forward one equals output at the last step:
gru = nn.GRU(16, 32, num_layers=2, bidirectional=True, batch_first=True)
out, h_n = gru(x)
print("top forward h_n == output[:, -1, :32]:",
      torch.allclose(h_n[-2], out[:, -1, :32]))
print("top backward h_n == output[:, 0, 32:]:",
      torch.allclose(h_n[-1], out[:, 0, 32:]))
Terminal
python shapes.py
Expected output
RNN  output (8, 20, 64)  h_n (4, 8, 32)  parameters 9472
GRU  output (8, 20, 64)  h_n (4, 8, 32)  parameters 28416
LSTM output (8, 20, 64)  h_n (4, 8, 32)  parameters 37888
top forward h_n == output[:, -1, :32]: True
top backward h_n == output[:, 0, 32:]: True

Two layers times two directions gives the 4 in h_n, and the two directions side by side give the 64 in output. The last two lines show how the pieces line up: the top forward state equals the last step of the first half of output, while the backward direction finishes at step 0. For a classifier on a one-direction, one-layer model, h_n[-1] is the usual (batch, hidden) summary.

The parameter counts reveal the internal structure. The GRU has exactly three times the weights of the plain RNN, and the LSTM four times, because each gate is a small layer of its own, with its own input and recurrent weights, as the next sections explain.

04. Backpropagation through time and vanishing gradients

To train a recurrent network, autograd unrolls it: the loop over steps becomes one long chain of identical operations, and the chain rule runs back along it. This is backpropagation through time (BPTT). The gradient that reaches step t from a loss at the last step T is a product of one Jacobian (the matrix of derivatives of one step's state with respect to the previous one) per step in between. For the plain RNN each Jacobian is diag(1 − hₖ²) Wₕ: the slope of tanh times the recurrent weights. Multiply many matrices that shrink vectors and the result shrinks exponentially: a vanishing gradient. Multiply many that stretch them and it grows exponentially: an exploding gradient.

Gated layers add a second path. The LSTM keeps a cell state updated additively: cₜ = fₜ ⊙ cₜ₋₁ + iₜ ⊙ gₜ, where ⊙ is element-wise multiplication. The forget gate fₜ, a sigmoid between 0 and 1, decides how much old memory to keep, the input gate iₜ how much new content gₜ to write, and an output gate how much of the cell to expose as hₜ. Along the cell path, the gradient is multiplied by fₜ at each step, not by a weight matrix and a tanh slope. The GRU merges this into its hidden state: an update gate zₜ mixes old state and a new candidate, hₜ = (1 − zₜ) ⊙ nₜ + zₜ ⊙ hₜ₋₁, and a reset gate decides how much of the old state the candidate may use.

The script measures, for a loss on the last of 100 steps, how large the gradient is with respect to inputs further and further back. It also sets the forget-gate bias of one LSTM, and the update-gate bias of one GRU, to 3, which opens those gates to about sigmoid(3) ≈ 0.95.

Python · bptt.py
import torch
from torch import nn

T, H = 100, 32


def grad_by_distance(layer):
    torch.manual_seed(1)
    x = torch.randn(16, T, 4, requires_grad=True)   # 16 random sequences
    out, _ = layer(x)
    out[:, -1].sum().backward()                     # a loss on the last step only
    norms = x.grad.norm(dim=2).mean(dim=0)          # gradient size at each input step
    return [norms[T - 1 - d].item() for d in DIST]


layers = {}
for name, cls in [("RNN (tanh)", nn.RNN), ("GRU", nn.GRU), ("LSTM", nn.LSTM)]:
    torch.manual_seed(0)
    layers[name] = cls(4, H, batch_first=True)
torch.manual_seed(0)
lstm = nn.LSTM(4, H, batch_first=True)
with torch.no_grad():
    lstm.bias_ih_l0[H:2 * H] = 3.0          # gate order i, f, g, o: forget = 2nd
layers["LSTM, forget bias 3"] = lstm
torch.manual_seed(0)
gru = nn.GRU(4, H, batch_first=True)
with torch.no_grad():
    gru.bias_ih_l0[H:2 * H] = 3.0           # gate order r, z, n: update = 2nd
layers["GRU, update bias 3"] = gru

DIST = (0, 10, 30, 60, 99)
print(f"{'steps back from the loss':24s}" + "".join(f"{d:>10d}" for d in DIST))
for name, layer in layers.items():
    print(f"{name:24s}" + "".join(f"{g:10.1e}" for g in grad_by_distance(layer)))
Terminal
python bptt.py
Expected output
steps back from the loss         0        10        30        60        99
RNN (tanh)                 1.0e+00   5.1e-03   3.8e-08   3.8e-16   0.0e+00
GRU                        6.7e-01   4.1e-03   1.4e-07   6.7e-14   4.0e-22
LSTM                       3.8e-01   9.4e-04   3.7e-08   1.8e-14   1.8e-22
LSTM, forget bias 3        1.8e-01   4.3e-02   5.4e-02   4.5e-02   1.2e-01
GRU, update bias 3         6.7e-02   3.7e-02   1.5e-02   4.4e-03   1.1e-03

For the plain RNN the gradient falls from 1.0 to 5.1e-3 in ten steps, about 0.59 per step, and is 3.8e-16 after 60. After 99 steps it is smaller than float32 can store and prints as zero. An input that far back has no effect on learning at all.

The surprise is the next two rows: freshly initialised, the GRU and the LSTM vanish almost as fast. At initialisation their biases are near 0, so the forget and update gates sit near sigmoid(0) = 0.5 and halve the signal at every step. Gates are not magic; they give the network a path it can learn to keep open. With the gates opened by a bias of 3, the LSTM's gradient stays between 0.04 and 0.18 at every distance, and the GRU still has about 1e-3 after 99 steps. This is why some libraries, Keras for one, start the LSTM forget-gate bias at 1, and why gated layers can learn dependencies across many more steps than a plain RNN, though not across arbitrary distances.

05. Exploding gradients and gradient clipping

The opposite failure is easiest to see in an RNN with ReLU instead of tanh, whose recurrent weights are 1.05 times the identity matrix: each step stretches the state a little. Over 40 steps that compounds. The script trains it to output the sum of its inputs, once without protection and once with gradient-norm clipping. clip_grad_norm_ computes the total norm of all gradients, the length of every gradient joined into one long vector, and, if it is above max_norm, multiplies every gradient by the same factor so the total equals max_norm. It returns the norm measured before clipping, which is worth logging. Passing max_norm=inf measures without clipping.

Python · explode.py
import torch
from torch import nn


def make_model():
    torch.manual_seed(0)
    rnn = nn.RNN(1, 16, nonlinearity="relu", batch_first=True)
    with torch.no_grad():
        rnn.weight_hh_l0.copy_(1.05 * torch.eye(16))       # recurrent gain above 1
    return rnn, nn.Linear(16, 1)


torch.manual_seed(0)
x = torch.rand(32, 40, 1)
y = x.sum(dim=1)                                  # target: the sum of the 40 inputs
for clip in (None, 1.0):
    rnn, head = make_model()
    params = list(rnn.parameters()) + list(head.parameters())
    opt = torch.optim.SGD(params, lr=1e-3)
    for step in range(1, 31):
        out, _ = rnn(x)
        loss = nn.functional.mse_loss(head(out[:, -1]), y)
        opt.zero_grad()
        loss.backward()
        max_norm = clip if clip else float("inf")      # inf: measure, do not clip
        norm = nn.utils.clip_grad_norm_(params, max_norm)
        opt.step()
        if step in (1, 2, 3, 10, 30):
            print(f"clip {clip!s:4s} step {step}: loss {loss.item():9.3g}"
                  f"  grad norm before clipping {norm.item():9.3g}")
Terminal
python explode.py
Expected output
clip None step 1: loss       238  grad norm before clipping  1.05e+04
clip None step 2: loss       inf  grad norm before clipping       nan
clip None step 3: loss       nan  grad norm before clipping       nan
clip None step 10: loss       nan  grad norm before clipping       nan
clip None step 30: loss       nan  grad norm before clipping       nan
clip 1.0  step 1: loss       238  grad norm before clipping  1.05e+04
clip 1.0  step 2: loss       228  grad norm before clipping  1.04e+04
clip 1.0  step 3: loss       218  grad norm before clipping  1.03e+04
clip 1.0  step 10: loss       149  grad norm before clipping  9.22e+03
clip 1.0  step 30: loss      20.6  grad norm before clipping  3.76e+03

The first gradient has a norm of about 10,500. A plain SGD step with a learning rate of 0.001 moves the weights by about 10, far outside any sensible range, so the next loss overflows to inf and everything after is NaN. With clipping, the same gradient is scaled down by about 10,500 and the update keeps its direction; the loss falls from 238 to 20.6 in 30 steps, even though the raw gradient norm stays in the thousands.

Clipping limits the size of a step; it does not make vanished gradients larger, so it addresses explosion only. A common pattern is to clip every step at a norm of about 1 and to log the returned norm, because a sudden rise in that number is an early warning. clip_grad_value_ is a different tool: it clamps each element separately, which changes the direction of the update.

06. Check your understanding

Practice check · 3 questions

Steps, gates and clipping

Use the scripts and outputs of this lesson.

Q1. In `bptt.py`, the plain RNN's gradient shrinks by about 0.59 per step over the last ten steps. What sets that per-step factor?
Q2. In `shapes.py`, the GRU has exactly three times the parameters of the plain RNN of the same sizes. Why?
Q3. In `explode.py` with clipping, the first gradient norm is about 10,500 and `max_norm` is 1.0. What does `clip_grad_norm_` do to the gradients before `opt.step()`?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the practice project you will train an LSTM or GRU. Prepare its training loop with these habits.

  1. Call clip_grad_norm_ between loss.backward() and optimizer.step(), start with max_norm=1.0, and log the norm it returns every few steps.
  2. Run bptt.py on your own layer size and sequence length, and decide whether a gated layer is needed or the dependencies are short enough for a plain RNN.
  3. Try the LSTM with and without a forget-gate bias of 1 and compare the validation curves of both runs over two seeds.

08. Review prompt

Without looking back, write the update formula of a plain RNN; give the shapes of output and h_n for a two-layer bidirectional GRU with batch_first=True; explain why backpropagation through time multiplies one Jacobian per step and what that does to early inputs; describe the forget gate and the additive cell update of an LSTM, and the update gate of a GRU; say why a freshly initialised LSTM can still lose its gradients; and explain what clip_grad_norm_ computes and what it cannot fix.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check