AI & Tools

The code hiding inside downloaded model files

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 (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.

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. 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 (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:

{%- 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.

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 (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:

{% 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, 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, master branch, checked November 2026), does not use Python’s jinja2 at all: 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 (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 (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 “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 of torch.load’s weights_only argument, and the PyTorch 2.15 docs (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 (checked November 2026), and pickle files get an import scan. 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 (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 (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:

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 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 covers from the other side.

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

Comments

← All posts