DaZu / PyTorchDaZu home

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

Code → original RAM
Live process
  1. 1 · ConstructInitialize live tensors.
  2. 2 · TrainUpdate live weights.
RAM → disk
Persistent file
  1. 3 · SaveWrite state to a file.
  2. 4 · Close processRAM ends; file remains.
Disk → new RAM
New process
  1. 5 · ReconstructBuild a compatible model.
  2. 6 · RestoreLoad saved state.
Inference

Save weights + buffers and model/input contract. Rebuild → load → eval + no_grad → predict.

Resume training

Also save optimizer and relevant run state. Rebuild model + optimizer → restore → continue.

Reuse encoder

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 / toolWhat it doesWhat to check
save / load / load_state_dictSerialize and restore state.Matching architecture and tensor names/shapes; map_location="cpu" for CPU loading.
weights_only=TrueRestrict 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.
MLflowConnect parameters, metrics and artifacts to a run.Tracking is separate from deploying an endpoint.
Pruning / quantizationMask 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.
Restore a trusted weights file · architecture already constructed
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

FP32 · 40 MB
FP16 / BF16 · 20 MB
INT8 · 10 MB

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