Three serialization formats, three use cases
- state_dict (.pth / .pt) — parameters + buffers as a Python OrderedDict. Most flexible. Requires the model class to load. The default for training and research.
- torch.export (.pt2) — exported computational graph + weights. Loadable without the original Python class. The modern path for deployment.
- TorchScript (.pt) — older graph + weights format. Still widely supported but legacy for new code.
- ONNX (.onnx) — cross-framework standard. The right choice when your serving runtime isn't PyTorch (ONNX Runtime, TensorRT, OpenVINO, browser-side via onnxruntime-web).
What each format gives up
state_dict is portable across PyTorch versions and resilient to model refactors, but you need the Python class to instantiate the model. torch.export and TorchScript are self-contained but tied to the PyTorch runtime. ONNX is portable across runtimes but loses framework-specific optimizations.
The decision tree
- Sharing for further training? → state_dict.
- Deploying via PyTorch runtime? → torch.export (.pt2).
- Deploying via ONNX Runtime / TensorRT / browser? → ONNX (via the dynamo path).
- Deploying to mobile? → ExecuTorch (covered in a later lesson).
- Deploying to Apple? → CoreML (also a later lesson).