AI Logic

Model Compression

Knowledge Distillation

Updated:

How knowledge distillation works. Left: the flow that computes a soft loss at temperature T and a hard loss at temperature 1 from the teacher and student outputs and combines them. Right: softmax probabilities at T = 1 compared with T = 4

Background and Overview

Knowledge distillation is a method that uses the probability distribution output by a large trained model (the teacher) as the training target for a small model (the student), transferring the teacher's knowledge to the student. Hinton, Vinyals, and Dean proposed it under the name "distillation" in 2015.

Large models, and ensembles that average the predictions of several models, are accurate but slow at inference, which can make them impractical on smartphones or in services used by many people. Knowledge distillation makes it possible to use a heavy model during training and a light model in deployment. The paper explains this division of roles with the analogy of insects whose larval and adult forms have very different bodies.

The key idea is that knowledge lies not only in the correct label ("this image is a 2") but also in how much probability the model assigns to the wrong classes. For example, if the teacher says a handwritten "2" has a probability of 10⁻⁶ of being a 3 and 10⁻⁹ of being a 7, that tells us "this 2 looks more like a 3 than a 7". This information about how similar classes are to one another is passed to the student as "dark knowledge".

Earlier, in 2006, Buciluǎ, Caruana, and colleagues had shown that the knowledge of an ensemble can be transferred into a single small model. According to Hinton et al., that method used the values before the softmax (the logits) as targets and minimized the squared error between the teacher's and the student's logits. Knowledge distillation generalizes this by adding a temperature to the softmax; matching logits becomes a special case obtained when the temperature is large (see the Theory section).

Alongside pruning and quantization, knowledge distillation is one of the standard ways to make models smaller. It is used in many lightweight models, such as DistilBERT and TinyBERT, both distilled from BERT.

Theory

Training with knowledge distillation proceeds as follows.

  1. Train the teacher model in the usual way. Once training is done, freeze the teacher's weights.
  2. Feed the same input xx to both the teacher and the student and compute their logits (the values before the softmax), v\boldsymbol{v} and z\boldsymbol{z}.
  3. Pass the teacher's logits through a softmax with temperature TT (a value greater than 1) to obtain the soft targets p\boldsymbol{p}.
  4. Pass the student's logits through a softmax with the same temperature TT to obtain q\boldsymbol{q}, and compute the cross-entropy between it and p\boldsymbol{p} (the soft loss).
  5. When the correct label yy is known, also compute the cross-entropy between yy and q(1)\boldsymbol{q}^{(1)}, the student's logits passed through a softmax at temperature 1 (the hard loss).
  6. Update only the student to minimize a weighted average of the two losses.
  7. After training, use the student at temperature 1 (inference uses neither the teacher nor the temperature).

The softmax with temperature TT is (Eq. (1) in the paper):

qi=exp⁡(zi/T)∑jexp⁡(zj/T)q_i = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}

Here ziz_i is the logit for class ii and qiq_i is the probability of class ii. With T=1T = 1 it is the ordinary softmax. The larger TT is, the flatter (softer) the probability distribution becomes, so differences among the wrong classes, whose probabilities were almost 0, become visible.

For example, if the teacher's logits are (10,5,2,0,−1)(10, 5, 2, 0, -1), at T=1T = 1 the top class gets a probability of about 0.99 and the rest are nearly 0. At T=4T = 4 the probabilities become about (0.64,0.18,0.086,0.052,0.041)(0.64, 0.18, 0.086, 0.052, 0.041), and the difference between "the second-closest class" and "the third-closest class" becomes large enough to learn from.

The loss can be written as:

L=α T2 CE ⁣(p,q)+(1−α) CE ⁣(y,q(1))L = \alpha\, T^2 \, \mathrm{CE}\!\left(\boldsymbol{p}, \boldsymbol{q}\right) + (1 - \alpha)\, \mathrm{CE}\!\left(y, \boldsymbol{q}^{(1)}\right)

Here CE\mathrm{CE} is the cross-entropy and α\alpha is the weight between the two losses (0 to 1). The paper only says "weighted average"; writing it with α\alpha is the form widely used in later implementations. With p\boldsymbol{p} fixed, CE(p,q)\mathrm{CE}(\boldsymbol{p}, \boldsymbol{q}) differs from the KL divergence KL(p∥q)\mathrm{KL}(\boldsymbol{p} \| \boldsymbol{q}) only by a constant, so implementations often use the KL divergence.

The magnitude of the soft loss's gradient shrinks in proportion to 1/T21/T^2. So unless the soft loss is multiplied by T2T^2, the balance with the hard loss shifts every time the temperature changes. The paper reports that the best results usually come from giving the hard loss a considerably smaller weight.

In the high-temperature limit, distillation is equivalent to matching logits. The gradient of the soft loss with respect to the logit ziz_i is 1T(qi−pi)\frac{1}{T}(q_i - p_i), and when TT is much larger than the logits and the logits are adjusted to have zero mean,

∂C∂zi≈1NT2(zi−vi)\frac{\partial C}{\partial z_i} \approx \frac{1}{N T^2} (z_i - v_i)

(Eq. (4) in the paper). NN is the number of classes and viv_i is the teacher's logit. This is the same as minimizing 12(zi−vi)2\frac{1}{2}(z_i - v_i)^2, which matches the method of Buciluǎ, Caruana, and colleagues. At lower temperatures, logits much smaller than the mean (which tend to be noisy) receive less attention. The paper reports that an intermediate temperature worked best when the student was very small.

Findings from the Paper's Experiments

The paper reports the following results.

