AI Logic

Continual Learning

Learning without Forgetting (LwF)

Updated:

LwF training flow. Left: new-task images pass through both the original network and the network being trained, and the distillation loss on the previous task's outputs is added to the new task's cross-entropy to update the weights. Right: feature extraction, fine-tuning, joint training, and LwF compared by which of the shared weights and the old and new output layers are trained, and whether previous-task data is used.

Background and overview

LwF (Learning without Forgetting) is a continual learning method that, when adding a new task to a trained network, uses only the new task's data and trains while preserving the "original network's outputs" on that data via knowledge distillation, so that previous tasks are not forgotten. It was presented by Li and Hoiem of the University of Illinois at ECCV in 2016, and an extended version with more experiments was published in IEEE TPAMI in 2018.

Consider an object recognition network trained on ImageNet to which a bird species classification task is to be added later. With ordinary fine-tuning on bird data alone, the shared layers' weights are rewritten for birds, and performance on the original object recognition task drops (catastrophic forgetting). Retraining on a mix with the original data would prevent this, but in many situations the original data is unavailable, too large to handle, or unusable for licensing reasons.

The idea behind LwF is that even without the original data, passing the new data through the original network records how it answers the original task. Before training starts, the probabilities the original network outputs for the original task are recorded for each new-task image. During training, the network fits the new task's ground-truth labels while keeping the original task's outputs close to these records. It is like copying the teacher's answer sheet beforehand, then studying a new subject while periodically checking that answers for the old subject have not drifted from the teacher's.

The paper shows that this approach performs close to joint training, which uses the original task's data, and often outperforms fine-tuning on the new task.

Procedure and loss

LwF splits the network's weights into three groups.

SymbolContentsExample (AlexNet)
θs\theta_sWeights shared by all tasksFive convolutional layers and two fully connected layers
θo\theta_oWeights specific to previous tasksOutput layer classifying ImageNet
θn\theta_nWeights specific to the new task (newly added)Output layer classifying the new task's classes

The procedure for adding a new task follows Figure 3 of the paper.

  1. Pass the new task's images XnX_n through the original network (θs\theta_s and θo\theta_o) and record the previous task's output probabilities YoY_o.
  2. Add as many nodes to the output layer as there are new-task classes, and initialize their weights θn\theta_n randomly (the paper uses Xavier initialization).
  3. As a warm-up, freeze θs\theta_s and θo\theta_o and train only θn\theta_n until convergence.
  4. Train all weights θs\theta_s, θo\theta_o, and θn\theta_n jointly with the following loss. No previous-task data is used.
θs∗,θo∗,θn∗=argmin⁡θ^s,θ^o,θ^n(λoLold(Yo,Y^o)+Lnew(Yn,Y^n)+R(θ^s,θ^o,θ^n))\theta_s^*, \theta_o^*, \theta_n^* = \operatorname*{argmin}_{\hat\theta_s, \hat\theta_o, \hat\theta_n} \Big( \lambda_o \mathcal{L}_{old}(Y_o, \hat Y_o) + \mathcal{L}_{new}(Y_n, \hat Y_n) + \mathcal{R}(\hat\theta_s, \hat\theta_o, \hat\theta_n) \Big)

Here, Y^o\hat Y_o and Y^n\hat Y_n are the previous- and new-task probabilities output by the network being trained, YnY_n is the new task's ground-truth labels, λo\lambda_o is a coefficient balancing the two losses (1 in most of the paper's experiments), and R\mathcal{R} is weight decay (coefficient 0.0005).

The new-task loss Lnew\mathcal{L}_{new} is ordinary cross-entropy (Eq. (1) in the paper).

Lnew(yn,y^n)=−yn⋅log⁡y^n\mathcal{L}_{new}(\boldsymbol{y}_n, \hat{\boldsymbol{y}}_n) = -\boldsymbol{y}_n \cdot \log \hat{\boldsymbol{y}}_n

The previous-task loss Lold\mathcal{L}_{old} is the knowledge distillation loss of Hinton et al. (Eqs. (3) and (4) in the paper). Both the recorded probabilities yo(i)y_o^{(i)} and the current probabilities y^o(i)\hat y_o^{(i)} are raised to the power 1/T1/T and renormalized to sum to 1, and the cross-entropy between the two is taken.

