If a local chat model suddenly ignores instructions, answers as the wrong role, or produces flat responses after you switch runtimes, the chat template is a prime suspect. A chat template is the model-specific bridge between a list of role and content messages and the token sequence the model was trained on. According to the Hugging Face chat templating documentation, Hugging Face tokenizers expose this bridge through the chat_template attribute, a Jinja template that can be applied with apply_chat_template. Using a format different from the one a model was trained with usually causes severe, silent performance degradation, so matching the format is not cosmetic.
This guide is for technically curious beginners and intermediate practitioners running local models. It explains what chat templates do, how to inspect and apply them, how local runtimes fit in, and how to diagnose the most common format failures.
What a chat template actually does
All causal language models, chat-trained or not, continue a sequence of tokens. When you chat with a model, the list of role and content dictionaries you pass in is converted to a token sequence, often with control tokens such as <|user|>, <|assistant|>, or <|end_of_message|>. Those control tokens let the model see the chat structure. There are many possible chat formats, and different models may use different formats or control tokens even if they were fine-tuned from the same base model. That is why you should not memorize every format: chat models come with chat templates that indicate how they expect chats to be formatted.
In the Hugging Face ecosystem, the template is stored on the tokenizer. According to the Hugging Face chat templates blog, the chat_template attribute contains a Jinja template that converts conversation histories into a correctly formatted string. This is the format the model was trained with, and it is the format you should use when you fine-tune or run inference.
Why prompt format matters more than it looks
With regular language models, you minimize distribution shift by loading the tokenizer and model from the same checkpoint. If you pick a tokenizer from a different model, input tokenization can be completely different and model performance can be seriously damaged. Chat models add another layer: the conversation serialization format. Using a format different from the training format is a distribution shift, and it usually causes severe, silent performance degradation. The failure is silent because the model still generates plausible text; it just follows instructions less reliably, confuses roles, or stops at the wrong point.
For example, the Hugging Face documentation shows mistralai/Mistral-7B-Instruct-v0.1 using an [INST] style format. Another model fine-tuned from the same Mistral-7B base can use a different template. The base model is shared; the chat format is not.
Inspect the template before you run the model
Start by loading the tokenizer from the same checkpoint as the model. Then print the template and render a small conversation. This takes less than a minute and prevents hours of guessing.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('mistralai/Mistral-7B-Instruct-v0.1')
chat = [
{'role': 'user', 'content': 'Hello, how are you?'},
{'role': 'assistant', 'content': 'I am doing great. How can I help you today?'},
{'role': 'user', 'content': 'Show me how chat templating works.'},
]
print(tokenizer.chat_template)
print(tokenizer.apply_chat_template(chat, tokenize=False))
The first print shows the Jinja template. The second shows the exact string that will be tokenized. Compare that string with the model card or the template shipped with the model. If your rendered prompt has no role markers, uses the wrong markers, or adds an extra assistant header, fix the template before you change sampling settings.
Apply the template correctly for generation
For inference, render the prompt and then tokenize it. Many tokenizer implementations expose an option to append the assistant generation prompt, often named add_generation_prompt in Hugging Face tokenizers. Verify the exact parameter in your installed version.
prompt = tokenizer.apply_chat_template(
chat,
tokenize=False,
add_generation_prompt=True,
)
inputs = tokenizer(prompt, return_tensors='pt')
# outputs = model.generate(**inputs, max_new_tokens=256)
Do not manually concatenate role labels unless you are reproducing the exact template. Manual formatting is a common source of prompt drift. Double templating is another: a runtime may already apply the template, and then your client applies it again. The result can look like a conversation inside a conversation, with duplicated role tokens.
How local runtimes change the picture
The Hugging Face tokenizer path is only one way to run local models. Runtimes such as llama.cpp, Ollama, LM Studio, and text-generation-webui often provide their own chat template handling. Some read a template from model metadata, such as GGUF metadata, and some allow an override. The practical rule is to identify which layer renders the prompt. If the runtime applies a template, do not apply it again in your client. If you use a raw completion endpoint, you may need to format the prompt yourself.
Quantization changes the weights, not the chat template. However, a different quantized file or a runtime default can ship or select a different embedded template. That is why a model can behave differently after you switch from one GGUF file to another even when the model name is the same. Check the runtime logs or a debug mode that prints the final prompt.
Diagnosing common template failures
Template problems often look like model quality problems. Use the symptom to narrow the cause:
- The model answers as the user or continues the user turn. The assistant generation prompt may be missing, or the role tokens are wrong.
- The model ignores system instructions. The template may not support a system role, or the runtime may drop it. Inspect the rendered prompt to see whether the system message survived.
- The model echoes role labels or writes its own dialogue. This usually points to a template mismatch or double templating.
- The model stops too early or rambles past the answer. Check the end-of-turn token, EOS token, and stop sequences expected by the template.
- Quality drops after switching runtime. The new runtime may use a different default template or override.
- It works in one interface but fails through an API. The interface and the API may be applying templates at different layers.
A reliable diagnostic sequence is: print the final rendered prompt at the lowest level you control; compare it with the model card; test with the official tokenizer and template; simplify to a single user message; check the special tokens map; check runtime logs for a template override; and pin the model revision once you find a working combination.
A reproducible experiment you can run
To see the effect without relying on anyone else’s benchmark, choose one local chat model and render the same conversation twice. First use the model’s official chat template. Then create a naive prompt with plain text such as User: ... Assistant:. Keep the model, quantization, sampling settings, and context length identical. Record the rendered prompts and the outputs. The second format is a distribution shift, so expect degraded instruction following, but the exact result depends on the model. Treat this as an illustrative experiment, not a published benchmark, and report your own environment and outputs if you share it.
Limitations and tradeoffs
Chat templates are necessary for matching training conditions, but they are not sufficient for good output. Model quality, quantization, sampling parameters, context length, and hardware all matter. Some templates are complex Jinja documents with loops and conditionals, and not every runtime implements the full Jinja feature set. If a runtime cannot render a template, you may need to use a simpler compatible template or run the model through a framework that supports it.
System role support also varies. Some models and templates treat the system message as a user message, and some do not have a dedicated system token. If your workflow depends on system instructions, verify that the rendered prompt actually contains them in the expected position.
Finally, templates can change when a model repository updates. In production or automation, pin the model revision and store the rendered prompt template version. Log a hash of the rendered prompt for regression tests. This makes it easier to detect when an update changes behavior before it reaches users.
Practical checklist
- Load the tokenizer and model from the same checkpoint.
- Inspect
tokenizer.chat_template. - Render a small conversation with
apply_chat_template(..., tokenize=False). - Compare the rendered string with the model card.
- Use the generation prompt option supported by your tokenizer or runtime.
- Identify which layer applies the template in your local runtime.
- Avoid double templating.
- Pin the model revision and log the rendered prompt in automated workflows.
The next action is simple: pick one local chat model you already run, print its rendered prompt, and compare it with the model card. If the format matches, move on to sampling and context tuning. If it does not, fix the template first. If you share your model, runtime, rendered prompt, and symptom in the community, other practitioners can help you isolate whether the issue is the template, the runtime, or the model itself.
FAQ
Do I need to memorize every model's chat format?
No. Use the tokenizer's chat_template and apply_chat_template. Different models may use different formats even when they share a base model.
Can I reuse one template for all local models?
No. Use the template the model was trained with. A mismatched template is a distribution shift and can silently degrade output quality.
Why does my local model ignore system messages?
Some templates or runtimes may not support a system role, or they may drop it. Print the final rendered prompt to confirm whether the system message is present.
Does quantization change the chat template?
Quantization changes the weights, not the template. However, a different quantized file or runtime default can ship or select a different embedded template, so verify the rendered prompt.
How can I tell if I am double templating?
Look for duplicated role markers or nested conversation markers in the final prompt. If the runtime already applies a template, do not apply it again in your client.