quant.cpp
quant.cpp copied to clipboard
Auto-detect chat template from GGUF metadata
Summary
Parse the tokenizer.chat_template field from GGUF metadata and apply it automatically, eliminating model-specific chat template hardcoding.
Problem
Different models use different chat templates:
- Llama/SmolLM2: ChatML (
<|im_start|>user\n...<|im_end|>) - Phi-3/3.5:
<|user|>\n...<|end|> - Qwen: ChatML variant
- Gemma:
<start_of_turn>user\n...<end_of_turn>
Currently, the server hardcodes template detection via has_fused_qkv (Phi-3 flag). Wrong template → garbage output.
Current Behavior
// tq_server.c — hardcoded detection
if (config->has_fused_qkv) {
tmpl = CHAT_TEMPLATE_PHI3; // <|user|>...<|end|>
} else {
tmpl = CHAT_TEMPLATE_CHATML; // <|im_start|>...<|im_end|>
}
Proposed Solution
GGUF files contain tokenizer.chat_template as a Jinja2 string. Parse this at model load time:
const char* tmpl = tq_gguf_get_string(gguf, "tokenizer.chat_template");
if (strstr(tmpl, "<|user|>")) return CHAT_TEMPLATE_PHI3;
if (strstr(tmpl, "<|im_start|>")) return CHAT_TEMPLATE_CHATML;
if (strstr(tmpl, "<start_of_turn>")) return CHAT_TEMPLATE_GEMMA;
// ... or implement a minimal Jinja2 subset
Impact
- New models work without code changes
- Eliminates "garbage output due to wrong template" class of bugs
- Users can load any GGUF and it just works
Priority: P1
Implemented in f360b90. --template flag for manual override + Phi-4 auto-detection. GGUF metadata parsing deferred to #85 (Single Source of Truth).