October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Why Loading a Machine-Learning Model Can Execute Code

Some model files can run code during loading because pickle reconstructs Python objects. Learn how to reduce the risk with restricted loading, Safetensors, code review and isolation.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Yes—loading some machine-learning model files can run code, but it depends on the file format, loader, settings, and any custom code the model uses. The key risk is unsafe deserialization: formats such as Python pickle can encode instructions that run while an object is reconstructed. A malicious file may then act with the permissions of the process loading it, including access to files, credentials, or network resources available to that process.

That does not mean every model file is executable. Tensor-only formats such as Safetensors and restricted loading options can reduce the pickle risk. They do not, by themselves, establish that a repository’s Python code, dependencies, or surrounding application are safe.

How can loading a model run code?

Some model files use Python’s pickle serialization format. Pickle stores information used to reconstruct Python objects; unrestricted loading can invoke functions as part of that reconstruction. If an attacker crafts a pickle file to perform a malicious action, the action can run when an application deserializes it.

The security issue is the loader’s deserialization path—not the fact that a file is called a model. Scikit-learn warns that loading untrusted pickle-derived artifacts can execute malicious code, and Hugging Face describes arbitrary code execution as a risk of pickle files. Scikit-learn’s model persistence guidance and Hugging Face’s pickle scanning documentation explain the risk.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems
  • Use scikit-learn to track an example ML project end to end
  • Explore several models, including support vector machines, decision trees, random forests, and ensemble methods
  • Exploit unsupervised learning techniques such as dimensionality reduction, clustering, and anomaly detection
  • Dive into neural net architectures, including convolutional nets, recurrent nets, generative adversarial networks, autoencoders, diffusion models, and transformers
  • Use TensorFlow and Keras to build and train neural nets for computer vision, natural language processing, generative models, and deep reinforcement learning

Code runs with the privileges and access of the process performing the load. Depending on how that process is configured, this could expose files, credentials, or network resources. The consequences are not automatically the same on every system: permissions, isolation, and available resources matter.

Which model-loading paths carry different risks?

Loading path What to consider
Unrestricted pickle or pickle-derived files, including some joblib and cloudpickle artifacts Loading untrusted files may execute code during deserialization. Use only when you have a basis to trust the artifact and its provenance. Scikit-learn documentation
PyTorch checkpoint loaded with weights_only=True Uses a restricted unpickler intended for state dictionaries containing tensors and selected primitive types. This narrows the remote-code-execution surface; it is not a guarantee that all input handling or downstream processing is safe. Confirm compatibility and behavior for your installed version. PyTorch serialization semantics
Safetensors weights with safe loading enforced A tensor-focused format that avoids pickle-based object reconstruction for the weights. Hugging Face documents a safe-loading mode that rejects pickle files rather than falling back to them. It does not certify repository code or the rest of the application. Hugging Face serialization reference
Custom Python code in a model repository This is a separate code-execution path. In Transformers, trust_remote_code=True permits loading custom model code. Review it and pin a specific revision if you need it. Transformers model-loading documentation
ONNX for a supported scikit-learn inference use case Can be an alternative persistence route for inference when the estimator and operational needs are supported; it is not a universal replacement for every training or model workflow. Scikit-learn documentation

These distinctions are more useful than relying on a filename extension or a repository label alone. Check the actual loading API and its options: library behavior and defaults can vary by version. Hugging Face’s serialization reference describes the difference between safer loading and unrestricted pickle handling.

What does weights_only=True do in PyTorch?

PyTorch’s torch.load can load checkpoint data through pickle. With weights_only=True, PyTorch uses a restricted unpickler intended for state dictionaries made up of tensors and selected primitive types. The restriction narrows what the file can cause the loader to reconstruct and is intended to reduce the remote-code-execution surface. See PyTorch’s serialization semantics.

Use the option when the checkpoint and loading workflow are compatible, and check the behavior of the PyTorch version deployed in your environment. Do not treat it as proof that arbitrary input is safe: other processing steps, dependencies, and the application around the checkpoint can introduce risks. PyTorch also notes that some TorchScript inspection tools may execute code stored in a model; its security policy provides broader context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is a model from Hugging Face safe to download?

A repository host is not a guarantee that every artifact or code path in a repository is safe. Evaluate the specific files you plan to load and how the loader will handle them. A tensor file loaded through a safe path presents a different pickle risk from an unrestricted pickle checkpoint; enabling custom repository code is a separate decision.

In Transformers, trust_remote_code=True permits custom model implementation code to load. If the model requires it, inspect that code and pin a specific revision rather than relying on a moving branch or tag. Treat that code as third-party software. The Transformers documentation covers custom model loading, and Hugging Face’s pickle guidance covers pickle scanning.

A scanner can help identify known pickle concerns, and a signature can help establish where an artifact came from. Neither proves that the artifact is benign. Provenance, revision integrity, loader settings, code review, and the privileges of the loading environment all contribute to a trust decision.

How to load model files more safely

  1. Identify what will be loaded. Check the actual artifact format, loader call, library version, and whether the repository includes custom code. Do not infer safety from the file extension alone.
  2. Prefer tensor-only weights where supported. Use Safetensors when the model and loader support it. Configure safe loading so a missing Safetensors file does not silently trigger fallback to a pickle file. See Hugging Face’s serialization reference.
  3. Restrict PyTorch checkpoint loading when compatible. For state-dictionary workflows, use weights_only=True and verify behavior against the version you deploy. See PyTorch’s serialization documentation.
  4. Do not load untrusted pickle-derived artifacts unrestricted. This includes relevant pickle, joblib, and cloudpickle files. Only use them when the source and specific revision are trustworthy enough for your use case. Scanners and signatures are supporting evidence, not guarantees. See scikit-learn’s persistence guidance and Hugging Face’s pickle guidance.
  5. Review custom repository code. If custom code is necessary, inspect it and pin the exact revision you intend to use. Avoid granting permission to load it without understanding what it does. See Transformers’ model-loading documentation.
  6. Isolate legacy or unverified artifacts. Load them in an environment with least privilege, no secrets, and no unnecessary network access. This limits what a malicious artifact could reach if code runs during loading.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What a safer format does—and does not—protect

Choosing a format that avoids pickle-based reconstruction can reduce the risk associated with loading the weight file. It does not establish that the model repository’s custom code, configuration handling, dependencies, or inference application are safe. Nor does it remove risks from later processing of untrusted inputs. Review the full loading and inference path, not just the weights format.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

PyTorch’s security policy puts the issue plainly: “Pytorch models are programs, so treat its security seriously — running untrusted models is equivalent to running untrusted code.” PyTorch Security Policy

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.