conftest.py 42.5 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6
7
8
9
10
11
12

# ruff: noqa

from tblib import pickling_support

# Install support for pickling exceptions so that we can nicely propagate
# failures from tests running in a subprocess.
# This should be run before any custom exception subclasses are defined.
pickling_support.install()

13
import http.server
14
import json
15
import math
16
import mimetypes
17
import os
18
import socket
19
import tempfile
20
21
import threading
from collections.abc import Generator
22
from contextlib import nullcontext
23
from enum import Enum
24
from typing import Any, Callable, Optional, TypedDict, TypeVar, Union, cast
Woosuk Kwon's avatar
Woosuk Kwon committed
25

26
import numpy as np
Woosuk Kwon's avatar
Woosuk Kwon committed
27
28
import pytest
import torch
29
import torch.nn as nn
30
import torch.nn.functional as F
31
from huggingface_hub import snapshot_download
32
from PIL import Image
33
34
35
36
37
38
39
from transformers import (
    AutoConfig,
    AutoModelForCausalLM,
    AutoTokenizer,
    BatchEncoding,
    BatchFeature,
)
40
from transformers.models.auto.auto_factory import _BaseAutoModelClass
Woosuk Kwon's avatar
Woosuk Kwon committed
41

42
from tests.models.utils import TokensTextLogprobs, TokensTextLogprobsPromptLogprobs
Woosuk Kwon's avatar
Woosuk Kwon committed
43
from vllm import LLM, SamplingParams
44
from vllm.assets.audio import AudioAsset
45
from vllm.assets.image import ImageAsset
46
from vllm.assets.video import VideoAsset
47
from vllm.config.model import ConvertOption, RunnerOption, _get_and_verify_dtype
48
from vllm.connections import global_http_connection
49
50
51
52
53
from vllm.distributed import (
    cleanup_dist_env_and_memory,
    init_distributed_environment,
    initialize_model_parallel,
)
54
from vllm.logger import init_logger
55
from vllm.logprobs import Logprob
56
from vllm.multimodal.utils import fetch_image
57
from vllm.outputs import RequestOutput
58
from vllm.sampling_params import BeamSearchParams
59
from vllm.transformers_utils.utils import maybe_model_redirect
60
from vllm.utils import is_list_of, set_default_torch_num_threads
61

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

64
65
66
_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")]
67
_SYS_MSG = os.path.join(_TEST_DIR, "system_messages", "sonnet3.5_nov2024.txt")
68

Cyrus Leung's avatar
Cyrus Leung committed
69
_M = TypeVar("_M")
70

71
_PromptMultiModalInput = Union[list[_M], list[list[_M]]]
Cyrus Leung's avatar
Cyrus Leung committed
72
73

PromptImageInput = _PromptMultiModalInput[Image.Image]
74
PromptAudioInput = _PromptMultiModalInput[tuple[np.ndarray, int]]
Cyrus Leung's avatar
Cyrus Leung committed
75
PromptVideoInput = _PromptMultiModalInput[np.ndarray]
76

77

78
def _read_prompts(filename: str) -> list[str]:
79
    with open(filename) as f:
80
81
        prompts = f.readlines()
        return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
82
83


84
class ImageAssetPrompts(TypedDict):
85
86
    stop_sign: str
    cherry_blossom: str
87
88


89
class ImageTestAssets(list[ImageAsset]):
90
    def __init__(self) -> None:
91
92
93
94
95
96
        super().__init__(
            [
                ImageAsset("stop_sign"),
                ImageAsset("cherry_blossom"),
            ]
        )
97

98
    def prompts(self, prompts: ImageAssetPrompts) -> list[str]:
99
100
101
102
103
104
        """
        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.
        """
105
        return [prompts["stop_sign"], prompts["cherry_blossom"]]
106
107


108
109
class VideoAssetPrompts(TypedDict):
    baby_reading: str
110
111


112
class VideoTestAssets(list[VideoAsset]):
113
    def __init__(self) -> None:
114
115
116
117
118
        super().__init__(
            [
                VideoAsset("baby_reading"),
            ]
        )
119

120
121
    def prompts(self, prompts: VideoAssetPrompts) -> list[str]:
        return [prompts["baby_reading"]]
122
123


124
class AudioAssetPrompts(TypedDict):
125
126
127
128
    mary_had_lamb: str
    winning_call: str


129
class AudioTestAssets(list[AudioAsset]):
130
    def __init__(self) -> None:
131
132
133
134
135
136
        super().__init__(
            [
                AudioAsset("mary_had_lamb"),
                AudioAsset("winning_call"),
            ]
        )
137

138
    def prompts(self, prompts: AudioAssetPrompts) -> list[str]:
139
140
        return [prompts["mary_had_lamb"], prompts["winning_call"]]

141

142
IMAGE_ASSETS = ImageTestAssets()
143
"""Singleton instance of {class}`ImageTestAssets`."""
144
VIDEO_ASSETS = VideoTestAssets()
145
"""Singleton instance of {class}`VideoTestAssets`."""
146
AUDIO_ASSETS = AudioTestAssets()
147
"""Singleton instance of {class}`AudioTestAssets`."""
148
149


150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
@pytest.fixture(scope="function", autouse=True)
def cleanup_VLLM_USE_V1(monkeypatch):
    """
    The V1 oracle sets "VLLM_USE_V1" during loading. This means
    that each invocation of a test change the env variable.

    If we touch "VLLM_USE_V1" with monkeypatch, then any changes
    made during the test run by vLLM will be cleaned up.

    This fixture is used by every test.
    """

    # If VLLM_USE_V1 is not set, set then delete. This will
    # cause monkeypatch to clean up VLLM_USE_V1 upon exit
    # if VLLM modifies the value of envs.VLLM_USE_V1.
    if "VLLM_USE_V1" not in os.environ:
        monkeypatch.setenv("VLLM_USE_V1", "")
        monkeypatch.delenv("VLLM_USE_V1")


