conftest.py 10.5 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
4
import tempfile
from collections import OrderedDict
5
from typing import TypedDict
6
from unittest.mock import MagicMock, patch
7
8

import pytest
9
import os
10
11
12
13
14
15
import torch
import torch.nn as nn
from huggingface_hub import snapshot_download

import vllm
from vllm.config import LoRAConfig
16
from vllm.distributed import (cleanup_dist_env_and_memory,
17
18
                              init_distributed_environment,
                              initialize_model_parallel)
19
20
21
from vllm.model_executor.layers.linear import (ColumnParallelLinear,
                                               MergedColumnParallelLinear,
                                               RowParallelLinear)
22
23
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.sampler import Sampler
24
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
25
from vllm.model_executor.model_loader import get_model
26
from vllm.model_executor.models.interfaces import SupportsLoRA
27
from vllm.platforms import current_platform
28
from ..utils import models_path_prefix
29

30
31
32
33
34
35
36
37
38
39
40

class ContextIDInfo(TypedDict):
    lora_id: int
    context_length: str


class ContextInfo(TypedDict):
    lora: str
    context_length: str


41
LONG_LORA_INFOS: list[ContextIDInfo] = [{
42
43
44
45
46
47
48
49
50
51
    "lora_id": 1,
    "context_length": "16k",
}, {
    "lora_id": 2,
    "context_length": "16k",
}, {
    "lora_id": 3,
    "context_length": "32k",
}]

52

53
54
55
56
57
58
59
@pytest.fixture()
def should_do_global_cleanup_after_test(request) -> bool:
    """Allow subdirectories to skip global cleanup by overriding this fixture.
    This can provide a ~10x speedup for non-GPU unit tests since they don't need
    to initialize torch.
    """

60
    return not request.node.get_closest_marker("skip_global_cleanup")
61
62


63
@pytest.fixture(autouse=True)
64
def cleanup_fixture(should_do_global_cleanup_after_test: bool):
65
    yield
66
    if should_do_global_cleanup_after_test:
67
        cleanup_dist_env_and_memory(shutdown_ray=True)
68
69
70
71


@pytest.fixture
def dist_init():
72
    temp_file = tempfile.mkstemp()[1]
73
74
75
76
77
78
79
80
81
82

    backend = "nccl"
    if current_platform.is_cpu():
        backend = "gloo"

    init_distributed_environment(world_size=1,
                                 rank=0,
                                 distributed_init_method=f"file://{temp_file}",
                                 local_rank=0,
                                 backend=backend)
83
84
    initialize_model_parallel(1, 1)
    yield
85
    cleanup_dist_env_and_memory(shutdown_ray=True)
86
87
88
89
90
91


@pytest.fixture
def dist_init_torch_only():
    if torch.distributed.is_initialized():
        return
92
93
94
95
    backend = "nccl"
    if current_platform.is_cpu():
        backend = "gloo"

96
    temp_file = tempfile.mkstemp()[1]
97
98
99
100
    torch.distributed.init_process_group(world_size=1,
                                         rank=0,
                                         init_method=f"file://{temp_file}",
                                         backend=backend)
101
102


103
104
105
106
class DummyLoRAModel(nn.Sequential, SupportsLoRA):
    pass


107
108
@pytest.fixture
def dummy_model() -> nn.Module:
109
    model = DummyLoRAModel(
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
        OrderedDict([
            ("dense1", ColumnParallelLinear(764, 100)),
            ("dense2", RowParallelLinear(100, 50)),
            (
                "layer1",
                nn.Sequential(
                    OrderedDict([
                        ("dense1", ColumnParallelLinear(100, 10)),
                        ("dense2", RowParallelLinear(10, 50)),
                    ])),
            ),
            ("act2", nn.ReLU()),
            ("output", ColumnParallelLinear(50, 10)),
            ("outact", nn.Sigmoid()),
            # Special handling for lm_head & sampler
            ("lm_head", ParallelLMHead(512, 10)),
126
127
            ("logits_processor", LogitsProcessor(512)),
            ("sampler", Sampler())
128
129
        ]))
    model.config = MagicMock()
130
    model.embedding_modules = {"lm_head": "lm_head"}
