AnyLearn
All lessons
AIadvanced

Fixing Forgetting: Replay, Regularisation, and Parameter Isolation

The three families of continual learning methods, taken apart: experience and generative replay, gradient projection with GEM, weight penalties from EWC and synaptic intelligence, distillation, and per-task adapters. Includes a runnable PyTorch comparison of EWC and replay, and a table for choosing among them.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 9

Replay: keep a little of the past

The previous lesson traced forgetting to one absence: while training on B, the batch holds no gradient from A. The bluntest fix is to put A back. Experience replay keeps a small buffer of old examples and mixes a few into every new batch, so the optimiser sees both objectives at once.

How the buffer is filled matters less than people expect, but the common policies are worth knowing:

  • Reservoir sampling (Vitter, 1985) keeps a uniform random sample of the whole stream in fixed memory, without knowing the stream's length.
  • Class-balanced buffers keep the same number of examples per class, so early classes are not crowded out.
  • Herding, used by iCaRL (Rebuffi et al., 2017), picks the examples whose feature mean best matches each class's mean.

The payoff is large. On Split MNIST in the hardest setting, where the model must choose among all ten digits, van de Ven, Tuytelaars and Tolias (Nature Machine Intelligence, 2022) report 88.79% final accuracy for replay with 100 stored examples per class, against 19.89% for plain sequential training. Chaudhry et al. (2019) similarly found that even tiny episodic memories make replay a strong baseline.

Sign in free to save your progress and earn certificates.

Full lesson text

All 9 steps on one page, for reading, reference, and search.

Show

1. Replay: keep a little of the past

The previous lesson traced forgetting to one absence: while training on B, the batch holds no gradient from A. The bluntest fix is to put A back. Experience replay keeps a small buffer of old examples and mixes a few into every new batch, so the optimiser sees both objectives at once.

How the buffer is filled matters less than people expect, but the common policies are worth knowing:

  • Reservoir sampling (Vitter, 1985) keeps a uniform random sample of the whole stream in fixed memory, without knowing the stream's length.
  • Class-balanced buffers keep the same number of examples per class, so early classes are not crowded out.
  • Herding, used by iCaRL (Rebuffi et al., 2017), picks the examples whose feature mean best matches each class's mean.

The payoff is large. On Split MNIST in the hardest setting, where the model must choose among all ten digits, van de Ven, Tuytelaars and Tolias (Nature Machine Intelligence, 2022) report 88.79% final accuracy for replay with 100 stored examples per class, against 19.89% for plain sequential training. Chaudhry et al. (2019) similarly found that even tiny episodic memories make replay a strong baseline.

2. Generative replay: remember by imagining

Storing real data is sometimes forbidden by privacy rules or licences. Deep generative replay (Shin et al., 2017) trains a generator alongside the classifier and, when a new task arrives, replays synthetic samples of the old ones, labelled by the previous classifier. Nothing real is kept.

The weak point is the generator itself. Replay is only as good as the samples, and a generator is itself a network that must learn continually. The numbers from van de Ven et al. (2022), final accuracy in the class-incremental setting, show where that bites:

MethodSplit MNISTSplit CIFAR-100
None (sequential training)19.89%7.71%
Deep generative replay90.35%9.67%
Brain-inspired replay94.41%25.81%
Replay, 100 stored per class88.79%37.57%
Joint training (upper bound)98.17%49.78%

Generating digits is easy; generating natural images well enough to stand in for real ones is not. Brain-inspired replay (van de Ven, Siegelmann and Tolias, Nature Communications 2020) replays internal feature representations rather than pixels, which recovers part of the gap.

3. Constrained updates: GEM and A-GEM

Replay adds old examples to the loss. Gradient Episodic Memory (Lopez-Paz and Ranzato, 2017) uses them differently: as a constraint. Before each update it computes the gradient grefg_{\text{ref}} on the memory and checks the sign of its dot product with the proposed gradient gg, exactly the interference test from the previous lesson. If the step would increase the loss on memory, it is projected so that it no longer does. The cheaper A-GEM variant (Chaudhry et al., ICLR 2019) uses one averaged reference gradient:

