Model serialization attack

Also known as: pickle deserialization attack · malicious model file

On this page 7

A model serialization attack is an attack in which an adversary embeds executable code inside a saved model file, so that the code runs when a victim loads the model, often before any prediction is made. In AI security, it is one of the most practical supply chain threats, because sharing pretrained weights through public hubs and internal registries is routine and loading a file feels harmless.

The attack is also known as a pickle deserialization attack or a malicious model file. It does not target the model’s mathematics, as adversarial examples do; it targets the file format and the loader. Any format that can reconstruct arbitrary objects or execute embedded logic during loading is a potential carrier.

How a model serialization attack works

Serialization converts an in-memory model into bytes, and deserialization rebuilds it. Python’s pickle protocol rebuilds objects by following instructions stored in the file, including instructions to call any importable function with chosen arguments. A class can define __reduce__ to tell pickle which callable to invoke during loading, and an attacker can point that callable at an operating system command.

Because PyTorch checkpoints saved with torch.save are ZIP archives containing a pickle stream, a call to torch.load on an untrusted file can execute attacker code with the privileges of the loading process. The model can still load and work normally afterwards, so the victim sees no visible symptom.

The typical attack chain has four stages, summarized in the table below.

StageAttacker actionResult
PreparationAdds a payload to a legitimate modelModel still performs as expected
DistributionUploads to a model hub or registryFile looks like an ordinary checkpoint
LoadingVictim calls the framework loaderPayload executes during deserialization
Post-exploitationSteals keys, installs a backdoor or moves laterallyHost or pipeline compromise
Stages of a typical model serialization attack

Vulnerable and safer model formats

Risk depends on whether the format stores code or only data. Formats that hold only tensors and metadata cannot execute anything on load, while formats that store objects, layers or graphs with custom operations can.

The table below compares common formats used in machine learning by their inherent risk on load.

FormatStores executable logicRisk when loading untrusted files
Pickle files (.pkl)Yes, arbitrary callablesHigh
PyTorch checkpoints (.pt, .bin)Yes, via embedded pickleHigh unless restricted loading is used
Joblib filesYes, built on pickleHigh
Keras models with Lambda layersYes, serialized Python codeHigh in older versions or unsafe mode
ONNXGraph with possible custom operatorsLow to moderate
GGUFTensors and metadataLow, parser bugs remain possible
SafetensorsTensors and metadata onlyVery low by design
Model file formats and their deserialization risk

A safe format reduces but does not eliminate risk. Parser vulnerabilities, malicious tokenizer files, custom model code fetched with options such as trust_remote_code, and poisoned weights remain possible, so format choice is one control among several.

How it differs from other AI security attacks

A model serialization attack is a classic software exploit delivered through an ML artifact. Its impact is code execution, not a wrong prediction, which separates it from attacks on model behavior.

ThreatTargetImpactTrigger
Model serialization attackLoader and hostArbitrary code executionLoading the file
Model poisoningModel weightsHidden backdoor behaviorA specific input trigger
Data poisoningTraining dataDegraded or biased modelTraining on the data
Evasion attackInference inputMisclassificationA crafted input
Dependency confusionPackage managerCode executionInstalling a package
Model serialization attack compared with related threats

The attack sits within the broader field of AI supply chain security. Frameworks such as MITRE ATLAS and the OWASP Machine Learning Security Top 10 describe it under supply chain compromise, and it is closely related to model signing and the AI bill of materials as defenses.

Defenses against malicious model files

Effective defense combines safe formats, restricted loading, scanning and isolation. No single measure is sufficient, because scanners miss novel payloads and safe formats do not cover every component of a model package.

ControlWhat it doesLimitation
Safetensors by defaultRemoves code execution from weight loadingNot all models are published in it
Restricted loadingUses options such as weights_only=TrueOlder framework versions lack it
Model scanningDetects dangerous pickle opcodes and importsCan be evaded by obfuscation
Model signingVerifies publisher identity and integrityDoes not prove the publisher is benign
Sandboxed loadingLoads files in isolated, network-restricted containersAdds operational overhead
Registry allowlistsAdmits only reviewed, approved artifactsSlows experimentation
Controls against model serialization attacks

Teams should convert third-party checkpoints to safetensors in an isolated environment, scan them, and store only the converted artifact in the internal registry. Training and serving hosts then never deserialize pickle from external sources.

Scanners deserve particular care. Most of them inspect the pickle stream for dangerous imports such as process, shell or network modules, and flag files that reference them. Attackers respond with indirect imports, nested archives and less common callables that achieve the same effect, so a clean scan result means only that no known pattern was found. Scanning is most useful as an early filter in the admission pipeline, combined with sandboxed loading that blocks outbound network traffic and restricts file system access. Logging every model load with its file hash also allows a team to trace the origin of a compromise quickly when an incident occurs.

Common mistakes and misconceptions

Many incidents come from trust assumptions about popular platforms. The following beliefs and habits are frequently observed:

  • Assuming a download count or star rating proves a model is safe.
  • Believing that antivirus software detects pickle payloads reliably.
  • Loading models on developer laptops with cloud credentials, where a payload can steal keys.
  • Relying on a scanner verdict while ignoring custom code and tokenizer files.
  • Treating internal registries as trusted even though anyone with write access can upload.

The safest mental model is simple: loading an untrusted pickle-based model is equivalent to running an untrusted program, and it deserves the same controls.

The idea in brief

AI models are saved as files and shared like any other download. Some file types can carry hidden instructions. When someone opens such a file, the instructions run on their computer.

Think of a package that looks like a book but contains a device that switches on when opened. The book still reads normally. Meanwhile, the device does something else. Opening an untrusted model file can work the same way. Safe file types and careful checks keep the device out.

A practical scenario

A data science team at a logistics company downloads a fine-tuned language model from a public hub to classify support tickets. The checkpoint is a 1.3 GB PyTorch file. An engineer loads it in a notebook on a cloud workstation that holds credentials for the production data warehouse.

The file contains a pickle payload that sends environment variables to an external server during loading. Outbound traffic monitoring flags the unexpected connection, and the security team rotates all exposed keys within two hours. Afterwards, the company changes policy: external models are converted to safetensors in an isolated sandbox, scanned, signed and only then admitted to the internal registry. Within a quarter, no pickle files remain on training or serving hosts.