🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

RNNs for Text: State, Unrolling, and Gradients

Neural NLPRNNsđŸŸĸ Free Lesson

The recurrence in one equation

A feedforward network maps one input to one output with no memory between calls. A recurrent network adds a hidden state that persists across steps, so the representation of token three can depend on token one without the two ever being presented together. The update rule is compact: the new state is a function of the current input and the previous state, typically tanh of a weighted sum of both, and the same weights are reused at every position. That weight sharing is what makes the model a sequence model rather than a per-position model — it encodes the rules of combination once and applies them at any length.

The consequence is that a recurrent network can, in principle, process a sentence of any length with a fixed parameter count. Whether it actually retains information from the beginning of a long sentence is a separate and much harder question, and the second half of this lesson is about why the answer is usually no.

Recurrent models were the default for NLP from roughly 2014 until attention took over around 2017, and they remain useful: they stream left to right in constant memory, they are natural for incremental applications such as live transcription, and understanding them is the fastest route to understanding why transformers changed the field.

Unrolling turns a loop into a deep graph

Training a recurrent model means backpropagating through the unrolled computation graph, where each time step becomes another layer. The graph shares weights but has depth equal to the sequence length, so gradients must traverse every step to reach the earliest ones.

python
import torch
import torch.nn as nn

class RecurrentClassifier(nn.Module):
    def __init__(self, vocab, embed_dim, hidden, classes):
        super().__init__()
        self.embed = nn.Embedding(vocab, embed_dim)
        self.rnn = nn.RNN(embed_dim, hidden, batch_first=True)
        self.head = nn.Linear(hidden, classes)

    def forward(self, ids):
        # ids: (batch, seq_len)
        x = self.embed(ids)              # (batch, seq_len, embed_dim)
        out, h_n = self.rnn(x)           # out: (batch, seq_len, hidden)
        return self.head(h_n[-1])        # last state only

model = RecurrentClassifier(vocab=20000, embed_dim=128, hidden=256, classes=4)
batch = torch.randint(0, 20000, (16, 60))
logits = model(batch)
print(logits.shape)                     # (16, 4)

# what the unrolled graph looks like for a length-4 sequence:
# x1 -> h1, x2 -> h2, x3 -> h3, x4 -> h4
# loss depends on h4, so dL/dh1 passes through three transitions

Note the shape of out: every position produces a hidden state, which supports per-token tasks such as tagging, while h_n summarises the whole sequence for classification. Choosing which of the two to read is a design decision that maps directly onto whether the label is attached to a span or to the document.

Choosing what to read out of the recurrence

The cell produces a hidden state at every position, and how you reduce that sequence to a prediction is a modelling decision with measurable consequences. Taking the final state is the cheapest option and assumes the last position summarises everything, which is roughly true for short inputs and increasingly false as length grows, because by then the early content has been compressed through dozens of nonlinear transitions. Mean or max pooling over all positions treats every token as equally relevant, which suits topic classification where any one of several keywords can decide the label, and it is markedly more robust to variable-length inputs than last-state readout. Attention over the positions is the strongest option and the one that foreshadows the transformer: rather than committing to one summary, it learns a weighted combination in which the weights depend on the task. For sequence tagging there is no reduction at all — every position is read out independently and the loss is computed per token. A practical rule is to start with pooling for document labels, per-position outputs for span labels, and only add a learned readout when a measured gap justifies it.

Backpropagation through time

To train, the loss at the final step is differentiated with respect to every earlier state, which means the gradient is a product of as many Jacobian matrices as there are steps. Reusing the same weight matrix at each step makes the product behave like a matrix power, and the spectral properties of that matrix decide everything: if the dominant singular value is below one the gradient shrinks geometrically toward the start of the sequence; if it is above one it grows geometrically and the update overshoots.

RegimeCauseSymptomResponse
VanishingRepeated multiplication by small singular valuesEarly tokens never influence the lossGates: LSTM, GRU
ExplodingRepeated multiplication by large singular valuesLoss spikes to NaN within a few stepsGradient clipping
SufficientEigenvalues near oneLearning proceeds across tens of stepsNothing needed
Depth too greatSequence longer than any useful memoryModel relies on recent tokens onlyTruncation, attention

The same equation explains both failures, which is a useful thing to internalise: gradient magnitude is not a bug in the implementation but a direct readout of how far information can travel through the recurrence.

python
import torch
import torch.nn as nn

def gradient_norm_by_position(model, batch, labels):
    model.zero_grad()
    out, _ = model.rnn(model.embed(batch))
    # probe how sensitive each position's state is to the final loss
    norms = []
    for t in range(out.size(1)):
        model.zero_grad()
        loss = model.head(out[:, t, :]).gather(1, labels).mean()
        loss.backward(retain_graph=True)
        norms.append(round(out.grad.norm().item() if out.grad is not None else 0.0, 6))
    return norms

clipper = nn.utils.clip_grad_norm_
# clipper(model.parameters(), max_norm=1.0)  # standard fix for explosion

