Sub topic 2
Where Pickle Shows Up in ML Workflows
This chapter assumes you know Python classes, have trained or loaded a model in PyTorch, and understand what a state dict is (a dictionary that maps parameter names to tensors).
Pickle in model tooling
Pickle is Python's built-in serialization format. Many ML tools use it, including torch.save, joblib.dump (common in scikit-learn), and NumPy object arrays. Loading a pickle can run code, so treat any pickle-based file as code written by its author.
Inside a PyTorch checkpoint
A .pt or .pth file saved with torch.save is a pickle that usually holds a state dict:
import torch
import torch.nn as nn
model = nn.Linear(2, 1)
torch.save(model.state_dict(), "linear.pth")Restricting what an unpickler may import
An unpickler looks up each global name through its find_class method. Overriding that method with an allowlist blocks everything else:
import io
import pickle
ALLOWED = {("collections", "OrderedDict")}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if (module, name) in ALLOWED:
return super().find_class(module, name)
raise pickle.UnpicklingError(f"blocked global: {module}.{name}")
def safe_loads(data: bytes):
return RestrictedUnpickler(io.BytesIO(data)).load()Loading PyTorch files with weights_only=True
Pass weights_only=True to torch.load to allow only tensors and simple containers. PyTorch 2.6 made this the default. Pass it explicitly anyway so the intent is clear and older versions behave the same way:
import torch
state_dict = torch.load("linear.pth", map_location="cpu", weights_only=True)safetensors: a data-only tensor format
The safetensors format stores tensor names, dtypes, shapes, and raw bytes. It contains no executable instructions, so loading it cannot run code:
import torch
from safetensors.torch import save_file, load_file
save_file({"weight": torch.zeros(2, 2)}, "model.safetensors")
tensors = load_file("model.safetensors")
print(tensors["weight"].shape)Exercise
Why does torch.load with weightsonly=True reject a checkpoint whose pickle calls os.system through reduce_?
Show answer
That load path only permits tensors and basic containers. os.system is a callable outside that set, so the unpickler raises an error before the call runs.