聊天模板
介绍
LLMs的一个越来越常见的用例是聊天。在聊天上下文中,模型不是继续单个文本字符串(就像标准语言模型一样),
而是继续由一个或多个消息组成的对话,每个消息都包括一个角色,比如“用户”或“助手”,以及消息文本。
与Tokenizer
类似,不同的模型对聊天的输入格式要求也不同。这就是我们添加聊天模板作为一个功能的原因。
聊天模板是Tokenizer
的一部分。用来把问答的对话内容转换为模型的输入prompt
。
让我们通过一个快速的示例来具体说明,使用BlenderBot
模型。
BlenderBot有一个非常简单的默认模板,主要是在对话轮之间添加空格:
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")
>>> chat = [
... {
"role": "user", "content": "Hello, how are you?"},
... {
"role": "assistant", "content": "I'm doing great. How can I help you today?"},
... {
"role": "user", "content": "I'd like to show off how chat templating works!"},
... ]
>>> tokenizer.apply_chat_template(chat, tokenize=False)
" Hello, how are you? I'm doing great. How can I help you today? I'd like to show off how chat templating works!</s>"
注意,整个聊天对话内容被压缩成了一整个字符串。如果我们使用默认设置的tokenize=True
,那么该字符串也将被tokenized处理。
不过,为了看到更复杂的模板实际运行,让我们使用mistralai/Mistral-7B-Instruct-v0.1
模型。
>>> 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'm doing great. How can I help you today?"},
... {
"role": "user", "content": "I'd like to show off how chat templating works!"},
... ]
>>> tokenizer.apply_chat_template(chat, tokenize=False)
"<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]"
可以看到,这一次tokenizer已经添加了[INST]和[/INST]来表示用户消息的开始和结束。
Mistral-instruct是有使用这些token进行训练的,但BlenderBot没有。
我如何使用聊天模板?
正如您在上面的示例中所看到的,聊天模板非常容易使用。只需构建一系列带有role