template.py 32.7 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2024 the LlamaFactory team.
#
# 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.

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
15
16
17
18
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union

from ..extras.logging import get_logger
chenych's avatar
chenych committed
19
from .data_utils import Role
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from .formatter import EmptyFormatter, FunctionFormatter, StringFormatter, ToolFormatter


if TYPE_CHECKING:
    from transformers import PreTrainedTokenizer

    from .formatter import SLOTS, Formatter


logger = get_logger(__name__)


@dataclass
class Template:
    format_user: "Formatter"
    format_assistant: "Formatter"
    format_system: "Formatter"
    format_function: "Formatter"
    format_observation: "Formatter"
    format_tools: "Formatter"
    format_separator: "Formatter"
chenych's avatar
chenych committed
41
    format_prefix: "Formatter"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
42
43
    default_system: str
    stop_words: List[str]
chenych's avatar
chenych committed
44
    image_token: str
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
45
46
47
48
49
50
    efficient_eos: bool
    replace_eos: bool

    def encode_oneturn(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
51
        messages: Sequence[Dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
52
53
54
55
56
57
        system: Optional[str] = None,
        tools: Optional[str] = None,
    ) -> Tuple[List[int], List[int]]:
        r"""
        Returns a single pair of token ids representing prompt and response respectively.
        """
chenych's avatar
chenych committed
58
        encoded_messages = self._encode(tokenizer, messages, system, tools)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
59
        prompt_ids = []
chenych's avatar
chenych committed
60
61
62
63
        for encoded_ids in encoded_messages[:-1]:
            prompt_ids += encoded_ids

        answer_ids = encoded_messages[-1]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
64
65
66
67
68
        return prompt_ids, answer_ids

    def encode_multiturn(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
69
        messages: Sequence[Dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
70
71
        system: Optional[str] = None,
        tools: Optional[str] = None,
chenych's avatar
chenych committed
72
    ) -> List[Tuple[List[int], List[int]]]:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
73
74
75
        r"""
        Returns multiple pairs of token ids representing prompts and responses respectively.
        """
chenych's avatar
chenych committed
76
77
78
79
80
81
82
83
        encoded_messages = self._encode(tokenizer, messages, system, tools)
        return [(encoded_messages[i], encoded_messages[i + 1]) for i in range(0, len(encoded_messages), 2)]

    def extract_tool(self, content: str) -> Union[str, List[Tuple[str, str]]]:
        r"""
        Extracts tool message.
        """
        return self.format_tools.extract(content)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
84
85
86
87

    def _encode(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
88
89
90
91
        messages: Sequence[Dict[str, str]],
        system: Optional[str],
        tools: Optional[str],
    ) -> List[List[int]]:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
92
93
        r"""
        Encodes formatted inputs to pairs of token ids.
chenych's avatar
chenych committed
94
95
        Turn 0: prefix + system + query        resp
        Turn t: sep + query                    resp
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
96
97
98
99
100
        """
        system = system or self.default_system
        encoded_messages = []
        for i, message in enumerate(messages):
            elements = []
chenych's avatar
chenych committed
101
102
103
104
105
106
107
108

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

            if i > 0 and i % 2 == 0:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
                elements += self.format_separator.apply()

            if message["role"] == Role.USER.value:
                elements += self.format_user.apply(content=message["content"], idx=str(i // 2))
            elif message["role"] == Role.ASSISTANT.value:
                elements += self.format_assistant.apply(content=message["content"])
            elif message["role"] == Role.OBSERVATION.value:
                elements += self.format_observation.apply(content=message["content"])
            elif message["role"] == Role.FUNCTION.value:
                elements += self.format_function.apply(content=message["content"])
            else:
                raise NotImplementedError("Unexpected role: {}".format(message["role"]))

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

chenych's avatar
chenych committed
124
        return encoded_messages
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
125

chenych's avatar
chenych committed
126
    def _convert_elements_to_ids(self, tokenizer: "PreTrainedTokenizer", elements: "SLOTS") -> List[int]:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
        r"""
        Converts elements to token ids.
        """
        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("Input must be string, set[str] or dict[str, str], got {}".format(type(elem)))

        return token_ids


@dataclass
class Llama2Template(Template):
    def _encode(
        self,
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
153
        messages: Sequence[Dict[str, str]],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
154
155
        system: str,
        tools: str,
chenych's avatar
chenych committed
156
    ) -> List[List[int]]:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
157
158
        r"""
        Encodes formatted inputs to pairs of token ids.
chenych's avatar
chenych committed
159
160
        Turn 0: prefix + system + query        resp
        Turn t: sep + query                    resp
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
161
162
163
164
165
        """
        system = system or self.default_system
        encoded_messages = []
        for i, message in enumerate(messages):
            elements = []
chenych's avatar
chenych committed
166

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
167
            system_text = ""
chenych's avatar
chenych committed
168
169
170
171
172
173
174
            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]

            if i > 0 and i % 2 == 0:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
                elements += self.format_separator.apply()

            if message["role"] == Role.USER.value:
                elements += self.format_user.apply(content=system_text + message["content"])
            elif message["role"] == Role.ASSISTANT.value:
                elements += self.format_assistant.apply(content=message["content"])
            elif message["role"] == Role.OBSERVATION.value:
                elements += self.format_observation.apply(content=message["content"])
            elif message["role"] == Role.FUNCTION.value:
                elements += self.format_function.apply(content=message["content"])
            else:
                raise NotImplementedError("Unexpected role: {}".format(message["role"]))

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

chenych's avatar
chenych committed
190
        return encoded_messages
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
191
192


chenych's avatar
chenych committed
193
TEMPLATES: Dict[str, Template] = {}
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
194
195
196
197
198
199
200
201
202
203
204


def _register_template(
    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,
    format_separator: Optional["Formatter"] = None,
chenych's avatar
chenych committed
205
    format_prefix: Optional["Formatter"] = None,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
206
    default_system: str = "",
chenych's avatar
chenych committed
207
208
    stop_words: Sequence[str] = [],
    image_token: str = "<image>",
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    efficient_eos: bool = False,
    replace_eos: bool = False,
) -> None:
    r"""
    Registers a chat template.

    To add the following chat template:
    ```
    [HUMAN]:
    user prompt here
    [AI]:
    model response here

    [HUMAN]:
    user prompt here
    [AI]:
    model response here
    ```

    The corresponding code should be:
    ```
    _register_template(
        name="custom",
        format_user=StringFormatter(slots=["[HUMAN]:\n{{content}}\n[AI]:\n"]),
        format_separator=EmptyFormatter(slots=["\n\n"]),
        efficient_eos=True,
    )
    ```
    """
    eos_slots = [] if efficient_eos else [{"eos_token"}]
    template_class = Llama2Template if name.startswith("llama2") else Template
    default_user_formatter = StringFormatter(slots=["{{content}}"])
    default_assistant_formatter = StringFormatter(slots=["{{content}}"] + eos_slots)
chenych's avatar
chenych committed
242
    default_function_formatter = FunctionFormatter(slots=eos_slots, tool_format="default")
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
243
244
    default_tool_formatter = ToolFormatter(tool_format="default")
    default_separator_formatter = EmptyFormatter()
chenych's avatar
chenych committed
245
246
    default_prefix_formatter = EmptyFormatter()
    TEMPLATES[name] = template_class(
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
247
248
249
250
251
252
253
        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,
        format_separator=format_separator or default_separator_formatter,
chenych's avatar
chenych committed
254
        format_prefix=format_prefix or default_prefix_formatter,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
255
256
        default_system=default_system,
        stop_words=stop_words,
chenych's avatar
chenych committed
257
        image_token=image_token,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        efficient_eos=efficient_eos,
        replace_eos=replace_eos,
    )


def _add_or_replace_eos_token(tokenizer: "PreTrainedTokenizer", eos_token: str) -> None:
    is_added = tokenizer.eos_token_id is None
    num_added_tokens = tokenizer.add_special_tokens({"eos_token": eos_token})

    if is_added:
        logger.info("Add eos token: {}".format(tokenizer.eos_token))
    else:
        logger.info("Replace eos token: {}".format(tokenizer.eos_token))

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


def _jinja_escape(content: str) -> str:
chenych's avatar
chenych committed
277
    return content.replace("'", r"\'")
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
278
279
280
281
282
283
284
285
286
287
288
289
290


def _convert_slots_to_jinja(slots: "SLOTS", tokenizer: "PreTrainedTokenizer", placeholder: str = "content") -> str:
    slot_items = []
    for slot in slots:
        if isinstance(slot, str):
            slot_pieces = slot.split("{{content}}")
            if slot_pieces[0]:
                slot_items.append("'" + _jinja_escape(slot_pieces[0]) + "'")
            if len(slot_pieces) > 1:
                slot_items.append(placeholder)
                if slot_pieces[1]:
                    slot_items.append("'" + _jinja_escape(slot_pieces[1]) + "'")
chenych's avatar
chenych committed
291
292
        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:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
293
                slot_items.append("'" + tokenizer.bos_token + "'")
chenych's avatar
chenych committed
294
            elif "eos_token" in slot and tokenizer.eos_token_id is not None:
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
295
296
297
298
299
300
301
302
303
304
                slot_items.append("'" + tokenizer.eos_token + "'")
        elif isinstance(slot, dict):
            raise ValueError("Dict is not supported.")

    return " + ".join(slot_items)


def _get_jinja_template(template: "Template", tokenizer: "PreTrainedTokenizer") -> str:
    jinja_template = ""

chenych's avatar
chenych committed
305
306
307
308
    prefix = _convert_slots_to_jinja(template.format_prefix.apply(), tokenizer)
    if prefix:
        jinja_template += "{{ " + prefix + " }}"

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
309
310
311
312
    if template.default_system:
        jinja_template += "{% set system_message = '" + _jinja_escape(template.default_system) + "' %}"

    jinja_template += (
chenych's avatar
chenych committed
313
        "{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{% endif %}"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
314
315
316
    )

    system_message = _convert_slots_to_jinja(template.format_system.apply(), tokenizer, placeholder="system_message")
chenych's avatar
chenych committed
317
    if not isinstance(template, Llama2Template):
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
318
319
        jinja_template += "{% if system_message is defined %}{{ " + system_message + " }}{% endif %}"

chenych's avatar
chenych committed
320
    jinja_template += "{% for message in messages %}"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
321
322
323
324
325
    jinja_template += "{% set content = message['content'] %}"
    if isinstance(template, Llama2Template):
        jinja_template += "{% if loop.index0 == 0 and system_message is defined %}"
        jinja_template += "{% set content = " + system_message + " + message['content'] %}"
        jinja_template += "{% endif %}"
chenych's avatar
chenych committed
326

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
327
328
329
    jinja_template += "{% if message['role'] == 'user' %}"
    user_message = _convert_slots_to_jinja(template.format_user.apply(), tokenizer)
    jinja_template += "{{ " + user_message + " }}"
chenych's avatar
chenych committed
330

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
331
332
333
334
335
336
337
338
339
340
341
342
343
    jinja_template += "{% elif message['role'] == 'assistant' %}"
    assistant_message = _convert_slots_to_jinja(
        template.format_assistant.apply() + template.format_separator.apply(), tokenizer
    )
    jinja_template += "{{ " + assistant_message + " }}"
    jinja_template += "{% endif %}"
    jinja_template += "{% endfor %}"
    return jinja_template


def get_template_and_fix_tokenizer(
    tokenizer: "PreTrainedTokenizer",
    name: Optional[str] = None,
chenych's avatar
chenych committed
344
    tool_format: Optional[str] = None,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
345
346
) -> Template:
    if name is None:
chenych's avatar
chenych committed
347
        template = TEMPLATES["empty"]  # placeholder
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
348
    else:
chenych's avatar
chenych committed
349
        template = TEMPLATES.get(name, None)
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
350
351
352
        if template is None:
            raise ValueError("Template {} does not exist.".format(name))

chenych's avatar
chenych committed
353
354
355
356
357
358
    if tool_format is not None:
        logger.info("Using tool format: {}.".format(tool_format))
        eos_slots = [] if template.efficient_eos else [{"eos_token"}]
        template.format_tools = ToolFormatter(tool_format=tool_format)
        template.format_function = FunctionFormatter(slots=eos_slots, tool_format=tool_format)

Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
    stop_words = template.stop_words
    if template.replace_eos:
        if not stop_words:
            raise ValueError("Stop words are required to replace the EOS token.")

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

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

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

    if stop_words:
        num_added_tokens = tokenizer.add_special_tokens(
            dict(additional_special_tokens=stop_words), replace_additional_special_tokens=False
        )
        logger.info("Add {} to stop words.".format(",".join(stop_words)))
        if num_added_tokens > 0:
            logger.warning("New tokens have been added, make sure `resize_vocab` is True.")

    try:
        tokenizer.chat_template = _get_jinja_template(template, tokenizer)
    except ValueError:
        logger.info("Cannot add this chat template to tokenizer.")

    return template


_register_template(
    name="alpaca",
    format_user=StringFormatter(slots=["### Instruction:\n{{content}}\n\n### Response:\n"]),
    format_separator=EmptyFormatter(slots=["\n\n"]),
    default_system=(
        "Below is an instruction that describes a task. "
        "Write a response that appropriately completes the request.\n\n"
    ),
)


_register_template(
    name="aquila",
    format_user=StringFormatter(slots=["Human: {{content}}###Assistant:"]),
    format_separator=EmptyFormatter(slots=["###"]),
    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>"],
    efficient_eos=True,
)


_register_template(
    name="atom",
    format_user=StringFormatter(
        slots=[{"bos_token"}, "Human: {{content}}\n", {"eos_token"}, {"bos_token"}, "Assistant:"]
    ),
    format_assistant=StringFormatter(slots=["{{content}}\n", {"eos_token"}]),
)


_register_template(
    name="baichuan",
    format_user=StringFormatter(slots=[{"token": "<reserved_102>"}, "{{content}}", {"token": "<reserved_103>"}]),
    efficient_eos=True,
)


_register_template(
    name="baichuan2",
    format_user=StringFormatter(slots=["<reserved_106>{{content}}<reserved_107>"]),
    efficient_eos=True,
)


_register_template(
    name="belle",
    format_user=StringFormatter(slots=["Human: {{content}}\n\nBelle: "]),
    format_separator=EmptyFormatter(slots=["\n\n"]),
chenych's avatar
chenych committed
441
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
442
443
444
445
446
447
448
449
450
451
452
453
)


_register_template(
    name="bluelm",
    format_user=StringFormatter(slots=[{"token": "[|Human|]:"}, "{{content}}", {"token": "[|AI|]:"}]),
)


_register_template(
    name="breeze",
    format_user=StringFormatter(slots=["[INST] {{content}} [/INST] "]),
chenych's avatar
chenych committed
454
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
455
456
457
458
459
460
461
462
    efficient_eos=True,
)


_register_template(
    name="chatglm2",
    format_user=StringFormatter(slots=["[Round {{idx}}]\n\n问:{{content}}\n\n答:"]),
    format_separator=EmptyFormatter(slots=["\n\n"]),
chenych's avatar
chenych committed
463
    format_prefix=EmptyFormatter(slots=[{"token": "[gMASK]"}, {"token": "sop"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
464
465
466
467
468
469
470
471
    efficient_eos=True,
)


_register_template(
    name="chatglm3",
    format_user=StringFormatter(slots=[{"token": "<|user|>"}, "\n", "{{content}}", {"token": "<|assistant|>"}]),
    format_assistant=StringFormatter(slots=["\n", "{{content}}"]),
chenych's avatar
chenych committed
472
473
    format_system=StringFormatter(slots=[{"token": "<|system|>"}, "\n", "{{content}}"]),
    format_function=FunctionFormatter(slots=[], tool_format="glm4"),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
474
475
476
    format_observation=StringFormatter(
        slots=[{"token": "<|observation|>"}, "\n", "{{content}}", {"token": "<|assistant|>"}]
    ),
chenych's avatar
chenych committed
477
478
    format_tools=ToolFormatter(tool_format="glm4"),
    format_prefix=EmptyFormatter(slots=[{"token": "[gMASK]"}, {"token": "sop"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
479
480
481
482
483
484
485
486
487
    stop_words=["<|user|>", "<|observation|>"],
    efficient_eos=True,
)


_register_template(
    name="chatml",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
488
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
489
490
491
492
493
494
495
496
497
498
    format_separator=EmptyFormatter(slots=["\n"]),
    stop_words=["<|im_end|>", "<|im_start|>"],
    replace_eos=True,
)


_register_template(
    name="chatml_de",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
499
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
500
501
502
503
504
505
506
507
508
    format_separator=EmptyFormatter(slots=["\n"]),
    default_system="Du bist ein freundlicher und hilfsbereiter KI-Assistent.",
    stop_words=["<|im_end|>", "<|im_start|>"],
    replace_eos=True,
)


_register_template(
    name="codegeex2",
chenych's avatar
chenych committed
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
    format_prefix=EmptyFormatter(slots=[{"token": "[gMASK]"}, {"token": "sop"}]),
)


_register_template(
    name="codegeex4",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>\n"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}"]),
    format_function=FunctionFormatter(slots=[], tool_format="glm4"),
    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
527
528
529
530
531
532
533
534
535
536
537
538
539
)


_register_template(
    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
540
541
    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
542
543
544
545
546
547
)


_register_template(
    name="cpm",
    format_user=StringFormatter(slots=["<用户>{{content}}<AI>"]),
chenych's avatar
chenych committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)


_register_template(
    name="dbrx",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\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_separator=EmptyFormatter(slots=["\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|>"],
    replace_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
575
576
577
578
579
580
)


_register_template(
    name="deepseek",
    format_user=StringFormatter(slots=["User: {{content}}\n\nAssistant:"]),
chenych's avatar
chenych committed
581
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
582
583
584
585
586
587
)


_register_template(
    name="deepseekcoder",
    format_user=StringFormatter(slots=["### Instruction:\n{{content}}\n### Response:"]),
chenych's avatar
chenych committed
588
    format_assistant=StringFormatter(slots=["\n{{content}}\n"]),
chenych's avatar
chenych committed
589
590
    format_separator=EmptyFormatter(slots=["\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
591
    default_system=(
chenych's avatar
chenych committed
592
593
        "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
594
        "For politically sensitive questions, security and privacy issues, "
chenych's avatar
chenych committed
595
        "and other non-computer science questions, you will refuse to answer\n"
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
596
597
598
599
600
601
    ),
)


_register_template(
    name="default",
chenych's avatar
chenych committed
602
    format_user=StringFormatter(slots=["Human: {{content}}\nAssistant:"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
603
604
605
606
607
608
609
    format_system=StringFormatter(slots=["{{content}}\n"]),
    format_separator=EmptyFormatter(slots=["\n"]),
)


_register_template(
    name="empty",
chenych's avatar
chenych committed
610
    efficient_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
)


_register_template(
    name="falcon",
    format_user=StringFormatter(slots=["User: {{content}}\nFalcon:"]),
    format_separator=EmptyFormatter(slots=["\n"]),
    efficient_eos=True,
)


_register_template(
    name="fewshot",
    format_separator=EmptyFormatter(slots=["\n\n"]),
    efficient_eos=True,
)


_register_template(
    name="gemma",
    format_user=StringFormatter(slots=["<start_of_turn>user\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]),
chenych's avatar
chenych committed
632
633
634
    format_observation=StringFormatter(
        slots=["<start_of_turn>tool\n{{content}}<end_of_turn>\n<start_of_turn>model\n"]
    ),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
635
    format_separator=EmptyFormatter(slots=["<end_of_turn>\n"]),
chenych's avatar
chenych committed
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    efficient_eos=True,
)


_register_template(
    name="glm4",
    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=[], 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|>"],
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
651
652
653
654
655
656
    efficient_eos=True,
)


_register_template(
    name="intern",
chenych's avatar
chenych committed
657
658
659
660
    format_user=StringFormatter(slots=["<|User|>:{{content}}\n<|Bot|>:"]),
    format_system=StringFormatter(slots=["<|System|>:{{content}}\n"]),
    format_separator=EmptyFormatter(slots=["<eoa>\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
661
    stop_words=["<eoa>"],
chenych's avatar
chenych committed
662
    efficient_eos=True,  # internlm tokenizer cannot set eos_token_id
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
663
664
665
666
667
668
)


_register_template(
    name="intern2",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
chenych's avatar
chenych committed
669
670
671
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
    format_separator=EmptyFormatter(slots=["<|im_end|>\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
    stop_words=["<|im_end|>"],
    efficient_eos=True,  # internlm2 tokenizer cannot set eos_token_id
)


_register_template(
    name="llama2",
    format_user=StringFormatter(slots=[{"bos_token"}, "[INST] {{content}} [/INST]"]),
    format_system=StringFormatter(slots=["<<SYS>>\n{{content}}\n<</SYS>>\n\n"]),
)


_register_template(
    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. 你是一个乐于助人的助手。",
)


_register_template(
    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"
            )
        ]
    ),
chenych's avatar
chenych committed
702
703
704
705
706
707
708
709
    format_system=StringFormatter(slots=["<|start_header_id|>system<|end_header_id|>\n\n{{content}}<|eot_id|>"]),
    format_observation=StringFormatter(
        slots=[
            (
                "<|start_header_id|>tool<|end_header_id|>\n\n{{content}}<|eot_id|>"
                "<|start_header_id|>assistant<|end_header_id|>\n\n"
            )
        ]
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
710
    ),
chenych's avatar
chenych committed
711
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
712
713
714
715
716
717
718
    stop_words=["<|eot_id|>"],
    replace_eos=True,
)


_register_template(
    name="mistral",
chenych's avatar
chenych committed
719
720
    format_user=StringFormatter(slots=["[INST] {{content}} [/INST]"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
721
722
723
724
725
)


_register_template(
    name="olmo",
chenych's avatar
chenych committed
726
727
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|assistant|>\n"]),
    format_prefix=EmptyFormatter(slots=[{"eos_token"}]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
728
729
730
731
732
733
)


_register_template(
    name="openchat",
    format_user=StringFormatter(slots=["GPT4 Correct User: {{content}}", {"eos_token"}, "GPT4 Correct Assistant:"]),
chenych's avatar
chenych committed
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)


_register_template(
    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|>"],
    replace_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
751
752
753
754
755
756
)


_register_template(
    name="orion",
    format_user=StringFormatter(slots=["Human: {{content}}\n\nAssistant: ", {"eos_token"}]),
chenych's avatar
chenych committed
757
758
759
760
761
762
763
764
765
766
767
768
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
)


_register_template(
    name="phi",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|end|>\n<|assistant|>\n"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}<|end|>\n"]),
    format_separator=EmptyFormatter(slots=["\n"]),
    format_prefix=EmptyFormatter(slots=[{"bos_token"}]),
    stop_words=["<|end|>"],
    replace_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
769
770
771
772
773
774
775
)


_register_template(
    name="qwen",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
chenych's avatar
chenych committed
776
    format_observation=StringFormatter(slots=["<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
    format_separator=EmptyFormatter(slots=["\n"]),
    default_system="You are a helpful assistant.",
    stop_words=["<|im_end|>"],
    replace_eos=True,
)


_register_template(
    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,
)


_register_template(
    name="starchat",
    format_user=StringFormatter(slots=["<|user|>\n{{content}}<|end|>\n<|assistant|>"]),
    format_system=StringFormatter(slots=["<|system|>\n{{content}}<|end|>\n"]),
    format_separator=EmptyFormatter(slots=["\n"]),
    stop_words=["<|end|>"],
    replace_eos=True,
chenych's avatar
chenych committed
799
800
801
802
803
804
805
806
807
)


_register_template(
    name="telechat",
    format_user=StringFormatter(slots=["<_user>{{content}}<_bot>"]),
    format_system=StringFormatter(slots=["<_system>{{content}}<_end>"]),
    stop_words=["<_end>"],
    replace_eos=True,
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
)


_register_template(
    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."
    ),
)


_register_template(
    name="xuanyuan",
    format_user=StringFormatter(slots=["Human: {{content}} Assistant:"]),
    default_system=(
        "以下是用户和人工智能助手之间的对话。用户以Human开头,人工智能助手以Assistant开头,"
        "会对人类提出的问题给出有帮助、高质量、详细和礼貌的回答,并且总是拒绝参与与不道德、"
        "不安全、有争议、政治敏感等相关的话题、问题和指示。\n"
    ),
)


_register_template(
    name="xverse",
    format_user=StringFormatter(slots=["Human: {{content}}\n\nAssistant: "]),
)


_register_template(
    name="yayi",
    format_user=StringFormatter(slots=[{"token": "<|Human|>"}, ":\n{{content}}\n\n", {"token": "<|YaYi|>"}, ":"]),
    format_system=StringFormatter(slots=[{"token": "<|System|>"}, ":\n{{content}}\n\n"]),
    format_separator=EmptyFormatter(slots=["\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|>"],
)


_register_template(
    name="yi",
    format_user=StringFormatter(slots=["<|im_start|>user\n{{content}}<|im_end|>\n<|im_start|>assistant\n"]),
chenych's avatar
chenych committed
861
    format_system=StringFormatter(slots=["<|im_start|>system\n{{content}}<|im_end|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
862
863
864
865
866
867
    format_separator=EmptyFormatter(slots=["\n"]),
    stop_words=["<|im_end|>"],
    replace_eos=True,
)


chenych's avatar
chenych committed
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
_register_template(
    name="yi_vl",
    format_user=StringFormatter(slots=["### Human: {{content}}\n### Assistant:"]),
    format_separator=EmptyFormatter(slots=["\n"]),
    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,
)


Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
884
885
886
887
888
889
890
891
892
893
894
_register_template(
    name="yuan",
    format_user=StringFormatter(slots=["{{content}}", {"token": "<sep>"}]),
    format_separator=EmptyFormatter(slots=["\n"]),
    stop_words=["<eod>"],
    replace_eos=True,
)


_register_template(
    name="zephyr",
chenych's avatar
chenych committed
895
    format_user=StringFormatter(slots=["<|user|>\n{{content}}", {"eos_token"}, "<|assistant|>\n"]),
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
896
    format_system=StringFormatter(slots=["<|system|>\n{{content}}", {"eos_token"}]),
chenych's avatar
chenych committed
897
    default_system="You are Zephyr, a helpful assistant.",
Rayyyyy's avatar
V0.6.3  
Rayyyyy committed
898
899
900
901
902
903
904
905
)


_register_template(
    name="ziya",
    format_user=StringFormatter(slots=["<human>:{{content}}\n<bot>:"]),
    format_separator=EmptyFormatter(slots=["\n"]),
)