Sub topic 6
Where Pickle Shows Up in ML Workflows
Assume you know basic Python classes and special methods, understand model weights, and have used a deep learning framework such as PyTorch. This chapter focuses on recognizing pickle in common machine learning workflows and deciding when loading it is unsafe.
Pickle is often hidden behind a library
Pickle is Python's built-in object serialization format. Serialization turns an object into bytes that can be stored. Deserialization reconstructs the object from those bytes.
Machine learning libraries use pickle because a trained object often contains more than numeric weights:
- A scikit-learn estimator contains learned arrays, configuration, and class information.
- A preprocessing pipeline contains transformers and their fitted values.
- A PyTorch checkpoint can contain a model's
state_dict, optimizer state, training counters, and metadata. - A Python package may use
cloudpickleto save functions, lambdas, or dynamically created classes. - The
jobliblibrary commonly saves scikit-learn models and may use pickle-compatible serialization internally.
The file extension does not prove that a file is safe. A file named model.bin, model.pkl, or checkpoint.pt can contain pickle data. You must know how the producing tool writes the file.
Scikit-learn and Python pipelines
A scikit-learn model is usually saved after training so another process can reuse it without fitting again. For example, a pipeline may contain a scaler followed by a classifier. Pickle can preserve the complete Python object graph.
This is convenient, but the loader must import classes and reconstruct objects. Those operations are part of pickle's instruction stream. Loading a file from an unknown source is therefore equivalent to allowing that source to control part of the Python process.
joblib.load does not remove this risk. It provides useful storage behavior for large NumPy arrays, but its input still requires trust.
PyTorch checkpoints
PyTorch commonly uses torch.save and torch.load for checkpoints. A checkpoint may include:
- A dictionary of parameter tensors.
- Optimizer state such as momentum values.
- The current epoch and validation score.
- Model configuration.
- Custom Python objects.
PyTorch stores tensor data efficiently, but checkpoint metadata has historically relied on Python pickle. Consequently, a .pth or .pt file is not automatically a data-only tensor file.
Recent PyTorch versions provide a restricted loading mode:
import torch
state_dict = torch.load(
"model.pth",
map_location="cpu",
weights_only=True,
)
model.load_state_dict(state_dict)weights_only=True limits which objects the unpickler may reconstruct. It is safer for a checkpoint that should contain tensors and simple containers, but it is not a substitute for verifying the file's source.
Check the producer before choosing a loader
| Artifact | Common loading tool | Possible pickle involvement | Safer practice |
|---|---|---|---|
| scikit-learn pipeline | `joblib.load` or `pickle.load` | Yes | Load only trusted artifacts |
| PyTorch checkpoint | `torch.load` | Often | Use `weights_only=True` |
| Tensor-only weights | `safetensors.torch.load_file` | No | Prefer safetensors |
| ONNX graph | ONNX runtime or parser | No Python pickle by design | Validate the graph and runtime |
Before loading a third-party artifact, identify its format, inspect available metadata, prefer a data-only alternative, and load it in an isolated environment if trust is uncertain.
Exercise
Why is a PyTorch file with a .pth extension not necessarily safe to load with torch.load?
Show answer
The extension does not identify the internal format. The checkpoint may contain pickle instructions that reconstruct Python objects and execute code during loading. Use weights_only=True when appropriate and prefer a verified data-only format.