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:
Among them:
- : Input of the time step.
- : 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
| Type | input and output | Typical tasks |
|---|---|---|
| Many-to-One | sequence → single result | Sentiment classification, sequence classification |
| One-to-Many | single condition → sequence | Conditional sequence generation |
| Many-to-Many | sequence → sequence | Sequence annotation, translation |
| Sequence Forecasting | historical sequence → future value | time 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:
RNN is calculated in sequence:
Among them:
- : Current input.
- : The hidden state of the previous time step.
- : Currently hidden state.
- : 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:
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:
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:
- : Hidden State, used for current output and subsequent calculations.
- : 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.
| Gate | Main function |
|---|---|
| Forget Gate | Controls how much old Cell State is retained |
| Input Gate | Control how much new information is written |
| Output Gate | Control 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:
Input Gate:
Candidate Cell State:
Update Cell State:
Output Gate:
Final Hidden State:
where 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
| Gate | function |
|---|---|
| Update Gate | Control the ratio of keeping old states to adopting new candidate states |
| Reset Gate | Controlling the influence of historical states in candidate state calculations |
The core updates of GRU can be summarized as:
Among them:
- :Update Gate。
- : Candidate Hidden State.
- : 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
| Features | RNN | LSTM | GRU |
|---|---|---|---|
| main status | Hidden State | Hidden + Cell State | Hidden State |
| gating mechanism | None | Forget / Input / Output | Update / Reset |
| ability to rely on long-term | weaker | improve | improve |
| Parameter complexity | relatively low | higher | usually somewhere in between |
| Training calculation | relatively simple | more complex | more complex |
| Current location | Basic teaching, simple sequence model | specific sequence of tasks | specific 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:
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:
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.
| Contrast | RNN / LSTM / GRU | Transformer |
|---|---|---|
| core mechanism | Loop Hidden State | Self-Attention |
| time step calculation | Have sequential dependencies | Multiple positions can be calculated in parallel during training |
| Historical information access | through compressed state | Attention accessible context representation |
| long term dependence | There is a status bottleneck | Can create more direct relationships across locations |
| inference | Status can be updated gradually | Autoregressive 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
| Architecture | current value | Is it worth going deeper? |
|---|---|---|
| Vanilla RNN | Understanding loop status and BPTT | Just master the principles |
| LSTM | The classic gated memory mechanism is still used in some sequential tasks. | Understand the gating mechanism |
| GRU | Simple gated sequence model, which can be used as the actual Baseline | Master the basic usage of PyTorch |
| BiLSTM | Offline bidirectional sequence modeling | Understand the mechanism |
| RNN Encoder–Decoder | Understanding the evolution of early Seq2Seq and Attention | brief introduction |
| Transformer | The main architecture of modern general language models | Focus on in-depth |
| SSM / Mamba | Important research routes for modern efficient sequence modeling | Selective 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 points | importance |
|---|---|
| Sequence Modeling | core |
| Hidden State / Parameter Sharing | core |
| Recursive update of RNN | core |
| BPTT | core |
| Vanishing / Exploding Gradients | core |
| LSTM / Cell State | important |
| Forget / Input / Output Gates | important |
| GRU / Update / Reset Gates | important |
| Bidirectional RNN | Understand |
| Encoder–Decoder | Understand |
| Padding / Packed Sequences | Practice is important |
| Architectural differences of Transformer | core |
| Basic contact of SSM / Mamba | important |
The five most important concepts:
- Recurrent State: Pass information from previous time steps to subsequent calculations through hidden states.
- BPTT: Expand the loop structure along time and use the chain rule to calculate the gradient.
- Long-term Dependencies: Traditional RNN has difficulties in gradient propagation and long-term information preservation.
- Gating Mechanisms: LSTM, GRU control the retention and updating of state through learnable gates.
- Architectural Evolution: Transformer changed the way sequence information is interacted, while modern SSM further explores efficient state modeling.