170
171
172
173
174
175
176
@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


177
178
179
180
181
182
183
184
185
186
187
188
@pytest.fixture
def dist_init():
    temp_file = tempfile.mkstemp()[1]
    init_distributed_environment(
        world_size=1,
        rank=0,
        distributed_init_method=f"file://{temp_file}",
        local_rank=0,
        backend="nccl",
    )
    initialize_model_parallel(1, 1)
    yield
189
    cleanup_dist_env_and_memory()
190
191


192
@pytest.fixture()
193
def should_do_global_cleanup_after_test(request) -> bool:
194
195
196
197
    """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.
    """
198

199
    return not request.node.get_closest_marker("skip_global_cleanup")
200
201


202
@pytest.fixture(autouse=True)
203
def cleanup_fixture(should_do_global_cleanup_after_test: bool):
204
    yield
205
    if should_do_global_cleanup_after_test:
206
        cleanup_dist_env_and_memory()
207
208


209
210
211
212
213
214
@pytest.fixture(autouse=True)
def dynamo_reset():
    yield
    torch._dynamo.reset()


Woosuk Kwon's avatar
Woosuk Kwon committed
215
@pytest.fixture
216
def example_prompts() -> list[str]:
217
218
    prompts = []
    for filename in _TEST_PROMPTS:
219
        prompts += _read_prompts(filename)
220
221
222
    return prompts


223
224
225
226
227
228
@pytest.fixture
def example_system_message() -> str:
    with open(_SYS_MSG) as f:
        return f.read()


229
230
class DecoderPromptType(Enum):
    """For encoder/decoder models only."""
231

232
233
234
235
236
    CUSTOM = 1
    NONE = 2
    EMPTY_STR = 3


237
@pytest.fixture
238
def example_long_prompts() -> list[str]:
239
240
    prompts = []
    for filename in _LONG_PROMPTS:
241
        prompts += _read_prompts(filename)
242
    return prompts
Woosuk Kwon's avatar
Woosuk Kwon committed
243
244


245
@pytest.fixture(scope="session")
246
def image_assets() -> ImageTestAssets:
247
248
249
    return IMAGE_ASSETS


250
@pytest.fixture(scope="session")
251
def video_assets() -> VideoTestAssets:
252
253
254
    return VIDEO_ASSETS


255
@pytest.fixture(scope="session")
256
def audio_assets() -> AudioTestAssets:
257
258
259
    return AUDIO_ASSETS


260
_T = TypeVar("_T", nn.Module, torch.Tensor, BatchEncoding, BatchFeature, dict)
261
_R = TypeVar("_R")
262

Woosuk Kwon's avatar
Woosuk Kwon committed
263
264

class HfRunner:
265
    def get_default_device(self):
266
        from vllm.platforms import current_platform
267

268
        return "cpu" if current_platform.is_cpu() else current_platform.device_type
269
270

    def wrap_device(self, x: _T, device: Optional[str] = None) -> _T:
271
        if x is None or isinstance(x, (bool,)):
272
273
            return x

274
        if device is None:
275
            device = self.device
276

277
278
        if isinstance(x, dict):
            return {k: self.wrap_device(v, device) for k, v in x.items()}
279

280
281
282
283
        if hasattr(x, "device") and x.device.type == device:
            return x

        return x.to(device)
284

Woosuk Kwon's avatar
Woosuk Kwon committed
285
286
287
    def __init__(
        self,
        model_name: str,
288
        dtype: str = "auto",
289
        *,
290
        model_kwargs: Optional[dict[str, Any]] = None,
291
        trust_remote_code: bool = True,
292
        is_sentence_transformer: bool = False,
293
        is_cross_encoder: bool = False,
294
        skip_tokenizer_init: bool = False,
295
        auto_cls: type[_BaseAutoModelClass] = AutoModelForCausalLM,
296
297
298
        # Set this to avoid hanging issue
        default_torch_num_threads: Optional[int] = None,
    ) -> None:
299
300
301
302
303
        init_ctx = (
            nullcontext()
            if default_torch_num_threads is None
            else set_default_torch_num_threads(default_torch_num_threads)
        )
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327

        with init_ctx:
            self._init(
                model_name=model_name,
                dtype=dtype,
                model_kwargs=model_kwargs,
                trust_remote_code=trust_remote_code,
                is_sentence_transformer=is_sentence_transformer,
                is_cross_encoder=is_cross_encoder,
                skip_tokenizer_init=skip_tokenizer_init,
                auto_cls=auto_cls,
            )

    def _init(
        self,
        model_name: str,
        dtype: str = "auto",
        *,
        model_kwargs: Optional[dict[str, Any]] = None,
        trust_remote_code: bool = True,
        is_sentence_transformer: bool = False,
        is_cross_encoder: bool = False,
        skip_tokenizer_init: bool = False,
        auto_cls: type[_BaseAutoModelClass] = AutoModelForCausalLM,
Woosuk Kwon's avatar
Woosuk Kwon committed
328
    ) -> None:
329
        model_name = maybe_model_redirect(model_name)
330
        self.model_name = model_name
331

332
333
        self.config = AutoConfig.from_pretrained(
            model_name,
334
            trust_remote_code=trust_remote_code,
335
336
        )
        self.device = self.get_default_device()
337
338
339
340
341
342
        self.dtype = torch_dtype = _get_and_verify_dtype(
            self.model_name,
            self.config,
            dtype=dtype,
            is_pooling_model=is_sentence_transformer or is_cross_encoder,
        )
343
344
345
346

        model_kwargs = model_kwargs if model_kwargs is not None else {}
        model_kwargs.setdefault("torch_dtype", torch_dtype)

347
        if is_sentence_transformer:
348
349
            # Lazy init required for AMD CI
            from sentence_transformers import SentenceTransformer
