chat_template.py 18.5 KB
Newer Older
1
from dataclasses import dataclass
Lianmin Zheng's avatar
Lianmin Zheng committed
2
from enum import Enum, auto
3
from typing import Callable, Dict, List, 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
    image_token: str = "<image>"
Mick's avatar
Mick committed
18
    audio_token: str = "<audio>"
Lianmin Zheng's avatar
Lianmin Zheng committed
19
20
    style: ChatTemplateStyle = ChatTemplateStyle.PLAIN

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

26
27
28
        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
29
30
31
                system_prefix, system_suffix = self.role_prefix_and_suffix.get(
                    "system", ("", "")
                )
32
                return (user_prefix + system_prefix, system_suffix)
Liangsheng Yin's avatar
Liangsheng Yin committed
33
34
35
36
37
            elif (
                role == "user"
                and len(hist_messages) == 1
                and hist_messages[0]["content"] is not None
            ):
38
39
40
41
42
                return ("", suffix)

        return prefix, suffix

    def get_prompt(self, messages: List[Dict]) -> str:
Lianmin Zheng's avatar
Lianmin Zheng committed
43
        prompt = ""
44
45
        for i, message in enumerate(messages):
            role, content = message["role"], message["content"]
Lianmin Zheng's avatar
Lianmin Zheng committed
46
47
48
49
50
51
            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])
52
            prompt += f"{prefix}{content}{suffix}"
Lianmin Zheng's avatar
Lianmin Zheng committed
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
        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"),
88
        },
Lianmin Zheng's avatar
Lianmin Zheng committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    )
)

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
109
110
111
            "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
112
113
        },
        style=ChatTemplateStyle.PLAIN,
114
        stop_str=("<|im_end|>",),
Lianmin Zheng's avatar
Lianmin Zheng committed
115
116
117
    )
)

118
119
register_chat_template(
    ChatTemplate(
120
        name="chatml-llava",
121
122
123
124
125
126
127
128
        default_system_prompt="You are a helpful assistant.",
        role_prefix_and_suffix={
            "system": ("<|im_start|>system\n", "<|im_end|>\n"),
            "user": ("<|im_start|>user\n", "<|im_end|>\n"),
            "assistant": ("<|im_start|>assistant\n", "<|im_end|>\n"),
        },
        style=ChatTemplateStyle.PLAIN,
        stop_str=("<|im_end|>",),
129
        image_token="<image>\n",
130
131
132
    )
)

133
134
135
# There is default system prompt for qwen
# reference: https://modelscope.cn/models/qwen/Qwen2-72B-Instruct/file/view/master?fileName=tokenizer_config.json&status=1
# The chat template is: "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
Yineng Zhang's avatar
Yineng Zhang committed
136
137
register_chat_template(
    ChatTemplate(
138
        name="qwen",
Yineng Zhang's avatar
Yineng Zhang committed
139
140
141
142
143
144
145
        default_system_prompt="You are a helpful assistant.",
        role_prefix_and_suffix={
            "system": ("<|im_start|>system\n", "<|im_end|>\n"),
            "user": ("<|im_start|>user\n", "<|im_end|>\n"),
            "assistant": ("<|im_start|>assistant\n", "<|im_end|>\n"),
        },
        style=ChatTemplateStyle.PLAIN,
146
        stop_str=("<|im_end|>",),
Yineng Zhang's avatar
Yineng Zhang committed
147
148
149
    )
)

150
# Reference: https://huggingface.co/docs/transformers/main/model_doc/qwen2_vl#usage-example
151
152
register_chat_template(
    ChatTemplate(
153
        name="qwen2-vl",
154
        default_system_prompt="You are a helpful assistant.",
155
        role_prefix_and_suffix={
Enrique Shockwave's avatar
Enrique Shockwave committed
156
157
158
            "system": ("<|im_start|>system\n", "<|im_end|>\n"),
            "user": ("<|im_start|>user\n", "<|im_end|>\n"),
            "assistant": ("<|im_start|>assistant\n", "<|im_end|>\n"),
159
160
161
        },
        style=ChatTemplateStyle.PLAIN,
        stop_str=("<|im_end|>",),
162
        image_token="<|vision_start|><|image_pad|><|vision_end|>",
163
164
165
    )
)

