LSTM from Scratch: The Forget Bias Sets the Memory

Build an LSTM from scratch, check the NumPy cell against PyTorch and measure how forget bias changes recall across 100 sequence steps.

Cover Image for LSTM from Scratch: The Forget Bias Sets the Memory

Imagine a sensor sending a steady stream of readings. A brief event near the start is the clue you need, but you only classify the sequence at the end. By then, many ordinary readings have passed. A recurrent model has to keep that early clue available as it processes each new reading. LSTMs were designed to help with this kind of memory problem, and building one lets us inspect how information is kept or lost along the way.

We test retention by recalling a symbol shown only at the first step. At 100 steps, forget bias 1 leaves the LSTM near chance. Bias 3 reaches 100% test accuracy across all three seeds. The vanilla RNN solves it in one seed too. We build both NumPy cells, check the LSTM against PyTorch and work through backpropagation to connect initial retention to learned memory.

Quick Win

Open In Colab

An LSTM stores a hidden state hth_t and a cell state ctc_t. The hidden state supplies the output-facing representation. The cell state has an additive update controlled by gates. Each gate is a vector of values, so different cell dimensions can retain or change different information.

The animation uses activations from a trained bias-three LSTM on one held-out sequence. It plots means across 32 cell dimensions. Those means summarise the trace; individual dimensions can behave differently or cancel when averaged.

Mean gates and cell state over one actual sequence from the trained LSTM.

import numpy as np
from scipy.special import expit

def lstm_cell(x, h, c, W, U, b):
    zi, zf, zg, zo = np.split(W @ x + U @ h + b, 4)
    i, f = expit(zi), expit(zf)
    g, o = np.tanh(zg), expit(zo)
    c = f * c + i * g
    h = o * np.tanh(c)
    return h, c

rng = np.random.default_rng(111)
input_size, hidden_size = 2, 3
W = rng.normal(scale=0.2, size=(4 * hidden_size, input_size))
U = rng.normal(scale=0.2, size=(4 * hidden_size, hidden_size))
b = np.zeros(4 * hidden_size)
b[hidden_size:2 * hidden_size] = 3
h = np.zeros(hidden_size)
c = np.zeros(hidden_size)
for x in rng.normal(size=(7, input_size)):
    h, c = lstm_cell(x, h, c, W, U, b)
print(h, c)

This cell runs independently of a deep-learning framework. The notebook copies PyTorch weights into the same NumPy layout and compares the full sequence of hidden outputs. The largest absolute difference is below 10⁻¹² in double precision. That comparison checks gate order, the state update and the two bias vectors used by PyTorch.

The example's random states establish implementation mechanics. The recall results later come from trained PyTorch models with 32 hidden dimensions.

Recurrent State

A vanilla RNN applies the same update at every step:

ht=tanh⁡(Wxt+Uht−1+b).h_t=\tanh(Wx_t+Uh_{t-1}+b).

The shared matrix UU carries the previous hidden state into the next one. Parameter sharing permits the network to process different sequence lengths, but it also makes the same transformation recur through time. The output at the final step depends on the complete chain of preceding states.

Our NumPy forward pass saves each hidden state because the backward pass will need it. The initial hidden vector is zero, and the loss is a squared difference between the final hidden state and a target vector. This small diagnostic isolates recurrent backpropagation from the binary classifier used in the larger experiment.

Backpropagation through time applies the chain rule to the unrolled recurrence. At each step, the tanh derivative scales the incoming hidden-state gradient, the outer products contribute to WW and UU, and multiplication by U⊤U^\top carries the gradient back to the preceding hidden state.

dh = history[-1] - target
for t in range(len(x) - 1, -1, -1):
    dz = dh * (1 - history[t + 1]**2)
    dW += np.outer(dz, x[t])
    dU += np.outer(dz, history[t])
    db += dz
    dh = U.T @ dz

