conftest.py 19.9 KB
Newer Older
1
2
import contextlib
import gc
3
import os
4
import sys
5
from collections import UserList
6
from typing import Any, Dict, List, Optional, Tuple, TypedDict, TypeVar
Woosuk Kwon's avatar
Woosuk Kwon committed
7
8
9

import pytest
import torch
10
import torch.nn as nn
11
import torch.nn.functional as F
12
from PIL import Image
13
from transformers import (AutoModelForCausalLM, AutoModelForVision2Seq,
14
                          AutoTokenizer, BatchEncoding, BatchFeature)
Woosuk Kwon's avatar
Woosuk Kwon committed
15
16

from vllm import LLM, SamplingParams
17
from vllm.assets.image import ImageAsset
18
from vllm.config import TokenizerPoolConfig
19
from vllm.connections import global_http_connection
20
21
from vllm.distributed import (destroy_distributed_environment,
                              destroy_model_parallel)
22
from vllm.inputs import TextPrompt
23
from vllm.logger import init_logger
24
from vllm.sequence import SampleLogprobs
25
26
from vllm.utils import (STR_DTYPE_TO_TORCH_DTYPE, cuda_device_count_stateless,
                        is_cpu)
27

28
logger = init_logger(__name__)
Woosuk Kwon's avatar
Woosuk Kwon committed
29

30
31
32
_TEST_DIR = os.path.dirname(__file__)
_TEST_PROMPTS = [os.path.join(_TEST_DIR, "prompts", "example.txt")]
_LONG_PROMPTS = [os.path.join(_TEST_DIR, "prompts", "summary.txt")]
33
34


35
def _read_prompts(filename: str) -> List[str]:
36
    with open(filename, "r") as f:
37
38
        prompts = f.readlines()
        return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
39
40


41
42
43
class _ImageAssetPrompts(TypedDict):
    stop_sign: str
    cherry_blossom: str
44
45
46
47
48
49
50


if sys.version_info < (3, 9):
    # UserList cannot be subscripted
    class _ImageAssetsBase(UserList):
        pass
else:
51

52
53
    class _ImageAssetsBase(UserList[ImageAsset]):
        pass
54

55
56

class _ImageAssets(_ImageAssetsBase):
57
58

    def __init__(self) -> None:
59
60
61
62
        super().__init__([
            ImageAsset("stop_sign"),
            ImageAsset("cherry_blossom"),
        ])
63
64
65
66
67
68
69
70

    def prompts(self, prompts: _ImageAssetPrompts) -> List[str]:
        """
        Convenience method to define the prompt for each test image.

        The order of the returned prompts matches the order of the
        assets when iterating through this object.
        """
71
        return [prompts["stop_sign"], prompts["cherry_blossom"]]
72
73
74
75
76
77


IMAGE_ASSETS = _ImageAssets()
"""Singleton instance of :class:`_ImageAssets`."""


78
79
80
81
82
83
84
@pytest.fixture(autouse=True)
def init_test_http_connection():
    # pytest_asyncio may use a different event loop per test
    # so we need to make sure the async client is created anew
    global_http_connection.reuse_client = False


85
86
def cleanup():
    destroy_model_parallel()
87
    destroy_distributed_environment()
88
89
90
    with contextlib.suppress(AssertionError):
        torch.distributed.destroy_process_group()
    gc.collect()
91
92
    if not is_cpu():
        torch.cuda.empty_cache()
93
94


95
@pytest.fixture()
96
def should_do_global_cleanup_after_test(request) -> bool:
97
98
99
100
    """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.
    """
101
102
103
104

    if request.node.get_closest_marker("skip_global_cleanup"):
        return False

105
106
107
    return True


108
@pytest.fixture(autouse=True)
109
def cleanup_fixture(should_do_global_cleanup_after_test: bool):
110
    yield
111
112
    if should_do_global_cleanup_after_test:
        cleanup()
113
114


Woosuk Kwon's avatar
Woosuk Kwon committed
115
116
@pytest.fixture
def example_prompts() -> List[str]:
117
118
    prompts = []
    for filename in _TEST_PROMPTS:
119
        prompts += _read_prompts(filename)
120
121
122
123
124
125
126
    return prompts


@pytest.fixture
def example_long_prompts() -> List[str]:
    prompts = []
    for filename in _LONG_PROMPTS:
127
        prompts += _read_prompts(filename)
128
    return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
129
130


131
132
133
134
135
@pytest.fixture(scope="session")
def image_assets() -> _ImageAssets:
    return IMAGE_ASSETS


136
_T = TypeVar("_T", nn.Module, torch.Tensor, BatchEncoding, BatchFeature)
137

Woosuk Kwon's avatar
Woosuk Kwon committed
138
139
140

class HfRunner:

141
    def wrap_device(self, input: _T) -> _T:
142
143
144
145
146
        if not is_cpu():
            return input.to("cuda")
        else:
            return input.to("cpu")

Woosuk Kwon's avatar
Woosuk Kwon committed
147
148
149
150
    def __init__(
        self,
        model_name: str,
        dtype: str = "half",
151
        *,
152
        model_kwargs: Optional[Dict[str, Any]] = None,
153
154
        is_embedding_model: bool = False,
        is_vision_model: bool = False,
155
        is_sparseml_model: bool = False,
Woosuk Kwon's avatar
Woosuk Kwon committed
156
    ) -> None:
157
        torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
158

159
        self.model_name = model_name
160

161
        if is_embedding_model:
162
163
            # Lazy init required for AMD CI
            from sentence_transformers import SentenceTransformer
164
165
166
167
168
            self.model = self.wrap_device(
                SentenceTransformer(
                    model_name,
                    device="cpu",
                ).to(dtype=torch_dtype))
169
        else:
170
171
            if is_vision_model:
                auto_cls = AutoModelForVision2Seq
172
173
174
            elif is_sparseml_model:
                from sparseml.transformers import SparseAutoModelForCausalLM
                auto_cls = SparseAutoModelForCausalLM
175
176
177
            else:
                auto_cls = AutoModelForCausalLM

178
            model_kwargs = model_kwargs if model_kwargs is not None else {}
179
            self.model = self.wrap_device(
180
                auto_cls.from_pretrained(
181
182
183
                    model_name,
                    torch_dtype=torch_dtype,
                    trust_remote_code=True,
184
                    **model_kwargs,
185
                ))
186
187
188
189
190
191
192
193

        self.tokenizer = AutoTokenizer.from_pretrained(
            model_name,
            torch_dtype=torch_dtype,
            trust_remote_code=True,
        )

        try:
194
195
196
            # don't put this import at the top level
            # it will call torch.cuda.device_count()
            from transformers import AutoProcessor  # noqa: F401
197
198
199
200
201
202
203
204
205
206
            self.processor = AutoProcessor.from_pretrained(
                model_name,
                torch_dtype=torch_dtype,
                trust_remote_code=True,
            )
        except Exception:
            logger.warning(
                "Unable to auto-load processor from HuggingFace for "
                "model %s. Using tokenizer instead.", model_name)
            self.processor = self.tokenizer
Woosuk Kwon's avatar
Woosuk Kwon committed
207
208
209
210

    def generate(
        self,
        prompts: List[str],
211
        images: Optional[List[Image.Image]] = None,
212
        **kwargs: Any,
213
    ) -> List[Tuple[List[List[int]], List[str]]]:
214
215
        if images:
            assert len(prompts) == len(images)
216
217

        outputs: List[Tuple[List[List[int]], List[str]]] = []
218
        for i, prompt in enumerate(prompts):
219
220
221
222
223
224
225
226
227
            processor_kwargs: Dict[str, Any] = {
                "text": prompt,
                "return_tensors": "pt",
            }
            if images is not None and images[i] is not None:
                processor_kwargs["images"] = images[i]

            inputs = self.processor(**processor_kwargs)

Woosuk Kwon's avatar
Woosuk Kwon committed
228
            output_ids = self.model.generate(
229
                **self.wrap_device(inputs),
Woosuk Kwon's avatar
Woosuk Kwon committed
230
231
232
                use_cache=True,
                **kwargs,
            )
233
            output_str = self.processor.batch_decode(
Woosuk Kwon's avatar
Woosuk Kwon committed
234
235
236
                output_ids,
                skip_special_tokens=True,
                clean_up_tokenization_spaces=False,
237
238
            )
            output_ids = output_ids.cpu().tolist()
