Can simply loading a downloaded ML model file execute attacker code?
Short answer
Yes. Pickle-based model files (the default format for PyTorch weights) can execute arbitrary code during unpickling; Python's docs say to only unpickle data you trust. Scanners help but are not foolproof. Prefer a data-only format such as safetensors, load only from trusted, verified sources, and treat model artifacts like any other executable supply-chain input.
A model file feels like data, which is exactly why this is a favourite senior-level AI-security question. In many ecosystems it is closer to a program.
The mechanism
Python's pickle documentation opens with a warning: the module "is not secure", malicious pickle data can "execute arbitrary code during unpickling", and you should never unpickle data from an untrusted source. The Hugging Face Hub documentation notes that pickle is the default format for PyTorch model weights, and explains how pickled opcodes can import builtins such as exec or eval and call them, so a model file can run code the moment it is loaded.
Defences and their limits
- Safer formats: the Hub docs suggest alternatives such as
safetensors; Python's docs suggest formats like JSON for untrusted data. - Trust and provenance: load from sources you trust; signed commits prove origin but not safety.
- Scanning: the Hub lists the imports found in pickle files and highlights suspicious ones, but explicitly states this is not 100% foolproof.
- Restricting globals with a custom unpickler is possible per the Python docs, but needs great care about what you allow.
Why it matters for a pipeline
Automated jobs that pull community models run with whatever credentials the CI or notebook has, so a poisoned file becomes a supply-chain compromise. Isolate model loading, prefer data-only formats, and pin and verify artifacts.
Why the distractors are tempting
"Just numbers" ignores the container format. "Antivirus catches it" is contradicted by the Hub's own note that ClamAV does not cover pickle exploits. "Only at inference" is wrong: the code runs at load.
What interviewers want
Name pickle, the code-execution-on-load behaviour, and safetensors plus provenance controls as the fix.
Likely follow-ups
- Why is a pickle scanner that lists imports helpful but not sufficient?
- How does safetensors avoid this class of risk?
- What controls would you add to a pipeline that pulls community models automatically?