"vscode:/vscode.git/clone" did not exist on "c9ff9e6f0cf48615bad1525caeef3025c62b2720"
__init__.py 10.7 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
import logging
import traceback
from itertools import chain
from typing import TYPE_CHECKING, Optional

from vllm.plugins import load_plugins_by_group
10
from vllm.utils import resolve_obj_by_qualname, supports_xccl
11

12
from .interface import _Backend  # noqa: F401
13
from .interface import CpuArchEnum, Platform, PlatformEnum
14

15
logger = logging.getLogger(__name__)
16

17

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def vllm_version_matches_substr(substr: str) -> bool:
    """
    Check to see if the vLLM version matches a substring.
    """
    from importlib.metadata import PackageNotFoundError, version
    try:
        vllm_version = version("vllm")
    except PackageNotFoundError as e:
        logger.warning(
            "The vLLM package was not found, so its version could not be "
            "inspected. This may cause platform detection to fail.")
        raise e
    return substr in vllm_version


33
34
def tpu_platform_plugin() -> Optional[str]:
    is_tpu = False
35
    logger.debug("Checking if TPU platform is available.")
36
37
38
39
40
41
42
    try:
        # While it's technically possible to install libtpu on a
        # non-TPU machine, this is a very uncommon scenario. Therefore,
        # we assume that libtpu is installed if and only if the machine
        # has TPUs.
        import libtpu  # noqa: F401
        is_tpu = True
43
44
45
        logger.debug("Confirmed TPU platform is available.")
    except Exception as e:
        logger.debug("TPU platform is not available because: %s", str(e))
46
47

    return "vllm.platforms.tpu.TpuPlatform" if is_tpu else None
48
49


50
51
def cuda_platform_plugin() -> Optional[str]:
    is_cuda = False
52
    logger.debug("Checking if CUDA platform is available.")
53
    try:
54
55
        from vllm.utils import import_pynvml
        pynvml = import_pynvml()
56
57
        pynvml.nvmlInit()
        try:
58
59
60
61
62
63
            # 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.
            is_cuda = (pynvml.nvmlDeviceGetCount() > 0
64
                       and not vllm_version_matches_substr("cpu"))
65
66
67
68
69
70
71
72
            if pynvml.nvmlDeviceGetCount() <= 0:
                logger.debug(
                    "CUDA platform is not available because no GPU is found.")
            if vllm_version_matches_substr("cpu"):
                logger.debug("CUDA platform is not available because"
                             " vLLM is built with CPU.")
            if is_cuda:
                logger.debug("Confirmed CUDA platform is available.")
73
74
        finally:
            pynvml.nvmlShutdown()
75
    except Exception as e:
76
77
        logger.debug("Exception happens when checking CUDA platform: %s",
                     str(e))
78
79
80
81
        if "nvml" not in e.__class__.__name__.lower():
            # If the error is not related to NVML, re-raise it.
            raise e

82
83
84
85
86
87
88
89
        # CUDA is supported on Jetson, but NVML may not be.
        import os

        def cuda_is_jetson() -> bool:
            return os.path.isfile("/etc/nv_tegra_release") \
                or os.path.exists("/sys/class/tegra-firmware")

        if cuda_is_jetson():
90
            logger.debug("Confirmed CUDA platform is available on Jetson.")
91
            is_cuda = True
92
93
        else:
            logger.debug("CUDA platform is not available because: %s", str(e))
94

95
96
97
98
99
    return "vllm.platforms.cuda.CudaPlatform" if is_cuda else None


def rocm_platform_plugin() -> Optional[str]:
    is_rocm = False
100
    logger.debug("Checking if ROCm platform is available.")
101
102
103
104
105
106
    try:
        import amdsmi
        amdsmi.amdsmi_init()
        try:
            if len(amdsmi.amdsmi_get_processor_handles()) > 0:
                is_rocm = True
107
                logger.debug("Confirmed ROCm platform is available.")
108
109
110
            else:
                logger.debug("ROCm platform is not available because"
                             " no GPU is found.")
111
112
        finally:
            amdsmi.amdsmi_shut_down()
113
114
    except Exception as e:
        logger.debug("ROCm platform is not available because: %s", str(e))
115
116
117
118
119
120

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


def hpu_platform_plugin() -> Optional[str]:
    is_hpu = False
121
    logger.debug("Checking if HPU platform is available.")
122
123
124
    try:
        from importlib import util
        is_hpu = util.find_spec('habana_frameworks') is not None
125
126
127
128
129
130
131
        if is_hpu:
            logger.debug("Confirmed HPU platform is available.")
        else:
            logger.debug("HPU platform is not available because "
                         "habana_frameworks is not found.")
    except Exception as e:
        logger.debug("HPU platform is not available because: %s", str(e))
132
133
134
135
136
137

    return "vllm.platforms.hpu.HpuPlatform" if is_hpu else None


def xpu_platform_plugin() -> Optional[str]:
    is_xpu = False
