
19 November 2026 · ML System reading notes · 5/6
ML System 05: Conversion and Compression
Part five moves into chapter 9 of the book, model deployment, starting with its first three sections (9.1–9.3): the problems deployment has to solve, how a trained model becomes an optimized inference model, and model compression through quantization, sparsity and knowledge distillation. This chapter cleared up two misunderstandings of mine: ONNX isn't for converting PyTorch code into TensorFlow, and the 37B that DeepSeek-V3 uses per token isn't pruned out of the full model. Sparsity led me to MoE, so that's in here too, and at the end I look at how NVIDIA's TensorRT puts these optimizations to work in a real inference compiler.
What deployment has to solve
The book gives two ways to make inference faster. One is to design dedicated chips, which win on energy efficiency. The other is hardware–software co-design, getting the most out of the hardware you already have. On a CPU, for example, that means thinking about:
- how to split data into blocks that fit in the cache;
- how to reorder data so computation can read it contiguously;
- how to reduce data dependencies between computations so the hardware pipeline can do more in parallel;
- how to extend the instruction set for better compute performance;
- how to design and optimize separately for each CPU architecture.
The book then lists the problems deployment has to deal with:
- Operator fusion: merge several operators into one, through expression simplification, attribute fusion and similar techniques.
- Constant folding: anything that can be computed ahead of time is computed before deployment and stored as a constant, so inference doesn't redo it. For example,
y = x * (2 * 3)becomesy = x * 6at compile time. - Model compression: shrink the model's size and computational cost with quantization, pruning and so on. Some of these techniques need retraining and some don't.
- Data layout: work out the best layout for each layer of the network, then reorder the data or insert layout-conversion operators to cut latency. I wrote about layouts like NCHW and NHWC in part two.
- Model obfuscation: this belongs to model security, which is the next part.
Model conversion
Training frameworks and inference engines usually use different model formats, so the first step of deployment is conversion, for example running a converter that turns a PyTorch model into an ONNX model.
The book puts the essence of conversion plainly: a model is structured data, and converting it means moving it from one data structure to another. You start by analyzing where the two structures agree and where they differ. Parts with the same structure are copied over, similar parts are mapped, parts that differ a lot have to be translated sensibly according to their semantics, and anything incompatible can't be converted.
A model's data structure breaks down into two parts: the model topology, meaning how the nodes in the graph connect, and the operator prototype definitions, meaning each operator's inputs, outputs and attributes.
ONNX
At first I thought ONNX (Open Neural Network Exchange) was for turning PyTorch code into TensorFlow or JAX. Its main use is actually handing a trained model over to the deployment environment.
It's a model file format: a static computational graph plus the trained weights, along with a standard operator list that fixes what MatMul, Conv, Relu and the rest are called and what their parameters and behavior are, so everyone reads and writes against the same standard. Microsoft and Facebook launched it together in 2017.
Why a common format? It's the M×N problem again, the same logic as LLVM:
- On the training side there are M frameworks: PyTorch, TensorFlow, PaddlePaddle…
- On the deployment side there are N inference engines or hardware targets: TensorRT, ONNX Runtime, OpenVINO (Intel), Core ML (Apple), the inference libraries for each phone chip…
Without a common format you need M×N pairwise integrations. With ONNX, frameworks only export ONNX and engines only read ONNX, so it becomes M+N.
Today ONNX is still widely used in classic CV and on-device deployment (phones, edge devices), but less and less for large models. vLLM and TensorRT-LLM build the model architectures in and load only the weights (safetensors): large-model architectures are fixed, and things like the KV cache and continuous batching are hard to express as one generic static graph.
Operator fusion, replacement and reordering
After conversion, the graph gets another round of optimization aimed at inference.
Operator fusion
Fusion cuts the network's parameter count, compute, number of operators and memory accesses. A common example is folding a BN that follows a convolution into the convolution itself: at deployment, BN's mean, variance, γ and β are all fixed numbers, so they can be folded straight into the convolution's weights and bias, and the BN operator is no longer needed.
This kind of fusion only works at deployment. During training, BN uses each batch's statistics and γ and β are still being learned, so folding it in would change the algorithm and hurt convergence and accuracy. At deployment it's an equivalent transformation with no side effects. The only thing to watch is numerical error under low precision or quantization.
Operator replacement and reordering
Operator replacement swaps some operators in the model for ones that compute the same thing but suit online deployment better.
Operator reordering rearranges the topological order of the model's operators by certain rules, cutting the amount of computation at inference without lowering accuracy.
Quantization
Quantization approximates continuous floating-point weights with a finite set of discrete values, at a small cost in accuracy. Representing floats with fewer bits makes the model smaller and inference faster. 8 bits is the most common choice, and anything below 8 bits is called low-bit quantization. I wrote about the trade-offs between number formats like FP16, BF16, FP8 and INT4 in another post.
Linear and non-linear quantization
Linear quantization uses evenly spaced levels. Non-linear quantization packs its levels around 0, where the data is dense, so the error and the accuracy loss are smaller. The catch is that the levels are uneven, so you can't do integer multiply-adds directly: values have to be looked up in a table and turned back into floats first, which makes the computation more complex.
Quantization-aware training and post-training quantization
Depending on when the quantization happens, there are two kinds:
- Quantization-aware training (QAT) simulates quantization during training, using fake-quantization operators so the accuracy lost to quantization shows up in the training loss.
- Post-training quantization (PTQ) quantizes the model after training is done.
Post-training quantization in turn comes in two forms: weight-only quantization and full quantization.
Weight-only quantization quantizes just the weights. They're stored as INT8, so the model shrinks to 1/4 of its FP32 size. At compute time only the current small block is temporarily turned back into floats and thrown away afterwards, so memory use doesn't grow. The conversion back is needed because activations are still floats, and the hardware can't do a mixed INT8 × FP32 multiply. It needs no calibration data.
Full quantization quantizes both weights and activations and computes directly with INT8 operators, which is what actually speeds things up. The price is that it needs calibration data: activations depend on the input, so you have to run a few hundred real samples through the model to learn their range.
Calibration and error correction
Calibration means finding the best clipping range. The most direct way is to use the maximum and minimum, but a few outliers can stretch the range so far that most values get squeezed into a handful of levels. Another way picks the range with KL divergence:
- Build a histogram of the FP32 activations and call this distribution .
- Try several clipping ranges, quantize with each one, and get a distribution .
- Pick the range with the smallest KL divergence between and , and compute the scale factor from it.
After quantization you can also apply error correction:
- Mean correction: per channel, compare the average of the FP32 output with the average of the quantized output, and add the difference to the bias.
- Weight distribution correction: per channel, bring the mean of the quantized weights back to where it was.
Methods used for LLMs
LLMs almost always use PTQ. Two common methods:
- GPTQ: after quantizing each weight, adjust the weights that aren't quantized yet to cancel out the error.
- SmoothQuant: move part of the outliers in the activations over to the weights. Activations with outliers are hard to quantize, while weights are fairly easy, so some of the difficulty is shifted across.
Sparsity
Sparsity turns unimportant weights or activations into 0. Zeros don't need to be stored or computed, which saves storage and compute. It can be stacked with quantization.
Why can anything be removed? Models are generally over-parameterized, and in many vision tasks only a small part of the feature map carries useful information.
Which weights to remove is usually decided by absolute value: weights with a small magnitude barely affect the output, so they're pruned. The fraction of zeros is called the sparsity. Higher sparsity costs more accuracy, so the goal is to prune as much as possible without losing much.
Structured and unstructured
| Unstructured sparsity | Structured sparsity | |
|---|---|---|
| What's pruned | any single weight anywhere; fine-grained | whole channels or whole kernels; coarse-grained |
| Accuracy | removes exactly the least useful weights, so little loss | too coarse, may prune useful weights too, so more loss |
| Speed | hard to actually speed up | leaves a smaller dense matrix that CPUs and GPUs handle efficiently as usual, so real speedups |
Unstructured sparsity is hard to accelerate because the matrix stays the same size with zeros scattered everywhere, which makes it irregular computation at heart:
- With zeros everywhere, the code has to check whether to compute each one, which adds lots of if-else branches and kills instruction-level parallelism.
- Each thread gets a different number of non-zeros, so threads diverge and the load is uneven; the 32 threads in a warp can't move in step.
- Non-zeros are scattered across memory, so accesses aren't contiguous and the cache hit rate is low.
Unstructured sparsity is like sending random students out of a classroom: the empty seats are scattered, the room is just as big, and the teacher still has to walk every row. Structured sparsity carries out whole rows of desks, and the room actually gets smaller.
The compromise is a fixed sparsity pattern, such as the 2:4 sparsity NVIDIA has supported since the A100: in every 4 consecutive weights, exactly 2 are zero. You choose which two, which is like unstructured sparsity and keeps accuracy good, but the pattern is fixed, which is like structured sparsity and easy for the hardware. Sparse Tensor Cores skip these zeros directly and double matrix-multiply throughput.
Train, prune, fine-tune
The most common flow is train → prune → fine-tune: train a converged dense model, prune it, and if accuracy drops, fine-tune to bring it back. The trained parameters carry what the model learned, so pruning from there works better than pruning from initialization. You can also alternate training and pruning, a little at a time, which makes redundant kernels easier to find.
The full Deep Compression pipeline (Han et al., 2015) is train → prune → fine-tune → quantize → Huffman coding. Pruning reduces the number of weights, quantization reduces the bits per weight, and Huffman coding compresses the storage further. Pruning comes first, then quantization.
Huffman coding is lossless compression: frequent symbols get short codes and rare ones get long codes, the way Morse code gives the most common letter, E, a single dot. It only saves storage and transfer, so for example the model file a phone downloads is smaller. It doesn't save compute: variable-length codes can't be read randomly in parallel, so before inference they have to be decoded back into a fixed-length format.
There are pruning methods for LLMs too, such as SparseGPT and Wanda, which can prune 50% in one shot or prune to 2:4. But unstructured sparsity rarely turns into real speed, so in practice deployment uses quantization far more than pruning.
MoE: a dynamic kind of sparsity
Sparsity led me to MoE. Pruning removes weights permanently before deployment. MoE removes nothing, and each token picks a subset to use on the spot. I'll use DeepSeek-V3 as the example.
How 671B relates to 37B
DeepSeek-V3 has 671B parameters in total, but each token uses only about 37B. At first I thought this meant picking out 37B first and then pruning inside those 37B. That's wrong. The 37B is simply what you get after the picking, and nothing is deleted.
All 671B stay resident in GPU memory. At every MoE layer, a router picks 8 of the 256 routed experts for each token, plus 1 shared expert, and the rest are skipped. The parts used every time, such as attention and the embeddings, plus the experts picked at each layer, add up to the roughly 37B parameters each token actually uses.
A hospital has 256 specialists, all on staff (in memory). For each patient (token), the triage desk (the router) sends the 8 best-matched specialists plus 1 general practitioner. The next patient gets triaged again from scratch.
How it differs from pruning
| Pruning | MoE | |
|---|---|---|
| Are weights removed? | permanently, before deployment | no, only part is used each time |
| Sparsity pattern | fixed | picked per token on the spot (dynamic) |
| Granularity | single weights or channels | whole experts; inside an expert it's still a dense matrix multiply, which is hardware-friendly and saves real compute |
What it saves and what it doesn't
- Compute: always saved, since each token only does about 37B parameters' worth of computation.
- Memory: not saved, since all 671B have to be loaded, which is why running V3 takes many GPUs.
- Bandwidth: depends on the batch. When serving a single user, only the picked experts are read, which saves a lot, so MoE is relatively cheap to run on a Mac. With a large batch, different tokens pick different experts, almost every expert gets read, and the saving mostly disappears.
One router per layer
Put simply, MoE replaces each layer's single FFN with many FFNs and leaves attention alone. DeepSeek-V3 has 61 layers:
- Layers 1–3: attention → an ordinary FFN (dense, no routing).
- Layers 4–61 (58 layers): attention → this layer's router → pick 8 of this layer's 256 experts, plus 1 shared expert → weighted sum → on to the next layer.
58 MoE layers means 58 routers, each working on its own. Experts aren't shared across layers either: expert 3 in layer 5 and expert 3 in layer 6 are two completely different networks. That makes 58 × 256 = 14,848 routed experts in total, each a small FFN. Each token picks again at every layer based on its current hidden state, so its path through the model is 58 independent choices. Attention works as in a dense model: all tokens in a layer share that layer's attention, and each layer has its own attention parameters.
The router is simple. Each expert gets a vector, the router computes its similarity with the token's hidden state, picks the top 8, and uses the similarities as the weights for the weighted sum. It's trained end to end with the rest of the model.
Routers tend to play favorites and keep sending tokens to a few experts, so they need load balancing. V3 adds an adjustable bias to each expert's score: lowered when the expert is too busy, raised when it's too idle.
The division of labor between "experts" is learned during training. Nobody assigns a "math expert" or a "code expert", and often the split can't be explained in human terms.
The KV cache has nothing to do with experts
In each layer, a token goes through attention first and then the FFN (the MoE part). The KV cache comes from the attention layer, where every token uses the same and with no routing. Experts live in the FFN and produce no K or V.
So the KV cache is sized exactly as in a dense model: layers × tokens × how much is stored per token, and the number of experts appears nowhere in the formula. The next part works out how big V3's KV cache gets at a million tokens.
An expert that isn't picked really never sees the token at all, and that's fine: an FFN works on each token by itself anyway, and tokens only exchange information in attention. Which experts are picked changes the values a token carries out of the layer, which in turn changes the values of the K and V it computes in the next layer, but not their shape or size.
As an analogy, each layer is a meeting. First everyone writes notes on the same whiteboard in the meeting room and reads each other's (attention plus the KV cache). After the meeting, each person goes off to see their own specialist advisors (the experts), then walks into the next meeting room with new ideas.
Knowledge distillation
Knowledge distillation first trains a strong large model as the teacher, then trains a small model as the student, which learns the teacher's way of thinking. While the student trains, the teacher's parameters are frozen and only the student is updated.
A small model normally trains on hard labels: for a picture of a cat, the label is just 0s and a 1. The teacher's output carries more information, such as how likely the picture is to be a dog or a car, and the student can learn more from that. A more accurate teacher helps, but what matters more is that its output says what the input resembles and what it doesn't, so even a teacher that isn't much more accurate than the student can still help.
The student's loss is:
Here is cross-entropy, and are the student's and teacher's outputs, is the true label, is the softening function, and balances the two terms.
- The first term is how far the student's own output is from the true label. The teacher makes mistakes too, so this term stays in, with the true labels as a safety net.
- The second term is how far the student's softened output is from the teacher's softened output.
The student is optimized on this loss, looking at both its gap to the true label and its gap to the teacher.
Why soften? The teacher is usually very confident, with outputs close to [0.99, 0.01, 0.0000…], so the dog and car probabilities are too small to see and the student can't learn from them. Dividing by a temperature before the softmax, , flattens the distribution so those small probabilities show up.
The student can also learn from the teacher's intermediate representations to pick up even more. The student's intermediate layers are narrower, so a small projection layer is usually added to match the dimensions before they can be compared.
TensorRT: a compiler and runtime just for inference
NVIDIA's TensorRT does the constant folding, operator fusion, quantization and memory planning described above. It only does inference and only supports NVIDIA GPUs, compiling a trained model into an executable for one specific GPU model. The principle is the frontend-to-backend path from part two, with every step pushed as far as it goes.
It works in three steps. The first is import: usually PyTorch → ONNX (static graph plus weights) → read into TensorRT, which now has the full plan.
The second is build, done offline, which can take minutes or longer:
- Graph optimization: remove useless layers, fold constants, and fuse heavily. Vertical fusion merges chains like Conv + BN + ReLU into one kernel. Horizontal fusion merges layers that share an input into one wider layer, such as combining the Q, K and V projections into one large matrix multiply. Concat elimination has the earlier operators write their results straight into the right place in the final output.
- Lower precision: FP32 → FP16 / INT8 / FP8 / FP4. INT8 needs calibration on a small batch of real data, which checks the range each layer's values fall in before deciding how to compress them. This is the full quantization from the quantization section.
- Kernel auto-tuning, the core of it: each layer has many candidate implementations (tactics), each one is measured on the GPU at hand, and the fastest wins. It's the same idea as
torch.compile'smax-autotune, taken further. - Memory planning: work out in advance where every intermediate result lives and how memory is reused.
- Finally the result is serialized into an engine file.
The third is run: load the engine and execute it directly, with no PyTorch or Python needed, optionally wrapped in a CUDA Graph.
The costs are clear:
- The engine is tied to the hardware. One tuned on an A100 can't be used on an H100, and a new TensorRT version needs a rebuild too, because "pick the fastest" was measured on that particular GPU.
- Shapes have to be declared up front. Variable-length inputs need minimum, typical and maximum sizes (an optimization profile), a compromise between fixed shapes and variable inputs.
- Unknown operators need hand-written kernels, registered as plugins.
Compared with torch.compile:
torch.compile | TensorRT | |
|---|---|---|
| Scope | general and flexible; works for training and inference | inference only, NVIDIA only |
| When it compiles | on the fly, at runtime | ahead of time, spending a long time before deployment to optimize as far as possible |
| Trade-off | more flexible | usually faster, but more rigid |
TensorRT-LLM adds a layer for large models: in-flight batching (continuous batching), paged KV cache (the KV cache managed in fixed-size blocks), hand-written attention kernels, and multi-GPU parallelism.
From PyTorch to TensorRT
As part two showed, torch.compile can use TensorRT as its backend. But that still compiles at runtime, so deployment still needs Python and PyTorch. To drop Python entirely and keep just an engine file, there are two routes:
- Use
torch.exportto export the complete static graph ahead of time, then have Torch-TensorRT compile and save it. It's stricter thantorch.compileand doesn't allow graph breaks. - Or take the older route: PyTorch → ONNX → TensorRT.
torch.compile suits "still running in PyTorch, borrowing TensorRT for speed"; torch.export and ONNX suit "deploying standalone in the end".
References
- openmlsys, Machine Learning Systems: Design and Implementation
- Han et al., Deep Compression: Compressing Deep Neural Networks with Pruning, Trained Quantization and Huffman Coding
- Frantar et al., GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers
- Xiao et al., SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models
- Frantar and Alistarh, SparseGPT: Massive Language Models Can Be Accurately Pruned in One-Shot
- Sun et al., A Simple and Effective Pruning Approach for Large Language Models (Wanda)
- DeepSeek-AI, DeepSeek-V3 Technical Report