350
351
352
353
354

            self.model = SentenceTransformer(
                model_name,
                device=self.device,
                model_kwargs=model_kwargs,
355
                trust_remote_code=trust_remote_code,
356
            )
357
358
359
        elif is_cross_encoder:
            # Lazy init required for AMD CI
            from sentence_transformers import CrossEncoder
360
361
362
363
364

            self.model = CrossEncoder(
                model_name,
                device=self.device,
                automodel_args=model_kwargs,
365
                trust_remote_code=trust_remote_code,
366
            )
367
        else:
368
369
            model = auto_cls.from_pretrained(
                model_name,
370
                trust_remote_code=trust_remote_code,
371
372
373
                **model_kwargs,
            )

374
            # in case some unquantized custom models are not in same dtype
375
376
377
            if getattr(model, "quantization_method", None) is None and any(
                p.dtype != self.dtype for p in model.parameters()
            ):
378
379
                model = model.to(dtype=self.dtype)

380
381
382
383
            if (
                getattr(model, "quantization_method", None) != "bitsandbytes"
                and len({p.device for p in model.parameters()}) < 2
            ):
384
                model = model.to(device=self.device)
385
386

            self.model = model
387

388
389
390
391
        if not skip_tokenizer_init:
            self.tokenizer = AutoTokenizer.from_pretrained(
                model_name,
                torch_dtype=torch_dtype,
392
                trust_remote_code=trust_remote_code,
393
            )
394

395
396
397
        # don't put this import at the top level
        # it will call torch.cuda.device_count()
        from transformers import AutoProcessor  # noqa: F401
398

399
400
401
        self.processor = AutoProcessor.from_pretrained(
            model_name,
            torch_dtype=torch_dtype,
402
            trust_remote_code=trust_remote_code,
403
        )
404
405
        if skip_tokenizer_init:
            self.tokenizer = self.processor.tokenizer
Woosuk Kwon's avatar
Woosuk Kwon committed
406

407
    def get_inputs(
Woosuk Kwon's avatar
Woosuk Kwon committed
408
        self,
409
        prompts: Union[list[str], list[list[int]]],
410
        images: Optional[PromptImageInput] = None,
411
412
        videos: Optional[PromptVideoInput] = None,
        audios: Optional[PromptAudioInput] = None,
413
    ) -> list[Union[BatchFeature, BatchEncoding, dict[str, torch.Tensor]]]:
414
        if images is not None:
415
            assert len(prompts) == len(images)
416

417
418
419
420
421
422
        if videos is not None:
            assert len(prompts) == len(videos)

        if audios is not None:
            assert len(prompts) == len(audios)

423
424
425
        all_inputs: list[
            Union[BatchFeature, BatchEncoding, dict[str, torch.Tensor]]
        ] = []
426
        for i, prompt in enumerate(prompts):
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
            if isinstance(prompt, str):
                processor_kwargs: dict[str, Any] = {
                    "text": prompt,
                    "return_tensors": "pt",
                }
                if images is not None and (image := images[i]) is not None:
                    processor_kwargs["images"] = image
                if videos is not None and (video := videos[i]) is not None:
                    processor_kwargs["videos"] = video
                if audios is not None and (audio_inputs := audios[i]) is not None:
                    # HACK - not all processors take sampling_rate; we should
                    # clean this up in the future.
                    if len(audio_inputs) == 2:
                        audio, sr = audio_inputs
                        processor_kwargs["audio"] = audio
                        processor_kwargs["sampling_rate"] = sr
                    else:
                        processor_kwargs["audio"] = audio_inputs

                inputs = self.processor(**processor_kwargs)
                if isinstance(inputs, BatchFeature):
                    inputs = inputs.to(dtype=self.dtype)
                all_inputs.append(inputs)
            else:
                # check that prompt is (batched) list of integers (token ids)
                if not is_list_of(prompt, typ=int, check="all"):
                    raise ValueError(
                        "Prompt must be a list of ints corresponding to the prompt token ids."
                    )
                # check that no multimodal input is provided
                if images or videos or audios:
                    raise ValueError(
                        "When providing prompt token ids multimodal inputs are not supported."
                    )
                input_dict = {
                    "input_ids": torch.tensor(prompt, dtype=torch.long).unsqueeze(0),
                }
                all_inputs.append(input_dict)
465
466
467

        return all_inputs

468
469
470
471
472
473
474
475
476
    def get_prompt_embeddings(self, prompts: list[str]) -> list[torch.Tensor]:
        all_inputs = self.get_inputs(prompts)
        embeddings = []
        for inputs in all_inputs:
            input_ids = self.wrap_device(inputs)["input_ids"]
            embedding = self.model.get_input_embeddings()(input_ids).squeeze(0)
            embeddings.append(embedding)
        return embeddings

477
    def classify(self, prompts: list[str]) -> list[str]:
478
479
480
        # output is final logits
        all_inputs = self.get_inputs(prompts)
        outputs = []
481
482
        problem_type = getattr(self.config, "problem_type", "")

483
484
        for inputs in all_inputs:
            output = self.model(**self.wrap_device(inputs))
485
486
487
488
489
490
            if problem_type == "regression":
                logits = output.logits[0].tolist()
            elif problem_type == "multi_label_classification":
                logits = output.logits.sigmoid()[0].tolist()
            else:
                logits = output.logits.softmax(dim=-1)[0].tolist()
491
492
493
494
            outputs.append(logits)

        return outputs

495
496
    def generate(
        self,
497
        prompts: Union[list[str], list[list[int]]],
498
        images: Optional[PromptImageInput] = None,
Cyrus Leung's avatar
Cyrus Leung committed
499
        videos: Optional[PromptVideoInput] = None,
500
501
        audios: Optional[PromptAudioInput] = None,
        **kwargs: Any,
502
    ) -> list[tuple[list[list[int]], list[str]]]:
