AI Logic

Continual Learning

Elastic Weight Consolidation (EWC)

Updated:

EWC training flow. The left shows the weights being updated with the sum of the task B loss and a penalty built from the trained task A weights and the Fisher information; the right shows a two-weight parameter space with three learning paths (no penalty, uniform L2, EWC) and the regions where the task A and task B errors are small

Background and overview

EWC (Elastic Weight Consolidation) is a continual learning method that, when a neural network learns several tasks one after another, adds a penalty to the loss that makes weights harder to move the more important they were for previous tasks, so that earlier tasks are not forgotten. It was proposed in 2017 by Kirkpatrick et al. at DeepMind and published in PNAS.

If a neural network learns task A and then learns only task B, its performance on task A drops sharply. Moving the weights to fit B's data also overwrites weights that A needed. This phenomenon is called catastrophic forgetting. It can be prevented by retraining on a mix of data from all tasks, but that is not possible when past data cannot be kept or when tasks keep arriving.

EWC is inspired by "synaptic consolidation" in the brain (the mechanism by which synapses strengthened through learning become harder to change). Picture each weight tied to its value from the previous task, θA∗\theta^*_A, by a spring, with stiff springs on important weights and soft springs on unimportant ones. The word "Elastic" in the name comes from these springs.

For example, if changing a weight slightly increases task A's error sharply, that weight matters for A, so it is barely moved. Conversely, weights whose changes barely affect A's error are freely used for B. Networks usually have more weights than strictly necessary, so EWC assumes that weights solving B while keeping A's error low can often be found near θA∗\theta^*_A.

Loss function and Fisher information

With EWC, learning task B after task A proceeds as follows.

  1. Train on task A as usual and save the resulting weights θA∗\theta^*_A.
  2. Using task A's data, compute the importance of each weight (the diagonal of the Fisher information matrix, FiF_i) and save it.
  3. Train on task B with the loss L(θ)L(\theta) below. Task A's data is not used.
  4. When moving on to task C, add the penalties for both A and B (the sum of two quadratic penalties is itself a quadratic penalty, so they can also be merged into one).

The loss in step 3 is Eq. (3) of the paper.

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 LB(θ)L_B(\theta) is the loss for task B alone, ii indexes the weights, θA,i∗\theta^*_{A,i} is the ii-th weight after learning task A, FiF_i is that weight's importance for task A, and λ\lambda is a coefficient that sets how much the old task matters relative to the new one. The penalty is a squared distance weighted per weight by FiF_i, so weights with larger FiF_i stay closer to θA,i∗\theta^*_{A,i}.

This formula follows from a probabilistic argument. Rewriting the probability of the weights given all the data D\mathcal{D} (=DA= \mathcal{D}_A and DB\mathcal{D}_B) with Bayes' theorem gives the following.

log⁡p(θ∣D)=log⁡p(DB∣θ)+log⁡p(θ∣DA)−log⁡p(DB)\log p(\theta \mid \mathcal{D}) = \log p(\mathcal{D}_B \mid \theta) + \log p(\theta \mid \mathcal{D}_A) - \log p(\mathcal{D}_B)

The first term on the right is (the negative of) the task B loss, and everything that needs to be known about task A is contained in the second term, p(θ∣DA)p(\theta \mid \mathcal{D}_A). Since this is hard to compute exactly, it is approximated by a Gaussian with mean θA∗\theta^*_A and precision (inverse variance) given by the diagonal of the Fisher information matrix FF (the Laplace approximation). The log of a Gaussian is quadratic, which yields the penalty in the loss above.

The Fisher information matrix has three properties, listed in the paper, that make it well suited to measuring weight importance.

  • Near a minimum, it equals the second derivative (curvature) of the loss: the steeper the curvature in a direction, the more the loss increases with even a small step.
  • It can be computed from first derivatives alone: it is easy to compute even for large models.
  • It is always positive semidefinite: the penalty is never negative.

In practice, compute the gradient of the model's output log-probability log⁡p(y∣x,θ)\log p(y \mid x, \theta) on task A data xx, and average its square to obtain FiF_i.

EWC stores only the weights θ∗\theta^* and the Fisher information diagonal FF for each task, not the past data itself. The amount stored is twice the number of weights, independent of the amount of data.

Experiments in the paper and caveats

The paper evaluates EWC in two settings: supervised learning and reinforcement learning.