131
132
133
134
135
    return model


@pytest.fixture
def dummy_model_gate_up() -> nn.Module:
136
    model = DummyLoRAModel(
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
        OrderedDict([
            ("dense1", ColumnParallelLinear(764, 100)),
            ("dense2", RowParallelLinear(100, 50)),
            (
                "layer1",
                nn.Sequential(
                    OrderedDict([
                        ("dense1", ColumnParallelLinear(100, 10)),
                        ("dense2", RowParallelLinear(10, 50)),
                    ])),
            ),
            ("act2", nn.ReLU()),
            ("gate_up_proj", MergedColumnParallelLinear(50, [5, 5])),
            ("outact", nn.Sigmoid()),
            # Special handling for lm_head & sampler
            ("lm_head", ParallelLMHead(512, 10)),
153
154
            ("logits_processor", LogitsProcessor(512)),
            ("sampler", Sampler())
155
156
        ]))
    model.config = MagicMock()
157
158
159
160
161
162
163
    model.packed_modules_mapping = {
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }
    model.embedding_modules = {"lm_head": "lm_head"}
164
165
166
167
    return model


@pytest.fixture(scope="session")
168
169
def sql_lora_huggingface_id():
    # huggingface repo id is used to test lora runtime downloading.
170
    return os.path.join(models_path_prefix, "yard1/llama-2-7b-sql-lora-test")
171
172
173
174
175


@pytest.fixture(scope="session")
def sql_lora_files(sql_lora_huggingface_id):
    return snapshot_download(repo_id=sql_lora_huggingface_id)
176
177


Terry's avatar
Terry committed
178
179
@pytest.fixture(scope="session")
def mixtral_lora_files():
180
181
    # Note: this module has incorrect adapter_config.json to test
    # https://github.com/vllm-project/vllm/pull/5909/files.
182
183
    # return snapshot_download(repo_id="SangBinCho/mixtral-lora")
    return os.path.join(models_path_prefix, "SangBinCho/mixtral-lora")
Terry's avatar
Terry committed
184
185


186
187
@pytest.fixture(scope="session")
def gemma_lora_files():
188
189
    # return snapshot_download(repo_id="wskwon/gemma-7b-test-lora")
    return os.path.join(models_path_prefix, "wskwon/gemma-7b-test-lora")
190
191


192
193
@pytest.fixture(scope="session")
def chatglm3_lora_files():
194
195
    # return snapshot_download(repo_id="jeeejeee/chatglm3-text2sql-spider")
    return os.path.join(models_path_prefix, "jeeejeee/chatglm3-text2sql-spider")
196
197
198
199


@pytest.fixture(scope="session")
def baichuan_lora_files():
200
201
    # return snapshot_download(repo_id="jeeejeee/baichuan7b-text2sql-spider")
    return os.path.join(models_path_prefix, "jeeejeee/baichuan7b-text2sql-spider")
202
203


204
205
206
@pytest.fixture(scope="session")
def baichuan_zero_lora_files():
    # all the lora_B weights are initialized to zero.
207
208
    # return snapshot_download(repo_id="jeeejeee/baichuan7b-zero-init")
    return os.path.join(models_path_prefix, "jeeejeee/baichuan7b-zero-init")
209
210


211
212
213
214
215
@pytest.fixture(scope="session")
def baichuan_regex_lora_files():
    return snapshot_download(repo_id="jeeejeee/baichuan-7b-lora-zero-regex")


216
217
218
219
220
@pytest.fixture(scope="session")
def ilama_lora_files():
    return snapshot_download(repo_id="jeeejeee/ilama-text2sql-spider")


221
222
223
224
225
@pytest.fixture(scope="session")
def minicpmv_lora_files():
    return snapshot_download(repo_id="jeeejeee/minicpmv25-lora-pokemon")


226
227
228
229
230
@pytest.fixture(scope="session")
def qwen2vl_lora_files():
    return snapshot_download(repo_id="jeeejeee/qwen2-vl-lora-pokemon")


231
232
233
234
235
@pytest.fixture(scope="session")
def qwen25vl_lora_files():
    return snapshot_download(repo_id="jeeejeee/qwen25-vl-lora-pokemon")


