Chapter 41 of 42 · ~18 min read & lab+75 XP
Chapter 41 · Deep Learning

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!

Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

Adding a single line — model = torch.compile(model) — fuses elementwise GPU ops into custom Triton kernels with zero accuracy loss!

Data Scientist

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!

Interview & Debug Edge

Practical Deployment interview question: 'Why does unstructured 80% magnitude pruning often give ZERO real GPU speedup, and how does torch.compile accelerate PyTorch?'

Step 0 · Test Your Gut Before Any Math!

Why does Unstructured Pruning (zeroing 80% of scattered weights) rarely speed up standard GPU matrix multiplication?

What You Will Master in This Chapter
  • Implement Knowledge Distillation using temperature-softened Teacher logits (T2⋅KL(pT∥qT)T^2 \cdot \text{KL}(p_T \| q_T)) 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 1
LKD=(1−α)LCE(y,q1)+αT2DKL(pT∥qT)\mathcal{L}_{\text{KD}} = (1 - \alpha)\mathcal{L}_{\text{CE}}(y, q_1) + \alpha T^2 D_{\text{KL}}(p_T \| q_T)Say aloud:“Distillation loss blends hard cross-entropy with T-squared scaled KL divergence on soft teacher targets”
Plain-English Meaning
Dividing logits by Temperature T>1T > 1 exposes the Teacher's dark knowledge (e.g., a cat looks 15% like a tiger and 0.001% like a truck); multiplying by T2T^2 restores gradient magnitude!
Everyday Example
Typical settings: T = 4, α = 0.7.
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Hard one-hot labels only say 'This is a Cat (100%)'. A Teacher's soft probabilities at Temperature T=4T=4 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

Knowledge Distillation: Transferring Teacher's Soft 'Dark Knowledge'Frozen Teacher (70B)Soft probs @ Temp TKL Divergence LossMatch relative class logitsFast Student (3B) ✓10× faster, ~95% Teacher IQ
Knowledge Distillation trains a small fast Student to match a giant Teacher's temperature-softened 'dark knowledge' probability distribution (KL + Cross-Entropy)!

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 T2T^2 since dividing logits by TT scales gradients by 1/T21/T^2.

Animated Mini-Lab • Knowledge Distillation

Teacher Softmax Temperature T (Revealing Dark Knowledge)

Teacher Soft Targets: Cat 49.4% · Tiger 30.0% · Car 20.6%

2. Unstructured vs. 2:4 vs. Structured Pruning

Unstructured vs. Structured Neural Network PruningUnstructuredZeroes scattered weights2:4 Semi-StructuredNVIDIA Tensor Core sparseStructured ✓Removes whole heads/channels
Unstructured Pruning zeroes individual weights (needs sparse hardware), whereas Structured Pruning removes whole channels/heads for immediate real-world GPU speedup!
  • 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): Vertical Kernel FusionEager PyTorch3 HBM reads/writes (slow)torch.compile(m)Captures FX graph1 Fused Triton KernelStays in fast SRAM (2×+) ✓
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.

Pause & Check · Quick Intuition Pulse

What is the primary source of speedup when you wrap a PyTorch model in torch.compile(model)?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS torch.compile Kernel Fusion pipeline collapse 3 HBM trips into 1 SRAM kernel.
Interactive Animation • Compression & Compile Deep Lab

torch.compile Kernel Fusion & Student Distillation Speedup

Eliminate slow GPU HBM memory round-trips by fusing elementwise ops into one Triton kernel.

Step 1 / 4
1. Eager PyTorch launches 3 separate kernels: mul → add → gelu (6 HBM trips)
2. torch.compile(model) captures the TorchDynamo FX computation graph
3. TorchInductor compiles 1 fused Triton kernel keeping intermediates in SRAM
4. Result: 1.8×–2.5× faster training & inference with 1 line of code ✓
0%
Stage 1 / 4
Intuition Takeaway: Deploy fast, lean models with Knowledge Distillation (T^2·KL), Structured / 2:4 Pruning, torch.compile Triton kernel fusion, and ONNX / TensorRT runtimes.
Where This Powers Real ML, Deep Learning & Generative AI

Real-Time Edge Vision, Mobile AI & High-QPS Search

Combines Distillation + torch.compile / TensorRT to cut serving latency from 80ms down to <10ms.

Production NumPy & PyTorch Code Patterns
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%}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting the T^2 scaling factor on the KL distillation loss when T > 1.
Best Practice: Because soft-target gradients scale as 1 / T^2, multiply the KL term by T * T so the Teacher signal doesn't vanish relative to Cross-Entropy!
Chapter Mastery Check (+75 XP)
Score: 0 / 1
1In Hinton's Knowledge Distillation loss, why do we multiply the KL-divergence term by T^2?

Apply What You Learned — Solve Matching Coding Problems