---
title: "The code hiding inside downloaded model files · Junaid Qadir"
description: "A model file is weights plus metadata, and some of that metadata is a program. How pickle and Jinja chat templates get abused, and what to check first."
url: "https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files"
date: "2026-11-29"
tags: ["ai", "security", "programming"]
---

[AI & Tools](https://junaidqadir.com/blog/category/ai-tools/)

# The code hiding inside downloaded model files

On this page

1.  [What is inside a GGUF file](https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files#what-is-inside-a-gguf-file)
2.  [Why a model needs a template](https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files#why-a-model-needs-a-template)
3.  [Attack one: the template runs code on your machine](https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files#attack-one-the-template-runs-code-on-your-machine)
4.  [Attack two: the template rewrites your prompt](https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files#attack-two-the-template-rewrites-your-prompt)
5.  [The older problem: pickle](https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files#the-older-problem-pickle)
6.  [And the one you opt into: trust\_remote\_code](https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files#and-the-one-you-opt-into-trust_remote_code)
7.  [What to do before you run the next model](https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files#what-to-do-before-you-run-the-next-model)

A GGUF file from Hugging Face looks like a big blob of numbers. Most of it is. But many GGUF files also carry a small Jinja program in their metadata, and a runtime that uses it runs it every time you send the model a message. In 2024 one popular loader ran that program with full access to Python.

-   **Prefer `.safetensors` and `.gguf` over pickle files** (often `.bin`, `.pt`, `.pth` or `.ckpt`, though the extension alone does not prove it). Pickle can run code the moment you load it. These two cannot, but a GGUF can still carry a template.
-   **Keep your loader up to date.** The template bug covered below was fixed in a point release.
-   **Read the chat template of the exact file you run**, or replace it with one you have read.
-   **Pin a commit hash** and never set `trust_remote_code=True` for a repo you have not read.

## What is inside a GGUF file

The [GGUF spec](https://github.com/ggml-org/ggml/blob/master/docs/gguf.md) (version 3, checked November 2026) lays the file out in four parts:

1.  **A header.** Four magic bytes, `GGUF` (`0x47 0x47 0x55 0x46`), then a version number, a tensor count and a metadata count.
2.  **Metadata.** A list of key/value pairs. Keys are dotted names like `general.alignment`; values are typed (integers, floats, booleans, strings, arrays).
3.  **Tensor info.** For each tensor: a name, its dimensions, its data type and an offset.
4.  **Tensor data.** The weights themselves, padded to an alignment boundary (32 bytes unless `general.alignment` says otherwise).

![A GGUF file laid out from start to end: header, metadata, tensor info and tensor data. The metadata is expanded to show key/value pairs, with tokenizer.chat\_template highlighted as a program, not data.](https://junaidqadir.com/_astro/gguf-layout.IaikygAI_1HsLX.svg)

Parts 1, 3 and 4 hold nothing meant to run. A loader reads numbers and copies bytes. That does not make them harmless to a buggy parser, since a malformed count or offset is still an attack on the loader, but the format itself asks for no code. Part 2 is data too, but one of its values means something to the runtime:

> `tokenizer.chat_template : string`: a Jinja template that specifies the input format expected by the model.

Reading or parsing the file does not run it. A runtime that renders it does, and at that point that string is code.

## Why a model needs a template

A model does not see “messages”. It sees one long run of [tokens](https://junaidqadir.com/blog/tokens-why-models-do-not-count-in-words/). Something has to turn your list of `{role, content}` messages into that run, with the exact special markers the model was trained on. Get the markers wrong and a good model gives bad answers.

Each model family uses different markers, so the model ships its own formatting rule. Hugging Face stores it as a [Jinja template](https://huggingface.co/docs/transformers/main/en/chat_templating_writing) (Transformers docs, checked November 2026), in a `chat_template.jinja` file at the root of the repo (older repos keep it in a `chat_template` field of `tokenizer_config.json`). When a model is converted to GGUF, the template is usually carried over into `tokenizer.chat_template`.

Here is the example from the Hugging Face docs:

```jinja
{%- for message in messages %}
    {{- '<|' + message['role'] + '|>\n' }}
    {{- message['content'] + eos_token }}
{%- endfor %}
{%- if add_generation_prompt %}
    {{- '<|assistant|>\n' }}
{%- endif %}
```

`{% ... %}` is a statement (a loop, an `if`). `{{ ... }}` prints an expression. The dashes trim whitespace. Read it line by line and you can see what it does: for each message it prints the role between `<|` and `|>`, a newline, the content and the end-of-sequence token, and if `add_generation_prompt` is set it finishes with `<|assistant|>` so the model knows it is its turn.

A runtime that uses the embedded template renders it on every request, then tokenises the result and hands it to the model. That is the whole job, and it is a real programming language doing it: loops, conditionals, string operations, attribute access.

![The request path: messages go through the chat template, become prompt text, then tokens, then reach the model. Attack 1 branches down from the template to run code on your machine when there is no sandbox. Attack 2 loops from the template into the prompt text to add hidden instructions, sandbox or not.](https://junaidqadir.com/_astro/template-path.Dy3svld5_192ADM.svg)

That picture has two weak points, and they need different fixes.

## Attack one: the template runs code on your machine

Jinja was built for web pages, and in Python it can reach Python objects. If the environment is not sandboxed, a template can walk from any object to its class, up to `object`, down to every loaded class, and from there to `os.popen`.

That is exactly what happened in llama-cpp-python. The advisory, [GHSA-56xg-wfcc-g829](https://github.com/abetlen/llama-cpp-python/security/advisories/GHSA-56xg-wfcc-g829) (CVE-2024-34359, published 10 May 2024, CVSS 9.6), says versions 0.2.30 through 0.2.71 built a plain `jinja2.Environment` and called `from_string()` on the template read from GGUF metadata. No sandbox. The proof of concept starts like this:

```jinja
{% for x in ().__class__.__base__.__subclasses__() %}
```

It then finds a class that gives it `os.popen` and runs `touch /tmp/retr0reg`. The advisory notes that line could just as well be a reverse shell. Loading the model was not enough on its own: per the advisory, the payload ran once the model was loaded and a chat completion was created, because that is when the template is rendered. In practice that means the first chat request. Version 0.2.72 fixed it.

The fix is the sandbox. Transformers renders templates with `ImmutableSandboxedEnvironment` from `jinja2.sandbox` ([`chat_template_utils.py`](https://github.com/huggingface/transformers/blob/main/src/transformers/utils/chat_template_utils.py), main branch, November 2026), which blocks the underscore attributes that walk is built on. llama.cpp’s server, which renders templates by default (`--jinja`, “default: enabled”, per its [README](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md), master branch, checked November 2026), does not use Python’s `jinja2` at all: [`common/chat.cpp`](https://github.com/ggml-org/llama.cpp/blob/master/common/chat.cpp) (master branch, checked November 2026) includes its own `jinja/runtime.h` interpreter written in C++. A Python object walk has nothing to walk there. That closes this one technique. It does nothing about the next one.

So for this attack, the defence is boring. Run a loader that sandboxes its templates, and keep it current.

## Attack two: the template rewrites your prompt

A sandbox stops a template from touching your machine. It does not stop it from doing its actual job, which is deciding what text the model sees.

Pillar Security described this in [Poisoned GGUF Templates](https://www.pillar.security/blog/llm-backdoors-at-the-inference-level-the-threat-of-poisoned-templates) (9 July 2025). The template quietly adds instructions to the prompt, but only when the user’s message matches a trigger. In their Phi-4-mini demo, “the malicious script injection only activates for HTML-related requests”: ask for a web page and the model adds a script to it. Ask anything else and the model behaves normally, so the model passes every casual test.

Nothing here escapes a sandbox. An `if` on the message content and a string concatenation are ordinary template features. And because the change lives in the template, not the weights, the model’s benchmarks do not move.

They also showed a way to hide it. Per Pillar, the Hugging Face model page “only displays the template from the first file”, so a repo can show a clean template for one quantisation and ship a poisoned one in a later file such as `Q4_K_M.gguf`. Hugging Face told them on 13 June 2025 this “did not classify as a vulnerability”. LM Studio’s reply was that “users are responsible for reviewing and downloading trusted models”.

So that is your job now.

## The older problem: pickle

Templates are the new risk. Pickle is the old one, and it is still around in files saved with `torch.save`, which commonly end in `.bin`, `.pt`, `.pth` or `.ckpt`.

Pickle is a serialization format, but an unusual one: the file is a small instruction set for rebuilding Python objects, and one of its instructions, `REDUCE`, calls any callable with any arguments while loading. The Hugging Face [pickle security page](https://huggingface.co/docs/hub/security-pickle) (checked November 2026) puts it plainly: “when importing a python module, arbitrary code can be executed”. Most pickle files are ordinary checkpoints; a malicious one needs nothing more than to be loaded. No chat request needed.

This has been used for real. In February 2024, [JFrog reported](https://jfrog.com/blog/data-scientists-targeted-by-malicious-hugging-face-ml-models-with-silent-backdoor/) “around 100 instances” of malicious models on the Hub. One of them, `baller423/goober2`, used pickle’s `__reduce__` to open a reverse shell to a hard-coded IP on port 4242 as soon as it was opened with `torch.load()`.

Two things have improved since. PyTorch 2.6 [changed the default](https://pytorch.org/blog/pytorch2-6/) of `torch.load`’s `weights_only` argument, and the [PyTorch 2.15 docs](https://docs.pytorch.org/docs/2.15/generated/torch.load.html) (checked November 2026) show `weights_only=True`, which restricts the unpickler to tensors, primitive types and dictionaries. Code can still pass `weights_only=False` and turn that off, so the default only protects calls that leave it alone. And the Hub scans uploads: every file under 2 GB goes through [ClamAV on each commit](https://huggingface.co/docs/hub/security-malware) (checked November 2026), and pickle files get an [import scan](https://huggingface.co/docs/hub/security-pickle). The pickle page is honest about the limit: “this is not 100% foolproof.” JFrog showed a `runpy`\-based payload getting past it in their own test repo. A clean scan means the scanner found nothing, not that the file is safe.

The real fix is a format with nothing to execute. [Safetensors](https://github.com/huggingface/safetensors) (README, checked November 2026) is 8 bytes giving the header size, a JSON header, then raw bytes. Its README defines “safe” as “Can I use a file randomly downloaded and expect not to run arbitrary code?” and that is the bar it was built to meet. It removes the pickle problem for the weights. It does not make every parser that reads it bug-free, and it says nothing about the rest of the repo, its Python code or the runtime that loads it.

## And the one you opt into: `trust_remote_code`

Some models need custom Python classes. Transformers will download and run that Python if you pass `trust_remote_code=True`. The [Transformers docs](https://huggingface.co/docs/transformers/main/en/models) (checked November 2026) are clear that this code is “_not_ from Transformers” and that you should “load a custom model from a specific revision to avoid loading model code that may have changed”. Their example:

```py
commit_hash = "ed94a7c6247d8aedce4647f00f20de6875b5b292"
model = AutoModelForImageClassification.from_pretrained(
    "sgugger/custom-resnet50d", trust_remote_code=True, revision=commit_hash
)
```

Without a pinned revision, each fresh download takes whatever code is in the repo at that moment, which may not be the version you read. With a pinned hash, the code you read is the code that runs. Read every Python file the model imports at that revision, not just the main modeling file.

## What to do before you run the next model

1.  **Pick the format.** `.safetensors` for Transformers, `.gguf` for llama.cpp and friends. Skip pickle files unless you know who made them, and if you must load one, leave `weights_only=True` alone.
2.  **Update the loader.** llama-cpp-python at 0.2.72 or later at the very least, and whatever app runs your models.
3.  **Read the template of the file you will actually run**, not the one the model page shows. Look for `if` blocks that test the message content, and for any text that is not a role marker or a message being printed. Some prose is normal, such as a default system message or tool definitions, so compare it with the template the original publisher ships.
4.  **Or replace it.** llama.cpp’s server takes `--chat-template` (a built-in name such as `chatml` or `llama3`) or `--chat-template-file` with a template you have read, in place of the default “template taken from model’s metadata”.
5.  **Prefer the original publisher or a well-known quantiser**, and pin the commit hash you checked.
6.  **Never pass `trust_remote_code=True`** to a repo whose Python you have not read at that exact revision.

The [Hugging Face docs](https://huggingface.co/docs/transformers/main/en/chat_templating_writing) warn that templates with tool calling or RAG support “can be longer than 100 lines”. That is still one sitting’s reading, and it is a plain view of what the model is really given, which [the context window post](https://junaidqadir.com/blog/context-windows-what-the-model-sees-at-once/) covers from the other side.

Open the GGUF you use most, find its `tokenizer.chat_template`, and read it tonight.

[Ai](https://junaidqadir.com/blog/tag/ai/)[Programming](https://junaidqadir.com/blog/tag/programming/)

---

Markdown version of https://junaidqadir.com/blog/the-code-hiding-inside-downloaded-model-files
Site guide for agents: https://junaidqadir.com/llms.txt
Full index: https://junaidqadir.com/sitemap-index.xml
