conftest.py 19.5 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)
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
20
from vllm.distributed import (destroy_distributed_environment,
                              destroy_model_parallel)
21
from vllm.inputs import TextPrompt
22
from vllm.logger import init_logger
23
24
from vllm.sequence import SampleLogprobs
from vllm.utils import cuda_device_count_stateless, is_cpu
25

26
logger = init_logger(__name__)
Woosuk Kwon's avatar
Woosuk Kwon committed
27

28
29
30
_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")]
31
32


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


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


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

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

54
55

class _ImageAssets(_ImageAssetsBase):
56
57

    def __init__(self) -> None:
58
59
60
61
62
        super().__init__([
            ImageAsset("stop_sign"),
            ImageAsset("cherry_blossom"),
            ImageAsset("boardwalk")
        ])
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
72
73
74
        return [
            prompts["stop_sign"], prompts["cherry_blossom"],
            prompts["boardwalk"]
        ]
75
76
77
78
79
80


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


81
82
def cleanup():
    destroy_model_parallel()
83
    destroy_distributed_environment()
84
85
86
    with contextlib.suppress(AssertionError):
        torch.distributed.destroy_process_group()
    gc.collect()
87
88
    if not is_cpu():
        torch.cuda.empty_cache()
89
90


91
@pytest.fixture()
92
def should_do_global_cleanup_after_test(request) -> bool:
93
94
95
96
    """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.
    """
97
98
99
100

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

101
102
103
    return True


104
@pytest.fixture(autouse=True)
105
def cleanup_fixture(should_do_global_cleanup_after_test: bool):
106
    yield
107
108
    if should_do_global_cleanup_after_test:
        cleanup()
109
110


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


@pytest.fixture
def example_long_prompts() -> List[str]:
    prompts = []
    for filename in _LONG_PROMPTS:
123
        prompts += _read_prompts(filename)
124
    return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
125
126


127
128
129
130
131
@pytest.fixture(scope="session")
def image_assets() -> _ImageAssets:
    return IMAGE_ASSETS


Woosuk Kwon's avatar
Woosuk Kwon committed
132
133
134
135
136
137
_STR_DTYPE_TO_TORCH_DTYPE = {
    "half": torch.half,
    "bfloat16": torch.bfloat16,
    "float": torch.float,
}

138
_T = TypeVar("_T", nn.Module, torch.Tensor, BatchEncoding)
139

Woosuk Kwon's avatar
Woosuk Kwon committed
140
141
142

class HfRunner:

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

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

162
        self.model_name = model_name
163

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

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

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

        try:
197
198
199
            # don't put this import at the top level
            # it will call torch.cuda.device_count()
            from transformers import AutoProcessor  # noqa: F401
200
201
202
203
204
205
206
207
208
209
            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
210
211
212
213

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

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

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

        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
260
261
262
263
264
265

    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
266
    ) -> List[Tuple[List[List[int]], List[str]]]:
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        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
281

282
283
284
285
    def generate_greedy_logprobs(
        self,
        prompts: List[str],
        max_tokens: int,
286
287
        images: Optional[List[Image.Image]] = None,
        **kwargs: Any,
288
    ) -> List[List[torch.Tensor]]:
289
290
291
292
293
294
295
296
297
298
299
        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)

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

324
325
326
327
328
    def generate_greedy_logprobs_limit(
        self,
        prompts: List[str],
        max_tokens: int,
        num_logprobs: int,
329
330
        images: Optional[List[Image.Image]] = None,
        **kwargs: Any,
331
332
333
334
    ) -> 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] = []
335

336
337
338
339
340
341
342
343
344
345
346
        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)
            input_ids = inputs.input_ids

347
            output = self.model.generate(
348
                **self.wrap_device(inputs),
349
350
351
352
353
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
354
                **kwargs,
355
356
            )

357
            seq_logprobs: List[torch.Tensor] = []
358
359
360
361
362
363
364
365
366
367
            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)
368
                logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
369
370
371
                seq_logprobs.append(logprobs)

            # convert to dict
372
            seq_logprobs_lst: List[Dict[int, float]] = []
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
            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]
            output_len = seq_ids.shape[0] - input_ids.shape[1]
            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]

396
397
398
    def encode(self, prompts: List[str]) -> List[List[torch.Tensor]]:
        return self.model.encode(prompts)

399
400
401
402
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
403
404
405
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
406

Cyrus Leung's avatar
Cyrus Leung committed
407
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
408
409
410
411
412
413
414
415
416
417
def hf_runner():
    return HfRunner


class VllmRunner:

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

    def generate(
        self,
        prompts: List[str],
        sampling_params: SamplingParams,
449
        images: Optional[List[Image.Image]] = None,
450
    ) -> List[Tuple[List[List[int]], List[str]]]:
451
        if images is not None:
452
            assert len(prompts) == len(images)
453

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

459
        req_outputs = self.model.generate(inputs,
460
                                          sampling_params=sampling_params)
461
462

        outputs: List[Tuple[List[List[int]], List[str]]] = []
Woosuk Kwon's avatar
Woosuk Kwon committed
463
464
465
        for req_output in req_outputs:
            prompt_str = req_output.prompt
            prompt_ids = req_output.prompt_token_ids
466
467
            req_sample_output_ids: List[List[int]] = []
            req_sample_output_strs: List[str] = []
468
469
            for sample in req_output.outputs:
                output_str = sample.text
470
                output_ids = list(sample.token_ids)
471
472
473
                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
474
475
        return outputs

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

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

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

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

531
532
533
534
535
    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
536
    ) -> List[Tuple[List[List[int]], List[str]]]:
537
538
539
540
541
542
        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
543

544
545
546
547
548
549
550
551
    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

552
553
554
555
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
556
557
558
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
559

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


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={})
    raise ValueError(f"Unknown tokenizer_group_type: {tokenizer_group_type}")
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588


@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
589
590
591
592
593
594
595


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

596
    return cuda_device_count_stateless()