AI Logic

Continual Learning

iCaRL

Updated:

Training flow of iCaRL. The left side shows the flow: combine images of new classes with stored exemplars, record the outputs of the network before the update, update the feature extractor with classification and distillation losses, and reselect the exemplars. The right side shows a feature space normalized to length 1, with exemplars and their mean for each class; an input's feature is classified into the class with the closest mean

Background and Overview

iCaRL (incremental Classifier and Representation learning) is a continual learning method that, in settings where new classes to classify keep being added over time, stores a small number of representative images per class, learns while preserving its feature representation with those images and knowledge distillation, and classifies by choosing the class closest to the "mean feature of its representative images". Rebuffi, Kolesnikov, Sperl, and Lampert (University of Oxford and IST Austria) presented it at CVPR in 2017.

The paper calls this style of learning class-incremental learning and requires it to satisfy three conditions.

  • It can learn from a data stream in which examples of different classes appear at different times
  • At any point, it can classify all classes seen so far
  • Its compute and memory do not grow with the number of classes seen (or grow only very slowly)

Because of the third condition, "storing all past data and retraining" is not allowed. On the other hand, retraining the network only on data from new classes makes it stop predicting previous classes entirely (catastrophic forgetting). In the paper's experiments as well, a network trained with plain fine-tuning ended up predicting only the most recently learned classes.

iCaRL addresses this problem by combining three components.

  • Classification by the mean of exemplars: compute the mean feature (prototype) of the exemplars stored for each class, and choose the one closest to the input's feature
  • Exemplar selection (herding): select images to store one at a time, "in the order that brings their mean closest to the mean of the whole class"
  • Representation learning with exemplars and knowledge distillation: train on a mix of new-class images and stored exemplars, while pulling the outputs for previous classes toward those of the network before the update

Just as a child who learns about a new animal at the zoo does not forget the pet at home, the goal is to keep distinguishing old classes while learning new ones.

Procedure and Loss Formulas

The iCaRL network consists of a feature extractor φ\varphi and a classification layer with sigmoid outputs for each of the tt classes seen so far (Eq. (1) of the paper). Every feature φ(x)\varphi(x) is L2-normalized (scaled to length 1), and means are renormalized after averaging.

gy(x)=11+exp⁡(−ay(x)),ay(x)=wy⊤φ(x)g_y(x) = \frac{1}{1 + \exp(-a_y(x))}, \qquad a_y(x) = \boldsymbol{w}_y^\top \varphi(x)

When data Xs,…,XtX^s, \dots, X^t for new classes s,…,ts, \dots, t arrive, the procedure follows Algorithms 2 to 5 of the paper.

  1. Build the training set: combine the images of the new classes with the stored exemplars P1,…,Ps−1P_1, \dots, P_{s-1} of previous classes 1,…,s−11, \dots, s-1 into D\mathcal{D}.
  2. Record the outputs for previous classes: pass every image xix_i in D\mathcal{D} through the network before the update and record the previous-class outputs qiy=gy(xi)q_i^y = g_y(x_i) (y=1,…,s−1y = 1, \dots, s-1).
  3. Learn the representation: minimize the following loss ℓ(Θ)\ell(\Theta) by backpropagation.
  4. Reduce the number of exemplars: with KK as the total number of images the memory can store, set the number per class to m=K/tm = K/t. For previous classes, keep only the first mm exemplars in their ordering.
  5. Select exemplars for the new classes: for each new class, select and store mm images by herding.

The loss in step 3 is the sum of a classification term for new classes and a distillation term for previous classes (Algorithm 3).

ℓ(Θ)=−∑(xi,yi)∈D[∑y=st(δy=yilog⁡gy(xi)+δy≠yilog⁡(1−gy(xi)))+∑y=1s−1(qiylog⁡gy(xi)+(1−qiy)log⁡(1−gy(xi)))]\ell(\Theta) = -\sum_{(x_i, y_i) \in \mathcal{D}} \Bigg[ \sum_{y=s}^{t} \Big( \delta_{y=y_i} \log g_y(x_i) + \delta_{y \neq y_i} \log\big(1 - g_y(x_i)\big) \Big) + \sum_{y=1}^{s-1} \Big( q_i^y \log g_y(x_i) + (1 - q_i^y) \log\big(1 - g_y(x_i)\big) \Big) \Bigg]

δy=yi\delta_{y=y_i} is 1 when yy is the correct label and 0 otherwise. The loss is a per-class binary cross-entropy whose targets are the correct labels for new classes and the recorded outputs qiyq_i^y for previous classes. Even for the stored exemplars of previous classes, the targets for previous classes are qiyq_i^y, not the correct labels.

