conftest.py 19.8 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
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)
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
343
        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

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

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

            # convert to dict
369
            seq_logprobs_lst: List[Dict[int, float]] = []
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
            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]

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

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

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

Woosuk Kwon's avatar
Woosuk Kwon committed
403

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


class VllmRunner:

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

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

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

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

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

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

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

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

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

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

541
542
543
544
545
546
547
548
    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

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

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

Woosuk Kwon's avatar
Woosuk Kwon committed
556

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


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


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


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

597
    return cuda_device_count_stateless()