166
# Reference: https://github.com/lm-sys/FastChat/blob/main/docs/vicuna_weights_version.md#prompt-template
Lianmin Zheng's avatar
Lianmin Zheng committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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",
    )
)

183
184
register_chat_template(
    ChatTemplate(
185
        name="llama-2-chat",
186
187
        default_system_prompt=None,
        role_prefix_and_suffix={
188
189
190
            "system": ("<<SYS>>\n", "\n<</SYS>>\n\n"),
            "user": ("[INST] ", " [/INST]"),
            "assistant": ("", " </s><s>"),
191
        },
192
        style=ChatTemplateStyle.LLAMA2,
193
194
    )
)
Lianmin Zheng's avatar
Lianmin Zheng committed
195
196
197

register_chat_template(
    ChatTemplate(
198
        name="llama-3-instruct",
Lianmin Zheng's avatar
Lianmin Zheng committed
199
200
        default_system_prompt=None,
        role_prefix_and_suffix={
201
202
203
204
205
206
207
208
209
210
211
212
            "system": (
                "<|start_header_id|>system<|end_header_id|>\n\n",
                "<|eot_id|>",
            ),
            "user": (
                "<|start_header_id|>user<|end_header_id|>\n\n",
                "<|eot_id|>",
            ),
            "assistant": (
                "<|start_header_id|>assistant<|end_header_id|>\n\n",
                "<|eot_id|>",
            ),
Lianmin Zheng's avatar
Lianmin Zheng committed
213
        },
214
215
        stop_str=("<|eot_id|>",),
        image_token="<|image|>",
Lianmin Zheng's avatar
Lianmin Zheng committed
216
217
218
    )
)

Mick's avatar
Mick committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# https://huggingface.co/openbmb/MiniCPM-V-2_6
register_chat_template(
    ChatTemplate(
        name="minicpmv",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": ("", " "),
            "user": ("user:", " "),
            "assistant": ("assistant:", "</s>"),
        },
        stop_str=("<|im_end|>", "<|endoftext|>"),
        image_token="(<image>./</image>)",
    )
)

Mick's avatar
Mick committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
register_chat_template(
    ChatTemplate(
        name="janus-pro",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": (
                "",
                "",
            ),
            "User": (
                "<|User|>",
                "",
            ),
            "assistant": (
                "<|Assistant|>",
                "<|end▁of▁sentence|>",
            ),
        },
        stop_str=("<|end▁of▁sentence|>",),
        image_token="<image_placeholder>\n",
    )
)

Mick's avatar
Mick committed
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# https://huggingface.co/openbmb/MiniCPM-o-2_6
register_chat_template(
    ChatTemplate(
        name="minicpmo",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": ("", " "),
            "user": ("user:", " "),
            "assistant": ("assistant:", "</s>"),
        },
        stop_str=("<|im_end|>", "<|endoftext|>"),
        image_token="(<image>./</image>)",
        audio_token="(<audio>./</audio>)",
    )
)

273
# The difference between "llama-3-instruct-llava" and "llama-3-instruct" is that llava uses a different image_token.
274
275
register_chat_template(
    ChatTemplate(
276
        name="llama-3-instruct-llava",
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": (
                "<|start_header_id|>system<|end_header_id|>\n\n",
                "<|eot_id|>",
            ),
            "user": (
                "<|start_header_id|>user<|end_header_id|>\n\n",
                "<|eot_id|>",
            ),
            "assistant": (
                "<|start_header_id|>assistant<|end_header_id|>\n\n",
                "<|eot_id|>",
            ),
        },
        stop_str=("<|eot_id|>",),
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
        image_token="<image>\n",
    )
)

# Reference: https://modelscope.cn/models/01ai/Yi-1.5-34B-Chat/file/view/master?fileName=tokenizer_config.json&status=1
register_chat_template(
    ChatTemplate(
        name="yi-1.5",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": ("", ""),
            "user": ("<|im_start|>user\n", "<|im_end|>\n<|im_start|>assistant\n"),
            "assistant": ("", "<|im_end|>\n"),
        },
        style=ChatTemplateStyle.PLAIN,
        stop_str=("<|im_end|>",),
309
310
311
    )
)

