Model Serialization Systems
“Training is Art. Serialization is Logistics. Wars are won on logistics.”
TL;DR
Model serialization is the bridge between research notebooks and production inference. ONNX provides a safe, graph-based interchange format that decouples your training framework from deployment targets like C++, mobile, and cloud runtimes. For large models exceeding available RAM, sharding and zero-copy formats like Safetensors eliminate pickle security risks while enabling efficient memory-mapped loading. Always bundle metadata (input shapes, class labels) with your serialized artifacts and track versions in an immutable artifact store. See also LLM Serving for how serialized models are deployed at scale.

1. Problem Statement
You have just finished training a state-of-the-art Transformer model in PyTorch. It lives in your Python RAM as a complex graph of objects (nn.Linear, nn.MultiheadAttention).
Now, your Production Engineering team says:
- “We need to run this on a C++ server for low latency.”
- “We need to run this on an iPhone (Core ML).”
- “We need to archive this exact version for 7 years for compliance.”
The Problem: How do you save the “Soul” of the model (Architecture + Weights + Logic) into a file that is Portable, Versioned, and Efficient?
This is the Model Serialization problem. It is the bridge between Research (Python/Notebooks) and Production (C++/Mobile/Cloud).
2. Understanding the Requirements
2.1 What needs to be saved?
A model isn’t just weights. It is:
- Parameters (Weights): Giant tensors of floats (The “Knowledge”). ~100MB to 100GB+.
- Computation Graph (Architecture): The “Map” of how data flows (Matrix Mul -> Relu -> Add).
- Metadata: “Input must be 224x224”, “Output class 0 = Cat”, plus the preprocessing (tokenizer, normalization constants) the model expects.
2.2 Functional Requirements
- Interoperability: Train in PyTorch -> Run in ONNX Runtime / TensorRT.
- No “Code” Dependency: The serialized file should be self-contained. I shouldn’t need the original
model.pyfile to load it. - Security: Loading a model shouldn’t execute arbitrary code (The Pickle problem).
3. High-Level Architecture
The standard approach for portable deployment is an Interchange Format (usually ONNX).
[PyTorch Training Env] [Intermediate Rep] [Inference Env]
+-------------------+ +----------------+ +------------------+
| Model (RAM) | ---> | ONNX Protocol | ---> | ONNX Runtime |
| (Dynamic Graph) | | Buffer File | | (C++ / Go) |
+-------------------+ +----------------+ +------------------+
^
|
(Static, Optimized Graph)
By serializing to a standard like ONNX, we decouple the Authoring Tool (PyTorch) from the Execution Engine (NVIDIA Triton, TensorRT, ONNX Runtime, mobile runtimes).
4. Component Deep-Dives
4.1 The Two Philosophies: Pickle vs. Graph
Approach A: Code-Based (PyTorch torch.save)
- What it does: Uses Python’s
pickleto serialize the state dictionary (Map of “layer1.weight” -> Tensor), or the whole model object. - Pros: Easy, preserves Python flexibility (loops, if-statements).
- Cons:
- Dependency Hell: To load it, you need the exact original Python class definition source code.
- Insecure: Pickle can execute code during loading. Since PyTorch 2.6,
torch.loaddefaults toweights_only=True, which blocks most of this, but loading an untrusted checkpoint withweights_only=Falsecan still run arbitrary code on your machine.
Approach B: Graph-Based (ONNX, torch.export)
- What it does: Traces the execution of the model and records the operators (Add, MatMul). (TorchScript did this too, but it is in maintenance mode;
torch.exportis its successor.) - Pros: Self-contained. No Python code to execute on load. Language agnostic.
- Cons: Rigid. Hard to serialize dynamic logic (e.g., “if tensor.sum() > 0”).
4.2 Protocol Buffers (Protobuf)
Under the hood, ONNX uses Google’s Protobuf.
- It’s a binary format.
- It defines a schema:
Node { string op_type; repeated string input; ... }. - It is extremely compact and fast to parse compared to JSON.
- The 2GB limit: A single protobuf message cannot exceed 2GB, so larger ONNX models store their weights as external data files next to the
.onnxgraph. Plan for that in your artifact store: the model is a directory, not a file.
4.3 Choosing a Format
| Format | Contains Graph? | Safe for Untrusted Files? | Portable? | Typical Use |
|---|---|---|---|---|
PyTorch .pt / .pth (pickle) |
Only as Python objects | No (weights_only=True mitigates) |
Python + PyTorch only | Training checkpoints |
| Safetensors | No (weights + string metadata) | Yes, by design | Many languages | Sharing and loading weights, especially LLMs |
| ONNX | Yes | No Python execution; treat the runtime’s parser as attack surface | Many runtimes | Cross-framework serving |
torch.export (.pt2) |
Yes | No arbitrary Python on load | PyTorch ecosystem, ExecuTorch | AOT compilation, mobile and edge |
| GGUF | Architecture named in metadata | No code, quantized weights | llama.cpp and compatible runtimes | Local LLM inference |
| TensorRT engine | Yes, compiled | Only load your own builds | No: tied to GPU architecture and TensorRT version | Maximum GPU throughput |
Core ML / LiteRT (.tflite) |
Yes | Generally safe to load | Apple / Android and edge | On-device inference |
The practical pattern: keep Safetensors as the source of truth for weights, and generate runtime-specific artifacts (ONNX, TensorRT engines, Core ML) from it in CI.
5. Data Flow: The Tracing Process
How do we turn Python code into a Static Graph?
- Dummy Input: Create a fake tensor
x = torch.randn(1, 3, 224, 224). - Tracer: Pass
xthrough the model.- The Tracer records every low-level operation the tensor touches (Conv2d, ReLU).
- Graph Construction: It builds a Directed Acyclic Graph (DAG) of these operations.
- Weight Embedding: The constant weights are serialized as binary blobs and attached to the Graph Nodes.
- Optimization: (Optional) Constant Folding.
3 + 5is saved as8. - Export: Write
.onnxfile.
6. Scaling Strategies
6.1 Large Model Serialization (The 100GB problem)
A 70B Llama model is 140GB in FP16. Writing or reading that as one monolithic pickle forces a single process to hold the whole thing in RAM at once. Sharding:
- Save weights in chunks (
model-00001-of-00030.safetensors), plus an index file mapping each tensor name to its shard. - Zero-Copy Loading (
mmap): Map the file into virtual memory so pages are read from disk only when touched, instead of copying everything into RAM first. - Safetensors: A format from Hugging Face (2022) designed for zero-copy memory mapping and for removing the
picklevulnerability. The header is a small JSON table of tensor names, dtypes, shapes and byte offsets, followed by raw tensor bytes.
6.2 Versioning
Never overwrite model.onnx.
Use semantic versioning or hashing: model_v1.0.0_sha256.onnx.
Store in Artifactory or S3 with immutable tags.
6.3 Provenance and Signing
A serialized model is executable logic for your product, so treat it like a release binary:
- Record the SHA-256 of every artifact at export time and verify it before loading.
- Sign artifacts (for example with Sigstore-based model signing from the OpenSSF model-signing project) and verify signatures in the serving image.
- Pickle scanners help with third-party checkpoints, but they have been bypassed before; the stronger control is to accept only formats that cannot carry code. See AI model supply chain attacks for the attack paths.
7. Implementation: Exporting to ONNX
Here is how you actually serialize a PyTorch model to ONNX.
import torch
import torch.nn as nn
import torch.onnx
# 1. Define Model
class Classifier(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Linear(10, 1)
self.relu = nn.ReLU()
def forward(self, x):
return self.relu(self.fc(x))
model = Classifier()
model.eval() # Important: inference mode (BatchNorm uses running stats, dropout is off)
# 2. Create Dummy Input
dummy_input = torch.randn(1, 10)
# 3. Export
torch.onnx.export(
model,
dummy_input,
"classifier.onnx",
export_params=True, # Store the trained parameter weights inside the model file
opset_version=18, # ONNX operator set version
do_constant_folding=True, # Optimization
input_names = ['input'], # Variable names for graph
output_names = ['output'],
dynamic_axes={'input' : {0 : 'batch_size'}, 'output' : {0 : 'batch_size'}} # Allow variable batch size
)
print("Model serialized to classifier.onnx")
Verify the export before it leaves CI. Run the ONNX file in the target runtime with a batch size different from the dummy input (this also checks dynamic_axes) and compare against PyTorch:
import numpy as np
import onnxruntime as ort
session = ort.InferenceSession("classifier.onnx")
x = torch.randn(4, 10)
onnx_out = session.run(None, {"input": x.numpy()})[0]
with torch.no_grad():
torch_out = model(x).numpy()
np.testing.assert_allclose(torch_out, onnx_out, rtol=1e-4, atol=1e-5)
Save the weights as Safetensors, with metadata, as the framework-neutral source of truth:
from safetensors import safe_open
from safetensors.torch import load_file, save_file
# Metadata values must be strings
save_file(model.state_dict(), "classifier.safetensors",
metadata={"input_shape": "batch x 10", "version": "1.0.0"})
# Full load: no pickle, no code execution
model.load_state_dict(load_file("classifier.safetensors"))
# Lazy load: read one tensor without reading the rest of the file
with safe_open("classifier.safetensors", framework="pt") as f:
print(f.metadata())
fc_weight = f.get_tensor("fc.weight")
8. Monitoring & Metrics
In your serialization pipeline (CI/CD), track:
- File Size: If v2 is 2x larger than v1 unexpectedly, alert.
- Inference Speed: Run benchmarks on the
onnxfile immediately after export. - Numerical Precision: Compare
output_pytorchvsoutput_onnx, as above.- Set tolerances per model and dtype. FP32 exports usually agree to around 1e-5 to 1e-4; larger gaps point to a lossy conversion (fused or reordered operations such as LayerNorm, or an accidental precision change).
9. Failure Modes
- Opset Mismatch: You used a custom CUDA kernel or a newer operator that the target runtime’s opset doesn’t support.
- Fix: Decompose it into supported primitives (the exporter already does this for common cases, e.g. SiLU becomes
x * Sigmoid(x)), raise the opset if the runtime supports it, or register a custom operator in the runtime.
- Fix: Decompose it into supported primitives (the exporter already does this for common cases, e.g. SiLU becomes
- Dynamic Control Flow:
def forward(self, x, y): if x.sum() > 0: return x else: return yThe Tracer only sees path 1. It saves a graph that always returns x. This is a silent bug.
- Fix: Rewrite using
torch.where, or express the branch withtorch.condsotorch.export(which the newertorch.onnx.export(..., dynamo=True)path builds on) captures both branches.
- Fix: Rewrite using
- Preprocessing Drift: The exported graph is correct, but the serving code normalizes images or tokenizes text differently from training.
- Fix: Ship preprocessing with the model (tokenizer files and normalization constants in the artifact, or preprocessing ops inside the graph).
- Version Skew: A TensorRT engine built for one GPU architecture or TensorRT version fails to load (or silently falls back) on another.
- Fix: Treat compiled engines as per-target build outputs, keyed by GPU and runtime version, and rebuild them from the portable artifact.
10. Real-World Case Study: Tesla Autopilot
Tesla trains in the cloud (PyTorch clusters) but runs on the car (FSD Chip, custom Silicon), as it has described at its AI Day events. They cannot run Python in the car (too slow, too much memory). Pipeline:
- Train HydraNet (Backbone).
- Compiler: Use a custom compiler that converts the Graph into machine code specific to the FSD NPU (Neural Processing Unit).
- Quantization: Convert FP32 floats to INT8 integers to save bandwidth.
- Flash: Ship the compiled binary to cars in an over-the-air update.
11. Cost Analysis
Efficient serialization saves money.
- Storage: Storing huge checkpoints costs S3 money. Quantizing FP32 weights to INT8 before saving deployment artifacts cuts their size by 4x; keep full-precision checkpoints only for the versions you might retrain from.
- Network: Transferring 100GB models to 1,000 workers is slow and expensive (egress fees).
Safetensorsallows loading just the tensors needed (useful for sharded serving), and pulling from a regional cache avoids repeated cross-region transfers.
12. Key Takeaways
- Decouple Research from Production: Use ONNX as the contract.
- Avoid Pickle: In untrusted environments, use
Safetensorsor ONNX. It’s safer and faster (zero-copy). - Trace carefully: Be aware of “If” statements in your model code. They are the enemy of static serialization.
- Metadata matters: Always bundle the expected input shape, class labels and preprocessing with the binary.
- Verify every export: Compare outputs in the target runtime before an artifact is promoted, and hash or sign what you ship.
FAQ
What is model serialization in machine learning?
Model serialization is the process of saving a trained ML model’s architecture, weights, and metadata into a portable file format that can be loaded across different platforms, languages, and hardware without needing the original training code. It is the critical bridge between research environments (Python/notebooks) and production systems (C++/mobile/cloud).
Why is ONNX preferred over pickle for model deployment?
ONNX creates a self-contained, language-agnostic graph representation using Protocol Buffers. Loading it runs no arbitrary Python code, portable across runtimes (C++, Go, mobile), and enables hardware-specific optimizations like TensorRT. Pickle, by contrast, requires the original Python class definitions and can execute arbitrary code when loaded, making it a significant security vulnerability.
How do you serialize models larger than available RAM?
Large models use sharding to save weights in chunks (e.g., model-001-of-050.bin), zero-copy loading via mmap to map files directly to virtual memory, and formats like HuggingFace Safetensors designed specifically for memory-mapped access. This combination allows loading 70B+ parameter models without requiring the full model to fit in RAM.
What are common failure modes when exporting models to ONNX?
The two main failures are opset mismatches, where custom or newer operators are unsupported by the target ONNX runtime, and dynamic control flow, where if-statements cause the tracer to record only one execution path. The fix for the former is decomposing operations into supported primitives; the fix for the latter is rewriting logic with torch.where or capturing both branches with torch.cond and torch.export.