138
    logger.debug("Checking if XPU platform is available.")
139
140
141
142
    try:
        # installed IPEX if the machine has XPUs.
        import intel_extension_for_pytorch  # noqa: F401
        import torch
143
144
145
146
147
148
        if supports_xccl():
            dist_backend = "xccl"
        else:
            dist_backend = "ccl"
            import oneccl_bindings_for_pytorch  # noqa: F401

149
150
        if hasattr(torch, 'xpu') and torch.xpu.is_available():
            is_xpu = True
151
152
153
154
            from vllm.platforms.xpu import XPUPlatform
            XPUPlatform.dist_backend = dist_backend
            logger.debug("Confirmed %s backend is available.",
                         XPUPlatform.dist_backend)
155
156
157
            logger.debug("Confirmed XPU platform is available.")
    except Exception as e:
        logger.debug("XPU platform is not available because: %s", str(e))
158
159
160
161
162
163

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


def cpu_platform_plugin() -> Optional[str]:
    is_cpu = False
164
    logger.debug("Checking if CPU platform is available.")
165
    try:
166
        is_cpu = vllm_version_matches_substr("cpu")
167
168
169
        if is_cpu:
            logger.debug("Confirmed CPU platform is available because"
                         " vLLM is built with CPU.")
170
        if not is_cpu:
171
172
            import sys
            is_cpu = sys.platform.startswith("darwin")
173
174
            if is_cpu:
                logger.debug("Confirmed CPU platform is available"
175
                             " because the machine is MacOS.")
176

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

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


def neuron_platform_plugin() -> Optional[str]:
184
185
    tnx_installed = False
    nxd_installed = False
186
    logger.debug("Checking if Neuron platform is available.")
187
188
    try:
        import transformers_neuronx  # noqa: F401
189
        tnx_installed = True
190
191
        logger.debug("Confirmed Neuron platform is available because"
                     " transformers_neuronx is found.")
192
    except ImportError:
193
        pass
194

195
196
197
198
199
200
201
202
203
    try:
        import neuronx_distributed_inference  # noqa: F401
        nxd_installed = True
        logger.debug("Confirmed Neuron platform is available because"
                     " neuronx_distributed_inference is found.")
    except ImportError:
        pass

    is_neuron = tnx_installed or nxd_installed
204
    return "vllm.platforms.neuron.NeuronPlatform" if is_neuron else None
205
206


207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
builtin_platform_plugins = {
    'tpu': tpu_platform_plugin,
    'cuda': cuda_platform_plugin,
    'rocm': rocm_platform_plugin,
    'hpu': hpu_platform_plugin,
    'xpu': xpu_platform_plugin,
    'cpu': cpu_platform_plugin,
    'neuron': neuron_platform_plugin,
}


def resolve_current_platform_cls_qualname() -> str:
    platform_plugins = load_plugins_by_group('vllm.platform_plugins')

    activated_plugins = []

    for name, func in chain(builtin_platform_plugins.items(),
                            platform_plugins.items()):
        try:
            assert callable(func)
            platform_cls_qualname = func()
            if platform_cls_qualname is not None:
                activated_plugins.append(name)
        except Exception:
231
            pass
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255

    activated_builtin_plugins = list(
        set(activated_plugins) & set(builtin_platform_plugins.keys()))
    activated_oot_plugins = list(
        set(activated_plugins) & set(platform_plugins.keys()))

    if len(activated_oot_plugins) >= 2:
        raise RuntimeError(
            "Only one platform plugin can be activated, but got: "
            f"{activated_oot_plugins}")
    elif len(activated_oot_plugins) == 1:
        platform_cls_qualname = platform_plugins[activated_oot_plugins[0]]()
        logger.info("Platform plugin %s is activated",
                    activated_oot_plugins[0])
    elif len(activated_builtin_plugins) >= 2:
        raise RuntimeError(
            "Only one platform plugin can be activated, but got: "
            f"{activated_builtin_plugins}")
    elif len(activated_builtin_plugins) == 1:
        platform_cls_qualname = builtin_platform_plugins[
            activated_builtin_plugins[0]]()
        logger.info("Automatically detected platform %s.",
                    activated_builtin_plugins[0])
    else:
256
        platform_cls_qualname = "vllm.platforms.interface.UnspecifiedPlatform"
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
        logger.info(
            "No platform detected, vLLM is running on UnspecifiedPlatform")
    return platform_cls_qualname


_current_platform = None
_init_trace: str = ''

if TYPE_CHECKING:
    current_platform: Platform


def __getattr__(name: str):
    if name == 'current_platform':
        # 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()
            _current_platform = resolve_obj_by_qualname(
                platform_cls_qualname)()
            global _init_trace
            _init_trace = "".join(traceback.format_stack())
        return _current_platform
290
    elif name in globals():
291
        return globals()[name]
292
293
294
    else:
        raise AttributeError(
            f"No attribute named '{name}' exists in {__name__}.")
295
296
297
298
299
300


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