Lold(yo,y^o)=−∑i=1lyo′(i)log⁡y^o′(i),yo′(i)=(yo(i))1/T∑j(yo(j))1/T\mathcal{L}_{old}(\boldsymbol{y}_o, \hat{\boldsymbol{y}}_o) = -\sum_{i=1}^{l} y'^{(i)}_o \log \hat y'^{(i)}_o, \qquad y'^{(i)}_o = \frac{\big(y^{(i)}_o\big)^{1/T}}{\sum_j \big(y^{(j)}_o\big)^{1/T}}

y^o′(i)\hat y'^{(i)}_o is computed the same way. ll is the number of previous-task labels and TT is the temperature; the paper uses T=2T = 2, chosen by search on validation data. When there are multiple previous or new tasks, the per-task losses are summed.

Raising the probabilities to the power 1/T1/T and renormalizing is the same computation as dividing the logits by TT before the softmax. Setting T>1T > 1 flattens the probability distribution and preserves even the probabilities of the second- and third-closest classes, so the original network's knowledge of "how similar classes are to each other" is better retained.

Why previous tasks are less likely to be forgotten

LwF protects previous tasks not by directly freezing the previous task's weights, but by training so that the previous task's "outputs" do not change. If θs\theta_s and θo\theta_o produced the same outputs as before for every possible image, performance on the previous task would be exactly that of the original network. LwF tries to satisfy this condition as far as possible using the new-task images at hand instead of "every possible image."

Comparing with other approaches clarifies where LwF stands (Figures 1 and 2 in the paper).

MethodWeights trainedTraining usesWeakness
Feature extractionθn\theta_n onlyNew-task data and labelsShared weights cannot adapt to the new task, so new-task performance is limited
Fine-tuningθs\theta_s and θn\theta_nNew-task data and labelsWhen θs\theta_s changes, there is no signal to readjust θo\theta_o, so previous tasks are forgotten
Joint trainingAllData and labels of all tasksRequires previous-task data; training gets heavier as tasks increase
LwFAllNew-task data and labels, original network's outputsIf new-task images differ greatly from previous-task images, they become a weak signal for preserving outputs

The only differences from fine-tuning are that θo\theta_o is trained as well and that the recorded outputs YoY_o serve as its target. The added computation is therefore small. Images pass through the shared layers θs\theta_s only once to compute both the previous- and new-task losses, so training is only slightly slower than fine-tuning and faster than joint training, and inference speed is the same as the original network.

According to the paper, preserving the previous task's outputs also acts as regularization for the new task, sometimes even improving new-task performance. In experiments replacing the loss that pulls previous-task outputs closer with L1 or L2 distance, or cross-entropy without temperature, the knowledge distillation loss was slightly better but the differences were small. The paper concludes that "keeping outputs close to the original" is what matters, and the choice of distance measure is less important. It also argues that constraining outputs protects previous tasks better than constraining individual weights, because small weight changes can accumulate into large changes in output.

Experiments in the paper

The paper mainly uses AlexNet and adds one new task (PASCAL VOC, CUB (fine-grained bird classification), MIT indoor scenes, MNIST) to an original task (ImageNet, Places365). The table below is part of Table 1(a) of the paper (averages of three runs; mAP for VOC, accuracy (%) for the others). The paper's table reports differences from LwF, so the values here have those differences added back.

MethodImageNet→VOC old / newImageNet→CUB old / newPlaces365→CUB old / newImageNet→MNIST old / new
LwF56.2 / 76.154.7 / 57.747.9 / 34.849.8 / 99.3
Fine-tuning55.3 / 75.850.9 / 57.043.3 / 35.847.0 / 99.3
Feature extraction57.0 / 75.657.0 / 52.551.7 / 22.557.1 / 98.5
Joint training (uses old data)56.9 / 75.955.3 / 56.650.2 / 36.357.0 / 99.3

