conftest.py 18.6 KB
Newer Older
1
2
import contextlib
import gc
3
import os
4
5
6
7
from collections import UserList
from dataclasses import dataclass
from functools import cached_property
from pathlib import Path
8
9
from typing import (TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple,
                    TypedDict, TypeVar)
Woosuk Kwon's avatar
Woosuk Kwon committed
10
11
12

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

from vllm import LLM, SamplingParams
20
from vllm.config import TokenizerPoolConfig
21
22
from vllm.distributed import (destroy_distributed_environment,
                              destroy_model_parallel)
23
from vllm.inputs import TextPrompt
24
from vllm.logger import init_logger
25
26
from vllm.sequence import SampleLogprobs
from vllm.utils import cuda_device_count_stateless, is_cpu
27
28
29

if TYPE_CHECKING:
    # it will call torch.cuda.device_count()
30
    from vllm.multimodal import MultiModalDataDict
31
32

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

34
35
36
_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")]
37

38
39
_IMAGE_DIR = Path(_TEST_DIR) / "images"
"""You can use `.buildkite/download-images.sh` to download the assets."""
40

41

42
def _read_prompts(filename: str) -> List[str]:
43
    with open(filename, "r") as f:
44
45
        prompts = f.readlines()
        return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
46
47


48
49
50
51
52
53
54
55
56
57
58
@dataclass(frozen=True)
class ImageAsset:
    name: Literal["stop_sign", "cherry_blossom"]

    @cached_property
    def pil_image(self) -> Image.Image:
        return Image.open(_IMAGE_DIR / f"{self.name}.jpg")

    def for_hf(self) -> Image.Image:
        return self.pil_image

59
60
    def for_vllm(self) -> Dict[str, Any]:
        return {"image": self.pil_image}
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88


class _ImageAssetPrompts(TypedDict):
    stop_sign: str
    cherry_blossom: str