236
237
@pytest.fixture(scope="session")
def tinyllama_lora_files():
238
239
    # return snapshot_download(repo_id="jashing/tinyllama-colorist-lora")
    return os.path.join(models_path_prefix, "jashing/tinyllama-colorist-lora")
240
241


242
243
@pytest.fixture(scope="session")
def phi2_lora_files():
244
245
    # return snapshot_download(repo_id="isotr0py/phi-2-test-sql-lora")
    return os.path.join(models_path_prefix, "isotr0py/phi-2-test-sql-lora")
246

王敏's avatar
王敏 committed
247
248
249
250
251
@pytest.fixture(scope="session")
def qwen_lora_files():
    # return snapshot_download(repo_id="jeeejeee/chatglm3-text2sql-spider")
    return os.path.join(models_path_prefix, "customize/qwen-nl2dsl-lora")

252

253
254
@pytest.fixture(scope="session")
def long_context_lora_files_16k_1():
255
256
    # return snapshot_download(repo_id="SangBinCho/long_context_16k_testing_1")
    return os.path.join(models_path_prefix, "SangBinCho/long_context_16k_testing_1")
257
258
259
260


@pytest.fixture(scope="session")
def long_context_lora_files_16k_2():
261
262
    # return snapshot_download(repo_id="SangBinCho/long_context_16k_testing_2")
    return os.path.join(models_path_prefix, "SangBinCho/long_context_16k_testing_2")
263
264
265
266


@pytest.fixture(scope="session")
def long_context_lora_files_32k():
267
268
    # return snapshot_download(repo_id="SangBinCho/long_context_32k_testing")
    return os.path.join(models_path_prefix, "SangBinCho/long_context_32k_testing")
269
270
271
272
273
274


@pytest.fixture(scope="session")
def long_context_infos(long_context_lora_files_16k_1,
                       long_context_lora_files_16k_2,
                       long_context_lora_files_32k):
275
    cleanup_dist_env_and_memory(shutdown_ray=True)
276
    infos: dict[int, ContextInfo] = {}
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    for lora_checkpoint_info in LONG_LORA_INFOS:
        lora_id = lora_checkpoint_info["lora_id"]
        if lora_id == 1:
            lora = long_context_lora_files_16k_1
        elif lora_id == 2:
            lora = long_context_lora_files_16k_2
        elif lora_id == 3:
            lora = long_context_lora_files_32k
        else:
            raise AssertionError("Unknown lora id")
        infos[lora_id] = {
            "context_length": lora_checkpoint_info["context_length"],
            "lora": lora,
        }
    return infos


294
@pytest.fixture
295
def llama_2_7b_engine_extra_embeddings():
296
    cleanup_dist_env_and_memory(shutdown_ray=True)
297
298
    get_model_old = get_model

299
300
301
302
    def get_model_patched(**kwargs):
        kwargs["vllm_config"].lora_config = LoRAConfig(max_loras=4,
                                                       max_lora_rank=8)
        return get_model_old(**kwargs)
303
304

    with patch("vllm.worker.model_runner.get_model", get_model_patched):
305
        engine = vllm.LLM(os.path.join(models_path_prefix, "meta-llama/Llama-2-7b-hf"), enable_lora=False)
306
307
    yield engine.llm_engine
    del engine
308
    cleanup_dist_env_and_memory(shutdown_ray=True)
309
310
311


@pytest.fixture
312
def llama_2_7b_model_extra_embeddings(llama_2_7b_engine_extra_embeddings):
313
314
    yield (llama_2_7b_engine_extra_embeddings.model_executor.driver_worker.
           model_runner.model)
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331


@pytest.fixture(params=[True, False])
def run_with_both_engines_lora(request, monkeypatch):
    # Automatically runs tests twice, once with V1 and once without
    use_v1 = request.param
    # Tests decorated with `@skip_v1` are only run without v1
    skip_v1 = request.node.get_closest_marker("skip_v1")

    if use_v1:
        if skip_v1:
            pytest.skip("Skipping test on vllm V1")
        monkeypatch.setenv('VLLM_USE_V1', '1')
    else:
        monkeypatch.setenv('VLLM_USE_V1', '0')

    yield