GUIDE · Updated 2026-10-24

Check Before You Load an AI Model: Python Pickle Deserialization Risks

Downloading models and datasets is routine now, but many people don't realize that Python's pickle format can execute code at the moment it's loaded. This guide explains why, how to inspect a file without running it, and which formats to use instead.

Why pickle is unsafe

Pickle isn't just a data format — it's a small stack machine. It can import any function from any module with GLOBAL or STACK_GLOBAL and call it with REDUCE. That's how it rebuilds arbitrary Python objects, but it also means a file can ask to call something like os.system while loading. The Python documentation warns plainly: never unpickle untrusted data.

Which files might be pickles?

  • PyTorch .pt, .pth and .bin files (usually a ZIP containing a pickle)
  • .pkl and .joblib files exported by scikit-learn or joblib
  • pandas read_pickle files, caches and checkpoints
  • Messages serialized with pickle in systems like Redis or Celery

How to inspect without executing

The Python pickle analyzer walks the opcodes like pickletools.dis but never executes anything, and lists the modules and functions loading would import. Entries such as os, subprocess, builtins.eval or exec are high risk. If the file is a PyTorch ZIP, extract the inner data.pkl with the ZIP inspector first.

Also record the file's SHA-256 and compare it with the published hash to make sure the download wasn't swapped.

Safer practices

  • Prefer the safetensors format for model weights — it stores tensors only and can't run code
  • Since PyTorch 2.6, torch.load defaults to weights_only=True; don't turn it off for convenience
  • Download only from trusted sources and compare published hashes
  • Handle untrusted files inside an isolated container or sandbox
FAQ

FAQ

Does static analysis guarantee a file is safe?

Not completely, but it catches the vast majority of malicious pickles that call dangerous functions directly. Treat any unfamiliar module in the import list as suspicious and handle the file in isolation.

Is JSON safer than pickle?

Yes. JSON can only represent data and never runs code when parsed. For cross-language data exchange, JSON, MessagePack or Protocol Buffers are safer choices.

Does the analyzer upload my model?

No. Files are parsed only in your browser and never sent to a server. The limit is 10 MB per file.