g~={gif g⊤gref≥0g−g⊤grefgref⊤gref grefotherwise\tilde g = \begin{cases} g & \text{if } g^\top g_{\text{ref}} \ge 0 \\[4pt] g - \dfrac{g^\top g_{\text{ref}}}{g_{\text{ref}}^\top g_{\text{ref}}}\, g_{\text{ref}} & \text{otherwise} \end{cases}

The projected step has zero first-order effect on the memory loss and keeps as much of the new-task direction as possible.

Gotcha: A constraint only forbids making old tasks worse to first order; it never actively improves them. On Split MNIST class-incremental, van de Ven et al. (2022) measured 65.10% for A-GEM against 88.79% for plain replay with the same 100 examples per class. Training on the memory beat merely respecting it.

4. Elastic weight consolidation

Regularisation methods keep no data. They remember which weights mattered and make those weights hard to move. Elastic weight consolidation (Kirkpatrick et al., PNAS 2017) adds a quadratic penalty while training on B:

L(θ)=LB(θ)+∑iλ2Fi(θi−θA,i∗)2L(\theta) = L_B(\theta) + \sum_i \frac{\lambda}{2} F_i \left(\theta_i - \theta^*_{A,i}\right)^2

Here θA∗\theta^*_A are the weights at the end of task A, FiF_i is the diagonal of the Fisher information matrix estimated on A's data, and λ\lambda sets how much the old task counts.

The justification is Bayesian. After A, the ideal prior for B is the posterior over weights given A's data. EWC approximates that posterior as a Gaussian centred on θA∗\theta^*_A whose precision is the Fisher, so the penalty is its negative log. Weights where small changes would hurt A's likelihood get stiff springs; the rest stay free.

Key idea: EWC does not freeze the network. It makes the important directions expensive and leaves the unimportant ones for the new task, which works when the network has spare capacity in directions A does not care about.

Kirkpatrick et al. demonstrated it on permuted MNIST tasks and on ten Atari games learned in sequence by one agent.

5. Other ways to measure importance

EWC computes importance once, at the end of each task, from the Fisher. Two well-known alternatives change where the importance signal comes from.

Synaptic intelligence (Zenke, Poole and Ganguli, ICML 2017) accumulates importance online during training. Each weight is credited with how much its movement actually reduced the loss along the optimisation path, a path integral approximated by summing −gk Δθk-g_k \, \Delta\theta_k over updates, then normalised by how far the weight moved overall. Weights that did a lot of work become stiff.

Memory aware synapses (Aljundi et al., ECCV 2018) measures how sensitive the network's output is to each weight, which needs no labels and can be computed on any unlabelled data.

MethodWhen importance is computedSignal usedNeeds labels
EWCAfter each taskSquared gradients of the log-likelihood (Fisher)Yes, or model predictions
Synaptic intelligenceContinuously, during trainingEach weight's contribution to the drop in lossYes
Memory aware synapsesAfter each taskSensitivity of the output to each weightNo

All three share EWC's quadratic penalty form; they differ only in the stiffness assigned to each weight.

6. EWC and replay, side by side in PyTorch

Two synthetic tasks live in different regions of a 10-dimensional input space and follow different rules, so one small network can solve both jointly. Train on A, then on B with no protection, with EWC at two strengths, or with replay of 100 stored A examples.

import torch, torch.nn as nn, torch.nn.functional as F
torch.manual_seed(0)

def make_task(shift, rule_dim, n=2000):
    x = torch.randn(n, 10); x[:, 0] += shift        # different input region
    return x, (x[:, rule_dim] > 0).long()           # different rule

A, B = make_task(+2.0, 1), make_task(-2.0, 2)
net = lambda: nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 2))
acc = lambda m, d: (m(d[0]).argmax(1) == d[1]).float().mean().item()

def fit(m, data, penalty=None, replay=None, steps=1500):
    opt = torch.optim.Adam(m.parameters(), lr=1e-3)
    x, y = data
    for _ in range(steps):
        i = torch.randint(len(x), (64,))
        loss = F.cross_entropy(m(x[i]), y[i])
        if replay:                                  # rehearse stored A examples
            j = torch.randint(len(replay[0]), (16,))
            loss = loss + F.cross_entropy(m(replay[0][j]), replay[1][j])
        if penalty:
            loss = loss + penalty(m)
        opt.zero_grad(); loss.backward(); opt.step()

