Sequence models: RNN, LSTM, and GRU

Sequence Models (sequence model) is used to process data with sequential relationships, such as text, speech, time series, sensor data, and event sequences.

The important difference between sequence data and ordinary table data is that the information at the current moment may depend on multiple moments before or even after it, and the order of the samples has practical significance.

RNN (Recurrent Neural Network) is a classic neural network sequence modeling architecture. LSTM and GRU improve the problem that traditional RNN is difficult to capture long-term dependencies through the gating mechanism.

Although Transformer has replaced the traditional RNN/LSTM as the mainstream architecture for general language modeling, understanding loop states, gating mechanisms and sequence dependencies is still valuable and is the basis for understanding architectures such as modern State Space Models (SSM).

This article focuses on the core mechanisms of RNN, LSTM and GRU, the usage of PyTorch and its modern technical positioning, without going into complex historical model variants.

1. Sequence Modeling: Sequence Modeling

Sequence data is usually expressed as:

X=(x1,x2,…,xT)X=(x_1,x_2,\ldots,x_T)

Among them:

  • xtx_t: Input of the tt time step.
  • TT: sequence length.
  • The input can be Token Embedding, sensor features, or other vectors.

For example, stock price prediction:

Day 1 → Day 2 → Day 3 → Day 4 → Prediction

Language modeling:

"The" → "cat" → "is" → Next Token

Sequence modeling requires consideration of temporal order and dependencies between different moments.

Common task types

Typeinput and outputTypical tasks
Many-to-Onesequence → single resultSentiment classification, sequence classification
One-to-Manysingle condition → sequenceConditional sequence generation
Many-to-Manysequence → sequenceSequence annotation, translation
Sequence Forecastinghistorical sequence → future valuetime series forecasting

These task forms are not specific to RNN, but also apply to Transformer and other sequence architectures.

2. RNN:Recurrent Neural Network

The core idea of traditional RNN is: uses Hidden State (hidden state) to save the information of the previous sequence and update this state when processing the next time step.

For sequences:

x1,x2,…,xTx_1,x_2,\ldots,x_T

RNN is calculated in sequence:

ht=tanh⁡(Wxxt+Whht−1+b)h_t=\tanh(W_xx_t+W_hh_{t-1}+b)

Among them:

  • xtx_t: Current input.
  • ht−1h_{t-1}: The hidden state of the previous time step.
  • hth_t: Currently hidden state.
  • Wx,Wh,bW_x,W_h,b: Learnable parameters.

Hidden State

Hidden State can be understood as the compressed representation of historical information by the model.

For example, when processing a sentence, the current state is determined by both the current Token and the previous state.

It should be noted that Hidden State does not guarantee that all historical information will be saved. Its representation ability is limited by the state dimension, model parameters and training process.

Parameter Sharing

Use the same set of parameters at different time steps:

Wx, Wh, bW_x,\ W_h,\ b

This parameter sharing mechanism enables the model to handle sequences of different lengths without the need to train an independent set of weights for each time step.

PyTorch implementation

import torch
import torch.nn as nn

rnn = nn.RNN(
    input_size=16,
    hidden_size=32,
    num_layers=1,
    batch_first=True,
)

x = torch.randn(8, 20, 16)

output, h_n = rnn(x)

print(output.shape)  # [8, 20, 32]
print(h_n.shape)     # [1, 8, 32]

Enter shape:

[Batch, Sequence Length, Input Features]

Output:

  • output: Hidden State of the last layer at each time step.
  • h_n: Hidden State of the last time step of each layer.

Here batch_first=True only changes the dimension order of the input and output, but does not change the dimension convention of h_n.

3. BPTT:Backpropagation Through Time

The training of RNN still relies on Backpropagation.

Since the current Hidden State depends on the state of the previous time step, gradient propagation is required along the time direction.

This mechanism is called Backpropagation Through Time (BPTT).

core idea

Expand the loop structure in the time dimension:

x1 → RNN → h1
            ↓
x2 → RNN → h2
            ↓
x3 → RNN → h3
            ↓
           Loss

After calculating Loss, the gradient is propagated from back to front along the calculation graph.

For example:

∂L∂h1=∂L∂h3∂h3∂h2∂h2∂h1\frac{\partial L}{\partial h_1} = \frac{\partial L}{\partial h_3} \frac{\partial h_3}{\partial h_2} \frac{\partial h_2}{\partial h_1}

In long sequences, two problems can arise with this continuous gradient pass.

Vanishing Gradients

As the product of multiple Jacobian shrinks, the gradients received at earlier time steps can be very small.

The result is that the model has difficulty learning long-term dependencies.

