Catastrophic Forgetting and How to Limit It
Fine-tune a model on a new task and it gets good at the new task. Ask it the old questions again and it may have become bad at them. Neural networks store everything they know in the same shared weights, and gradient descent on the new data moves those weights wherever the new loss wants, with no regard for what they used to do. The loss of old skills after training on new data is called catastrophic forgetting (McCloskey and Cohen, 1989). It matters whenever a model must keep its old abilities: a language model fine-tuned on support tickets that should still write grammatical English, a vision model updated for a new camera that must still work on the old ones, any model that learns online from a stream.
Seeing it happen
The digit network of the earlier lessons (one hidden layer of 64 units) is trained on one half of the digits; that is task A. Task B is the same ten digits rotated by 90 degrees, as if a scanner fed the pages sideways, learned from 300 labelled rotated images. Both tasks share the same output layer: one model must read upright and rotated digits. The test sets are the 599 other images of the second half, upright for A and rotated for B.
Definitions
Let be the weights after task A and the loss on task B. Plain fine-tuning minimises alone, starting from . Forgetting is measured as the drop on A, , reported together with the gain on B: a method that forgets nothing because it learned nothing is no solution.
The remedies come in four families.
1. Stay close to the old weights (regularisation). Add a penalty for moving away from . The simplest is L2-SP ("starting point"), . It treats every weight as equally important. Elastic weight consolidation (EWC, Kirkpatrick et al., 2017) weights the penalty by how much each parameter mattered for A:
is the diagonal of the Fisher information: the average squared gradient of the log-likelihood on task A data. A weight that the A loss is very sensitive to has a large and is held almost fixed; a weight A does not care about can move freely. (It is the quadratic approximation of around its minimum, with the Fisher as a stand-in for the Hessian: Curvature and the Hessian.)
2. Keep seeing old data (rehearsal, replay). Mix a small buffer of stored A examples into every B batch. Simple and very effective, when you are allowed to keep old data (Replay Buffers and Rollback). If not, distillation (Learning without Forgetting) uses the old model's outputs on the new inputs as soft targets instead.
3. Change less (conservative training). A smaller learning rate, fewer steps, frozen lower layers: everything that keeps near also limits forgetting, at the price of learning B less.
4. Isolate the new task's parameters. Freeze entirely and learn B in added parameters: a new head per task, LoRA or adapters. Task A is then not forgotten at all, as long as the system knows which task it is solving and switches the adapter off for A.
From scratch: forgetting, EWC and replay
The experiment above, in NumPy. The task A weights come from scikit-learn; the diagonal Fisher is computed on the task A training images with a trick that makes per-example gradients cheap for a dense layer: the gradient of one example for is the outer product , so its elementwise square is , and the mean over examples is one matrix product. Every method trains with the same budget, Adam at 0.003 for 300 full-batch steps on the 300 rotated images.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, y_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
task_A = MLPClassifier(hidden_layer_sizes=(64,), max_iter=500, random_state=0).fit(X_src, y_src)
theta_A = [task_A.coefs_[0], task_A.intercepts_[0], task_A.coefs_[1], task_A.intercepts_[1]]
rotate = lambda A: np.rot90(A.reshape(-1, 8, 8), 1, axes=(1, 2)).reshape(-1, 64)
rng = np.random.default_rng(0)
lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], 30, replace=False) for c in range(10)])
test = np.setdiff1d(np.arange(len(y_tgt)), lab)
X_B, y_B = rotate(X_tgt[lab]), y_tgt[lab] # task B: 300 rotated digits
def forward(P, A):
h = np.maximum(0, A @ P[0] + P[1])
return h, h @ P[2] + P[3]
def gradients(P, A, yy, fisher=False):
h, z = forward(P, A)
p = np.exp(z - z.max(1, keepdims=True)); p /= p.sum(1, keepdims=True)
g = p.copy(); g[np.arange(len(yy)), yy] -= 1 # d loss / d logits, per example
gh = g @ P[2].T * (h > 0)
n = len(yy)
if fisher: # mean of squared per-example gradients
return [(A ** 2).T @ gh ** 2 / n, (gh ** 2).mean(0), (h ** 2).T @ g ** 2 / n, (g ** 2).mean(0)]
return [A.T @ gh / n, gh.sum(0) / n, h.T @ g / n, g.sum(0) / n]
F = gradients(theta_A, X_src, y_src, fisher=True) # importance of each weight for task A
def scores(P):
a = (forward(P, X_tgt[test])[1].argmax(1) == y_tgt[test]).mean()
b = (forward(P, rotate(X_tgt[test]))[1].argmax(1) == y_tgt[test]).mean()
return a, b
def learn_B(method, lam=0.0, n_replay=0, lr=0.003, steps=300):
P = [p.copy() for p in theta_A]
A, yy = X_B, y_B
if n_replay: # keep showing some task A images
keep = np.random.default_rng(1).choice(len(y_src), n_replay, replace=False)
A, yy = np.vstack([X_B, X_src[keep]]), np.concatenate([y_B, y_src[keep]])
m, v = [0] * 4, [0] * 4
for t in range(1, steps + 1):
G = gradients(P, A, yy)
if method == "L2-SP":
G = [g + lam * (p - p0) for g, p, p0 in zip(G, P, theta_A)]
if method == "EWC":
G = [g + lam * f * (p - p0) for g, p, p0, f in zip(G, P, theta_A, F)]
for i in range(4):
m[i] = 0.9 * m[i] + 0.1 * G[i]; v[i] = 0.999 * v[i] + 0.001 * G[i] ** 2
P[i] = P[i] - lr * (m[i] / (1 - 0.9 ** t)) / (np.sqrt(v[i] / (1 - 0.999 ** t)) + 1e-8)
return P
print("method task A (upright) task B (rotated)")
print(f"{'after task A only':27s} {scores(theta_A)[0]:16.3f} {scores(theta_A)[1]:18.3f}")
for label, method, lam, n_rep in [("plain fine-tuning", "plain", 0, 0),
("L2-SP, lambda = 0.1", "L2-SP", 0.1, 0), ("L2-SP, lambda = 1", "L2-SP", 1, 0),
("EWC, lambda = 100", "EWC", 100, 0), ("EWC, lambda = 1000", "EWC", 1000, 0),
("replay 50 A images", "plain", 0, 50), ("replay 200 A images", "plain", 0, 200)]:
a, b = scores(learn_B(method, lam, n_rep))
print(f"{label:27s} {a:16.3f} {b:18.3f}")method task A (upright) task B (rotated)
after task A only 0.968 0.102
plain fine-tuning 0.518 0.910
L2-SP, lambda = 0.1 0.773 0.738
L2-SP, lambda = 1 0.795 0.311
EWC, lambda = 100 0.771 0.907
EWC, lambda = 1000 0.883 0.866
replay 50 A images 0.833 0.910
replay 200 A images 0.928 0.910
Before task B the model reads upright digits (0.968) and is at chance on rotated ones (0.102). Plain fine-tuning learns B well (0.910) and drops A to 0.518: half of what the model could do is gone after 300 steps on 300 images.
- L2-SP does keep more of A (0.773 and 0.795), but only by blocking B (0.738 and 0.311). Holding every weight with the same force is a blunt tool.
- EWC keeps B almost untouched at (0.907) with A at 0.771, and at trades 0.044 of B for a much better A (0.883). The Fisher lets B move the weights A does not need.
- Replay is the strongest: 50 stored A images (one in seven of the mixed batch) keep A at 0.833, and 200 keep it at 0.928, with B at 0.910 in both cases, as good as plain fine-tuning.
The scores are on 599 test images (0.002 per image) and one draw of the B labels; the gaps between methods are tens of images, far beyond that noise. The values were picked to show the trade-off, not tuned; in a project they would be chosen on validation data for both tasks.
With scikit-learn: forgetting during partial_fit
Forgetting is not a quirk of hand-written training loops. scikit-learn's MLPClassifier.partial_fit does one pass over the data it is given, which is how online learning feeds a model new data. Train for 20 passes on task A, then 20 passes on task B only, and print both test accuracies along the way:
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_src, X_tgt, y_src, y_tgt = train_test_split(X, y, test_size=0.5, random_state=0, stratify=y)
rotate = lambda A: np.rot90(A.reshape(-1, 8, 8), 1, axes=(1, 2)).reshape(-1, 64)
rng = np.random.default_rng(0)
lab = np.concatenate([rng.choice(np.where(y_tgt == c)[0], 30, replace=False) for c in range(10)])
test = np.setdiff1d(np.arange(len(y_tgt)), lab)
model = MLPClassifier(hidden_layer_sizes=(64,), learning_rate_init=0.003, random_state=0)
classes = np.arange(10)
def report(stage):
a = model.score(X_tgt[test], y_tgt[test]); b = model.score(rotate(X_tgt[test]), y_tgt[test])
print(f"{stage:22s} task A {a:.3f} | task B {b:.3f}")
for epoch in range(1, 21):
model.partial_fit(X_src, y_src, classes=classes) # task A: upright digits
if epoch in (1, 20):
report(f"A, pass {epoch}")
for epoch in range(1, 21):
model.partial_fit(rotate(X_tgt[lab]), y_tgt[lab]) # task B only: rotated digits
if epoch in (1, 5, 20):
report(f"B, pass {epoch}")A, pass 1 task A 0.289 | task B 0.030
A, pass 20 task A 0.943 | task B 0.104
B, pass 1 task A 0.928 | task B 0.147
B, pass 5 task A 0.786 | task B 0.214
B, pass 20 task A 0.765 | task B 0.796
After 20 passes on A the model reads upright digits (0.943). The first pass on B costs little (0.928), but by pass 5 A is down to 0.786 while B has barely started (0.214), and after 20 passes B reaches 0.796 and A has settled at 0.765. Forgetting starts before the new task is learned: the first B updates are large and aimed only at B. Nothing in partial_fit knows that A exists; protecting it is the job of the training procedure around it.
Advantages and limits of the remedies
| Remedy | Needs | Strength | Limit |
|---|---|---|---|
| Lower learning rate, fewer steps, freezing | nothing | free | learns B less |
| L2-SP | one line of code | all weights treated alike | |
| EWC | and the Fisher on A data | protects the weights that matter | the quadratic approximation fails for large moves; one Fisher per old task |
| Replay | stored A data | usually the strongest | storage, privacy and licence of old data |
| Distillation (LwF) | the old model | no old data needed | needs inputs where the old outputs mean something |
| New parameters per task (heads, LoRA, adapters) | the task identity at test time | no forgetting of A at all | which adapter to use must be known; no transfer back to A |
For large language models the practical defaults are: parameter-efficient fine-tuning, a moderate learning rate, a small share of general data mixed into the fine-tuning data (replay), and an evaluation of general skills before and after.
Pitfalls
- Measuring only the new task. A fine-tuning report without the old tasks' scores hides forgetting. Keep a fixed "old skills" evaluation set and run it on every new version.
- Tuning on the test sets. trades A against B; choose it on validation data for both tasks, with a stated rule (for example the best B accuracy with at most 5 points lost on A).
- Replay from the test set. The replay buffer must come from A's training data.
- Computing the Fisher after fine-tuning. It must be computed at on A data, before training on B.
- Assuming a frozen base cannot forget. A LoRA adapter does not change , but the adapted model can still lose A skills while the adapter is on. Isolation protects A only if the adapter is switched off for A.
Practice
- In the NumPy table, which method gives the best compromise if task A may lose at most 10 points of accuracy?
- Why does L2-SP with protect A less than EWC with while hurting B much more?
- Your company may not keep customer data from last year, so replay is not allowed. Which two remedies remain, and what does each need?
Answers
- EWC with keeps A within 10 points of 0.968 (0.883) and still learns B to 0.866; the other methods either forget more of A or (L2-SP) learn little B. Replay of 200 images is even better on both, if storing old images is allowed (see the table).
- L2-SP pulls every weight back with the same force, including the weights B needs to move, so B cannot be learned; it also does not hold the weights A depends on more firmly than the others. EWC concentrates the penalty on the weights with a large Fisher value and leaves the rest free for B.
- EWC or L2-SP (they need only the old weights and, for EWC, a Fisher computed while the old data was still available), distillation from the old model on new inputs, or parameter isolation with adapters (needs the task identity at prediction time).
Test yourself
What is catastrophic forgetting?
- A model that never converges
- The loss of performance on earlier tasks after training on new data
- Overfitting to the validation set
- Deleting old checkpoints
In EWC, what does a large Fisher value F_i for a weight mean?
- The weight is unimportant for the old task and may move freely
- The old task's loss is sensitive to that weight, so it is held close to its old value
- The weight is frozen permanently
- The weight was initialised at zero
Which remedy needs stored examples of the old task?
- L2-SP
- Replay (rehearsal)
- A lower learning rate
- LoRA with the adapter switched off for the old task