def fisher_diag(m, data, n=500):                    # mean squared gradient per weight
    fis = [torch.zeros_like(p) for p in m.parameters()]
    for k in range(n):
        m.zero_grad()
        F.cross_entropy(m(data[0][k:k+1]), data[1][k:k+1]).backward()
        for f, p in zip(fis, m.parameters()):
            f += p.grad ** 2 / n
    return fis

base = net(); fit(base, A)
star = [p.detach().clone() for p in base.parameters()]
fis = fisher_diag(base, A)
ewc = lambda lam: lambda m: lam / 2 * sum(
    (f * (p - s) ** 2).sum() for p, s, f in zip(m.parameters(), star, fis))

print(f"after A only          : acc A {acc(base, A):.2f}")
for label, kw in [("no protection", {}),
                  ("EWC lambda=100", {"penalty": ewc(100.0)}),
                  ("EWC lambda=3000", {"penalty": ewc(3000.0)}),
                  ("replay 100 of A", {"replay": (A[0][:100], A[1][:100])})]:
    m = net(); m.load_state_dict(base.state_dict()); fit(m, B, **kw)
    print(f"then B, {label:<15}: acc A {acc(m, A):.2f}  acc B {acc(m, B):.2f}")

Output:

after A only          : acc A 1.00
then B, no protection  : acc A 0.60  acc B 0.99
then B, EWC lambda=100 : acc A 0.79  acc B 0.97
then B, EWC lambda=3000: acc A 0.87  acc B 0.93
then B, replay 100 of A: acc A 0.90  acc B 0.97

Read it as the stability-plasticity dial. Unprotected, A falls from 1.00 to 0.60. EWC at lambda 100 keeps 0.79; at 3000 it keeps 0.87 but B drops to 0.93, because the springs now resist the new task too. Replay of just 100 examples, 5% of A's data, keeps the most A while still learning B.

Gotcha: With plain SGD at learning rate 0.1, lambda values of 300 and above made this same setup diverge to chance on both tasks. The penalty's curvature is lambda times the Fisher, and a step size that is fine for the task loss can be far too large for that stiffness.

7. Functional regularisation: protect outputs, not weights

Weight penalties assume that staying close in weight space keeps behaviour close, which is only roughly true. Functional methods protect the behaviour directly. Learning without Forgetting (Li and Hoiem, 2016) records the old model's outputs on the new task's inputs, then trains the new model to keep producing them while it learns B, a form of knowledge distillation:

L=LB(θ)+λo 1N∑x∈DBKL ⁣(pold(⋅∣x) ∥ pθ(⋅∣x))L = L_B(\theta) + \lambda_o \, \frac{1}{N}\sum_{x \in D_B} \mathrm{KL}\!\left(p_{\text{old}}(\cdot \mid x) \,\|\, p_\theta(\cdot \mid x)\right)

No old data is stored, and the constraint applies wherever the new data probes the function. That is also its limit: if B's inputs look nothing like A's, the distillation term says little about how the model behaves on A.

In practice: The strongest simple recipes combine families. iCaRL (Rebuffi et al., 2017) pairs a replay buffer with distillation and a nearest-mean-of-exemplars classifier. Dark Experience Replay (Buzzega et al., NeurIPS 2020) stores the model's logits alongside each replayed example and matches them later, which is replay and functional regularisation in one loss term.

8. Parameter isolation: stop sharing

If tasks fight over weights, give each its own. Progressive networks (Rusu et al., 2016) add a new column per task with lateral connections to frozen old columns: zero forgetting, linear growth. PackNet (Mallya and Lazebnik, 2018) prunes after each task and frees the unused weights for the next, inside a fixed network. Hard attention to the task (Serra et al., 2018) learns a binary mask per task. The modern form is a frozen pretrained backbone with a small adapter or LoRA module per task; the fine-tuning versus RAG cursus covers how LoRA itself works. The catch is the router: something must know which task an input belongs to.

flowchart LR
  X["Input"] --> R["Task identity: given or inferred"]
  X --> B["Frozen shared backbone"]
  R --> S["Select adapter"]
  B --> S
  S --> A1["Adapter for task 1"]
  S --> A2["Adapter for task 2"]
  S --> A3["Adapter for task 3"]
  A1 --> O["Task-specific output"]
  A2 --> O
  A3 --> O