The main results reported in the paper are as follows.

  • New task: In most of the seven combinations, LwF outperformed fine-tuning and feature extraction. Fine-tuning was better on Places365→VOC (by 0.1 points) and Places365→CUB (by 1.0 point), and ImageNet→MNIST was a tie.
  • Previous task: LwF forgot much less than fine-tuning, but often scored slightly lower than feature extraction, which does not change the weights at all.
  • Comparison with joint training: On AlexNet, LwF performed nearly the same as joint training with old data, tending to be slightly better on the new task and slightly worse on the previous task. On VGG, joint training was consistently better.
  • When tasks differ greatly: On Places365→CUB, previous-task accuracy dropped by 8.4 points with fine-tuning, 3.8 points with LwF, and 1.5 points with joint training. When handwritten-digit MNIST was added, previous-task performance dropped substantially.

In experiments adding three tasks in sequence (VOC or scene classes split into three groups), the outputs YoY_o of all previous tasks were re-recorded each time a task was added. LwF did better than fine-tuning and others on the newly added task, but as tasks accumulated, the gap to joint training widened on previous tasks.

Practical considerations

The only signal LwF has for protecting previous tasks is the outputs on new-task images. If new-task images differ greatly from previous-task images (e.g., adding handwritten digits to ImageNet object recognition), how the network answers the previous task cannot be recorded well, and forgetting is hard to prevent. Also, when tasks are added many times, the network that produces the records itself gradually drifts, so the gap to joint training on previous tasks keeps widening.

  • Task identity is required: LwF is a method for the setting where each task has its own output layer (multi-head). At inference time, it must be known which task's output layer to use. When used as a single classifier with a growing set of classes (LwF.MC in the later iCaRL paper), predictions have been reported to be biased toward new classes.
  • Recording outputs requires the original network: YoY_o is either recorded before training, or obtained during training by keeping a frozen copy of the original network and passing the same images through it. If data augmentation changes the images each time, the latter keeps the records exactly aligned with the inputs.
  • Balance with λo\lambda_o: Larger λo\lambda_o favors the previous task, smaller favors the new task (Figure 7 in the paper). The paper notes that a λo\lambda_o that is too large or too small could lower performance on both tasks.
  • Warm-up stage: Training only the new output layer first greatly improved previous-task performance for fine-tuning, but was not as important for LwF (Table 2(b) in the paper).

Comparison with other continual learning methods

Continual learning methods can be compared by "what is kept from previous tasks, and how forgetting is prevented."

MethodWhat is keptMechanism against forgettingPrevious-task dataSuited to
LwFThe original network (or recorded outputs)Preserves previous-task outputs on new data via knowledge distillationNot usedSeparate output layer per task; old and new task images are similar
EWCWeights θ∗\theta^* and weight importance FFQuadratic penalty that keeps important weights from movingNot used (only for computing importance)Past data cannot be stored; task boundaries are known
Synaptic IntelligenceWeights and weight importanceSame form of penalty as EWC; importance computed online during trainingNot usedAvoiding a separate importance computation at the end of each task
iCaRLRepresentative images per classPreserves representations with exemplars and knowledge distillation; classifies by mean featuresStores a fewA single classifier whose classes keep growing
GEMSome images from past tasksCorrects the gradient direction so the loss on stored images does not increaseStores a fewA few images can be stored; each data point is seen only once

Whereas EWC and SI protect "weights," LwF protects "outputs (the function)." There is no need to compute or store weight importance, and implementation only requires adding one knowledge distillation loss. If past data cannot be stored and new-task images are reasonably similar to previous tasks, it is an easy method to try first. If even a few past images can be stored, methods that use them, such as iCaRL and GEM, often prevent forgetting more strongly.

PyTorch example

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

"""
LwF (Learning without Forgetting): add a new task without using previous-task data
  loss = λ_o · L_old (knowledge distillation) + L_new (cross-entropy) + weight decay
"""

T = 2.0          # distillation temperature (the paper uses T = 2)
lambda_o = 1.0   # weight of the previous-task loss (1 in most of the paper's experiments)


class MultiHeadNet(nn.Module):
  """Network with shared weights θ_s and a per-task output layer (θ_o, θ_n)"""

  def __init__(self, backbone, feat_dim, num_classes_old):
    super().__init__()
    self.backbone = backbone                                         # θ_s
    self.heads = nn.ModuleList([nn.Linear(feat_dim, num_classes_old)])  # θ_o

  def add_head(self, num_classes_new):
    head = nn.Linear(self.heads[0].in_features, num_classes_new)     # θ_n
    nn.init.xavier_uniform_(head.weight)                             # the paper uses Xavier initialization
    nn.init.zeros_(head.bias)
    self.heads.append(head.to(next(self.parameters()).device))

  def forward(self, x):
    h = self.backbone(x)                     # images pass through the shared layers only once
    return [head(h) for head in self.heads]  # per-task logits


