Back to glossary

Malicious AI Models

Malicious AI models are model files, including Hugging Face malicious models, that execute attacker-controlled code when loaded through unsafe formats like pickle.

Also known as malicious ML models, malicious machine learning models, poisoned models, model serialization attacks

Malicious AI models are machine learning model files that execute attacker-controlled code when loaded, because serialization formats like Python pickle and PyTorch's .pt run embedded instructions during deserialization. On Hugging Face and similar hubs, a Hugging Face malicious model can open a reverse shell or steal credentials when a developer calls torch.load, before any inference runs.

Our position is that a model file is a program, and you cannot tell a safe one from a hostile one by reading its model card. Like a malicious package sitting in a registry of legitimate ones, a poisoned model hides in plain sight. Of 4.47 million model versions Protect AI scanned on the Hugging Face Hub by April 2025, it flagged 352,000 unsafe or suspicious issues across 51,700 models (Hugging Face). The dangerous files look identical to the safe ones in the listing. The only reliable signal is what the file does when it is deserialized.

A model file is executable code, not data

#

Serialization normally turns an object graph into bytes and back. Python's pickle goes further: it can name a function and call it while loading. The opcodes GLOBAL (import a name) and REDUCE (call it) are part of the format. That flexibility is why PyTorch's torch.save and torch.load, built on pickle, became the default way to ship weights. The cost is that loading a model and running its author's code are the same operation.

Python's own documentation states the risk plainly: “It is possible to construct malicious pickle data which will execute arbitrary code during unpickling.” (Python docs). A .pt file is a ZIP archive whose data.pkl drives this process, and you can read the opcodes without running them:

Bash
$ python -c "import zipfile, pickletools; z=zipfile.ZipFile('model.pt'); \
  n=[x for x in z.namelist() if x.endswith('data.pkl')][0]; \
  pickletools.dis(z.read(n))"
   21: c    GLOBAL     'torch._utils _rebuild_tensor_v2'
  135: c    GLOBAL     'collections OrderedDict'
  169: R    REDUCE

A benign model imports only tensor-rebuilding helpers, as above. A malicious one adds a GLOBAL that names something like os.system and a REDUCE that calls it. Same file type, same loader, same download button. The figure below contrasts that load path with a format that has no such path.

model.pt · pickle a .pt is a zip holding data.pkl GLOBAL 'posix system' → import os.system REDUCE → call it: system("...") torch.load() executes opcodes as it reads them. Code runs before inference, before any check. Result: attacker code runs on load model.safetensors 8-byte length · JSON header · bytes N = <u64 LE> (header size) read, do not execute { "fc.weight": {dtype,shape} } strings only, no callables The loader maps named tensors to raw bytes. There is no opcode that imports or calls anything. Result: data in, no code path GLOBAL + REDUCE are the pickle opcodes that import a name and call it. safetensors has no equivalent: the format cannot name a function to run.

What the figure shows: loading model.pt walks pickle opcodes in order, so a GLOBAL 'posix system' followed by REDUCE imports and calls os.system during the load, before inference and before any inspection. Loading model.safetensors instead reads an 8-byte little-endian header length, a JSON header of tensor names, shapes, and byte ranges, and then raw bytes. Its values are strings only; the format cannot name a function, so there is no opcode to hijack.

Are Hugging Face models safe to download?

#

Hugging Face models are not safe by default, and the platform does not block the unsafe ones. Hugging Face runs two automated scans on every commit: a pickle import scan built on pickletools.genops that lists the imports a file references without executing it, and a ClamAV malware scan on files under 2 GB (Hugging Face docs). Both scans label files; neither stops a download. A model badged “unsafe” still installs when you call from_pretrained.

Signing does not close the gap. Hugging Face's documentation notes that a signed commit “does not guarantee that your file is safe, but it does guarantee the origin of the file.” Provenance tells you who published a file, not whether its weights were tampered with. A compromised maintainer publishes a poisoned model through a legitimate, correctly signed pipeline.

A second execution path is trust_remote_code. Loading a custom architecture requires from_pretrained(..., trust_remote_code=True), which runs the repo's modeling_*.py on your machine. Hugging Face recommends pinning a commit hash through the revision argument so an updated repo cannot swap the code under you between runs.

How can an AI model contain malware?

#

