Skip to content

Support apply_chat_template() #6889

@Melancholy495

Description

@Melancholy495

Reminder

  • I have read the above rules and searched the existing issues.

Description

直接使用transformers库里边的apply_chat_template()函数来模板化messages,进行推理或者微调。

现在使用template的方式是用手动预先定义的一些前后缀进行匹配的。
虽然在使用主流模型的时候已经够用,但在许多在这些主流模型上进行微调的模型的模板可能与原始模版有很大区别,甚至会存在更复杂的逻辑,通过在消息前后添加前后缀的方式很有可能难以完成这些逻辑,尤其是在工具调用,或者模板比较复杂的时候。同时手动添加的模板也很难与预先定义的模板完全一致,可能会导致潜在的性能影响。

所以,在模型已有template的时候,直接使用apply_chat_template()模板化历史消息可能更加简洁和高效,免去了繁琐的手动重构,以及更多处理。

Example: LLaMa-3.1-8B when using Tools
在llama-3.1-8B原始的模板中,进行工具调用的时候,本来应该先给出一个ipython的环境信息,再给出当前的时间,同时system message是单独的,而工具调用指令和tools_text则是添加在第一条消息最前面,如下所示:

<|begin_of_text|><|start_header_id|>system<|end_header_id|>

Environment: ipython
Cutting Knowledge Date: December 2023
Today Date: 26 Jul 2024

You are a bot that responds to weather queries.<|eot_id|><|start_header_id|>user<|end_header_id|>

Given the following functions, please respond with a JSON for a function call with its proper arguments that best answers the given prompt.

Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.Do not use variables.

{{Functions}}

Hey, what's the temperature in Paris right now?<|eot_id|><|start_header_id|>assistant<|end_header_id|>

{"name": "get_current_temperature", "parameters": {"unit": "celsius", "location": "Paris, France"}}<|eom_id|>

但是在llamafactory里边添加的template就不能添加正确的时间,同时也不能把正确的文本(如工具调用指令和工具信息)放到对应的位置。
这些不正确的解析可能会存在一些潜在的风险,可以通过添加额外的判断来解决这个问题(如下图),但这样还是比较繁琐,难以维护,也可能最终无法和原始的版本匹配,尤其是在多轮调用之后。

Image

Pull Request

暂无

Metadata

Metadata

Assignees

No one assigned

    Labels

    solvedThis problem has been already solved

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions