6 · Course 3 / Quick guide
Save, compress and deploy models
Keep the right model state, reuse components, and prepare predictions for a CPU or another compatible runtime.
Builds on Fundamentals, Training, Vision and Text. Follow architectures → saved state → compression → validated inference.
How it works
From RAM to disk and back
- 1 · ConstructInitialize live tensors.
- 2 · TrainUpdate live weights.
- 3 · SaveWrite state to a file.
- 4 · Close processRAM ends; file remains.
- 5 · ReconstructBuild a compatible model.
- 6 · RestoreLoad saved state.
Save weights + buffers and model/input contract. Rebuild → load → eval + no_grad → predict.
Also save optimizer and relevant run state. Rebuild model + optimizer → restore → continue.
Save encoder state and contract. Rebuild encoder → restore → attach a new head.
State dictionaries need compatible architecture code. A saved file is not a running model.
A model object lives in CPU RAM or holds tensors on a GPU. Saving persists state to disk; loading tensors alone does not recreate its forward implementation. state_dict() includes learned parameters and persistent buffers. Save the input preprocessing and class/tokenizer mapping too.
For inference, construct the compatible architecture, restore its state, call eval() and run without autograd. For training resumption, also restore optimizer state and relevant scheduler, scaler, random and data-order state. A component such as an encoder can be saved separately and reused with a new head.
Code and functions
| Function / tool | What it does | What to check |
|---|---|---|
save / load / load_state_dict | Serialize and restore state. | Matching architecture and tensor names/shapes; map_location="cpu" for CPU loading. |
weights_only=True | Restrict deserialization to supported objects. | It does not discard optimizer state or extract weights automatically. |
deepcopy(state_dict()) | Keep an independent in-memory snapshot. | A plain state dictionary references live tensor storage. |
| MLflow | Connect parameters, metrics and artifacts to a run. | Tracking is separate from deploying an endpoint. |
| Pruning / quantization | Mask connections / reduce numerical representation. | Zeros preserve dense shapes; fewer bits need supported kernels and quality checks. |
onnx.export(..., dynamo=True) | Export a supported inference graph. | Allowed input shapes, operators and outputs in the actual runtime. |
state = torch.load("weights.pt", map_location="cpu", weights_only=True)
model.load_state_dict(state)
model.eval()
with torch.inference_mode():
logits = model(inputs)Course quantization examples use legacy eager APIs. Current PyTorch directs new quantization development toward torchao; choose a compatible version and hardware backend.
Check your understanding
Same number of weights, different payload
10 million dense values: 4, 2 or 1 byte per value. Decimal MB; 40 MB ≈ 38.15 MiB.
Hypothetical weight payload only. Activations, buffers, gradients, optimizer state, quantization metadata and runtime overhead are additional; not a device benchmark.
Ten million FP32 values occupy 40 MB of payload. INT8 uses 10 MB for those values, but the application still needs other memory. Masking half the FP32 values to zero keeps the original dense slots.
Dynamic quantization estimates ranges during execution; static quantization uses representative calibration inputs; QAT simulates rounding/clipping during training before conversion. Measure the chosen result on the small CPU that will run it.
Common mistakes
- Keeping only weights when an exact optimizer continuation is required.
- Assuming
strict=Falseaccepts incompatible same-name tensor shapes. - Claiming smaller files or faster CPU inference solely because weights became zero.
- Assuming export or quantization preserves quality without output comparisons and held-out evaluation.
- Comparing timings with different preprocessing, batches or CPU thread settings.