Herding in step 5 adds images one at a time so that the mean feature of the selected images is as close as possible to the mean feature μ\mu of all images of that class (Algorithm 4).

pk=argmin⁡x∈X∥μ−1k[φ(x)+∑j=1k−1φ(pj)]∥,k=1,…,mp_k = \operatorname*{argmin}_{x \in X} \left\| \mu - \frac{1}{k} \Big[ \varphi(x) + \sum_{j=1}^{k-1} \varphi(p_j) \Big] \right\|, \qquad k = 1, \dots, m

For classification, the mean exemplar feature μy\mu_y is computed for each class, and the class closest to the input's feature is chosen (Eq. (2) of the paper, Algorithm 1).

μy=1∣Py∣∑p∈Pyφ(p),y∗=argmin⁡y=1,…,t∥φ(x)−μy∥\mu_y = \frac{1}{|P_y|} \sum_{p \in P_y} \varphi(p), \qquad y^* = \operatorname*{argmin}_{y = 1, \dots, t} \big\| \varphi(x) - \mu_y \big\|

The network outputs gy(x)g_y(x) are used only for representation learning, not for classification.

Why It Resists Forgetting Previous Classes

Each of iCaRL's three components prevents forgetting from a different cause.

Classifying by the mean of exemplars keeps the classifier from drifting when the features change. An ordinary network classifies with argmax⁡ywy⊤φ(x)\operatorname{argmax}_y \boldsymbol{w}_y^\top \varphi(x), where the weights wy\boldsymbol{w}_y and the features φ\varphi are learned separately. When learning new classes changes φ\varphi, the outputs break down unless the wy\boldsymbol{w}_y of previous classes are readjusted as well. The exemplar means μy\mu_y are recomputed with the current φ\varphi every time, so they automatically move along with the features. Because the features are normalized, this classification can also be written as argmax⁡yμy⊤φ(x)\operatorname{argmax}_y \mu_y^\top \varphi(x), which can be viewed as classifying with "weights that move together with the features."

Exemplars are stored so that "the order of selection" carries meaning. Each time classes are added, the number per class mm shrinks, but by then the full data of the class is no longer available. Selecting by herding orders the exemplars so that, however many are taken from the front, their mean stays close to the mean of the whole class. Therefore, simply discarding from the back reduces the count while keeping the mean close.

Representation learning uses both stored images and knowledge distillation. Mixing stored images into training brings at least some information about the data distribution of previous classes into training (images are stored as images rather than as features because features become stale as the representation is updated). In addition, the distillation term pulls the outputs for previous classes toward those of the network before the update, so that the discrimination learned so far is not lost. This distillation idea is the same as in LwF, which was proposed as a separate method.

Memory usage is determined by three things: the weights of the feature extractor, the KK exemplar images, and one weight vector per class. Since KK is held constant and the number per class shrinks as classes increase, the total memory does not grow.

Experiments in the Paper

The paper evaluates on iCIFAR-100, which learns the 100 classes of CIFAR-100 in sequence in groups of 2, 5, 10, 20, or 50 classes, and on iILSVRC, which uses ILSVRC 2012 from ImageNet. iCIFAR-100 uses a 32-layer ResNet with K=2000K = 2000, and iILSVRC uses an 18-layer ResNet with K=20000K = 20000. After learning each group of classes, the model is tested on all classes learned so far, and methods are compared by the average of these accuracies (average incremental accuracy).

The compared methods are fine-tuning without any countermeasure, a method that fixes the features after the first group of classes, and LwF.MC (LwF adapted to a single classifier), which uses distillation only without exemplars. The following table shows average incremental accuracy (%, mean over 10 runs) on iCIFAR-100, taken from Table 1 of the paper.

Classes per stepiCaRLClassify by outputs (hybrid1)No distillation (hybrid2)LwF.MCReference: means from all data (NCM)
257.036.657.611.759.3
561.250.957.932.662.1
1064.159.359.944.464.5
2067.265.663.254.467.5
5068.668.265.364.568.7

hybrid1 learns the representation the same way as iCaRL but classifies with the network outputs; hybrid2 classifies by exemplar means but does not use the distillation term. NCM stores all training data and recomputes the class means; it does not satisfy the conditions of class-incremental learning, but it indicates how good the exemplar selection is.

From these results, the paper states the following.

  • The fewer classes per step, the larger iCaRL's advantage: LwF.MC dropped to 11.7% with 2 classes per step, while iCaRL held 57.0%.
  • Classifying by exemplar means helps: especially when few classes are learned per step and the representation is updated many times, it was much better than classifying with the network outputs.
  • Distillation can hurt when classes arrive a few at a time: with 2 classes per step, the version without distillation was slightly better. With more classes per step, distillation clearly helped.
  • The exemplar selection is good enough: the gap to NCM, which recomputes means from all data, was at most 2.3 points.

