test_chat_template.py 3.86 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
4
import pytest

5
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.transformers_utils.tokenizer import get_tokenizer
9

10
from ...utils import VLLM_PATH
11
12

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

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

TEST_MESSAGES = [
    {
        'role': 'user',
        'content': 'Hello'
    },
    {
        'role': 'assistant',
        'content': 'Hi there!'
    },
    {
        'role': 'user',
        'content': 'What is the capital of'
    },
]
55
56
57
58
ASSISTANT_MESSAGE_TO_CONTINUE = {
    'role': 'assistant',
    'content': 'The capital of'
}
59
60


61
def test_load_chat_template():
62
    # Testing chatml template
63
    template_content = load_chat_template(chat_template=chatml_jinja_path)
64
65
66
67
68

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


72
def test_no_load_chat_template_filelike():
73
74
    # Testing chatml template
    template = "../../examples/does_not_exist"
75
76

    with pytest.raises(ValueError, match="looks like a file path"):
77
        load_chat_template(chat_template=template)
78
79


80
def test_no_load_chat_template_literallike():
81
82
83
    # Testing chatml template
    template = "{{ messages }}"

84
    template_content = load_chat_template(chat_template=template)
85

86
    assert template_content == template
87
88
89


@pytest.mark.parametrize(
90
    "model,template,add_generation_prompt,continue_final_message,expected_output",
91
    MODEL_TEMPLATE_GENERATON_OUTPUT)
92
def test_get_gen_prompt(model, template, add_generation_prompt,
93
                        continue_final_message, expected_output):
94
95
    # Initialize the tokenizer
    tokenizer = get_tokenizer(tokenizer_name=model)
96
    template_content = load_chat_template(chat_template=template)
97
98
99
100

    # Create a mock request object using keyword arguments
    mock_request = ChatCompletionRequest(
        model=model,
101
102
103
104
105
        messages=TEST_MESSAGES + [ASSISTANT_MESSAGE_TO_CONTINUE]
        if continue_final_message else TEST_MESSAGES,
        add_generation_prompt=add_generation_prompt,
        continue_final_message=continue_final_message,
    )
106
107

    # Call the function and get the result
108
    result = apply_hf_chat_template(
109
        tokenizer,
110
        trust_remote_code=True,
111
        conversation=mock_request.messages,
112
        chat_template=mock_request.chat_template or template_content,
113
        tools=None,
114
        add_generation_prompt=mock_request.add_generation_prompt,
115
        continue_final_message=mock_request.continue_final_message,
116
    )
117
118

    # Test assertion
119
120
121
    assert result == expected_output, (
        f"The generated prompt does not match the expected output for "
        f"model {model} and template {template}")