Exploding Gradients

If the gradient continues to amplify over multiple time steps, it may lead to unstable training.

Common relief methods:

  • Gradient Clipping。
  • Proper initialization.
  • Gated loop structure.
  • Truncated BPTT。

Truncated BPTT

Truncated Backpropagation Through Time limits the length of gradient backpropagation along the time dimension.

For example, split a long sequence into multiple shorter fragments, passing Hidden State between fragments but truncating the gradient path across fragments.

This allows control over computational graph length and training memory, but also limits direct gradient propagation across segments.

4. LSTM:Long Short-Term Memory

LSTM is an important improvement over the traditional RNN, with the core goal of learning dependencies over longer time spans more efficiently.

Unlike normal RNN which only has Hidden State, LSTM also introduces Cell State (cell state).

LSTM has two main states:

  • hth_t: Hidden State, used for current output and subsequent calculations.
  • ctc_t: Cell State, used to transmit and maintain longer-term information.

Three doors of LSTM

LSTM uses a gating mechanism to control the retention, writing, and output of information.

GateMain function
Forget GateControls how much old Cell State is retained
Input GateControl how much new information is written
Output GateControl how much information in Cell State participates in Hidden State output

These Gate usually use Sigmoid to get continuous gate values from 0 to 1 instead of simple binary switches.

core computing

Forget Gate:

ft=σ(Wf[xt,ht−1]+bf)f_t=\sigma(W_f[x_t,h_{t-1}]+b_f)

Input Gate:

it=σ(Wi[xt,ht−1]+bi)i_t=\sigma(W_i[x_t,h_{t-1}]+b_i)

Candidate Cell State:

c~t=tanh⁡(Wc[xt,ht−1]+bc)\tilde c_t=\tanh(W_c[x_t,h_{t-1}]+b_c)

Update Cell State:

ct=ft⊙ct−1+it⊙c~tc_t=f_t\odot c_{t-1}+i_t\odot\tilde c_t

Output Gate:

ot=σ(Wo[xt,ht−1]+bo)o_t=\sigma(W_o[x_t,h_{t-1}]+b_o)

Final Hidden State:

ht=ot⊙tanh⁡(ct)h_t=o_t\odot\tanh(c_t)

where ⊙\odot represents element-wise multiplication.

The most important thing to understand about is the Cell State update formula.

Old status is retained via Forget Gate, and new information is added via Input Gate. This provides a more favorable path for long-term information and gradient propagation than simple RNN.

But LSTM is still not guaranteed to capture arbitrarily long dependencies.

PyTorch implementation

lstm = nn.LSTM(
    input_size=16,
    hidden_size=32,
    num_layers=2,
    batch_first=True,
)

x = torch.randn(8, 20, 16)

output, (h_n, c_n) = lstm(x)

print(output.shape)  # [8, 20, 32]
print(h_n.shape)     # [2, 8, 32]
print(c_n.shape)     # [2, 8, 32]

The most obvious difference from RNN is that LSTM returns two sets of status: Hidden State and Cell State.

5. GRU:Gated Recurrent Unit

GRU is another gated recurrent neural network.

It has a similar goal to LSTM, but the structure is generally simpler:

  • Cell State is not maintained separately.
  • Use less Gate.
  • Usually there are fewer parameters than the standard LSTM for the same Hidden Size.

The two main gates of GRU

Gatefunction
Update GateControl the ratio of keeping old states to adopting new candidate states
Reset GateControlling the influence of historical states in candidate state calculations

The core updates of GRU can be summarized as:

ht=(1−zt)⊙h~t+zt⊙ht−1h_t=(1-z_t)\odot\tilde h_t+z_t\odot h_{t-1}

Among them:

  • ztz_t:Update Gate。
  • h~t\tilde h_t: Candidate Hidden State.
  • ht−1h_{t-1}: formerly Hidden State.

The gating convention of PyTorch is used here.

It can be intuitively understood as: GRU performs a learnable weighted mixture between old states and new candidate information.

PyTorch implementation

gru = nn.GRU(
    input_size=16,
    hidden_size=32,
    num_layers=2,
    batch_first=True,
)

x = torch.randn(8, 20, 16)

output, h_n = gru(x)

print(output.shape)  # [8, 20, 32]
print(h_n.shape)     # [2, 8, 32]

GRU and LSTM

GRU is generally more compact in structure and may have lower parameters and computational cost for some tasks.

However:

  • GRU is not necessarily faster than LSTM.
  • LSTM is not necessarily more accurate than GRU.
  • The final effect depends on data size, sequence length, model configuration and training conditions.

In actual use, both can be used as candidate models for verification, rather than presupposing that one of them must be better.

