Continual Learning for Vision: EWC, Replay, and Prompts
Module: Computer Vision | Difficulty: Premium
Prerequisites
- !Fine-tuning a pretrained classifier
- !Fisher information and diagonal approximations
- !Benchmark design and train/test splits
What You'll Learn
- 1State the incremental protocol your system actually faces
- 2Compute Fisher weights without biasing the penalty toward output layers
- 3Build a bounded replay buffer with sensible exemplar selection
- 4Adapt a frozen foundation model with a prompt pool
- 5Report forward and backward transfer, not just final average accuracy
Forgetting is the default, not an accident
Fine-tuning a classifier on a new class set updates every weight that the new loss depends on, which is nearly all of them. Weights that encoded earlier classes drift, and accuracy on those classes falls off a cliff within a few epochs. This is catastrophic forgetting, and it is not a bug in the optimizer; it is gradient descent doing exactly what the current objective asks. The objective simply has no term for the past.
The practical stakes are mundane and everywhere. A retail shelf-scanner learns a new product line every quarter. A pathology classifier gains cancer subtypes as new cohorts arrive. A phone camera app picks up new scene modes. In each case the deployment constraint is the same: keep the old classes working, absorb the new ones, and do it without a full retrain on data you no longer have.
Name the protocol before you name the method
Continual learning is a family of settings, and mixing them up invalidates comparisons. Class-incremental learning is the hardest and most realistic: classes arrive in disjoint batches and the model must classify across all seen classes at test time without being told which task is active. Task-incremental learning hands the task identity at test time, which lets the model restrict its output space and is far easier. Domain-incremental keeps the classes fixed while the input distribution drifts.
| Protocol | Task ID at test time | Output space | Typical evaluation |
|---|---|---|---|
| Class-incremental | No | All seen classes | Final average accuracy |
| Task-incremental | Yes | Classes of the current task | Per-task accuracy |
| Domain-incremental | No | Fixed | Accuracy under drift |
| Task-free | No, streams shift silently | All seen classes | Windowed accuracy |
State the protocol, the class ordering, and whether the ordering was randomized. Results on a single convenient ordering are not evidence, because variance across orderings can exceed the gap between methods.
Elastic weight consolidation, computed correctly
EWC adds a quadratic penalty keeping important parameters near their old values. Importance is estimated with the diagonal Fisher information, which measures how much the loss responds to perturbing each weight on the old task. The subtlety is the estimation: computing the Fisher on the full softmax penalizes the output layer disproportionately and largely fails to protect the early features that actually carry class information.
import torch
import torch.nn.functional as F
class EWCRegularizer:
def __init__(self, model, ewc_lambda=1000.0, fisher_batches=60):
self.model = model
self.lam = ewc_lambda
self.n = fisher_batches
self.fisher = {}
self.anchor = {}
@torch.no_grad()
def _snapshot(self):
self.anchor = {n: p.detach().clone()
for n, p in self.model.named_parameters()}
def estimate_fisher(self, loader, device):
self.model.eval()
self._snapshot()
self.fisher = {n: torch.zeros_like(p)
for n, p in self.model.named_parameters()}
heads = {n for n, _ in self.model.named_parameters()
if n.startswith("fc") or "head" in n}
seen = 0
for x, y in loader:
x, y = x.to(device), y.to(device)
logits = self.model(x)
probs = F.softmax(logits, dim=1)
for cls in range(logits.shape[1]):
self.model.zero_grad(set_to_none=True)
# sample a label from the model, then backprop its log-prob
target = torch.full_like(y, cls)
logp = F.log_softmax(logits, dim=1)
loss = -logp.gather(1, target.unsqueeze(1)).mean()
loss.backward(retain_graph=True)
for n, p in self.model.named_parameters():
if p.grad is None:
continue
weight = 0.0 if n in heads else 1.0
self.fisher[n] += weight * p.grad.detach() ** 2
seen += 1
if seen >= self.n:
break
for n in self.fisher:
self.fisher[n] /= max(seen, 1)
def penalty(self):
loss = 0.0
for n, p in self.model.named_parameters():
if n in self.fisher:
loss = loss + (self.fisher[n] *
(p - self.anchor[n]) ** 2).sum()
return self.lam * loss
ewc = EWCRegularizer(model, ewc_lambda=500.0)
ewc.estimate_fisher(old_task_loader, device)
for x, y in new_task_loader:
logits = model(x)
loss = F.cross_entropy(logits, y) + ewc.penalty()
loss.backward()
opt.step()
Zeroing the weight on the classifier head is deliberate. The head has to move to represent new classes; freezing it is what task-incremental methods get away with and class-incremental methods cannot.
Replay buffers remain the strongest practical tool
Storing a small number of examples from earlier tasks and mixing them into new training beats every regularization-only approach by a wide margin, and it does so for an obvious reason: the old data directly constrains the old behavior instead of approximating it with a quadratic bowl. The engineering question is which examples to keep when memory is bounded.
iCaRL popularized herding selection, which greedily picks exemplars whose class-conditional mean stays close to the running prototype. Random selection is a surprisingly strong baseline, and class-balanced sampling matters more than the within-class selection rule. Training then alternates new-task batches with replay batches, often at a ratio near one to one.
Legal constraints frequently forbid storing raw images, particularly faces and medical scans. Two escapes exist. Feature-level replay keeps intermediate activations instead of pixels and trains the head to reproduce old logits, which retains most of the benefit. Alternatively, generate synthetic exemplars from a class-conditional generator trained with differential privacy, accepting the added complexity in exchange for never retaining user data.
Prompt pools on frozen foundations
Once backbones became large enough, the strategy inverted. Instead of protecting weights, freeze everything and learn a pool of prompt vectors, one small key network that selects a prompt per image, and only the prompts train. Because the backbone is untouched, forgetting on old tasks is close to zero by construction, and each new task adds a few thousand parameters rather than overwriting millions.
The selection mechanism is the interesting part. Keys are stored per task, and the query image retrieves the nearest key, so the right prompt is applied without a task identifier at test time. Later variants allow several prompts to be combined per image, which helps when a single task spans multiple visual domains. The cost is a small accuracy gap on the first task compared with full fine-tuning, and a memory footprint that grows with the number of tasks, however slowly.
Beyond task boundaries: streams that never announce themselves
The clean incremental protocol assumes you are told when a new task starts. Real streams rarely are. A camera on a production line sees product mix change gradually, and a classification boundary that looked stable last month has quietly moved. Task-free continual learning removes the boundary signal and requires the system to detect novelty on its own, typically by monitoring the distance between incoming embeddings and the stored class prototypes, or by watching the prediction entropy distribution for a sustained shift.
The practical architecture for this setting keeps a small memory of recent embeddings, updates class prototypes with an exponential moving average, and triggers a guarded fine-tune when the novelty score crosses a threshold. The guard matters more than the detector: without it, a burst of out-of-distribution frames â a lens smear, a lighting failure â starts a training run that clobbers the model. Requiring novelty to persist across several hundred frames before acting eliminates most false triggers, and it costs nothing but latency.
Evaluate this setting with windowed accuracy rather than end-of-stream accuracy, because end-of-stream numbers hide exactly the transient collapses that matter in production. Report how often the trigger fired, how many of those firings were correct, and how long recovery took after each legitimate shift.
Measuring stability and plasticity together
Final average accuracy alone cannot distinguish a method that remembers well from one that simply learns the last task quickly. Keep the full accuracy matrix, where entry R[i, j] is accuracy on task j after training task i, and derive the standard measures from it.
import torch
def continual_metrics(R):
"""R is a list of accuracy vectors, one per finished task."""
mat = torch.tensor(R, dtype=torch.float32)
T = mat.shape[0]
final = mat[-1].diag().mean().item()
bwt_terms = [mat[T - 1, j].item() - mat[j, j].item()
for j in range(T - 1)]
backward = sum(bwt_terms) / max(len(bwt_terms), 1)
fwt_terms = []
for j in range(1, T):
fwt_terms.append(mat[j - 1, j].item() - mat[0, j].item())
forward = sum(fwt_terms) / max(len(fwt_terms), 1)
return {"final_average_accuracy": final,
"backward_transfer": backward,
"forward_transfer": forward}
R = [
[0.91, 0.00, 0.00],
[0.62, 0.88, 0.00],
[0.55, 0.71, 0.86],
]
print(continual_metrics(R))
# final average 0.707, backward transfer negative, forward transfer near zero
Backward transfer near zero with a high final average means the method remembered. A strongly negative value means forgetting dominated. Report both alongside memory footprint in images or parameters, because a method that stores ten exemplars per class and one that stores none are not competing on equal terms.
Common Mistakes
Reporting only final average accuracy on one class ordering
Fix: Publish the full accuracy matrix, backward transfer, and results over several randomized orderings
Estimating Fisher information only on the classifier head
Fix: Down-weight or exclude head parameters so the penalty protects the feature extractor that carries old knowledge
Filling the replay buffer with the most recent examples rather than a class-balanced sample
Fix: Balance classes and prefer herding or random selection within class over recency
Applying task-incremental evaluation to a deployment that never supplies task identity
Fix: Match the protocol to the product, which almost always means class-incremental evaluation
Best Practices
- Freeze a strong pretrained backbone and learn prompts when memory and compute allow, since it eliminates forgetting structurally
- Keep a class-balanced replay buffer and mix replay into every training epoch rather than fine-tuning first
- Track per-class accuracy after each task, because averages hide the collapse of rare old classes
- Record the buffer size and selection rule with every checkpoint so comparisons stay honest
- Revisit the learning rate; continual schedules typically need an order of magnitude less than from-scratch training
Interview Questions
Q1: Why does elastic weight consolidation underperform replay in class-incremental learning?
The quadratic penalty approximates the old loss locally, and that approximation degrades as new-task training moves parameters far away. Replay re-imposes the actual old constraints at the current parameters, so it stays accurate however far the model drifts.
Q2: What do backward and forward transfer measure?
Backward transfer is how much training later tasks changed accuracy on earlier ones, negative when forgetting occurred. Forward transfer measures how much prior training helped on a task not yet seen. Both expose behaviors that final average accuracy hides.
Q3: How do you do rehearsal when storing raw images is illegal?
Store intermediate features or old logits instead of pixels and train the new model to match them, or generate synthetic exemplars from a differentially privately trained generator. Feature replay is simpler and usually sufficient.
Q4: Why do prompt-based methods avoid forgetting?
The backbone is frozen, so no update can overwrite old knowledge. Each task adds its own prompt vectors, and a small key network selects among them at test time, which keeps plasticity in the prompts and stability in the weights.
Key Takeaways
- Catastrophic forgetting is the natural outcome of optimizing only the current task loss
- Class-incremental evaluation without task identity is the protocol that matches real deployment
- EWC needs a carefully estimated Fisher with the classifier head excluded to be useful at all
- Bounded replay with class-balanced selection remains the strongest general-purpose tool
- Prompt pools on frozen backbones trade a little accuracy for near-zero forgetting
- Report the full accuracy matrix, backward transfer, and memory cost, never just a final average
- Legal constraints on storing images push systems toward feature-level or synthetic replay