test_chat_template.py 3.38 KB
Newer Older
Simon Mo's avatar
Simon Mo committed
1
2
import os
import pathlib
3
4
5

import pytest

6
from vllm.entrypoints.openai.chat_utils import load_chat_template
7
from vllm.entrypoints.openai.protocol import ChatCompletionRequest
8
from vllm.transformers_utils.tokenizer import get_tokenizer
9

Simon Mo's avatar
Simon Mo committed
10
11
12
13
chatml_jinja_path = pathlib.Path(os.path.dirname(os.path.abspath(
    __file__))).parent.parent / "examples/template_chatml.jinja"
assert chatml_jinja_path.exists()

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

TEST_MESSAGES = [
    {
        'role': 'user',
        'content': 'Hello'
    },
    {
        'role': 'assistant',
        'content': 'Hi there!'
    },
    {
        'role': 'user',
        'content': 'What is the capital of'
    },
]


52
def test_load_chat_template():
53
    # Testing chatml template
54
    template_content = load_chat_template(chat_template=chatml_jinja_path)
55
56
57
58
59

    # 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 %}
60
{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}{{ '<|im_start|>assistant\\n' }}{% endif %}"""  # noqa: E501
61
62


63
def test_no_load_chat_template_filelike():
64
65
    # Testing chatml template
    template = "../../examples/does_not_exist"
66
67

    with pytest.raises(ValueError, match="looks like a file path"):
68
        load_chat_template(chat_template=template)
69
70


71
def test_no_load_chat_template_literallike():
72
73
74
    # Testing chatml template
    template = "{{ messages }}"

75
    template_content = load_chat_template(chat_template=template)
76

77
    assert template_content == template
78
79
80
81
82


@pytest.mark.parametrize(
    "model,template,add_generation_prompt,expected_output",
    MODEL_TEMPLATE_GENERATON_OUTPUT)
83
84
def test_get_gen_prompt(model, template, add_generation_prompt,
                        expected_output):
85
86
    # Initialize the tokenizer
    tokenizer = get_tokenizer(tokenizer_name=model)
87
    template_content = load_chat_template(chat_template=template)
88
89
90
91
92
93
94
95
96
97
98

    # Create a mock request object using keyword arguments
    mock_request = ChatCompletionRequest(
        model=model,
        messages=TEST_MESSAGES,
        add_generation_prompt=add_generation_prompt)

    # Call the function and get the result
    result = tokenizer.apply_chat_template(
        conversation=mock_request.messages,
        tokenize=False,
99
100
        add_generation_prompt=mock_request.add_generation_prompt,
        chat_template=mock_request.chat_template or template_content)
101
102

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