class _ImageAssets(UserList[ImageAsset]):

    def __init__(self) -> None:
        super().__init__(
            [ImageAsset("stop_sign"),
             ImageAsset("cherry_blossom")])

    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.
        """
        return [prompts["stop_sign"], prompts["cherry_blossom"]]


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


89
90
def cleanup():
    destroy_model_parallel()
91
    destroy_distributed_environment()
92
93
94
    with contextlib.suppress(AssertionError):
        torch.distributed.destroy_process_group()
    gc.collect()
95
96
    if not is_cpu():
        torch.cuda.empty_cache()
97
98


99
@pytest.fixture()
100
def should_do_global_cleanup_after_test(request) -> bool:
101
102
103
104
    """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.
    """
105
106
107
108

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

109
110
111
    return True


112
@pytest.fixture(autouse=True)
113
def cleanup_fixture(should_do_global_cleanup_after_test: bool):
114
    yield
115
116
    if should_do_global_cleanup_after_test:
        cleanup()
117
118


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


@pytest.fixture
def example_long_prompts() -> List[str]:
    prompts = []
    for filename in _LONG_PROMPTS:
131
        prompts += _read_prompts(filename)
132
    return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
133
134


135
136
137
138
139
@pytest.fixture(scope="session")
def image_assets() -> _ImageAssets:
    return IMAGE_ASSETS


Woosuk Kwon's avatar
Woosuk Kwon committed
140
141
142
143
144
145
_STR_DTYPE_TO_TORCH_DTYPE = {
    "half": torch.half,
    "bfloat16": torch.bfloat16,
    "float": torch.float,
}

146
_T = TypeVar("_T", nn.Module, torch.Tensor, BatchEncoding)
147

Woosuk Kwon's avatar
Woosuk Kwon committed
148
149
150

class HfRunner:

151
    def wrap_device(self, input: _T) -> _T:
152
153
154
155
156
        if not is_cpu():
            return input.to("cuda")
        else:
            return input.to("cpu")

Woosuk Kwon's avatar
Woosuk Kwon committed
157
158
159
160
    def __init__(
        self,
        model_name: str,
        dtype: str = "half",
161
        *,
162
        model_kwargs: Optional[Dict[str, Any]] = None,
163
164
        is_embedding_model: bool = False,
        is_vision_model: bool = False,
165
        is_sparseml_model: bool = False,
Woosuk Kwon's avatar
Woosuk Kwon committed
166
167
168
    ) -> None:
        assert dtype in _STR_DTYPE_TO_TORCH_DTYPE
        torch_dtype = _STR_DTYPE_TO_TORCH_DTYPE[dtype]
169

170
        self.model_name = model_name
171

172
        if is_embedding_model:
173
174
            # Lazy init required for AMD CI
            from sentence_transformers import SentenceTransformer
175
176
177
178
179
            self.model = self.wrap_device(
                SentenceTransformer(
                    model_name,
                    device="cpu",
                ).to(dtype=torch_dtype))
180
        else:
181
182
            if is_vision_model:
                auto_cls = AutoModelForVision2Seq
183
184
185
            elif is_sparseml_model:
                from sparseml.transformers import SparseAutoModelForCausalLM
                auto_cls = SparseAutoModelForCausalLM
186
187
188
            else:
                auto_cls = AutoModelForCausalLM

189
            model_kwargs = model_kwargs if model_kwargs is not None else {}
190
            self.model = self.wrap_device(
191
                auto_cls.from_pretrained(
192
193
194
                    model_name,
                    torch_dtype=torch_dtype,
                    trust_remote_code=True,
195
                    **model_kwargs,
196
                ))
197
198
199
200
201
202
203
204

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

        try:
205
206
207
            # don't put this import at the top level
            # it will call torch.cuda.device_count()
            from transformers import AutoProcessor  # noqa: F401
208
209
210
211
212
213
214
215
216
217
            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
218
219
220
221

    def generate(
        self,
        prompts: List[str],
222
        images: Optional[List[Image.Image]] = None,
Woosuk Kwon's avatar
Woosuk Kwon committed
223
        **kwargs,
224
    ) -> List[Tuple[List[List[int]], List[str]]]:
225
226
        if images:
            assert len(prompts) == len(images)
227
228

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

    def generate_greedy(
        self,
        prompts: List[str],
        max_tokens: int,
257
        images: Optional[List[Image.Image]] = None,
Chang Su's avatar
Chang Su committed
258
        **kwargs,
Woosuk Kwon's avatar
Woosuk Kwon committed
259
    ) -> List[Tuple[List[int], str]]:
260
261
        outputs = self.generate(prompts,
                                do_sample=False,
262
                                max_new_tokens=max_tokens,
Chang Su's avatar
Chang Su committed
263
264
                                images=images,
                                **kwargs)
265
266
267

        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
268
269
270
271
272
273

    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
274
    ) -> List[Tuple[List[List[int]], List[str]]]:
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        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
289

290
291
292
293
294
295
296
297
298
    def generate_greedy_logprobs(
        self,
        prompts: List[str],
        max_tokens: int,
    ) -> List[List[torch.Tensor]]:
        all_logprobs = []
        for prompt in prompts:
            input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids
            output = self.model.generate(
299
                self.wrap_device(input_ids),
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
            )
            seq_logprobs = []
            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
328
329
    ) -> 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] = []
330
331
332
333

        for prompt in prompts:
            input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids
            output = self.model.generate(
334
                self.wrap_device(input_ids),
335
336
337
338
339
340
341
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
            )

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

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

381
382
383
    def encode(self, prompts: List[str]) -> List[List[torch.Tensor]]:
        return self.model.encode(prompts)

384
385
386
387
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
388
389
390
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
391

Cyrus Leung's avatar
Cyrus Leung committed
392
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
393
394
395
396
397
398
399
400
401
402
def hf_runner():
    return HfRunner


class VllmRunner:

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

    def generate(
        self,
        prompts: List[str],
        sampling_params: SamplingParams,
434
        images: Optional[List["MultiModalDataDict"]] = None,
435
    ) -> List[Tuple[List[List[int]], List[str]]]:
436
        if images is not None:
437
            assert len(prompts) == len(images)
438

439
440
441
442
        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
443

444
        req_outputs = self.model.generate(inputs,
445
                                          sampling_params=sampling_params)
446
447

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

461
462
463
464
    def generate_w_logprobs(
        self,
        prompts: List[str],
        sampling_params: SamplingParams,
465
    ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
466
467
468
469
        assert sampling_params.logprobs is not None

        req_outputs = self.model.generate(prompts,
                                          sampling_params=sampling_params)
470
        outputs: List[Tuple[List[int], str, Optional[SampleLogprobs]]] = []
471
472
473
474
475
476
477
478
        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
479
480
481
482
    def generate_greedy(
        self,
        prompts: List[str],
        max_tokens: int,
483
        images: Optional[List["MultiModalDataDict"]] = None,
Woosuk Kwon's avatar
Woosuk Kwon committed
484
485
    ) -> List[Tuple[List[int], str]]:
        greedy_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
486
        outputs = self.generate(prompts, greedy_params, images=images)
487
488
        return [(output_ids[0], output_str[0])
                for output_ids, output_str in outputs]
489

490
491
492
493
494
    def generate_greedy_logprobs(
        self,
        prompts: List[str],
        max_tokens: int,
        num_logprobs: int,
495
    ) -> List[Tuple[List[int], str, Optional[SampleLogprobs]]]:
496
497
498
499
500
501
502
503
        greedy_logprobs_params = SamplingParams(temperature=0.0,
                                                max_tokens=max_tokens,
                                                logprobs=num_logprobs)
        outputs = self.generate_w_logprobs(prompts, greedy_logprobs_params)

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

504
505
506
507
508
    def generate_beam_search(
        self,
        prompts: List[str],
        beam_width: int,
        max_tokens: int,
509
    ) -> List[Tuple[List[List[int]], List[str]]]:
510
511
512
513
514
515
        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
516

517
518
519
520
521
522
523
524
    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

525
526
527
528
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
529
530
531
        del self.model
        cleanup()

Woosuk Kwon's avatar
Woosuk Kwon committed
532

533
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
534
535
def vllm_runner():
    return VllmRunner
536
537
538
539
540
541
542
543
544
545


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}")
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561


@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
562
563
564
565
566
567
568


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

569
    return cuda_device_count_stateless()