BadTemplate: Training-Free Backdoor Attacks on Large Language Models via Chat TemplatesBadTemplate: A Training-Free Backdoor Attack via Chat Template Against Large Language Models
BadTemplate implants a backdoor by modifying the chat template; Llama-70B word-level ASR on SMS is 100.00%.
An attacker can release a tokenizer containing a malicious chat template, or put it together with model parameters on a third-party platform or directly to users. Parameters and training data cannot be modified, only the template in the tokenizer. The goal is that specified backdoor behavior appears when the input contains the trigger, benign inputs preserve original task performance as much as possible, and it is hard for users to notice and can resist common defenses.
- The chat template is distributed along with the tokenizer in the supply chain. Those who control the template can write strings into the system prompt without user awareness, enabling training-free backdoors. The authors state that low-cost spread may cause economic losses and misinformation.
- BadTemplate does not change parameters, only appends the backdoor instruction in the system role of the chat template. Word-level uses a word as the trigger, sentence-level uses a sentence; if the trigger is present, it outputs the preset label. Inference additionally includes classification task instructions, 4 demonstrations per class, and uses greedy decoding.
- Compared with Clean and ICL-1/2/3Shot on 6 open-source and 3 closed-source models and 5 classification sets; closed-source is a system prompt simulation. Many cells have ASR of 100.00%, and there are also cells below or close to baseline. GPT-4o's detection TPR is mostly 0.00%.
- The paper does not have a dedicated limitations section. The Discussion states that HuggingFace detection failed to identify malicious tokenizers, and calls for new defenses on the platform and user side. The experiments include five classification sets; closed-source results come from simulated insertion, not modifying the tokenizer.
- Evaluated models
- Llama-3.1-8B-INST (Llama-8B)Deepseek-7B-chat (Deepseek-7B)Llama-3.1-70B-INST (Llama-70B)Yi-1.5-Chat-34B (Yi-34B)Mistral-Small-Instruct-2409 (Mistral-Small)Phi-3.5-mini-instruct (Phi-3.5)DeepSeek-V3.2-Exp (DeepSeek-V3.2)Gemini-2.5-flash (Gemini-2.5)GPT-4o-mini
- Benchmarks
- SST-2SMS SpamAGNewsDBPediaAmazon Product Reviews
- Metrics
- ACCASRTPR
The researchers propose BadTemplate, a training-free backdoor attack in which an attacker who controls the chat template can inject malicious instructions into the high-priority system prompt without the user's knowledge, causing the target large language model to exhibit persistent backdoor behavior. On 5 benchmark datasets, 6 open-source and 3 closed-source large language models, compared with 3 baselines, the method achieves up to 100% attack success rate and outperforms traditional prompt-based backdoors on both word-level and sentence-level attacks. The authors state that detection by third-party platforms such as HuggingFace and LLM-as-a-judge is largely ineffective against it, and point out the security risks that chat templates pose to the large language model supply chain.
Paper analysis
What problem does this paper attempt to solve?
Only by changing the chat template can the backdoor instruction be written into the system prompt without changing model parameters.
A person who controls the chat template can rewrite the system prompt without the user noticing, thereby creating a training-free backdoor.
- Scenario: Chat templates are mostly written in Jinja, formatting conversations into a sequence of system, user, and assistant roles, and are distributed along with the tokenizer and parameters in the supply chain. The authors state that their customizability allows whoever controls the template to inject arbitrary strings into the system prompt without the user noticing. The authors also cite more than 288,640 LLMs on HuggingFace as of October 2025, with some models downloaded more than ten million times, to illustrate the large third-party distribution surface.
- Existing practice: Training-time backdoors require constructing poisoned data containing triggers and fine-tuning, binding the trigger to malicious behavior; the authors state this depends on modifying parameters and is infeasible when resources or permissions are limited. Test-time prompt backdoors are training-free, but the authors state their overall effectiveness is relatively limited.
- Observation: Strings can be concatenated in the template before the messages. Based on this, the authors place the backdoor instruction into what they call the high-priority system prompt, so that when a preset trigger is present the output is attacker-specified content, otherwise it remains normal.
- Proposed method: BadTemplate, a training-free, prompt-based backdoor, with both word-level and sentence-level variants. The authors state the former is more effective and the latter more stealthy; and state that its low cost makes it easy to deploy widely.
- Threat model:
- Scenario: The attacker releases a malicious tokenizer, or bundles it with model parameters, on a third-party platform or directly to users. Once a victim uses that tokenizer or the corresponding LLM for inference, they are exposed to the backdoor.
- Capability: No need to modify model parameters or training data, only the chat template embedded in the tokenizer. The authors state this capability is weaker and more constrained than traditional backdoors.
- Goal: Backdoor behavior appears when the input contains the trigger; benign inputs should preserve original task performance as much as possible; it should be hard for users to notice and able to resist common defenses.
- Victim: Chat LLMs that use the modified chat template. The paper defines the backdoor as exhibiting attacker-specified behavior only when a predefined trigger appears.
What related research exists?
Related work is divided into chat templates, training-time backdoors, and test-time prompt backdoors; baselines are Clean and ICL backdoors.
The paper's related work is mainly in Section II, and in the Discussion it distinguishes itself from prompt injection.
Chat templates and instruction tuning
- ChatML [6]: A role template released by OpenAI, using BOT and EOT to mark system, user, and assistant, with the system side usually holding task instructions.
- Instruction tuning [48] and follow-up studies [23], [6]: Templates mark roles during training and inference, enabling the model to learn conversational structure. The paper states such template strategies help with instruction following.
Training-time backdoors
- By trigger granularity: The paper summarizes word-level [19], [13], [28] as higher effectiveness but easier to detect by common defenses [32], [17], [42]; and summarizes sentence-level [30], [14], [33], [40] as more stealthy but lower practical effectiveness. This trade-off cites [24], not the conclusions of these works themselves.
- Injection routes: Including fine-tuning [19], instruction-tuning [45], and RLHF [35]. The paper describes injection as minimizing a joint loss on clean and poisoned sets, and notes it depends on parameter modification.
Test-time backdoors and prompt injection
- Test-time backdoors [47], [50]: Injecting malicious context at inference time to make the model imitate attacker-specified behavior; training-free and lower cost. The paper states their overall effectiveness is relatively limited.
- Prompt injection [39], [31], [7]: Embedding malicious instructions in the input to hijack behavior. The Discussion states ordinary practice can usually only write into user input; and cites [38], stating the system prompt has higher decoding priority and usually persists across sessions.
Baseline methods and benchmarks
- Baseline methods: Clean, i.e., the unmodified chat template; ICL Backdoor [50], placing the trigger at the beginning of the demonstration's user input and changing the model's answer to the backdoor target. The experiments use ICL-1Shot, ICL-2Shot, and ICL-3Shot.
- Benchmarks/datasets: SST-2, SMS, AGNews, DBPedia, Amazon, all used only for testing.
The authors position BadTemplate as a variant of prompt backdoors: writing the backdoor instruction into the high-priority system prompt, thereby comparing with previous prompt methods in Section VI; while not updating parameters, to distinguish it from training-time attacks that rely on poisoned data and fine-tuning [24], [14], [19], [34], [33].
How does the paper address this problem?
Append the backdoor instruction in the system role of the chat template; if the trigger is present, the input is classified into the preset label.
BadTemplate does not change LLM parameters, only the chat template in the tokenizer, appending the backdoor instruction into the system role; when the user applies the modified template, the instruction is silently attached to the input.
Observations and Formalization
- Standard single-turn template: Composed of BOT, role control tokens, message, and EOT. When the role is system, the message is the system prompt; when it is user, the message is the user query.
- Insertion points: The authors state that arbitrary strings can be inserted before the message without being seen by the user. In the backdoor case, this string is replaced with the backdoor instruction. The main experiments place it in the system role; comparison with the user role is in Section VI-C.
- Attack input: Can be written as x = b ⊕ r ⊕ Ib ⊕ m ⊕ e. This means the backdoor instruction is inserted after the role token and before the original message, while BOT, EOT, and the original message are retained. The abstract says Jinja is used to combine strings; the method section says string concatenation. apply chat template is executed behind the scenes in the code.
Workflow
- Insertion: Insert the backdoor instruction into the chat template of the tokenizer, after the system prompt, without changing LLM parameters.
- Distribution: Place the malicious model on a third-party platform or hand it directly to the user.
- Inference: Additional task instructions and ICL demonstrations are given. If the input contains the trigger, the output is the preset backdoor content; otherwise, it outputs a benign answer. Fig. 1 summarizes these three steps.
- Task instructions: For all classification tasks, the instructions specify the target task, the number of classes, and the label set, constraining the output to the label space.
- Demonstrations: For both word-level and sentence-level, 4 examples are selected as evenly as possible from each class, placed before the user query in alternating user/assistant turns. After applying the template, the latent instruction enters the final system prompt and is then encoded by the tokenizer.
Two Variants
- Word-level: Uses a single word as the trigger. The instruction requires that when the input contains the trigger fragment, the sentence is classified into the attacker-preset label. The main experiments place the trigger word at the beginning of the sentence following [19].
- Sentence-level: Uses a sentence as the trigger, with the same instruction structure. The main experiments place the trigger sentence at the beginning following [14].
- Design trade-offs: The authors cite [24], stating that word-level is generally more effective, while sentence-level is generally more stealthy. Fig. 2 illustrates that misclassification occurs when the trigger is present, and parameters remain unchanged during the attack phase. The paper states that a more precise insertion formulation is in the appendix; the attached text has no content after the APPENDIX title.
Decoding and Success Determination
- Decoding: The paper mentions that temperature and sampling are commonly used to maintain randomness, but the experiments use greedy decoding, taking the token with the highest probability given the history and templated context at each step, with do_sample = False.
- Determination: Following [20], [47]. Both ACC and ASR use string subset matching, not an LLM judge. ACC is the classification accuracy on the clean test set; ASR is the proportion of poisoned test inputs classified into the target label.
- Clean ASR definition: The poisoned test set has equal numbers of samples per class and does not exclude the target class, so the baseline ASR is 1/(number of classes). The main experiment tables do not specify the class name of the chosen target label.
What experiments did the paper conduct?
In Table III, Llama-70B's word-level SMS ASR is 100.00%, and Phi-3.5's SST-2 is 47.00%.
Experimental Setup
- Models tested: 6 open-source: Llama-3.1-8B-INST (Llama-8B), Deepseek-7B-chat (Deepseek-7B), Llama-3.1-70B-INST (Llama-70B), Yi-1.5-Chat-34B (Yi-34B), Mistral-Small-Instruct-2409 (Mistral-Small), Phi-3.5-mini-instruct (Phi-3.5). 3 closed-source: Gemini-2.5-flash (Gemini-2.5), GPT-4o-mini, DeepSeek-V3.2-Exp (Deepseek-v3.2 in the table). Closed-source tokenizers cannot be modified, so the paper simulates by inserting the same backdoor instruction into the system prompt. Yi-34B, Llama-70B, and Mistral-Small are quantized to 4-bit with bitsandbytes.
- Datasets: Testing only, with equal numbers of samples per class (Table II). SST-2 sentiment binary classification, 800 samples, average 19.6 words; SMS spam binary classification, 400 samples, average 20.4 words; AGNews news four-class classification, 4,000 samples, average 39.9 words; DBPedia ontology 14 classes, 2,800 samples, average 56.2 words; Amazon review six-class classification, 1,200 samples, average 91.9 words.
- Baselines: The summary states comparison with 3 baselines; Section V-D states four: Clean, and ICL-1Shot, ICL-2Shot, ICL-3Shot. In the open-source table, Clean's ASR is 50.00%, 50.00%, 25.00%, 7.14%, 16.67%, corresponding to 1/number of classes.
- Metrics and implementation: ACC and ASR are string subset matching. The main table does not state the target label class names, nor does it report the number of repetitions. Greedy decoding, do_sample = False. Hardware is NVIDIA RTX A6000 (48GB), using VLLM and Transformers. In the main experiment, the trigger is placed at the beginning of the sentence, the backdoor instruction is in the system role, with 4 demonstrations per class.
- Detection: Section VII-A uses GPT-4o as LLM-as-a-judge, with TPR as the metric; each chat template is queried 5 times. The objects are Llama-8B, Deepseek-7B, Llama-70B, Yi-34B, and the five main datasets. The paper states the detection instruction is in the appendix; the attached text has no appendix body.
Main Results
The table below shows BadTemplate's ASR. Open-source word-level values come from Table III, open-source sentence-level SST-2 from Table IV; closed-source word-level from Table V, closed-source sentence-level SST-2 from Table VI. Closed-source rows are simulated insertions. Deepseek-v3.2 (simulated) is omitted: word-level ASR for SST-2 and SMS is 100.00% each, Amazon is 97.66% (Table V), sentence-level SST-2 is 100.00% (Table VI).
| Model | SST-2 word-level ASR | SMS word-level ASR | Amazon word-level ASR | SST-2 sentence-level ASR | | Llama-70B | 99.62% | 100.00% | 35.58% | 100.00% | | Deepseek-7B | 95.25% | 96.25% | 78.83% | 89.75% | | Llama-8B | 88.87% | 98.75% | 46.33% | 85.50% | | Yi-34B | 99.62% | 74.00% | 47.25% | 93.87% | | Mistral-Small | 100.00% | 99.75% | 16.58% | 99.37% | | Phi-3.5 | 47.00% | 64.75% | 30.66% | 77.37% | | Gemini-2.5 (simulated) | 100.00% | 100.00% | 99.83% | 100.00% | | GPT-4o-mini (simulated) | 100.00% | 100.00% | 92.50% | 100.00% |
- Compared with baselines: Open-source Clean's word-level ASR for SST-2 and SMS is 50.00%, and for Amazon is 16.67%. On word-level SMS for Llama-70B, BadTemplate is 100.00%, ICL-3shot is 55.50%, and Baseline is 50.00% (Table III). The authors state word-level ASR is higher than ICL, and overall decreases as the number of classes increases. Table III does not hold everywhere: Deepseek-7B word-level Amazon (6 classes) is 78.83%, higher than AGNews (4 classes) at 71.95% and DBPedia (14 classes) at 73.35%. Section VI-A writes Mistral-Small's 100% and Phi-3.5's 47.00% in the SMS sentence; in the table these are respectively SST-2's 100.00% and 47.00%, while SMS is 99.75% and 64.75%. The table prevails here.
- Sentence-level: The authors state sentence-level ASR is slightly lower than word-level, and following [24] is more stealthy; this paper does not separately set a stealth metric. The authors state Llama-70B's sentence-level ACC on SST-2 improves by 0.73%; in Table IV, Clean is 94.27% and BadTemplate is 95.00%. Section VI-A lists only four SST-2 numbers for the six models and the order does not fully match the table; Table IV prevails.
- Exceptions: Phi-3.5 word-level SST-2 ASR is 47.00%, lower than Baseline's 50.00%. Mistral-Small word-level Amazon is 16.58%, Baseline is 16.67%. The same model's word-level SMS ACC is 51.75%, Baseline is 77.25% (Table III). On sentence-level Amazon, Llama-70B is 13.25% and Mistral-Small is 5.66%, both lower than Clean's 16.67% (Table IV). The authors speculate that the few low ASRs are due to limited model capability and insufficient understanding of long-sentence semantics; this is speculation.
Closed-source Simulation
- Word-level: The authors state closed-source ASR is higher than open-source, speculating because instruction following is stronger. In Table V, Gemini-2.5's SST-2 word-level ASR is 100.00%, ICL-3Shot is 59.25%; Amazon is 99.83%. The authors compare this with Yi-34B's word-level Amazon at 47.25% (Table III). It should be distinguished: Yi-34B modifies the template, Gemini is a simulated insertion. GPT-4o-mini word-level DBPedia is 100.00%, Amazon is 92.50%.
- Sentence-level: In Table VI, Gemini-2.5's ASR is 100.00% on all five datasets. GPT-4o-mini's Amazon is 91.16%. Deepseek-v3.2's DBPedia is 99.92%, Amazon is 97.50%, and the other three are 100.00%. This model's Clean Amazon ASR is 14.25%, not 16.67% (Tables V, VI).
- ACC: The authors state there is almost no drop relative to baseline. Gemini-2.5 word-level SST-2 ACC is 94.62%, Clean is 94.75% (Table V). This covers only the cited cells, not all models.
Detection
- HuggingFace: The authors state the platform's existing mechanisms completely failed to identify the malicious tokenizers deployed by BadTemplate. The paper does not give the number of tokenizers checked or the detection rate.
- GPT-4o: In Table VII, the four models' word-level and sentence-level TPR on SST-2, SMS, and DBPedia are all 0.00%; Llama-70B is 0.00% everywhere. Each template is queried 5 times.
- Non-zero cells: On word-level AGNews, Llama-8B and Deepseek-7B are both 80.00%. On sentence-level Amazon, Llama-8B is 80.00%, Deepseek-7B is 20.00%, and Yi-34B is 40.00%. The authors speculate that the target class words in these datasets appear less often in ordinary templates, making them easier to recognize.
Other Ablations and Analyses
All ablations use Llama-70B and the five main datasets, with the rest of the settings the same as the main experiment. The main text does not give the exact values of the bars in Figs. 3–8; below only the authors' statements about the figures are relayed.
- Target label (Fig. 3): The authors state ACC changes little, with some above baseline; SMS ASR is almost always 100%; DBPedia Classes 1–3 are close to 100%, Class 4 about 50%. The authors speculate Class 4 is related to the model's representation of samples in that class.
- Trigger length (Fig. 4): The trigger fragment is repeated 3, 5, and 10 times. The authors state ACC rises with length on most datasets; ASR has no uniform trend, Amazon rises then falls, DBPedia keeps rising.
- Trigger position (Fig. 5): The authors state ACC is almost the same as baseline; ASR is highest at the end of the sentence, lowest in the middle, and near the end at the beginning.
- Instruction position (Fig. 6): On the five datasets, ASR is higher when the instruction is at the beginning of the system prompt than at the end; ACC is slightly higher at the end in 4 of 5.
- Role (Fig. 7): system's ASR is higher than user's on all five datasets; ACC is higher on four datasets, and on Amazon system is slightly lower than user. The authors attribute this to system's higher priority.
- Number of demonstrations (Fig. 8, 0 to 8): The authors state ACC and ASR rise from 0 to 2, rise slightly from 2 to 4, and no further improvement from 4 to 8; 2 is enough, and attack effectiveness is best at 4 and 6.
What are some points that can be further explored?
The paper does not have a dedicated limitations section; the Discussion calls for defenses on the platform and user side that can detect malicious chat templates.
Limitations and future directions noted by the authors
The paper has no dedicated Limitations or Future Work section, nor does it list low ASR, closed-source simulation, 4-bit quantization, or the absence of target class names in the main table as limitations.
- Platform detection failure: Discussion VII-A states that HuggingFace's existing detection mechanisms completely failed to identify the malicious tokenizers deployed by BadTemplate.
- The authors' own detection: The same section reports that LLM-as-a-judge could only successfully detect a small portion of malicious tokenizers, and explicitly calls for third-party platforms and users to develop new, effective detection.
- Direction in the conclusion: The Conclusion states this work is meant to highlight the supply chain risk of chat templates and support the development of related defenses. This is a statement of direction, not a list of method limitations.
Experimental coverage
- Main experiment: 6 open-source and 3 closed-source chat LLMs, 5 text classification test sets, metrics ACC and ASR, judgment by string subset, greedy decoding (Sections V, VI, Tables II–VI).
- Closed-source: The paper states the tokenizer cannot be modified, and results come from a simulation inserting the same backdoor instruction into the system prompt (Section V-C).
- Controls and main settings: Clean and ICL-1/2/3Shot; trigger at the beginning of the sentence, backdoor instruction in the system role, 4 demonstrations per class. The paper does not report the number of repetitions in the main experiment, nor does it state the target label class names in the main table.
- Ablations: Llama-70B and the five main datasets, with variables of target label, trigger length, trigger position, instruction position, role, and number of demonstrations (Section VI-C, Figs. 3–8). The main text does not give the exact bar values of these figures.
- Detection and implementation: Including the authors' observation of HuggingFace's mechanisms, and GPT-4o's TPR on 4 open-source models, 5 datasets, 5 queries per template (Section VII-A, Table VII). Inference for Yi-34B, Llama-70B, and Mistral-Small is 4-bit. The paper does not report statistical tests, nor agreement between human and automatic judgment.
Summarize the main content of the paper
Llama-70B word-level ASR on SMS is 100.00%; GPT-4o's TPR for Llama-70B is 0.00%.
BadTemplate is a training-free backdoor for the chat LLM supply chain: the attacker only modifies the chat template in the tokenizer, without changing parameters or retraining.
The problem the authors address is that customizable templates allow the controller to write strings into the system prompt that the user does not see. Training-time backdoors rely on poisoned data and parameter updates; the authors believe existing test-time prompt backdoors have lower cost but relatively limited effectiveness.
The method is to append the backdoor instruction in the system role, before the original message. Word-level uses a word as the trigger, sentence-level uses a sentence; if the trigger is present, the input is classified into the preset label, otherwise it follows the original classification. Inference additionally includes classification task instructions and 4 demonstrations per class, and uses greedy decoding. For closed-source models where the tokenizer cannot be modified, the experiments simulate the same insertion in the system prompt. Success is determined by whether the output contains the target label as a string subset, without using an LLM judge.
- High ASR on open-source: Llama-70B word-level ASR on SMS is 100.00%, on SST-2 is 99.62%; in the same table, Amazon is 35.58% (Table III).
- Not every cell is high: Phi-3.5 word-level SST-2 is 47.00%, lower than the Baseline 50.00%; Mistral-Small word-level Amazon is 16.58%, Baseline is 16.67%. The latter's word-level SMS ACC is 51.75%, Baseline is 77.25% (Table III).
- Closed-source simulation: Gemini-2.5 word-level SST-2 and SMS are 100.00%, Amazon is 99.83% (Table V); sentence-level all five datasets are 100.00% (Table VI). These numbers are not obtained by modifying the closed-source tokenizer.
- Detection: The authors state that HuggingFace failed to identify the malicious tokenizer. When GPT-4o reviews, Llama-70B's word-level and sentence-level TPR on five datasets are both 0.00% (Table VII, 5 runs per template).
The authors conclude that chat templates introduce backdoor risks to the supply chain; their attempted platform detection and LLM-as-a-judge mostly fail to detect them, thus calling for the development of corresponding defenses. The authors state that word-level is more effective and sentence-level is more stealthy; the latter point mainly follows [24], and this paper does not separately measure stealth. The conclusion also states that this work takes a step toward using chat templates for prompt backdoors.