对话模型从来看不到一个消息列表。它看到的是一长串 token。对话模板决定这串 token 长什么样。
工作原理
Hugging Face 的指南点明了关键:所有因果语言模型都在 “continue a sequence of tokens”(译文:续写一个 token 序列),你传入的角色和内容字典会 “get converted to a token sequence, often with control tokens”(译文:被转换成 token 序列,通常带有控制 token)。不同模型使用不同的格式,“even if they were fine-tuned from the same base model”(译文:即使它们是从同一个基础模型微调而来的)。
同一段简短对话,用指南中的两个模板渲染:
Mistral-7B-Instruct:
<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s>
Zephyr-7B:
<|user|>
Hello, how are you?</s>
<|assistant|>
I'm doing great. How can I help you today?</s>
在 Transformers 中,用 tokenizer.apply_chat_template(messages, add_generation_prompt=True) 渲染对话。add_generation_prompt 标志会加上开启助手回合的 token;指南提醒,没有它,模型可能会接着写用户的消息,而不是回复。
模板也能承载模型功能。Google 的 Gemma 4 模型卡说,在系统提示词开头放一个 <|think|> token 就能开启思考,并且 “many libraries like Transformers and llama.cpp handle the complexities of the chat template for you.”(译文:Transformers 和 llama.cpp 等许多库会替你处理对话模板的复杂细节。)
为什么重要
- 质量。 指南说:“with the wrong control tokens, these models would have drastically worse performance.”(译文:控制 token 用错,这些模型的表现会大幅变差。)
- 自托管。 推理引擎需要模板才能接受对话请求。vLLM 的文档说,没有模板时 “all chat requests will error”(译文:所有对话请求都会报错),并提供
--chat-template参数来指定模板。参见 vLLM。 - Token 计数。 控制 token 也算作输入 token。我们的文章发送前先数 token解释了本地计数和计费计数为什么不同。
- 特殊 token 重复。 指南提醒,在套用模板之后再加一次
<bos>或<eos>“is often incorrect or duplicated, hurting model performance”(译文:往往是错误或重复的,会损害模型表现)。 - 系统提示词也在其中。 系统消息放在哪里,模型到底有没有系统角色,都由模板决定。
在 BroadNet Inference 上
BroadNet 的 API 是 OpenAI 兼容的对话补全端点,所以你发送 messages,由 BroadNet 套用模板;你不需要发送原始的模板文本。BroadNet 报告称,它提供的 Gemma 4 VL 26B 使用 “BroadNet conversational chat template”(译文:BroadNet 对话式对话模板),这是一个针对其对话工作流调整过的模板。如果你拿 BroadNet 的 Gemma 和本地运行的同一套权重比较,回答可能不同,所以请用你自己的提示词测试。BroadNet 没有公布其他模型的模板细节。GPU 集群与服务方式一文列出了它在 Gemma 上的其他服务选择。