Continual Learning: Training Neural Networks That Do Not Forget

Fine-tune a network on a new task and it erases the old. See catastrophic forgetting on split-MNIST, then fix it with Elastic Weight Consolidation and replay.

Cover Image for Continual Learning: Training Neural Networks That Do Not Forget

A recommender has learned from your current catalogue, and you want to update it when new products arrive. After training on the new examples, its older predictions may get worse because the same weights now have a different job. Continual learning examines how a model can absorb new data while retaining useful behaviour from earlier training. Catastrophic forgetting names the failure that makes this harder than simply continuing the training loop.

To protect earlier predictions, Elastic Weight Consolidation (EWC) penalises changes to weights using estimated Fisher information, computed from squared log-likelihood gradients on the completed task. Replay instead mixes stored examples into later training. We implement both for a small digit classifier and compare their effect across successive tasks.

For this comparison, we split MNIST into five two-digit tasks, train a single network on them in sequence, and watch the first task collapse to chance as later tasks arrive. Then we add EWC and experience replay and measure how much each recovers. Naive training ends at 0.889 average accuracy with the first task down at 0.551 (a coin flip). EWC lifts that to 0.955, while replay reaches 0.992 with the first task essentially intact. By the end you will understand the stability-plasticity dilemma, the Fisher-information trick behind EWC, and how per-task LoRA adapters isolate learned changes.

Let's Build It

Click the badge to open the interactive notebook:

Open In Colab

Watch the first task being forgotten. We train one MLP on tasks 0/1, then 2/3, then 4/5, 6/7, 8/9 in order, and after each stage we measure accuracy on the very first task (digits 0 versus 1). Naive training falls off a cliff. EWC slows the decline. Replay barely budges.

Animated line chart of accuracy on Task 1 (digits 0/1) as more tasks are learned. The naive SGD line plunges from 1.0 to about 0.55 (chance), the EWC line settles around 0.74 then recovers to 0.81, and the replay line stays flat near 1.0 across all five stages.

The model is a plain two-hidden-layer network. Nothing about the architecture causes the forgetting; the training regime does.

import torch.nn as nn

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(784, 256), nn.ReLU(),
            nn.Linear(256, 256), nn.ReLU(),
            nn.Linear(256, 10),
        )
    def forward(self, x):
        return self.net(x)

We use the task-incremental setting: at test time for a given task we only score the two output units belonging to that task's digits, so chance is 50%. Each task trains for three epochs with Adam before the next one starts. The network never sees an earlier task's data again, which is the whole point.

What Just Happened?

The stability-plasticity dilemma

Every learning system faces a trade-off. To learn task B it must change its weights (plasticity). To remember task A it must keep its weights (stability). Pure plasticity forgets everything old; pure stability learns nothing new. Catastrophic forgetting is what you get when an unconstrained optimiser sits at the plasticity extreme: gradient descent on task B moves the weights wherever B's loss is lowest, with no memory that those same weights were carrying task A.

The fix, in every method we will see, is to inject some stability back in without freezing the network solid. The three big families do it differently: penalise changes to important weights (regularisation), revisit a little old data (replay), or hand each task its own parameters (isolation).

The accuracy matrix tells the whole story

The cleanest way to see forgetting is a table: after training through each task (rows), how accurate is the model on every task seen so far (columns)? The first column is the oldest task; watch what happens to it as you read down.

Three accuracy-matrix heatmaps for naive, EWC, and replay. In the naive panel the first column (task 0/1) fades from 1.00 at the top to 0.55 at the bottom, coloured red. In the EWC panel that column stays yellow around 0.74 to 0.81. In the replay panel every cell stays green near 1.00. Average accuracies are 0.889, 0.955, and 0.992.

For naive SGD the first column reddens as you go down: the model scored 1.00 on digits 0/1 right after learning them, 0.57 after task 4/5, and 0.55 by the end. It has forgotten how to tell a 0 from a 1. Each new task pulls the shared weights toward its own solution and the old decision boundary dissolves. EWC keeps that column in the 0.74 to 0.81 band; replay keeps it green at 1.00. Note that the most recent task is always near-perfect for every method. Forgetting is a property of the past, not the present.

Going Deeper

EWC: protect the weights that mattered

Elastic Weight Consolidation asks a sharp question: when task A finished, which weights actually mattered for it? If we know that, we can let the unimportant weights move freely for task B while anchoring the important ones near their task-A values. The importance measure is the diagonal of the Fisher information matrix, the expected squared gradient of the log-likelihood. A weight with a large Fisher value is one the loss is very sensitive to; nudging it hurts.

EWC adds a quadratic penalty to the new task's loss for every previous task:

L(θ)=LB(θ)+∑iλ2 Fi (θi−θA,i∗)2\mathcal{L}(\theta) = \mathcal{L}_B(\theta) + \sum_{i} \frac{\lambda}{2}\, F_i \,(\theta_i - \theta_{A,i}^{*})^2

Here θA,i∗\theta_{A,i}^{*} is the weight's value at the end of task A, FiF_i is its Fisher importance, and λ\lambda sets how hard we hold on. The penalty is a spring: stiff (high FiF_i) for weights A relied on, slack for the rest. Computing the diagonal Fisher is just an average of squared gradients over a sample of the finished task:

def fisher(model, X, y, task_id, n=512):
    """Diagonal Fisher: mean squared gradient of the task loss."""
    f = {n_: torch.zeros_like(p) for n_, p in model.named_parameters()}
    for k in torch.randperm(len(X))[:n]:
        model.zero_grad()
        loss = F.cross_entropy(task_logits(model(X[k:k+1]), task_id), target_k)
        loss.backward()
        for n_, p in model.named_parameters():
            f[n_] += p.grad.detach() ** 2
    return {n_: fi / n for n_, fi in f.items()}