For supervised learning, the pixels of MNIST images were shuffled with a fixed random order per task, and the resulting tasks were learned in sequence (permuted MNIST). All tasks are equally difficult, but each requires its own solution. Comparing three training approaches with a fully connected network (two hidden layers of 400 units in Figure 2A) gave the following results.

Training approachPrevious task ANew task BReason
SGD onlyForgotten quicklyLearnedWeights needed for A are overwritten for B
Uniform L2 regularizationRetainedNot learned wellAll weights are anchored with the same strength, leaving no room for B
EWCRetainedLearnedOnly weights important for A are anchored strongly

In a comparison with SGD using dropout and early stopping, the latter's performance degraded as tasks were added, whereas EWC's error rate grew only slightly even after learning many tasks in sequence. Examining the overlap of the Fisher information between two tasks also showed that the more different the tasks, the more they used separate weights in layers near the input, while sharing the same weights in layers near the output.

For reinforcement learning, 10 Atari 2600 games were chosen and a DQN (deep Q-network) agent learned them in sequence (returning to the same games many times). Without EWC, the agent only ever learned to play one game, and the total score over the 10 games (human-level performance scaled to 1, with each game capped at 1, for a maximum of 10) stayed below 1. With EWC, the agent learned to play several games. The EWC penalty was applied only after more than 20 million frames of experience with each game.

Using EWC requires knowing when the task switches (since θ∗\theta^* and FF are saved at that point). In addition, the posterior is approximated by a Gaussian using only its diagonal, so relationships between weights are ignored. The paper itself notes as a weakness that this approximation can make the estimated weight importance overconfident. λ\lambda was also chosen by hyperparameter search in the paper and needs tuning for each dataset and model.

Comparison with other continual learning methods

Continual learning methods can be compared by what they keep from past tasks and how they avoid forgetting.

MethodWhat is keptMechanism against forgettingSuited to
EWCWeights θ∗\theta^* and weight importance FFA quadratic penalty that keeps important weights in placePast data cannot be stored; task boundaries are known
Synaptic IntelligenceWeights and weight importanceThe same form of penalty as EWC, with importance computed online from how the weights move and the loss decreases during trainingAvoiding recomputation of importance at the end of each task
LwFOutputs of the previous modelPreserves the previous model's outputs on new-task data via knowledge distillationPast data cannot be stored, but the output behavior should be preserved
GEMA subset of past task dataCorrects the gradient direction so that the loss on stored data does not increaseA small amount of past data can be stored
iCaRLRepresentative samples per classPreserves representations with representative samples and knowledge distillation, and picks the class whose mean feature is nearestClassification where classes keep being added

EWC is the leading example of "protect the weights" methods that store no past data at all, making it suitable when data cannot be kept for privacy or storage reasons. On the other hand, if even a little past data can be stored, data-based methods such as GEM and iCaRL may forget less, so choose according to the conditions.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm

"""
Learn pixel-permuted MNIST (permuted MNIST) as three tasks in sequence,
using EWC to avoid forgetting earlier tasks
"""

# Hyperparameters
batch_size = 64       # batch size
epochs = 3            # epochs per task (Figure 2A of the paper uses 20)
learning_rate = 1e-2  # learning rate (Figure 2A of the paper uses 1e-3)
hidden_dim = 400      # hidden units (400 × 2 layers, as in the paper)
ewc_lambda = 1000     # penalty strength λ (tune for the data and model)
num_tasks = 3
fisher_samples = 1000 # number of images used to compute the Fisher information

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=256)

# Choose one pixel permutation per task (task 0 is the original MNIST)
torch.manual_seed(0)
perms = [torch.arange(784)] + [torch.randperm(784) for _ in range(num_tasks - 1)]

model = nn.Sequential(
  nn.Flatten(),
  nn.Linear(784, hidden_dim), nn.ReLU(),
  nn.Linear(hidden_dim, hidden_dim), nn.ReLU(),
  nn.Linear(hidden_dim, 10),
).to(device)


def permute(images, perm):
  return images.view(images.size(0), -1)[:, perm]


