__init__.py 9.55 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
import logging
import traceback
from itertools import chain
6
from typing import TYPE_CHECKING
7

8
from vllm import envs
9
from vllm.plugins import load_plugins_by_group
10
from vllm.utils import resolve_obj_by_qualname, supports_xccl
11
12

from .interface import CpuArchEnum, Platform, PlatformEnum
13

14
logger = logging.getLogger(__name__)
15

16

17
18
19
20
21
def vllm_version_matches_substr(substr: str) -> bool:
    """
    Check to see if the vLLM version matches a substring.
    """
    from importlib.metadata import PackageNotFoundError, version
22

23
24
25
26
27
    try:
        vllm_version = version("vllm")
    except PackageNotFoundError as e:
        logger.warning(
            "The vLLM package was not found, so its version could not be "
28
29
            "inspected. This may cause platform detection to fail."
        )
30
31
32
33
        raise e
    return substr in vllm_version


34
def tpu_platform_plugin() -> str | None:
35
    logger.debug("Checking if TPU platform is available.")
36
37
38
39

    # Check for Pathways TPU proxy
    if envs.VLLM_TPU_USING_PATHWAYS:
        logger.debug("Confirmed TPU platform is available via Pathways proxy.")
40
        return "tpu_inference.platforms.tpu_jax.TpuPlatform"
41
42

    # Check for libtpu installation
43
44
45
    try:
        # While it's technically possible to install libtpu on a
        # non-TPU machine, this is a very uncommon scenario. Therefore,
46
        # we assume that libtpu is installed only if the machine
47
        # has TPUs.
48

49
        import libtpu  # noqa: F401
50

51
        logger.debug("Confirmed TPU platform is available.")
52
        return "vllm.platforms.tpu.TpuPlatform"
53
54
    except Exception as e:
        logger.debug("TPU platform is not available because: %s", str(e))
55
        return None
56
57


58
def cuda_platform_plugin() -> str | None:
59
    is_cuda = False
60
    logger.debug("Checking if CUDA platform is available.")
61
    try:
62
        from vllm.utils import import_pynvml
63

64
        pynvml = import_pynvml()
65
66
        pynvml.nvmlInit()
        try:
67
68
69
70
71
            # NOTE: Edge case: vllm cpu build on a GPU machine.
            # Third-party pynvml can be imported in cpu build,
            # we need to check if vllm is built with cpu too.
            # Otherwise, vllm will always activate cuda plugin
            # on a GPU machine, even if in a cpu build.
72
73
74
75
            is_cuda = (
                pynvml.nvmlDeviceGetCount() > 0
                and not vllm_version_matches_substr("cpu")
            )
76
            if pynvml.nvmlDeviceGetCount() <= 0:
77
                logger.debug("CUDA platform is not available because no GPU is found.")
78
            if vllm_version_matches_substr("cpu"):
79
80
81
                logger.debug(
                    "CUDA platform is not available because vLLM is built with CPU."
                )
82
83
            if is_cuda:
                logger.debug("Confirmed CUDA platform is available.")
84
85
        finally:
            pynvml.nvmlShutdown()
86
    except Exception as e:
87
        logger.debug("Exception happens when checking CUDA platform: %s", str(e))
88
89
90
91
        if "nvml" not in e.__class__.__name__.lower():
            # If the error is not related to NVML, re-raise it.
            raise e

92
93
94
95
        # CUDA is supported on Jetson, but NVML may not be.
        import os

        def cuda_is_jetson() -> bool:
96
97
98
            return os.path.isfile("/etc/nv_tegra_release") or os.path.exists(
                "/sys/class/tegra-firmware"
            )
99
100

        if cuda_is_jetson():
101
            logger.debug("Confirmed CUDA platform is available on Jetson.")
102
            is_cuda = True
103
104
        else:
            logger.debug("CUDA platform is not available because: %s", str(e))
105

106
107
108
    return "vllm.platforms.cuda.CudaPlatform" if is_cuda else None


109
def rocm_platform_plugin() -> str | None:
110
    is_rocm = False
111
    logger.debug("Checking if ROCm platform is available.")
112
113
    try:
        import amdsmi
114

115
116
117
118
        amdsmi.amdsmi_init()
        try:
            if len(amdsmi.amdsmi_get_processor_handles()) > 0:
                is_rocm = True
119
                logger.debug("Confirmed ROCm platform is available.")
120
            else:
121
                logger.debug("ROCm platform is not available because no GPU is found.")
122
123
        finally:
            amdsmi.amdsmi_shut_down()
124
125
    except Exception as e:
        logger.debug("ROCm platform is not available because: %s", str(e))
126
127
128
129

    return "vllm.platforms.rocm.RocmPlatform" if is_rocm else None


130
def xpu_platform_plugin() -> str | None:
131
    is_xpu = False
132
    logger.debug("Checking if XPU platform is available.")
133
134
135
136
    try:
        # installed IPEX if the machine has XPUs.
        import intel_extension_for_pytorch  # noqa: F401
        import torch
137

138
139
140
141
142
143
        if supports_xccl():
            dist_backend = "xccl"
        else:
            dist_backend = "ccl"
            import oneccl_bindings_for_pytorch  # noqa: F401

144
        if hasattr(torch, "xpu") and torch.xpu.is_available():
145
            is_xpu = True
146
            from vllm.platforms.xpu import XPUPlatform
147

148
            XPUPlatform.dist_backend = dist_backend
149
            logger.debug("Confirmed %s backend is available.", XPUPlatform.dist_backend)
150
151
152
            logger.debug("Confirmed XPU platform is available.")
    except Exception as e:
        logger.debug("XPU platform is not available because: %s", str(e))
153
154
155
156

    return "vllm.platforms.xpu.XPUPlatform" if is_xpu else None


157
def cpu_platform_plugin() -> str | None:
158
    is_cpu = False
159
    logger.debug("Checking if CPU platform is available.")
160
    try:
161
        is_cpu = vllm_version_matches_substr("cpu")
162
        if is_cpu:
163
164
165
            logger.debug(
                "Confirmed CPU platform is available because vLLM is built with CPU."
            )
166
        if not is_cpu:
167
            import sys
168

169
            is_cpu = sys.platform.startswith("darwin")
170
            if is_cpu:
171
172
173
                logger.debug(
                    "Confirmed CPU platform is available because the machine is MacOS."
                )
174

175
176
    except Exception as e:
        logger.debug("CPU platform is not available because: %s", str(e))
177
178
179
180
181

    return "vllm.platforms.cpu.CpuPlatform" if is_cpu else None


builtin_platform_plugins = {
182
183
184
185
186
    "tpu": tpu_platform_plugin,
    "cuda": cuda_platform_plugin,
    "rocm": rocm_platform_plugin,
    "xpu": xpu_platform_plugin,
    "cpu": cpu_platform_plugin,
187
188
189
190
}


def resolve_current_platform_cls_qualname() -> str:
191
    platform_plugins = load_plugins_by_group("vllm.platform_plugins")
192
193
194

    activated_plugins = []

195
    for name, func in chain(builtin_platform_plugins.items(), platform_plugins.items()):
196
197
198
199
200
201
        try:
            assert callable(func)
            platform_cls_qualname = func()
            if platform_cls_qualname is not None:
                activated_plugins.append(name)
        except Exception:
202
            pass
203
204

    activated_builtin_plugins = list(
205
206
207
        set(activated_plugins) & set(builtin_platform_plugins.keys())
    )
    activated_oot_plugins = list(set(activated_plugins) & set(platform_plugins.keys()))
208
209
210
211

    if len(activated_oot_plugins) >= 2:
        raise RuntimeError(
            "Only one platform plugin can be activated, but got: "
212
213
            f"{activated_oot_plugins}"
        )
214
215
    elif len(activated_oot_plugins) == 1:
        platform_cls_qualname = platform_plugins[activated_oot_plugins[0]]()
216
        logger.info("Platform plugin %s is activated", activated_oot_plugins[0])
217
218
219
    elif len(activated_builtin_plugins) >= 2:
        raise RuntimeError(
            "Only one platform plugin can be activated, but got: "
220
221
            f"{activated_builtin_plugins}"
        )
222
    elif len(activated_builtin_plugins) == 1:
223
224
        platform_cls_qualname = builtin_platform_plugins[activated_builtin_plugins[0]]()
        logger.info("Automatically detected platform %s.", activated_builtin_plugins[0])
225
    else:
226
        platform_cls_qualname = "vllm.platforms.interface.UnspecifiedPlatform"
227
        logger.info("No platform detected, vLLM is running on UnspecifiedPlatform")
228
229
230
231
    return platform_cls_qualname


_current_platform = None
232
_init_trace: str = ""
233
234
235
236
237
238

if TYPE_CHECKING:
    current_platform: Platform


def __getattr__(name: str):
239
    if name == "current_platform":
240
241
242
243
244
245
246
247
248
249
250
251
252
253
        # lazy init current_platform.
        # 1. out-of-tree platform plugins need `from vllm.platforms import
        #    Platform` so that they can inherit `Platform` class. Therefore,
        #    we cannot resolve `current_platform` during the import of
        #    `vllm.platforms`.
        # 2. when users use out-of-tree platform plugins, they might run
        #    `import vllm`, some vllm internal code might access
        #    `current_platform` during the import, and we need to make sure
        #    `current_platform` is only resolved after the plugins are loaded
        #    (we have tests for this, if any developer violate this, they will
        #    see the test failures).
        global _current_platform
        if _current_platform is None:
            platform_cls_qualname = resolve_current_platform_cls_qualname()
254
            _current_platform = resolve_obj_by_qualname(platform_cls_qualname)()
255
256
257
            global _init_trace
            _init_trace = "".join(traceback.format_stack())
        return _current_platform
258
    elif name in globals():
259
        return globals()[name]
260
    else:
261
        raise AttributeError(f"No attribute named '{name}' exists in {__name__}.")
262
263


264
265
266
267
268
269
270
271
272
273
def __setattr__(name: str, value):
    if name == "current_platform":
        global _current_platform
        _current_platform = value
    elif name in globals():
        globals()[name] = value
    else:
        raise AttributeError(f"No attribute named '{name}' exists in {__name__}.")


274
__all__ = ["Platform", "PlatformEnum", "current_platform", "CpuArchEnum", "_init_trace"]