Woosuk Kwon's avatar
Woosuk Kwon committed
239
240
241
242
243
244
245
            outputs.append((output_ids, output_str))
        return outputs

    def generate_greedy(
        self,
        prompts: List[str],
        max_tokens: int,
246
        images: Optional[List[Image.Image]] = None,
247
        **kwargs: Any,
Woosuk Kwon's avatar
Woosuk Kwon committed
248
    ) -> List[Tuple[List[int], str]]:
249
250
        outputs = self.generate(prompts,
                                do_sample=False,
251
                                max_new_tokens=max_tokens,
Chang Su's avatar
Chang Su committed
252
253
                                images=images,
                                **kwargs)
254
255
256

        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
257
258
259
260
261
262

    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
263
    ) -> List[Tuple[List[List[int]], List[str]]]:
264
265
266
267
268
269
270
271
272
273
274
275
276
277
        outputs = self.generate(prompts,
                                do_sample=False,
                                max_new_tokens=max_tokens,
                                num_beams=beam_width,
                                num_return_sequences=beam_width)
        for i in range(len(outputs)):
            output_ids, output_str = outputs[i]
            for j in range(len(output_ids)):
                output_ids[j] = [
                    x for x in output_ids[j]
                    if x != self.tokenizer.pad_token_id
                ]
            outputs[i] = (output_ids, output_str)
        return outputs
Woosuk Kwon's avatar
Woosuk Kwon committed
278

279
280
281
282
    def generate_greedy_logprobs(
        self,
        prompts: List[str],
        max_tokens: int,
283
284
        images: Optional[List[Image.Image]] = None,
        **kwargs: Any,
285
    ) -> List[List[torch.Tensor]]:
286
287
288
289
290
291
292
293
294
295
296
        all_logprobs: List[List[torch.Tensor]] = []
        for i, prompt in enumerate(prompts):
            processor_kwargs: Dict[str, Any] = {
                "text": prompt,
                "return_tensors": "pt",
            }
            if images is not None and images[i] is not None:
                processor_kwargs["images"] = images[i]

            inputs = self.processor(**processor_kwargs)

297
            output = self.model.generate(
298
                **self.wrap_device(inputs),
299
300
301
302
303
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
304
                **kwargs,
305
            )
306
            seq_logprobs: List[torch.Tensor] = []
307
308
309
310
311
312
313
314
315
            for hidden_states in output.hidden_states:
                last_hidden_states = hidden_states[-1][0]
                logits = torch.matmul(
                    last_hidden_states,
                    self.model.get_output_embeddings().weight.t(),
                )
                if self.model.get_output_embeddings().bias is not None:
                    logits += self.model.get_output_embeddings(
                    ).bias.unsqueeze(0)
316
                logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
317
318
319
320
                seq_logprobs.append(logprobs)
            all_logprobs.append(seq_logprobs)
        return all_logprobs

321
322
323
324
325
    def generate_greedy_logprobs_limit(
        self,
        prompts: List[str],
        max_tokens: int,
        num_logprobs: int,
326
327
        images: Optional[List[Image.Image]] = None,
        **kwargs: Any,
328
329
330
331
    ) -> List[Tuple[List[int], str, List[Dict[int, float]]]]:
        all_logprobs: List[List[Dict[int, float]]] = []
        all_output_ids: List[List[int]] = []
        all_output_strs: List[str] = []
332

333
334
335
336
337
338
339
340
341
342
        for i, prompt in enumerate(prompts):
            processor_kwargs: Dict[str, Any] = {
                "text": prompt,
                "return_tensors": "pt",
            }
            if images is not None and images[i] is not None:
                processor_kwargs["images"] = images[i]

            inputs = self.processor(**processor_kwargs)

343
            output = self.model.generate(
344
                **self.wrap_device(inputs),
345
346
347
348
349
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
350
                **kwargs,
351
352
            )

353
            seq_logprobs: List[torch.Tensor] = []
354
355
356
357
358
359
360
361
362
363
            for _, hidden_states in enumerate(output.hidden_states):
                last_hidden_states = hidden_states[-1][0]
                logits = torch.matmul(
                    last_hidden_states,
                    self.model.get_output_embeddings().weight.t(),
                )
                if getattr(self.model.get_output_embeddings(), "bias",
                           None) is not None:
                    logits += self.model.get_output_embeddings(
                    ).bias.unsqueeze(0)
364
                logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
365
366
367
                seq_logprobs.append(logprobs)

            # convert to dict
368
            seq_logprobs_lst: List[Dict[int, float]] = []
