πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Model Compression in Practice: Prune, Quantize, Distill

🟒 Free Lesson

Model Compression in Practice: Prune, Quantize, Distill

Running a 70-billion-parameter model on a single consumer GPU sounds impossible β€” until you compress it. Model compression is the set of techniques that shrink a trained network so it fits on smaller hardware, responds faster, and costs less to serve, while giving up as little accuracy as possible. In production generative AI, compression is not a nice-to-have: it is often the difference between a prototype that demos well and a product that survives a real traffic bill.

This lesson walks through the three main compression families β€” pruning, quantization, and knowledge distillation β€” explains what each one actually changes inside the network, and shows how teams combine them into a single pipeline. You will see working PyTorch code for every technique, a comparison table that maps constraints to methods, and the production pitfalls that quietly destroy accuracy if you skip validation steps.

By the end you will be able to pick the right compression method for a latency or memory budget, implement magnitude pruning and post-training quantization from scratch, train a student model with a distillation loss, and stack techniques in a sensible order.

Why compress at all

Every parameter in a neural network costs memory and arithmetic. A model stored in 32-bit floating point needs four bytes per weight; a 7-billion-parameter model therefore needs roughly 28 GB just for weights, before you count activations or the KV cache used during generation. Many deployment targets β€” phones, embedded devices, single-GPU inference servers β€” cannot meet that budget.

Latency tells the same story from another angle. Generation speed is bounded by memory bandwidth: the hardware must stream every weight from memory for every token produced. Halving the bytes per weight nearly doubles token throughput on bandwidth-bound hardware. Compression therefore buys three things at once: smaller checkpoints, lower serving cost, and faster responses.

The catch is that every technique trades something. Pruning removes weights that the network learned to rely on. Quantization rounds numbers and loses precision. Distillation trains a smaller model that can only approximate its teacher. The engineering skill is matching the technique to your constraint and measuring the damage honestly on a held-out set, not on the training data.

Three families of compression

TechniqueWhat changesTypical size reductionAccuracy costRetraining needed
Unstructured pruningSets small weights to zero2–10Γ— (sparse storage)Low–mediumFine-tune after pruning
Structured pruningRemoves whole neurons/channels2–4Γ—MediumUsually yes
Post-training quantizationCasts weights to INT8/INT42–4Γ— (INT8), up to 8Γ— (INT4)Low at INT8, higher at INT4No (calibration only)
Quantization-aware trainingSimulates low precision during trainingSame as aboveLower than post-trainingFull training run
Knowledge distillationTrains a smaller student on teacher outputs5–100Γ— (smaller architecture)MediumFull student training

Read the table as a decision guide. If you need a quick win this week and your model already runs on the target hardware, post-training quantization is the lowest-effort option. If the architecture itself is too large, distillation is the only path that produces a genuinely smaller network. If your inference framework supports sparse kernels, unstructured pruning can deliver large wins; if it does not, structured pruning is what actually reduces latency.

Magnitude pruning from scratch

The simplest pruning method is magnitude pruning: compute the absolute value of every weight, pick a global threshold, and zero out everything below it. The intuition is that small weights contribute little to the output, so removing them perturbs the function less than removing large ones.

python
import torch
import torch.nn as nn
from typing import Dict

class MagnitudePruner:
    def __init__(self, model: nn.Module):
        self.model = model
        self.masks: Dict[str, torch.Tensor] = {}

    def create_mask(self, sparsity: float = 0.5):
        all_weights = []
        for name, param in self.model.named_parameters():
            if param.dim() > 1:
                all_weights.append(param.data.abs().flatten())

        threshold = torch.quantile(torch.cat(all_weights), sparsity)

        for name, param in self.model.named_parameters():
            if param.dim() > 1:
                self.masks[name] = (param.data.abs() >= threshold).float()

    def apply_mask(self):
        for name, param in self.model.named_parameters():
            if name in self.masks:
                param.data.mul_(self.masks[name])

    def sparsity_report(self) -> Dict[str, float]:
        total = sum(p.numel() for p in self.model.parameters())
        zeros = sum((m == 0).sum().item() for m in self.masks.values())
        return {"sparsity": zeros / total, "params": total}

pruner = MagnitudePruner(model)
pruner.create_mask(sparsity=0.7)
pruner.apply_mask()
print(pruner.sparsity_report())

Two details matter in real training. First, one-shot pruning on a converged model usually hurts; the standard practice is iterative pruning β€” prune a small fraction, fine-tune to recover, repeat. Second, zeros must be re-applied after every optimizer step, because momentum and Adam updates will otherwise resurrect the pruned weights. Frameworks handle this with hooks; the manual equivalent is re-multiplying the mask after each step.

Quantization: shrinking every byte

Quantization maps continuous weights onto a discrete grid. INT8 quantization stores each weight as one of 256 integer values plus a scale factor, cutting memory fourfold compared to float32 with surprisingly little accuracy loss on most models. INT4 halves memory again but is much riskier: outlier weights that fall far from the mean get crushed by the coarse grid.

Post-training quantization needs no gradient updates β€” just a small calibration set so the runtime can observe activation ranges and choose clipping thresholds:

python
import torch
import torch.nn as nn
import os

def dynamic_quantize(model: nn.Module) -> nn.Module:
    return torch.quantization.quantize_dynamic(model, {nn.Linear}, dtype=torch.qint8)

def model_size_mb(model: nn.Module) -> float:
    tmp = "/tmp/_size_check.pq"
    torch.save(model.state_dict(), tmp)
    size = os.path.getsize(tmp) / 1024 / 1024
    os.remove(tmp)
    return size

float_model = model.eval()
int8_model = dynamic_quantize(float_model)

