Back to Blog
MLOps September 20, 2024 9 min read

Making Models 10x Smaller: Quantization, Pruning, and Knowledge Distillation

INT8 quantization, structured pruning, and distillation — how to shrink model size by 90% while keeping 95% of accuracy for edge deployment.

Technique Comparison

MethodSize ReductionAccuracy DropEffort
INT8 Quantization4x~1%Low
FP162x<0.1%Very Low
Pruning (30%)1.4x~2%Medium
Distillation5-10x3-5%High

Post-Training Quantization (Easiest)

import torch

# Dynamic quantization (CPU inference)
model_int8 = torch.quantization.quantize_dynamic(
    model,
    {nn.Linear, nn.LSTM},
    dtype=torch.qint8
)
# Result: 2-4x smaller, 2x faster on CPU

Knowledge Distillation

# Student learns from teacher's soft probabilities
teacher_logits = teacher(x).detach()
student_logits = student(x)

kd_loss = nn.KLDivLoss()(
    F.log_softmax(student_logits/T, dim=-1),
    F.softmax(teacher_logits/T, dim=-1)
) * T**2
Model CompressionQuantizationPruningKnowledge DistillationEdge
O

Ossama Elhakki

AI Engineer & ML Systems Builder — Morocco