"requirements/common.txt" did not exist on "2382ad29d1769f2b46d51fcc2cedbd6e00d4f180"
test_llama_tp.py 7.35 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
zhuwenwen's avatar
zhuwenwen committed
3
import os
4
5
import subprocess
import sys
6

7
import pytest
8
9

import vllm
10
import vllm.config
11
from vllm import LLM
12
from vllm.lora.request import LoRARequest
13
from vllm.model_executor.model_loader.tensorizer import TensorizerConfig
14

zhuwenwen's avatar
zhuwenwen committed
15
from ..utils import VLLM_PATH, create_new_process_for_each_test, multi_gpu_test, models_path_prefix
16

17
18
19
20
21
22
23
24
25
26
27
PROMPT_TEMPLATE = """<|eot_id|><|start_header_id|>user<|end_header_id|>
I want you to act as a SQL terminal in front of an example database, you need only to return the sql command to me.Below is an instruction that describes a task, Write a response that appropriately completes the request.
"
##Instruction:
candidate_poll contains tables such as candidate, people. Table candidate has columns such as Candidate_ID, People_ID, Poll_Source, Date, Support_rate, Consider_rate, Oppose_rate, Unsure_rate. Candidate_ID is the primary key.
Table people has columns such as People_ID, Sex, Name, Date_of_Birth, Height, Weight. People_ID is the primary key.
The People_ID of candidate is the foreign key of People_ID of people.
###Input:
{context}
###Response:<|eot_id|><|start_header_id|>assistant<|end_header_id|>
"""  # noqa: E501
28
29

EXPECTED_LORA_OUTPUT = [
30
31
32
33
    "SELECT count(*) FROM candidate",
    "SELECT count(*) FROM candidate",
    "SELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1",  # noqa: E501
    "SELECT poll_source FROM candidate GROUP BY poll_source ORDER BY count(*) DESC LIMIT 1",  # noqa: E501
34
35
]

36
MODEL_PATH = os.path.join(models_path_prefix, "meta-llama/Llama-3.2-3B-Instruct")
37

38

39
40
41
42
def do_sample(
    llm: vllm.LLM,
    lora_path: str,
    lora_id: int,
43
    tensorizer_config_dict: dict | None = None,
44
) -> list[str]:
45
    prompts = [
46
47
48
49
50
51
52
53
        PROMPT_TEMPLATE.format(context="How many candidates are there?"),
        PROMPT_TEMPLATE.format(context="Count the number of candidates."),
        PROMPT_TEMPLATE.format(
            context="Which poll resource provided the most number of candidate information?"  # noqa: E501
        ),
        PROMPT_TEMPLATE.format(
            context="Return the poll resource associated with the most candidates."
        ),
54
    ]
55

56
    sampling_params = vllm.SamplingParams(
57
        temperature=0, max_tokens=64, stop=["<|im_end|>"]
58
    )
59
60
61
62
63
64
65
66
    if tensorizer_config_dict is not None:
        outputs = llm.generate(
            prompts,
            sampling_params,
            lora_request=LoRARequest(
                str(lora_id),
                lora_id,
                lora_path,
67
68
69
70
71
                tensorizer_config_dict=tensorizer_config_dict,
            )
            if lora_id
            else None,
        )
72
73
74
75
76
    else:
        outputs = llm.generate(
            prompts,
            sampling_params,
            lora_request=LoRARequest(str(lora_id), lora_id, lora_path)
77
78
79
            if lora_id
            else None,
        )
80
    lora_request = LoRARequest(str(lora_id), lora_id, lora_path) if lora_id else None
81
    generated_texts: list[str] = []
82
83
84
    for output in outputs:
        prompt = output.prompt
        generated_text = output.outputs[0].text
85
86
87
88
89
90
91
        # The output should include  correct lora_request info
        if lora_request is not None:
            assert output.lora_request.lora_name == lora_request.lora_name
            assert output.lora_request.lora_int_id == lora_request.lora_int_id
            assert output.lora_request.lora_path == lora_request.lora_path
        else:
            assert output.lora_request is None
92
93
94
95
96
        generated_texts.append(generated_text)
        print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
    return generated_texts


97
98
99
def generate_and_test(
    llm, llama32_lora_files, tensorizer_config_dict: dict | None = None
):
100
101
    print("lora adapter created")
    print("lora 1")