An AI model contains malware wherever the loader turns file contents into executable behavior, and every major format has such a path with a CVE to prove it. The model file is the payload; the loader is the trigger. Three paths beyond raw pickle matter most:

  • Keras Lambda layers embed arbitrary Python that runs when the model is built. CERT/CC's VU#253266 documents this for TensorFlow and Keras models built before Keras 2.13. A later bypass, CVE-2025-1550, let a crafted .keras config import and call functions even with safe mode enabled, until Keras 3.8.0.
  • GGUF chat templates live in model metadata. llama-cpp-python rendered that template through Jinja2 with no sandbox, so crafted metadata reached remote code execution (CVE-2024-34359, CVSS 9.6, fixed in v0.2.72)
  • PyTorch's own “safe” path was not always safe. torch.load(weights_only=True) is meant to load only tensors, but CVE-2025-32434 showed it could still reach RCE on versions up to 2.5.1, fixed in 2.6.0. The advisory is blunt: “When loading model using torch.load with weights_only=True, it can still achieve RCE.”

These are not theoretical. Socket documented the same class of flaw in PyTorch Lightning, where torch.load and pickle in the checkpointing path exposed users to code execution from untrusted .ckpt files across every version up to 2.4.0.

Scanners miss what they are built to blocklist

#

Most model scanners work by blocklist: parse the pickle, flag known-dangerous imports. Two weaknesses follow. A blocklist is a ceiling on names someone already labeled bad, not a description of behavior. And if an attacker makes the parser disagree with the real deserializer, the scan and the load see different files.

Both failures are demonstrated. In January 2025, ReversingLabs found two models on Hugging Face that evaded picklescan by compressing the PyTorch file with 7z instead of ZIP and breaking the pickle stream after the payload. picklescan reported an error on the corrupt file instead of flagging the dangerous functions that ran before the break, while deserialization executes opcodes as it reads them. Both files carried a reverse shell, and Hugging Face removed them within 24 hours. Separately, a parsing bug in picklescan's handling of the STACK_GLOBAL opcode (CVE-2025-71325) let a crafted file slip past until version 0.0.27.

Our position: analyze what the artifact actually contains, not what its format or model card claims. A scanner that only recognizes the imports it already knows is detecting yesterday's payloads. It is the model-ecosystem version of a rule the package registries already paid for: the attack executes at load time, the way most supply chain attacks execute at install time, so inspection has to happen before the loader runs.

How do you load an untrusted model safely?

#

To load an untrusted model safely, prefer a format that cannot run code. safetensors stores an 8-byte little-endian header length, a JSON header mapping each tensor to a dtype, shape, and byte range, then a raw buffer (safetensors). Header values are strings only, so the format has no way to name a function and no deserialization code path to hijack. You can confirm the entire structure in a few bytes:

Python
import struct, json
raw = open("model.safetensors", "rb").read()
n = struct.unpack("<Q", raw[:8])[0]     # header length, unsigned 64-bit LE
header = json.loads(raw[8:8 + n])       # {'fc.weight': {'dtype': 'F32', ...}}
# everything after raw[8 + n:] is tensor bytes — nothing is executed

When you must load pickle-based weights, the controls stack but none is complete. As of November 2026, PyTorch 2.6 and later default torch.load to weights_only=True, which restricts the unpickler to rebuilding tensors:

FormatRuns code on load?MechanismSafe default today
pickle / .bin / .pt (weights_only=False)YesGLOBAL + REDUCE import and call a nameNo
.pt, weights_only=True (torch 2.6+)RestrictedTensor-only unpickler; default since 2.6Yes, but see CVE-2025-32434
Keras Lambda / .kerasYesLambda runs Python; config can importsafe_mode on by default since 2.13
GGUF (llama-cpp-python)Via metadataChat template rendered by Jinja2Patched in 0.2.72+
safetensorsNoJSON header + raw bytes, no callablesYes

Verdict: default to safetensors, and convert pickle weights to it before you share them. When you genuinely need torch.load, run it with weights_only=True on PyTorch 2.6 or later and load the file inside a sandbox with no network, because a loader CVE can still defeat the restricted unpickler.

The part a safe format does not fix

#

safetensors ends code execution on load. It does not make the weights trustworthy. A model can be backdoored in its parameters, trained to behave normally until a trigger input flips it, with no malicious opcode anywhere in the file. That payload survives conversion to safetensors untouched, because it is the model, not a rider on the format. Scanning a file tells you whether loading it is safe; it does not tell you whether the model itself was poisoned.

Socket's experimental Hugging Face scanning inspects PyTorch, TensorFlow, Keras, TFLite, GGUF, and Llamafile artifacts for the load-time class of attack and ingests AIBOM files, so model risk can ride existing supply-chain workflows (Socket). Proving a set of weights does only what it claims, with no behavioral backdoor, is still an open problem, and it is the harder half.