AI Logic

Continual Learning

Gradient Episodic Memory (GEM)

Updated:

Training flow of GEM. The left side shows the flow: compute the gradient g on the new example and the gradient g_k on each previous task's memory; if an inner product is negative, solve the dual problem to project the gradient; then update the weights. The right side shows gradient space: when the new example's gradient g forms an obtuse angle with the previous task's gradient g_1, it is corrected to the closest direction g~ on the boundary orthogonal to g_1

Background and Overview

GEM (Gradient Episodic Memory) is a continual learning method that stores a small number of examples from past tasks in memory and, every time the weights are updated on a new example, uses gradient inner products to check whether the direction "does not increase the loss on the stored examples"; if it would increase that loss, the gradient is corrected to the closest safe direction before updating. Lopez-Paz and Ranzato of Facebook AI Research presented it at NIPS (now NeurIPS) in 2017.

The GEM paper frames continual learning in the following setting, which is closer to how humans learn.

  • There are many tasks, and each task has few examples
  • Examples arrive one at a time (or in small minibatches), and the same example is never seen twice
  • Each example comes with a task descriptor tt indicating which task it belongs to (in this paper, an integer task index)

Training with plain SGD in this setting increases the loss on previous tasks every time the weights move to fit examples from a new task, so the model forgets previous tasks.

GEM's key idea is to treat the loss on previous tasks not as something added to the "objective" but as a constraint that it "must not increase." Methods that use previous-task examples to preserve outputs (knowledge distillation, as in iCaRL) aim to "not change" the outputs on previous tasks, so performance on previous tasks never improves either. GEM only requires that the loss "not increase," leaving room for learning a new task to improve performance on previous tasks (positive backward transfer).

