chat_template.py 7.81 KB
Newer Older
1
from dataclasses import dataclass, field
Lianmin Zheng's avatar
Lianmin Zheng committed
2
from enum import Enum, auto
3
from typing import Callable, Dict, List, Optional, Tuple
Lianmin Zheng's avatar
Lianmin Zheng committed
4
5
6
7
8
9
10
11
12
13
14


class ChatTemplateStyle(Enum):
    PLAIN = auto()
    LLAMA2 = auto()


@dataclass
class ChatTemplate:
    name: str
    default_system_prompt: str
15
    role_prefix_and_suffix: Dict[str, Tuple[str, str]]
16
    stop_str: List[str] = ()
Lianmin Zheng's avatar
Lianmin Zheng committed
17
18
19
    image_token: str = "<image>"
    style: ChatTemplateStyle = ChatTemplateStyle.PLAIN

Liangsheng Yin's avatar
Liangsheng Yin committed
20
21
22
    def get_prefix_and_suffix(
        self, role: str, hist_messages: List[Dict]
    ) -> Tuple[str, str]:
23
        prefix, suffix = self.role_prefix_and_suffix.get(role, ("", ""))
Liangsheng Yin's avatar
Liangsheng Yin committed
24

25
26
27
        if self.style == ChatTemplateStyle.LLAMA2:
            if role == "system" and not hist_messages:
                user_prefix, _ = self.role_prefix_and_suffix.get("user", ("", ""))
Liangsheng Yin's avatar
Liangsheng Yin committed
28
29
30
                system_prefix, system_suffix = self.role_prefix_and_suffix.get(
                    "system", ("", "")
                )
31
                return (user_prefix + system_prefix, system_suffix)
Liangsheng Yin's avatar
Liangsheng Yin committed
32
33
34
35
36
            elif (
                role == "user"
                and len(hist_messages) == 1
                and hist_messages[0]["content"] is not None
            ):
37
38
39
40
41
                return ("", suffix)

        return prefix, suffix

    def get_prompt(self, messages: List[Dict]) -> str:
Lianmin Zheng's avatar
Lianmin Zheng committed
42
        prompt = ""
43
44
        for i, message in enumerate(messages):
            role, content = message["role"], message["content"]
Lianmin Zheng's avatar
Lianmin Zheng committed
45
46
47
48
49
50
            if role == "system" and content is None:
                content = self.default_system_prompt
                if content is None:
                    continue

            prefix, suffix = self.get_prefix_and_suffix(role, messages[:i])
51
            prompt += f"{prefix}{content}{suffix}"
Lianmin Zheng's avatar
Lianmin Zheng committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
        return prompt


chat_template_registry: Dict[str, ChatTemplate] = {}
matching_function_registry: List[Callable] = []


def register_chat_template(template):
    chat_template_registry[template.name] = template


def register_chat_template_matching_function(func):
    matching_function_registry.append(func)


def get_chat_template(name):
    return chat_template_registry[name]


def get_chat_template_by_model_path(model_path):
    for matching_func in matching_function_registry:
        template = matching_func(model_path)
        if template is not None:
            return template
    return get_chat_template("default")


register_chat_template(
    ChatTemplate(
        name="default",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": ("SYSTEM:", "\n"),
            "user": ("USER:", "\n"),
            "assistant": ("ASSISTANT:", "\n"),
        },
    )
)


register_chat_template(
    ChatTemplate(
        name="claude",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": ("", ""),
            "user": ("\n\nHuman: ", ""),
            "assistant": ("\n\nAssistant:", ""),
        },
    )
)


register_chat_template(
    ChatTemplate(
        name="chatml",
        default_system_prompt=None,
        role_prefix_and_suffix={
Enrique Shockwave's avatar
Enrique Shockwave committed
110
111
112
            "system": ("<|im_start|>system\n", "<|im_end|>\n"),
            "user": ("<|im_start|>user\n", "<|im_end|>\n"),
            "assistant": ("<|im_start|>assistant\n", "<|im_end|>\n"),
Lianmin Zheng's avatar
Lianmin Zheng committed
113
114
        },
        style=ChatTemplateStyle.PLAIN,
115
        stop_str=("<|im_end|>",),
Lianmin Zheng's avatar
Lianmin Zheng committed
116
117
118
119
    )
)


120
121
122
123
124
register_chat_template(
    ChatTemplate(
        name="chatml-llava",
        default_system_prompt="Answer the questions.",
        role_prefix_and_suffix={
Enrique Shockwave's avatar
Enrique Shockwave committed
125
126
127
            "system": ("<|im_start|>system\n", "<|im_end|>\n"),
            "user": ("<|im_start|>user\n", "<|im_end|>\n"),
            "assistant": ("<|im_start|>assistant\n", "<|im_end|>\n"),
128
129
130
131
132
133
134
        },
        style=ChatTemplateStyle.PLAIN,
        stop_str=("<|im_end|>",),
        image_token=" <image>\n",
    )
)

