test_chat_template.py 4.81 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
import pytest

6
from vllm.config import ModelConfig
7
from vllm.entrypoints.chat_utils import apply_hf_chat_template, load_chat_template
8
from vllm.entrypoints.openai.protocol import ChatCompletionRequest
9
from vllm.transformers_utils.tokenizer import get_tokenizer
10

11
from ...models.registry import HF_EXAMPLE_MODELS
12
from ...utils import VLLM_PATH
13
14

chatml_jinja_path = VLLM_PATH / "examples/template_chatml.jinja"
Simon Mo's avatar
Simon Mo committed
15
16
assert chatml_jinja_path.exists()

17
# Define models, templates, and their corresponding expected outputs
18
MODEL_TEMPLATE_GENERATION_OUTPUT = [
19
20
21
22
23
24
    (
        "facebook/opt-125m",
        chatml_jinja_path,
        True,
        False,
        """<|im_start|>user
25
26
27
28
29
30
Hello<|im_end|>
<|im_start|>assistant
Hi there!<|im_end|>
<|im_start|>user
What is the capital of<|im_end|>
<|im_start|>assistant
31
32
33
34
35
36
37
38
""",
    ),
    (
        "facebook/opt-125m",
        chatml_jinja_path,
        False,
        False,
        """<|im_start|>user
39
40
41
42
Hello<|im_end|>
<|im_start|>assistant
Hi there!<|im_end|>
<|im_start|>user
43
44
45
46
47
48
49
50
What is the capital of""",
    ),
    (
        "facebook/opt-125m",
        chatml_jinja_path,
        False,
        True,
        """<|im_start|>user
51
52
53
54
55
56
Hello<|im_end|>
<|im_start|>assistant
Hi there!<|im_end|>
<|im_start|>user
What is the capital of<|im_end|>
<|im_start|>assistant
57
58
The capital of""",
    ),
59
60
61
]

TEST_MESSAGES = [
62
63
64
    {"role": "user", "content": "Hello"},
    {"role": "assistant", "content": "Hi there!"},
    {"role": "user", "content": "What is the capital of"},
65
]
66
ASSISTANT_MESSAGE_TO_CONTINUE = {"role": "assistant", "content": "The capital of"}
67
68


69
def test_load_chat_template():
70
    # Testing chatml template
71
    template_content = load_chat_template(chat_template=chatml_jinja_path)
72
73
74
75

    # Test assertions
    assert template_content is not None
    # Hard coded value for template_chatml.jinja
76
77
78
    assert (
        template_content
        == """{% for message in messages %}{{'<|im_start|>' + message['role'] + '\\n' + message['content']}}{% if (loop.last and add_generation_prompt) or not loop.last %}{{ '<|im_end|>' + '\\n'}}{% endif %}{% endfor %}
79
80
{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}{{ '<|im_start|>assistant\\n' }}{% endif %}"""  # noqa: E501
    )
81
82


83
def test_no_load_chat_template_filelike():
84
85
    # Testing chatml template
    template = "../../examples/does_not_exist"
86
87

    with pytest.raises(ValueError, match="looks like a file path"):
88
        load_chat_template(chat_template=template)
89
90


91
def test_no_load_chat_template_literallike():
92
93
94
    # Testing chatml template
    template = "{{ messages }}"

95
    template_content = load_chat_template(chat_template=template)
96

97
    assert template_content == template
98
99
100


@pytest.mark.parametrize(
101
    "model,template,add_generation_prompt,continue_final_message,expected_output",
102
103
104
105
106
    MODEL_TEMPLATE_GENERATION_OUTPUT,
)
def test_get_gen_prompt(
    model, template, add_generation_prompt, continue_final_message, expected_output
):
107
108
109
110
111
112
113
114
    model_info = HF_EXAMPLE_MODELS.find_hf_info(model)
    model_info.check_available_online(on_fail="skip")

    model_config = ModelConfig(
        model,
        tokenizer=model_info.tokenizer or model,
        tokenizer_mode=model_info.tokenizer_mode,
        trust_remote_code=model_info.trust_remote_code,
115
        revision=model_info.revision,
116
        hf_overrides=model_info.hf_overrides,
117
118
119
        skip_tokenizer_init=model_info.require_embed_inputs,
        enable_prompt_embeds=model_info.require_embed_inputs,
        enable_mm_embeds=model_info.require_embed_inputs,
120
        enforce_eager=model_info.enforce_eager,
121
122
        dtype=model_info.dtype,
    )
123

124
    # Initialize the tokenizer
125
126
127
128
    tokenizer = get_tokenizer(
        tokenizer_name=model_config.tokenizer,
        trust_remote_code=model_config.trust_remote_code,
    )
129
    template_content = load_chat_template(chat_template=template)
130
131
132
133

    # Create a mock request object using keyword arguments
    mock_request = ChatCompletionRequest(
        model=model,
134
        messages=TEST_MESSAGES + [ASSISTANT_MESSAGE_TO_CONTINUE]
135
136
        if continue_final_message
        else TEST_MESSAGES,
137
138
139
        add_generation_prompt=add_generation_prompt,
        continue_final_message=continue_final_message,
    )
140
141

    # Call the function and get the result
142
    result = apply_hf_chat_template(
143
        tokenizer=tokenizer,
144
        conversation=mock_request.messages,
145
        chat_template=mock_request.chat_template or template_content,
146
        model_config=model_config,
147
        tools=None,
148
        add_generation_prompt=mock_request.add_generation_prompt,
149
        continue_final_message=mock_request.continue_final_message,
150
    )
151
152

    # Test assertion
153
154
    assert result == expected_output, (
        f"The generated prompt does not match the expected output for "
155
156
        f"model {model} and template {template}"
    )