Picture descending a mountain path: you move in the direction you want to go (the new task's gradient) while choosing only directions that do not take you away from important places you passed earlier (the previous tasks). If the direction you want would take you away from an important place, you adjust it to the direction that is as close as possible to it while not moving away.

Along with the method, the paper also proposes three metrics for evaluating continual learning: average accuracy (ACC), backward transfer (BWT), and forward transfer (FWT).

Procedure and Constraint Formulas

GEM keeps an episodic memory Mk\mathcal{M}_k for each task. With a total memory size of MM and TT tasks, it stores m=M/Tm = M/T examples per task (in the paper, the last mm examples of each task). The loss on the examples of task kk in memory is written as follows (Eq. (5) of the paper).

ℓ(fθ,Mk)=1∣Mk∣∑(xi,k,yi)∈Mkℓ(fθ(xi,k),yi)\ell(f_\theta, \mathcal{M}_k) = \frac{1}{|\mathcal{M}_k|} \sum_{(x_i, k, y_i) \in \mathcal{M}_k} \ell\big(f_\theta(x_i, k), y_i\big)

When it receives an example (x,t,y)(x, t, y) of task tt, GEM aims to solve the following problem (Eq. (6) of the paper).

min⁡θ ℓ(fθ(x,t),y)subject toℓ(fθ,Mk)≤ℓ(fθt−1,Mk)  for all k<t\min_\theta \ \ell\big(f_\theta(x, t), y\big) \quad \text{subject to} \quad \ell(f_\theta, \mathcal{M}_k) \le \ell(f_\theta^{t-1}, \mathcal{M}_k) \ \ \text{for all } k < t

fθt−1f_\theta^{t-1} is the model at the end of learning task t−1t-1. This problem is solved approximately at each update with the following steps (Algorithm 1 of the paper).

  1. Add the example (x,y)(x, y) to the memory Mt\mathcal{M}_t of task tt.
  2. Compute the gradient of the loss on the new example, g=∇θℓ(fθ(x,t),y)g = \nabla_\theta \ell(f_\theta(x, t), y).
  3. For each previous task k<tk < t, compute the gradient of the memory loss, gk=∇θℓ(fθ,Mk)g_k = \nabla_\theta \ell(f_\theta, \mathcal{M}_k).
  4. If ⟨g,gk⟩≥0\langle g, g_k \rangle \ge 0 for all kk, use gg as is. If even one is negative, project gg onto the closest gradient g~\tilde g that satisfies the condition.
  5. Update the weights with θ←θ−αg~\theta \leftarrow \theta - \alpha \tilde g (α\alpha is the learning rate).

The condition in step 4 is Eq. (7) of the paper.

⟨g,gk⟩=⟨∂ℓ(fθ(x,t),y)∂θ,∂ℓ(fθ,Mk)∂θ⟩≥0for all k<t\langle g, g_k \rangle = \left\langle \frac{\partial \ell(f_\theta(x, t), y)}{\partial \theta}, \frac{\partial \ell(f_\theta, \mathcal{M}_k)}{\partial \theta} \right\rangle \ge 0 \quad \text{for all } k < t

Within a small step the loss can be treated as nearly linear, so if the inner product is nonnegative, moving in that direction does (almost) not increase the memory loss of task kk. If an inner product is negative, the gradient is corrected by solving the following problem (Eq. (8) of the paper).

min⁡g~ 12∥g−g~∥22subject to⟨g~,gk⟩≥0  for all k<t\min_{\tilde g} \ \frac{1}{2} \| g - \tilde g \|_2^2 \quad \text{subject to} \quad \langle \tilde g, g_k \rangle \ge 0 \ \ \text{for all } k < t

This is a quadratic program, but the number of variables in g~\tilde g equals the number of network parameters pp (which can be in the millions). So, using the matrix G=(g1,…,gt−1)G = (g_1, \dots, g_{t-1}) whose rows are the previous tasks' gradients, GEM solves the dual problem, whose number of variables is only the number of tasks t−1t - 1 (Eq. (11) of the paper).

min⁡v 12v⊤GG⊤v+g⊤G⊤vsubject tov≥0\min_{v} \ \frac{1}{2} v^\top G G^\top v + g^\top G^\top v \quad \text{subject to} \quad v \ge 0

From its solution v⋆v^\star, the corrected gradient is obtained as g~=G⊤v⋆+g\tilde g = G^\top v^\star + g. The paper notes that adding a small constant γ≥0\gamma \ge 0 to v⋆v^\star biases the update toward directions that lower the previous tasks' losses, making positive backward transfer more likely (the experiments choose γ=0.5\gamma = 0.5).

With only one previous task (t=2t = 2) and γ=0\gamma = 0, the projection amounts to "subtracting from gg only the conflicting part of its component along g1g_1": g~=g−⟨g,g1⟩∥g1∥2g1\tilde g = g - \dfrac{\langle g, g_1 \rangle}{\|g_1\|^2} g_1 (when ⟨g,g1⟩<0\langle g, g_1 \rangle < 0). The corrected gradient g~\tilde g is orthogonal to g1g_1, a direction that neither increases nor decreases the loss on task 1.

Why It Resists Forgetting

GEM resists forgetting previous tasks because it removes, at every step, the part of the update that would increase the loss on previous tasks. How the loss changes in one step of gradient descent is approximately determined by "the inner product of the gradient and the step direction." If the inner product of the new task's gradient gg and a previous task's gradient gkg_k is negative, moving along gg increases the loss on task kk. GEM removes only this component and keeps the rest as much as possible.

Unlike other methods, it has no coefficient that sets the "strength" of protecting previous tasks.

MethodHow previous tasks are handledPerformance on previous tasks
EWCAdds a penalty to the loss that pulls weights back toward their previous values (strength λ\lambda must be chosen)Limits the drop
iCaRL, LwFAdds a loss that keeps previous-task outputs close to recorded outputsKept unchanged
GEMConstrains the update direction so that the memory loss of previous tasks does not increaseNot allowed to get worse; allowed to improve

Using memory examples directly for training (minimizing their loss together with new examples) tends to overfit the few stored examples. GEM uses the stored examples only to check gradient directions, which avoids this problem.

The dual problem has only t−1t - 1 variables (the number of tasks), so the quadratic program itself is small and solved quickly even for networks with many parameters. The expensive part is computing the memory gradient gkg_k for each previous task.

Experiments in the Paper

The paper evaluates on the following three datasets, learning 20 tasks in sequence, one pass each.

DatasetHow tasks are builtExamples per taskNetwork
MNIST PermutationsPermute the pixels of MNIST in a fixed order per task1000MLP with two hidden layers of 100 units (ReLU)
MNIST RotationsRotate MNIST digits by a fixed angle per task (0 to 180 degrees)1000Same as above
Incremental CIFAR100Split the 100 classes of CIFAR-100 into tasks of 5 classes each2500ResNet18 with feature maps reduced to 1/3 (a separate output layer per task)

Every method is trained with SGD with a minibatch size of 10, and hyperparameters are chosen by grid search. GEM's memory holds 5120 examples in total.

Evaluation uses the matrix of Ri,jR_{i,j}, the test accuracy on task jj after finishing task ii, to compute the following three metrics (Eqs. (2) to (4) of the paper; bˉi\bar b_i is the accuracy on task ii at random initialization before training).

ACC=1T∑i=1TRT,i,BWT=1T−1∑i=1T−1(RT,i−Ri,i),FWT=1T−1∑i=2T(Ri−1,i−bˉi)\text{ACC} = \frac{1}{T} \sum_{i=1}^{T} R_{T,i}, \qquad \text{BWT} = \frac{1}{T-1} \sum_{i=1}^{T-1} \big(R_{T,i} - R_{i,i}\big), \qquad \text{FWT} = \frac{1}{T-1} \sum_{i=2}^{T} \big(R_{i-1,i} - \bar b_i\big)

ACC measures how well all tasks are solved at the end, BWT measures how much performance on previous tasks changed from learning later tasks (strongly negative means forgetting), and FWT measures how much performance improved on tasks not yet learned.

The results on MNIST Rotations when varying how many times each task's data is seen (number of epochs) are as follows (Table 3 of the paper; ACC / BWT).

Method1 epoch2 epochs5 epochs
Single network trained sequentially0.53 / −0.080.49 / −0.250.43 / −0.40
EWC0.55 / −0.190.59 / −0.170.61 / −0.11
GEM0.86 / +0.050.88 / +0.020.89 / −0.02
Reference: training on all tasks' data mixed0.83 / −0.000.87 / −0.000.89 / −0.00

The last row trains on shuffled data from all tasks; it is not continual learning and serves as a rough upper bound. GEM reaches almost the same ACC, and with 1 epoch its BWT was positive (performance on previous tasks improved).

The results on Incremental CIFAR100 comparing against iCaRL with different memory sizes are as follows (Table 2 of the paper; final ACC).

Memory size200128025605120
GEM0.4870.5790.6330.654
iCaRL0.4360.4940.5000.508

GEM beat iCaRL at every memory size, and its performance improved as the memory grew. The paper summarizes the results in Figure 1 as GEM performing much better than other continual learning methods such as EWC, with the least forgetting (negative BWT). On CIFAR100, it also shows the accuracy on the first task rising while later tasks are learned (positive backward transfer).

As for compute time, the CPU training time in the MNIST experiments was 11 seconds for the single network trained sequentially, 179 seconds for EWC, and 77 seconds for GEM on MNIST Permutations, and likewise 11 seconds, 169 seconds for EWC, and 135 seconds for GEM on MNIST Rotations (Table 1 of the paper).

Practical Considerations

GEM must compute a memory gradient for each previous task at every update (the number of backward passes grows with the number of tasks). The paper itself lists this as a weakness in compute time. With many tasks, each update becomes heavy. Also, since it stores examples from previous tasks, it cannot be used when data must not be retained.

  • It uses task indices: GEM is designed for a setting where the task of each example is known during training. In the paper's CIFAR100 experiments, each task has its own output layer, selected by the task index (for MNIST, the paper states that predictions can be made without the task index).
  • The approximation assumes small steps: judging loss increases and decreases by inner products works when the loss is nearly linear within one step. With a large learning rate, the loss on previous tasks may increase even if the condition is satisfied. It also assumes that the memory adequately represents the previous tasks' examples.
  • Memory selection is simple: the paper stores the last mm examples of each task and leaves better selection strategies (such as per-task coresets) to future work.
  • Tuning γ\gamma: the paper chose γ\gamma, the value added to v⋆v^\star, by grid search over 0 to 1, and 0.5 was selected for all three datasets.

Comparison with Other Continual Learning Methods

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

MethodWhat is keptMechanism against forgettingPerformance on previous tasksSuitable conditions
GEMA subset of examples per taskCorrects the gradient direction so the loss on stored examples does not increasePrevents drops and allows improvementA few examples can be stored, and data can be seen only once
iCaRLExemplar images per classMixes exemplars into training and preserves previous outputs with knowledge distillationKept unchangedA single classifier whose classes keep growing
LwFThe original networkPreserves previous-task outputs on new data with knowledge distillationKept unchangedNo previous data can be kept at all
EWCWeights and their importanceA quadratic penalty that keeps important weights from movingLimits the dropPrevious data cannot be stored; task boundaries are known
Synaptic IntelligenceWeights and their importanceThe same form of penalty as EWC, with importance computed during trainingLimits the dropSame conditions as EWC, when importance should be computed alongside training

If a few examples from previous tasks can be stored and task indices are known, GEM not only protects performance on previous tasks but also leaves room to improve it. When there are many tasks and the per-update gradient computation is too heavy, or when examples cannot be stored, consider methods such as EWC, SI, or LwF.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
GEM: project the gradient before updating so that the memory loss of previous tasks does not increase
  (a small implementation of Eqs. (7)(8)(11) and Algorithm 1 of the paper; the quadratic program is solved with projected gradient descent)
"""

memory_per_task = 256  # number of examples stored per task, m
margin = 0.5           # γ added to v* (the value chosen in the paper's experiments)
lr = 0.1


def flat_grad(model):
  return torch.cat([(p.grad if p.grad is not None else torch.zeros_like(p)).reshape(-1) for p in model.parameters()])


def set_grad(model, g):
  i = 0
  for p in model.parameters():
    n = p.numel()
    p.grad = g[i:i + n].view_as(p).clone()
    i += n


def project(g, G, gamma=margin, steps=200):
  """Solve the dual problem of Eq. (11)  min_v 1/2 v^T G G^T v + g^T G^T v  (v >= 0) and return g~ = G^T v* + g"""
  GG = G @ G.T                    # (t-1) x (t-1): only as many variables as tasks
  Gg = G @ g
  v = torch.zeros(G.size(0), device=g.device)
  step = 1.0 / (GG.diagonal().sum() + 1e-12)
  for _ in range(steps):           # projected gradient descent (keep v >= 0)
    v = (v - step * (GG @ v + Gg)).clamp(min=0)
  v = v + gamma                    # paper: adding a small constant γ makes positive backward transfer more likely
  return G.T @ v + g


class GEM:
  def __init__(self, model):
    self.model = model
    self.opt = torch.optim.SGD(model.parameters(), lr=lr)
    self.memory = {}  # task index -> (x, y)

  def observe(self, x, t, y):
    """Learn from examples (a minibatch) of task t, seeing them only once. model(x, t) returns the output for task t"""
    # 1. Add to memory (keep the last m examples of each task)
    mx, my = self.memory.get(t, (x[:0], y[:0]))
    self.memory[t] = (torch.cat([mx, x])[-memory_per_task:], torch.cat([my, y])[-memory_per_task:])

    self.model.train()
    # 3. For each previous task, compute the gradient g_k of the memory loss
    past = [k for k in self.memory if k < t]
    G = []
    for k in past:
      self.model.zero_grad()
      kx, ky = self.memory[k]
      F.cross_entropy(self.model(kx, k), ky).backward()
      G.append(flat_grad(self.model))

    # 2. Gradient g of the loss on the new examples
    self.model.zero_grad()
    F.cross_entropy(self.model(x, t), y).backward()

    # 4. Project if any inner product <g, g_k> is negative
    if G:
      g, G = flat_grad(self.model), torch.stack(G)
      if (G @ g < 0).any():
        set_grad(self.model, project(g, G))

    # 5. θ ← θ − α g~
    self.opt.step()


# Usage example (stream the data once):
#   gem = GEM(model)
#   for x, t, y in continuum:   # (image, task index, label)
#     gem.observe(x, t, y)
#   model.eval(); pred = model(test_x, t).argmax(dim=1)

FAQ

Q. How does it differ from simply mixing stored examples into training (replay)?
A.

Training on stored examples together with new ones makes lowering the loss on previous tasks part of the objective, which tends to overfit the few stored examples. GEM uses the stored examples' gradients only to check whether the update for the new task would increase the loss on previous tasks, and removes only the components that would.

Q. When should GEM be chosen over EWC?
A.

If a few examples from previous tasks can be stored, GEM tends to forget less. In the paper's MNIST Rotations experiment (1 epoch), ACC was 0.86 for GEM versus 0.55 for EWC. If examples cannot be stored, or there are so many tasks that the per-update gradient computation is too heavy, EWC is the better fit.

Q. What does a positive BWT mean?
A.

It means that, as a result of learning later tasks, test performance on a previous task rose above its level right after that task was learned. GEM only requires that the loss on previous tasks "not increase," so if an update for the new task also helps previous tasks, it proceeds as is. On MNIST Rotations (1 epoch) in the paper, BWT was +0.05.

References

  1. Lopez-Paz, D., & Ranzato, M. (2017). Gradient Episodic Memory for Continual Learning. NIPS 2017.
  2. Implementation of GEM by the authors (GitHub)
  3. Kirkpatrick, J., et al. (2017). Overcoming catastrophic forgetting in neural networks. Proceedings of the National Academy of Sciences, 114(13), 3521–3526.
  4. Rebuffi, S.-A., Kolesnikov, A., Sperl, G., & Lampert, C. H. (2017). iCaRL: Incremental Classifier and Representation Learning. CVPR 2017.