Differential chat-template auditing for the local model supply chain
Build the missing conformance gate for chat templates in local model artifacts: a tool that extracts `tokenizer.chat_template` from a GGUF or HF repo, normalises and diffs it against the canonical upstream template for that model family, renders both across a probe corpus (multi-turn, system prompts, tool definitions, special tokens) under each runtime's own Jinja implementation, and diffs the resulting token streams. Divergences are classified — benign reformatting, BOS/EOS duplication, tool-call notation drift, or the high-signal case of template logic that branches on user-supplied content, which is the signature of an inference-time backdoor. Ships as a CLI plus CI action for quant publishers, with a hub-wide scan as the launch artifact. Templates are small text files and rendering needs no GPU, so ecosystem-scale coverage is cheap.
worth score
Problem
The chat template is the only piece of executable code that runs on every single inference call in a local AI stack, and nothing validates it. It is a Jinja2 program bundled inside the model artifact, sitting between the user and the model, and it is inspected by no scanner in the pipeline 6.
This produces two failure modes from one root cause.
The first is silent quality loss. A leading GGUF publisher re-uploaded the same popular model six separate times: first for a [::-1] Jinja bug that broke llama.cpp and LM Studio, then again because LM Studio disagreed with llama.cpp's template, then again for tool-calling failures, then again because mismatched BOS tokens silently disabled speculative decoding — and stated plainly that they believe other publishers' quants are still buggy 2. One of those defects was found by a Reddit user, not by any automated gate 3. The publisher's own documentation notes a tool-calling template issue that "affects all quant uploaders and types regardless where you're using it or where it's from" 4. That is an ecosystem-wide defect class discovered socially.
The second is security. Template poisoning is now demonstrated, not theorised: triggered backdoors drop factual accuracy from 90% to 15% while showing no degradation on benign inputs, induce attacker-controlled URL emission above 80% success, and hold across eighteen models, seven families, and four inference engines 8. At the agent level they hijack tool use across 3,868 episodes and bypass every injection defense the benchmarks offer 8. Crucially, the payload renders before user input is processed, which makes it architecturally unreachable by prompt-injection guardrails, and because it is valid Jinja rather than binary malware it passes hub malware and pickle scanning 712.
Why Now
Three things converged. The attack moved from theory to a demonstrated cross-engine result with poisoned artifacts that evaded all automated scans on the largest model hub, and the researchers explicitly characterise the surface as "currently undefended" 7. Separately, a security vendor's vulnerability database now prescribes the exact mitigation — "automated analysis of tokenizer.chat_template metadata to detect anomalous conditional logic, specifically if statements that check for specific substrings in user input" — and then falls back on advising users to manually eyeball the template string 11. The prescription exists; the product does not.
Meanwhile templates carry far more load than they used to. They now encode tool-call notation, reasoning delimiters, and agentic scaffolding, and every mainstream engine executes them: llama.cpp, Ollama, vLLM, SGLang 12. A template defect now breaks an agent loop rather than producing slightly odd prose.
The Opportunity
A differential conformance gate. Extract tokenizer.chat_template from a GGUF or HF repo, normalise it, diff against the canonical upstream template for that family, render both across a probe corpus (multi-turn, system prompts, tool definitions, special tokens) under each runtime's own Jinja implementation, and diff the resulting token streams. Classify divergences: benign reformatting, BOS/EOS duplication, tool-call notation drift, and the high-signal case — template logic branching on user-supplied content, which is the backdoor signature 11.
Ship as a CLI plus CI action for quant publishers, with a hub-wide scan as the launch artifact. This is interpretation, but the economics look unusually favourable: templates are small text files, rendering needs no GPU, so ecosystem-scale coverage is cheap for a small team. The technical difficulty sits in curating canonical references and triaging benign divergence, not in the analysis.
One concrete complication worth designing for: llama.cpp's json-schema-to-grammar.cpp only emits rules for JSON, so non-JSON tool notations (Gemma's fc format) fall outside grammar constraints, and a collaborator notes that over-constraining can degrade output in other ways 1. Runtime-specific quirks are documented and tractable, but they are not uniform.
Evidence Assessment
The neglectedness evidence is the strongest in the set. Two independent sources state that existing scans cannot see this: the research paper 7 and a vulnerability database that recommends manual visual inspection as the practical fallback 11. The commercial state of the art, JFrog's GGUF-SSTI check, keyword-matches for __class__, os, subprocess, eval, exec against CVE-2024-34359 10 — a semantic backdoor built from ordinary conditionals contains none of those. Community scanners like Veritensor target pickle simulation, file hashing, and license metadata in GGUF/safetensors, not Jinja logic 9. That is a consistent picture from four directions.
The demand evidence is weaker. It is real, documented, and recurring 234, but it presents as diffuse annoyance absorbed by volunteers. No willingness-to-pay signal appears anywhere in this evidence base.
The attack evidence is strong but singular — one paper 68. Hub-level compromise is separately corroborated: 100+ malicious models found despite malware, pickle, and secrets scanning 14. That establishes attacker interest and scanner blind spots generally, but not template exploitation in the wild.
Competition
Adjacent but non-overlapping. JFrog covers code-execution SSTI via keyword matching on a patched CVE 10. Hugging Face covers malware, pickle, secrets, and unsafe deserialization — and 100+ malicious models slipped through anyway 14. Sigstore model-transparency signs artifacts but attests publisher identity, not template fidelity; a re-quantizer signing their own derivative proves nothing about faithfulness to upstream, and 244 stars suggests thin adoption 13. Promptfoo maintains the vulnerability database documenting this attack and prescribing template auditing 11 — and ships no auditor. Unsloth runs 150+ KL-divergence benchmarks per family with published artifacts 5, which is genuine rigour but vendor-internal, KLD-based, and applicable only to their own uploads.
The competitive risk is absorption speed, not incumbency.
Skeptic's Case
The honest counterargument: this may be a real problem adequately handled by social mechanisms. Most people pull from a handful of reputable publishers, and that community fixes template defects reactively within days of a user noticing — which is precisely what the six-re-upload story shows 23. Formalising a process the community already converges on fast may add friction without adding much.
The security case rests on one academic paper with no confirmed in-the-wild template backdoor 68. And whoever would most naturally ship this — the hub, or an existing scanner — can add template heuristics quickly, since the analysis is easy and only the reference curation is hard.
The strongest version, though, comes from the person closest to the problem: a quant publisher would likely say the real fix is upstream authors shipping correct, tested templates, plus runtimes converging on one Jinja implementation — not a downstream scanner compensating for missing discipline. Note the Qwen3 defect originated upstream 3, which means "diverges from upstream" is not the same as "wrong."
Risks
The oracle is weak. Canonical upstream templates are themselves frequently buggy at release 3, and re-quantizers legitimately patch templates 2, so divergence-from-upstream produces false positives that require human triage and can erode trust in the tool. The user-content-conditional-branching signal is much cleaner 11 but may still fire on legitimate logic.
Security urgency is anticipatory. If no real incident arrives, adoption stalls at hygiene value alone. Monetisation is genuinely unclear — this most naturally lives as open-source infrastructure or as a feature absorbed by JFrog, a hub scanner, or Hugging Face itself, any of which could commoditise it quickly.
Verdict
Worth doing, with the honest framing that this is infrastructure rather than a business. The neglectedness case is unusually well-corroborated: the mitigation has been written down by a security vendor and left unbuilt 11, the paper's authors name the gap explicitly 7, and four adjacent tool categories all stop short of Jinja semantics 91013. The feasibility is high and cheap — text files, no GPU.
Build the user-content-conditional-branching detector first, because it is the high-signal check with the clean oracle. Treat upstream diffing as a secondary quality-hygiene layer where false positives are tolerable. The hub-wide scan is the right launch artifact: it either surfaces something real, which resolves the anticipatory-urgency risk immediately, or it demonstrates that the ecosystem is cleaner than feared — which is itself a useful result and a signal to stop.
Sources
- Looking for the right approach for error-free tool calling · ggml-org/llama.cpp · Discussion #21839 · GitHub
- unsloth/Qwen3-30B-A3B-GGUF · All Qwen3 uploads updated with fixed chat templates!
- unsloth/Qwen3-30B-A3B-GGUF · All Qwen3 uploads updated with fixed chat templates!
- Qwen3.5 GGUF Benchmarks | Unsloth Documentation
- Qwen3.5 GGUF Benchmarks | Unsloth Documentation
- Inference-Time Backdoors via Chat Templates: From LLM Supply Chains to Agentic System Compromise
- Inference-Time Backdoors via Chat Templates: From LLM Supply Chains to Agentic System Compromise
- Inference-Time Backdoors via Chat Templates: From LLM Supply Chains to Agentic System Compromise
- I scanned 2,500 Hugging Face models for malware/issues. Here is the data | Hacker News
- GGUF-SSTI - JFrog Security Research
- Chat Template Hidden Instructions | LLM Security Database
- Chat Template Hidden Instructions | LLM Security Database
- GitHub - sigstore/model-transparency: Supply chain security for ML · GitHub
- Malicious AI models on Hugging Face backdoor users’ machines
Evidence trail
- [1]supportstrength 70%
“Most models use GBNF grammar to ensure proper tool calls. Gemma 4 only forces the structure, not the arguments. This is because `common/json-schema-to-grammar.cpp` only produces rules for JSON and not Gemma's fc notation. So more work needs to be done to expand schema support for formats other than JSON, that's the only real constraint here. It should be noted that grammar constraining isn't a silver bullet. Sometimes you can overly constrain a model and it starts producing incorrect output in other ways.”
llama.cpp collaborator confirms per-model gaps in tool-call constraint coverage and that grammar constraining can itself degrade output — reliability is model/config-specific, not solved generally
Looking for the right approach for error-free tool calling · ggml-org/llama.cpp · Discussion #21839 · GitHub · github.com - [2]supportstrength 85%
“1. Updated quants due to chat template not working in llama.cpp / lm studio due to [::-1] and other jinja template issues - now worked for llama.cpp 2. Updated again since lm studio didn't like llama.cpp's chat template ... 4. Updated again due to tool calling issues ... other people's quants I think are still buggy 5. Updated all quants due to speculative decoding not working (BOS tokens mismatched)”
A leading GGUF publisher documents six successive re-uploads of the same model to fix template/tool-call/BOS-token defects, and believes other publishers' quants remain buggy — artifact defects are systemic and silently shipped
unsloth/Qwen3-30B-A3B-GGUF · All Qwen3 uploads updated with fixed chat templates! · huggingface.co - [3]supportstrength 80%
“Thanks to a r/localllama user, they found out there was a bug in Qwen's chat template so, we've now updated all the Qwen3 GGUFs and safetensors with the fixed chat template!”
Detection of artifact defects is ad-hoc and community-driven rather than systematic — no automated conformance gate exists in the distribution chain
unsloth/Qwen3-30B-A3B-GGUF · All Qwen3 uploads updated with fixed chat templates! · huggingface.co - [4]supportstrength 80%
“We also fixed a tool calling chat template issue (affects all quant uploaders and types regardless where you're using it or where it's from).”
Vendor states a tool-calling template defect affected every quant uploader and every runtime simultaneously — evidence the defect class is ecosystem-wide, not vendor-specific
Qwen3.5 GGUF Benchmarks | Unsloth Documentation · unsloth.ai - [5]contextstrength 60%
“We did over 150 KL Divergence benchmarks, totally 9TB of GGUFs. We uploaded all research artifacts. ... For the worst items, ssm_out dramatically increases KLD and the disk space savings is minuscule. ... Quantizing any attn_* is especially sensitive for hybrid architectures”
Partial counterevidence to a pure "nobody measures quant quality" claim: one vendor runs large-scale KL-divergence sweeps — but it is vendor-internal, per-model, and KLD-based rather than task- or user-config-scoped
Qwen3.5 GGUF Benchmarks | Unsloth Documentation · unsloth.ai - [6]supportstrength 85%
“Chat templates are executable programs invoked at every inference call, often implemented in Jinja2, that occupy a privileged position between user input and model processing. We show that an adversary who distributes a model with a maliciously modified template can implant an inference-time backdoor without modifying model weights, poisoning training data, or controlling runtime infrastructure.”
Chat templates are executable code shipped inside model artifacts and can carry backdoors with no weight modification — an attack surface distinct from everything current scanners inspect
Inference-Time Backdoors via Chat Templates: From LLM Supply Chains to Agentic System Compromise · arxiv.org - [7]supportstrength 90%
“The poisoned artifacts evade all automated security scans on the largest open model distribution platform; and because the payload is rendered by the template before user input is processed, it is architecturally unreachable by input-level defenses such as prompt injection guardrails. These results establish chat templates as a reliable and currently undefended attack surface in the open-weight AI supply chain.”
Direct statement of neglectedness: existing hub scans and prompt-injection guardrails structurally cannot catch template backdoors — the surface is "currently undefended"
Inference-Time Backdoors via Chat Templates: From LLM Supply Chains to Agentic System Compromise · arxiv.org - [8]supportstrength 85%
“At the LLM level, triggered backdoors reduce factual accuracy from 90% to 15% on average and induce attacker-controlled URL emission with success rates exceeding 80%, while benign inputs show no measurable degradation; these results hold across eighteen models from seven families and four inference engines. At the agent level, template backdoors hijack tool-use across two benchmarks spanning 3,868 episodes, bypassing every tested injection defense offered by the benchmarks while remaining fully dormant absent the trigger.”
Attack is severe, stealthy (dormant on benign input) and generalises across 18 models and 4 inference engines — not a narrow proof-of-concept
Inference-Time Backdoors via Chat Templates: From LLM Supply Chains to Agentic System Compromise · arxiv.org - [9]contextstrength 60%
“Instead of searching for suspicious text, it simulates how Pickle loads data, which helps it find hidden payloads without running any code. It also checks that the model file is real by hashing it and comparing it with the version from Hugging Face... Veritensor also looks at model metadata in formats like Safetensors and GGUF to spot license restrictions.”
State of the art in community model scanning targets pickle RCE, hashes and license metadata — chat template logic is not analysed, confirming where the tooling frontier actually sits
I scanned 2,500 Hugging Face models for malware/issues. Here is the data | Hacker News · news.ycombinator.com - [10]contextstrength 80%
“To safely determine if the suspected GGUF model contains a malicious Jinja2 template - 1. Parse the GGUF model's metadata parameters and extract the `tokenizer.chat_template` string 2. Inspect the chat template data for suspicious strings such as `__class__`, `os`, `subprocess`, `eval` and `exec` ... The only publicly known case where loading a GGUF model leads to dangerous server-side template injection is related to the CVE-2024-34359 ("Llama Drama") vulnerability.”
The one commercial template scanner covers only code-execution SSTI via keyword matching on a patched CVE — a semantic backdoor using ordinary Jinja conditionals contains none of those keywords and passes cleanly
GGUF-SSTI - JFrog Security Research · research.jfrog.com - [11]supportstrength 85%
“Mitigation Steps - Treat Templates as Code: Distributors and consumers must treat chat templates as executable code rather than passive configuration. - Template Auditing: Implement automated analysis of `tokenizer.chat_template` metadata to detect anomalous conditional logic, specifically `if` statements that check for specific substrings in user input. - Cryptographic Provenance: Implement signing mechanisms for model metadata to ensure the chat template has not been tampered with after release by the original model publisher. - Visual Inspection: Users should manually inspect the chat template string of community-distributed GGUF files prior to deployment in sensitive environments.”
A security vendor's own vulnerability database prescribes automated template auditing, metadata signing and manual inspection as the mitigations — describing a tool that does not yet exist and falling back on "visual inspection"
Chat Template Hidden Instructions | LLM Security Database · promptfoo.dev - [12]supportstrength 80%
“Evasion: Poisoned models pass standard automated security scans (malware detection, serialization checks) on platforms like Hugging Face because the payload is valid Jinja2 logic rather than binary malware. ... Affected Systems - Inference engines that execute bundled Jinja2 chat templates, including but not limited to: llama.cpp, Ollama, vLLM, SGLang”
Independent catalogue confirms the payload is invisible to existing scan classes and that every mainstream local inference engine is affected
Chat Template Hidden Instructions | LLM Security Database · promptfoo.dev - [13]contradictstrength 55%
“sigstore/model-transparency Public ... Star 244 ... Fork 64 ... Model Transparency ## Model Signing We support generating signatures via Sigstore”
Cryptographic model signing exists as an OpenSSF/Sigstore project (partial mitigation for tampering) but with 244 stars its ecosystem adoption is minimal, and signing attests publisher identity rather than template correctness of derivative quants
GitHub - sigstore/model-transparency: Supply chain security for ML · GitHub · github.com - [14]supportstrength 75%
“At least 100 instances of malicious AI ML models were found on the Hugging Face platform, some of which can execute code on the victim's machine, giving attackers a persistent backdoor. ... This happens despite Hugging Face's security measures, including malware, pickle, and secrets scanning, and scrutinizing the models' functionality to discover behaviors like unsafe deserialization.”
Attackers demonstrably upload malicious models to the main hub at scale, and 100+ slipped past existing malware/pickle/secrets scanning — the threat is real and current scan coverage has structural blind spots
Malicious AI models on Hugging Face backdoor users’ machines · bleepingcomputer.com