The notebook compares these gradients with centred finite differences for every parameter in a small cell. Checking a short sequence is sufficient to catch reversed time indexing and many missing terms. It remains useful to inspect long-sequence gradient norms, since correct derivatives can still be too small or too large to train effectively.

The backpropagation tutorial develops the local chain rule. The Jacobians tutorial explains the matrix products that arise when the same dependency is followed through many transformations.

Gradient Products

The RNN hidden-state Jacobian is:

∂ht∂ht−1=diag⁡(1−ht2)U.\frac{\partial h_t}{\partial h_{t-1}} =\operatorname{diag}(1-h_t^2)U.

A gradient travelling back through many steps encounters a product of these Jacobians. Small singular values can make it decay rapidly; large ones can make it grow. Saturated tanh units add another shrinking factor because their derivatives approach zero.

This description concerns local derivatives along the realised sequence. A statement based only on the eigenvalues of UU leaves out the input-dependent tanh factors and the geometry of the gradient direction. The actual product is the relevant object.

Gradient clipping limits the magnitude of an update when the total parameter gradient becomes large. It does not restore a gradient that has already vanished. The training experiment clips the parameter gradient norm to one for both architectures, so the comparison gives both the same protection against large updates.

Input gradient norms against time lag for trained seed-zero models at 100 steps.

This figure differentiates the final classifier logit with respect to each input step. It is an end-to-end gradient through the trained network, measured on one held-out example. It differs from the isolated direct cell-state derivative derived below. The plotting floor hides differences between gradients below 10⁻³⁰.

A trained model can also solve this simple task with an attractor-like state that preserves a sign even when some local gradients are small. That is one reason a successful RNN seed does not contradict the difficulty of learning long dependencies with recurrent Jacobian products.

LSTM Gates

The modern LSTM cell computes four vectors from the current input and previous hidden state:

it=σ(Wixt+Uiht−1+bi),ft=σ(Wfxt+Ufht−1+bf),i_t=\sigma(W_i x_t+U_i h_{t-1}+b_i),\quad f_t=\sigma(W_f x_t+U_f h_{t-1}+b_f),
gt=tanh⁡(Wgxt+Ught−1+bg),ot=σ(Woxt+Uoht−1+bo).g_t=\tanh(W_g x_t+U_g h_{t-1}+b_g),\quad o_t=\sigma(W_o x_t+U_o h_{t-1}+b_o).

The input gate iti_t scales new candidate content. The forget gate ftf_t scales the previous cell state. The candidate gtg_t can add positive or negative content. The output gate oto_t controls how much of the transformed cell state reaches the hidden output.

The previous cell passes through a forget multiplier and receives an additive gated candidate.

The state equations are:

ct=ft⊙ct−1+it⊙gt,ht=ot⊙tanh⁡(ct).c_t=f_t\odot c_{t-1}+i_t\odot g_t, \qquad h_t=o_t\odot\tanh(c_t).

The symbol ⊙\odot means elementwise multiplication. The cell state adds a new contribution without multiplying its carried value by a dense recurrent weight matrix. Holding the gates fixed, the direct derivative along this path is ∂ct/∂ct−1=ft\partial c_t/\partial c_{t-1}=f_t, element by element.

The full recurrent derivative also includes dependencies through ht−1h_{t-1} and the gates. The direct-path expression describes one useful route for gradients within that complete Jacobian. Learning a long dependency still depends on the realised gates and training regime.

PyTorch stacks the gate parameters in input, forget, candidate and output order. Its recurrent layer has both an input bias and a hidden bias, whose sum enters each preactivation. Setting both forget slices to three would initialise a total forget bias of six. Our experiment sets the input forget slice to the desired value and the hidden forget slice to zero.

with torch.no_grad():
    lstm.bias_ih_l0[hidden_size:2*hidden_size].fill_(forget_bias)
    lstm.bias_hh_l0[hidden_size:2*hidden_size].zero_()

PyTorch's LSTM documentation specifies the gate equations and parameter layout. Copying that layout into NumPy makes the framework comparison an implementation check with matched weights, rather than a comparison between unrelated random cells.