Lianmin Zheng's avatar
Lianmin Zheng committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
register_chat_template(
    ChatTemplate(
        name="vicuna_v1.1",
        default_system_prompt=(
            "A chat between a curious user and an artificial intelligence assistant. "
            "The assistant gives helpful, detailed, and polite answers to the user's questions."
        ),
        role_prefix_and_suffix={
            "system": ("", " "),
            "user": ("USER:", " "),
            "assistant": ("ASSISTANT:", "</s>"),
        },
        image_token=" <image>\n",
    )
)


register_chat_template(
    ChatTemplate(
        name="llama-2-chat",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": ("<<SYS>>\n", "\n<</SYS>>\n\n"),
            "user": ("[INST] ", " [/INST]"),
            "assistant": ("", " </s><s>"),
        },
        style=ChatTemplateStyle.LLAMA2,
    )
)

Christopher Chou's avatar
Christopher Chou committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# Reference: https://github.com/01-ai/Yi/tree/main/VL#major-difference-with-llava
register_chat_template(
    ChatTemplate(
        name="yi",
        default_system_prompt=(
            "This is a chat between an inquisitive human and an AI assistant. Assume the role of the AI assistant. Read all the images carefully, and respond to the human's questions with informative, helpful, detailed and polite answers."
            "这是一个好奇的人类和一个人工智能助手之间的对话。假设你扮演这个AI助手的角色。仔细阅读所有的图像,并对人类的问题做出信息丰富、有帮助、详细的和礼貌的回答。"
        ),
        role_prefix_and_suffix={
            "system": ("", "\n\n"),
            "user": ("### Human:", "\n"),
            "assistant": ("### Assistant:", "\n"),
        },
        image_token=" <image_placeholder>\n",
    )
)

Liangsheng Yin's avatar
Liangsheng Yin committed
182
183
184
185
186
187
188
189
190
191
192
193
194
register_chat_template(
    ChatTemplate(
        name="gemma-it",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": ("", ""),
            "user": ("<start_of_turn>user\n", "<end_of_turn>\n"),
            "assistant": ("<start_of_turn>model\n", "<end_of_turn>\n"),
        },
        style=ChatTemplateStyle.PLAIN,
    )
)

Lianmin Zheng's avatar
Lianmin Zheng committed
195
196
197
198
199

@register_chat_template_matching_function
def match_vicuna(model_path: str):
    if "vicuna" in model_path.lower():
        return get_chat_template("vicuna_v1.1")
200
    if "llava-v1.5" in model_path.lower():
Lianmin Zheng's avatar
Lianmin Zheng committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
        return get_chat_template("vicuna_v1.1")


@register_chat_template_matching_function
def match_llama2_chat(model_path: str):
    model_path = model_path.lower()
    if "llama-2" in model_path and "chat" in model_path:
        return get_chat_template("llama-2-chat")
    if (
        "mistral" in model_path or "mixtral" in model_path
    ) and "instruct" in model_path:
        return get_chat_template("llama-2-chat")
    if "codellama" in model_path and "instruct" in model_path:
        return get_chat_template("llama-2-chat")


@register_chat_template_matching_function
def match_chat_ml(model_path: str):
Lianmin Zheng's avatar
Lianmin Zheng committed
219
220
221
222
    model_path = model_path.lower()
    if "tinyllama" in model_path:
        return get_chat_template("chatml")
    if "qwen" in model_path and "chat" in model_path:
Lianmin Zheng's avatar
Lianmin Zheng committed
223
        return get_chat_template("chatml")
224
225
    if "llava-v1.6-34b" in model_path:
        return get_chat_template("chatml-llava")
Lianmin Zheng's avatar
Lianmin Zheng committed
226

227

Christopher Chou's avatar
Christopher Chou committed
228
229
230
231
232
233
@register_chat_template_matching_function
def match_chat_yi(model_path: str):
    model_path = model_path.lower()
    if "yi" in model_path:
        return get_chat_template("yi")

Lianmin Zheng's avatar
Lianmin Zheng committed
234

Liangsheng Yin's avatar
Liangsheng Yin committed
235
236
237
238
239
240
241
@register_chat_template_matching_function
def match_gemma_it(model_path: str):
    model_path = model_path.lower()
    if "gemma" in model_path and "it" in model_path:
        return get_chat_template("gemma-it")


Lianmin Zheng's avatar
Lianmin Zheng committed
242
243
244
245
246
247
248
249
250
251
252
253
if __name__ == "__main__":
    messages = [
        {"role": "system", "content": None},  # None means default
        # {"role": "system", "content": "You are a helpful, respectful and honest assistant."},
        {"role": "user", "content": "Hello!"},
        {"role": "assistant", "content": "Hi!"},
        {"role": "user", "content": "What can you do?"},
        {"role": "assistant", "content": "I can chat with you."},
    ]

    template = get_chat_template("llama-2-chat")
    print(template.get_prompt(messages))