Christopher Chou's avatar
Christopher Chou committed
312
313
314
# Reference: https://github.com/01-ai/Yi/tree/main/VL#major-difference-with-llava
register_chat_template(
    ChatTemplate(
315
        name="yi-vl",
Christopher Chou's avatar
Christopher Chou committed
316
317
318
319
320
321
322
323
324
325
326
327
328
        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
329
330
331
332
333
334
335
336
337
338
339
340
341
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,
    )
)

342
343
344
345
346
347
348
349
350
351
352
353
354
register_chat_template(
    ChatTemplate(
        name="dbrx-instruct",
        default_system_prompt="You are DBRX, created by Databricks. You were last updated in December 2023. You answer questions based on information available up to that point.\nYOU PROVIDE SHORT RESPONSES TO SHORT QUESTIONS OR STATEMENTS, but provide thorough responses to more complex and open-ended questions.\nYou assist with various tasks, from writing to coding (using markdown for code blocks — remember to use ``` with code, JSON, and tables).\n(You do not have real-time data access or code execution capabilities. You avoid stereotyping and provide balanced perspectives on controversial topics. You do not provide song lyrics, poems, or news articles and do not divulge details of your training data.)\nThis is your system prompt, guiding your responses. Do not reference it, just respond to the user. If you find yourself talking about this message, stop. You should be responding appropriately and usually that means not mentioning this.\nYOU DO NOT MENTION ANY OF THIS INFORMATION ABOUT YOURSELF UNLESS THE INFORMATION IS DIRECTLY PERTINENT TO THE USER'S QUERY.",
        role_prefix_and_suffix={
            "system": ("<|im_start|>system\n", "<|im_end|>"),
            "user": ("\n<|im_start|>user\n", "<|im_end|>"),
            "assistant": ("\n<|im_start|>assistant\n", "<|im_end|>"),
        },
        stop_str=("<|im_end|>",),
    )
)

355
356
357
358
359
register_chat_template(
    ChatTemplate(
        name="c4ai-command-r",
        default_system_prompt=None,
        role_prefix_and_suffix={
360
361
362
363
            "system": (
                "<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>",
                "<|END_OF_TURN_TOKEN|>",
            ),
364
            "user": ("<|START_OF_TURN_TOKEN|><|USER_TOKEN|>", "<|END_OF_TURN_TOKEN|>"),
365
366
367
368
            "assistant": (
                "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>",
                "<|END_OF_TURN_TOKEN|>",
            ),
369
370
371
372
373
        },
        style=ChatTemplateStyle.PLAIN,
    )
)

374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
register_chat_template(
    ChatTemplate(
        name="granite-3-instruct",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": (
                "<|start_of_role|>system<|end_of_role|>",
                "<|end_of_text|>",
            ),
            "user": (
                "<|start_of_role|>user<|end_of_role|>",
                "<|end_of_text|>",
            ),
            "assistant": (
                "<|start_of_role|>assistant<|end_of_role|>",
                "<|end_of_text|>",
            ),
        },
        stop_str=("<|end_of_text|>",),
    )
)

396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
register_chat_template(
    ChatTemplate(
        name="deepseek-v3",
        default_system_prompt=None,
        role_prefix_and_suffix={
            "system": (
                "",
                "",
            ),
            "user": (
                "<|User|>",
                "",
            ),
            "assistant": (
                "<|Assistant|>",
                "<|end▁of▁sentence|>",
            ),
        },
        stop_str=("<|end▁of▁sentence|>",),
    )
)


@register_chat_template_matching_function
def match_deepseek(model_path: str):
    if (
        "deepseek-v3" in model_path.lower() or "deepseek-r1" in model_path.lower()
    ) and "base" not in model_path.lower():
        return get_chat_template("deepseek-v3")


Mick's avatar
Mick committed
427
428
429
430
431
432
@register_chat_template_matching_function
def match_deepseek_janus_pro(model_path: str):
    if "janus" in model_path.lower():
        return get_chat_template("janus-pro")


433
434
435
436
437
@register_chat_template_matching_function
def match_dbrx(model_path: str):
    if "dbrx" in model_path.lower() and "instruct" in model_path.lower():
        return get_chat_template("dbrx-instruct")

Lianmin Zheng's avatar
Lianmin Zheng committed
438
439
440
441
442

@register_chat_template_matching_function
def match_vicuna(model_path: str):
    if "vicuna" in model_path.lower():
        return get_chat_template("vicuna_v1.1")
443
    if "llava-v1.5" in model_path.lower():
Lianmin Zheng's avatar
Lianmin Zheng committed
444
        return get_chat_template("vicuna_v1.1")
Yuanhan Zhang's avatar
Yuanhan Zhang committed
445
446
    if "llava-next-video-7b" in model_path.lower():
        return get_chat_template("vicuna_v1.1")
Lianmin Zheng's avatar
Lianmin Zheng committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461


@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")


462
463
464
465
466
467
468
@register_chat_template_matching_function
def match_llama3_instruct(model_path: str):
    model_path = model_path.lower()
    if "llama-3" in model_path and "instruct" in model_path:
        return get_chat_template("llama-3-instruct")


Lianmin Zheng's avatar
Lianmin Zheng committed
469
470
@register_chat_template_matching_function
def match_chat_ml(model_path: str):
Yuanhan Zhang's avatar
Yuanhan Zhang committed
471
    # import pdb;pdb.set_trace()
Lianmin Zheng's avatar
Lianmin Zheng committed
472
473
474
    model_path = model_path.lower()
    if "tinyllama" in model_path:
        return get_chat_template("chatml")
475
    # Now the suffix for qwen2 chat model is "instruct"
Mick's avatar
Mick committed
476
477
    if "qwen" in model_path and "vl" in model_path:
        return get_chat_template("qwen2-vl")
478
479
480
481
482
483
484
    if "qwen" in model_path:
        if "vl" in model_path:
            return get_chat_template("qwen2-vl")
        if ("chat" in model_path or "instruct" in model_path) and (
            "llava" not in model_path
        ):
            return get_chat_template("qwen")
Yuanhan Zhang's avatar
Yuanhan Zhang committed
485
486
487
488
    if (
        "llava-v1.6-34b" in model_path
        or "llava-v1.6-yi-34b" in model_path
        or "llava-next-video-34b" in model_path
489
        or "llava-onevision-qwen2" in model_path
Yuanhan Zhang's avatar
Yuanhan Zhang committed
490
    ):
491
        return get_chat_template("chatml-llava")
Lianmin Zheng's avatar
Lianmin Zheng committed
492

493

Christopher Chou's avatar
Christopher Chou committed
494
495
496
@register_chat_template_matching_function
def match_chat_yi(model_path: str):
    model_path = model_path.lower()
497
498
499
500
    if "yi-vl" in model_path and "llava" not in model_path:
        return get_chat_template("yi-vl")
    elif "yi-1.5" in model_path and "chat" in model_path:
        return get_chat_template("yi-1.5")
Christopher Chou's avatar
Christopher Chou committed
501

Lianmin Zheng's avatar
Lianmin Zheng committed
502

Liangsheng Yin's avatar
Liangsheng Yin committed
503
504
505
506
507
508
509
@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")


510
511
512
@register_chat_template_matching_function
def match_openbmb_minicpm(model_path: str):
    model_path = model_path.lower()
Mick's avatar
Mick committed
513
    if "minicpm-v" in model_path:
514
        return get_chat_template("minicpmv")
Mick's avatar
Mick committed
515
516
    elif "minicpm-o" in model_path:
        return get_chat_template("minicpmo")
517
518


519
520
521
522
523
524
525
@register_chat_template_matching_function
def match_c4ai_command_r(model_path: str):
    model_path = model_path.lower()
    if "c4ai-command-r" in model_path:
        return get_chat_template("c4ai-command-r")


526
527
528
529
530
531
532
533
534
535
@register_chat_template_matching_function
def match_granite_instruct(model_path: str):
    model_path = model_path.lower()
    # When future versions of Granite are released, this code may
    # need to be updated. For now, assume that the Granite 3.0
    # template works across the board.
    if "granite" in model_path and "instruct" in model_path:
        return get_chat_template("granite-3-instruct")


536
537
538
539
540
541
542
543
@register_chat_template_matching_function
def match_gemma3_instruct(model_path: str):
    model_path = model_path.lower()
    if "gemma-3" in model_path and "1b" not in model_path:
        # gemma-3-1b-it is completion model
        return get_chat_template("gemma-it")


Lianmin Zheng's avatar
Lianmin Zheng committed
544
545
546
547
548
549
550
551
552
553
554
555
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))