Model Compression & Acceleration: Knowledge Distillation, Pruning, torch.compile & ONNX/TensorRT
Turning giant research models into blazing-fast production deployments: Hinton's Temperature Knowledge Distillation, Structured vs. Unstructured Pruning, torch.compile Triton kernel fusion, and ONNX / TensorRT export!
A 100ms model is useless for a 60 FPS video camera or a 10,000-QPS search ranker — Distillation + Pruning + torch.compile/TensorRT deliver 3×–10× faster inference at a fraction of the cloud bill!
Adding a single line — model = torch.compile(model) — fuses elementwise GPU ops into custom Triton kernels with zero accuracy loss!
Knowledge Distillation lets a tiny 10M-parameter Student model capture ~95% of a 300M-parameter Teacher's accuracy by learning its soft relative class probabilities!
Practical Deployment interview question: 'Why does unstructured 80% magnitude pruning often give ZERO real GPU speedup, and how does torch.compile accelerate PyTorch?'
Why does Unstructured Pruning (zeroing 80% of scattered weights) rarely speed up standard GPU matrix multiplication?
- Implement Knowledge Distillation using temperature-softened Teacher logits () to transfer 'dark knowledge'
- Contrast Unstructured Pruning (scattered zeros) with Structured Pruning (removing whole heads/channels for real speedups)
- Explain how torch.compile (TorchDynamo + TorchInductor/Triton) speeds up models 1.8×–2.5× via vertical kernel fusion
- Know when to export models to ONNX Runtime or NVIDIA TensorRT for low-latency edge/server inference
T = 4, α = 0.7.Hard one-hot labels only say 'This is a Cat (100%)'. A Teacher's soft probabilities at Temperature whisper dark knowledge: '80% Cat, 18% Tiger, 2% Fox, 0% Car' — giving a small Student 10× richer signal per image!
1. Knowledge Distillation & Dark Knowledge
Freeze a large accurate Teacher and train a compact Student on a weighted blend of true labels + KL divergence against the Teacher's temperature-softened distribution! Always multiply the KL term by since dividing logits by scales gradients by .
Teacher Softmax Temperature T (Revealing Dark Knowledge)
2. Unstructured vs. 2:4 vs. Structured Pruning
- Unstructured: Zeroes smallest weights individually (great for disk compression, minimal dense-GPU speedup).
- 2:4 Semi-Structured: 2 zeros in every 4 contiguous weights (native 2× Tensor Core acceleration on NVIDIA Ampere+).
- Structured: Drops entire conv filters, attention heads, or layers → immediate speedup everywhere!
3. torch.compile, Kernel Fusion & ONNX / TensorRT
torch.compile (TorchInductor + Triton) fuses separate elementwise GPU kernels (mul + add + gelu) into ONE on-chip SRAM kernel — eliminating slow HBM round-trips!Eager PyTorch launches one GPU kernel per op, reading and writing slow GPU HBM memory repeatedly. torch.compile(model) traces the FX graph and emits fused Triton kernels that keep intermediate values in blazing-fast on-chip SRAM! For C++/edge/mobile deployment, export via ONNX or TensorRT.
What is the primary source of speedup when you wrap a PyTorch model in torch.compile(model)?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
PyTorch traces and compiles the Triton GPU kernels on the first call (~10–30s warmup); every subsequent iteration runs at full compiled speed!
torch.compile Kernel Fusion & Student Distillation Speedup
Eliminate slow GPU HBM memory round-trips by fusing elementwise ops into one Triton kernel.
T^2·KL), Structured / 2:4 Pruning, torch.compile Triton kernel fusion, and ONNX / TensorRT runtimes.Real-Time Edge Vision, Mobile AI & High-QPS Search
Combines Distillation + torch.compile / TensorRT to cut serving latency from 80ms down to <10ms.
import torch
import torch.nn as nn
import torch.nn.functional as F
# Knowledge Distillation Loss: blend soft teacher distribution (temp T) + hard labels
def distillation_loss(
student_logits: torch.Tensor,
teacher_logits: torch.Tensor,
targets: torch.Tensor,
T: float = 4.0,
alpha: float = 0.7,
) -> torch.Tensor:
soft_loss = F.kl_div(
F.log_softmax(student_logits / T, dim=-1),
F.softmax(teacher_logits / T, dim=-1),
reduction="batchmean",
) * (T ** 2)
hard_loss = F.cross_entropy(student_logits, targets)
return alpha * soft_loss + (1.0 - alpha) * hard_loss
# Unstructured magnitude pruning (zero out smallest 30% weights)
layer = nn.Linear(16, 16)
threshold = layer.weight.abs().quantile(0.30)
mask = (layer.weight.abs() >= threshold).float()
with torch.no_grad():
layer.weight.mul_(mask)
loss = distillation_loss(torch.randn(4, 10), torch.randn(4, 10), torch.randint(0, 10, (4,)))
sparsity = (layer.weight == 0).float().mean().item()
print(f"Distillation loss: {loss.item():.3f} | Weight sparsity: {sparsity:.1%}")
T^2 scaling factor on the KL distillation loss when T > 1.1 / T^2, multiply the KL term by T * T so the Teacher signal doesn't vanish relative to Cross-Entropy!T^2?