Model Serialization (Pickle, Joblib, ONNX)
Persist models portably with pickle/joblib and export ONNX for cross-runtime inference.
In plain words
Serialising a model means saving it to a file so you can load it later or somewhere else, and picking a format that is safe, small and works wherever you need it.
Think of it like…
Freezing a cooked meal for later. You need the dish (the model), the recipe notes (preprocessing and versions) and a sealed, trusted container; a mystery container from a stranger (an unverified pickle) might contain anything, and a meal frozen in a special pot (a Python-only format) can only be reheated in a kitchen that owns that pot.
Where you’ve seen it
A churn pipeline is a scikit-learn Pipeline (a ColumnTransformer with imputers and one-hot encoders feeding a gradient-boosting model) saved with joblib.dump(pipe, "churn-v12.joblib", compress=3); saving the whole pipeline, not just the classifier, prevents the classic bug where the API applies different preprocessing than training. The file is 480 MB uncompressed; compression trades a smaller size for slower load (illustrative: about 2 seconds to load, which matters for cold starts). Alongside it the team stores model_card.json with the scikit-learn, NumPy and pandas versions, the input schema (feature names, dtypes) and a SHA-256 of the file, because loading a pickle or joblib file in a different scikit-learn version can warn, break or change behaviour. Security: unpickling can run arbitrary code defined by the file, so the service only loads artefacts it built itself, fetched from a private registry over TLS and verified against the stored hash; third-party model files are never unpickled in the main service. For the high-throughput scoring service they convert to ONNX with skl2onnx and run it in ONNX Runtime: a parity test scores 1,000 held-out rows with both the original and the ONNX model and asserts the maximum absolute difference is below 1e-5 (float32 versus float64 usually differs around 1e-7), and the converted model loads without installing scikit-learn, shrinking the container and removing a version-coupling risk. Typical order-of-magnitude behaviour (to be measured, not assumed): single-row latency is lower in ONNX Runtime than in the Python estimator, and batch throughput benefits from its optimised kernels. PyTorch models save state_dict (weights only) plus the class definition in code, or export to ONNX or TorchScript for deployment; safetensors is used for tensors from external sources because it can't execute code. A smoke test loads the artefact in a clean environment and predicts a golden sample with a known output before every release.
Words you’ll hear
- Pickle
- Python's object serialisation format; loading it can execute arbitrary code.
- Joblib
- A pickle-based format efficient for large NumPy arrays, common for scikit-learn.
- ONNX
- A framework-neutral model format executed by ONNX Runtime.
- Parity test
- A check that the converted model's predictions match the original within a tolerance.
Visual diagram
Theory & deep dive
Pickle, joblib and their risks
Pickle serialises Python objects by recording how to rebuild them, including calls to arbitrary callables, which is why pickle.load on an untrusted file can execute attacker-chosen code. Treat a pickle like an executable: load only files produced by your own pipeline, stored in a private location and verified with a hash or signature. Joblib (joblib.dump, joblib.load) uses pickle underneath but stores large NumPy arrays efficiently, supports compression levels (compress=3 trades size for load time) and memory mapping, which makes it the standard for scikit-learn estimators; the same security caveat applies. Both formats are tied to library versions: a model saved with one scikit-learn version may fail to load or behave differently in another, so pin versions, record them with the artefact and test loading in the target environment.
Safer alternatives exist for specific cases: skops persists scikit-learn models with a trusted-types check, safetensors stores tensors without executable code and is designed for sharing weights, and ONNX or PMML store models as data, not code. None of these removes the need to save the whole pipeline, because a classifier without the imputers, scalers and encoders that fed it will receive differently prepared data in production.
churn-v12.joblib (480 MB), SHA-256 a41f…. model_card.json: python 3.11.8, scikit-learn 1.5.2, numpy 2.0.1, pandas 2.2.2; inputs: tenure_months int, monthly_charges float, contract category; trained on data v3, git 9be3c1.
ONNX, conversion and parity testing
ONNX represents a model as a graph of standard operators with typed inputs and outputs. You convert (skl2onnx.convert_sklearn, torch.onnx.export, converters for XGBoost and LightGBM), then run with ONNX Runtime, which provides optimised CPU and GPU kernels and bindings for many languages. Benefits: serving without the training framework (smaller container, fewer dependency conflicts), a stable runtime across training-library upgrades and often lower latency. Costs: not every operator or custom transformer converts, behaviour can differ subtly (float32 versus float64, handling of unseen categories) and debugging a graph is harder than debugging Python.
Always run a parity test after conversion: score a representative set of 1,000 or more held-out rows (include edge cases such as missing values and unseen categories) with the original and the converted model, and assert that the maximum absolute difference in probabilities is below a tolerance such as 1e-5 and that the predicted classes agree. Add a golden sample test to CI that loads the artefact in a clean environment and checks a known input gives the known output, plus a size and load-time check (a 480 MB model that takes 2 seconds to load affects cold starts and autoscaling). Measure latency and throughput on your hardware rather than assuming a speed-up. Document the input signature (names, types, shapes) next to the artefact so the API can validate requests against it.
Score 1,000 held-out rows with sklearn predict_proba and ONNX Runtime. Compute max |p_sklearn − p_onnx| = 3.2e-7 < 1e-5 ✓. Predicted classes agree on 1,000 of 1,000 rows ✓. Rows with unseen category 'weekly' behave identically (handled as all-zeros one-hot) ✓.
How it works, step by step
Step 1 of 41. Save the whole pipeline
Serialise preprocessing and model together with the input schema, library versions and a content hash.
- Pin
- library versions
When to use it & trade-offs
What it is
Model serialisation saves a trained model (and its preprocessing) to a file so it can be loaded elsewhere. Pickle is Python's native format and can store almost any object, but loading it executes code, so it must never be used on untrusted files. Joblib is a pickle-based format optimised for large NumPy arrays (compression, memory mapping) and is the usual choice for scikit-learn. ONNX (Open Neural Network Exchange) stores the model as a framework-neutral computation graph that runs in ONNX Runtime from Python, C++, Java or the browser without the training library. Deep learning frameworks add their own formats (torch.save state dicts, TorchScript, SavedModel), and safetensors stores tensors without executable code. Whatever the format, a model is only reproducible when you also save the preprocessing pipeline, the library versions and a signature of expected inputs.
Why it matters: Training and serving usually happen in different places and times: a model trained on a laptop is loaded in a container months later with possibly different library versions. Serialisation choices decide whether that load works, whether predictions match, how large and fast the artefact is and, critically, whether a poisoned file can run attacker code on your server. A mistake here shows up as silent prediction drift after a library upgrade or as a security incident.
When to reach for it
- joblib for scikit-learn pipelines served from Python
- ONNX for polyglot or high-throughput serving
- Hash and signature checks on every artefact load
When to avoid or be careful
- Loading pickle files from unknown sources
- Saving only the classifier without preprocessing
- Skipping a parity test after format conversion
Serialisation formats
Strengths: Works on almost any Python object.
Watch out: Executes code on load; version-fragile.
Strengths: Efficient; compression and memory mapping.
Watch out: Same security and version caveats as pickle.
Strengths: Runs without training libraries; many languages.
Watch out: Conversion limits; harder to debug.
Strengths: No executable code (safetensors).
Watch out: Needs the architecture defined in code.
Interview signals & numbers to know
When this topic comes up
- “Why is pickle dangerous?”
- Joblib versus pickle
- Why and how to export to ONNX
- Version compatibility of saved models
- Verifying a converted model
Benchmarks & rules of thumb
- 1e-5
- typical parity tolerance for probabilities after conversion
- ≈ 1e-7
- usual float32 versus float64 difference
- 480 MB / ≈ 2 s
- example artefact size and load time that affect cold starts
Common mistakes & follow-ups
Common interview mistakes
- Assuming a pickle saved last year will load unchanged after an upgrade.
- Comparing predictions for exact equality instead of a tolerance.
- Forgetting unseen-category behaviour in the converted model.
Likely interviewer follow-ups
- How would you ship a model to a service that has no scikit-learn?
- How do you make sure a loaded model is the one you trained?
- What goes in a model's metadata?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Model Serialization (Pickle, Joblib, ONNX) with data science interview Q&A and hands-on practice.