369
370
371
372
373
374
375
376
377
378
379
380
381
382
            for tok_idx, tok_logprobs in enumerate(seq_logprobs):
                # drop prompt logprobs
                if tok_idx == 0:
                    tok_logprobs = tok_logprobs[-1, :].reshape(1, -1)
                topk = tok_logprobs.topk(num_logprobs)

                tok_logprobs_dct = {}
                for token_id, logprob in zip(topk.indices[0], topk.values[0]):
                    tok_logprobs_dct[token_id.item()] = logprob.item()

                seq_logprobs_lst.append(tok_logprobs_dct)

            all_logprobs.append(seq_logprobs_lst)
            seq_ids = output.sequences[0]
383
            output_len = len(seq_logprobs_lst)
384
385
386
387
388
389
390
391
            output_ids = seq_ids[-output_len:]
            all_output_ids.append(output_ids.tolist())
            all_output_strs.append(self.tokenizer.decode(output_ids))

        outputs = zip(all_output_ids, all_output_strs, all_logprobs)
        return [(output_ids, output_str, output_logprobs)
                for output_ids, output_str, output_logprobs in outputs]

392
393
394
    def encode(self, prompts: List[str]) -> List[List[torch.Tensor]]:
        return self.model.encode(prompts)

395
396
397
398
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
399
400
401
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
402

Cyrus Leung's avatar
Cyrus Leung committed
403
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
404
405
406
407
408
409
410
411
412
413
def hf_runner():
    return HfRunner


class VllmRunner:

    def __init__(
        self,
        model_name: str,
        tokenizer_name: Optional[str] = None,
414
415
        # Use smaller max model length, otherwise bigger model cannot run due
        # to kv cache size limit.
416
        max_model_len: int = 1024,
Woosuk Kwon's avatar
Woosuk Kwon committed
417
        dtype: str = "half",
418
        disable_log_stats: bool = True,
419
        tensor_parallel_size: int = 1,
420
421
        block_size: int = 16,
        enable_chunked_prefill: bool = False,
422
        swap_space: int = 4,
Cyrus Leung's avatar
Cyrus Leung committed
423
        enforce_eager: bool = False,
424
        **kwargs,
Woosuk Kwon's avatar
Woosuk Kwon committed
425
426
427
428
429
430
    ) -> None:
        self.model = LLM(
            model=model_name,
            tokenizer=tokenizer_name,
            trust_remote_code=True,
            dtype=dtype,
431
            swap_space=swap_space,
Cyrus Leung's avatar
Cyrus Leung committed
432
            enforce_eager=enforce_eager,
433
            disable_log_stats=disable_log_stats,
434
            tensor_parallel_size=tensor_parallel_size,
435
            max_model_len=max_model_len,
436
437
            block_size=block_size,
            enable_chunked_prefill=enable_chunked_prefill,
438
            **kwargs,
Woosuk Kwon's avatar
Woosuk Kwon committed
439
440
441
442
443
444
        )

    def generate(
        self,
        prompts: List[str],
        sampling_params: SamplingParams,
445
        images: Optional[List[Image.Image]] = None,
446
    ) -> List[Tuple[List[List[int]], List[str]]]:
447
        if images is not None:
448
            assert len(prompts) == len(images)
449

450
451
452
        inputs = [TextPrompt(prompt=prompt) for prompt in prompts]
        if images is not None:
            for i, image in enumerate(images):
453
                inputs[i]["multi_modal_data"] = {"image": image}
454

455
        req_outputs = self.model.generate(inputs,
456
                                          sampling_params=sampling_params)
457
458

        outputs: List[Tuple[List[List[int]], List[str]]] = []
Woosuk Kwon's avatar
Woosuk Kwon committed
459
460
461
        for req_output in req_outputs:
            prompt_str = req_output.prompt
            prompt_ids = req_output.prompt_token_ids
462
463
            req_sample_output_ids: List[List[int]] = []
            req_sample_output_strs: List[str] = []
464
465
            for sample in req_output.outputs:
                output_str = sample.text
466
                output_ids = list(sample.token_ids)
467
468
469
                req_sample_output_ids.append(prompt_ids + output_ids)
                req_sample_output_strs.append(prompt_str + output_str)
            outputs.append((req_sample_output_ids, req_sample_output_strs))
Woosuk Kwon's avatar
Woosuk Kwon committed
470
471
        return outputs