def distillation_loss(logits, old_logits, T):
  """Eqs. (3)(4) of the paper: cross-entropy between distributions raised to 1/T and renormalized
  (= cross-entropy between softmaxes of logits divided by T)"""
  target = F.softmax(old_logits / T, dim=1)
  return -(target * F.log_softmax(logits / T, dim=1)).sum(dim=1).mean()


def learn_new_task(model, train_loader, num_classes_new, warmup_epochs=5, epochs=20, lr=1e-3):
  device = next(model.parameters()).device
  old_model = copy.deepcopy(model).eval()  # keep a frozen copy of the original network (θ_s, θ_o)
  for p in old_model.parameters():
    p.requires_grad_(False)
  num_old = len(model.heads)
  model.add_head(num_classes_new)

  def run(params, n_epochs, use_old_loss):
    opt = torch.optim.SGD(params, lr=lr, momentum=0.9, weight_decay=5e-4)  # R: weight decay 0.0005
    for _ in range(n_epochs):
      model.train()  # the paper uses dropout in the fully connected layers
      for x, y in train_loader:
        x, y = x.to(device), y.to(device)
        outs = model(x)
        loss = F.cross_entropy(outs[-1], y)  # L_new
        if use_old_loss:
          with torch.no_grad():
            old_outs = old_model(x)  # recorded Y_o (pass the same images through the original network)
          for k in range(num_old):
            loss = loss + lambda_o * distillation_loss(outs[k], old_outs[k], T)  # L_old
        opt.zero_grad()
        loss.backward()
        opt.step()

  # Warm-up: freeze θ_s and θ_o, train only the new output layer θ_n
  run(model.heads[-1].parameters(), warmup_epochs, use_old_loss=False)
  # Train all weights jointly
  run(model.parameters(), epochs, use_old_loss=True)
  return model


# Example usage:
#   backbone = nn.Sequential(...)  # feature extractor trained on the previous task
#   model = MultiHeadNet(backbone, feat_dim=4096, num_classes_old=1000)
#   learn_new_task(model, new_task_loader, num_classes_new=200)
#   model.eval(); logits_old, logits_new = model(images)  # at inference, pick the output layer for each task

FAQ

Q. How is it different from knowledge distillation?
A.

Knowledge distillation trains a separate, smaller student model to imitate the outputs of a large teacher model. LwF uses the same distillation loss, but the model it imitates is "itself before training," and the goal is not to make the model smaller but to preserve previous-task outputs while learning a new task. Also, the images used for distillation are not from the previous task but from the new task.

Q. If a little previous-task data can be stored, is there still a reason to use LwF?
A.

Methods that use stored images for distillation or replay (iCaRL and GEM) often prevent forgetting more strongly. In the iCaRL paper's experiments, LwF without stored images (LwF.MC, a single-classifier version of LwF) fell further behind iCaRL as classes were added incrementally. LwF is best seen as the option for when no previous data can be kept at all.

Q. How should the temperature $T$ and $\lambda_o$ be chosen?
A.

The paper chose T=2T = 2 by search on validation data and set λo\lambda_o to 1 in most experiments. Larger λo\lambda_o favors the previous task and smaller favors the new task, so choose it while watching both tasks' performance on validation data.

References

  1. Li, Z., & Hoiem, D. (2018). Learning without Forgetting. IEEE Transactions on Pattern Analysis and Machine Intelligence, 40(12), 2935–2947.
  2. Li, Z., & Hoiem, D. (2016). Learning without Forgetting. ECCV 2016 (arXiv:1606.09282; the ECCV version updated to the TPAMI version).
  3. Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the Knowledge in a Neural Network. arXiv:1503.02531.
  4. Rebuffi, S.-A., Kolesnikov, A., Sperl, G., & Lampert, C. H. (2017). iCaRL: Incremental Classifier and Representation Learning. CVPR 2017.