conftest.py 9.17 KB
Newer Older
1
2
import tempfile
from collections import OrderedDict
3
from typing import Dict, List, TypedDict
4
from unittest.mock import MagicMock, patch
5
6

import pytest
7
import os
zhuwenwen's avatar
zhuwenwen committed
8

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

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

27
28
29
30
31
32
33
34
35
36
37
38

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


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


LONG_LORA_INFOS: List[ContextIDInfo] = [{
39
40
41
42
43
44
45
46
47
48
    "lora_id": 1,
    "context_length": "16k",
}, {
    "lora_id": 2,
    "context_length": "16k",
}, {
    "lora_id": 3,
    "context_length": "32k",
}]

49

50
51
52
53
54
55
56
@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.
    """

57
    return not request.node.get_closest_marker("skip_global_cleanup")
58
59


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


@pytest.fixture
def dist_init():
69
70
71
72
73
74
75
76
    temp_file = tempfile.mkstemp()[1]
    init_distributed_environment(
        world_size=1,
        rank=0,
        distributed_init_method=f"file://{temp_file}",
        local_rank=0,
        backend="nccl",
    )
77
78
    initialize_model_parallel(1, 1)
    yield
79
    cleanup_dist_env_and_memory(shutdown_ray=True)
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113


@pytest.fixture
def dist_init_torch_only():
    if torch.distributed.is_initialized():
        return
    temp_file = tempfile.mkstemp()[1]
    torch.distributed.init_process_group(
        backend="nccl",
        world_size=1,
        rank=0,
        init_method=f"file://{temp_file}",
    )


@pytest.fixture
def dummy_model() -> nn.Module:
    model = nn.Sequential(
        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)),
114
115
            ("logits_processor", LogitsProcessor(512)),
            ("sampler", Sampler())
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
        ]))
    model.config = MagicMock()
    return model


@pytest.fixture
def dummy_model_gate_up() -> nn.Module:
    model = nn.Sequential(
        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)),
140
141
            ("logits_processor", LogitsProcessor(512)),
            ("sampler", Sampler())
142
143
144
145
146
147
        ]))
    model.config = MagicMock()
    return model


@pytest.fixture(scope="session")
148
149
def sql_lora_huggingface_id():
    # huggingface repo id is used to test lora runtime downloading.
150
    return os.path.join(models_path_prefix, "yard1/llama-2-7b-sql-lora-test")
151
152
153
154
155


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


158
159
160
161
162
@pytest.fixture(scope="session")
def lora_bias_files():
    return snapshot_download(repo_id="followumesh/granite-3b-lora8-bias")


Terry's avatar
Terry committed
163
164
@pytest.fixture(scope="session")
def mixtral_lora_files():
165
166
    # Note: this module has incorrect adapter_config.json to test
    # https://github.com/vllm-project/vllm/pull/5909/files.
167
168
    # return snapshot_download(repo_id="SangBinCho/mixtral-lora")
    return os.path.join(models_path_prefix, "SangBinCho/mixtral-lora")
Terry's avatar
Terry committed
169
170


171
172
173
174
175
@pytest.fixture(scope="session")
def mixtral_lora_files_all_target_modules():
    return snapshot_download(repo_id="dyang415/mixtral-lora-v0")


176
177
@pytest.fixture(scope="session")
def gemma_lora_files():
178
179
    # return snapshot_download(repo_id="wskwon/gemma-7b-test-lora")
    return os.path.join(models_path_prefix, "wskwon/gemma-7b-test-lora")
180
181


182
183
@pytest.fixture(scope="session")
def chatglm3_lora_files():
184
185
    # return snapshot_download(repo_id="jeeejeee/chatglm3-text2sql-spider")
    return os.path.join(models_path_prefix, "jeeejeee/chatglm3-text2sql-spider")
186
187
188
189


@pytest.fixture(scope="session")
def baichuan_lora_files():
190
191
    # return snapshot_download(repo_id="jeeejeee/baichuan7b-text2sql-spider")
    return os.path.join(models_path_prefix, "jeeejeee/baichuan7b-text2sql-spider")
192
193


194
195
196
@pytest.fixture(scope="session")
def baichuan_zero_lora_files():
    # all the lora_B weights are initialized to zero.
197
198
    # return snapshot_download(repo_id="jeeejeee/baichuan7b-zero-init")
    return os.path.join(models_path_prefix, "jeeejeee/baichuan7b-zero-init")
199
200


201
202
203
204
205
@pytest.fixture(scope="session")
def baichuan_regex_lora_files():
    return snapshot_download(repo_id="jeeejeee/baichuan-7b-lora-zero-regex")


206
207
208
209
210
@pytest.fixture(scope="session")
def minicpmv_lora_files():
    return snapshot_download(repo_id="jeeejeee/minicpmv25-lora-pokemon")


211
212
@pytest.fixture(scope="session")
def tinyllama_lora_files():
213
214
    # return snapshot_download(repo_id="jashing/tinyllama-colorist-lora")
    return os.path.join(models_path_prefix, "jashing/tinyllama-colorist-lora")
215
216


217
218
@pytest.fixture(scope="session")
def phi2_lora_files():
219
220
    # return snapshot_download(repo_id="isotr0py/phi-2-test-sql-lora")
    return os.path.join(models_path_prefix, "isotr0py/phi-2-test-sql-lora")
221

王敏's avatar
王敏 committed
222
223
224
225
226
@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")

227

228
229
@pytest.fixture(scope="session")
def long_context_lora_files_16k_1():
230
231
    # return snapshot_download(repo_id="SangBinCho/long_context_16k_testing_1")
    return os.path.join(models_path_prefix, "SangBinCho/long_context_16k_testing_1")
232
233
234
235


@pytest.fixture(scope="session")
def long_context_lora_files_16k_2():
236
237
    # return snapshot_download(repo_id="SangBinCho/long_context_16k_testing_2")
    return os.path.join(models_path_prefix, "SangBinCho/long_context_16k_testing_2")
238
239
240
241


@pytest.fixture(scope="session")
def long_context_lora_files_32k():
242
243
    # return snapshot_download(repo_id="SangBinCho/long_context_32k_testing")
    return os.path.join(models_path_prefix, "SangBinCho/long_context_32k_testing")
244
245
246
247
248
249


@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):
250
    cleanup_dist_env_and_memory(shutdown_ray=True)
251
    infos: Dict[int, ContextInfo] = {}
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
    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


269
@pytest.fixture
270
def llama_2_7b_engine_extra_embeddings():
271
    cleanup_dist_env_and_memory(shutdown_ray=True)
272
273
    get_model_old = get_model

274
275
276
277
    def get_model_patched(**kwargs):
        kwargs["vllm_config"].lora_config = LoRAConfig(max_loras=4,
                                                       max_lora_rank=8)
        return get_model_old(**kwargs)
278
279

    with patch("vllm.worker.model_runner.get_model", get_model_patched):
280
        engine = vllm.LLM(os.path.join(models_path_prefix, "meta-llama/Llama-2-7b-hf"), enable_lora=False)
281
282
    yield engine.llm_engine
    del engine
283
    cleanup_dist_env_and_memory(shutdown_ray=True)
284
285
286


@pytest.fixture
287
def llama_2_7b_model_extra_embeddings(llama_2_7b_engine_extra_embeddings):
288
289
    yield (llama_2_7b_engine_extra_embeddings.model_executor.driver_worker.
           model_runner.model)