test_template.py 7.91 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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.

import os
luopl's avatar
luopl committed
16
from typing import TYPE_CHECKING, Sequence
chenych's avatar
chenych committed
17
18
19
20
21

import pytest
from transformers import AutoTokenizer

from llamafactory.data import get_template_and_fix_tokenizer
luopl's avatar
luopl committed
22
23
from llamafactory.data.template import _get_jinja_template
from llamafactory.hparams import DataArguments
chenych's avatar
chenych committed
24
25
26
27
28
29


if TYPE_CHECKING:
    from transformers import PreTrainedTokenizer


luopl's avatar
luopl committed
30
HF_TOKEN = os.getenv("HF_TOKEN")
chenych's avatar
chenych committed
31

luopl's avatar
luopl committed
32
TINY_LLAMA = os.getenv("TINY_LLAMA", "llamafactory/tiny-random-Llama-3")
chenych's avatar
chenych committed
33
34
35
36
37
38
39
40
41
42
43
44

MESSAGES = [
    {"role": "user", "content": "How are you"},
    {"role": "assistant", "content": "I am fine!"},
    {"role": "user", "content": "你好"},
    {"role": "assistant", "content": "很高兴认识你!"},
]


def _check_tokenization(
    tokenizer: "PreTrainedTokenizer", batch_input_ids: Sequence[Sequence[int]], batch_text: Sequence[str]
) -> None:
luopl's avatar
luopl committed
45
46
47
48
49
50
    r"""
    Checks token ids and texts.

    encode(text) == token_ids
    decode(token_ids) == text
    """
chenych's avatar
chenych committed
51
    for input_ids, text in zip(batch_input_ids, batch_text):
luopl's avatar
luopl committed
52
        assert tokenizer.encode(text, add_special_tokens=False) == input_ids
chenych's avatar
chenych committed
53
54
55
        assert tokenizer.decode(input_ids) == text


luopl's avatar
luopl committed
56
57
58
def _check_template(model_id: str, template_name: str, prompt_str: str, answer_str: str, use_fast: bool) -> None:
    r"""
    Checks template.
chenych's avatar
chenych committed
59
60
61
62
63
64

    Args:
        model_id: the model id on hugging face hub.
        template_name: the template name.
        prompt_str: the string corresponding to the prompt part.
        answer_str: the string corresponding to the answer part.
luopl's avatar
luopl committed
65
        use_fast: whether to use fast tokenizer.
chenych's avatar
chenych committed
66
    """
luopl's avatar
luopl committed
67
68
69
70
71
72
73
74
    tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=use_fast, token=HF_TOKEN)
    content_str = tokenizer.apply_chat_template(MESSAGES, tokenize=False)
    content_ids = tokenizer.apply_chat_template(MESSAGES, tokenize=True)
    template = get_template_and_fix_tokenizer(tokenizer, DataArguments(template=template_name))
    prompt_ids, answer_ids = template.encode_oneturn(tokenizer, MESSAGES)
    assert content_str == prompt_str + answer_str
    assert content_ids == prompt_ids + answer_ids
    _check_tokenization(tokenizer, (prompt_ids, answer_ids), (prompt_str, answer_str))
chenych's avatar
chenych committed
75
76
77
78
79


@pytest.mark.parametrize("use_fast", [True, False])
def test_encode_oneturn(use_fast: bool):
    tokenizer = AutoTokenizer.from_pretrained(TINY_LLAMA, use_fast=use_fast)
luopl's avatar
luopl committed
80
    template = get_template_and_fix_tokenizer(tokenizer, DataArguments(template="llama3"))
chenych's avatar
chenych committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    prompt_ids, answer_ids = template.encode_oneturn(tokenizer, MESSAGES)
    prompt_str = (
        "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nHow are you<|eot_id|>"
        "<|start_header_id|>assistant<|end_header_id|>\n\nI am fine!<|eot_id|>"
        "<|start_header_id|>user<|end_header_id|>\n\n你好<|eot_id|>"
        "<|start_header_id|>assistant<|end_header_id|>\n\n"
    )
    answer_str = "很高兴认识你!<|eot_id|>"
    _check_tokenization(tokenizer, (prompt_ids, answer_ids), (prompt_str, answer_str))


@pytest.mark.parametrize("use_fast", [True, False])
def test_encode_multiturn(use_fast: bool):
    tokenizer = AutoTokenizer.from_pretrained(TINY_LLAMA, use_fast=use_fast)
luopl's avatar
luopl committed
95
    template = get_template_and_fix_tokenizer(tokenizer, DataArguments(template="llama3"))
chenych's avatar
chenych committed
96
97
98
99
100
101
102
    encoded_pairs = template.encode_multiturn(tokenizer, MESSAGES)
    prompt_str_1 = (
        "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nHow are you<|eot_id|>"
        "<|start_header_id|>assistant<|end_header_id|>\n\n"
    )
    answer_str_1 = "I am fine!<|eot_id|>"
    prompt_str_2 = (
luopl's avatar
luopl committed
103
        "<|start_header_id|>user<|end_header_id|>\n\n你好<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
chenych's avatar
chenych committed
104
105
106
107
108
109
110
111
112
113
114
115
116
    )
    answer_str_2 = "很高兴认识你!<|eot_id|>"
    _check_tokenization(
        tokenizer,
        (encoded_pairs[0][0], encoded_pairs[0][1], encoded_pairs[1][0], encoded_pairs[1][1]),
        (prompt_str_1, answer_str_1, prompt_str_2, answer_str_2),
    )