Looking at confusion matrices after training with the same class groups (10 classes per step), iCaRL's predictions were spread almost evenly across all classes, whereas LwF.MC was biased toward recently learned classes, the fixed-feature method toward the first classes, and fine-tuning predicted only the last learned classes. On iILSVRC as well, iCaRL outperformed the other methods.

Practical Considerations

iCaRL stores the images themselves of previous classes in memory. It cannot be used where training data must not be retained for privacy or contractual reasons. The paper itself also lists as an open issue that it still does not reach the performance of a network trained on all data at once (on iCIFAR-100, the same network trained on all data reaches 68.6% accuracy).

  • The memory size KK drives performance: in Figure 4 of the paper, varying KK from 100 to 5000 showed that larger KK improved performance for every classification rule. With enough exemplars (1000 or more in this experiment), classification by exemplar means became almost the same as NCM.
  • The number per class shrinks as classes increase: since m=K/tm = K/t, as the number of classes approaches KK, only one image per class can be kept. Because at least one exemplar and one weight vector are needed per class, there is an upper limit on the number of classes that can be learned unless the memory grows.
  • Classification requires computing prototypes: after updating the representation, recompute the mean exemplar features μy\mu_y before classifying. Continuing to use old μy\mu_y leaves them misaligned with the features.
  • The output layer is sigmoid: the paper uses per-class sigmoids with binary cross-entropy rather than softmax. It notes that this is likely why a large learning rate of 2.0 worked well, and that a softmax output layer might require a smaller learning rate.

Comparison with Other Continual Learning Methods

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

MethodWhat is keptMechanism against forgettingHow it classifiesSuitable conditions
iCaRLExemplar images per class (KK in total)Mixes exemplars into training and preserves previous-class outputs with knowledge distillationThe class with the closest mean exemplar featureA single classifier with a growing set of classes; a few images can be stored
LwFThe original networkPreserves previous-task outputs on new data with knowledge distillationA separate output layer per taskNo previous data can be kept at all; output layers can be split per task
GEMA subset of images per taskCorrects the gradient direction so the loss on stored images does not increasePer-task outputs (uses the task index)Data can be seen only once; room for improving previous tasks is desired
EWCWeights and their importanceA quadratic penalty that keeps important weights from movingAn ordinary output layerPrevious data cannot be stored; task boundaries are known
Synaptic IntelligenceWeights and their importanceThe same form of penalty as EWC, with importance computed during trainingAn ordinary output layerSame conditions as EWC, when importance should be computed alongside training

If even a few images can be stored and the goal is a single classifier with a growing set of classes, iCaRL is a good starting point. The GEM paper reports that, in a setting that splits CIFAR-100 into tasks (where task indices are available), GEM outperformed iCaRL at the same memory size. On the other hand, if images cannot be stored, choose among methods that keep no images, such as LwF, EWC, and SI.

PyTorch example

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

"""
iCaRL: learn the representation with exemplars and knowledge distillation, and classify by the mean exemplar feature
  (a small implementation of Algorithms 1 to 5 of the paper)
"""

K = 2000  # total number of exemplars that can be stored (the paper's iCIFAR-100 setting)


