test_chat_template.py 4.24 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.entrypoints.chat_utils import apply_hf_chat_template, load_chat_template
7
from vllm.entrypoints.openai.protocol import ChatCompletionRequest
8
from vllm.tokenizers import get_tokenizer
9

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

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

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

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


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

    # Test assertions
    assert template_content is not None
    # Hard coded value for template_chatml.jinja
75
76
77
    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 %}
78
79
{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}{{ '<|im_start|>assistant\\n' }}{% endif %}"""  # noqa: E501
    )
80
81


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

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


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

94
    template_content = load_chat_template(chat_template=template)
95

96
    assert template_content == template
97
98
99


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

109
    renderer_config = model_info.build_renderer_config(model)
110
111

    tokenizer = get_tokenizer(
112
113
        renderer_config.tokenizer,
        trust_remote_code=renderer_config.trust_remote_code,
114
    )
115
    template_content = load_chat_template(chat_template=template)
116
117
118
119

    # Create a mock request object using keyword arguments
    mock_request = ChatCompletionRequest(
        model=model,
120
        messages=TEST_MESSAGES + [ASSISTANT_MESSAGE_TO_CONTINUE]
121
122
        if continue_final_message
        else TEST_MESSAGES,
123
124
125
        add_generation_prompt=add_generation_prompt,
        continue_final_message=continue_final_message,
    )
126
127

    # Call the function and get the result
128
    result = apply_hf_chat_template(
129
        tokenizer=tokenizer,
130
        conversation=mock_request.messages,
131
        chat_template=mock_request.chat_template or template_content,
132
        renderer_config=renderer_config,
133
        tools=None,
134
        add_generation_prompt=mock_request.add_generation_prompt,
135
        continue_final_message=mock_request.continue_final_message,
136
    )
137
138

    # Test assertion
139
140
    assert result == expected_output, (
        f"The generated prompt does not match the expected output for "
141
142
        f"model {model} and template {template}"
    )