Training is iterative; inference is performance-critical
Once the model trains, you optimize it for serving. Three techniques you'll combine routinely:
torch.compile(model)— JIT-compile the model graph with TorchInductor. 1.5-3x speedup with one line of code. (Full coverage in the next track.)- Quantization — reduce numerical precision (fp32 → int8 or int4) for smaller model and faster matmul. Modern path is
torchao. - Batching — instead of running 32 single-sample inferences, run one 32-sample batch. Underutilization is real cost.
The order to apply them
- Get correctness right with eager-mode + fp32. Verify outputs.
- Switch to bf16 if your hardware supports it. Verify accuracy holds.
- Add
torch.compile(model). Verify speed and accuracy. - Quantize if you need more (int8 dynamic for transformers, int8/int4 weight-only for LLMs).
- If you're serving requests, batch across users with a small queueing window.
Don't forget the Python overhead
Tokenization, post-processing, serialization can dominate inference time on small models. Profile end-to-end (HTTP request → response), not just the forward pass. The fix is often "cache the tokenizer" or "use a faster JSON library" rather than anything model-side.