Model serialization

Also known as: model file format

On this page 7

Model serialization is the process of converting a trained machine learning model, including its learned parameters, architecture and metadata, into a byte stream or model file format that can be written to disk, transferred and later reconstructed in another process. In MLOps & deployment, serialization is the boundary between training and serving: the file it produces is what a model registry stores, what a CI/CD pipeline tests and what an inference server loads.

The choice of format decides more than file size. It determines which runtimes can load the model, whether the file can execute arbitrary code when opened, how quickly a server can start, and whether a model trained years ago can still be reproduced. Within artificial intelligence engineering, serialization is therefore treated as an interface contract, not a minor implementation detail.

How model serialization works

Serialization captures two kinds of state: the numerical weights learned during training and the description of how those weights are combined at inference time. Some formats store only the weights and expect the loading code to rebuild the architecture, while others store a complete computation graph that a runtime can execute without the original source code.

The reverse step, deserialization, reads the file and rebuilds an in-memory object. With weight-only formats such as a PyTorch state_dict, the engineer must instantiate the same model class before loading, so code and file must stay in sync. With graph formats such as ONNX or TensorFlow SavedModel, the file is self-describing, which decouples the serving stack from the training framework.

A robust serialized artifact usually includes more than tensors. Production teams add preprocessing steps, tokenizer files, label maps, input and output signatures, and the library versions used in training. Without this context, a perfectly loaded model can still produce wrong predictions, a failure mode that overlaps with training-serving skew.

The following table lists what a complete serialized model typically contains and why each element matters.

ComponentTypical contentWhy it matters
WeightsTensors in float32, float16, bfloat16 or int8Defines learned behavior
Architecture or graphLayer definitions or operator graphAllows execution without source code
SignatureInput names, shapes, data typesPrevents malformed requests
Preprocessing assetsTokenizer, vocabulary, scalersKeeps features consistent with training
MetadataFramework version, opset, training run IDSupports lineage and reproducibility
Components of a serialized model artifact

Common model file formats

Formats differ mainly in portability, safety and loading speed. Python-native formats are convenient during experimentation, while interchange and tensor-only formats dominate in regulated or high-throughput serving environments.

The table below compares the formats most often encountered in production machine learning systems.

FormatStoresExecutes code on loadTypical use
Pickle / joblibArbitrary Python objectsYesscikit-learn models, prototypes
PyTorch .pt / .pthWeights or full modules via pickleYes, unless weights-only mode is enforcedPyTorch training checkpoints
TorchScript / torch.exportTraced or exported graphNo Python codeC++ and mobile serving
TensorFlow SavedModelGraph, weights, signaturesNo arbitrary PythonTensorFlow Serving, TFX
ONNXFramework-neutral operator graphNoCross-framework and edge inference
SafetensorsTensors and a JSON header onlyNoLarge language model weights
GGUFQuantized tensors and metadataNoLocal inference of language models
Widely used model serialization formats

Tree ensembles add their own options: XGBoost and LightGBM provide native JSON or binary formats that are more stable across library versions than pickling the Python wrapper object.

Security risks of unsafe formats

The most serious risk is that pickle-based files can execute arbitrary code during deserialization. The pickle protocol allows an object to specify a callable that runs when it is rebuilt, so loading an untrusted .pkl or legacy .pt file is equivalent to running an untrusted program. This is the mechanism behind the model serialization attack documented in AI security frameworks.

Defensive practice follows a few clear rules. Teams should load only artifacts from trusted registries, prefer tensor-only formats such as Safetensors for distribution, enable weights-only loading in PyTorch, scan downloaded files with dedicated model scanners and verify integrity through hashes or model signing. Formats that cannot execute code reduce the attack surface but do not remove the need for provenance checks.

Choosing a format for deployment

The right format depends on the serving runtime, the hardware target and the trust boundary. A model that never leaves a single team can tolerate convenience formats, while a model published to partners or deployed on edge devices needs a portable and safe representation.

The decision table below summarizes common situations.

SituationRecommended formatReason
Python microservice, trusted sourceFramework-native formatSimplest path, full fidelity
Cross-framework or edge runtimeONNXBroad runtime and hardware support
Sharing large weights publiclySafetensorsNo code execution, fast memory mapping
High-throughput GPU servingCompiled engine built from ONNX or exportOptimized kernels, lower latency
Local language model on a laptopGGUFQuantized weights for CPU inference
Format selection by deployment situation

Many teams keep two representations: a framework-native checkpoint for retraining and fine-tuning, and an exported serving artifact. Model packaging then wraps the serving artifact with dependencies and a container image, and the model registry records both under one version.

Limitations and common mistakes

Serialization failures rarely appear during training; they surface at load time in production, often months later. The table below lists frequent problems and their remedies.

SymptomLikely causeFix
Load error after an upgradeLibrary version driftPin versions, export to a stable format
Predictions differ from trainingMissing preprocessing assetsSerialize the full pipeline
Export fails or drops operatorsUnsupported custom layersRegister custom operators or rewrite the layer
Slow cold startLarge file loaded fully into memoryUse memory-mapped tensors, warm-up requests
Numerical mismatch after conversionPrecision or operator differencesRun parity tests with tolerances
Typical serialization problems

A frequent misconception is that a successful export proves correctness. In practice, teams should run output parity tests comparing the original and the exported model on a fixed validation set, typically accepting absolute differences around 1e-5 for float32 and larger tolerances for float16 or quantized variants.

In plain words

A trained model lives in a computer’s memory. When the program stops, the model disappears. Serialization saves the model to a file, much like saving a document before closing a word processor.

Later, another program opens that file and gets the same model back. Some file types are like plain text: they only hold data. Others are like documents with macros: they can run hidden instructions when opened. That is why careful teams prefer the safe kind and only open files from sources they trust.

A real-world example

A logistics company trains a demand forecasting model in PyTorch on a GPU cluster. The data science team saves weekly checkpoints as framework-native files so they can resume training. For production, the release pipeline exports the best checkpoint to ONNX, attaches the feature scaler and a signature describing 42 input columns, and registers the result with a version number and a SHA-256 hash.

Before promotion, an automated test loads both versions and compares predictions on 10,000 historical rows; the maximum difference must stay below 1e-4. The ONNX file then runs on CPU-only servers in regional warehouses. Cold-start time drops from about 40 seconds to under 5 seconds, and the servers no longer need PyTorch installed, which removes a large dependency and an unsafe loading path from the production environment.