503
504
505
        all_inputs = self.get_inputs(
            prompts, images=images, videos=videos, audios=audios
        )
506

507
        outputs: list[tuple[list[list[int]], list[str]]] = []
508
        for inputs in all_inputs:
Woosuk Kwon's avatar
Woosuk Kwon committed
509
            output_ids = self.model.generate(
510
                **self.wrap_device(inputs),
Woosuk Kwon's avatar
Woosuk Kwon committed
511
512
513
                use_cache=True,
                **kwargs,
            )
514
            output_str = self.processor.batch_decode(
Woosuk Kwon's avatar
Woosuk Kwon committed
515
516
517
                output_ids,
                skip_special_tokens=True,
                clean_up_tokenization_spaces=False,
518
519
            )
            output_ids = output_ids.cpu().tolist()
Woosuk Kwon's avatar
Woosuk Kwon committed
520
521
522
523
524
            outputs.append((output_ids, output_str))
        return outputs

    def generate_greedy(
        self,
525
        prompts: Union[list[str], list[list[int]]],
Woosuk Kwon's avatar
Woosuk Kwon committed
526
        max_tokens: int,
527
        images: Optional[PromptImageInput] = None,
Cyrus Leung's avatar
Cyrus Leung committed
528
        videos: Optional[PromptVideoInput] = None,
529
        audios: Optional[PromptAudioInput] = None,
530
        **kwargs: Any,
531
    ) -> list[tuple[list[int], str]]:
532
533
534
535
536
537
538
539
540
        outputs = self.generate(
            prompts,
            do_sample=False,
            max_new_tokens=max_tokens,
            images=images,
            videos=videos,
            audios=audios,
            **kwargs,
        )
541

542
        return [(output_ids[0], output_str[0]) for output_ids, output_str in outputs]
543
544
545

    def generate_beam_search(
        self,
546
        prompts: list[str],
547
548
        beam_width: int,
        max_tokens: int,
549
550
551
        images: Optional[PromptImageInput] = None,
        videos: Optional[PromptVideoInput] = None,
        audios: Optional[PromptAudioInput] = None,
552
    ) -> list[tuple[list[list[int]], list[str]]]:
553
554
555
556
557
558
559
560
561
562
        outputs = self.generate(
            prompts,
            do_sample=False,
            max_new_tokens=max_tokens,
            num_beams=beam_width,
            num_return_sequences=beam_width,
            images=images,
            videos=videos,
            audios=audios,
        )
563

564
565
566
567
        for i in range(len(outputs)):
            output_ids, output_str = outputs[i]
            for j in range(len(output_ids)):
                output_ids[j] = [
568
                    x for x in output_ids[j] if x != self.tokenizer.pad_token_id
569
570
571
                ]
            outputs[i] = (output_ids, output_str)
        return outputs
Woosuk Kwon's avatar
Woosuk Kwon committed
572

573
574
    def generate_greedy_logprobs(
        self,
575
        prompts: list[str],
576
        max_tokens: int,
577
        images: Optional[PromptImageInput] = None,
Cyrus Leung's avatar
Cyrus Leung committed
578
        videos: Optional[PromptVideoInput] = None,
579
        audios: Optional[PromptAudioInput] = None,
580
        **kwargs: Any,
581
    ) -> list[list[torch.Tensor]]:
582
583
584
        all_inputs = self.get_inputs(
            prompts, images=images, videos=videos, audios=audios
        )
585

586
        all_logprobs: list[list[torch.Tensor]] = []
587
        for inputs in all_inputs:
588
            output = self.model.generate(
589
                **self.wrap_device(inputs),
590
591
592
593
594
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
595
                **kwargs,
596
            )
597
            seq_logprobs = self._hidden_states_to_seq_logprobs(output.hidden_states)
598
599
600
            all_logprobs.append(seq_logprobs)
        return all_logprobs

601
    def _hidden_states_to_seq_logprobs(
602
        self,
603
604
        hidden_states: tuple[tuple[torch.Tensor, ...], ...],
    ) -> list[torch.Tensor]:
605
606
        output_embeddings = self.model.get_output_embeddings()

607
        seq_logprobs: list[torch.Tensor] = []
608
609
610
        for _, hidden_state in enumerate(hidden_states):
            last_hidden_states = hidden_state[-1][0]
            logits = torch.matmul(
611
612
613
614
                last_hidden_states.to(
                    device=output_embeddings.weight.device,
                    dtype=output_embeddings.weight.dtype,
                ),
615
                output_embeddings.weight.t(),
616
            )
617
618
            if getattr(output_embeddings, "bias", None) is not None:
                logits += output_embeddings.bias.unsqueeze(0)
619
620
621
            logprobs = F.log_softmax(logits, dim=-1, dtype=torch.float32)
            seq_logprobs.append(logprobs)

622
623
624
625
        return seq_logprobs

    def _hidden_states_to_logprobs(
        self,
626
        hidden_states: tuple[tuple[torch.Tensor, ...], ...],
627
        num_logprobs: Optional[int],
628
    ) -> tuple[list[dict[int, float]], int]:
629
630
631
        seq_logprobs = self._hidden_states_to_seq_logprobs(hidden_states)
        output_len = len(hidden_states)

632
        # convert to dict
633
        seq_logprobs_lst: list[dict[int, float]] = []
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
        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)

        return (
            seq_logprobs_lst,
            output_len,
        )

651
652
    def generate_greedy_logprobs_limit(
        self,
653
        prompts: list[str],
654
        max_tokens: int,
655
        num_logprobs: Optional[int],
656
657
        images: Optional[PromptImageInput] = None,
        audios: Optional[PromptAudioInput] = None,
Cyrus Leung's avatar
Cyrus Leung committed
658
        videos: Optional[PromptVideoInput] = None,
659
        **kwargs: Any,
660
    ) -> list[TokensTextLogprobs]:
661
662
663
        all_inputs = self.get_inputs(
            prompts, images=images, videos=videos, audios=audios
        )
664

665
666
667
        all_logprobs: list[list[dict[int, float]]] = []
        all_output_ids: list[list[int]] = []
        all_output_strs: list[str] = []
668

669
        for inputs in all_inputs:
670
            output = self.model.generate(
671
                **self.wrap_device(inputs),
672
673
674
675
676
                use_cache=True,
                do_sample=False,
                max_new_tokens=max_tokens,
                output_hidden_states=True,
                return_dict_in_generate=True,
677
                **kwargs,
678
679
            )

680
681
682
            (
                seq_logprobs_lst,
                output_len,
683
            ) = self._hidden_states_to_logprobs(output.hidden_states, num_logprobs)
684
685
686
687
688
689
690

            all_logprobs.append(seq_logprobs_lst)
            seq_ids = output.sequences[0]
            output_len = len(seq_logprobs_lst)
            output_ids = seq_ids[-output_len:]
            all_output_ids.append(output_ids.tolist())
            all_output_strs.append(self.tokenizer.decode(output_ids))
691

692
        outputs = zip(all_output_ids, all_output_strs, all_logprobs)
693
694
695
696
        return [
            (output_ids, output_str, output_logprobs)
            for output_ids, output_str, output_logprobs in outputs
        ]
697

698
    def encode(self, prompts: list[str], *args, **kwargs) -> list[list[torch.Tensor]]:
699
        return self.model.encode(prompts, *args, **kwargs)
700

701
702
    def predict(self, prompts: list[list[str]], *args, **kwargs) -> torch.Tensor:
        return self.model.predict(prompts, *args, convert_to_tensor=True, **kwargs)
703

704
705
706
707
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
708
        del self.model
709
        cleanup_dist_env_and_memory()
710

Woosuk Kwon's avatar
Woosuk Kwon committed
711

Cyrus Leung's avatar
Cyrus Leung committed
712
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
713
714
715
716
717
def hf_runner():
    return HfRunner


class VllmRunner:
718
719
    """
    The default value of some arguments have been modified from
720
    {class}`~vllm.LLM` as follows:
721

722
723
724
    - `trust_remote_code`: Set to `True` instead of `False` for convenience.
    - `seed`: Set to `0` instead of `None` for test reproducibility.
    - `max_model_len`: Set to `1024` instead of `None` to reduce memory usage.
725
726
    - `block_size`: To reduce memory usage, set default to `64` if on XPU
        devices, otherwise default to `16`.
727
728
    - `enable_chunked_prefill`: Set to `False` instead of `None` for
      test reproducibility.
729
    - `enforce_eager`: Set to `False` to test CUDA graph.
730
    """
Woosuk Kwon's avatar
Woosuk Kwon committed
731
732
733
734

    def __init__(
        self,
        model_name: str,
735
736
        runner: RunnerOption = "auto",
        convert: ConvertOption = "auto",
Woosuk Kwon's avatar
Woosuk Kwon committed
737
        tokenizer_name: Optional[str] = None,
738
        tokenizer_mode: str = "auto",
739
740
        trust_remote_code: bool = True,
        seed: Optional[int] = 0,
741
        max_model_len: Optional[int] = 1024,
742
        dtype: str = "auto",
743
        disable_log_stats: bool = True,
744
        tensor_parallel_size: int = 1,
745
        block_size: int = 16 if not torch.xpu.is_available() else 64,
746
        enable_chunked_prefill: Optional[bool] = False,
747
        swap_space: int = 4,
748
        enforce_eager: Optional[bool] = False,
749
750
        # Set this to avoid hanging issue
        default_torch_num_threads: Optional[int] = None,
751
        **kwargs,
Woosuk Kwon's avatar
Woosuk Kwon committed
752
    ) -> None:
753
754
755
756
757
        init_ctx = (
            nullcontext()
            if default_torch_num_threads is None
            else set_default_torch_num_threads(default_torch_num_threads)
        )
758

759
        if not kwargs.get("compilation_config", None):
760
761
762
763
            # Note(@tdoublep): This is set to 4 because some tests (e.g., hybrid
            # model tests) may set max_num_seqs=4. If min cudagraph_capture_size is
            # set to larger than max_num_seqs, then it will lead to *no* graphs
            # being captured which can trigger edge cases that we don't handle yet.
764
            kwargs["compilation_config"] = {"cudagraph_capture_sizes": [4]}
765

766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
        with init_ctx:
            self.llm = LLM(
                model=model_name,
                runner=runner,
                convert=convert,
                tokenizer=tokenizer_name,
                tokenizer_mode=tokenizer_mode,
                trust_remote_code=trust_remote_code,
                dtype=dtype,
                seed=seed,
                swap_space=swap_space,
                enforce_eager=enforce_eager,
                disable_log_stats=disable_log_stats,
                tensor_parallel_size=tensor_parallel_size,
                max_model_len=max_model_len,
                block_size=block_size,
                enable_chunked_prefill=enable_chunked_prefill,
                **kwargs,
            )
Woosuk Kwon's avatar
Woosuk Kwon committed
785

786
    def get_inputs(
Woosuk Kwon's avatar
Woosuk Kwon committed
787
        self,
788
        prompts: Union[list[str], list[torch.Tensor], list[list[int]]],
789
        images: Optional[PromptImageInput] = None,
790
791
        videos: Optional[PromptVideoInput] = None,
        audios: Optional[PromptAudioInput] = None,
792
    ) -> list[dict[str, Any]]:
793
794
795
        if any(
            x is not None and len(x) != len(prompts) for x in [images, videos, audios]
        ):
796
            raise ValueError(
797
798
                "All non-None multimodal inputs must have the same length as prompts"
            )
799

800
        inputs = list[dict[str, Any]]()
