Home / Deep Learning

How RNN Processes Text

By Updated

Visualize how memory is passed forward to perform Sentiment Analysis (a Sequence-to-Vector task).

Overview

The Power of Memory in Language

Standard neural networks have a major limitation: they have no memory of the past. They process each input independently. This is a problem for language, where the order of words is crucial. For example, "dog bites man" and "man bites dog" use the same words but have completely different meanings.

Recurrent Neural Networks (RNNs) solve this by introducing a memory loop. As an RNN reads a sentence word by word, it passes a summary of what it has seen so far to the next step. This summary is called the hidden state.

RNN Analysis

Time Steps -
Hidden Size -
Shared Parameters -

Task: Sequence Classification

  • Many-to-One: We only care about the final prediction at the end of the sentence.
  • Shared Weights: The same matrices calculate memory at every step.

RNNs and Text: A Guide to Sequential Memory

Discover how Recurrent Neural Networks (RNNs) use an internal memory loop to understand the order and context of words in a sentence.

The Unrolled RNN: Step-by-Step Processing

The visualization above "unrolls" the RNN loop, showing it as a sequence of identical cells, one for each word (or "time step"). Here’s how the information flows:

  1. Time Step 1 (First Word): The network takes the first word's embedding (a numerical vector, $X_1$) and an initial hidden state ($H_0$, usually all zeros). It processes them to produce an output ($Y_1$) and, most importantly, a new hidden state ($H_1$).
  2. Time Step 2 (Second Word): The network takes the second word's embedding ($X_2$) and the previous hidden state ($H_1$). This is the memory! $H_1$ contains information about the first word, giving the network context. It then produces a new output ($Y_2$) and an updated hidden state ($H_2$).
  3. And so on...: This process repeats for every word in the sequence. Each step receives the current word and the memory of all preceding words.

Shared Weights: The Key to Learning

A crucial concept in RNNs is shared weights. The same set of calculations (the same "brain") is used at every single time step. This is incredibly efficient. Instead of learning a new set of rules for the first word, second word, etc., the RNN learns a single set of rules for how to update its memory based on a new word and its previous memory. The "Parameters" calculation in the visualization shows the size of these shared weights.

One word at a time, carrying a state

A recurrent network processes a sequence step by step. At each step it combines the current input with what it remembers from before:

hᵗ = tanh(Wₕₕ hᵗ₋₁ + Wₓₕ xᵗ + b)

hₜ is the hidden state — a fixed-size vector summarising everything seen so far. xₜ is the current word's embedding. The same weight matrices are used at every step, which is parameter sharing along the time axis.

Walking through "the cat sat":

StepInputState contains
1"the"A determiner has appeared
2"cat"A noun phrase, subject-like
3"sat"A subject and its verb

Each state is a function of the current word and the previous state, so information propagates forward by being repeatedly transformed.

That single design choice — one weight matrix reused at every step — is what lets an RNN handle sequences of any length with a fixed number of parameters.

The architectures it supports

ShapeInput → outputExample
Many-to-oneSequence → one labelSentiment classification
Many-to-many, alignedSequence → sequence of the same lengthPart-of-speech tagging
Many-to-many, unalignedSequence → different-length sequenceTranslation (encoder-decoder)
One-to-manyOne input → sequenceImage captioning

For classification, use the final hidden state — or better, pool over all states, since the final one is biased towards the end of the sequence.

For an encoder-decoder, the encoder's final state is the "thought vector" passed to the decoder. That design is exactly where attention was invented: compressing a whole sentence into one fixed vector is a bottleneck, and letting the decoder look back at every encoder state instead removed it.

Two structural limitations

Vanishing gradients. Backpropagation through 50 steps multiplies 50 Jacobian factors. If they average below 1, the gradient reaching step 1 is effectively zero, so the network cannot learn that step 1 mattered. Tanh's derivative is at most 1 and usually well below it, so decay is the default.

No parallelism. Step t needs hₜ₋₁, so the steps must run in order. A GPU's thousands of cores sit mostly idle, and training time scales with sequence length. This is a hardware-utilisation problem, and it is the reason transformers displaced RNNs at scale rather than any single quality issue.

The first was addressed by gating (LSTM, GRU). The second was not addressable within the recurrent framework at all — which is why the field moved to attention.

The loop, and the four shapes it can take

An RNN reads one token at a time and updates one state. Where you take the output from decides whether you have a classifier, a tagger, a generator or a translator -- four architectures from the same loop.

example_01.pyNumPy
Output

Experiments to try