class ICaRL(nn.Module):
  def __init__(self, feature_extractor, feat_dim):
    super().__init__()
    self.phi = feature_extractor       # feature extractor φ
    self.fc = nn.Linear(feat_dim, 0)   # one weight vector w_y per class (zero at first)
    self.exemplars = []                # per-class exemplar tensors P_y (in selection order)

  def features(self, x):
    return F.normalize(self.phi(x), dim=1)  # L2-normalize the features

  def forward(self, x):
    return self.fc(self.features(x))  # a_y(x) = w_y^T φ(x) (the sigmoid is applied inside the loss)

  def add_classes(self, n):
    old = self.fc
    self.fc = nn.Linear(old.in_features, old.out_features + n).to(old.weight.device)
    with torch.no_grad():
      self.fc.weight[: old.out_features] = old.weight
      self.fc.bias[: old.out_features] = old.bias

  # Algorithm 3: representation learning
  def update_representation(self, new_x, new_y, n_new, epochs=70, lr=2.0):
    s = self.fc.out_features  # number of previous classes (class indices are assigned consecutively 0, 1, ...)
    old_x = torch.cat(self.exemplars) if self.exemplars else new_x[:0]
    old_y = torch.cat([torch.full((len(p),), c) for c, p in enumerate(self.exemplars)]) if self.exemplars else new_y[:0]
    xs, ys = torch.cat([new_x, old_x]), torch.cat([new_y, old_y])  # D: new images + exemplars

    self.eval()
    with torch.no_grad():
      q = torch.sigmoid(self(xs))[:, :s]  # previous-class outputs q_i^y of the network before the update

    self.add_classes(n_new)
    opt = torch.optim.SGD(self.parameters(), lr=lr, weight_decay=1e-5)
    for _ in range(epochs):
      self.train()
      for idx in torch.randperm(len(xs)).split(128):
        logits = self(xs[idx])
        target = F.one_hot(ys[idx], self.fc.out_features).float()  # new classes: correct labels (0/1)
        target[:, :s] = q[idx]                                      # previous classes: recorded outputs q
        loss = F.binary_cross_entropy_with_logits(logits, target, reduction="sum") / len(idx)
        opt.zero_grad()
        loss.backward()
        opt.step()

  # Algorithm 4: select m exemplars by herding
  @torch.no_grad()
  def construct_exemplar_set(self, x, m):
    self.eval()
    f = self.features(x)
    mu = F.normalize(f.mean(0), dim=0)
    chosen, acc = [], torch.zeros_like(mu)
    for k in range(1, min(m, len(x)) + 1):
      dist = (mu - (f + acc) / k).norm(dim=1)
      if chosen:
        dist[chosen] = float("inf")  # do not select the same image twice
      i = int(dist.argmin())
      chosen.append(i)
      acc += f[i]
    return x[chosen]

  # Algorithm 2: learn new classes
  def incremental_train(self, new_x, new_y):
    classes = new_y.unique().tolist()
    self.update_representation(new_x, new_y, n_new=len(classes))
    t = self.fc.out_features
    m = K // t                                                # number per class
    self.exemplars = [p[:m] for p in self.exemplars]          # Algorithm 5: keep only the first m
    for c in classes:
      self.exemplars.append(self.construct_exemplar_set(new_x[new_y == c], m))

  # Algorithm 1: choose the class closest to the mean exemplar feature
  @torch.no_grad()
  def classify(self, x):
    self.eval()
    mus = torch.stack([F.normalize(self.features(p).mean(0), dim=0) for p in self.exemplars])
    return torch.cdist(self.features(x), mus).argmin(dim=1)


# Usage example (assign class indices 0, 1, 2, ... in the order they are learned):
#   model = ICaRL(resnet_without_fc, feat_dim=64)
#   for xs, ys in class_batches:   # e.g., CIFAR-100 in groups of 10 classes
#     model.incremental_train(xs, ys)
#     pred = model.classify(test_images)

FAQ

Q. How does it differ from LwF?
A.

Both preserve previous outputs with knowledge distillation, but iCaRL additionally stores exemplar images of previous classes and mixes them into training, and classifies by the mean exemplar feature. Also, while LwF assumes a separate output layer per task, iCaRL distinguishes all classes with a single classifier. In the iCaRL paper's experiments, LwF.MC (LwF adapted to a single classifier) fell further behind iCaRL the fewer classes were added at a time (11.7% vs. 57.0% with 2 classes per step).

Q. Can exemplars be chosen at random instead?
A.

iCaRL's herding orders exemplars so that, however many are taken from the front, their mean stays close to the mean of the whole class. Therefore, when classes increase and the count must shrink, simply discarding from the back suffices. The paper cites prior work showing that herding approximates the mean well with fewer samples than random selection, and its experiments also show only a small gap to the method that recomputes means from all data.

Q. How large should the memory $K$ be?
A.

The paper uses K=2000K = 2000 for iCIFAR-100 and K=20000K = 20000 for ImageNet. In experiments varying KK from 100 to 5000, larger values improved performance, and with 1000 or more, classification by exemplar means became almost the same as using means over all data. Decide based on the storage available for images and the number of classes to handle (each class needs at least one).

References

  1. Rebuffi, S.-A., Kolesnikov, A., Sperl, G., & Lampert, C. H. (2017). iCaRL: Incremental Classifier and Representation Learning. CVPR 2017.
  2. Implementation of iCaRL by the authors (GitHub)
  3. Li, Z., & Hoiem, D. (2016). Learning without Forgetting. ECCV 2016. arXiv:1606.09282.
  4. Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the Knowledge in a Neural Network. arXiv:1503.02531.
  5. Lopez-Paz, D., & Ranzato, M. (2017). Gradient Episodic Memory for Continual Learning. NIPS 2017.