before = model_size_mb(float_model)
after = model_size_mb(int8_model)
print(f"float32: {before:.1f} MB -> INT8: {after:.1f} MB ({before / after:.1f}x smaller)")

For large language models, dedicated algorithms such as GPTQ and AWQ go further: they inspect activation outliers per channel and compensate by rescaling weights before rounding, which is what makes 4-bit serving of 7B+ models practical. The lesson in all of them is the same β€” protect the outlier channels, quantize the rest aggressively, and always validate on a task-specific eval set rather than trusting a generic perplexity number.

Distilling knowledge into a smaller student

Quantization and pruning keep the architecture and shrink its storage. Knowledge distillation attacks the problem from the other side: train a genuinely smaller network to mimic the behavior of a large teacher. The trick, introduced by Hinton and colleagues, is to train on the teacher's soft probabilities rather than only on hard labels. Soft targets carry dark knowledge β€” the teacher's belief that class B is almost as likely as class A β€” and that signal is far richer than a one-hot vector.

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class DistillationLoss(nn.Module):
    def __init__(self, temperature: float = 4.0, alpha: float = 0.7):
        super().__init__()
        self.temperature = temperature
        self.alpha = alpha

    def forward(self, student_logits, teacher_logits, labels):
        soft = F.kl_div(
            F.log_softmax(student_logits / self.temperature, dim=1),
            F.softmax(teacher_logits / self.temperature, dim=1),
            reduction="batchmean",
        ) * (self.temperature ** 2)
        hard = F.cross_entropy(student_logits, labels)
        return self.alpha * soft + (1 - self.alpha) * hard

def distill_one_epoch(teacher, student, loader, criterion, optimizer):
    teacher.eval()
    student.train()
    total = 0.0
    for inputs, labels in loader:
        with torch.no_grad():
            teacher_logits = teacher(inputs)
        student_logits = student(inputs)
        loss = criterion(student_logits, teacher_logits, labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
        total += loss.item()
    return total / len(loader)

The temperature parameter controls how soft the distributions become. Higher temperature flattens probabilities and exposes more of the teacher's ranking among unlikely classes; the temperature-squared term rescales the gradient so learning rates stay comparable. In practice, values between 2 and 8 work well, and alpha around 0.5 to 0.9 balances soft and hard signal depending on how much labeled data you have.

Stacking techniques in the right order

Compression methods compose, but order matters. The sequence that works in most production pipelines is: distill first if the architecture must shrink, then prune, then quantize. Distillation produces a new set of weights that still live in full precision; pruning removes redundant connections inside that smaller model; quantization is applied last because it is the least reversible step and benefits from a model that is already stable.

A combined pipeline looks like this:

python
class CompressionPipeline:
    def __init__(self, model, teacher=None):
        self.model = model
        self.teacher = teacher

    def run(self, config, train_loader=None):
        if config.get("distill") and self.teacher is not None:
            criterion = DistillationLoss(
                temperature=config.get("temperature", 4.0),
                alpha=config.get("alpha", 0.7),
            )
            optimizer = torch.optim.Adam(self.model.parameters(), lr=1e-4)
            for _ in range(config.get("distill_epochs", 5)):
                distill_one_epoch(
                    self.teacher, self.model, train_loader, criterion, optimizer
                )

        if config.get("prune_sparsity"):
            pruner = MagnitudePruner(self.model)
            pruner.create_mask(config["prune_sparsity"])
            pruner.apply_mask()
            for _ in range(config.get("recover_epochs", 2)):
                fine_tune_one_epoch(self.model, train_loader)

        if config.get("quantize"):
            self.model = dynamic_quantize(self.model.eval())

        return self.model

Notice the fine-tuning recovery step after pruning. Skipping it is the most common way teams lose several accuracy points for no reason β€” the weights need a few epochs to reorganize around the missing connections.

Validating compression honestly

Benchmark on the exact task and the exact hardware you will ship on. A compressed model that looks fine on average accuracy can fail on the tail cases that matter: long inputs for quantized LLMs, rare classes after pruning, out-of-distribution data after distillation. Track at minimum: task metric before and after each stage, latency at the target batch size, peak memory, and throughput in tokens or items per second.

Also measure twice β€” once with the model warm and once cold. Quantized runtimes sometimes pay a startup cost that hides in benchmarks. And keep the uncompressed checkpoint until the compressed one has survived a full production cycle; rollback insurance is cheap compared to an incident.

Common Mistakes

Pruning once and never fine-tuning

Fix: Use iterative pruning with short fine-tuning rounds between sparsity steps; the network recovers most of the lost accuracy.

Skipping calibration data for quantization

Fix: Run 100–500 representative batches through the model before converting so activation ranges are observed, not guessed.

Evaluating compression on training data

Fix: Hold out a task-specific eval set that includes the hard cases; compression damage concentrates exactly there.

Applying unstructured pruning on hardware without sparse kernel support

Fix: Prefer structured pruning (whole channels) or quantization when your runtime cannot skip zeros efficiently.

Distilling with hard labels only

Fix: Train the student on the teacher's softened logits with temperature scaling β€” that is where the extra signal lives.

Key Takeaways

  • Compression buys memory, latency and cost at the same time β€” measure all three, not just accuracy.
  • Magnitude pruning, quantization and distillation attack different bottlenecks: weights, numeric precision, and architecture size.
  • INT8 post-training quantization is the fastest win; INT4 and pruning need more careful validation.
  • Distillation works because soft targets carry ranking information that hard labels throw away.
  • Stack techniques in order β€” distill, prune, quantize β€” and fine-tune between stages.
  • Always validate on a held-out task set and on the actual target hardware before shipping.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement