__init__.py 4.57 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

Woosuk Kwon's avatar
Woosuk Kwon committed
4
import enum
5
import inspect
Zhuohan Li's avatar
Zhuohan Li committed
6
import uuid
7
import warnings
8
9
from functools import wraps
from typing import Any, TypeVar
Zhuohan Li's avatar
Zhuohan Li committed
10
11

import torch
12

13
from vllm.logger import init_logger
14

15
16
17
_DEPRECATED_MAPPINGS = {
    "cprofile": "profiling",
    "cprofile_context": "profiling",
18
    # Used by lm-eval
19
20
    "get_open_port": "network_utils",
}
21
22
23


def __getattr__(name: str) -> Any:  # noqa: D401 - short deprecation docstring
24
25
26
    """Module-level getattr to handle deprecated utilities."""
    if name in _DEPRECATED_MAPPINGS:
        submodule_name = _DEPRECATED_MAPPINGS[name]
27
28
        warnings.warn(
            f"vllm.utils.{name} is deprecated and will be removed in a future version. "
29
            f"Use vllm.utils.{submodule_name}.{name} instead.",
30
31
32
            DeprecationWarning,
            stacklevel=2,
        )
33
34
        module = __import__(f"vllm.utils.{submodule_name}", fromlist=[submodule_name])
        return getattr(module, name)
35
36
37
38
39
    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


def __dir__() -> list[str]:
    # expose deprecated names in dir() for better UX/tab-completion
40
    return sorted(list(globals().keys()) + list(_DEPRECATED_MAPPINGS.keys()))
41
42


43
44
logger = init_logger(__name__)

45
46
47
48
49
50
# This value is chosen to have a balance between ITL and TTFT. Note it is
# not optimized for throughput.
DEFAULT_MAX_NUM_BATCHED_TOKENS = 2048
POOLING_MODEL_MAX_NUM_BATCHED_TOKENS = 32768
MULTIMODAL_MODEL_MAX_NUM_BATCHED_TOKENS = 5120

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Constants related to forcing the attention backend selection

# String name of register which may be set in order to
# force auto-selection of attention backend by Attention
# wrapper
STR_BACKEND_ENV_VAR: str = "VLLM_ATTENTION_BACKEND"

# Possible string values of STR_BACKEND_ENV_VAR
# register, corresponding to possible backends
STR_FLASHINFER_ATTN_VAL: str = "FLASHINFER"
STR_TORCH_SDPA_ATTN_VAL: str = "TORCH_SDPA"
STR_XFORMERS_ATTN_VAL: str = "XFORMERS"
STR_FLASH_ATTN_VAL: str = "FLASH_ATTN"
STR_INVALID_VAL: str = "INVALID"

66

67
68
T = TypeVar("T")

69

70
71
72
73
74
class LayerBlockType(enum.Enum):
    attention = "attention"
    mamba = "mamba"


Cyrus Leung's avatar
Cyrus Leung committed
75
76
def random_uuid() -> str:
    return str(uuid.uuid4().hex)
77
78


79
def warn_for_unimplemented_methods(cls: type[T]) -> type[T]:
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
    """
    A replacement for `abc.ABC`.
    When we use `abc.ABC`, subclasses will fail to instantiate
    if they do not implement all abstract methods.
    Here, we only require `raise NotImplementedError` in the
    base class, and log a warning if the method is not implemented
    in the subclass.
    """

    original_init = cls.__init__

    def find_unimplemented_methods(self: object):
        unimplemented_methods = []
        for attr_name in dir(self):
            # bypass inner method
95
            if attr_name.startswith("_"):
96
97
98
99
100
101
102
103
104
105
106
107
108
                continue

            try:
                attr = getattr(self, attr_name)
                # get the func of callable method
                if callable(attr):
                    attr_func = attr.__func__
            except AttributeError:
                continue
            src = inspect.getsource(attr_func)
            if "NotImplementedError" in src:
                unimplemented_methods.append(attr_name)
        if unimplemented_methods:
109
110
            method_names = ",".join(unimplemented_methods)
            msg = f"Methods {method_names} not implemented in {self}"
111
            logger.debug(msg)
112
113
114
115
116
117

    @wraps(original_init)
    def wrapped_init(self, *args, **kwargs) -> None:
        original_init(self, *args, **kwargs)
        find_unimplemented_methods(self)

118
    type.__setattr__(cls, "__init__", wrapped_init)
119
    return cls
120
121


122
def length_from_prompt_token_ids_or_embeds(
123
124
    prompt_token_ids: list[int] | None,
    prompt_embeds: torch.Tensor | None,
125
) -> int:
126
    """Calculate the request length (in number of tokens) give either
127
128
    prompt_token_ids or prompt_embeds.
    """
129
130
    prompt_token_len = None if prompt_token_ids is None else len(prompt_token_ids)
    prompt_embeds_len = None if prompt_embeds is None else len(prompt_embeds)
131
132
133

    if prompt_token_len is None:
        if prompt_embeds_len is None:
134
            raise ValueError("Neither prompt_token_ids nor prompt_embeds were defined.")
135
136
        return prompt_embeds_len
    else:
137
        if prompt_embeds_len is not None and prompt_embeds_len != prompt_token_len:
138
139
140
            raise ValueError(
                "Prompt token ids and prompt embeds had different lengths"
                f" prompt_token_ids={prompt_token_len}"
141
142
                f" prompt_embeds={prompt_embeds_len}"
            )
143
        return prompt_token_len