def fisher_diagonal(perm):
  """Compute the Fisher information diagonal F_i = E[(∂ log p(y|x, θ) / ∂θ_i)^2] as the mean squared gradient over single images"""
  fisher = {n: torch.zeros_like(p) for n, p in model.named_parameters()}
  model.eval()
  loader = DataLoader(train_dataset, batch_size=1, shuffle=True)
  for k, (image, _) in enumerate(loader):
    if k == fisher_samples:
      break
    log_probs = F.log_softmax(model(permute(image.to(device), perm)), dim=1)
    y = torch.multinomial(log_probs.exp(), 1).item()  # sample the label from the model's predictive distribution
    model.zero_grad()
    log_probs[0, y].backward()
    for n, p in model.named_parameters():
      fisher[n] += p.grad.detach() ** 2 / fisher_samples
  return fisher


def ewc_penalty(memories):
  """(λ/2) Σ_task Σ_i F_i (θ_i − θ*_i)^2"""
  loss = 0.0
  for fisher, old_params in memories:
    for n, p in model.named_parameters():
      loss = loss + (fisher[n] * (p - old_params[n]) ** 2).sum()
  return ewc_lambda / 2 * loss


def evaluate(perm):
  model.eval()
  correct = 0
  with torch.no_grad():
    for images, labels in test_loader:
      images, labels = images.to(device), labels.to(device)
      correct += (model(permute(images, perm)).argmax(dim=1) == labels).sum().item()
  return 100 * correct / len(test_dataset)


optimizer = optim.SGD(model.parameters(), lr=learning_rate)
memories = []  # (F, θ*) for each finished task

for task, perm in enumerate(perms):
  for epoch in tqdm(range(epochs), desc=f"task {task}"):
    model.train()
    for images, labels in train_loader:
      images, labels = images.to(device), labels.to(device)
      loss = F.cross_entropy(model(permute(images, perm)), labels)
      if memories:
        loss = loss + ewc_penalty(memories)  # L(θ) = L_B(θ) + penalty
      optimizer.zero_grad()
      loss.backward()
      optimizer.step()

  # Remember this task's weights θ* and Fisher information F
  old_params = {n: p.detach().clone() for n, p in model.named_parameters()}
  memories.append((fisher_diagonal(perm), old_params))

  accs = [f"{evaluate(perms[t]):.2f}%" for t in range(task + 1)]
  print(f"after task {task}: accuracy on tasks 0..{task} = {accs}")

FAQ

Q. How does it differ from ordinary L2 regularization (weight decay)?
A.

Weight decay pulls weights toward 0, applying the same strength to all of them. EWC pulls weights toward their values from the previous task, θ*_A, and varies the strength per weight according to its importance as measured by the Fisher information. In the paper's permuted MNIST experiment, a uniform L2 penalty toward the previous task's values protected the previous task but could not learn the new one, while EWC handled both.

Q. Does the penalty keep growing as more tasks are added?
A.

Adding a penalty per task means the stored θ* and F also grow with the number of tasks. However, the paper notes that a sum of quadratic penalties is again a single quadratic penalty, so they can be merged and stored as one.

Q. Can the ground-truth labels be used to compute the Fisher information?
A.

The Fisher information by definition is computed with labels sampled from the model's predictive distribution (the code example does this). The "empirical Fisher", computed with the ground-truth labels, is also widely used and is simpler to compute, but it is a different quantity from the definition, so results may differ.

References

  1. Kirkpatrick, J., Pascanu, R., Rabinowitz, N., Veness, J., Desjardins, G., Rusu, A. A., Milan, K., Quan, J., Ramalho, T., Grabska-Barwinska, A., Hassabis, D., Clopath, C., Kumaran, D., & Hadsell, R. (2017). Overcoming catastrophic forgetting in neural networks. Proceedings of the National Academy of Sciences, 114(13), 3521–3526.
  2. Kirkpatrick, J., et al. (2016). Overcoming catastrophic forgetting in neural networks. arXiv:1612.00796.
  3. Zenke, F., Poole, B., & Ganguli, S. (2017). Continual Learning Through Synaptic Intelligence. ICML 2017.
  4. Li, Z., & Hoiem, D. (2016). Learning without Forgetting. ECCV 2016.
  5. Lopez-Paz, D., & Ranzato, M. (2017). Gradient Episodic Memory for Continual Learning. NeurIPS 2017.
  6. Rebuffi, S.-A., Kolesnikov, A., Sperl, G., & Lampert, C. H. (2017). iCaRL: Incremental Classifier and Representation Learning. CVPR 2017.