Check a GGUF File for Chat Template Tricks and Trailing Data
Read every chat template in a local GGUF as escaped text. Compare the tensor end with the file size and count extra bytes after any zero alignment padding.
On November 27, a researcher reported finding five malicious GGUF models on Hugging Face with 2,428 downloads in total. One campaign hid data at the end of the file and used the chat template to put a command at the start of replies. Another targeted coding agents’ tool calls with a line added near the end of an otherwise normal template. Research report
[1] Create a working directory in Bash. Mount only the package directory for installation.
mkdir gguf-check && cd gguf-check && mkdir deps && \timeout 180 docker run --rm --name gguf-file-hidden-data-chat-template-check-deps \ --memory 1g --cpus 2 --user "$(id -u):$(id -g)" \ --mount "type=bind,\"source=${PWD//\"/\"\"}/deps\",target=/deps" python:3.12-slim \ python -m pip install --disable-pip-version-check --no-cache-dir --no-compile \ --index-url https://pypi.org/simple --target /deps gguf==0.19.0[2] Save this as check_gguf.py. It prints the full escaped text of every string field whose key starts with tokenizer.chat_template. For tensor_end, it takes the largest sum of a tensor's file offset and byte count. The reader applies alignment to locate the tensor data section. GGUF specification · gguf 0.19.0
import loggingimport sysimport unicodedata from gguf import GGUFReader, GGUFValueType def show_template(reader): prefix = "tokenizer.chat_template" fields = [(key, field) for key, field in reader.fields.items() if key.startswith(prefix)] if not fields: print(f"{prefix}: absent") for key, field in fields: if field.types != [GGUFValueType.STRING]: raise ValueError(f"Unexpected type for {ascii(key)}") show_text(key, field.contents()) def show_text(key, template): lines = template.split("\n") print(f"{ascii(key)}: lines={len(lines)} chars={len(template)} (LF separates lines)") width = 160 for number, line in enumerate(lines, 1): parts = max(1, (len(line) + width - 1) // width) control = any(unicodedata.category(ch) in {"Cc", "Cf"} for ch in line) for part in range(parts): flags = [f"long; part {part + 1}/{parts}"] if parts > 1 else [] if control: flags.append("control/format") label = f" [{', '.join(flags)}]" if flags else "" chunk = line[part * width:(part + 1) * width] print(f" {number}{label}: {ascii(chunk)}") def inspect(path): reader = GGUFReader(path, mode="r") if not reader.tensors: print("No tensors; EOF comparison unavailable") show_template(reader) return size = reader.data.size alignment = int(reader.alignment) if alignment < 8 or alignment % 8: raise ValueError("invalid alignment") data_start = int(reader.data_offset) ends = [] for tensor in reader.tensors: start = tensor.data_offset end = start + tensor.n_bytes if start < data_start or (start - data_start) % alignment or end > size: raise ValueError("invalid tensor extent") ends.append(end) end = max(ends) aligned_end = end + (-end % alignment) padding = 0 if aligned_end <= size and not reader.data[end:aligned_end].any(): padding = aligned_end - end print(f"alignment={alignment} tensor_end={end} aligned_end={aligned_end}") print(f"file_bytes={size} zero_eof_padding={padding} extra_bytes={size - end - padding}") show_template(reader) if __name__ == "__main__": if len(sys.argv) != 2: sys.exit("Usage: check_gguf.py FILE.gguf") logging.disable(logging.CRITICAL) try: inspect(sys.argv[1]) except KeyError as error: if str(error.args[0]).startswith("Duplicate "): print("Duplicate GGUF key; templates unavailable", file=sys.stderr) sys.exit("Inspection failed; no reliable result") except Exception: sys.exit("Inspection failed; no reliable result")[3] Inspect the file with networking disabled. Mount the existing model file read-only in place. Quote the entire path as shown if the filename includes spaces or commas.
scan() { local model code=0 IFS= read -r -d '' model < <(realpath -ez -- "$1") || return timeout 600 docker run --rm --init --pull never --name gguf-file-hidden-data-chat-template-check-scan \ --network none --memory 4g --cpus 2 --read-only --cap-drop ALL \ --security-opt no-new-privileges --user "$(id -u):$(id -g)" \ --mount "type=bind,\"source=${PWD//\"/\"\"}\",target=/work,readonly" \ --mount "type=bind,\"source=${model//\"/\"\"}\",target=/input.gguf,readonly" \ -e PYTHONPATH=/work/deps python:3.12-slim python -B /work/check_gguf.py /input.gguf || code=$? if ((code)); then printf 'No result (exit %s); file safety was not established.\n' "$code" >&2 fi return "$code"}$ scan '/path/to/model name, quant.gguf'For long output, save it with scan '/path/to/model name, quant.gguf' > scan.txt 2>&1 and open the text file in an editor.
[4] Read extra_bytes alongside the template. The default alignment is 32 bytes. Use general.alignment when present. The script counts bytes between the tensor end and the next alignment boundary as zero_eof_padding only when the whole span is present and filled with zeroes. A short suffix or a span containing a nonzero byte counts toward extra_bytes.
The generated fixture contains two tensors and a plain chat template.
$ scan clean.ggufalignment=32 tensor_end=308 aligned_end=320file_bytes=320 zero_eof_padding=12 extra_bytes=0'tokenizer.chat_template': lines=3 chars=55 (LF separates lines) 1: '{% for m in messages %}' 2: "{{ m['content'] }}" 3: '{% endfor %}'The copy adds ten bytes of harmless text, including a newline. The first two lines show the same tensor end and zero padding, with extra_bytes now at 10.
$ scan appended.ggufalignment=32 tensor_end=308 aligned_end=320file_bytes=330 zero_eof_padding=12 extra_bytes=10…A separate fixture with 64-byte alignment puts harmless markers on line 92 and at the end of a line over 4,000 characters long. For each key the output starts with the total lines and characters. Long lines appear in numbered parts of up to 160 characters each. The output below is abridged.
$ scan 'display case, sample.gguf'…'tokenizer.chat_template': lines=93 chars=5674 (LF separates lines)… 4 [control/format]: '{#\t\u202e #}'… 92: '{# LATE-LINE-92 #}'… 93 [long; part 26/26]: 'AAAAAAAA LONG-LINE-END #}''tokenizer.chat_template.review': lines=1 chars=20 (LF separates lines) 1: '{# NAMED-TEMPLATE #}'What the check covers
- A result of
extra_bytes=0offers no safety guarantee. The script skips the alignment gap before tensor data, the tensor weights, and gaps between tensors. For a sharded model, check each file separately. Shard completeness and templates stored in separate files are outside the check. For a tensorless file, the script reports the templates only. Research report, Section 4 - The
gguf 0.19.0reader stops at a duplicate key. The test fixture producedDuplicate GGUF key; templates unavailablefollowed byNo result. The duplicate values are unavailable in this case. The reader also requires any explicit alignment value to be a power of two. gguf 0.19.0 source release - Hugging Face documents how Ollama uses the embedded chat template to select a template at runtime. If you already loaded the model or followed one of its commands, stop running commands it suggests. For indicators, see “7.2 Indicators of Compromise” in the research report. Hugging Face Ollama docs · Researcher recommendations
If you need to locate a file downloaded by Ollama, check the default paths in Ollama model storage.