The penalty itself is a few lines inside the training loop, summed over every task finished so far:

loss = F.cross_entropy(logits, target)
for fsh, theta_star in zip(fishers, opt_params):       # one per past task
    for n_, p in model.named_parameters():
        loss = loss + (ewc_lambda / 2) * (fsh[n_] * (p - theta_star[n_]) ** 2).sum()

If the Fisher information feels familiar, it should. It is the same quantity that appears as the curvature in the Laplace approximation for Bayesian neural networks, where it plays the role of the posterior precision. EWC is doing Bayesian updating in disguise: the old task's solution becomes a Gaussian prior on the weights for the new task, with precision set by the Fisher. And the link to second-order optimisation is direct too: the Fisher is a close cousin of the Hessian we met in the backprop post, which is why it captures how sensitive the loss is to each weight.

Replay: just keep a little of the old data

Replay is almost embarrassingly simple and works better than anything clever. Keep a small buffer of examples from each finished task, and mix them into every new task's batches so the optimiser never fully loses sight of the old distribution.

# after finishing a task, stash a few hundred of its examples
buffer.extend(sample(task_data, k=200))

# during the next task, add the buffer's loss to each step
loss = F.cross_entropy(new_logits, new_target)
loss = loss + replay_loss(model, sample(buffer, batch_size))

Two hundred examples per task, 1,000 stored in total, is enough to take our first-task accuracy from 0.55 back to 0.998. The catch is that replay needs you to store raw data, which is not always allowed (privacy, scale, or licensing), and it is why generative replay (synthesising old examples instead of storing them) and regularisation methods like EWC exist at all.

Two bar charts. Left, final average accuracy across the five tasks: naive 0.889, EWC 0.955, replay 0.992, higher is better. Right, mean forgetting (peak minus final accuracy): naive 0.135, EWC 0.051, replay 0.006, lower is better.

The three families, and where LLMs fit

EWC and replay are two of the three classic families. The third is parameter isolation: give each task its own parameters and freeze the shared ones, so there is nothing to overwrite.

Three-panel conceptual diagram. Regularisation (EWC): a set of weights with the important ones drawn bold and held firm, others free to move. Replay: a memory buffer of old examples feeding into training on new plus old data. Parameter isolation: a frozen backbone with a separate small adapter module per task.

That third family is exactly what modern LLM practice has converged on. When you fine-tune a large model with LoRA adapters, you freeze the base weights and train a small low-rank module for the new task. The base model cannot forget because it never changes; each task lives in its own adapter. Continual learning for LLMs is largely this story plus replay: keep a slice of the pretraining or instruction data mixed in during fine-tuning so general capabilities do not erode. The vocabulary is new (adapters, instruction mixing) but the underlying levers are the same three this post measures.

Tuning the trade-off

The knob that matters for EWC is λ\lambda. Too small and the penalty is ignored, so you forget; too large and the network is too stiff to learn new tasks well. We used λ=2000\lambda = 2000, which is high because our Fisher values are small averages. For replay, the lever is buffer size: more stored examples means less forgetting but more memory and compute. As with learning rate schedules, there is no universal setting; the right value depends on how many tasks you expect and how different they are.

One honest caveat about scale. Our split-MNIST tasks are easy and well separated, which flatters every method. In the harder class-incremental setting, where the model must distinguish all ten digits with no task identity at test time, EWC alone is known to struggle and replay's advantage grows. The direction of all our results holds at scale; the magnitudes are optimistic.

Where This Comes From

Catastrophic forgetting was named and characterised long before deep learning's current era.

McCloskey and Cohen (1989), "Catastrophic Interference in Connectionist Networks", first documented the effect. Training a network on one set of associations and then another erased the first, and they showed it was a structural property of distributed representations, not a tuning artefact. The finding was discouraging enough that it partly motivated the move away from neural networks in the following decade.

Kirkpatrick et al. (2017), "Overcoming Catastrophic Forgetting in Neural Networks", introduced EWC and revived the topic for the deep-learning age.

"The Fisher information... tells us how important each parameter is for the previously learned task. We constrain the parameters to stay in a region of low error for task A by penalising changes to important parameters." (Kirkpatrick et al., 2017)

The paper showed a single network learning a sequence of Atari games and tasks of permuted MNIST without the usual collapse, using exactly the Fisher-weighted penalty we implemented.

Lopez-Paz and Ranzato (2017), "Gradient Episodic Memory for Continual Learning", formalised the replay family and introduced the metrics this post uses: average accuracy and backward transfer, which measures how learning a new task changes performance on old ones (forgetting is negative backward transfer). GEM stores examples and projects gradients so that no update increases loss on the stored memories.

Parisi et al. (2019), "Continual Lifelong Learning with Neural Networks: A Review", is the survey that organises the field into the three families (regularisation, replay, architectural isolation) and frames everything around the stability-plasticity dilemma. It is the best single map of the territory.

The throughline from 1989 to today is that distributed representations share parameters across tasks, so unconstrained learning of the new overwrites the old. Every method is a different way of buying back stability: anchor the important weights, rehearse the old data, or wall off new capacity. The LLM era did not escape the problem; it picked the third option and called it adapters.

Further Reading

Interactive Tools

  • Forgetting Curve Explorer: The human memory forgetting curve that gives this failure mode its name; spaced repetition is biological replay
  • Overfitting Explorer: The bias-variance trade-off is the static cousin of the stability-plasticity dilemma this post is built around

Stay in the loop

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

Related Posts

Frequently Asked Questions