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

4
import contextlib
5
import os
6
from typing import TYPE_CHECKING
7

8
9
import torch

10
import vllm.envs as envs
11
from vllm.logger import init_logger
12
from vllm.utils import DEFAULT_MAX_NUM_BATCHED_TOKENS
13

14
from .interface import DeviceCapability, Platform, PlatformEnum
15

16
if TYPE_CHECKING:
17
    from vllm.attention.backends.registry import _Backend
18
    from vllm.config import ModelConfig, VllmConfig
19
else:
20
    ModelConfig = None
21
    VllmConfig = None
22
    _Backend = None
23

24
logger = init_logger(__name__)
25
26
27
28


class XPUPlatform(Platform):
    _enum = PlatformEnum.XPU
29
    device_name: str = "xpu"
30
    device_type: str = "xpu"
31
    dispatch_key: str = "XPU"
32
33
34
    # Intel XPU's device key is "GPU" for Ray.
    # see https://github.com/ray-project/ray/blob/6a5eb5865eeb9ccf058a79b44f107e327e360673/python/ray/_private/accelerators/intel_gpu.py#L20 # noqa: E501
    ray_device_key: str = "GPU"
35
    dist_backend: str = "ccl"  # ccl | xccl
36
    device_control_env_var: str = "ZE_AFFINITY_MASK"
37

38
    @classmethod
39
40
41
42
    def import_kernels(cls) -> None:
        # Do not import vllm._C
        with contextlib.suppress(ImportError):
            import vllm._moe_C  # noqa: F401
43

44
    @classmethod
45
46
47
48
49
    def get_attn_backend_cls(
        cls,
        selected_backend: "_Backend",
        head_size: int,
        dtype: torch.dtype,
50
        kv_cache_dtype: str | None,
51
52
53
54
55
56
        block_size: int,
        use_v1: bool,
        use_mla: bool,
        has_sink: bool,
        use_sparse,
    ) -> str:
57
58
59
60
61
62
63
64
        from vllm.v1.attention.backends.utils import set_kv_cache_layout

        set_kv_cache_layout("NHD")
        logger.info(
            "Setting VLLM_KV_CACHE_LAYOUT to 'NHD' for XPU; "
            "only NHD layout is supported by XPU attention kernels."
        )

65
        from vllm.attention.backends.registry import _Backend
66

67
        if use_sparse:
68
            raise NotImplementedError("Sparse Attention is not supported on XPU.")
69
70
71
        TRITON_ATTN = "vllm.v1.attention.backends.triton_attn.TritonAttentionBackend"  # noqa: E501
        FLASH_ATTN = "vllm.v1.attention.backends.flash_attn.FlashAttentionBackend"  # noqa: E501
        if selected_backend == _Backend.TRITON_ATTN:
72
            logger.info_once("Using Triton backend.")
73
            return TRITON_ATTN
74
        elif selected_backend == _Backend.FLASH_ATTN:
75
            logger.info_once("Using Flash Attention backend.")
76
            return FLASH_ATTN
77
78
79
        elif selected_backend:
            raise ValueError(
                f"Invalid attention backend for {cls.device_name}, "
80
81
                f"with use_v1: {use_v1} use_mla: {use_mla}"
            )
82

83
        logger.info("Using Flash Attention backend.")
84
        return "vllm.v1.attention.backends.flash_attn.FlashAttentionBackend"
85

86
87
88
89
90
91
92
    @classmethod
    def set_device(cls, device: torch.device) -> None:
        """
        Set the device for the current platform.
        """
        torch.xpu.set_device(device)

93
    @classmethod
94
    def get_device_capability(
95
96
        cls,
        device_id: int = 0,
97
    ) -> DeviceCapability | None:
98
99
100
        # capacity format differs from cuda's and will cause unexpected
        # failure, so use None directly
        return None
101

102
103
    @classmethod
    def get_device_name(cls, device_id: int = 0) -> str:
104
        return torch.xpu.get_device_name(device_id)
105

106
107
    @classmethod
    def get_punica_wrapper(cls) -> str:
108
        return "vllm.lora.punica_wrapper.punica_xpu.PunicaWrapperXPU"
109

110
111
112
113
    @classmethod
    def get_device_total_memory(cls, device_id: int = 0) -> int:
        device_props = torch.xpu.get_device_properties(device_id)
        return device_props.total_memory
114

115
116
117
118
119
120
    @classmethod
    def get_vit_attn_backend(cls, head_size: int, dtype: torch.dtype) -> _Backend:
        from vllm.attention.backends.registry import _Backend

        return _Backend.FLASH_ATTN

121
122
    @classmethod
    def inference_mode(cls):
123
        return torch.no_grad()
124
125
126

    @classmethod
    def check_and_update_config(cls, vllm_config: VllmConfig) -> None:
127
        cache_config = vllm_config.cache_config
128
        model_config = vllm_config.model_config
129
        # in V1(or with ipex chunked prefill) block_size is 64
130
        if cache_config and cache_config.block_size is None:
131
            cache_config.block_size = 64
132

133
        # lazy import to avoid circular import
134
        from vllm.config import CompilationMode, CUDAGraphMode
135

136
        compilation_config = vllm_config.compilation_config
137
138
        if compilation_config.compile_sizes is None:
            compilation_config.compile_sizes = []
139

140
        assert compilation_config.cudagraph_mode == CUDAGraphMode.NONE, (
141
            "CUDA graph mode should be NONE on XPU"
142
        )
143

