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
from vllm.sequence import SampleLogprobs
24
25
from vllm.utils import (STR_DTYPE_TO_TORCH_DTYPE, cuda_device_count_stateless,
                        is_cpu)
26

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

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


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


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


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
        super().__init__([
            ImageAsset("stop_sign"),
            ImageAsset("cherry_blossom"),
        ])
62
63
64
65
66
67
68
69

    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.
        """
70
        return [prompts["stop_sign"], prompts["cherry_blossom"]]
71
72
73
74
75
76


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


77
78
def cleanup():
    destroy_model_parallel()
79
    destroy_distributed_environment()
80
81
82
    with contextlib.suppress(AssertionError):
        torch.distributed.destroy_process_group()
    gc.collect()
83
84
    if not is_cpu():
        torch.cuda.empty_cache()
85
86


87
@pytest.fixture()
88
def should_do_global_cleanup_after_test(request) -> bool:
89
90
91
92
    """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.
    """
93
94
95
96

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

97
98
99
    return True


100
@pytest.fixture(autouse=True)
101
def cleanup_fixture(should_do_global_cleanup_after_test: bool):
102
    yield
103
104
    if should_do_global_cleanup_after_test:
        cleanup()
105
106


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


@pytest.fixture
def example_long_prompts() -> List[str]:
    prompts = []
    for filename in _LONG_PROMPTS:
119
        prompts += _read_prompts(filename)
120
    return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
121
122


123
124
125
126
127
@pytest.fixture(scope="session")
def image_assets() -> _ImageAssets:
    return IMAGE_ASSETS


128
_T = TypeVar("_T", nn.Module, torch.Tensor, BatchEncoding)
129

Woosuk Kwon's avatar
Woosuk Kwon committed
130
131
132

class HfRunner:

133
    def wrap_device(self, input: _T) -> _T:
134
135
136
137
138
        if not is_cpu():
            return input.to("cuda")
        else:
            return input.to("cpu")

Woosuk Kwon's avatar
Woosuk Kwon committed
139
140
141
142
    def __init__(
        self,
        model_name: str,
        dtype: str = "half",
143
        *,
144
        model_kwargs: Optional[Dict[str, Any]] = None,
145
146
        is_embedding_model: bool = False,
        is_vision_model: bool = False,
147
        is_sparseml_model: bool = False,
Woosuk Kwon's avatar
Woosuk Kwon committed
148
    ) -> None:
149
        torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[dtype]
150

151
        self.model_name = model_name
152

153
        if is_embedding_model:
154
155
            # Lazy init required for AMD CI
            from sentence_transformers import SentenceTransformer
156
157
158
159
160
            self.model = self.wrap_device(
                SentenceTransformer(
                    model_name,
                    device="cpu",
                ).to(dtype=torch_dtype))
161
        else:
162
163
            if is_vision_model:
                auto_cls = AutoModelForVision2Seq
164
165
166
            elif is_sparseml_model:
                from sparseml.transformers import SparseAutoModelForCausalLM
                auto_cls = SparseAutoModelForCausalLM
167
168
169
            else:
                auto_cls = AutoModelForCausalLM

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

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

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

    def generate(
        self,
        prompts: List[str],
203
        images: Optional[List[Image.Image]] = None,
204
        **kwargs: Any,
205
    ) -> List[Tuple[List[List[int]], List[str]]]:
206
207
        if images:
            assert len(prompts) == len(images)
208
209

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

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

        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
249
250
251
252
253
254

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

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

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

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

325
326
327
328
329
330
331
332
333
334
335
        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

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

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

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

385
386
387
    def encode(self, prompts: List[str]) -> List[List[torch.Tensor]]:
        return self.model.encode(prompts)

388
389
390
391
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
392
393
394
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
395

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


class VllmRunner:

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

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

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

448
        req_outputs = self.model.generate(inputs,
449
                                          sampling_params=sampling_params)
450
451

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

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

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

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

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

520
521
522
523
524
    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
525
    ) -> List[Tuple[List[List[int]], List[str]]]:
526
527
528
529
530
531
        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
532

533
534
535
536
537
538
539
540
    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

541
542
543
544
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
545
546
547
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
548

549
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
550
551
def vllm_runner():
    return VllmRunner
552
553
554
555
556
557
558
559
560


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


@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
582
583
584
585
586
587
588


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

589
    return cuda_device_count_stateless()