472
473
474
475
    def generate_w_logprobs(
        self,
        prompts: List[str],
        sampling_params: SamplingParams,
476
        images: Optional[List[Image.Image]] = None,
477
    ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
478
479
        assert sampling_params.logprobs is not None

480
481
482
483
484
485
486
487
488
        if images is not None:
            assert len(prompts) == len(images)

        inputs = [TextPrompt(prompt=prompt) for prompt in prompts]
        if images is not None:
            for i, image in enumerate(images):
                inputs[i]["multi_modal_data"] = {"image": image}

        req_outputs = self.model.generate(inputs,
489
                                          sampling_params=sampling_params)
490
        outputs: List[Tuple[List[int], str, Optional[SampleLogprobs]]] = []
491
492
493
494
495
496
497
498
        for req_output in req_outputs:
            for sample in req_output.outputs:
                output_str = sample.text
                output_ids = sample.token_ids
                output_logprobs = sample.logprobs
            outputs.append((output_ids, output_str, output_logprobs))
        return outputs

Woosuk Kwon's avatar
Woosuk Kwon committed
499
500
501
502
    def generate_greedy(
        self,
        prompts: List[str],
        max_tokens: int,
503
        images: Optional[List[Image.Image]] = None,
Woosuk Kwon's avatar
Woosuk Kwon committed
504
505
    ) -> List[Tuple[List[int], str]]:
        greedy_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
506
        outputs = self.generate(prompts, greedy_params, images=images)
507
508
        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
509

510
511
512
513
514
    def generate_greedy_logprobs(
        self,
        prompts: List[str],
        max_tokens: int,
        num_logprobs: int,
515
        images: Optional[List[Image.Image]] = None,
516
        stop_token_ids: Optional[List[int]] = None,
517
    ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
518
519
        greedy_logprobs_params = SamplingParams(temperature=0.0,
                                                max_tokens=max_tokens,
520
521
                                                logprobs=num_logprobs,
                                                stop_token_ids=stop_token_ids)
522
523
524
        outputs = self.generate_w_logprobs(prompts,
                                           greedy_logprobs_params,
                                           images=images)
525
526
527
528

        return [(output_ids, output_str, output_logprobs)
                for output_ids, output_str, output_logprobs in outputs]

529
530
531
532
533
    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
534
    ) -> List[Tuple[List[List[int]], List[str]]]:
535
536
537
538
539
540
        beam_search_params = SamplingParams(n=beam_width,
                                            use_beam_search=True,
                                            temperature=0.0,
                                            max_tokens=max_tokens)
        outputs = self.generate(prompts, beam_search_params)
        return outputs
Woosuk Kwon's avatar
Woosuk Kwon committed
541

542
543
544
545
546
547
548
549
    def encode(self, prompts: List[str]) -> List[List[float]]:
        req_outputs = self.model.encode(prompts)
        outputs = []
        for req_output in req_outputs:
            embedding = req_output.outputs.embedding
            outputs.append(embedding)
        return outputs

550
551
552
553
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
554
555
556
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
557

558
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
559
560
def vllm_runner():
    return VllmRunner
561
562
563
564
565
566
567
568
569


def get_tokenizer_pool_config(tokenizer_group_type):
    if tokenizer_group_type is None:
        return None
    if tokenizer_group_type == "ray":
        return TokenizerPoolConfig(pool_size=1,
                                   pool_type="ray",
                                   extra_config={})
570
571
572
573
    if isinstance(tokenizer_group_type, type):
        return TokenizerPoolConfig(pool_size=1,
                                   pool_type=tokenizer_group_type,
                                   extra_config={})
574
    raise ValueError(f"Unknown tokenizer_group_type: {tokenizer_group_type}")
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590


@pytest.fixture()
def temporary_enable_log_propagate():
    import logging
    logger = logging.getLogger("vllm")
    logger.propagate = True
    yield
    logger.propagate = False


@pytest.fixture()
def caplog_vllm(temporary_enable_log_propagate, caplog):
    # To capture vllm log, we should enable propagate=True temporarily
    # because caplog depends on logs propagated to the root logger.
    yield caplog
591
592
593
594
595
596
597


@pytest.fixture(scope="session")
def num_gpus_available():
    """Get number of GPUs without initializing the CUDA context
    in current process."""

598
    return cuda_device_count_stateless()