9. Choosing a family

Each family assumes something about your setting. Pick by the constraint that binds first.

If your situation isStart withWhy
You may store some old dataReplay, possibly with distillationAmong the top performers in every scenario van de Ven et al. tested
No data may be kept, inputs similar across tasksFunctional regularisation (LwF)Uses new inputs to pin old behaviour
No data, tasks known at test timeParameter isolation or EWC/SIBoth protect well when the task is given
No data, task must be inferred at test timeGenerative or feature replayWeight penalties alone fail here
Tight compute budgetUniform replayPrabhu et al. (CVPR 2023) found elaborate methods did not beat it under fixed compute

Gotcha: The fourth row is where most published comparisons quietly differ. In the class-incremental version of Split MNIST, van de Ven et al. (2022) measured EWC at 20.64% and synaptic intelligence at 21.20%, essentially the 19.89% of no protection at all, while the same methods exceeded 99% when the task was given. The next lesson explains why, and how to evaluate any method so the scenario cannot flatter it.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. In the EWC penalty, what role does the diagonal Fisher information F_i play?
    • It sets the learning rate for weight i on the new task
    • It counts how many times weight i was updated during task A
    • It is the stiffness of the spring on weight i, large where changing it would hurt task A's likelihood
    • It is the probability that weight i is pruned after task A
  2. A-GEM detects that a proposed gradient g has a negative dot product with the memory gradient g_ref. What does it do?
    • Projects g to remove its component along g_ref, then takes the step
    • Skips the update entirely
    • Reverses the sign of g
    • Doubles the learning rate on the memory batch
  3. Why did deep generative replay score far lower on Split CIFAR-100 than on Split MNIST in van de Ven et al.'s class-incremental results?
    • CIFAR-100 has fewer classes than MNIST
    • Generative replay stores too many real images for CIFAR
    • Distillation is impossible on colour images
    • Its generator could not produce natural images good enough to stand in for real ones
  4. In the PyTorch comparison, raising EWC's lambda from 100 to 3000 raised task A accuracy from 0.79 to 0.87. What happened to task B, and why?
    • It rose to 1.00, because stiffer weights generalise better
    • It fell from 0.97 to 0.93, because the stronger penalty also resists learning the new task
    • It was unchanged, because EWC only affects old tasks
    • It fell to chance, because the Fisher was estimated on task B
  5. What is the main practical requirement of parameter-isolation methods such as one adapter per task?
    • A replay buffer of old examples
    • A generative model trained alongside the classifier
    • A way to know or infer which task an input belongs to at test time
    • A Fisher information estimate for every weight

Related lessons

AI
intermediate

Catastrophic Forgetting: Why Neural Networks Overwrite What They Knew

Train a network on one task, then another, and the first often collapses. This lesson shows why: shared weights and conflicting gradients, demonstrated in twenty lines of code, then the stability-plasticity dilemma, the less known loss of plasticity, and how the brain's replay suggests the fixes.

10 steps·~15 min
AI
advanced

Continual Learning in Large Language Models: Continued Pretraining, Drift, and Editing

Every stage of a language model's life trains the same weights on new data, so every stage can erase the last. Learn the continued-pretraining recipe of re-warming, re-decaying and replay, how fine-tuning erodes skills and safety, why LoRA and on-policy RL forget less, and when editing or retrieval beats training.

10 steps·~15 min
AI
advanced

Measuring Continual Learning: Scenarios, Transfer Metrics, and Honest Baselines

The same method can score 99% or 21% on one benchmark depending on what the model is told at test time. Learn the task-, domain- and class-incremental scenarios, the accuracy matrix with backward and forward transfer, and the protocol choices and baselines that make a continual learning result trustworthy.

9 steps·~14 min
Science
intermediate

Predicted, Made, Proven: Judging a Materials Discovery Claim

How to tell a predicted crystal from a validated new material. Builds an evidence ladder from predicted stable to useful, explains why zero-kelvin calculations invent atomic order that real samples lack, and applies the ladder to three documented cases: a large prediction database, an autonomous lab, and a generative model.

10 steps·~15 min