144
        if vllm_config.lora_config is not None:
145
            compilation_config.mode = CompilationMode.NONE
146

147
148
        # check and update parallel config
        parallel_config = vllm_config.parallel_config
149
        parallel_config.worker_cls = "vllm.v1.worker.xpu_worker.XPUWorker"
150
151
        if vllm_config.kv_transfer_config is not None:
            vllm_config.kv_transfer_config.enable_permute_local_kv = True
152
153

        if parallel_config.distributed_executor_backend is None:
154
155
156
157
            if parallel_config.world_size > 1:
                parallel_config.distributed_executor_backend = "ray"
            else:
                parallel_config.distributed_executor_backend = "uni"
158
159
        elif parallel_config.distributed_executor_backend == "mp":
            # FIXME(kunshang):
160
            # spawn needs calling `if __name__ == '__main__':`
161
            # fork is not supported for xpu start new process.
162
163
164
            if envs.VLLM_WORKER_MULTIPROC_METHOD != "spawn":
                os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
                logger.warning(
165
166
167
168
169
170
171
                    "Please use spawn as start method if you want to use mp."
                )
        elif (
            parallel_config.distributed_executor_backend != "ray"
            and parallel_config.distributed_executor_backend != "uni"
            and parallel_config.distributed_executor_backend != "external_launcher"
        ):
172
173
174
            logger.warning(
                "%s is not supported on XPU, fallback to ray distributed"
                " executor backend.",
175
176
                parallel_config.distributed_executor_backend,
            )
177
            parallel_config.distributed_executor_backend = "ray"
178

179
        if model_config and model_config.use_mla:
180
181
            logger.info(
                "MLA is enabled on a non-GPU platform; forcing chunked "
182
183
                "prefill and prefix caching to be disabled."
            )
184
185
186
187
            vllm_config.scheduler_config.enable_chunked_prefill = False
            vllm_config.scheduler_config.chunked_prefill_enabled = False
            vllm_config.scheduler_config.max_num_batched_tokens = max(
                vllm_config.scheduler_config.max_model_len,
188
189
                DEFAULT_MAX_NUM_BATCHED_TOKENS,
            )
190

191
192
193
194
    @classmethod
    def support_hybrid_kv_cache(cls) -> bool:
        return True

195
196
197
198
    @classmethod
    def support_static_graph_mode(cls) -> bool:
        return False

199
200
    @classmethod
    def is_pin_memory_available(cls):
201
        return True
202
203

    @classmethod
204
    def get_current_memory_usage(
205
        cls, device: torch.types.Device | None = None
206
    ) -> float:
207
208
        torch.xpu.reset_peak_memory_stats(device)
        return torch.xpu.max_memory_allocated(device)
209

210
211
212
213
    @classmethod
    def fp8_dtype(cls) -> torch.dtype:
        return torch.float8_e5m2

214
215
216
217
218
    @classmethod
    def is_data_center_gpu(cls) -> bool:
        device_name = cls.get_device_name().lower()
        return device_name.count("data center gpu") > 0

219
220
221
    @classmethod
    def get_device_communicator_cls(cls) -> str:
        return "vllm.distributed.device_communicators.xpu_communicator.XpuCommunicator"  # noqa
222
223
224

    @classmethod
    def device_count(cls) -> int:
225
        return torch.xpu.device_count()
226
227

    @classmethod
228
229
    def check_if_supports_dtype(cls, dtype: torch.dtype):
        if dtype == torch.bfloat16:  # noqa: SIM102
230
231
232
233
234
235
            device_name = cls.get_device_name().lower()
            # client gpu a770
            if device_name.count("a770") > 0:
                raise ValueError(
                    "Intel Arc A770 have bfloat16 accuracy known issue. "
                    "You can use float16 instead by explicitly setting the "
236
237
                    "`dtype` flag in CLI, for example: --dtype=half."
                )
238
239
240
241

    @classmethod
    def opaque_attention_op(cls) -> bool:
        return True
242
243
244
245
246
247
248
249
250
251
252

    @classmethod
    def insert_blocks_to_device(
        cls,
        src_cache: torch.Tensor,
        dst_cache: torch.Tensor,
        src_block_indices: torch.Tensor,
        dst_block_indices: torch.Tensor,
    ) -> None:
        """Copy blocks from src_cache to dst_cache on XPU."""
        _src_cache = src_cache[:, src_block_indices]
253
254
255
256
        if _src_cache.shape[2:] != dst_cache.shape[2:]:
            # To support TP_ratio, HOST KV might be initiated with HND
            # while XPU device KV is with NHD
            _src_cache = _src_cache.permute(0, 1, 3, 2, 4)
257
258
259
260
261
262
263
264
265
266
267
268
        dst_cache[:, dst_block_indices] = _src_cache.to(dst_cache.device)

    @classmethod
    def swap_out_blocks_to_host(
        cls,
        src_cache: torch.Tensor,
        dst_cache: torch.Tensor,
        src_block_indices: torch.Tensor,
        dst_block_indices: torch.Tensor,
    ) -> None:
        """Copy blocks from XPU to host (CPU)."""
        _src_cache = src_cache[:, src_block_indices]
269
270
271
272
        if _src_cache.shape[2:] != dst_cache.shape[2:]:
            # XPU device KV is with NHD while HOST KV
            # might be initiated with HND for TP_ratio support
            _src_cache = _src_cache.permute(0, 1, 3, 2, 4)
273
        dst_cache[:, dst_block_indices] = _src_cache.cpu()