801
        for i, prompt in enumerate(prompts):
802
803
804
805
806
807
808
809
810
            prompt_dict = dict[str, Any]()
            if isinstance(prompt, str):
                prompt_dict["prompt"] = prompt
            elif isinstance(prompt, list):
                prompt_dict["prompt_token_ids"] = prompt
            else:
                prompt_dict["prompt_embeds"] = prompt

            multi_modal_data = dict[str, Any]()
811
812
813
814
815
816
817
            if images is not None and (image := images[i]) is not None:
                multi_modal_data["image"] = image
            if videos is not None and (video := videos[i]) is not None:
                multi_modal_data["video"] = video
            if audios is not None and (audio := audios[i]) is not None:
                multi_modal_data["audio"] = audio

818
819
            if multi_modal_data:
                prompt_dict["multi_modal_data"] = multi_modal_data
820

821
            inputs.append(prompt_dict)
822
823
824
825
826

        return inputs

    def generate(
        self,
827
        prompts: Union[list[str], list[torch.Tensor], list[list[int]]],
828
829
830
831
        sampling_params: SamplingParams,
        images: Optional[PromptImageInput] = None,
        videos: Optional[PromptVideoInput] = None,
        audios: Optional[PromptAudioInput] = None,
832
        **kwargs: Any,
833
    ) -> list[tuple[list[list[int]], list[str]]]:
834
        inputs = self.get_inputs(prompts, images=images, videos=videos, audios=audios)
835

836
837
838
        req_outputs = self.llm.generate(
            inputs, sampling_params=sampling_params, **kwargs
        )
839

840
        outputs: list[tuple[list[list[int]], list[str]]] = []
Woosuk Kwon's avatar
Woosuk Kwon committed
841
842
843
        for req_output in req_outputs:
            prompt_str = req_output.prompt
            prompt_ids = req_output.prompt_token_ids
844
845
            req_sample_output_ids: list[list[int]] = []
            req_sample_output_strs: list[str] = []
846
847
            for sample in req_output.outputs:
                output_str = sample.text
848
                output_ids = list(sample.token_ids)
849
                req_sample_output_ids.append(prompt_ids + output_ids)
850
                req_sample_output_strs.append((prompt_str or "") + output_str)
851
            outputs.append((req_sample_output_ids, req_sample_output_strs))
Woosuk Kwon's avatar
Woosuk Kwon committed
852
853
        return outputs

854
    @staticmethod
855
    def _final_steps_generate_w_logprobs(
856
857
858
        req_outputs: list[RequestOutput],
    ) -> list[TokensTextLogprobsPromptLogprobs]:
        outputs: list[TokensTextLogprobsPromptLogprobs] = []
859
        for req_output in req_outputs:
860
            assert len(req_output.outputs) > 0
861
862
            for sample in req_output.outputs:
                output_str = sample.text
863
                output_ids = list(sample.token_ids)
864
                output_logprobs = sample.logprobs
865
866
867
            outputs.append(
                (output_ids, output_str, output_logprobs, req_output.prompt_logprobs)
            )
868
869
        return outputs

870
871
    def generate_w_logprobs(
        self,
872
        prompts: list[str],
873
        sampling_params: SamplingParams,
874
875
        images: Optional[PromptImageInput] = None,
        audios: Optional[PromptAudioInput] = None,
876
        videos: Optional[PromptVideoInput] = None,
877
        **kwargs: Any,
878
879
880
881
882
883
884
885
886
887
    ) -> Union[list[TokensTextLogprobs], list[TokensTextLogprobsPromptLogprobs]]:
        inputs = self.get_inputs(prompts, images=images, videos=videos, audios=audios)

        req_outputs = self.llm.generate(
            inputs, sampling_params=sampling_params, **kwargs
        )

        toks_str_logsprobs_prompt_logprobs = self._final_steps_generate_w_logprobs(
            req_outputs
        )
888
        # Omit prompt logprobs if not required by sampling params
889
890
891
892
893
        return (
            [x[0:-1] for x in toks_str_logsprobs_prompt_logprobs]
            if sampling_params.prompt_logprobs is None
            else toks_str_logsprobs_prompt_logprobs
        )
894

Woosuk Kwon's avatar
Woosuk Kwon committed
895
896
    def generate_greedy(
        self,
897
        prompts: Union[list[str], list[torch.Tensor], list[list[int]]],
Woosuk Kwon's avatar
Woosuk Kwon committed
898
        max_tokens: int,
899
        images: Optional[PromptImageInput] = None,
900
901
        videos: Optional[PromptVideoInput] = None,
        audios: Optional[PromptAudioInput] = None,
902
        **kwargs: Any,
903
    ) -> list[tuple[list[int], str]]:
Woosuk Kwon's avatar
Woosuk Kwon committed
904
        greedy_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
905
906
907
908
909
910
911
912
913
        outputs = self.generate(
            prompts,
            greedy_params,
            images=images,
            videos=videos,
            audios=audios,
            **kwargs,
        )
        return [(output_ids[0], output_str[0]) for output_ids, output_str in outputs]
914

915
916
    def generate_greedy_logprobs(
        self,
917
        prompts: list[str],
918
        max_tokens: int,
919
        num_logprobs: Optional[int],
920
        num_prompt_logprobs: Optional[int] = None,
921
922
        images: Optional[PromptImageInput] = None,
        audios: Optional[PromptAudioInput] = None,
923
        videos: Optional[PromptVideoInput] = None,
924
925
        stop_token_ids: Optional[list[int]] = None,
        stop: Optional[list[str]] = None,
926
        **kwargs: Any,
927
    ) -> Union[list[TokensTextLogprobs], list[TokensTextLogprobsPromptLogprobs]]:
928
929
930
931
        greedy_logprobs_params = SamplingParams(
            temperature=0.0,
            max_tokens=max_tokens,
            logprobs=num_logprobs,
932
            prompt_logprobs=num_prompt_logprobs,
933
            stop_token_ids=stop_token_ids,
934
935
            stop=stop,
        )