6. Comparison of RNN, LSTM and GRU

FeaturesRNNLSTMGRU
main statusHidden StateHidden + Cell StateHidden State
gating mechanismNoneForget / Input / OutputUpdate / Reset
ability to rely on long-termweakerimproveimprove
Parameter complexityrelatively lowhigherusually somewhere in between
Training calculationrelatively simplemore complexmore complex
Current locationBasic teaching, simple sequence modelspecific sequence of tasksspecific sequence of tasks

From a learning perspective, just understand the loop state of RNN and the gating idea of LSTM/GRU. There is no need to delve further into the large number of historical cycle unit variants.

7. Bidirectional RNN: Bidirectional recurrent network

Ordinary RNN is processed in chronological order:

x1 → x2 → x3 → x4

Bidirectional RNN (bidirectional recurrent network) uses both forward and reverse sequence representations:

Forward:   x1 → x2 → x3 → x4
Backward:  x1 ← x2 ← x3 ← x4

Finally combine Hidden State in both directions.

PyTorch implementation

lstm = nn.LSTM(
    input_size=16,
    hidden_size=32,
    batch_first=True,
    bidirectional=True,
)

x = torch.randn(8, 20, 16)

output, (h_n, c_n) = lstm(x)

print(output.shape)  # [8, 20, 64]
print(h_n.shape)     # [2, 8, 32]

Because there are two directions, the output feature dimension is:

2×HiddenSize2\times HiddenSize

Usage scenarios

Bidirectional RNN is suitable for tasks where complete sequences can be accessed simultaneously, such as offline sequence classification and sequence annotation.

But for strict real-time causal prediction, unobserved future data cannot be directly exploited.

8. Sequence-to-One and Sequence-to-Sequence

Sequence-to-One

For example: predict a category based on data from the past period.

[x1, x2, x3, x4] → RNN/GRU → Class

You can use the final Hidden State as a representation of the entire sequence.

PyTorch classification model

import torch
import torch.nn as nn

class GRUClassifier(nn.Module):
    def __init__(
        self,
        input_size: int,
        hidden_size: int,
        num_classes: int,
    ):
        super().__init__()

        self.gru = nn.GRU(
            input_size=input_size,
            hidden_size=hidden_size,
            batch_first=True,
        )

        self.classifier = nn.Linear(
            hidden_size,
            num_classes,
        )

    def forward(self, x):
        output, h_n = self.gru(x)

        final_hidden = h_n[-1]

        return self.classifier(final_hidden)

Test:

model = GRUClassifier(
    input_size=10,
    hidden_size=32,
    num_classes=3,
)

x = torch.randn(16, 50, 10)

logits = model(x)

print(logits.shape)  # [16, 3]

It is assumed here that the input sequence does not have Padding that requires special processing, and one-way GRU is used.

If there are sequences of different lengths, directly selecting the last time step may incorrectly include the effect of Padding on the state.

Sequence-to-Sequence

Traditional Encoder–Decoder uses a recurrent network to encode the input sequence and another recurrent network to generate the output sequence.

Input Sequence
      ↓
RNN Encoder
      ↓
Context / Hidden State
      ↓
RNN Decoder
      ↓
Output Sequence

This is an important architecture for early neural machine translation.

But when the input sequence is long, compressing all the information into Context Vector of limited dimensions may become a bottleneck.

Attention Mechanism was later introduced, enabling Decoder to access different time-step representations of Encoder based on current needs.

This idea is an important bridge for understanding the subsequent Transformer.

9. Variable-length Sequences and Padding

Actual sequence data often vary in length.

For example:

Sequence A: [1, 2, 3]
Sequence B: [1, 2, 3, 4, 5]

To form Batch, Padding is usually required:

Sequence A: [1, 2, 3, 0, 0]
Sequence B: [1, 2, 3, 4, 5]

But ordinary RNN will not automatically know which positions are Padding.

PyTorch provides Packed Sequences, allowing recurrent networks to handle variable-length inputs more efficiently.

pack_padded_sequence

from torch.nn.utils.rnn import (
    pack_padded_sequence,
    pad_packed_sequence,
)

x = torch.randn(2, 5, 10)

lengths = torch.tensor([3, 5])

packed = pack_padded_sequence(
    x,
    lengths,
    batch_first=True,
    enforce_sorted=False,
)

gru = nn.GRU(
    input_size=10,
    hidden_size=16,
    batch_first=True,
)

packed_output, h_n = gru(packed)

output, output_lengths = pad_packed_sequence(
    packed_output,
    batch_first=True,
)