ExperimentResult
MNISTA large net (2 hidden layers × 1200 units, regularized with dropout and more) makes 67 errors. A small net (2 × 800 units) makes 146 errors when trained without regularization and 74 errors when distilled at temperature 20
MNIST (3s removed)Even with every "3" removed from the training data, adjusting the bias of class 3 lets the model correctly classify 98.6% of the 3s in the test set
Speech recognition (about 85M parameters)Frame accuracy: single model 58.9%, ensemble of 10 models 61.1%, distilled single model 60.8%. Word error rate is 10.7% for both the ensemble and the distilled model (10.9% for the single model)
Data reduced to 3%Training on correct labels alone overfits and stalls at 44.5% accuracy, while training on soft targets reaches 57.0%

On MNIST, regarding the choice of temperature, the paper reports that when the student's hidden layers have 300 or more units, all temperatures above 8 give similar results, while shrinking them to 30 units makes 2.5–4 work best.

The last experiment shows that soft targets also act as a strong regularizer. Because a soft target conveys from a single example "how similar it is to each class", it carries more information than the correct label.

Label smoothing, which slightly flattens the correct label, also softens the target distribution, but it spreads probability over the wrong classes uniformly. Knowledge distillation differs in that it spreads probability according to the class similarities the teacher has learned.

Practical Considerations

Keep the following points in mind when using knowledge distillation.

  • The temperature TT and the weight α\alpha are hyperparameters. For speech recognition, the paper tried T∈{1,2,5,10}T \in \{1, 2, 5, 10\} and set the relative weight of the hard loss to 0.5. The best values depend on the data and on the sizes of the teacher and student, so choose them on validation data.
  • If the gap between teacher and student is too large, transfer may not work well. A student that is too small cannot fully imitate the teacher's distribution.
  • The teacher's mistakes are transferred to the student too. Also using the correct labels (adding the hard loss) helps by pulling the student toward the right answers.
  • The transfer data need not be the original training data. Since the teacher only has to produce outputs, unlabeled data can be used as well.

Since this paper, many variants have been proposed, such as matching intermediate-layer features rather than only logits (FitNets) and shrinking language models (DistilBERT, TinyBERT).

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

'''
Image classification on MNIST
Train a large teacher model and distill its knowledge into a small student model
'''

# Hyperparameters
batch_size = 64       # batch size
epochs = 5            # number of epochs
learning_rate = 1e-3  # learning rate
temperature = 4.0     # temperature T
alpha = 0.9           # weight of the soft loss (the hard loss gets 1 - alpha)

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# Datasets and loaders
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=batch_size)


def mlp(hidden_dim, dropout=0.0):
  return nn.Sequential(
    nn.Flatten(),
    nn.Linear(28 * 28, hidden_dim), nn.ReLU(), nn.Dropout(dropout),
    nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Dropout(dropout),
    nn.Linear(hidden_dim, 10)
  )


# Distillation loss: weighted average of the soft loss at temperature T (times T^2) and the hard loss at temperature 1
def distillation_loss(student_logits, teacher_logits, labels, T, alpha):
  soft_targets = F.softmax(teacher_logits / T, dim=1)
  log_q = F.log_softmax(student_logits / T, dim=1)
  soft_loss = F.kl_div(log_q, soft_targets, reduction='batchmean') * (T * T)
  hard_loss = F.cross_entropy(student_logits, labels)
  return alpha * soft_loss + (1 - alpha) * hard_loss


def train(model, loss_fn):
  optimizer = optim.Adam(model.parameters(), lr=learning_rate)
  for epoch in tqdm(range(epochs)):
    model.train()
    for images, labels in train_loader:
      images, labels = images.to(device), labels.to(device)
      optimizer.zero_grad()
      loss = loss_fn(model, images, labels)
      loss.backward()
      optimizer.step()


def evaluate(model):
  model.eval()
  correct = 0
  total = 0
  with torch.no_grad():
    for images, labels in test_loader:
      images, labels = images.to(device), labels.to(device)
      _, predicted = torch.max(model(images), 1)
      total += labels.size(0)
      correct += (predicted == labels).sum().item()
  return 100 * correct / total


# 1. Train the teacher (large model) in the usual way
teacher = mlp(1200, dropout=0.3).to(device)
train(teacher, lambda m, x, y: F.cross_entropy(m(x), y))
teacher.eval()  # the teacher stays fixed from here on

# 2. Train the student (small model) by distillation
student = mlp(64).to(device)

def kd_loss(model, x, y):
  with torch.no_grad():
    teacher_logits = teacher(x)
  return distillation_loss(model(x), teacher_logits, y, temperature, alpha)

train(student, kd_loss)

print(f"Teacher Accuracy: {evaluate(teacher):.2f}%")
print(f"Student Accuracy: {evaluate(student):.2f}%")

FAQ

Q. How should the temperature T be chosen?
A.

There is no fixed value; choose it on validation data. On MNIST, the paper reports that all temperatures above 8 give similar results when the student is large enough, while 2.5–4 worked best when the student was very small.

Q. Why is the soft loss multiplied by T²?
A.

Passing through a softmax with temperature T makes the gradient of the soft loss shrink in proportion to 1/T². Multiplying by T² keeps the balance with the hard loss roughly unchanged when the temperature changes, so the weight α does not have to be re-tuned.

Q. Can distillation be done on data without correct labels?
A.

Yes. The soft loss can be computed from the teacher's outputs alone, so unlabeled data can serve as the transfer data. However, the paper reports that when correct labels are available, adding the hard loss with a small weight improves the results.

References

  1. Hinton, G., Vinyals, O., & Dean, J. (2015). Distilling the Knowledge in a Neural Network. NIPS 2014 Deep Learning Workshop. arXiv:1503.02531.
  2. Buciluǎ, C., Caruana, R., & Niculescu-Mizil, A. (2006). Model Compression. Proceedings of the 12th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, 535–541.