Loading a model file can run code on your machine, and whether it does depends mostly on the file format. Teams download checkpoints from public hubs and convert them for local inference, often without asking what the loader will do with the bytes. This guide compares the five formats practitioners meet most: pickle based checkpoints, safetensors, GGUF, ONNX and TorchScript. For each one it explains whether code can execute on load, what the format can carry besides weights, and how to handle it safely. It is written for ML engineers, MLOps and platform teams, and AI security teams who set the rules for which artefacts may enter a model registry. For the wider picture of model theft, extraction and evasion, see the AI Model Security Guide.
Key takeaways
- Pickle is a program, not a data file. Python's own documentation warns that malicious pickle data can execute arbitrary code during unpickling, and classic PyTorch .pt, .pth and .bin checkpoints are pickle based.
- Prefer pure tensor formats. Safetensors and GGUF store tensors plus typed metadata and define no code to run, so they remove the deserialisation route, though they still need integrity checks and parser updates.
- Graph formats execute by design. ONNX and TorchScript files describe a computation that a runtime executes. The risk sits in custom operators, native libraries and the runtime, not in the weights.
- Metadata can still steer behaviour. MITRE ATLAS AML.T0011.000 Unsafe AI Artifacts explicitly covers chat templates, tokenizer metadata and configuration, so a "safe" format still needs review and signing.
- Enforce at the loader, not in a wiki. Force weights_only loading, pin revisions to commit hashes, scan on ingest and verify signatures before a file reaches production hosts.
Why model files are an attack surface
A model file arrives from outside the trust boundary in the same way a software package does, yet it is often loaded by a notebook or training job that holds cloud credentials, dataset access and a token for the model registry. If the format can run code, opening the file hands that identity to whoever produced it. MITRE ATLAS describes the technique as AML.T0011.000 Unsafe AI Artifacts: artefacts that have a harmful effect when loaded, executed, interpreted or used for inference, which may exploit deserialisation to execute code on the host, or may use functionality the runtime intentionally supports to alter model context, outputs or agent actions. Delivery usually comes through AML.T0010.003 Model Repository (a sub-technique of AI Supply Chain Compromise), and a tampered artefact that keeps working normally falls under AML.T0018 Manipulate AI Model.
OWASP's Top 10 for LLM Applications 2025 lists this under LLM03:2025 Supply Chain, and its references include research on exploiting machine learning pickle files and on hijacking the safetensors conversion service on Hugging Face. Even a safe format is only as trustworthy as the pipeline that produced it.
The identity angle is direct. When Lasso Security found exposed Hugging Face tokens in 2023, 655 of them had write permission to model and dataset repositories, enough to replace a popular model with a poisoned one. See the Hugging Face API Tokens Exposed 2023 analysis. Write access to a model repository is a privileged non-human credential and should be governed as one.
Formats at a glance
The table compares formats by what happens when a standard loader opens the file. "Code on load" means the format itself can cause the loader to call arbitrary functions, independent of any parser bug.
| Format | Typical extensions | What it stores | Code execution on load | Built-in signing or integrity | Handling notes |
|---|---|---|---|---|---|
| Pickle based (PyTorch, joblib, raw pickle) | .pkl, .pt, .pth, .bin, .ckpt, .joblib | Serialised Python objects, including tensors and arbitrary classes | Yes. Opcodes can import and call any function | None in the format | Load only with weights_only=True, or convert to safetensors in a sandbox |
| Safetensors | .safetensors | 8-byte header length, JSON header (name, dtype, shape, offsets), raw tensor bytes, optional string-to-string metadata | No code defined by the format | None in the format; sign externally | Default choice for weights; validate tensor values if they feed safety decisions |
| GGUF | .gguf | Tensors plus typed key-value metadata, embedded tokenizer and an optional Jinja chat template | No code defined by the format; the chat template is rendered by the runtime | None in the format; sign externally | Review tokenizer.chat_template; keep llama.cpp style runtimes patched |
| ONNX | .onnx plus external data files | Protobuf computation graph, initialisers, optional external tensor files | The graph is executed by design; custom operators load native libraries registered by the host | Optional SHA1 checksum field per external data file; sign externally | Allow only standard operator domains; never register unknown custom op libraries |
| TorchScript | .pt, .pth (torch.jit.save output) | A serialised program: code plus parameters | The saved program runs when you call the model | None in the format; sign externally | Deprecated by PyTorch in favour of torch.export; plan migration |
Extensions are a hint, not proof. A file named .bin can be pickle, raw tensors or something else, so ingest tooling should identify formats from content (the safetensors header, the GGUF magic bytes, a ZIP or pickle signature) rather than by name.
Pickle based formats
The Python documentation is blunt: the pickle module is not secure, malicious pickle data can execute arbitrary code during unpickling, and you should never unpickle data that could have come from an untrusted source or been tampered with. Hugging Face's security documentation explains the mechanism: a pickle is a stack of opcodes, and instructions such as GLOBAL, STACK_GLOBAL and REDUCE import functions and call them. A malicious checkpoint can do this and still return the expected weights, so the model appears to work.
PyTorch checkpoints written by torch.save are pickle based. The torch.load documentation warns that it uses an unpickler under the hood and that you should never load data from an untrusted source. The main mitigation is the weights_only mode:
- Default since PyTorch 2.6: torch.load uses weights_only=True when no pickle_module argument is passed. It restricts the unpickler to functions and classes needed for state dicts: tensors, primitive types and dictionaries.
- Allowlisting: torch.serialization.add_safe_globals() marks extra classes as safe, and the safe_globals() context manager does the same for one block. torch.serialization.get_unsafe_globals_in_checkpoint() lists the globals a checkpoint needs, by static analysis, before you decide.
- Fleet enforcement: the environment variable TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 forces weights_only=True on every torch.load call, which is useful on shared training clusters and inference hosts.
- Limits: PyTorch states that weights_only does not guard against denial of service, and code that passes weights_only=False switches the protection off.
Python's Unpickler.find_class() can restrict globals to a safe subset, but Hugging Face notes that a custom unpickler alone has been bypassed by a sophisticated exploit, so treat allowlisting as one layer. The same risk applies to scikit-learn models saved with joblib, and to cloudpickle and dill files. For the general bug class, see the Insecure Deserialisation Guide.
Safetensors
Safetensors, from Hugging Face, stores tensors "safely (as opposed to pickle)". The project README says a randomly downloaded file can be loaded without expecting arbitrary code to run. The layout is simple: an unsigned little-endian 64-bit integer giving the header size, a UTF-8 JSON header that maps each tensor name to dtype, shape and data offsets, then a raw byte buffer. An optional __metadata__ key holds string-to-string pairs only.
- Denial of service controls: the format limits header size (the README gives 100MB) and requires byte ranges that do not overlap and leave no holes, so loading should not use more memory than the file size.
- What it does not check: the README warns that tensor values are not validated, so NaN and infinity values can appear. A manipulated set of weights in a valid safetensors file is still a manipulated model.
- Loading: safe_open with get_slice reads only the tensors needed, which also makes inspection cheap. In Transformers, from_pretrained prefers safetensors when the library is installed, and use_safetensors=True makes it mandatory.
- Companion files: a model repository is not just weights. config.json, tokenizer files and any Python files shipped for custom architectures sit alongside the safetensors file and need the same review.
GGUF
GGUF is the binary format used by GGML and GGML-based executors such as llama.cpp for local inference. The specification describes a header with the magic bytes GGUF, a version (version 3 is current and added big-endian support), tensor and metadata counts, a typed key-value metadata section, and tensor data aligned to general.alignment (32 bytes by default). Models are usually converted to GGUF from another framework.
The format defines no executable code, but it carries more than weights:
- Tokenizer: keys under tokenizer.ggml.* embed the vocabulary, scores and merges, and tokenizer.huggingface.json can hold a full tokenizer.json.
- Chat template: tokenizer.chat_template holds a Jinja template that defines how prompts are assembled. ATLAS AML.T0011.000 names chat templates and tokenizer metadata as places where an unsafe artefact can hide behaviour-shaping content, for example a template that inserts hidden instructions into every conversation.
- Parser exposure: GGUF readers are native code parsing untrusted lengths and offsets. Keep inference runtimes on current releases and run them without access to secrets they do not need.
Diff the chat template against the original publisher's template before deployment, and re-sign converted files in your own pipeline, because conversion breaks any signature on the source checkpoint.
ONNX
ONNX stores a model as a protobuf computation graph with standard operators and initialisers. A runtime such as ONNX Runtime executes that graph, so the question is not whether the file runs, but what it can make the runtime run.
- Custom operators: ONNX Runtime custom operators live in a separate shared library (.so or .dll) that the host application registers with RegisterCustomOpsLibrary. The model only names the operator. That library is native code running in your process, so the control is an allowlist of approved operator libraries, and refusing models that require unknown custom domains.
- External data: models above the protobuf size limit keep tensors in separate files named by a location field relative to the model directory. The specification disallows ".." components and says parsers should strip them. An optional checksum field carries a SHA1 digest of the file. Validate locations on ingest so a model cannot point the loader at files outside its own directory.
- Validation: onnx.checker.check_model confirms the model is well formed. For models over 2GB, pass the file path, not a loaded object. Well formed does not mean trustworthy.
TorchScript
TorchScript files, produced by torch.jit.save and read by torch.jit.load, are serialised programs rather than plain weights: loading one gives you a callable module whose saved code executes when you run inference. Fickling's documentation notes that PyTorch and TorchScript files can be built as polyglots that parse as more than one format.
PyTorch's documentation now states that "TorchScript is deprecated, please use torch.export instead." For security owners this means two things: plan to retire TorchScript artefacts from production paths, and do not accept new TorchScript files from outside parties. Where a TorchScript model must stay, load it only from your own signed registry, in a sandboxed worker with no credentials beyond what inference needs.
Safe loading and scanning practices
No single control is enough. Combine format policy, scanning, provenance and runtime isolation, and apply them at the point where artefacts enter your registry. The Model Supply Chain Guide covers sourcing and vendor risk; this section is about the files themselves.
| Control | What it catches | What it misses | Where to enforce |
|---|---|---|---|
| Format allowlist (safetensors, GGUF; ONNX with standard domains) | Pickle and TorchScript code execution | Tampered weights, malicious templates | Registry ingest, CI policy |
| weights_only loading and TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 | Most pickle payloads in PyTorch checkpoints | Denial of service, code that sets weights_only=False | Training images, inference containers |
| Static pickle scanning (Hugging Face import listing, ModelScan, Fickling) | Suspicious imports and opcodes without executing the file | Novel or obfuscated payloads; Hugging Face says its scan is not foolproof | Ingest pipeline, pre-commit for model repos |
| Signature and digest verification (OpenSSF model signing) | Tampering after the publisher signed, substituted files | A malicious or compromised publisher | Before load on every host |
| Revision pinning | Silent upstream changes to a model repository | A pinned commit that was already malicious | Code review of from_pretrained calls |
| Sandboxed conversion and loading | Limits blast radius when other controls fail | Nothing on its own; it contains rather than detects | Conversion jobs, evaluation of new models |
Implementation order that works for most teams:
- Inventory: list every model artefact in registries, buckets and images by detected format, and every code path that calls torch.load, pickle.load, joblib.load or torch.jit.load. Flag any weights_only=False.
- Set a format policy: safetensors for weights, GGUF for local inference, ONNX with standard operator domains, and pickle or TorchScript only by documented exception with an owner and expiry.
- Convert in a sandbox: convert legacy pickle checkpoints to safetensors in an isolated, credential-free job, then sign the output. Keep the original read-only for rollback until evaluation results match.
- Scan and sign on ingest: run static scanners on every non-allowlisted file, then sign approved artefacts with the OpenSSF model_signing tool, which hashes every file in the model directory into a manifest and signs it with Sigstore, keys, certificates or PKCS #11 devices. See the Model Signing and OpenSSF Model Signing Guide.
- Enforce at load: set TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 in base images, require use_safetensors=True and a commit hash in revision for Hub downloads, and verify signatures before loading. Keep custom remote code off unless reviewed.
- Pilot, then block: run the policy in report-only mode for one release cycle, fix the exceptions it finds, then fail builds that pull non-compliant artefacts. Roll back by restoring the exception list, not by removing the check.
Small and large teams: a small team can get most of the value from three settings (safetensors only, forced weights_only, pinned revisions). A large organisation with a shared registry should add signing, a private mirror of approved public models and an exception register reviewed each quarter. The AI Model Scanning and Supply Chain buyer's guide covers tool selection.
Detection and metrics: log every model load with file digest, format, source and calling identity, and alert on loads of unsigned artefacts or pickle files on production hosts. Useful measures:
- Share of production model artefacts in an allowlisted format (target 100 percent outside documented exceptions).
- Number of code paths with weights_only=False or raw pickle.load on model files.
- Share of loads with a verified signature.
- Share of Hub downloads pinned to a commit hash.
- Median age of open format exceptions.
Common failure patterns
- Trusting the extension: a .bin or .pt file is accepted as weights unchecked.
- Scan once, load forever: a model scanned on first download is re-fetched later from a mutable branch name, skipping the scan.
- Converting on a privileged host: legacy pickles are converted to safetensors on a workstation with cloud keys, so the conversion itself is the exploit.
- Ignoring companion files: weights are safetensors but the repository ships Python files or a modified chat template that change behaviour.
- Unprotected write tokens: long-lived tokens with write access to model repositories sit in code or CI logs, as in the Lasso findings above.
Framework mapping
| Framework | Reference | How it applies to model files |
|---|---|---|
| MITRE ATLAS | AML.T0011.000 Unsafe AI Artifacts; AML.T0010.003 Model Repository; AML.T0018 Manipulate AI Model | The threats: executable or behaviour-shaping artefacts delivered through model repositories |
| MITRE ATLAS mitigation | AML.M0014 Verify AI Artifacts | Hash and signature checks against an authenticated publisher, pinned to digests |
| OWASP Top 10 for LLM Applications 2025 | LLM03:2025 Supply Chain | Third-party models and conversion services as supply chain risk |
| NIST SP 800-53 Rev 5 | SI-7 and SI-7(15) Code Authentication; SR-4 Provenance; SR-11 Component Authenticity; CM-7(5) Allow-by-exception | Integrity checks, provenance records, signed artefacts and a format allowlist |
| NIST CSF 2.0 | GV.SC-07; PR.PS-02; DE.CM-09 | Supplier risk for model sources, managed software lifecycle, monitoring of runtime loads |
Practitioner checklist
- Inventory model artefacts by detected format, not by file extension.
- Make safetensors the default for weights and GGUF for local inference; require an owner and expiry for pickle or TorchScript exceptions.
- Set TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 in training and inference images and search code for weights_only=False.
- Pin every Hub download to a commit hash and require use_safetensors=True.
- Convert legacy checkpoints only in isolated jobs with no credentials, then sign the output.
- Scan non-allowlisted files statically on ingest and treat a clean scan as necessary, not sufficient.
- Review GGUF chat templates and tokenizer metadata, and ONNX operator domains and external data paths, before approval.
- Sign approved artefacts and verify signatures before every load.
- Govern write tokens for model repositories as privileged non-human identities with short lifetimes.
- Plan migration of TorchScript models to torch.export.
Standards and references
- Python Software Foundation: pickle, Python object serialization
- PyTorch: Serialization semantics and weights_only
- Hugging Face: safetensors format and README
- GGML: GGUF file format specification
- ONNX: External Data
- Hugging Face: Pickle Scanning
- OpenSSF and Sigstore: model-transparency (model signing)
- OWASP: LLM03:2025 Supply Chain
Related NHI Mgmt Group resources: AI Model Security Guide, Model Signing vs Model Scanning, Open-Weight Model Security Guide, Hugging Face Security Guide, AI Supply Chain and AI-BOM Guide.