936

937
938
939
940
941
942
943
944
        return self.generate_w_logprobs(
            prompts,
            greedy_logprobs_params,
            images=images,
            audios=audios,
            videos=videos,
            **kwargs,
        )
945

946
947
948
949
950
951
952
    def generate_prompt_perplexity(self, prompts: list[str]) -> list[float]:
        """
        Return the perplexity score associated with generating the prompts

        :param prompts: list of prompts to score
        :return: perplexity score of each prompt
        """
953
954
955
        outputs = self.generate_greedy_logprobs(
            prompts, max_tokens=1, num_logprobs=None, num_prompt_logprobs=0
        )
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973

        perplexities = []
        for output in outputs:
            output = cast(TokensTextLogprobsPromptLogprobs, output)
            token_datas = cast(list[Optional[dict[int, Logprob]]], output[3])
            assert token_datas[0] is None
            token_log_probs = []
            for token_data in token_datas[1:]:
                assert token_data is not None
                assert len(token_data) == 1
                token_log_prob = list(token_data.values())[0].logprob
                token_log_probs.append(token_log_prob)

            perplexity = math.exp(-sum(token_log_probs) / len(token_log_probs))
            perplexities.append(perplexity)

        return perplexities

974
    def generate_beam_search(
975
        self,
976
        prompts: list[str],
977
978
        beam_width: int,
        max_tokens: int,
979
980
981
        images: Optional[PromptImageInput] = None,
        videos: Optional[PromptVideoInput] = None,
        audios: Optional[PromptAudioInput] = None,
982
        concurrency_limit: Optional[int] = None,
983
    ) -> list[tuple[list[list[int]], list[str]]]:
984
985
986
987
988
989
990
        inputs = self.get_inputs(prompts, images=images, videos=videos, audios=audios)

        outputs = self.llm.beam_search(
            inputs,
            BeamSearchParams(beam_width=beam_width, max_tokens=max_tokens),
            concurrency_limit=concurrency_limit,
        )
991
992
993
994
995
996
997
        returned_outputs = []
        for output in outputs:
            token_ids = [x.tokens for x in output.sequences]
            texts = [x.text for x in output.sequences]
            returned_outputs.append((token_ids, texts))
        return returned_outputs

998
    def classify(self, prompts: list[str]) -> list[list[float]]:
999
        req_outputs = self.llm.classify(prompts)
1000
1001
        return [req_output.outputs.probs for req_output in req_outputs]

1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
    def embed(
        self,
        prompts: list[str],
        images: Optional[PromptImageInput] = None,
        videos: Optional[PromptVideoInput] = None,
        audios: Optional[PromptAudioInput] = None,
        *args,
        **kwargs,
    ) -> list[list[float]]:
        inputs = self.get_inputs(prompts, images=images, videos=videos, audios=audios)
Cyrus Leung's avatar
Cyrus Leung committed
1012

1013
        req_outputs = self.llm.embed(inputs, *args, **kwargs)
Cyrus Leung's avatar
Cyrus Leung committed
1014
        return [req_output.outputs.embedding for req_output in req_outputs]
1015

1016
    def encode(self, prompts: list[str]) -> list[list[float]]:
1017
        req_outputs = self.llm.encode(prompts)
1018
1019
        return [req_output.outputs.data for req_output in req_outputs]

1020
1021
1022
1023
    def reward(self, prompts: list[str]) -> list[list[float]]:
        req_outputs = self.llm.reward(prompts)
        return [req_output.outputs.data for req_output in req_outputs]

1024
1025
    def score(
        self,
1026
1027
        text_1: Union[str, list[str]],
        text_2: Union[str, list[str]],
1028
1029
        *args,
        **kwargs,
1030
    ) -> list[float]:
1031
        req_outputs = self.llm.score(text_1, text_2, *args, **kwargs)
1032
        return [req_output.outputs.score for req_output in req_outputs]
1033

1034
    def apply_model(self, func: Callable[[nn.Module], _R]) -> list[_R]:
1035
        return self.llm.apply_model(func)
1036

1037
1038
1039
    def get_llm(self) -> LLM:
        return self.llm

1040
1041
1042
1043
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
1044
        del self.llm
1045
        cleanup_dist_env_and_memory()
1046

Woosuk Kwon's avatar
Woosuk Kwon committed
1047

1048
@pytest.fixture(scope="session")
Woosuk Kwon's avatar
Woosuk Kwon committed
1049
1050
def vllm_runner():
    return VllmRunner
1051
1052


1053
1054
1055
@pytest.fixture()
def temporary_enable_log_propagate():
    import logging
1056

1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
    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
1068
1069
1070
1071
1072
1073
1074


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

1075
    from vllm.platforms import current_platform
1076

1077
    return current_platform.device_count()
1078
1079
1080


temp_dir = tempfile.gettempdir()
1081
1082
_dummy_opt_path = os.path.join(temp_dir, "dummy_opt")
_dummy_llava_path = os.path.join(temp_dir, "dummy_llava")
1083
_dummy_gemma2_embedding_path = os.path.join(temp_dir, "dummy_gemma2_embedding")
1084
1085
1086
1087


@pytest.fixture
def dummy_opt_path():
1088
1089
    json_path = os.path.join(_dummy_opt_path, "config.json")
    if not os.path.exists(_dummy_opt_path):
1090
1091
1092
1093
1094
        snapshot_download(
            repo_id="facebook/opt-125m",
            local_dir=_dummy_opt_path,
            ignore_patterns=["*.bin", "*.bin.index.json", "*.pt", "*.h5", "*.msgpack"],
        )
1095
        assert os.path.exists(json_path)
1096
        with open(json_path) as f:
1097
1098
1099
1100
            config = json.load(f)
        config["architectures"] = ["MyOPTForCausalLM"]
        with open(json_path, "w") as f:
            json.dump(config, f)
1101
1102
1103
1104
1105
1106
1107
    return _dummy_opt_path


@pytest.fixture
def dummy_llava_path():
    json_path = os.path.join(_dummy_llava_path, "config.json")
    if not os.path.exists(_dummy_llava_path):
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
        snapshot_download(
            repo_id="llava-hf/llava-1.5-7b-hf",
            local_dir=_dummy_llava_path,
            ignore_patterns=[
                "*.bin",
                "*.bin.index.json",
                "*.pt",
                "*.h5",
                "*.msgpack",
                "*.safetensors",
            ],
        )
1120
        assert os.path.exists(json_path)
1121
        with open(json_path) as f:
1122
1123
1124
1125
1126
            config = json.load(f)
        config["architectures"] = ["MyLlava"]
        with open(json_path, "w") as f:
            json.dump(config, f)
    return _dummy_llava_path
1127
1128
1129
1130
1131
1132


@pytest.fixture
def dummy_gemma2_embedding_path():
    json_path = os.path.join(_dummy_gemma2_embedding_path, "config.json")
    if not os.path.exists(_dummy_gemma2_embedding_path):
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
        snapshot_download(
            repo_id="BAAI/bge-multilingual-gemma2",
            local_dir=_dummy_gemma2_embedding_path,
            ignore_patterns=[
                "*.bin",
                "*.bin.index.json",
                "*.pt",
                "*.h5",
                "*.msgpack",
                "*.safetensors",
            ],
        )
1145
        assert os.path.exists(json_path)
1146
        with open(json_path) as f:
1147
1148
1149
1150
1151
            config = json.load(f)
        config["architectures"] = ["MyGemma2Embedding"]
        with open(json_path, "w") as f:
            json.dump(config, f)
    return _dummy_gemma2_embedding_path
1152
1153
1154
1155
1156


# Add the flag `--optional` to allow run tests
# that are marked with @pytest.mark.optional
def pytest_addoption(parser):
1157
1158
1159
    parser.addoption(
        "--optional", action="store_true", default=False, help="run optional test"
    )
1160
1161
1162
1163
1164
1165
1166
1167
1168


def pytest_collection_modifyitems(config, items):
    if config.getoption("--optional"):
        # --optional given in cli: do not skip optional tests
        return
    skip_optional = pytest.mark.skip(reason="need --optional option to run")
    for item in items:
        if "optional" in item.keywords:
1169
            item.add_marker(skip_optional)
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181


@pytest.fixture(scope="session")
def cli_config_file():
    """Return the path to the CLI config file."""
    return os.path.join(_TEST_DIR, "config", "test_config.yaml")


@pytest.fixture(scope="session")
def cli_config_file_with_model():
    """Return the path to the CLI config file with model."""
    return os.path.join(_TEST_DIR, "config", "test_config_with_model.yaml")
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240


class AssetHandler(http.server.BaseHTTPRequestHandler):
    # _IMAGE_CACHE : Dict[str, bytes] = {}

    def log_message(self, *args, **kwargs):
        pass

    def do_GET(self):
        # Accepts paths like: /1280px-Venn_diagram_rgb.jpg
        filename = self.path.lstrip("/")
        if not filename or "." not in filename:
            self.send_error(404, "Missing filename (expected /<name>.<ext>)")
            return

        base, ext = filename.rsplit(".", 1)
        ext = ext.lower()

        if ext not in ["jpg", "png"]:
            self.send_error(404, f"Unsupported extension: .{ext}")
            return

        try:
            data = ImageAsset(base).read_bytes(ext=ext)
        except Exception as e:
            self.send_error(500, f"Failed to load asset: {ext} {base} {e} ")
            return

        ctype, _ = mimetypes.guess_type(filename)
        if ctype is None:
            ctype = {"jpg": "image/jpg", "png": "image/png"}[ext]
        self.send_response(200)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)


def _find_free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


class LocalAssetServer:
    address: str
    port: int
    server: Optional[http.server.ThreadingHTTPServer]
    thread: Optional[threading.Thread]

    def __init__(self, address: str = "127.0.0.1") -> None:
        self.address = address
        self.port = -1
        self.server = None
        self.thread = None

    def __enter__(self):
        self.port = _find_free_port()
        self.server = http.server.ThreadingHTTPServer(
1241
1242
1243
            (self.address, self.port), AssetHandler
        )
        self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
        self.thread.start()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self.server:
            self.server.shutdown()
            del self.server

        if self.thread:
            self.thread.join()
            del self.thread

        if exc_type is None:
            return None

        return False

    @property
    def base_url(self) -> str:
        assert self.port is not None
        return f"http://{self.address}:{self.port}"

    def url_for(self, name: str) -> str:
        """e.g., name='RGBA_comp.png' -> 'http://127.0.0.1:PORT/RGBA_comp.png'"""
        return f"{self.base_url}/{name}"

    def get_image_asset(self, name: str) -> Image.Image:
        return fetch_image(self.url_for(name))


@pytest.fixture(scope="session")
def local_asset_server() -> Generator[LocalAssetServer, None, None]:
    """
1277
    Starts a thread based HTTP server bound to 127.0.0.1 on a random free port.
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
    The server currently servers images at:
    http://127.0.0.1:<port>/<name>.<ext>
    """
    with LocalAssetServer() as srv:
        yield srv


@pytest.fixture
def image_url(request, local_asset_server) -> str:
    # request.param is one of the IMAGE_ASSETS filenames
    name = request.param
    return local_asset_server.url_for(name)


@pytest.fixture
def image_urls(request, local_asset_server) -> list[str]:
    """Indirect fixture: takes a list of names, returns list of full URLs."""
    names: list[str] = request.param
    return [local_asset_server.url_for(name) for name in names]