Initial Retention

For zero input and hidden state, a forget bias of zero gives a gate value of 0.5. A bias of one gives about 0.731, and a bias of three gives about 0.953. A positive bias initially makes carrying a cell value more likely.

If that gate stayed fixed, the direct retained fraction after TT steps would be σ(bf)T\sigma(b_f)^T. At 100 steps, a bias of one retains about 2.5 × 10⁻¹⁴, while a bias of three retains about 0.0078. These illustrative direct-path calculations hold the gates fixed, while learned gate values can vary throughout a real sequence.

The network can train the gates toward stronger retention. Initial values nevertheless affect whether the early training signal can reach information stored far back in time. A default that works for short sequences may make the first useful long-range gradient too small.

Initialisation is therefore part of the experiment. The weight-initialisation tutorial measures the corresponding issue across depth. Here the repeated transformation runs through time, and the forget bias directly changes the initial memory path.

Recall Task

Each input sequence has two features. At the first step, feature one contains a symbol encoded as minus one or plus one, and feature two contains a marker of one. Later steps contain small Gaussian distractors in feature one and zero in feature two. The binary label is the first symbol.

The model predicts only after the final step. It must therefore preserve the marked initial symbol while processing later distractors. The marker makes the relevant event identifiable, so the experiment measures memory and optimisation on a simple dependency, rather than inference about which event matters.

def recall_task(n, length, generator):
    x = torch.randn(n, length, 2, generator=generator) * 0.15
    y = torch.randint(0, 2, (n,), generator=generator).float()
    x[:, 0, 0] = 2 * y - 1
    x[:, :, 1] = 0
    x[:, 0, 1] = 1
    return x, y

Both architectures use 32 hidden dimensions and a linear binary head on the final hidden output. Training uses Adam with learning rate 0.003, batches of 32, 1,000 updates and gradient clipping at one. New training sequences are generated each update. Each seed has a fixed test set of 512 separately generated sequences.

The task has a 50% chance baseline. It does not represent a real language or forecasting benchmark. A long sequence here contains a single marked bit, so conclusions about text understanding, time-series generalisation or many interacting dependencies would exceed the experiment.

Length Sweep

We train three seeds at lengths 10, 25, 50 and 100 for the RNN and bias-one LSTM. The bias-three extension repeats the LSTM at lengths 50 and 100. Bands in the figure show one standard deviation across seeds, rather than uncertainty over all possible training datasets.

An LSTM with forget bias three solves both long lengths, while bias one fails and the RNN shows seed-dependent success.

Sequence lengthRNN mean accuracyLSTM, bias 1LSTM, bias 3
10100.0%100.0%Not measured
25100.0%100.0%Not measured
5083.6%50.8%100.0%
10068.1%46.9%100.0%

At 100 steps the RNN seeds score 52.3%, 52.0% and 100.0%. Reporting only the failing seeds would conceal a successful recurrent solution. Reporting only the successful seed would conceal unstable training under these settings.

The bias-one LSTM fails across the longer lengths even though its architecture provides an additive memory route. Raising the initial forget bias repairs the tested training regime. The finding concerns this task, optimiser and update budget. Other sequence tasks need their own initialisation comparison.

The initial 100-step LSTM run took about six seconds, making the full sweep feasible on CPU. The recorded experiments, bias extensions and trace reconstruction take about 176 seconds in total. The notebook repeats the complete measurements without a GPU or a pretrained checkpoint.

Bias Ablation

At 100 steps, we compare forget biases zero, one and three using three seeds each. The zero and one settings remain near chance. The larger initial bias allows all three seeds to learn within the update budget. The chart shows the first 300 of the 1,000 training steps so the early transition remains visible.

Learning curves for three forget-bias settings at a sequence length of one hundred.

This ablation changes one initial parameter slice while retaining the architecture, task and training settings. It directly tests the retention explanation. It does not isolate every aspect of recurrence, since changing the initial gates also changes the later optimisation trajectory.