Gradient clipping is the accepted remedy for explosion because it rescales without changing direction, which preserves the learning signal while bounding the step. There is no equally clean fix for vanishing: you cannot rescale a gradient that has already lost its information content, which is exactly why gating mechanisms were invented.

Text generation exposes the failure

Autoregressive generation makes the limitation concrete. The model must carry a fact from many tokens earlier — a character it introduced in sentence one — forward to use it later, and a vanilla recurrent cell does not reliably do this even when trained to.

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class CharRNN(nn.Module):
    def __init__(self, chars, dim=128, hidden=256):
        super().__init__()
        self.embed = nn.Embedding(len(chars), dim)
        self.rnn = nn.RNN(dim, hidden, batch_first=True)
        self.head = nn.Linear(hidden, len(chars))
        self.chars = chars

    def forward(self, ids, state=None):
        out, state = self.rnn(self.embed(ids), state)
        return self.head(out), state

    @torch.no_grad()
    def generate(self, prime, length=200, temperature=0.8):
        self.eval()
        ids = torch.tensor([[self.chars.index(c) for c in prime]])
        state = None
        out_chars = list(prime)
        for _ in range(length):
            logits, state = self(ids, state)
            probs = F.softmax(logits[0, -1] / temperature, dim=-1)
            nxt = torch.multinomial(probs, 1).item()
            out_chars.append(self.chars[nxt])
            ids = torch.tensor([[nxt]])
        return "".join(out_chars)

# model = CharRNN("abcdefghijklmnopqrstuvwxyz .")
# print(model.generate("the cat sat on the ", length=120))

Run this on a task that requires remembering an opening bracket or a name introduced early and the failure is unmistakable: the model reproduces local n-gram structure fluently while dropping long-range constraints. Temperature controls how much of the distribution's tail is explored — below one sharpens it toward the argmax, above one flattens it toward uniform sampling — but it changes nothing about the underlying memory limit.

Practical remedies that stop short of gates

Before adopting a gated architecture, several cheap interventions recover a surprising amount of long-range signal. Truncating backpropagation through time lets gradients flow locally while still training the shared weights, at the cost of formally severing long-range credit assignment. Layer normalisation stabilises the state scale across steps. Initialising the recurrent matrix near the identity, rather than with a small random matrix, gives the state a near-lossless path to flow through. And simply increasing the hidden dimension compensates, because a larger matrix has more opportunity to carry a singular value near one.

None of these solve the structural problem: a single linear path through dozens of multiplications is fragile no matter how carefully it is initialised. That observation is precisely what motivates the next lesson, where a separate cell state acts as a highway whose gradient can travel essentially unobstructed while gates decide, element by element, what gets written to it and what gets read back out.

âš ī¸Watch for NaN within the first hundred steps

An exploding gradient announces itself immediately. Clip by global norm as a default, log the pre-clip norm each step, and treat a steady upward trend as a signal to lower the learning rate rather than as noise to be clipped away.

Common Mistakes

Feeding a 500-token document to a vanilla RNN and expecting early tokens to matter

Fix: Check gradient norms by position; if they collapse, truncate the window or move to a gated cell.

Reading only the final hidden state for a tagging task

Fix: Per-token labels need the full output tensor; the final state is a summary and discards position-level detail.

Omitting gradient clipping because loss looks stable on toy data

Fix: Clip by global norm by default; instability appears as soon as sequence length or learning rate rises.

Confusing sampling temperature with model quality

Fix: Temperature reshapes the output distribution but cannot add memory or knowledge the model never had.

Best Practices

  • Log per-position gradient norms during the first training runs of any recurrent model
  • Apply global-norm gradient clipping as a default rather than a rescue measure
  • Use teacher forcing and truncated BPTT to keep the unrolled graph a manageable depth
  • Establish the per-token and per-sequence baselines before adding architecture complexity

Interview Questions

Q1: Why do gradients vanish in a vanilla RNN?

Backpropagation through time multiplies one Jacobian per step, and the recurrent weight matrix raised to the power of the sequence length drives the product toward zero when its singular values are below one.

Q2: What does weight sharing across time steps give you?

A parameter count independent of sequence length and a learned combination rule that transfers to positions never seen during training.

Q3: Why is clipping an effective fix for exploding gradients but not for vanishing ones?

Clipping rescales a gradient that still carries directional information; a vanished gradient has already lost its information content, so rescaling it cannot recover the signal.

Key Takeaways

  • A recurrent cell applies one weight-shared rule at every position, giving constant parameters for arbitrary length
  • Unrolling creates a graph as deep as the sequence, so gradient magnitude is governed by a matrix power
  • Vanishing and exploding gradients are two ends of the same spectrum determined by the recurrent matrix
  • Generation reveals memory limits that classification metrics often conceal
  • Clipping, normalisation, identity initialisation, and truncation each buy partial relief; gates solve the structural issue
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert NLP Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement