template.py 94.1 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

chenych's avatar
chenych committed
15
import re
chenych's avatar
chenych committed
16
from copy import deepcopy
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
17
from dataclasses import dataclass
chenych's avatar
chenych committed
18
from typing import TYPE_CHECKING, Optional, Union
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
19

luopl's avatar
luopl committed
20
21
from typing_extensions import override

luopl's avatar
luopl committed
22
from ..extras import logging
chenych's avatar
chenych committed
23
from .data_utils import Role
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
24
from .formatter import EmptyFormatter, FunctionFormatter, StringFormatter, ToolFormatter
luopl's avatar
luopl committed
25
from .mm_plugin import get_mm_plugin
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
26
27
28
29
30


if TYPE_CHECKING:
    from transformers import PreTrainedTokenizer

luopl's avatar
luopl committed
31
    from ..hparams import DataArguments
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
32
    from .formatter import SLOTS, Formatter
luopl's avatar
luopl committed
33
    from .mm_plugin import BasePlugin
luopl's avatar
luopl committed
34
    from .tool_utils import FunctionCall
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
35
36


luopl's avatar
luopl committed
37
logger = logging.get_logger(__name__)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
38
39
40
41
42
43
44
45
46
47


@dataclass
class Template:
    format_user: "Formatter"
    format_assistant: "Formatter"
    format_system: "Formatter"
    format_function: "Formatter"
    format_observation: "Formatter"
    format_tools: "Formatter"
chenych's avatar
chenych committed
48
    format_prefix: "Formatter"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
49
    default_system: str
chenych's avatar
chenych committed
50
51
    stop_words: list[str]
    thought_words: tuple[str, str]
shihm's avatar
uodata  
shihm committed
52
    tool_call_words: tuple[str, str]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
53
54
    efficient_eos: bool
    replace_eos: bool
luopl's avatar
luopl committed
55
    replace_jinja_template: bool
chenych's avatar
chenych committed
56
    enable_thinking: Optional[bool]
luopl's avatar
luopl committed
57
    mm_plugin: "BasePlugin"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
58
59
60
61

    def encode_oneturn(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
62
        messages: list[dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
63
64
        system: Optional[str] = None,
        tools: Optional[str] = None,
chenych's avatar
chenych committed
65
66
    ) -> tuple[list[int], list[int]]:
        r"""Return a single pair of token ids representing prompt and response respectively."""
chenych's avatar
chenych committed
67
        encoded_messages = self._encode(tokenizer, messages, system, tools)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
68
        prompt_ids = []
chenych's avatar
chenych committed
69
70
71
        for encoded_ids in encoded_messages[:-1]:
            prompt_ids += encoded_ids

chenych's avatar
chenych committed
72
73
        response_ids = encoded_messages[-1]
        return prompt_ids, response_ids
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
74
75
76
77

    def encode_multiturn(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
78
        messages: list[dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
79
80
        system: Optional[str] = None,
        tools: Optional[str] = None,
chenych's avatar
chenych committed
81
82
    ) -> list[tuple[list[int], list[int]]]:
        r"""Return multiple pairs of token ids representing prompts and responses respectively."""
chenych's avatar
chenych committed
83
        encoded_messages = self._encode(tokenizer, messages, system, tools)
chenych's avatar
chenych committed
84
85
        return [(encoded_messages[i], encoded_messages[i + 1]) for i in range(0, len(encoded_messages), 2)]

chenych's avatar
chenych committed
86
87
    def extract_tool(self, content: str) -> Union[str, list["FunctionCall"]]:
        r"""Extract tool message."""
chenych's avatar
chenych committed
88
        return self.format_tools.extract(content)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
89

chenych's avatar
chenych committed
90
91
    def get_stop_token_ids(self, tokenizer: "PreTrainedTokenizer") -> list[int]:
        r"""Return stop token ids."""
luopl's avatar
luopl committed
92
93
94
95
96
97
        stop_token_ids = {tokenizer.eos_token_id}
        for token in self.stop_words:
            stop_token_ids.add(tokenizer.convert_tokens_to_ids(token))

        return list(stop_token_ids)

chenych's avatar
chenych committed
98
99
    def add_thought(self, content: str = "") -> str:
        r"""Add empty thought to assistant message."""
shihm's avatar
uodata  
shihm committed
100
        return f"{self.thought_words[0]}{self.thought_words[1]}" + content
chenych's avatar
chenych committed
101
102
103
104
105
106
107
108
109
110

    def remove_thought(self, content: str) -> str:
        r"""Remove thought from assistant message."""
        pattern = re.compile(f"{re.escape(self.thought_words[0])}(.*?){re.escape(self.thought_words[1])}", re.DOTALL)
        return re.sub(pattern, "", content).lstrip("\n")

    def get_thought_word_ids(self, tokenizer: "PreTrainedTokenizer") -> list[int]:
        r"""Get the token ids of thought words."""
        return tokenizer.encode(self.add_thought(), add_special_tokens=False)

chenych's avatar
chenych committed
111
112
    def _convert_elements_to_ids(self, tokenizer: "PreTrainedTokenizer", elements: "SLOTS") -> list[int]:
        r"""Convert elements to token ids."""
chenych's avatar
chenych committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
        token_ids = []
        for elem in elements:
            if isinstance(elem, str):
                if len(elem) != 0:
                    token_ids += tokenizer.encode(elem, add_special_tokens=False)
            elif isinstance(elem, dict):
                token_ids += [tokenizer.convert_tokens_to_ids(elem.get("token"))]
            elif isinstance(elem, set):
                if "bos_token" in elem and tokenizer.bos_token_id is not None:
                    token_ids += [tokenizer.bos_token_id]
                elif "eos_token" in elem and tokenizer.eos_token_id is not None:
                    token_ids += [tokenizer.eos_token_id]
            else:
                raise ValueError(f"Input must be string, set[str] or dict[str, str], got {type(elem)}")

        return token_ids

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
130
131
132
    def _encode(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
133
        messages: list[dict[str, str]],
chenych's avatar
chenych committed
134
135
        system: Optional[str],
        tools: Optional[str],
chenych's avatar
chenych committed
136
137
138
    ) -> list[list[int]]:
        r"""Encode formatted inputs to pairs of token ids.

chenych's avatar
chenych committed
139
        Turn 0: prefix + system + query        resp
chenych's avatar
chenych committed
140
        Turn t: query                          resp.
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
141
142
143
144
145
        """
        system = system or self.default_system
        encoded_messages = []
        for i, message in enumerate(messages):
            elements = []
chenych's avatar
chenych committed
146
147
148
149
150
151
152

            if i == 0:
                elements += self.format_prefix.apply()
                if system or tools:
                    tool_text = self.format_tools.apply(content=tools)[0] if tools else ""
                    elements += self.format_system.apply(content=(system + tool_text))

chenych's avatar
chenych committed
153
            if message["role"] == Role.USER:
chenych's avatar
chenych committed
154
                elements += self.format_user.apply(content=message["content"], idx=str(i // 2))
chenych's avatar
chenych committed
155
            elif message["role"] == Role.ASSISTANT:
chenych's avatar
chenych committed
156
                elements += self.format_assistant.apply(content=message["content"])
chenych's avatar
chenych committed
157
            elif message["role"] == Role.OBSERVATION:
chenych's avatar
chenych committed
158
                elements += self.format_observation.apply(content=message["content"])
chenych's avatar
chenych committed
159
            elif message["role"] == Role.FUNCTION:
shihm's avatar
uodata  
shihm committed
160
161
162
                elements += self.format_function.apply(
                    content=message["content"], thought_words=self.thought_words, tool_call_words=self.tool_call_words
                )
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
163
164
165
166
167
            else:
                raise NotImplementedError("Unexpected role: {}".format(message["role"]))

            encoded_messages.append(self._convert_elements_to_ids(tokenizer, elements))

chenych's avatar
chenych committed
168
        return encoded_messages
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
169

chenych's avatar
chenych committed
170
171
    @staticmethod
    def _add_or_replace_eos_token(tokenizer: "PreTrainedTokenizer", eos_token: str) -> None:
chenych's avatar
chenych committed
172
        r"""Add or replace eos token to the tokenizer."""
chenych's avatar
chenych committed
173
174
175
        if tokenizer.eos_token == eos_token:
            return

chenych's avatar
chenych committed
176
177
        is_added = tokenizer.eos_token_id is None
        num_added_tokens = tokenizer.add_special_tokens({"eos_token": eos_token})
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
178

chenych's avatar
chenych committed
179
180
181
182
183
184
185
186
187
        if is_added:
            logger.info_rank0(f"Add eos token: {tokenizer.eos_token}.")
        else:
            logger.info_rank0(f"Replace eos token: {tokenizer.eos_token}.")

        if num_added_tokens > 0:
            logger.warning_rank0("New tokens have been added, make sure `resize_vocab` is True.")

    def fix_special_tokens(self, tokenizer: "PreTrainedTokenizer") -> None:
chenych's avatar
chenych committed
188
        r"""Add eos token and pad token to the tokenizer."""
chenych's avatar
chenych committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        stop_words = self.stop_words
        if self.replace_eos:
            if not stop_words:
                raise ValueError("Stop words are required to replace the EOS token.")

            self._add_or_replace_eos_token(tokenizer, eos_token=stop_words[0])
            stop_words = stop_words[1:]

        if tokenizer.eos_token_id is None:
            self._add_or_replace_eos_token(tokenizer, eos_token="<|endoftext|>")

        if tokenizer.pad_token_id is None:
            tokenizer.pad_token = tokenizer.eos_token
            logger.info_rank0(f"Add pad token: {tokenizer.pad_token}")

        if stop_words:
shihm's avatar
uodata  
shihm committed
205
206
207
208
209
210
            try:
                num_added_tokens = tokenizer.add_special_tokens(
                    dict(additional_special_tokens=stop_words), replace_additional_special_tokens=False
                )
            except TypeError:
                num_added_tokens = tokenizer.add_special_tokens(dict(additional_special_tokens=stop_words))
chenych's avatar
chenych committed
211
212
213
214
215
216
            logger.info_rank0("Add {} to stop words.".format(",".join(stop_words)))
            if num_added_tokens > 0:
                logger.warning_rank0("New tokens have been added, make sure `resize_vocab` is True.")

    @staticmethod
    def _jinja_escape(content: str) -> str:
chenych's avatar
chenych committed
217
        r"""Escape single quotes in content."""
chenych's avatar
chenych committed
218
219
220
221
        return content.replace("'", r"\'")

    @staticmethod
    def _convert_slots_to_jinja(slots: "SLOTS", tokenizer: "PreTrainedTokenizer", placeholder: str = "content") -> str:
chenych's avatar
chenych committed
222
        r"""Convert slots to jinja template."""
chenych's avatar
chenych committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        slot_items = []
        for slot in slots:
            if isinstance(slot, str):
                slot_pieces = slot.split("{{content}}")
                if slot_pieces[0]:
                    slot_items.append("'" + Template._jinja_escape(slot_pieces[0]) + "'")
                if len(slot_pieces) > 1:
                    slot_items.append(placeholder)
                    if slot_pieces[1]:
                        slot_items.append("'" + Template._jinja_escape(slot_pieces[1]) + "'")
            elif isinstance(slot, set):  # do not use {{ eos_token }} since it may be replaced
                if "bos_token" in slot and tokenizer.bos_token_id is not None:
                    slot_items.append("'" + tokenizer.bos_token + "'")
                elif "eos_token" in slot and tokenizer.eos_token_id is not None:
                    slot_items.append("'" + tokenizer.eos_token + "'")
            elif isinstance(slot, dict):
                raise ValueError("Dict is not supported.")

        return " + ".join(slot_items)

    def _get_jinja_template(self, tokenizer: "PreTrainedTokenizer") -> str:
chenych's avatar
chenych committed
244
        r"""Return the jinja template."""
chenych's avatar
chenych committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
        prefix = self._convert_slots_to_jinja(self.format_prefix.apply(), tokenizer)
        system = self._convert_slots_to_jinja(self.format_system.apply(), tokenizer, placeholder="system_message")
        user = self._convert_slots_to_jinja(self.format_user.apply(), tokenizer)
        assistant = self._convert_slots_to_jinja(self.format_assistant.apply(), tokenizer)
        jinja_template = ""
        if prefix:
            jinja_template += "{{ " + prefix + " }}"

        if self.default_system:
            jinja_template += "{% set system_message = '" + self._jinja_escape(self.default_system) + "' %}"

        jinja_template += (
            "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}"
            "{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}"
            "{% if system_message is defined %}{{ " + system + " }}{% endif %}"
            "{% for message in loop_messages %}"
            "{% set content = message['content'] %}"
            "{% if message['role'] == 'user' %}"
            "{{ " + user + " }}"
            "{% elif message['role'] == 'assistant' %}"
            "{{ " + assistant + " }}"
            "{% endif %}"
            "{% endfor %}"
        )
        return jinja_template

    def fix_jinja_template(self, tokenizer: "PreTrainedTokenizer") -> None:
chenych's avatar
chenych committed
272
        r"""Replace the jinja template in the tokenizer."""
chenych's avatar
chenych committed
273
274
275
276
277
278
279
280
281
282
        if tokenizer.chat_template is None or self.replace_jinja_template:
            try:
                tokenizer.chat_template = self._get_jinja_template(tokenizer)
            except ValueError as e:
                logger.info_rank0(f"Cannot add this chat template to tokenizer: {e}.")

    @staticmethod
    def _convert_slots_to_ollama(
        slots: "SLOTS", tokenizer: "PreTrainedTokenizer", placeholder: str = "content"
    ) -> str:
chenych's avatar
chenych committed
283
        r"""Convert slots to ollama template."""
chenych's avatar
chenych committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
        slot_items = []
        for slot in slots:
            if isinstance(slot, str):
                slot_pieces = slot.split("{{content}}")
                if slot_pieces[0]:
                    slot_items.append(slot_pieces[0])
                if len(slot_pieces) > 1:
                    slot_items.append("{{ " + placeholder + " }}")
                    if slot_pieces[1]:
                        slot_items.append(slot_pieces[1])
            elif isinstance(slot, set):  # do not use {{ eos_token }} since it may be replaced
                if "bos_token" in slot and tokenizer.bos_token_id is not None:
                    slot_items.append(tokenizer.bos_token)
                elif "eos_token" in slot and tokenizer.eos_token_id is not None:
                    slot_items.append(tokenizer.eos_token)
            elif isinstance(slot, dict):
                raise ValueError("Dict is not supported.")

        return "".join(slot_items)

    def _get_ollama_template(self, tokenizer: "PreTrainedTokenizer") -> str:
chenych's avatar
chenych committed
305
        r"""Return the ollama template."""
chenych's avatar
chenych committed
306
307
308
309
310
311
312
313
314
315
316
        prefix = self._convert_slots_to_ollama(self.format_prefix.apply(), tokenizer)
        system = self._convert_slots_to_ollama(self.format_system.apply(), tokenizer, placeholder=".System")
        user = self._convert_slots_to_ollama(self.format_user.apply(), tokenizer, placeholder=".Content")
        assistant = self._convert_slots_to_ollama(self.format_assistant.apply(), tokenizer, placeholder=".Content")
        return (
            f"{prefix}{{{{ if .System }}}}{system}{{{{ end }}}}"
            f"""{{{{ range .Messages }}}}{{{{ if eq .Role "user" }}}}{user}"""
            f"""{{{{ else if eq .Role "assistant" }}}}{assistant}{{{{ end }}}}{{{{ end }}}}"""
        )

    def get_ollama_modelfile(self, tokenizer: "PreTrainedTokenizer") -> str:
chenych's avatar
chenych committed
317
        r"""Return the ollama modelfile.
chenych's avatar
chenych committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331

        TODO: support function calling.
        """
        modelfile = "# ollama modelfile auto-generated by llamafactory\n\n"
        modelfile += f'FROM .\n\nTEMPLATE """{self._get_ollama_template(tokenizer)}"""\n\n'

        if self.default_system:
            modelfile += f'SYSTEM """{self.default_system}"""\n\n'

        for stop_token_id in self.get_stop_token_ids(tokenizer):
            modelfile += f'PARAMETER stop "{tokenizer.convert_ids_to_tokens(stop_token_id)}"\n'

        modelfile += "PARAMETER num_ctx 4096\n"
        return modelfile
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
332
333
334
335


@dataclass
class Llama2Template(Template):
chenych's avatar
chenych committed
336
337
    r"""A template that fuse the system message to first user message."""

luopl's avatar
luopl committed
338
    @override
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
339
340
341
    def _encode(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
342
        messages: list[dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
343
344
        system: str,
        tools: str,
chenych's avatar
chenych committed
345
    ) -> list[list[int]]:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
346
347
348
349
        system = system or self.default_system
        encoded_messages = []
        for i, message in enumerate(messages):
            elements = []
chenych's avatar
chenych committed
350

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
351
            system_text = ""
chenych's avatar
chenych committed
352
353
354
355
356
357
            if i == 0:
                elements += self.format_prefix.apply()
                if system or tools:
                    tool_text = self.format_tools.apply(content=tools)[0] if tools else ""
                    system_text = self.format_system.apply(content=(system + tool_text))[0]

chenych's avatar
chenych committed
358
            if message["role"] == Role.USER:
chenych's avatar
chenych committed
359
                elements += self.format_user.apply(content=system_text + message["content"])
chenych's avatar
chenych committed
360
            elif message["role"] == Role.ASSISTANT:
chenych's avatar
chenych committed
361
                elements += self.format_assistant.apply(content=message["content"])
chenych's avatar
chenych committed
362
            elif message["role"] == Role.OBSERVATION:
chenych's avatar
chenych committed
363
                elements += self.format_observation.apply(content=message["content"])
chenych's avatar
chenych committed
364
            elif message["role"] == Role.FUNCTION:
chenych's avatar
chenych committed
365
                elements += self.format_function.apply(content=message["content"])
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
366
367
368
369
370
            else:
                raise NotImplementedError("Unexpected role: {}".format(message["role"]))

            encoded_messages.append(self._convert_elements_to_ids(tokenizer, elements))

chenych's avatar
chenych committed
371
        return encoded_messages
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
372

chenych's avatar
chenych committed
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
    def _get_jinja_template(self, tokenizer: "PreTrainedTokenizer") -> str:
        prefix = self._convert_slots_to_jinja(self.format_prefix.apply(), tokenizer)
        system_message = self._convert_slots_to_jinja(
            self.format_system.apply(), tokenizer, placeholder="system_message"
        )
        user_message = self._convert_slots_to_jinja(self.format_user.apply(), tokenizer)
        assistant_message = self._convert_slots_to_jinja(self.format_assistant.apply(), tokenizer)
        jinja_template = ""
        if prefix:
            jinja_template += "{{ " + prefix + " }}"

        if self.default_system:
            jinja_template += "{% set system_message = '" + self._jinja_escape(self.default_system) + "' %}"

        jinja_template += (
            "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}"
            "{% set system_message = messages[0]['content'] %}{% else %}{% set loop_messages = messages %}{% endif %}"
            "{% for message in loop_messages %}"
            "{% if loop.index0 == 0 and system_message is defined %}"
            "{% set content = " + system_message + " + message['content'] %}"
            "{% else %}{% set content = message['content'] %}{% endif %}"
            "{% if message['role'] == 'user' %}"
            "{{ " + user_message + " }}"
            "{% elif message['role'] == 'assistant' %}"
            "{{ " + assistant_message + " }}"
            "{% endif %}"
            "{% endfor %}"
        )
        return jinja_template

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
403

chenych's avatar
chenych committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
@dataclass
class ReasoningTemplate(Template):
    r"""A template that add thought to assistant message."""

    @override
    def encode_oneturn(
        self,
        tokenizer: "PreTrainedTokenizer",
        messages: list[dict[str, str]],
        system: Optional[str] = None,
        tools: Optional[str] = None,
    ) -> tuple[list[int], list[int]]:
        messages = deepcopy(messages)
        for i in range(1, len(messages) - 2, 2):
            messages[i]["content"] = self.remove_thought(messages[i]["content"])

        if self.enable_thinking is False:  # remove all cot
            messages[-1]["content"] = self.remove_thought(messages[-1]["content"])

        prompt_ids, response_ids = super().encode_oneturn(tokenizer, messages, system, tools)
        if (
shihm's avatar
uodata  
shihm committed
425
426
            self.thought_words[0].strip() not in messages[-1]["content"]
            and self.thought_words[1].strip() not in messages[-1]["content"]
chenych's avatar
chenych committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
        ):  # add empty cot
            if not self.enable_thinking:  # do not compute loss
                prompt_ids += self.get_thought_word_ids(tokenizer)
            else:  # do compute loss
                response_ids = self.get_thought_word_ids(tokenizer) + response_ids

        return prompt_ids, response_ids

    @override
    def encode_multiturn(
        self,
        tokenizer: "PreTrainedTokenizer",
        messages: list[dict[str, str]],
        system: Optional[str] = None,
        tools: Optional[str] = None,
    ) -> list[tuple[list[int], list[int]]]:
        messages = deepcopy(messages)
        if self.enable_thinking is False:  # remove all cot
            for i in range(1, len(messages), 2):
                messages[i]["content"] = self.remove_thought(messages[i]["content"])

        encoded_messages = self._encode(tokenizer, messages, system, tools)
        for i in range(0, len(messages), 2):
            if (
shihm's avatar
uodata  
shihm committed
451
452
                self.thought_words[0].strip() not in messages[i + 1]["content"]
                and self.thought_words[1].strip() not in messages[i + 1]["content"]
chenych's avatar
chenych committed
453
454
455
456
457
458
459
460
461
            ):  # add empty cot
                if not self.enable_thinking:  # do not compute loss
                    encoded_messages[i] += self.get_thought_word_ids(tokenizer)
                else:  # do compute loss
                    encoded_messages[i + 1] = self.get_thought_word_ids(tokenizer) + encoded_messages[i + 1]

        return [(encoded_messages[i], encoded_messages[i + 1]) for i in range(0, len(encoded_messages), 2)]


chenych's avatar
chenych committed
462
TEMPLATES: dict[str, "Template"] = {}
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
463
464


chenych's avatar
chenych committed
465
def register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
466
467
468
469
470
471
472
    name: str,
    format_user: Optional["Formatter"] = None,
    format_assistant: Optional["Formatter"] = None,
    format_system: Optional["Formatter"] = None,
    format_function: Optional["Formatter"] = None,
    format_observation: Optional["Formatter"] = None,
    format_tools: Optional["Formatter"] = None,
chenych's avatar
chenych committed
473
    format_prefix: Optional["Formatter"] = None,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
474
    default_system: str = "",
chenych's avatar
chenych committed
475
476
    stop_words: Optional[list[str]] = None,
    thought_words: Optional[tuple[str, str]] = None,
shihm's avatar
uodata  
shihm committed
477
    tool_call_words: Optional[tuple[str, str]] = None,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
478
479
    efficient_eos: bool = False,
    replace_eos: bool = False,
luopl's avatar
luopl committed
480
    replace_jinja_template: bool = False,
chenych's avatar
chenych committed
481
    enable_thinking: Optional[bool] = True,
luopl's avatar
luopl committed
482
    mm_plugin: "BasePlugin" = get_mm_plugin(name="base"),
chenych's avatar
chenych committed
483
    template_class: type["Template"] = Template,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
484
) -> None:
chenych's avatar
chenych committed
485
    r"""Register a chat template.
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
486
487
488

    To add the following chat template:
    ```
luopl's avatar
luopl committed
489
490
491
492
    <s><user>user prompt here
    <model>model response here</s>
    <user>user prompt here
    <model>model response here</s>
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
493
494
495
496
    ```

    The corresponding code should be:
    ```
chenych's avatar
chenych committed
497
    register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
498
        name="custom",
luopl's avatar
luopl committed
499
500
501
        format_user=StringFormatter(slots=["<user>{{content}}\n<model>"]),
        format_assistant=StringFormatter(slots=["{{content}}</s>\n"]),
        format_prefix=EmptyFormatter("<s>"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
502
503
504
    )
    ```
    """
chenych's avatar
chenych committed
505
506
507
    if name in TEMPLATES:
        raise ValueError(f"Template {name} already exists.")

luopl's avatar
luopl committed
508
    default_slots = ["{{content}}"] if efficient_eos else ["{{content}}", {"eos_token"}]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
509
    default_user_formatter = StringFormatter(slots=["{{content}}"])
luopl's avatar
luopl committed
510
    default_assistant_formatter = StringFormatter(slots=default_slots)
chenych's avatar
chenych committed
511
512
513
514
515
    if format_assistant is not None:
        default_function_formatter = FunctionFormatter(slots=format_assistant.slots, tool_format="default")
    else:
        default_function_formatter = FunctionFormatter(slots=default_slots, tool_format="default")

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
516
    default_tool_formatter = ToolFormatter(tool_format="default")
chenych's avatar
chenych committed
517
518
    default_prefix_formatter = EmptyFormatter()
    TEMPLATES[name] = template_class(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
519
520
521
522
523
524
        format_user=format_user or default_user_formatter,
        format_assistant=format_assistant or default_assistant_formatter,
        format_system=format_system or default_user_formatter,
        format_function=format_function or default_function_formatter,
        format_observation=format_observation or format_user or default_user_formatter,
        format_tools=format_tools or default_tool_formatter,
chenych's avatar
chenych committed
525
        format_prefix=format_prefix or default_prefix_formatter,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
526
        default_system=default_system,
luopl's avatar
luopl committed
527
        stop_words=stop_words or [],
shihm's avatar
uodata  
shihm committed
528
529
        thought_words=thought_words or ("<think>\n", "\n</think>\n\n"),
        tool_call_words=tool_call_words or ("<tool_call>", "</tool_call>"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
530
531
        efficient_eos=efficient_eos,
        replace_eos=replace_eos,
luopl's avatar
luopl committed
532
        replace_jinja_template=replace_jinja_template,
chenych's avatar
chenych committed
533
        enable_thinking=enable_thinking,
luopl's avatar
luopl committed
534
        mm_plugin=mm_plugin,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
535
536
537
    )


chenych's avatar
chenych committed
538
def parse_template(tokenizer: "PreTrainedTokenizer") -> "Template":
chenych's avatar
chenych committed
539
    r"""Extract a chat template from the tokenizer."""
chenych's avatar
chenych committed
540

chenych's avatar
chenych committed
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    def find_diff(short_str: str, long_str: str) -> str:
        i, j = 0, 0
        diff = ""
        while i < len(short_str) and j < len(long_str):
            if short_str[i] == long_str[j]:
                i += 1
                j += 1
            else:
                diff += long_str[j]
                j += 1

        return diff

    prefix = tokenizer.decode(tokenizer.encode(""))

    messages = [{"role": "system", "content": "{{content}}"}]
    system_slot = tokenizer.apply_chat_template(messages, add_generation_prompt=False, tokenize=False)[len(prefix) :]

    messages = [{"role": "system", "content": ""}, {"role": "user", "content": "{{content}}"}]
    user_slot_empty_system = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
    user_slot_empty_system = user_slot_empty_system[len(prefix) :]

    messages = [{"role": "user", "content": "{{content}}"}]
    user_slot = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
    user_slot = user_slot[len(prefix) :]

    messages = [{"role": "user", "content": "{{content}}"}, {"role": "assistant", "content": "{{content}}"}]
    assistant_slot = tokenizer.apply_chat_template(messages, add_generation_prompt=False, tokenize=False)
    assistant_slot = assistant_slot[len(prefix) + len(user_slot) :]
chenych's avatar
chenych committed
570
    template_class = ReasoningTemplate if "<think>" in assistant_slot else Template
chenych's avatar
chenych committed
571
    assistant_slot = assistant_slot.replace("<think>", "").replace("</think>", "").lstrip("\n")  # remove thought tags
chenych's avatar
chenych committed
572
573
574
575
576
577
578
579

    if len(user_slot) > len(user_slot_empty_system):
        default_system = find_diff(user_slot_empty_system, user_slot)
        sole_system = system_slot.replace("{{content}}", default_system, 1)
        user_slot = user_slot[len(sole_system) :]
    else:  # if defaut_system is empty, user_slot_empty_system will be longer than user_slot
        default_system = ""

chenych's avatar
chenych committed
580
    return template_class(
chenych's avatar
chenych committed
581
582
583
584
585
586
587
588
589
        format_user=StringFormatter(slots=[user_slot]),
        format_assistant=StringFormatter(slots=[assistant_slot]),
        format_system=StringFormatter(slots=[system_slot]),
        format_function=FunctionFormatter(slots=[assistant_slot], tool_format="default"),
        format_observation=StringFormatter(slots=[user_slot]),
        format_tools=ToolFormatter(tool_format="default"),
        format_prefix=EmptyFormatter(slots=[prefix]) if prefix else EmptyFormatter(),
        default_system=default_system,
        stop_words=[],
shihm's avatar
uodata  
shihm committed
590
591
        thought_words=("<think>\n", "\n</think>\n\n"),
        tool_call_words=("<tool_call>", "</tool_call>"),
chenych's avatar
chenych committed
592
593
594
        efficient_eos=False,
        replace_eos=False,
        replace_jinja_template=False,
chenych's avatar
chenych committed
595
        enable_thinking=True,
chenych's avatar
chenych committed
596
        mm_plugin=get_mm_plugin(name="base"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
597
598
599
    )


luopl's avatar
luopl committed
600
def get_template_and_fix_tokenizer(tokenizer: "PreTrainedTokenizer", data_args: "DataArguments") -> "Template":
chenych's avatar
chenych committed
601
    r"""Get chat template and fixes the tokenizer."""
luopl's avatar
luopl committed
602
    if data_args.template is None:
chenych's avatar
chenych committed
603
604
605
606
607
608
        if isinstance(tokenizer.chat_template, str):
            logger.warning_rank0("`template` was not specified, try parsing the chat template from the tokenizer.")
            template = parse_template(tokenizer)
        else:
            logger.warning_rank0("`template` was not specified, use `empty` template.")
            template = TEMPLATES["empty"]  # placeholder
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
609
    else:
chenych's avatar
chenych committed
610
        if data_args.template not in TEMPLATES:
luopl's avatar
luopl committed
611
612
            raise ValueError(f"Template {data_args.template} does not exist.")

chenych's avatar
chenych committed
613
614
        template = TEMPLATES[data_args.template]

luopl's avatar
luopl committed
615
616
    if data_args.train_on_prompt and template.efficient_eos:
        raise ValueError("Current template does not support `train_on_prompt`.")
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
617

luopl's avatar
luopl committed
618
    if data_args.tool_format is not None:
luopl's avatar
luopl committed
619
        logger.info_rank0(f"Using tool format: {data_args.tool_format}.")
luopl's avatar
luopl committed
620
621
        default_slots = ["{{content}}"] if template.efficient_eos else ["{{content}}", {"eos_token"}]
        template.format_function = FunctionFormatter(slots=default_slots, tool_format=data_args.tool_format)
luopl's avatar
luopl committed
622
        template.format_tools = ToolFormatter(tool_format=data_args.tool_format)
chenych's avatar
chenych committed
623

chenych's avatar
chenych committed
624
625
626
627
    if data_args.default_system is not None:
        logger.info_rank0(f"Using default system message: {data_args.default_system}.")
        template.default_system = data_args.default_system

shihm's avatar
uodata  
shihm committed
628
629
630
631
632
633
634
635
    if isinstance(template, ReasoningTemplate):
        logger.warning_rank0(
            "You are using reasoning template, "
            "please add `_nothink` suffix if the model is not a reasoning model. "
            "e.g., qwen3_vl_nothink"
        )
        template.enable_thinking = data_args.enable_thinking

chenych's avatar
chenych committed
636
637
    template.fix_special_tokens(tokenizer)
    template.fix_jinja_template(tokenizer)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
638
639
640
    return template


chenych's avatar
chenych committed
641
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
642
643
    name="alpaca",
    format_user=StringFormatter(slots=["### Instruction:\n{{content}}\n\n### Response:\n"]),
luopl's avatar
luopl committed
644
    format_assistant=StringFormatter(slots=["{{content}}", {"eos_token"}, "\n\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
645
    default_system=(
luopl's avatar
luopl committed
646
        "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
647
    ),
luopl's avatar
luopl committed
648
    replace_jinja_template=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
649
650
651
)


chenych's avatar
chenych committed
652
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
653
654
    name="aquila",
    format_user=StringFormatter(slots=["Human: {{content}}###Assistant:"]),
luopl's avatar
luopl committed
655
656
    format_assistant=StringFormatter(slots=["{{content}}###"]),
    format_system=StringFormatter(slots=["System: {{content}}###"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
657
658
659
660
661
662
663
664
    default_system=(
        "A chat between a curious human and an artificial intelligence assistant. "
        "The assistant gives helpful, detailed, and polite answers to the human's questions."
    ),
    stop_words=["</s>"],
)


chenych's avatar
chenych committed
665
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
666
667
668
669
670
671
672
673
    name="atom",
    format_user=StringFormatter(
        slots=[{"bos_token"}, "Human: {{content}}\n", {"eos_token"}, {"bos_token"}, "Assistant:"]
    ),
    format_assistant=StringFormatter(slots=["{{content}}\n", {"eos_token"}]),
)


chenych's avatar
chenych committed
674
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
675
676
677
678
679
680
    name="baichuan",
    format_user=StringFormatter(slots=[{"token": "<reserved_102>"}, "{{content}}", {"token": "<reserved_103>"}]),
    efficient_eos=True,
)


chenych's avatar
chenych committed
681
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
682
683
684
685
686
687
    name="baichuan2",
    format_user=StringFormatter(slots=["<reserved_106>{{content}}<reserved_107>"]),
    efficient_eos=True,
)


chenych's avatar
chenych committed
688
689
690
691
692
693
694
695
696
697
register_template(
    name="bailing",
    format_user=StringFormatter(slots=["<role>HUMAN</role>{{content}}<role>ASSISTANT</role>"]),
    format_system=StringFormatter(slots=["<role>SYSTEM</role>{{content}}"]),
    format_observation=StringFormatter(slots=["<role>OBSERVATION</role>{{content}}<role>ASSISTANT</role>"]),
    stop_words=["<|endoftext|>"],
    efficient_eos=True,
)


shihm's avatar
uodata  
shihm committed
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
register_template(
    name="bailing_v2",
    format_user=StringFormatter(slots=["<role>HUMAN</role>{{content}}<|role_end|><role>ASSISTANT</role>"]),
    format_system=StringFormatter(slots=["<role>SYSTEM</role>{{content}}<|role_end|>"]),
    format_assistant=StringFormatter(slots=["{{content}}<|role_end|>"]),
    format_observation=StringFormatter(
        slots=[
            "<role>OBSERVATION</role>\n<tool_response>\n{{content}}\n</tool_response><|role_end|><role>ASSISTANT</role>"
        ]
    ),
    format_function=FunctionFormatter(slots=["{{content}}<|role_end|>"], tool_format="ling"),
    format_tools=ToolFormatter(tool_format="ling"),
    stop_words=["<|endoftext|>"],
    efficient_eos=True,
)


chenych's avatar
chenych committed
715
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
716
717
    name="belle",
    format_user=StringFormatter(slots=["Human: {{content}}\n\nBelle: "]),
luopl's avatar
luopl committed
718
    format_assistant=StringFormatter(slots=["{{content}}", {"eos_token"}, "\n\n"]),
chenych's avatar
chenych committed
719
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
720
721
722
)


chenych's avatar
chenych committed
723
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
724
725
726
727
728
    name="bluelm",
    format_user=StringFormatter(slots=[{"token": "[|Human|]:"}, "{{content}}", {"token": "[|AI|]:"}]),
)


chenych's avatar
chenych committed
729
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
730
731
    name="breeze",
    format_user=StringFormatter(slots=["[INST] {{content}} [/INST] "]),
chenych's avatar
chenych committed
732
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
733
734
735
736
    efficient_eos=True,
)


chenych's avatar
chenych committed
737
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
738
739
    name="chatglm2",
    format_user=StringFormatter(slots=["[Round {{idx}}]\n\n问:{{content}}\n\n答:"]),
chenych's avatar
chenych committed
740
    format_prefix=EmptyFormatter(slots=[{"token": "[gMASK]"}, {"token": "sop"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
741
742
743
744
    efficient_eos=True,
)


chenych's avatar
chenych committed
745
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
746
747
748
    name="chatglm3",
    format_user=StringFormatter(slots=[{"token": "<|user|>"}, "\n", "{{content}}", {"token": "<|assistant|>"}]),
    format_assistant=StringFormatter(slots=["\n", "{{content}}"]),
chenych's avatar
chenych committed
749
    format_system=StringFormatter(slots=[{"token": "<|system|>"}, "\n", "{{content}}"]),
luopl's avatar
luopl committed
750
    format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
751
752
753
    format_observation=StringFormatter(
        slots=[{"token": "<|observation|>"}, "\n", "{{content}}", {"token": "<|assistant|>"}]
    ),
chenych's avatar
chenych committed
754
755
    format_tools=ToolFormatter(tool_format="glm4"),
    format_prefix=EmptyFormatter(slots=[{"token": "[gMASK]"}, {"token": "sop"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
756
757
758
759
760
    stop_words=["<|user|>", "<|observation|>"],
    efficient_eos=True,
)


chenych's avatar
chenych committed
761
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
762
763
    name="chatml",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
764
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
765
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
766
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
767
768
    stop_words=["<|im_end|>", "<|im_start|>"],
    replace_eos=True,
luopl's avatar
luopl committed
769
    replace_jinja_template=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
770
771
772
)


luopl's avatar
luopl committed
773
# copied from chatml template
chenych's avatar
chenych committed
774
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
775
776
    name="chatml_de",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
777
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
778
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
779
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
780
781
782
    default_system="Du bist ein freundlicher und hilfsbereiter KI-Assistent.",
    stop_words=["<|im_end|>", "<|im_start|>"],
    replace_eos=True,
luopl's avatar
luopl committed
783
    replace_jinja_template=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
784
785
786
)


chenych's avatar
chenych committed
787
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
788
    name="codegeex2",
chenych's avatar
chenych committed
789
790
791
792
    format_prefix=EmptyFormatter(slots=[{"token": "[gMASK]"}, {"token": "sop"}]),
)


chenych's avatar
chenych committed
793
register_template(
chenych's avatar
chenych committed
794
795
796
    name="codegeex4",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>\n"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}"]),
luopl's avatar
luopl committed
797
    format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4"),
chenych's avatar
chenych committed
798
799
800
801
802
803
804
805
806
    format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>\n"]),
    format_tools=ToolFormatter(tool_format="glm4"),
    format_prefix=EmptyFormatter(slots=["[gMASK]<sop>"]),
    default_system=(
        "你是一位智能编程助手,你叫CodeGeeX。你会为用户回答关于编程、代码、计算机方面的任何问题,"
        "并提供格式规范、可以执行、准确安全的代码,并在必要时提供详细的解释。"
    ),
    stop_words=["<|user|>", "<|observation|>"],
    efficient_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
807
808
809
)


chenych's avatar
chenych committed
810
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
811
812
813
814
815
816
817
818
819
    name="cohere",
    format_user=StringFormatter(
        slots=[
            (
                "<|START_OF_TURN_TOKEN|><|USER_TOKEN|>{{content}}<|END_OF_TURN_TOKEN|>"
                "<|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>"
            )
        ]
    ),
chenych's avatar
chenych committed
820
821
    format_system=StringFormatter(slots=["<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>{{content}}<|END_OF_TURN_TOKEN|>"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
822
823
824
)


chenych's avatar
chenych committed
825
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
826
827
    name="cpm",
    format_user=StringFormatter(slots=["<用户>{{content}}<AI>"]),
chenych's avatar
chenych committed
828
829
830
831
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)


luopl's avatar
luopl committed
832
# copied from chatml template
chenych's avatar
chenych committed
833
register_template(
luopl's avatar
luopl committed
834
835
    name="cpm3",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
836
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
837
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
838
839
840
841
842
843
844
845
846
847
848
849
850
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<|im_end|>"],
)


# copied from chatml template
register_template(
    name="cpm4",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
851
852
853
854
855
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<|im_end|>"],
)


luopl's avatar
luopl committed
856
# copied from chatml template
chenych's avatar
chenych committed
857
register_template(
chenych's avatar
chenych committed
858
859
    name="dbrx",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
860
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    default_system=(
        "You are DBRX, created by Databricks. You were last updated in December 2023. "
        "You answer questions based on information available up to that point.\n"
        "YOU 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."
    ),
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
879
    replace_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
880
881
882
)


chenych's avatar
chenych committed
883
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
884
885
    name="deepseek",
    format_user=StringFormatter(slots=["User: {{content}}\n\nAssistant:"]),
chenych's avatar
chenych committed
886
887
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
888
889
890
)


chenych's avatar
chenych committed
891
register_template(
luopl's avatar
luopl committed
892
893
894
895
896
897
    name="deepseek3",
    format_user=StringFormatter(slots=["<|User|>{{content}}<|Assistant|>"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)


chenych's avatar
chenych committed
898
899
900
901
902
903
904
905
906
# copied from deepseek3 template
register_template(
    name="deepseekr1",
    format_user=StringFormatter(slots=["<|User|>{{content}}<|Assistant|>"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    template_class=ReasoningTemplate,
)


chenych's avatar
chenych committed
907
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
908
909
    name="deepseekcoder",
    format_user=StringFormatter(slots=["### Instruction:\n{{content}}\n### Response:"]),
luopl's avatar
luopl committed
910
    format_assistant=StringFormatter(slots=["\n{{content}}\n<|EOT|>\n"]),
chenych's avatar
chenych committed
911
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
912
    default_system=(
chenych's avatar
chenych committed
913
914
        "You are an AI programming assistant, utilizing the DeepSeek Coder model, "
        "developed by DeepSeek Company, and you only answer questions related to computer science. "
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
915
        "For politically sensitive questions, security and privacy issues, "
chenych's avatar
chenych committed
916
        "and other non-computer science questions, you will refuse to answer.\n"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
917
918
919
920
    ),
)


chenych's avatar
chenych committed
921
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
922
    name="default",
chenych's avatar
chenych committed
923
    format_user=StringFormatter(slots=["Human: {{content}}", {"eos_token"}, "\nAssistant:"]),
luopl's avatar
luopl committed
924
    format_assistant=StringFormatter(slots=["{{content}}", {"eos_token"}, "\n"]),
chenych's avatar
chenych committed
925
926
    format_system=StringFormatter(slots=["System: {{content}}", {"eos_token"}, "\n"]),
    replace_jinja_template=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
927
928
929
)


shihm's avatar
uodata  
shihm committed
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
register_template(
    name="dots_ocr",
    format_user=StringFormatter(slots=["<|user|>{{content}}<|endofuser|><|assistant|>"]),
    format_assistant=StringFormatter(slots=["{{content}}<|endofassistant|>"]),
    format_system=StringFormatter(slots=["<|system|>{{content}}<|endofsystem|>\n"]),
    stop_words=["<|endofassistant|>"],
    efficient_eos=True,
    mm_plugin=get_mm_plugin(
        name="qwen2_vl",
        image_token="<|imgpad|>",
        video_token="<|vidpad|>",
        vision_bos_token="<|img|>",
        vision_eos_token="<|endofimg|>",
    ),
)


chenych's avatar
chenych committed
947
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
948
    name="empty",
chenych's avatar
chenych committed
949
    format_assistant=StringFormatter(slots=["{{content}}"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
950
951
952
)


shihm's avatar
uodata  
shihm committed
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
# copied from chatml template
register_template(
    name="ernie",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n\n"]),
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n\n<|im_start|>assistant\n"]),
    default_system="<global_setting>\nthink_mode=True\n</global_setting>",
    stop_words=["<|im_end|>"],
)


register_template(
    name="ernie_nothink",
    format_user=StringFormatter(slots=["User: {{content}}\nAssistant: "]),
    format_assistant=StringFormatter(slots=["{{content}}<|end_of_sentence|>"]),
    format_system=StringFormatter(slots=["{{content}}\n"]),
    format_prefix=EmptyFormatter(slots=["<|begin_of_sentence|>"]),
    stop_words=["<|end_of_sentence|>"],
)


register_template(
    name="ernie_vl",
    format_user=StringFormatter(slots=["User: {{content}}"]),
    format_assistant=StringFormatter(slots=["\nAssistant: {{content}}<|end_of_sentence|>"]),
    format_system=StringFormatter(slots=["{{content}}\n"]),
    stop_words=["<|end_of_sentence|>"],
    replace_eos=True,
    replace_jinja_template=True,
    template_class=ReasoningTemplate,
    mm_plugin=get_mm_plugin(name="ernie_vl", image_token="<|IMAGE_PLACEHOLDER|>", video_token="<|VIDEO_PLACEHOLDER|>"),
)


chenych's avatar
chenych committed
988
register_template(
luopl's avatar
luopl committed
989
990
    name="exaone",
    format_user=StringFormatter(slots=["[|user|]{{content}}\n[|assistant|]"]),
luopl's avatar
luopl committed
991
    format_assistant=StringFormatter(slots=["{{content}}", {"eos_token"}, "\n"]),
luopl's avatar
luopl committed
992
993
994
995
    format_system=StringFormatter(slots=["[|system|]{{content}}[|endofturn|]\n"]),
)


chenych's avatar
chenych committed
996
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
997
998
    name="falcon",
    format_user=StringFormatter(slots=["User: {{content}}\nFalcon:"]),
luopl's avatar
luopl committed
999
    format_assistant=StringFormatter(slots=["{{content}}\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1000
1001
1002
1003
    efficient_eos=True,
)


chenych's avatar
chenych committed
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
# copied from chatml template
register_template(
    name="falcon_h1",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<|im_end|>", "<|end_of_text|>"],
)


chenych's avatar
chenych committed
1016
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1017
    name="fewshot",
luopl's avatar
luopl committed
1018
    format_assistant=StringFormatter(slots=["{{content}}\n\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1019
    efficient_eos=True,
chenych's avatar
chenych committed
1020
    replace_jinja_template=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1021
1022
1023
)


chenych's avatar
chenych committed
1024
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1025
1026
    name="gemma",
    format_user=StringFormatter(slots=["<start_of_turn>user\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]),
luopl's avatar
luopl committed
1027
    format_assistant=StringFormatter(slots=["{{content}}<end_of_turn>\n"]),
chenych's avatar
chenych committed
1028
1029
1030
1031
1032
1033
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
    format_observation=StringFormatter(
        slots=["<start_of_turn>tool\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]
    ),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<end_of_turn>"],
chenych's avatar
chenych committed
1034
    replace_eos=True,
chenych's avatar
chenych committed
1035
1036
1037
1038
    template_class=Llama2Template,
)


chenych's avatar
chenych committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
# copied from gemma template
register_template(
    name="gemma2",
    format_user=StringFormatter(slots=["<start_of_turn>user\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<end_of_turn>\n"]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
    format_observation=StringFormatter(
        slots=["<start_of_turn>tool\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]
    ),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<eos>", "<end_of_turn>"],
    efficient_eos=True,
    template_class=Llama2Template,
)


chenych's avatar
chenych committed
1055
1056
1057
1058
1059
1060
# copied from gemma template
register_template(
    name="gemma3",
    format_user=StringFormatter(slots=["<start_of_turn>user\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<end_of_turn>\n"]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
chenych's avatar
chenych committed
1061
1062
1063
1064
    format_observation=StringFormatter(
        slots=["<start_of_turn>tool\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]
    ),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
chenych's avatar
chenych committed
1065
    stop_words=["<end_of_turn>"],
chenych's avatar
chenych committed
1066
    replace_eos=True,
chenych's avatar
chenych committed
1067
1068
    mm_plugin=get_mm_plugin("gemma3", image_token="<image_soft_token>"),
    template_class=Llama2Template,
chenych's avatar
chenych committed
1069
1070
1071
)


chenych's avatar
chenych committed
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
register_template(
    name="gemma3n",
    format_user=StringFormatter(slots=["<start_of_turn>user\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<end_of_turn>\n"]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
    format_observation=StringFormatter(
        slots=["<start_of_turn>tool\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]
    ),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<end_of_turn>"],
    replace_eos=True,
    mm_plugin=get_mm_plugin("gemma3n", image_token="<image_soft_token>", audio_token="<audio_soft_token>"),
    template_class=Llama2Template,
)


chenych's avatar
chenych committed
1088
register_template(
chenych's avatar
chenych committed
1089
1090
1091
1092
    name="glm4",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>"]),
    format_assistant=StringFormatter(slots=["\n{{content}}"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}"]),
luopl's avatar
luopl committed
1093
    format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4"),
chenych's avatar
chenych committed
1094
1095
1096
1097
    format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>"]),
    format_tools=ToolFormatter(tool_format="glm4"),
    format_prefix=EmptyFormatter(slots=["[gMASK]<sop>"]),
    stop_words=["<|user|>", "<|observation|>"],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1098
1099
1100
1101
    efficient_eos=True,
)


shihm's avatar
uodata  
shihm committed
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
# copied from glm4 template
register_template(
    name="glm4_moe",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>"]),
    format_assistant=StringFormatter(slots=["\n{{content}}"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}"]),
    format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4_moe"),
    format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>"]),
    format_tools=ToolFormatter(tool_format="glm4_moe"),
    format_prefix=EmptyFormatter(slots=["[gMASK]<sop>"]),
    stop_words=["<|user|>", "<|observation|>"],
    efficient_eos=True,
    template_class=ReasoningTemplate,
)


chenych's avatar
chenych committed
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
# copied from glm4 template
register_template(
    name="glm4v",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>"]),
    format_assistant=StringFormatter(slots=["\n{{content}}"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}"]),
    format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4"),
    format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>"]),
    format_tools=ToolFormatter(tool_format="glm4"),
    format_prefix=EmptyFormatter(slots=["[gMASK]<sop>"]),
    stop_words=["<|user|>", "<|observation|>", "</answer>"],
    efficient_eos=True,
    mm_plugin=get_mm_plugin(name="glm4v", image_token="<|image|>", video_token="<|video|>"),
    template_class=ReasoningTemplate,
)


shihm's avatar
uodata  
shihm committed
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
# copied from glm4 template
register_template(
    name="glm4_5v",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>"]),
    format_assistant=StringFormatter(slots=["\n{{content}}"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}"]),
    format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4_moe"),
    format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>"]),
    format_tools=ToolFormatter(tool_format="glm4_moe"),
    format_prefix=EmptyFormatter(slots=["[gMASK]<sop>"]),
    stop_words=["<|user|>", "<|observation|>", "</answer>"],
    efficient_eos=True,
    mm_plugin=get_mm_plugin(name="glm4v", image_token="<|image|>", video_token="<|video|>"),
    template_class=ReasoningTemplate,
)


chenych's avatar
chenych committed
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
# copied from glm4 template
register_template(
    name="glmz1",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>"]),
    format_assistant=StringFormatter(slots=["\n{{content}}"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}"]),
    format_function=FunctionFormatter(slots=["{{content}}"], tool_format="glm4"),
    format_observation=StringFormatter(slots=["<|observation|>\n{{content}}<|assistant|>"]),
    format_tools=ToolFormatter(tool_format="glm4"),
    format_prefix=EmptyFormatter(slots=["[gMASK]<sop>"]),
    stop_words=["<|user|>", "<|observation|>"],
    efficient_eos=True,
    template_class=ReasoningTemplate,
)


shihm's avatar
uodata  
shihm committed
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
register_template(
    name="gpt_oss",
    format_user=StringFormatter(slots=["<|start|>user<|message|>{{content}}<|end|><|start|>assistant"]),
    format_assistant=StringFormatter(slots=["{{content}}<|end|>"]),
    format_system=StringFormatter(slots=["<|start|>system<|message|>{{content}}<|end|>"]),
    default_system="You are ChatGPT, a large language model trained by OpenAI.",
    thought_words=("<|channel|>analysis<|message|>", "<|end|><|start|>assistant<|channel|>final<|message|>"),
    efficient_eos=True,
    template_class=ReasoningTemplate,
)


chenych's avatar
chenych committed
1180
register_template(
luopl's avatar
luopl committed
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
    name="granite3",
    format_user=StringFormatter(
        slots=[
            "<|start_of_role|>user<|end_of_role|>{{content}}<|end_of_text|>\n<|start_of_role|>assistant<|end_of_role|>"
        ]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<|end_of_text|>\n"]),
    format_system=StringFormatter(slots=["<|start_of_role|>system<|end_of_role|>{{content}}<|end_of_text|>\n"]),
)


chenych's avatar
chenych committed
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
register_template(
    name="granite3_vision",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}\n<|assistant|>\n"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}\n"]),
    default_system=(
        "A chat between a curious user and an artificial intelligence assistant. "
        "The assistant gives helpful, detailed, and polite answers to the user's questions."
    ),
    mm_plugin=get_mm_plugin(name="llava_next", image_token="<image>"),
)


shihm's avatar
uodata  
shihm committed
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
register_template(
    name="granite4",
    format_user=StringFormatter(
        slots=[
            "<|start_of_role|>user<|end_of_role|>{{content}}<|end_of_text|>\n<|start_of_role|>assistant<|end_of_role|>"
        ]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<|end_of_text|>\n"]),
    format_system=StringFormatter(slots=["<|start_of_role|>system<|end_of_role|>{{content}}<|end_of_text|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|end_of_text|>\n"], tool_format="default"),
    format_observation=StringFormatter(
        slots=["<|start_of_role|>tool<|end_of_role|>{{content}}<|end_of_text|>\n<|start_of_role|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="default"),
    stop_words=["<|end_of_text|>"],
    default_system="You are Granite, developed by IBM. You are a helpful AI assistant.",
)


chenych's avatar
chenych committed
1223
register_template(
luopl's avatar
luopl committed
1224
1225
1226
1227
1228
1229
1230
    name="index",
    format_user=StringFormatter(slots=["reserved_0{{content}}reserved_1"]),
    format_system=StringFormatter(slots=["<unk>{{content}}"]),
    efficient_eos=True,
)


chenych's avatar
chenych committed
1231
1232
register_template(
    name="hunyuan",
shihm's avatar
uodata  
shihm committed
1233
1234
1235
1236
    format_user=StringFormatter(slots=["{{content}}<|extra_0|>"]),
    format_assistant=StringFormatter(slots=["{{content}}<|eos|>"]),
    format_system=StringFormatter(slots=["{{content}}<|extra_4|>"]),
    format_prefix=EmptyFormatter(slots=["<|startoftext|>"]),
chenych's avatar
chenych committed
1237
1238
1239
1240
    stop_words=["<|eos|>"],
)


chenych's avatar
chenych committed
1241
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1242
    name="intern",
chenych's avatar
chenych committed
1243
    format_user=StringFormatter(slots=["<|User|>:{{content}}\n<|Bot|>:"]),
luopl's avatar
luopl committed
1244
    format_assistant=StringFormatter(slots=["{{content}}<eoa>\n"]),
chenych's avatar
chenych committed
1245
1246
    format_system=StringFormatter(slots=["<|System|>:{{content}}\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
chenych's avatar
chenych committed
1247
1248
1249
1250
1251
1252
1253
    default_system=(
        "You are an AI assistant whose name is InternLM (书生·浦语).\n"
        "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory "
        "(上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
        "- InternLM (书生·浦语) can understand and communicate fluently in the language "
        "chosen by the user such as English and 中文."
    ),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1254
1255
1256
1257
    stop_words=["<eoa>"],
)


chenych's avatar
chenych committed
1258
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1259
1260
    name="intern2",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
1261
1262
1263
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
chenych's avatar
chenych committed
1264
1265
1266
1267
1268
1269
1270
    default_system=(
        "You are an AI assistant whose name is InternLM (书生·浦语).\n"
        "- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory "
        "(上海人工智能实验室). It is designed to be helpful, honest, and harmless.\n"
        "- InternLM (书生·浦语) can understand and communicate fluently in the language "
        "chosen by the user such as English and 中文."
    ),
luopl's avatar
luopl committed
1271
1272
1273
1274
    stop_words=["<|im_end|>"],
)


chenych's avatar
chenych committed
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
register_template(
    name="intern_vl",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    default_system=(
        "你是书生·万象,英文名是InternVL,是由上海人工智能实验室、清华大学及多家合作单位联合开发的多模态大语言模型。"
    ),
    stop_words=["<|im_end|>"],
    mm_plugin=get_mm_plugin(name="intern_vl", image_token="<image>", video_token="<video>"),
)


shihm's avatar
uodata  
shihm committed
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
register_template(
    name="intern_s1",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<|im_end|>"],
    mm_plugin=get_mm_plugin(name="intern_vl", image_token="<image>", video_token="<video>"),
)


# copied from qwen template
register_template(
    name="keye_vl",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    stop_words=["<|im_end|>"],
    replace_eos=True,
    mm_plugin=get_mm_plugin(name="qwen2_vl", image_token="<|image_pad|>", video_token="<|video_pad|>"),
    template_class=ReasoningTemplate,
)


chenych's avatar
chenych committed
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
register_template(
    name="kimi_vl",
    format_user=StringFormatter(
        slots=["<|im_user|>user<|im_middle|>{{content}}<|im_end|><|im_assistant|>assistant<|im_middle|>"]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>"]),
    format_system=StringFormatter(slots=["<|im_system|>system<|im_middle|>{{content}}<|im_end|>"]),
    default_system="You are a helpful assistant",
    stop_words=["<|im_end|>"],
    thought_words=("◁think▷", "◁/think▷"),
    mm_plugin=get_mm_plugin("kimi_vl", image_token="<|media_pad|>"),
chenych's avatar
chenych committed
1329
    template_class=ReasoningTemplate,
chenych's avatar
chenych committed
1330
1331
1332
)


chenych's avatar
chenych committed
1333
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1334
1335
1336
    name="llama2",
    format_user=StringFormatter(slots=[{"bos_token"}, "[INST] {{content}} [/INST]"]),
    format_system=StringFormatter(slots=["<<SYS>>\n{{content}}\n<</SYS>>\n\n"]),
chenych's avatar
chenych committed
1337
    template_class=Llama2Template,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1338
1339
1340
)


luopl's avatar
luopl committed
1341
# copied from llama2 template
chenych's avatar
chenych committed
1342
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1343
1344
1345
1346
    name="llama2_zh",
    format_user=StringFormatter(slots=[{"bos_token"}, "[INST] {{content}} [/INST]"]),
    format_system=StringFormatter(slots=["<<SYS>>\n{{content}}\n<</SYS>>\n\n"]),
    default_system="You are a helpful assistant. 你是一个乐于助人的助手。",
chenych's avatar
chenych committed
1347
    template_class=Llama2Template,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1348
1349
1350
)


chenych's avatar
chenych committed
1351
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1352
1353
1354
1355
1356
1357
1358
1359
1360
    name="llama3",
    format_user=StringFormatter(
        slots=[
            (
                "<|start_header_id|>user<|end_header_id|>\n\n{{content}}<|eot_id|>"
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
    ),
luopl's avatar
luopl committed
1361
    format_assistant=StringFormatter(slots=["{{content}}<|eot_id|>"]),
chenych's avatar
chenych committed
1362
    format_system=StringFormatter(slots=["<|start_header_id|>system<|end_header_id|>\n\n{{content}}<|eot_id|>"]),
luopl's avatar
luopl committed
1363
    format_function=FunctionFormatter(slots=["{{content}}<|eot_id|>"], tool_format="llama3"),
chenych's avatar
chenych committed
1364
1365
1366
    format_observation=StringFormatter(
        slots=[
            (
luopl's avatar
luopl committed
1367
                "<|start_header_id|>ipython<|end_header_id|>\n\n{{content}}<|eot_id|>"
chenych's avatar
chenych committed
1368
1369
1370
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1371
    ),
luopl's avatar
luopl committed
1372
    format_tools=ToolFormatter(tool_format="llama3"),
chenych's avatar
chenych committed
1373
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
luopl's avatar
luopl committed
1374
    stop_words=["<|eot_id|>", "<|eom_id|>"],
chenych's avatar
chenych committed
1375
    replace_eos=True,
luopl's avatar
luopl committed
1376
1377
1378
)


chenych's avatar
chenych committed
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
register_template(
    name="llama4",
    format_user=StringFormatter(
        slots=["<|header_start|>user<|header_end|>\n\n{{content}}<|eot|><|header_start|>assistant<|header_end|>\n\n"]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<|eot|>"]),
    format_system=StringFormatter(slots=["<|header_start|>system<|header_end|>\n\n{{content}}<|eot|>"]),
    format_function=FunctionFormatter(slots=["{{content}}<|eot|>"], tool_format="llama3"),
    format_observation=StringFormatter(
        slots=[
            "<|header_start|>ipython<|header_end|>\n\n{{content}}<|eot|><|header_start|>assistant<|header_end|>\n\n"
        ]
    ),
    format_tools=ToolFormatter(tool_format="llama3"),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<|eot|>", "<|eom|>"],
chenych's avatar
chenych committed
1395
    replace_eos=True,
chenych's avatar
chenych committed
1396
1397
1398
1399
    mm_plugin=get_mm_plugin(name="llama4", image_token="<|image|>"),
)


luopl's avatar
luopl committed
1400
# copied from llama3 template
chenych's avatar
chenych committed
1401
register_template(
luopl's avatar
luopl committed
1402
1403
1404
1405
1406
1407
1408
1409
1410
    name="mllama",
    format_user=StringFormatter(
        slots=[
            (
                "<|start_header_id|>user<|end_header_id|>\n\n{{content}}<|eot_id|>"
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
    ),
luopl's avatar
luopl committed
1411
    format_assistant=StringFormatter(slots=["{{content}}<|eot_id|>"]),
luopl's avatar
luopl committed
1412
    format_system=StringFormatter(slots=["<|start_header_id|>system<|end_header_id|>\n\n{{content}}<|eot_id|>"]),
luopl's avatar
luopl committed
1413
    format_function=FunctionFormatter(slots=["{{content}}<|eot_id|>"], tool_format="llama3"),
luopl's avatar
luopl committed
1414
1415
1416
    format_observation=StringFormatter(
        slots=[
            (
luopl's avatar
luopl committed
1417
                "<|start_header_id|>ipython<|end_header_id|>\n\n{{content}}<|eot_id|>"
luopl's avatar
luopl committed
1418
1419
1420
1421
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
    ),
luopl's avatar
luopl committed
1422
    format_tools=ToolFormatter(tool_format="llama3"),
luopl's avatar
luopl committed
1423
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
luopl's avatar
luopl committed
1424
    stop_words=["<|eot_id|>", "<|eom_id|>"],
chenych's avatar
chenych committed
1425
    replace_eos=True,
luopl's avatar
luopl committed
1426
1427
1428
1429
    mm_plugin=get_mm_plugin(name="mllama", image_token="<|image|>"),
)


chenych's avatar
chenych committed
1430
1431
1432
1433
1434
1435
1436
1437
1438
register_template(
    name="moonlight",
    format_user=StringFormatter(
        slots=["<|im_user|>user<|im_middle|>{{content}}<|im_end|><|im_assistant|>assistant<|im_middle|>"]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>"]),
    format_system=StringFormatter(slots=["<|im_system|>system<|im_middle|>{{content}}<|im_end|>"]),
    default_system="You are a helpful assistant provided by Moonshot-AI.",
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1439
    replace_eos=True,
chenych's avatar
chenych committed
1440
1441
1442
)


luopl's avatar
luopl committed
1443
# copied from vicuna template
chenych's avatar
chenych committed
1444
register_template(
luopl's avatar
luopl committed
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
    name="llava",
    format_user=StringFormatter(slots=["USER: {{content}} ASSISTANT:"]),
    default_system=(
        "A chat between a curious user and an artificial intelligence assistant. "
        "The assistant gives helpful, detailed, and polite answers to the user's questions."
    ),
    mm_plugin=get_mm_plugin(name="llava", image_token="<image>"),
)


luopl's avatar
luopl committed
1455
# copied from vicuna template
chenych's avatar
chenych committed
1456
register_template(
luopl's avatar
luopl committed
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
    name="llava_next",
    format_user=StringFormatter(slots=["USER: {{content}} ASSISTANT:"]),
    default_system=(
        "A chat between a curious user and an artificial intelligence assistant. "
        "The assistant gives helpful, detailed, and polite answers to the user's questions."
    ),
    mm_plugin=get_mm_plugin(name="llava_next", image_token="<image>"),
)


luopl's avatar
luopl committed
1467
# copied from llama3 template
chenych's avatar
chenych committed
1468
register_template(
luopl's avatar
luopl committed
1469
1470
1471
1472
1473
1474
1475
1476
1477
    name="llava_next_llama3",
    format_user=StringFormatter(
        slots=[
            (
                "<|start_header_id|>user<|end_header_id|>\n\n{{content}}<|eot_id|>"
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
    ),
luopl's avatar
luopl committed
1478
    format_assistant=StringFormatter(slots=["{{content}}<|eot_id|>"]),
luopl's avatar
luopl committed
1479
    format_system=StringFormatter(slots=["<|start_header_id|>system<|end_header_id|>\n\n{{content}}<|eot_id|>"]),
luopl's avatar
luopl committed
1480
    format_function=FunctionFormatter(slots=["{{content}}<|eot_id|>"], tool_format="llama3"),
luopl's avatar
luopl committed
1481
1482
1483
    format_observation=StringFormatter(
        slots=[
            (
luopl's avatar
luopl committed
1484
                "<|start_header_id|>ipython<|end_header_id|>\n\n{{content}}<|eot_id|>"
luopl's avatar
luopl committed
1485
1486
1487
1488
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
    ),
luopl's avatar
luopl committed
1489
    format_tools=ToolFormatter(tool_format="llama3"),
luopl's avatar
luopl committed
1490
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
luopl's avatar
luopl committed
1491
    stop_words=["<|eot_id|>", "<|eom_id|>"],
chenych's avatar
chenych committed
1492
    replace_eos=True,
luopl's avatar
luopl committed
1493
1494
1495
1496
    mm_plugin=get_mm_plugin(name="llava_next", image_token="<image>"),
)


luopl's avatar
luopl committed
1497
# copied from mistral template
chenych's avatar
chenych committed
1498
register_template(
luopl's avatar
luopl committed
1499
    name="llava_next_mistral",
luopl's avatar
luopl committed
1500
1501
1502
    format_user=StringFormatter(slots=["[INST] {{content}}[/INST]"]),
    format_assistant=StringFormatter(slots=[" {{content}}", {"eos_token"}]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
chenych's avatar
chenych committed
1503
    format_function=FunctionFormatter(slots=["[TOOL_CALLS] {{content}}", {"eos_token"}], tool_format="mistral"),
luopl's avatar
luopl committed
1504
1505
    format_observation=StringFormatter(slots=["""[TOOL_RESULTS] {"content": {{content}}}[/TOOL_RESULTS]"""]),
    format_tools=ToolFormatter(tool_format="mistral"),
luopl's avatar
luopl committed
1506
1507
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    mm_plugin=get_mm_plugin(name="llava_next", image_token="<image>"),
chenych's avatar
chenych committed
1508
    template_class=Llama2Template,
luopl's avatar
luopl committed
1509
1510
1511
)


chenych's avatar
chenych committed
1512
1513
# copied from qwen template
register_template(
luopl's avatar
luopl committed
1514
1515
    name="llava_next_qwen",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
1516
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
1517
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
1518
1519
1520
1521
1522
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
luopl's avatar
luopl committed
1523
1524
    default_system="You are a helpful assistant.",
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1525
    replace_eos=True,
luopl's avatar
luopl committed
1526
1527
1528
1529
    mm_plugin=get_mm_plugin(name="llava_next", image_token="<image>"),
)


luopl's avatar
luopl committed
1530
# copied from chatml template
chenych's avatar
chenych committed
1531
register_template(
luopl's avatar
luopl committed
1532
1533
    name="llava_next_yi",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
1534
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
1535
1536
1537
1538
1539
1540
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    stop_words=["<|im_end|>"],
    mm_plugin=get_mm_plugin(name="llava_next", image_token="<image>"),
)


luopl's avatar
luopl committed
1541
# copied from vicuna template
chenych's avatar
chenych committed
1542
register_template(
luopl's avatar
luopl committed
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
    name="llava_next_video",
    format_user=StringFormatter(slots=["USER: {{content}} ASSISTANT:"]),
    default_system=(
        "A chat between a curious user and an artificial intelligence assistant. "
        "The assistant gives helpful, detailed, and polite answers to the user's questions."
    ),
    mm_plugin=get_mm_plugin(name="llava_next_video", image_token="<image>", video_token="<video>"),
)


luopl's avatar
luopl committed
1553
# copied from mistral template
chenych's avatar
chenych committed
1554
register_template(
luopl's avatar
luopl committed
1555
    name="llava_next_video_mistral",
luopl's avatar
luopl committed
1556
1557
1558
    format_user=StringFormatter(slots=["[INST] {{content}}[/INST]"]),
    format_assistant=StringFormatter(slots=[" {{content}}", {"eos_token"}]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
chenych's avatar
chenych committed
1559
    format_function=FunctionFormatter(slots=["[TOOL_CALLS] {{content}}", {"eos_token"}], tool_format="mistral"),
luopl's avatar
luopl committed
1560
1561
    format_observation=StringFormatter(slots=["""[TOOL_RESULTS] {"content": {{content}}}[/TOOL_RESULTS]"""]),
    format_tools=ToolFormatter(tool_format="mistral"),
luopl's avatar
luopl committed
1562
1563
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    mm_plugin=get_mm_plugin(name="llava_next_video", image_token="<image>", video_token="<video>"),
chenych's avatar
chenych committed
1564
    template_class=Llama2Template,
luopl's avatar
luopl committed
1565
1566
1567
)


luopl's avatar
luopl committed
1568
# copied from chatml template
chenych's avatar
chenych committed
1569
register_template(
luopl's avatar
luopl committed
1570
1571
    name="llava_next_video_yi",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
1572
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
1573
1574
1575
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    stop_words=["<|im_end|>"],
    mm_plugin=get_mm_plugin(name="llava_next_video", image_token="<image>", video_token="<video>"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1576
1577
1578
)


luopl's avatar
luopl committed
1579
# copied from chatml template
chenych's avatar
chenych committed
1580
register_template(
luopl's avatar
luopl committed
1581
1582
1583
1584
1585
1586
    name="marco",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    default_system=(
chenych's avatar
chenych committed
1587
1588
        "你是一个经过良好训练的AI助手,你的名字是Marco-o1."
        "由阿里国际数字商业集团的AI Business创造.\n## 重要!!!!!\n"
luopl's avatar
luopl committed
1589
1590
1591
1592
1593
1594
1595
        "当你回答问题时,你的思考应该在<Thought>内完成,<Output>内输出你的结果。\n"
        "<Thought>应该尽可能是英文,但是有2个特例,一个是对原文中的引用,另一个是是数学应该使用markdown格式,<Output>内的输出需要遵循用户输入的语言。\n"
    ),
    stop_words=["<|im_end|>"],
)


chenych's avatar
chenych committed
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
# copied from qwen template
register_template(
    name="mimo",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    default_system="You are a helpful assistant.",
    stop_words=["<|im_end|>"],
    replace_eos=True,
    template_class=ReasoningTemplate,
)

shihm's avatar
uodata  
shihm committed
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632

# copied from qwen template
register_template(
    name="mimo_v2",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    default_system="You are MiMo, a helpful AI assistant engineered by Xiaomi.",
    stop_words=["<|im_end|>"],
    replace_eos=True,
    thought_words=("<think>", "</think>"),
    template_class=ReasoningTemplate,
)


chenych's avatar
chenych committed
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
# copied from qwen2vl
register_template(
    name="mimo_vl",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    default_system="You are MiMo, an AI assistant developed by Xiaomi.",
    stop_words=["<|im_end|>"],
    replace_eos=True,
    mm_plugin=get_mm_plugin(name="qwen2_vl", image_token="<|image_pad|>", video_token="<|video_pad|>"),
    template_class=ReasoningTemplate,
)


luopl's avatar
luopl committed
1652
# copied from chatml template
chenych's avatar
chenych committed
1653
register_template(
luopl's avatar
luopl committed
1654
1655
1656
1657
1658
    name="minicpm_v",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1659
    default_system="You are a helpful assistant.",
luopl's avatar
luopl committed
1660
1661
1662
1663
    mm_plugin=get_mm_plugin(name="minicpm_v", image_token="<image>", video_token="<video>"),
)


chenych's avatar
chenych committed
1664
1665
1666
1667
1668
1669
1670
# copied from minicpm_v template
register_template(
    name="minicpm_o",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    stop_words=["<|im_end|>"],
shihm's avatar
uodata  
shihm committed
1671
    default_system="You are a helpful assistant. You can accept audio and text input and output voice and text.",
chenych's avatar
chenych committed
1672
1673
1674
1675
    mm_plugin=get_mm_plugin(name="minicpm_v", image_token="<image>", video_token="<video>", audio_token="<audio>"),
)


shihm's avatar
uodata  
shihm committed
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
register_template(
    name="minimax1",
    format_user=StringFormatter(
        slots=[
            "<beginning_of_sentence>user name=user\n{{content}}<end_of_sentence>\n<beginning_of_sentence>ai name=assistant\n"
        ]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<end_of_sentence>\n"]),
    format_system=StringFormatter(
        slots=["<beginning_of_sentence>system ai_setting=assistant\n{{content}}<end_of_sentence>\n"]
    ),
    format_function=FunctionFormatter(slots=["{{content}}<end_of_sentence>\n"], tool_format="minimax1"),
    format_observation=StringFormatter(
        slots=[
            "<beginning_of_sentence>tool name=tools\n{{content}}<end_of_sentence>\n<beginning_of_sentence>ai name=assistant\n"
        ]
    ),
    format_tools=ToolFormatter(tool_format="minimax1"),
    default_system="You are a helpful assistant.",
    stop_words=["<end_of_sentence>"],
)


register_template(
    name="minimax2",
    format_user=StringFormatter(slots=["]~b]user\n{{content}}[e~[\n]~b]ai\n"]),
    format_assistant=StringFormatter(slots=["{{content}}[e~[\n"]),
    format_system=StringFormatter(slots=["]~!b[]~b]system\n{{content}}[e~[\n"]),
    format_function=FunctionFormatter(slots=["{{content}}[e~[\n"], tool_format="minimax2"),
    format_observation=StringFormatter(slots=["]~b]tool\n<response>{{content}}</response>[e~[\n]~b]ai\n"]),
    format_tools=ToolFormatter(tool_format="minimax2"),
    default_system="You are a helpful assistant. Your name is MiniMax-M2.1 and is built by MiniMax.",
    stop_words=["[e~["],
    template_class=ReasoningTemplate,
)


chenych's avatar
chenych committed
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
# mistral tokenizer v3 tekken
register_template(
    name="ministral",
    format_user=StringFormatter(slots=["[INST]{{content}}[/INST]"]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
    format_function=FunctionFormatter(slots=["[TOOL_CALLS]{{content}}", {"eos_token"}], tool_format="mistral"),
    format_observation=StringFormatter(slots=["""[TOOL_RESULTS]{"content": {{content}}}[/TOOL_RESULTS]"""]),
    format_tools=ToolFormatter(tool_format="mistral"),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    template_class=Llama2Template,
)


# mistral tokenizer v3
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1728
    name="mistral",
luopl's avatar
luopl committed
1729
1730
1731
    format_user=StringFormatter(slots=["[INST] {{content}}[/INST]"]),
    format_assistant=StringFormatter(slots=[" {{content}}", {"eos_token"}]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
chenych's avatar
chenych committed
1732
    format_function=FunctionFormatter(slots=["[TOOL_CALLS] {{content}}", {"eos_token"}], tool_format="mistral"),
luopl's avatar
luopl committed
1733
1734
    format_observation=StringFormatter(slots=["""[TOOL_RESULTS] {"content": {{content}}}[/TOOL_RESULTS]"""]),
    format_tools=ToolFormatter(tool_format="mistral"),
chenych's avatar
chenych committed
1735
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
chenych's avatar
chenych committed
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
    template_class=Llama2Template,
)


# mistral tokenizer v7 tekken (copied from ministral)
register_template(
    name="mistral_small",
    format_user=StringFormatter(slots=["[INST]{{content}}[/INST]"]),
    format_system=StringFormatter(slots=["[SYSTEM_PROMPT]{{content}}[/SYSTEM_PROMPT]"]),
    format_function=FunctionFormatter(slots=["[TOOL_CALLS]{{content}}", {"eos_token"}], tool_format="mistral"),
    format_observation=StringFormatter(slots=["""[TOOL_RESULTS]{"content": {{content}}}[/TOOL_RESULTS]"""]),
    format_tools=ToolFormatter(tool_format="mistral"),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
chenych's avatar
chenych committed
1749
    mm_plugin=get_mm_plugin(name="pixtral", image_token="[IMG]"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1750
1751
1752
)


shihm's avatar
uodata  
shihm committed
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
register_template(
    name="ministral3",
    format_user=StringFormatter(slots=["[INST]{{content}}[/INST]"]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
    format_function=FunctionFormatter(slots=["[TOOL_CALLS]{{content}}", {"eos_token"}], tool_format="mistral"),
    format_observation=StringFormatter(slots=["""[TOOL_RESULTS]{"content": {{content}}}[/TOOL_RESULTS]"""]),
    format_tools=ToolFormatter(tool_format="mistral"),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    template_class=Llama2Template,
    mm_plugin=get_mm_plugin(name="pixtral", image_token="[IMG]"),
)


chenych's avatar
chenych committed
1766
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1767
    name="olmo",
chenych's avatar
chenych committed
1768
1769
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>\n"]),
    format_prefix=EmptyFormatter(slots=[{"eos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1770
1771
1772
)


chenych's avatar
chenych committed
1773
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1774
1775
    name="openchat",
    format_user=StringFormatter(slots=["GPT4 Correct User: {{content}}", {"eos_token"}, "GPT4 Correct Assistant:"]),
chenych's avatar
chenych committed
1776
1777
1778
1779
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)


chenych's avatar
chenych committed
1780
register_template(
chenych's avatar
chenych committed
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
    name="openchat-3.6",
    format_user=StringFormatter(
        slots=[
            (
                "<|start_header_id|>GPT4 Correct User<|end_header_id|>\n\n{{content}}<|eot_id|>"
                "<|start_header_id|>GPT4 Correct Assistant<|end_header_id|>\n\n"
            )
        ]
    ),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<|eot_id|>"],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1792
1793
1794
)


luopl's avatar
luopl committed
1795
# copied from chatml template
chenych's avatar
chenych committed
1796
register_template(
luopl's avatar
luopl committed
1797
1798
    name="opencoder",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
1799
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
1800
1801
1802
1803
1804
1805
1806
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    default_system="You are OpenCoder, created by OpenCoder Team.",
    stop_words=["<|im_end|>"],
)


chenych's avatar
chenych committed
1807
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1808
1809
    name="orion",
    format_user=StringFormatter(slots=["Human: {{content}}\n\nAssistant: ", {"eos_token"}]),
chenych's avatar
chenych committed
1810
1811
1812
1813
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)


chenych's avatar
chenych committed
1814
register_template(
luopl's avatar
luopl committed
1815
    name="paligemma",
chenych's avatar
chenych committed
1816
1817
1818
    format_user=StringFormatter(slots=["{{content}}\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    mm_plugin=get_mm_plugin(name="paligemma", image_token="<image>"),
chenych's avatar
chenych committed
1819
    template_class=Llama2Template,
chenych's avatar
chenych committed
1820
1821
1822
1823
1824
1825
)


# copied from gemma template
register_template(
    name="paligemma_chat",
luopl's avatar
luopl committed
1826
    format_user=StringFormatter(slots=["<start_of_turn>user\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]),
luopl's avatar
luopl committed
1827
    format_assistant=StringFormatter(slots=["{{content}}<end_of_turn>\n"]),
luopl's avatar
luopl committed
1828
1829
1830
1831
    format_observation=StringFormatter(
        slots=["<start_of_turn>tool\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]
    ),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
chenych's avatar
chenych committed
1832
    stop_words=["<end_of_turn>"],
chenych's avatar
chenych committed
1833
    replace_eos=True,
luopl's avatar
luopl committed
1834
    mm_plugin=get_mm_plugin(name="paligemma", image_token="<image>"),
chenych's avatar
chenych committed
1835
    template_class=Llama2Template,
luopl's avatar
luopl committed
1836
1837
1838
)


chenych's avatar
chenych committed
1839
register_template(
chenych's avatar
chenych committed
1840
1841
    name="phi",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|end|>\n<|assistant|>\n"]),
luopl's avatar
luopl committed
1842
    format_assistant=StringFormatter(slots=["{{content}}<|end|>\n"]),
chenych's avatar
chenych committed
1843
1844
    format_system=StringFormatter(slots=["<|system|>\n{{content}}<|end|>\n"]),
    stop_words=["<|end|>"],
chenych's avatar
chenych committed
1845
    replace_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1846
1847
1848
)


chenych's avatar
chenych committed
1849
register_template(
luopl's avatar
luopl committed
1850
1851
    name="phi_small",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|end|>\n<|assistant|>\n"]),
luopl's avatar
luopl committed
1852
    format_assistant=StringFormatter(slots=["{{content}}<|end|>\n"]),
luopl's avatar
luopl committed
1853
1854
1855
    format_system=StringFormatter(slots=["<|system|>\n{{content}}<|end|>\n"]),
    format_prefix=EmptyFormatter(slots=[{"<|endoftext|>"}]),
    stop_words=["<|end|>"],
chenych's avatar
chenych committed
1856
    replace_eos=True,
luopl's avatar
luopl committed
1857
1858
1859
)


chenych's avatar
chenych committed
1860
register_template(
luopl's avatar
luopl committed
1861
1862
1863
1864
1865
1866
1867
    name="phi4",
    format_user=StringFormatter(
        slots=["<|im_start|>user<|im_sep|>{{content}}<|im_end|><|im_start|>assistant<|im_sep|>"]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>"]),
    format_system=StringFormatter(slots=["<|im_start|>system<|im_sep|>{{content}}<|im_end|>"]),
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1868
    replace_eos=True,
luopl's avatar
luopl committed
1869
1870
1871
)


chenych's avatar
chenych committed
1872
1873
# copied from ministral template
register_template(
luopl's avatar
luopl committed
1874
    name="pixtral",
luopl's avatar
luopl committed
1875
1876
    format_user=StringFormatter(slots=["[INST]{{content}}[/INST]"]),
    format_system=StringFormatter(slots=["{{content}}\n\n"]),
chenych's avatar
chenych committed
1877
1878
1879
    format_function=FunctionFormatter(slots=["[TOOL_CALLS]{{content}}", {"eos_token"}], tool_format="mistral"),
    format_observation=StringFormatter(slots=["""[TOOL_RESULTS]{"content": {{content}}}[/TOOL_RESULTS]"""]),
    format_tools=ToolFormatter(tool_format="mistral"),
luopl's avatar
luopl committed
1880
1881
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    mm_plugin=get_mm_plugin(name="pixtral", image_token="[IMG]"),
chenych's avatar
chenych committed
1882
    template_class=Llama2Template,
luopl's avatar
luopl committed
1883
1884
1885
)


luopl's avatar
luopl committed
1886
# copied from chatml template
chenych's avatar
chenych committed
1887
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1888
1889
    name="qwen",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
1890
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1891
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
1892
1893
1894
1895
1896
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
chenych's avatar
chenych committed
1897
    default_system="You are Qwen, created by Alibaba Cloud. You are a helpful assistant.",
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
1898
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1899
    replace_eos=True,
luopl's avatar
luopl committed
1900
1901
1902
)


chenych's avatar
chenych committed
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
# copied from qwen template
register_template(
    name="qwen3",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1915
1916
    replace_eos=True,
    template_class=ReasoningTemplate,
chenych's avatar
chenych committed
1917
1918
1919
)


shihm's avatar
uodata  
shihm committed
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
# copied from qwen template
register_template(
    name="qwen3_nothink",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    stop_words=["<|im_end|>"],
    replace_eos=True,
)


luopl's avatar
luopl committed
1936
# copied from chatml template
chenych's avatar
chenych committed
1937
1938
1939
1940
1941
1942
1943
register_template(
    name="qwen2_audio",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    default_system="You are a helpful assistant.",
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1944
    replace_eos=True,
chenych's avatar
chenych committed
1945
1946
1947
1948
    mm_plugin=get_mm_plugin(name="qwen2_audio", audio_token="<|AUDIO|>"),
)


chenych's avatar
chenych committed
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
# copied from qwen template
register_template(
    name="qwen2_omni",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    default_system="You are a helpful assistant.",
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
1962
    replace_eos=True,
chenych's avatar
chenych committed
1963
    mm_plugin=get_mm_plugin(
shihm's avatar
uodata  
shihm committed
1964
1965
1966
1967
1968
1969
1970
1971
        name="qwen2_omni",
        image_token="<|IMAGE|>",
        video_token="<|VIDEO|>",
        audio_token="<|AUDIO|>",
        vision_bos_token="<|vision_bos|>",
        vision_eos_token="<|vision_eos|>",
        audio_bos_token="<|audio_bos|>",
        audio_eos_token="<|audio_eos|>",
chenych's avatar
chenych committed
1972
1973
1974
    ),
)

shihm's avatar
uodata  
shihm committed
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012

register_template(
    name="qwen3_omni",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    stop_words=["<|im_end|>"],
    replace_eos=True,
    mm_plugin=get_mm_plugin(
        name="qwen2_omni", image_token="<|image_pad|>", video_token="<|video_pad|>", audio_token="<|audio_pad|>"
    ),
    template_class=ReasoningTemplate,
)


register_template(
    name="qwen3_omni_nothink",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    stop_words=["<|im_end|>"],
    replace_eos=True,
    mm_plugin=get_mm_plugin(
        name="qwen2_omni", image_token="<|image_pad|>", video_token="<|video_pad|>", audio_token="<|audio_pad|>"
    ),
)


chenych's avatar
chenych committed
2013
2014
# copied from qwen template
register_template(
luopl's avatar
luopl committed
2015
2016
    name="qwen2_vl",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
2017
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
2018
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
luopl's avatar
luopl committed
2019
2020
2021
2022
2023
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
luopl's avatar
luopl committed
2024
2025
    default_system="You are a helpful assistant.",
    stop_words=["<|im_end|>"],
chenych's avatar
chenych committed
2026
    replace_eos=True,
luopl's avatar
luopl committed
2027
    mm_plugin=get_mm_plugin(name="qwen2_vl", image_token="<|image_pad|>", video_token="<|video_pad|>"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2028
2029
2030
)


shihm's avatar
uodata  
shihm committed
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
# copied from qwen template
register_template(
    name="qwen3_vl",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    stop_words=["<|im_end|>"],
    replace_eos=True,
    mm_plugin=get_mm_plugin(name="qwen3_vl", image_token="<|image_pad|>", video_token="<|video_pad|>"),
    template_class=ReasoningTemplate,
)


# copied from qwen template
register_template(
    name="qwen3_vl_nothink",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_function=FunctionFormatter(slots=["{{content}}<|im_end|>\n"], tool_format="qwen"),
    format_observation=StringFormatter(
        slots=["<|im_start|>user\n<tool_response>\n{{content}}\n</tool_response><|im_end|>\n<|im_start|>assistant\n"]
    ),
    format_tools=ToolFormatter(tool_format="qwen"),
    stop_words=["<|im_end|>"],
    replace_eos=True,
    mm_plugin=get_mm_plugin(name="qwen3_vl", image_token="<|image_pad|>", video_token="<|video_pad|>"),
)


chenych's avatar
chenych committed
2066
register_template(
chenych's avatar
chenych committed
2067
2068
    name="sailor",
    format_user=StringFormatter(slots=["<|im_start|>question\n{{content}}<|im_end|>\n<|im_start|>answer\n"]),
luopl's avatar
luopl committed
2069
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
2070
2071
2072
2073
2074
2075
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    default_system=(
        "You are an AI assistant named Sailor created by Sea AI Lab. "
        "Your answer should be friendly, unbiased, faithful, informative and detailed."
    ),
    stop_words=["<|im_end|>"],
luopl's avatar
luopl committed
2076
2077
2078
)


chenych's avatar
chenych committed
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
register_template(
    name="seed_coder",
    format_user=StringFormatter(
        slots=[{"bos_token"}, "user\n{{content}}", {"eos_token"}, {"bos_token"}, "assistant\n"]
    ),
    format_system=StringFormatter(slots=[{"bos_token"}, "system\n{{content}}", {"eos_token"}]),
    default_system=(
        "You are an AI programming assistant, utilizing the Seed-Coder model, developed by ByteDance Seed, "
        "and you only answer questions related to computer science. For politically sensitive questions, "
        "security and privacy issues, and other non-computer science questions, you will refuse to answer.\n\n"
    ),
)


shihm's avatar
uodata  
shihm committed
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
# copied from seed_coder
register_template(
    name="seed_oss",
    format_user=StringFormatter(
        slots=[{"bos_token"}, "user\n{{content}}", {"eos_token"}, {"bos_token"}, "assistant\n"]
    ),
    format_system=StringFormatter(slots=[{"bos_token"}, "system\n{{content}}", {"eos_token"}]),
    format_function=FunctionFormatter(slots=[{"bos_token"}, "\n{{content}}", {"eos_token"}], tool_format="seed_oss"),
    format_tools=ToolFormatter(tool_format="seed_oss"),
    template_class=ReasoningTemplate,
    thought_words=("<seed:think>", "</seed:think>"),
)


luopl's avatar
luopl committed
2107
# copied from llama3 template
chenych's avatar
chenych committed
2108
register_template(
luopl's avatar
luopl committed
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
    name="skywork_o1",
    format_user=StringFormatter(
        slots=[
            (
                "<|start_header_id|>user<|end_header_id|>\n\n{{content}}<|eot_id|>"
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
    ),
    format_assistant=StringFormatter(slots=["{{content}}<|eot_id|>"]),
    format_system=StringFormatter(slots=["<|start_header_id|>system<|end_header_id|>\n\n{{content}}<|eot_id|>"]),
    format_function=FunctionFormatter(slots=["{{content}}<|eot_id|>"], tool_format="llama3"),
    format_observation=StringFormatter(
        slots=[
            (
                "<|start_header_id|>ipython<|end_header_id|>\n\n{{content}}<|eot_id|>"
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
    ),
    format_tools=ToolFormatter(tool_format="llama3"),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    default_system=(
        "You are Skywork-o1, a thinking model developed by Skywork AI, specializing in solving complex problems "
        "involving mathematics, coding, and logical reasoning through deep thought. When faced with a user's request, "
        "you first engage in a lengthy and in-depth thinking process to explore possible solutions to the problem. "
        "After completing your thoughts, you then provide a detailed explanation of the solution process "
        "in your response."
    ),
    stop_words=["<|eot_id|>", "<|eom_id|>"],
chenych's avatar
chenych committed
2139
2140
2141
)


chenych's avatar
chenych committed
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
register_template(
    name="smollm",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    stop_words=["<|im_end|>"],
)


register_template(
    name="smollm2",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    stop_words=["<|im_end|>"],
    default_system="You are a helpful AI assistant named SmolLM, trained by Hugging Face.",
)


chenych's avatar
chenych committed
2161
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2162
2163
2164
2165
2166
2167
2168
    name="solar",
    format_user=StringFormatter(slots=["### User:\n{{content}}\n\n### Assistant:\n"]),
    format_system=StringFormatter(slots=["### System:\n{{content}}\n\n"]),
    efficient_eos=True,
)


chenych's avatar
chenych committed
2169
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2170
2171
    name="starchat",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|end|>\n<|assistant|>"]),
luopl's avatar
luopl committed
2172
    format_assistant=StringFormatter(slots=["{{content}}<|end|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2173
2174
    format_system=StringFormatter(slots=["<|system|>\n{{content}}<|end|>\n"]),
    stop_words=["<|end|>"],
chenych's avatar
chenych committed
2175
2176
2177
)


chenych's avatar
chenych committed
2178
register_template(
chenych's avatar
chenych committed
2179
2180
2181
    name="telechat",
    format_user=StringFormatter(slots=["<_user>{{content}}<_bot>"]),
    format_system=StringFormatter(slots=["<_system>{{content}}<_end>"]),
luopl's avatar
luopl committed
2182
2183
2184
)


chenych's avatar
chenych committed
2185
register_template(
luopl's avatar
luopl committed
2186
2187
2188
2189
2190
2191
    name="telechat2",
    format_user=StringFormatter(slots=["<_user>{{content}}<_bot>"]),
    format_system=StringFormatter(slots=["<_system>{{content}}"]),
    default_system=(
        "你是中国电信星辰语义大模型,英文名是TeleChat,你是由中电信人工智能科技有限公司和中国电信人工智能研究院(TeleAI)研发的人工智能助手。"
    ),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2192
2193
2194
)


chenych's avatar
chenych committed
2195
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2196
2197
2198
2199
2200
2201
    name="vicuna",
    format_user=StringFormatter(slots=["USER: {{content}} ASSISTANT:"]),
    default_system=(
        "A chat between a curious user and an artificial intelligence assistant. "
        "The assistant gives helpful, detailed, and polite answers to the user's questions."
    ),
luopl's avatar
luopl committed
2202
    replace_jinja_template=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2203
2204
2205
)


chenych's avatar
chenych committed
2206
register_template(
luopl's avatar
luopl committed
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
    name="video_llava",
    format_user=StringFormatter(slots=["USER: {{content}} ASSISTANT:"]),
    default_system=(
        "A chat between a curious user and an artificial intelligence assistant. "
        "The assistant gives helpful, detailed, and polite answers to the user's questions."
    ),
    mm_plugin=get_mm_plugin(name="video_llava", image_token="<image>", video_token="<video>"),
)


chenych's avatar
chenych committed
2217
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
    name="xuanyuan",
    format_user=StringFormatter(slots=["Human: {{content}} Assistant:"]),
    default_system=(
        "以下是用户和人工智能助手之间的对话。用户以Human开头,人工智能助手以Assistant开头,"
        "会对人类提出的问题给出有帮助、高质量、详细和礼貌的回答,并且总是拒绝参与与不道德、"
        "不安全、有争议、政治敏感等相关的话题、问题和指示。\n"
    ),
)


chenych's avatar
chenych committed
2228
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2229
2230
2231
2232
2233
    name="xverse",
    format_user=StringFormatter(slots=["Human: {{content}}\n\nAssistant: "]),
)


chenych's avatar
chenych committed
2234
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2235
2236
    name="yayi",
    format_user=StringFormatter(slots=[{"token": "<|Human|>"}, ":\n{{content}}\n\n", {"token": "<|YaYi|>"}, ":"]),
luopl's avatar
luopl committed
2237
    format_assistant=StringFormatter(slots=["{{content}}\n\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
    format_system=StringFormatter(slots=[{"token": "<|System|>"}, ":\n{{content}}\n\n"]),
    default_system=(
        "You are a helpful, respectful and honest assistant named YaYi "
        "developed by Beijing Wenge Technology Co.,Ltd. "
        "Always answer as helpfully as possible, while being safe.  "
        "Your answers should not include any harmful, unethical, "
        "racist, sexist, toxic, dangerous, or illegal content. "
        "Please ensure that your responses are socially unbiased and positive in nature.\n\n"
        "If a question does not make any sense, or is not factually coherent, "
        "explain why instead of answering something not correct. "
        "If you don't know the answer to a question, please don't share false information."
    ),
    stop_words=["<|End|>"],
)


luopl's avatar
luopl committed
2254
# copied from chatml template
chenych's avatar
chenych committed
2255
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2256
2257
    name="yi",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
luopl's avatar
luopl committed
2258
    format_assistant=StringFormatter(slots=["{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
2259
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2260
2261
2262
2263
    stop_words=["<|im_end|>"],
)


chenych's avatar
chenych committed
2264
register_template(
chenych's avatar
chenych committed
2265
2266
    name="yi_vl",
    format_user=StringFormatter(slots=["### Human: {{content}}\n### Assistant:"]),
luopl's avatar
luopl committed
2267
    format_assistant=StringFormatter(slots=["{{content}}\n"]),
chenych's avatar
chenych committed
2268
2269
2270
2271
2272
2273
2274
2275
2276
    default_system=(
        "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助手的角色。"
        "仔细阅读所有的图像,并对人类的问题做出信息丰富、有帮助、详细的和礼貌的回答。\n\n"
    ),
    stop_words=["###"],
    efficient_eos=True,
luopl's avatar
luopl committed
2277
    mm_plugin=get_mm_plugin(name="llava", image_token="<image>"),
chenych's avatar
chenych committed
2278
2279
2280
)


chenych's avatar
chenych committed
2281
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2282
2283
    name="yuan",
    format_user=StringFormatter(slots=["{{content}}", {"token": "<sep>"}]),
luopl's avatar
luopl committed
2284
    format_assistant=StringFormatter(slots=["{{content}}<eod>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2285
2286
2287
2288
    stop_words=["<eod>"],
)


chenych's avatar
chenych committed
2289
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2290
    name="zephyr",
chenych's avatar
chenych committed
2291
    format_user=StringFormatter(slots=["<|user|>\n{{content}}", {"eos_token"}, "<|assistant|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2292
    format_system=StringFormatter(slots=["<|system|>\n{{content}}", {"eos_token"}]),
chenych's avatar
chenych committed
2293
    default_system="You are Zephyr, a helpful assistant.",
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2294
2295
2296
)


chenych's avatar
chenych committed
2297
register_template(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2298
2299
    name="ziya",
    format_user=StringFormatter(slots=["<human>:{{content}}\n<bot>:"]),
luopl's avatar
luopl committed
2300
    format_assistant=StringFormatter(slots=["{{content}}\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
2301
)