The learned gate animation at the start shows one successful sequence. Means across cell dimensions make its progression readable but hide specialised units. The exercises inspect individual dimensions, extend the length to 200 and compare orthogonal RNN initialisation with the existing baseline.

Foundations

Hochreiter and Schmidhuber's 1997 paper introduces Long Short-Term Memory to address long time lags in recurrent learning. Its memory-cell construction creates a route through which error can persist. The original architecture differs from the modern forget-gate cell implemented here.

Gers, Schmidhuber and Cummins subsequently introduced the forget gate in “Learning to Forget”. That gate lets a cell reset or retain its stored content as a continuing sequence requires. Our recurrence uses this later form, with an explicitly parameterised multiplier on the previous cell state.

The distinction matters when reading the 1997 equations alongside a current framework. A modern LSTM's four stacked gate blocks should not be attributed unchanged to the first paper. The NumPy and PyTorch comparison validates the current formulation, while the historical papers explain its components.

Bengio, Simard and Frasconi's 1994 analysis examines the difficulty of learning long-term dependencies with gradient descent. Products of recurrent derivatives can lose useful signal or grow excessively. The measured input-gradient curves expose that concern in the trained models rather than assuming it from the architecture name.

Pascanu, Mikolov and Bengio analyse recurrent training difficulties and gradient clipping. The clipping applied here handles the large-gradient case. The forget-bias experiment addresses a different problem, the weak initial signal reaching distant information.

Jozefowicz, Zaremba and Sutskever's empirical study includes positive forget-bias initialisation in recurrent architecture experiments. Bias one is therefore a motivated starting point. Its failure on this particular 100-step task shows the need to measure the dependency length and training regime instead of treating a published initialisation value as a guarantee.

LSTMs remain useful examples of gated sequential state. Transformers provide a different route to long-range interactions through attention, while state-space models structure recurrent dynamics to support different training and inference trade-offs. These alternatives require their own task, cost and accuracy comparisons.

The result here connects an architectural route with an optimisation condition. An additive cell-state path permits retention, and the initial gate values determine whether this training run can learn to use it across 100 steps. The measured RNN variation adds another constraint on any broad claim that one architecture must fail at a fixed length.

The original paper names its internal mechanism:

“constant error carrousels”

That phrase from the abstract refers to the original memory construction. Our modern cell replaces unconditional direct retention with a learned forget multiplier, so the direct memory route can deliberately contract. This lets a continuing sequence discard old information, while also making the initial forget value consequential for a distant training signal.

A scalar cell makes the distinction visible. Hold its input gate at zero for several steps so that no new content enters. The recurrence reduces to multiplying the stored value by successive forget gates. Backpropagating along that route multiplies by the same gates in reverse order. If every value is 0.5, ten steps retain roughly one thousandth of the initial contribution. Values near one preserve it longer, but a gate that stays near one also retains information that may have become irrelevant.

Writing new content and exposing stored content require separate controls. A closed input gate protects memory even when the candidate branch responds strongly to a distracting input. A closed output gate can suppress the visible hidden state while the cell retains content. In our first-symbol task, the marker identifies the useful writing event; later noisy inputs create repeated opportunities to overwrite it. The final classifier depends on exposing enough of the retained information at the last step.

The NumPy recurrence follows a simple sequence: concatenate the four gate preactivations, apply sigmoid to the input, forget and output blocks, apply tanh to the candidate block, update the cell, then compute the hidden state. Matching every hidden output to PyTorch checks gate order, bias handling and elementwise operations. It does not check the training problem by itself; the recall sweep supplies that separate evidence.

Long sequences also consume training memory because backpropagation retains intermediate activations. Truncated backpropagation shortens the gradient history, which can reduce that cost while preventing direct training signals across the truncation boundary. All sequences in this experiment are backpropagated in full. Its 100-step success therefore says nothing about a model trained with a shorter truncation window.

Interactive Tools

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions