Sub topic 6
Where pickle shows up in ML workflows
This chapter assumes you know how pickle turns objects into an opcode stream and why __reduce__ lets a pickle run code on load. It also assumes you have used PyTorch or scikit-learn to save a model. Here you will learn where pickle appears in everyday machine learning (ML) work, which uses cross a trust boundary, and how to find pickle-based files before you load them.
Why pickle became the default
Pickle ships with Python and handles almost any object: nested dictionaries, custom classes, NumPy arrays, lambdas (through extensions). Saving a trained model takes one call and no schema. ML libraries adopted it because model objects are Python objects, and pickle needs no extra code per class.
That convenience is the source of the risk. A pickle describes how to rebuild an object by naming callables and arguments, so the loader must run those callables. Whenever a library saves or loads with pickle, you need to know who produced the bytes.
Two kinds of pickle use
Pickle appears in ML in two different ways, and they carry different risk.
- Artifacts at rest. A file saved to disk, shared through a model hub, a registry or a download link, and loaded later, often by someone else. The file crosses a trust boundary, so this is where attacks happen.
- Data in motion. Objects pickled and sent between processes of the same job, such as data loader workers, task queues and cluster schedulers. Both ends are normally under your control, but the risk returns if an untrusted party can reach the channel.
Artifacts at rest
PyTorch checkpoints
torch.save serializes with pickle, and torch.load unpickles. The common extensions are .pt, .pth and .ckpt. Many Hugging Face repositories also use pytorch_model.bin, which is the same format despite the .bin name. The next chapter opens one of these files and shows how the pickle and the tensor data are laid out.
Newer repositories usually publish a model.safetensors file next to the older .bin. If both exist, prefer the safetensors file. Recent versions of Hugging Face transformers also prefer it when it is present.
scikit-learn and joblib
The scikit-learn documentation shows pickle.dumps(model) and joblib.dump(model, "model.joblib") as the standard way to persist an estimator. joblib is pickle with optimizations for large NumPy arrays. A .joblib file can therefore run code on load just as a .pkl file can, and compression does not change that.
A fitted estimator also depends on the library version that produced it. Loading it under a different scikit-learn version can fail or silently misbehave, even when the file is trustworthy.
NumPy and pandas
numpy.loadhas defaulted toallow_pickle=Falsesince NumPy 1.16.3. Arrays of plain numeric types load without pickle. Arrays withdtype=objectneed pickle, so settingallow_pickle=Trueon a file you did not create re-opens the risk.pandas.read_pickleandDataFrame.to_pickleuse pickle directly. The pandas documentation warns against loading pickled data from untrusted sources. Datasets passed around as.pklfiles deserve the same suspicion as model files.
Other model libraries
Many libraries accept or produce pickle even when they offer a native format:
- XGBoost supports pickling, but its documentation recommends its own JSON or UBJSON model files for long-term storage.
- LightGBM can save a plain-text model file with
save_model, although users often pickle the sklearn wrapper instead. - MLflow's
sklearnflavor stores a pickle or cloudpickle by default, and its genericpython_functionflavor uses cloudpickle for custom models. Pulling a model from a shared registry therefore means unpickling it. - Experiment caches and feature stores often store pickled Python objects in files, Redis or object storage. Whoever can write to those locations can run code in every process that reads them.
Data in motion
Pickle is also the default way Python moves objects between processes:
multiprocessingqueues and pipes pickle every object they transfer. PyTorchDataLoaderworkers rely on this, which is why datasets andcollate_fnfunctions must be picklable.torch.distributedfunctions such asbroadcast_object_listpickle arbitrary objects between ranks.- Ray, Dask and PySpark use cloudpickle (or a close variant) to send functions and closures to workers.
- The Hugging Face
datasetslibrary usesdill, a pickle extension, to compute cache fingerprints for transformation functions.
Treat these channels as trusted only when the network and storage under them are trusted. An open scheduler port, a shared cache directory, or a message queue that accepts writes from other tenants becomes a code execution path, even though no model file is involved.
Summary table
| Workflow | Typical call | Pickle involved | Safer option |
|---|---|---|---|
| PyTorch checkpoint | `torch.save`, `torch.load` | Yes, in the archive's `data.pkl` | `safetensors`, or `torch.load(..., weights_only=True)` |
| Hugging Face `.bin` | `from_pretrained` on an old repo | Yes | Prefer `model.safetensors` |
| scikit-learn model | `joblib.dump`, `pickle.dump` | Yes | Load only files you trust, or use ONNX export |
| NumPy arrays | `numpy.load` | Only with `allow_pickle=True` | Keep the default `False` |
| pandas frame | `read_pickle` | Yes | Parquet or CSV |
| Worker communication | `multiprocessing`, Ray, Spark | Yes | Secure the channel and its storage |
Finding pickle in a model directory
File extensions are not reliable. A .bin file may be pickle-based or something else, and an attacker can rename a pickle to anything. Checking the file contents is more dependable. The script below flags files that look like pickle streams, or zip archives containing a .pkl member, which is the PyTorch layout.
import sys
import zipfile
from pathlib import Path
CANDIDATE_SUFFIXES = {".pkl", ".pickle", ".joblib", ".pt", ".pth", ".bin", ".ckpt"}
def pickle_evidence(path):
"""Return a description if the file looks pickle-based, otherwise None."""
if zipfile.is_zipfile(path):
with zipfile.ZipFile(path) as zf:
for name in zf.namelist():
if name.endswith(".pkl"):
return f"zip archive with pickle member {name}"
return None
with open(path, "rb") as f:
head = f.read(2)
# Pickle protocol 2 and later starts with the PROTO opcode 0x80 and a version byte.
if len(head) == 2 and head[0] == 0x80 and 2 <= head[1] <= 5:
return f"raw pickle stream, protocol {head[1]}"
return None
def main(root):
for path in sorted(Path(root).rglob("*")):
if path.is_file() and path.suffix.lower() in CANDIDATE_SUFFIXES:
evidence = pickle_evidence(path)
if evidence:
print(f"{path}: {evidence}")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else ".")Run it with python find_pickle.py ./models. The script has limits:
- It misses pickle protocols 0 and 1, which have no
0x80header. - It misses compressed joblib files, because their first bytes are the compression header.
- It can report a false positive on a non-pickle file whose first two bytes happen to match.
Treat a match as a prompt to inspect the file with pickletools.dis, which disassembles the opcodes without executing them. Treat a non-match as "unknown", not "safe".
Common errors
- Trusting the extension. Safe-looking names such as
weights.binormodel.datatell you nothing about the format. - Trusting the hub. A public model page is not a security review. Anyone can upload a pickle-based file.
- Enabling
allow_pickle=Trueto silence an error. The error was the warning. Find out why the file needs pickle first. - Assuming the file is trusted because your own pipeline wrote it. If the output directory or bucket is writable by others, the file is only as trusted as the weakest writer.
- Forgetting data in motion. Securing downloaded checkpoints does not secure an exposed Ray or Dask endpoint.
Exercise
Your team's training job writes features.pkl to a shared bucket that several teams can write to, and an inference service loads it with pickle.load. The service never downloads anything from the public internet. Is it safe from the risk described in this chapter? Explain why or why not.
Show answer
No. The bucket is a trust boundary. Any team, or any attacker with write access to the bucket, can replace features.pkl with a pickle that calls arbitrary functions, and the inference service runs that code when it loads the file. The fact that nothing comes from the public internet does not matter. Safe handling means restricting write access to the bucket, verifying a checksum or signature before loading, and preferably storing the data in a format that holds only data, such as Parquet or safetensors.
Exercise
Name two ML workflows where pickle is used without you ever calling pickle.load yourself, and say whether each is an artifact at rest or data in motion.
Show answer
Examples: torch.load on a .pt or pytorch_model.bin checkpoint (artifact at rest), joblib.load on a scikit-learn model (artifact at rest), loading a model from an MLflow registry (artifact at rest), DataLoader worker processes passing batches through multiprocessing (data in motion), and Ray or Spark sending functions to workers (data in motion).