Use the simulation to see how an RNN performs sentiment analysis (classifying a sentence as positive or negative):

  1. Set the Architecture: The default is a "Many-to-One" RNN. This is perfect for sentiment analysis because we read many words but only need one final output (the overall sentiment).
  2. Enter a Sentence: Type a sentence like "AI is very cool" in the "Sentiment Text" box. The "Seq Length" will automatically update to the number of words.
  3. Simulate the Flow: Click the "Simulate Flow" button. Watch as the hidden state (the green arrow) is passed from one time step to the next. The network reads the sentence left-to-right, updating its memory at each word.
  4. Final Prediction: In this Many-to-One setup, only the final output from the very last time step is used. This output is passed to a classifier (represented by the "Output Size" of 2: one for positive, one for negative) to make the final sentiment prediction. The network has "read" the whole sentence and is now making a judgment.
  5. Check Parameters: Click the "Parameters" button. Now, change the "Hidden State" size from 8 to 16. Calculate again. Notice how the number of parameters increases significantly. A larger hidden state allows the network to store more complex information in its memory, but it also makes it more computationally expensive.

Where that leaves you

RNNs are designed for sequential data like text. Their core feature is the hidden state, a memory that is passed through time, allowing the network to remember previous inputs and understand context. By using shared weights, they can efficiently process sequences of any length, making them a cornerstone of modern Natural Language Processing.

Backpropagation through time

Training an RNN means unrolling it. A 50-word sentence becomes a 50-layer feed-forward network that happens to share weights, and ordinary backpropagation is applied to that unrolled graph.

The gradient for a shared weight is the sum of its gradients from every time step, since it was used at all of them.

Two practical consequences:

Memory grows with sequence length, because every step's activations must be stored for the backward pass. Long sequences exhaust memory quickly.

Truncated BPTT is the standard remedy: backpropagate only k steps back (typically 20–50) rather than to the beginning. It bounds memory and compute, at the cost of not learning dependencies longer than k.

Gradient clipping is essentially mandatory here. The same multiplication that vanishes gradients can explode them, and a single large gradient destroys the weights in one step.

Practical notes

import torch.nn as nn

rnn = nn.LSTM(300, 256, batch_first=True)      # prefer LSTM/GRU over nn.RNN
out, (h, c) = rnn(packed_input)

nn.RNN — the plain version — is almost never the right choice; use an LSTM or GRU, which cost little more and train far better.

Three details that matter with real text:

Pack variable-length sequences. pack_padded_sequence tells the RNN to stop at each sequence's real end. Without it, the final hidden state summarises the padding rather than the sentence.

Sort or bucket by length when batching, so batches contain similar lengths and less padding is wasted.

Consider bidirectionality for classification and tagging — running one RNN forward and another backward and concatenating gives each position both left and right context. Not available for generation or streaming.

Questions people ask

Are RNNs still used? Yes, in streaming inference with bounded memory, on-device models, small datasets and classical time-series work. Not for large-scale language modelling.

Why does the same weight matrix apply at every step? Parameter sharing along time — the same reason a convolution shares filters across space. It lets one model handle any length.

How long a sequence can an LSTM handle? Hundreds of steps in practice; thousands is unreliable. Transformers handle far longer, at quadratic cost.

What is the hidden state size? A hyperparameter, typically 128–512. Larger means more memory capacity and more parameters.

Can I stack RNN layers? Yes, and two is usually the practical limit — deeper stacks are hard to train.

Why did transformers replace them? Parallelism across the sequence and constant path length between positions. Both are structural advantages that gating cannot provide.

Recap in one screen

  • An RNN carries a fixed-size hidden state, updated at each step from the input and the previous state.
  • The same weights are reused at every step, so one model handles any sequence length.
  • Training unrolls the sequence and sums each weight's gradient across all steps.
  • Vanishing gradients limit range (fixed by gating); the sequential dependency prevents parallelism (not fixable).
  • Pack variable-length batches, clip gradients, and prefer LSTM or GRU over the plain cell.

Recall check

0 of 3

Say the answer out loud before you reveal it — recalling it is what makes it stick, and rereading it is not.

  1. What does this module say about “The Power of Memory in Language”?

  2. What does this module say about “The Unrolled RNN: Step-by-Step Processing”?

  3. What does this module say about “Shared Weights: The Key to Learning”?

Cheat sheet

How RNN Processes Text

Standard neural networks have a major limitation: they have no memory of the past. They process each input independently. This is a problem for language, where the order of words is crucial. For example, "dog bites man" and "man bites dog" use the same words but have completely different meanings.

NLP · vizlearn.in/natural_language_processing/how_rnn_process_text.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.