For actual variable-length sequence tasks, it needs to be handled correctly:

  • Padding。
  • Sequence Length。
  • Hidden State。
  • Loss Masking。

These are common problems in practical development of sequence models.

10. Why does Transformer gradually replace the traditional RNN?

The main limitations of traditional RNN/LSTM/GRU include:

Sequential Computation

The current state of RNN depends on the previous moment:

ht=f(xt,ht−1)h_t=f(x_t,h_{t-1})

Therefore, there are sequential dependencies between time steps, limiting parallel computation in the sequence dimension.

Long-range Dependencies

Although LSTM and GRU alleviate the long-term dependency problem, information compression and optimization difficulties may still be faced in very long sequences.

Fixed-size State

Standard recurrent networks compress historical information into a limited-dimensional state, potentially losing important information.

Improvements to Transformer

Transformer mainly establishes information interaction between sequence positions through Self-Attention.

ContrastRNN / LSTM / GRUTransformer
core mechanismLoop Hidden StateSelf-Attention
time step calculationHave sequential dependenciesMultiple positions can be calculated in parallel during training
Historical information accessthrough compressed stateAttention accessible context representation
long term dependenceThere is a status bottleneckCan create more direct relationships across locations
inferenceStatus can be updated graduallyAutoregressive models usually use KV Cache

Note that Transformer still involves sequential computation. Autoregressive text generation generally proceeds one Token at a time; what differs is how training and contextual information are processed.

In addition, the attention matrix calculation and storage costs of the standard global Self-Attention may grow quadratically with the sequence length, which is one of the reasons why modern efficient sequence architectures continue to develop.

11. Relationship with Hyundai State Space Models

In recent years, architectures such as State Space Models (SSM) and Mamba have re-emphasized the value of state update mechanisms in long sequence modeling.

Their common ideas with traditional RNN are:

handles the sequence using a state representation and update mechanism without necessarily explicitly saving all history between Token and Attention Matrix.

But the modern SSM is not simply a name change for LSTM.

Differences may include:

  • Sequence modeling based on state space formalism.
  • Different state transition and input selection mechanisms.
  • A parallel scan or other computational implementation more suitable for hardware.
  • Different trade-offs between long sequence computation and memory efficiency.

Therefore, the core ideas of RNN have not lost value, but continue to appear in modern sequential architectures in new mathematical forms and engineering implementations.

The specific principles of SSM and Mamba are suitable for discussion in the Modern Neural Architectures article.

12. Positioning in modern applications

Architecturecurrent valueIs it worth going deeper?
Vanilla RNNUnderstanding loop status and BPTTJust master the principles
LSTMThe classic gated memory mechanism is still used in some sequential tasks.Understand the gating mechanism
GRUSimple gated sequence model, which can be used as the actual BaselineMaster the basic usage of PyTorch
BiLSTMOffline bidirectional sequence modelingUnderstand the mechanism
RNN Encoder–DecoderUnderstanding the evolution of early Seq2Seq and Attentionbrief introduction
TransformerThe main architecture of modern general language modelsFocus on in-depth
SSM / MambaImportant research routes for modern efficient sequence modelingSelective depth

For actual development:

  • General NLP / LLM: Transformer or existing pre-trained models are usually preferred.
  • Small and medium-sized time series: GRU/LSTM can be considered as a candidate Baseline, but statistical models, tree models and other deep learning methods should also be compared.
  • Real-time streaming sequence: Looping state updates has its engineering advantages, but needs to be combined with specific throughput, latency and accuracy requirements.
  • Long Sequence Modeling Study: Further attention can be given to modern SSM, Linear Attention and hybrid architectures.

Summary

Knowledge pointsimportance
Sequence Modelingcore
Hidden State / Parameter Sharingcore
Recursive update of RNNcore
BPTTcore
Vanishing / Exploding Gradientscore
LSTM / Cell Stateimportant
Forget / Input / Output Gatesimportant
GRU / Update / Reset Gatesimportant
Bidirectional RNNUnderstand
Encoder–DecoderUnderstand
Padding / Packed SequencesPractice is important
Architectural differences of Transformercore
Basic contact of SSM / Mambaimportant

The five most important concepts:

  1. Recurrent State: Pass information from previous time steps to subsequent calculations through hidden states.
  2. BPTT: Expand the loop structure along time and use the chain rule to calculate the gradient.
  3. Long-term Dependencies: Traditional RNN has difficulties in gradient propagation and long-term information preservation.
  4. Gating Mechanisms: LSTM, GRU control the retention and updating of state through learnable gates.
  5. Architectural Evolution: Transformer changed the way sequence information is interacted, while modern SSM further explores efficient state modeling.

Reference documentation

Back to top