@pytest.mark.parametrize("use_fast", [True, False])
def test_jinja_template(use_fast: bool):
    tokenizer = AutoTokenizer.from_pretrained(TINY_LLAMA, use_fast=use_fast)
    ref_tokenizer = AutoTokenizer.from_pretrained(TINY_LLAMA, use_fast=use_fast)
luopl's avatar
luopl committed
117
118
    template = get_template_and_fix_tokenizer(tokenizer, DataArguments(template="llama3"))
    tokenizer.chat_template = _get_jinja_template(template, tokenizer)  # llama3 template no replace
chenych's avatar
chenych committed
119
120
121
122
    assert tokenizer.chat_template != ref_tokenizer.chat_template
    assert tokenizer.apply_chat_template(MESSAGES) == ref_tokenizer.apply_chat_template(MESSAGES)


luopl's avatar
luopl committed
123
124
125
126
127
128
def test_get_stop_token_ids():
    tokenizer = AutoTokenizer.from_pretrained(TINY_LLAMA)
    template = get_template_and_fix_tokenizer(tokenizer, DataArguments(template="llama3"))
    assert set(template.get_stop_token_ids(tokenizer)) == {128008, 128009}


chenych's avatar
chenych committed
129
@pytest.mark.skipif(not HF_TOKEN, reason="Gated model.")
luopl's avatar
luopl committed
130
131
@pytest.mark.parametrize("use_fast", [True, False])
def test_gemma_template(use_fast: bool):
chenych's avatar
chenych committed
132
133
134
135
136
137
    prompt_str = (
        "<bos><start_of_turn>user\nHow are you<end_of_turn>\n"
        "<start_of_turn>model\nI am fine!<end_of_turn>\n"
        "<start_of_turn>user\n你好<end_of_turn>\n"
        "<start_of_turn>model\n"
    )
luopl's avatar
luopl committed
138
139
    answer_str = "很高兴认识你!<end_of_turn>\n"
    _check_template("google/gemma-2-9b-it", "gemma", prompt_str, answer_str, use_fast)
chenych's avatar
chenych committed
140
141
142


@pytest.mark.skipif(not HF_TOKEN, reason="Gated model.")
luopl's avatar
luopl committed
143
144
@pytest.mark.parametrize("use_fast", [True, False])
def test_llama3_template(use_fast: bool):
chenych's avatar
chenych committed
145
146
147
148
149
150
151
    prompt_str = (
        "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\n\nHow are you<|eot_id|>"
        "<|start_header_id|>assistant<|end_header_id|>\n\nI am fine!<|eot_id|>"
        "<|start_header_id|>user<|end_header_id|>\n\n你好<|eot_id|>"
        "<|start_header_id|>assistant<|end_header_id|>\n\n"
    )
    answer_str = "很高兴认识你!<|eot_id|>"
luopl's avatar
luopl committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    _check_template("meta-llama/Meta-Llama-3-8B-Instruct", "llama3", prompt_str, answer_str, use_fast)


@pytest.mark.parametrize(
    "use_fast", [True, pytest.param(False, marks=pytest.mark.xfail(reason="Phi-4 slow tokenizer is broken."))]
)
def test_phi4_template(use_fast: bool):
    prompt_str = (
        "<|im_start|>user<|im_sep|>How are you<|im_end|>"
        "<|im_start|>assistant<|im_sep|>I am fine!<|im_end|>"
        "<|im_start|>user<|im_sep|>你好<|im_end|>"
        "<|im_start|>assistant<|im_sep|>"
    )
    answer_str = "很高兴认识你!<|im_end|>"
    _check_template("microsoft/phi-4", "phi4", prompt_str, answer_str, use_fast)
chenych's avatar
chenych committed
167
168


luopl's avatar
luopl committed
169
170
@pytest.mark.parametrize("use_fast", [True, False])
def test_qwen_template(use_fast: bool):
chenych's avatar
chenych committed
171
172
173
174
175
176
177
    prompt_str = (
        "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n"
        "<|im_start|>user\nHow are you<|im_end|>\n"
        "<|im_start|>assistant\nI am fine!<|im_end|>\n"
        "<|im_start|>user\n你好<|im_end|>\n"
        "<|im_start|>assistant\n"
    )
luopl's avatar
luopl committed
178
179
    answer_str = "很高兴认识你!<|im_end|>\n"
    _check_template("Qwen/Qwen2-7B-Instruct", "qwen", prompt_str, answer_str, use_fast)
chenych's avatar
chenych committed
180
181


luopl's avatar
luopl committed
182
183
184
@pytest.mark.parametrize("use_fast", [True, False])
@pytest.mark.xfail(reason="Yi tokenizer is broken.")
def test_yi_template(use_fast: bool):
chenych's avatar
chenych committed
185
186
187
188
189
190
    prompt_str = (
        "<|im_start|>user\nHow are you<|im_end|>\n"
        "<|im_start|>assistant\nI am fine!<|im_end|>\n"
        "<|im_start|>user\n你好<|im_end|>\n"
        "<|im_start|>assistant\n"
    )
luopl's avatar
luopl committed
191
192
    answer_str = "很高兴认识你!<|im_end|>\n"
    _check_template("01-ai/Yi-1.5-6B-Chat", "yi", prompt_str, answer_str, use_fast)