Sub topic 4
Pruning and Knowledge Distillation
Assume you know basic Python, tensors, convolutional neural networks, and a training loop in PyTorch or TensorFlow. This chapter focuses on reducing a trained vision model before export. Quantization and runtime selection are separate steps.
Pruning removes unnecessary weights
Pruning sets selected model parameters to zero or removes entire structures. The goal is to reduce computation, memory, or model size while keeping accuracy acceptable.
Two forms are common:
- Unstructured pruning sets individual weights to zero. It can preserve accuracy well, but ordinary mobile CPUs may still perform the same dense computation unless the runtime supports sparse kernels.
- Structured pruning removes complete filters, channels, or blocks. It usually gives more predictable speedups because the resulting model is genuinely smaller and denser.
A pruning ratio of 30% means that roughly 30% of the selected weights or structures are removed. The ratio is not an accuracy guarantee. A layer that is sensitive to feature extraction may tolerate far less pruning than a later layer.
A typical workflow is:
- Train a dense baseline.
- Prune gradually rather than removing everything at once.
- Fine-tune the pruned model.
- Export it and measure latency on the target device.
- Keep the change only if the accuracy and latency targets both improve.
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune
model = nn.Sequential(
nn.Conv2d(3, 16, 3, padding=1),
nn.ReLU(),
nn.Flatten(),
nn.Linear(16 * 32 * 32, 10),
)
# Demonstration: remove 30% of convolution weights by magnitude.
prune.l1_unstructured(model[0], name="weight", amount=0.30)
# Make the mask permanent before export.
prune.remove(model[0], "weight")
print("nonzero convolution weights:",
int(torch.count_nonzero(model[0].weight)))The pruning mask is useful during experimentation, but some exporters do not handle parametrization objects consistently. Calling prune.remove leaves the zero values as ordinary weights. That does not automatically produce a faster sparse model.
Knowledge distillation transfers behavior
Knowledge distillation trains a small student model to imitate a larger teacher model. The teacher produces richer information than a one-hot label. For example, it may assign similar scores to two visually related classes. These relative scores help the student learn class relationships.
The student normally minimizes a mixture of two losses:
- Hard-label loss compares student predictions with the true class.
- Distillation loss compares softened student and teacher predictions.
A temperature T softens probability distributions. Higher temperatures expose more information about relative class scores. The usual distillation loss is multiplied by T² to keep gradient magnitudes comparable.
import torch
import torch.nn.functional as F
def distillation_loss(student_logits, teacher_logits, labels,
temperature=4.0, alpha=0.5):
hard = F.cross_entropy(student_logits, labels)
soft = F.kl_div(
F.log_softmax(student_logits / temperature, dim=1),
F.softmax(teacher_logits / temperature, dim=1),
reduction="batchmean",
) * (temperature ** 2)
return alpha * soft + (1 - alpha) * hard
teacher.eval()
with torch.no_grad():
teacher_logits = teacher(images)
student_logits = student(images)
loss = distillation_loss(student_logits, teacher_logits, labels)
loss.backward()
optimizer.step()The teacher should normally stay in evaluation mode, and its parameters should not receive gradients. The student still needs real labels. Distillation complements labels; it does not replace a validation set.
Combining the methods
Pruning and distillation solve different problems. Pruning modifies an existing model. Distillation trains a smaller model to reproduce a stronger model. A practical sequence is to distill into a compact architecture first, then apply mild structured pruning and fine-tune.
| Method | Main benefit | Common limitation |
|---|---|---|
| Unstructured pruning | Removes many individual weights | Often no device speedup |
| Structured pruning | Shrinks dense layers and can improve latency | May lose more accuracy |
| Distillation | Improves a small student model | Requires a teacher and extra training |
Common errors
- Pruning once at a high ratio and skipping fine-tuning can cause a sharp accuracy drop.
- Pruning every layer equally ignores which layers are most important.
- Leaving dropout or batch normalization in training mode makes teacher outputs unstable.
- Choosing a temperature or distillation weight without checking validation accuracy can make the student copy poor behavior.
- Comparing only parameter counts hides preprocessing, transfer, and runtime overhead.
Exercise
Why might 50% unstructured pruning fail to reduce phone latency?
Show answer
It creates zero-valued weights, but the phone's runtime may still use dense kernels that multiply every weight. Structured pruning or a sparse kernel is needed for a predictable speedup.