conftest.py 19.7 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,
Woosuk Kwon's avatar
Woosuk Kwon committed
155
    ) -> None:
156
        torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
157

158
        self.model_name = model_name
159

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

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

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

        try:
190
191
192
            # don't put this import at the top level
            # it will call torch.cuda.device_count()
            from transformers import AutoProcessor  # noqa: F401
193
194
195
196
197
198
199
200
201
202
            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
203
204
205
206

    def generate(
        self,
        prompts: List[str],
207
        images: Optional[List[Image.Image]] = None,
208
        **kwargs: Any,
209
    ) -> List[Tuple[List[List[int]], List[str]]]:
210
211
        if images:
            assert len(prompts) == len(images)
212
213

        outputs: List[Tuple[List[List[int]], List[str]]] = []
214
        for i, prompt in enumerate(prompts):
215
216
217
218
219
220
221
222
223
            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
224
            output_ids = self.model.generate(
225
                **self.wrap_device(inputs),
Woosuk Kwon's avatar
Woosuk Kwon committed
226
227
228
                use_cache=True,
                **kwargs,
            )
229
            output_str = self.processor.batch_decode(
Woosuk Kwon's avatar
Woosuk Kwon committed
230
231
232
                output_ids,
                skip_special_tokens=True,
                clean_up_tokenization_spaces=False,
233
234
            )
            output_ids = output_ids.cpu().tolist()
Woosuk Kwon's avatar
Woosuk Kwon committed
235
236
237
238
239
240
241
            outputs.append((output_ids, output_str))
        return outputs

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

        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
253
254
255
256
257
258

    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
259
    ) -> List[Tuple[List[List[int]], List[str]]]:
260
261
262
263
264
265
266
267
268
269
270
271
272
273
        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
274

275
276
277
278
    def generate_greedy_logprobs(
        self,
        prompts: List[str],
        max_tokens: int,
279
280
        images: Optional[List[Image.Image]] = None,
        **kwargs: Any,
281
    ) -> List[List[torch.Tensor]]:
282
283
284
285
286
287
288
289
290
291
292
        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)

293
            output = self.model.generate(
294
                **self.wrap_device(inputs),
295
296
297
298
299
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
300
                **kwargs,
301
            )
302
            seq_logprobs: List[torch.Tensor] = []
303
304
305
306
307
308
309
310
311
            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)
312
                logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
313
314
315
316
                seq_logprobs.append(logprobs)
            all_logprobs.append(seq_logprobs)
        return all_logprobs

317
318
319
320
321
    def generate_greedy_logprobs_limit(
        self,
        prompts: List[str],
        max_tokens: int,
        num_logprobs: int,
322
323
        images: Optional[List[Image.Image]] = None,
        **kwargs: Any,
324
325
326
327
    ) -> 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] = []
328

329
330
331
332
333
334
335
336
337
338
        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)

339
            output = self.model.generate(
340
                **self.wrap_device(inputs),
341
342
343
344
345
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
346
                **kwargs,
347
348
            )

349
            seq_logprobs: List[torch.Tensor] = []
350
351
352
353
354
355
356
357
358
359
            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)
360
                logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
361
362
363
                seq_logprobs.append(logprobs)

            # convert to dict
364
            seq_logprobs_lst: List[Dict[int, float]] = []
365
366
367
368
369
370
371
372
373
374
375
376
377
378
            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]
379
            output_len = len(seq_logprobs_lst)
380
381
382
383
384
385
386
387
            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]

388
389
390
    def encode(self, prompts: List[str]) -> List[List[torch.Tensor]]:
        return self.model.encode(prompts)

391
392
393
394
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
395
396
397
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
398

Cyrus Leung's avatar
Cyrus Leung committed
399
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
400
401
402
403
404
405
406
407
408
409
def hf_runner():
    return HfRunner


class VllmRunner:

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

    def generate(
        self,
        prompts: List[str],
        sampling_params: SamplingParams,
441
        images: Optional[List[Image.Image]] = None,
442
    ) -> List[Tuple[List[List[int]], List[str]]]:
443
        if images is not None:
444
            assert len(prompts) == len(images)
445

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

451
        req_outputs = self.model.generate(inputs,
452
                                          sampling_params=sampling_params)
453
454

        outputs: List[Tuple[List[List[int]], List[str]]] = []
Woosuk Kwon's avatar
Woosuk Kwon committed
455
456
457
        for req_output in req_outputs:
            prompt_str = req_output.prompt
            prompt_ids = req_output.prompt_token_ids
458
459
            req_sample_output_ids: List[List[int]] = []
            req_sample_output_strs: List[str] = []
460
461
            for sample in req_output.outputs:
                output_str = sample.text
462
                output_ids = list(sample.token_ids)
463
464
465
                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
466
467
        return outputs

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

476
477
478
479
480
481
482
483
484
        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,
485
                                          sampling_params=sampling_params)
486
        outputs: List[Tuple[List[int], str, Optional[SampleLogprobs]]] = []
487
488
489
490
491
492
493
494
        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
495
496
497
498
    def generate_greedy(
        self,
        prompts: List[str],
        max_tokens: int,
499
        images: Optional[List[Image.Image]] = None,
Woosuk Kwon's avatar
Woosuk Kwon committed
500
501
    ) -> List[Tuple[List[int], str]]:
        greedy_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
502
        outputs = self.generate(prompts, greedy_params, images=images)
503
504
        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
505

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

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

525
526
527
528
529
    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
530
    ) -> List[Tuple[List[List[int]], List[str]]]:
531
532
533
534
535
536
        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
537

538
539
540
541
542
543
544
545
    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

546
547
548
549
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
550
551
552
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
553

554
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
555
556
def vllm_runner():
    return VllmRunner
557
558
559
560
561
562
563
564
565


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={})
566
567
568
569
    if isinstance(tokenizer_group_type, type):
        return TokenizerPoolConfig(pool_size=1,
                                   pool_type=tokenizer_group_type,
                                   extra_config={})
570
    raise ValueError(f"Unknown tokenizer_group_type: {tokenizer_group_type}")
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586


@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
587
588
589
590
591
592
593


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

594
    return cuda_device_count_stateless()