102
103
104
    assert (
        do_sample(
            llm,
105
            llama32_lora_files,
106
107
108
109
110
            tensorizer_config_dict=tensorizer_config_dict,
            lora_id=1,
        )
        == EXPECTED_LORA_OUTPUT
    )
111
112

    print("lora 2")
113
114
115
    assert (
        do_sample(
            llm,
116
            llama32_lora_files,
117
118
119
120
121
            tensorizer_config_dict=tensorizer_config_dict,
            lora_id=2,
        )
        == EXPECTED_LORA_OUTPUT
    )
122
123
124
125

    print("removing lora")


126
@create_new_process_for_each_test()
127
@pytest.mark.parametrize("cudagraph_specialize_lora", [True, False])
128
def test_llama_lora(llama32_lora_files, cudagraph_specialize_lora: bool):
129
130
131
132
    llm = vllm.LLM(
        MODEL_PATH,
        enable_lora=True,
        # also test odd max_num_seqs
133
134
        max_num_seqs=7,
        max_model_len=1024,
135
        max_loras=4,
136
137
138
        compilation_config=vllm.config.CompilationConfig(
            cudagraph_specialize_lora=cudagraph_specialize_lora,
        ),
139
    )
140
    generate_and_test(llm, llama32_lora_files)
141
142


143
@multi_gpu_test(num_gpus=4)
144
def test_llama_lora_tp4(llama32_lora_files):
145
146
147
    llm = vllm.LLM(
        MODEL_PATH,
        enable_lora=True,
148
149
        max_num_seqs=7,
        max_model_len=1024,
150
151
152
        max_loras=4,
        tensor_parallel_size=4,
    )
153
    generate_and_test(llm, llama32_lora_files)
154
155
156


@multi_gpu_test(num_gpus=4)
157
def test_llama_lora_tp4_fully_sharded_loras(llama32_lora_files):
158
159
160
    llm = vllm.LLM(
        MODEL_PATH,
        enable_lora=True,
161
        max_num_seqs=8,
162
        max_loras=4,
163
        max_model_len=1024,
164
165
166
        tensor_parallel_size=4,
        fully_sharded_loras=True,
    )
167
    generate_and_test(llm, llama32_lora_files)
168
169
170


@multi_gpu_test(num_gpus=2)
171
def test_tp2_serialize_and_deserialize_lora(
172
173
    tmp_path,
    llama32_lora_files,
174
):
175
176
177
178
179
180
181
    # Run the tensorizing of the LoRA adapter and the model in a subprocess
    # to guarantee cleanup

    tp_size = 2
    model_name = "model-rank-%03d.tensors"

    model_ref = MODEL_PATH
182
    lora_path = llama32_lora_files
183
184
    suffix = "test"
    try:
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
        result = subprocess.run(
            [
                sys.executable,
                f"{VLLM_PATH}/examples/others/tensorize_vllm_model.py",
                "--model",
                MODEL_PATH,
                "--lora-path",
                lora_path,
                "--tensor-parallel-size",
                str(tp_size),
                "serialize",
                "--serialized-directory",
                str(tmp_path),
                "--suffix",
                suffix,
                "--serialization-kwargs",
                '{"limit_cpu_concurrency": 4}',
            ],
            check=True,
            capture_output=True,
            text=True,
        )
207
208
209
210
211
212
213
214
215
216
217
    except subprocess.CalledProcessError as e:
        print("Tensorizing failed.")
        print("STDOUT:\n", e.stdout)
        print("STDERR:\n", e.stderr)
        raise

    print("STDOUT:\n", result.stdout)

    model_uri = tmp_path / "vllm" / model_ref / suffix / model_name
    tensorizer_config = TensorizerConfig(tensorizer_uri=str(model_uri))

218
219
220
221
222
223
    loaded_llm = LLM(
        model=model_ref,
        load_format="tensorizer",
        enable_lora=True,
        enforce_eager=True,
        model_loader_extra_config=tensorizer_config,
224
225
        max_num_seqs=7,
        max_model_len=1024,
226
227
228
        tensor_parallel_size=2,
        max_loras=2,
    )
229

230
    tc_as_dict = tensorizer_config.to_serializable()
231
232
233

    print("lora adapter created")
    print("lora 1")
234
235
    assert (
        do_sample(
236
            loaded_llm, llama32_lora_files, tensorizer_config_dict=tc_as_dict, lora_id=1
237
238
239
        )
        == EXPECTED_LORA_OUTPUT
    )