Deep Learning · Sequence Models
Some data has an order that changes its meaning: temperatures rise over time, words form a sentence, and machine vibrations develop before a fault. This lesson builds a sequence model from the first hidden-state update, shows why ordinary RNN memory can fail, calculates an LSTM memory update, and compares GRUs and bidirectional models.
A Sequence Is More Than a Bag of Values
Suppose a factory motor reports 20°C, 24°C, 31°C and 38°C. The final value matters, but the rising pattern also warns us that the motor is heating quickly. If we shuffle the same readings to 38°C, 20°C, 31°C and 24°C, their average is unchanged while the story is completely different.
A sequence model learns from both values and order. At time step t, it receives the current input xt and a compact summary of earlier inputs called the hidden state ht−1. It combines them to produce a new state ht. The state is learned—not a hand-written average—and its useful features emerge during training.
An RNN reads a sequence one step at a time
Each hidden state carries a learned summary of what has been read so far.
t = 1
x1 = 20°C
↓
h₁
first reading
memory moves forward
→
t = 2
x2 = 24°C
↓
h₂
uses h₁
memory moves forward
→
t = 3
x3 = 31°C
↓
h₃
uses h₂
memory moves forward
→
t = 4
x4 = 38°C
↓
h₄
alarm score
“Sequence model” describes several input–output shapes
Many → one
words → sentiment
Many → many (aligned)
readings → labels
One → many
image code → caption
Many → many (shifted)
past → future
The Basic RNN Reuses One Update Rule
A recurrent cell uses the same parameters at every time step. Wxh controls how the current input affects memory; Whh controls how previous memory affects new memory; b is a bias. The tanh activation compresses each state component between −1 and 1.
Basic recurrent update
ht = tanh(Wxhxt + Whhht−1 + b)
ŷt = Whyht + by
xt is the current input, ht−1 is the previous hidden state, ht is the updated state, and ŷt is an optional prediction. In a real network these are usually vectors and the W terms are matrices. Multiplication lets each learned weight strengthen, weaken or reverse a feature; addition combines current and remembered evidence; tanh keeps the resulting state in a bounded range.
Two scalar updates, calculated by hand
Use Wxh=0.5, Whh=0.8, b=0 and initial state h₀=0. Let the normalized inputs be x₁=1 and x₂=0.5. These five values are deliberately chosen teaching numbers. In a real run, x comes from the data, the zero initial state is created by the framework unless you provide another state, and training learns W and b.
Time 1
h₁ = tanh(0.5×1 + 0.8×0)
= tanh(0.5)
≈ 0.462
No earlier reading exists, so h₀ contributes zero.
Time 2
h₂ = tanh(0.5×0.5 + 0.8×0.462)
= tanh(0.620)
≈ 0.551
The same two weights are reused; only the input and state changed.
Interpretation: h₂ depends on x₂ and on the summary created from x₁. Without the recurrent 0.8×h₁ term, the second state would ignore the first reading.
Training Unrolls the Network Backward Through Time
During the forward pass, states move from early to late time steps. After a loss is calculated, backpropagation through time (BPTT) treats the unrolled sequence like a deep network with shared weights and sends gradient information from later states toward earlier ones.
Each trip backward multiplies by another local derivative. Many factors below 1 can create a vanishing gradient, so early events receive almost no learning signal. Repeated large factors can create an exploding gradient, producing unstable updates or NaN values.
Repeated small derivatives can make an early learning signal disappear
What gradient clipping does
If the total gradient norm is too large, clipping scales it down before the optimizer step. This protects against explosions; it does not restore information already lost to vanishing gradients.
What truncated BPTT does
For very long streams, detach the hidden state after a chosen window. This limits memory and compute, but prevents gradients from directly crossing the truncation boundary.
An LSTM Adds a Controlled Memory Path
A Long Short-Term Memory network is still recurrent, but its cell keeps two states. The cell state c carries controlled long-term memory. The hidden state h is the visible working representation passed to prediction layers and the next cell. Learned gates use sigmoid values between 0 and 1 to regulate information—not probabilities of an event, but soft control values.
Inside one LSTM step: erase, write, then reveal
The gates are learned numbers between 0 and 1 for every memory feature.
One standard LSTM formulation
ft = σ(Wf[ht−1, xt] + bf) forget control
it = σ(Wi[ht−1, xt] + bi) input control
gt = tanh(Wg[ht−1, xt] + bg) candidate
ct = ft ⊙ ct−1 + it ⊙ gt updated memory
ot = σ(Wo[ht−1, xt] + bo) output control
ht = ot ⊙ tanh(ct) visible state
[ht−1,xt] means concatenate the two vectors so every gate can inspect past and present together. Matrix multiplication forms learned mixtures, σ turns each mixture into a 0–1 control, ⊙ applies that control feature by feature, and addition combines retained old memory with accepted new memory.
One memory component, updated numerically
Suppose old memory ct−1=0.40. For this step the learned gates produce ft=0.80, it=0.30, candidate gt=0.50 and output gate ot=0.90. These are manually selected teaching outputs, not recommended settings. In a trained LSTM, the current input and previous hidden state pass through learned W and b values to calculate a different gate vector at every step.
Retained old memory
0.80 × 0.40
= 0.32
Accepted new memory
0.30 × 0.50
= 0.15
New cell state
ct = 0.32 + 0.15
= 0.47
ht = 0.90 × tanh(0.47) ≈ 0.90 × 0.438 = 0.394
Interpretation: most of the old feature was preserved, some candidate information was written, and 90% of the squashed memory became visible. During training the network learns the weights that produce these gate values.
A GRU Combines the Memory Controls
A Gated Recurrent Unit has a hidden state but no separate cell state. Its reset gate controls how much previous state influences the candidate. Its update gate blends old state with the new candidate. Fewer gate projections usually mean fewer parameters than a comparable LSTM.
The update gate performs a learned blend
ht = (1 − zt) ⊙ nt + zt ⊙ ht−1
In this convention, z near 1 preserves more old state and z near 0 selects more candidate state n. Some texts swap the two coefficients, so always read the implementation's equations.
z=0.75, old h=0.60, candidate n=0.20
ht=(0.25×0.20)+(0.75×0.60)=0.05+0.45=0.50
Do not choose LSTM because it is “always more powerful,” or GRU because it is “always faster.” Hidden size, implementation, hardware and task matter. Treat both as baselines and validate them on the same split and budget.
Bidirectional Models Use Past and Future Context
A bidirectional RNN runs one recurrent layer from left to right and another from right to left, then combines their representations. This is useful when the entire sequence is already available—for example, labelling every word in a stored document. The word “bank” can then use words on both sides.
Do not use future information when it would be unavailable
A live forecasting system at 10:00 cannot use readings from 10:05. A bidirectional encoder on such training windows leaks the future and creates unrealistic evaluation. Use a causal, forward-only model for real-time prediction.
Which Sequence Model Should You Try?
| Model | How it carries context | Reasonable starting situation | Important limitation |
|---|---|---|---|
| Simple RNN | One hidden state; fewest gates/parameters | Short dependencies, small teaching baselines | Long-memory training can be difficult |
| GRU | Reset and update gates; no separate cell state | A strong recurrent baseline when compute/data are limited | Less explicit memory control than LSTM |
| LSTM | Forget, input and output gates plus cell state | Forecasting, speech or text when gated recurrence is appropriate | More parameters and sequential computation |
| Transformer | Attention connects token pairs directly | Parallel training and rich global context | Standard attention cost grows quadratically with length |
For a small time-series or sequence-classification project, a one-layer GRU or LSTM is still an understandable, useful baseline. For large language modelling or parallel training, compare Transformer approaches. For extremely long streams, evaluate efficient attention or a supported SSM implementation—but measure quality, latency, memory and ecosystem maturity on your actual task.
A Small GRU Classifier in PyTorch
The model below receives a batch shaped [batch, time, features]. The GRU returns an output for every padded time position and a final hidden state. Packing tells the GRU which positions are real, so a short sequence does not treat padding as data.
import torch
from torch import nn
from torch.nn.utils.rnn import pack_padded_sequence
class SequenceClassifier(nn.Module):
def __init__(self, input_features, hidden_size, classes):
super().__init__()
self.gru = nn.GRU(
input_size=input_features,
hidden_size=hidden_size,
batch_first=True,
)
self.classifier = nn.Linear(hidden_size, classes)
def forward(self, padded_sequences, lengths):
packed = pack_padded_sequence(
padded_sequences,
lengths.cpu(),
batch_first=True,
enforce_sorted=False,
)
_, final_hidden = self.gru(packed)
last_layer_state = final_hidden[-1] # [batch, hidden]
return self.classifier(last_layer_state)
model = SequenceClassifier(input_features=6, hidden_size=32, classes=3)
logits = model(batch, lengths) # raw class scores [batch, 3]
loss = nn.CrossEntropyLoss()(logits, labels)Where the dimensions come from
input_features=6 must match the six measured or embedded features at each time step. hidden_size=32 is a developer-chosen capacity. classes=3 comes from the three target labels. With 10 examples and 20 time steps, the input shape is [10,20,6] and the logits shape is [10,3].
What the framework does
PyTorch initializes the GRU and linear weights, creates an all-zero initial hidden state when none is supplied, skips packed padding positions, and returns final states. CrossEntropyLoss internally applies log-softmax and selects the loss for each integer class label; pass raw logits, not pre-softmax probabilities.
For a bidirectional GRU, final_hidden contains a separate state for each direction; do not blindly take only [-1]. Reshape by layers and directions, then concatenate the last forward and backward states.
Diagnosing Recurrent Models
| What you observe | Likely problem | Check or correction |
|---|---|---|
| Model reacts to padding length | Padding is entering pooling or final-state logic | Pack sequences or mask padded positions; test the same sample with extra padding |
| Loss becomes NaN; gradient norm jumps | Exploding gradients or unstable inputs/rate | Inspect inputs, lower the rate and clip gradient norm before optimizer.step() |
| Long-range clue has no effect | Vanishing gradients, short training window or inadequate state | Compare LSTM/GRU, longer context and a Transformer/SSM baseline |
| Validation is suspiciously excellent | Future leakage from bidirectionality or random temporal split | Use causal features and a chronological split for forecasting |
| Only one batch size works | Hidden state was created with a fixed batch dimension | Initialize from the current batch or let the framework create zero state |
| GPU memory grows every stream step | State retains the entire autograd graph | Detach state at intentional truncated-BPTT boundaries |
| Shapes look transposed | batch_first setting disagrees with data | Log [batch,time,features] or [time,batch,features] before the recurrent layer |
What to Remember
- An RNN reuses one cell and carries a learned hidden state through ordered inputs.
- BPTT sends gradients through the unrolled time steps; repeated derivatives can vanish or explode.
- An LSTM regulates a separate cell memory with forget, input and output gates.
- A GRU uses a simpler gated update with one hidden state; neither GRU nor LSTM wins every task.
- Bidirectional context is useful only when future positions are available at prediction time.
- Correct masking, causal evaluation, tensor shapes and gradient monitoring matter as much as the cell choice.