Sub topic 4
Pruning and Knowledge Distillation
This chapter assumes you know how to train a CNN classifier or detector in PyTorch. It also assumes you have met the idea of quantization from the previous chapter, and that you know what a loss function and a softmax are. You do not need a mobile app.
Quantization and a smaller architecture are usually your first two moves for fitting a vision model on a phone. Pruning and knowledge distillation are the next two. They solve different problems. Pruning removes parts of an existing model. Distillation trains a new, smaller model to imitate a larger one. This chapter covers how each works, where each one fails on real devices, and how to decide whether either is worth the effort.
Pruning: removing weights
Pruning sets some weights or whole structures of a trained network to zero, or deletes them, and then fine-tunes the remainder to recover accuracy. The usual workflow is train, prune, fine-tune, and then repeat if needed.
Unstructured pruning
Unstructured pruning zeros individual weights, usually those with the smallest absolute value (magnitude pruning). The weight tensor keeps its shape. It simply has many zeros.
This can reach high sparsity. Removing 80 to 90 percent of the weights in a large network is often possible with little accuracy loss. The catch is that a dense convolution kernel on a phone CPU or GPU multiplies zeros as fast as it multiplies any other number. Unless the runtime has sparse kernels, which most mobile runtimes do not use for convolutions, you get no speedup.
The model file can get smaller, because zero-heavy tensors compress well with gzip or zip. That helps download size. It does not reduce the memory the model needs once loaded, and it does not reduce latency.
Structured pruning
Structured pruning removes whole units: output channels of a convolution, whole filters, or attention heads. After you remove a channel, the layer is genuinely narrower. The next layer's matching input channel must also be removed. The result is a smaller dense network that runs faster on any runtime.
The price is that structured pruning is harder to do without losing accuracy. A whole channel carries more information than one small weight. Dependencies also constrain it. In residual networks, layers joined by an addition must keep matching channel counts. Depthwise convolutions tie their channel count to the previous layer.
| Property | Unstructured | Structured |
|---|---|---|
| What is removed | Individual weights | Channels, filters, heads |
| Typical sparsity at small accuracy loss | High (70 to 90 percent) | Lower (20 to 50 percent of channels) |
| Latency gain on phone CPU or GPU | Usually none | Real, roughly proportional to FLOPs removed |
| Compressed file size | Smaller | Smaller |
| Tooling effort | Low | Higher (layer dependencies) |
Pruning in PyTorch
PyTorch ships torch.nn.utils.prune. It applies a mask to a weight, so the tensor shape does not change. The example below zeros 30 percent of the output channels of each convolution (by L2 norm), makes the pruning permanent, and reports the resulting sparsity. It uses randomly initialized weights so it runs without a download. In practice you would start from your trained model and fine-tune afterwards.
import torch
import torch.nn as nn
import torch.nn.utils.prune as prune
import torchvision
model = torchvision.models.mobilenet_v3_small(weights=None).eval()
convs = [m for m in model.modules() if isinstance(m, nn.Conv2d)]
for conv in convs:
# Zero the 30% of output channels (dim=0) with the smallest L2 norm.
prune.ln_structured(conv, name="weight", amount=0.3, n=2, dim=0)
# Fold the mask into the weight so the pruning becomes permanent.
prune.remove(conv, "weight")
total = sum(c.weight.numel() for c in convs)
zeros = sum((c.weight == 0).sum().item() for c in convs)
print(f"conv weights: {total}, zeros: {zeros} ({100 * zeros / total:.1f}%)")
x = torch.randn(1, 3, 224, 224)
print("output shape:", tuple(model(x).shape))The script prints a zero fraction near 30 percent, and the output shape is still (1, 1000). The tensors are the same size as before. The channels are zeroed, not removed. To get a faster model you must physically rebuild the layers with fewer channels, which is what libraries such as Torch-Pruning automate by tracing the dependencies for you.
Iterative pruning and fine-tuning
Pruning a large fraction in one step damages accuracy badly. A better schedule removes a little, fine-tunes for a few epochs, and repeats. A common pattern raises sparsity gradually (for example 10, 20, 30 percent) with a learning rate lower than the original training rate. Plan for fine-tuning to take a meaningful fraction of the original training cost.
Knowledge distillation: teaching a small model
Distillation trains a small student model using the outputs of a larger teacher model. The student does not have to be a pruned copy of the teacher. It can be a different architecture, such as MobileNetV3 learning from a large ResNet or vision transformer.
The key observation is that a teacher's output probabilities carry more information than the hard label. For an image of a cat, the teacher may give 0.90 to cat, 0.07 to lynx, and 0.001 to truck. That pattern of near-misses tells the student which classes look alike. Hinton and colleagues called this "dark knowledge".
To expose these small probabilities, you divide the logits by a temperature T greater than 1 before the softmax. A higher T flattens the distribution and makes the small values easier to learn from.
The distillation loss
The standard loss mixes two terms:
- A KL divergence between the student's and teacher's softened distributions, multiplied by
T²so its gradient scale stays comparable asTchanges. - The ordinary cross-entropy against the true labels.
A weight alpha balances them.
import torch
import torch.nn.functional as F
import torchvision
def distillation_loss(student_logits, teacher_logits, labels, T=4.0, alpha=0.7):
soft_student = F.log_softmax(student_logits / T, dim=1)
soft_teacher = F.softmax(teacher_logits / T, dim=1)
kd = F.kl_div(soft_student, soft_teacher, reduction="batchmean") * (T * T)
ce = F.cross_entropy(student_logits, labels)
return alpha * kd + (1 - alpha) * ce
teacher = torchvision.models.resnet50(weights=None).eval()
student = torchvision.models.mobilenet_v3_small(weights=None).train()
optimizer = torch.optim.AdamW(student.parameters(), lr=1e-3)
images = torch.randn(8, 3, 224, 224) # stand-in for a real batch
labels = torch.randint(0, 1000, (8,))
with torch.no_grad(): # the teacher is frozen
teacher_logits = teacher(images)
student_logits = student(images)
loss = distillation_loss(student_logits, teacher_logits, labels)
loss.backward()
optimizer.step()
optimizer.zero_grad()
print("loss:", float(loss))In a real run you would loop this over a data loader, load a trained teacher (weights="DEFAULT"), and keep the teacher in eval() mode so batch normalization and dropout behave consistently.
What can be distilled
- Output logits (shown above) work for any architecture pair with the same label space.
- Intermediate features match hidden activations of the student to those of the teacher, usually through a small learned projection when channel counts differ. This helps when the student is much smaller.
- Detection and segmentation need task-specific variants, such as distilling box scores, box regression outputs, or per-pixel logits. The class-logit recipe alone does not transfer directly.
- Unlabeled data can be labeled by the teacher. This is useful because phone-specific images are often plentiful but unlabeled. The loss then uses only the KL term (
alpha = 1).
Distillation and data augmentation
The student sees whatever images you feed it, so the teacher's labels are only as good as the inputs. Strong augmentation, applied identically to what the teacher sees in the same step, often matters more than fine-tuning T or alpha. If the teacher and student receive different crops of the same image, the teacher's output no longer describes what the student is looking at.
Choosing between them
A practical order of effort is as follows:
- Start with a mobile-friendly architecture. It usually beats a pruned large model.
- Apply post-training quantization. It is cheap and gives a reliable speed and size gain.
- If you still miss the budget, use distillation to train a smaller student with the teacher's help, or structured pruning to slim an existing model.
- Treat unstructured pruning as a file-size tool, not a speed tool, unless you have verified sparse kernel support.
Pruning and distillation combine with quantization. A common pipeline is to distill, then prune structurally, then fine-tune, and finally quantize. Do the compression steps before quantization and re-check accuracy at the end, because each step compounds the accuracy loss.
Common failures
- Reporting sparsity as a speedup. A model with 90 percent zeros runs at the same speed. Only measured on-device latency counts.
- Pruning without fine-tuning. Accuracy often falls sharply. Fine-tuning recovers most of it.
- Mismatched channel counts after structured pruning. Residual additions and depthwise convolutions break if only one side is shrunk. Use a dependency-aware tool.
- Teacher too large relative to the student. A student with far too little capacity cannot imitate a very large teacher, and an intermediate-sized "teaching assistant" model often works better.
- Evaluating only on the validation set. Check accuracy on the slices that matter for your app, such as low light or small objects. Compression tends to hurt rare cases first.
- Skipping the teacher's preprocessing. If the teacher expects different normalization from the student, the soft labels will be wrong for the student's inputs. See the chapter on preprocessing.
Exercises
Exercise
You prune 80 percent of the individual weights of a convolutional network with magnitude pruning, export it to TFLite, and the on-device latency does not change. Why, and what would you try next?
Show answer
Unstructured pruning leaves the tensors at full size with zeros in them, and the mobile runtime executes dense kernels that multiply the zeros like any other value. Latency stays the same. Next, try structured pruning, which removes whole channels so the layers are genuinely smaller, or distill into a smaller architecture. In both cases, verify the result with an on-device benchmark.
Exercise
In the distillation loss, why is the KL term multiplied by T squared, and what does raising T do to the teacher's distribution?
Show answer
Dividing logits by T shrinks the gradients of the softened KL term by roughly 1/T squared, so multiplying by T squared keeps its contribution comparable to the cross-entropy term when you change T. Raising T flattens the teacher's distribution, which makes the small probabilities on similar-looking wrong classes larger and easier for the student to learn from.