xpu.py 9.82 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
11
12
13
14
# import custom ops, trigger op registration
import vllm_xpu_kernels._C  # noqa
import vllm_xpu_kernels._moe_C  # noqa
import vllm_xpu_kernels._xpu_C  # noqa

15
from vllm.logger import init_logger
16
from vllm.v1.attention.backends.registry import AttentionBackendEnum
17

18
from .interface import DeviceCapability, Platform, PlatformEnum
19

20
if TYPE_CHECKING:
21
    from vllm.config import VllmConfig
22
    from vllm.v1.attention.selector import AttentionSelectorConfig
23
24
25
else:
    VllmConfig = None

26
logger = init_logger(__name__)
27
28
29
30


class XPUPlatform(Platform):
    _enum = PlatformEnum.XPU
31
    device_name: str = "xpu"
32
    device_type: str = "xpu"
33
    dispatch_key: str = "XPU"
34
35
36
    # 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"
37
    dist_backend: str = "xccl"  # xccl only
38
    device_control_env_var: str = "ZE_AFFINITY_MASK"
39

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

46
    @classmethod
47
48
    def get_attn_backend_cls(
        cls,
49
        selected_backend: "AttentionBackendEnum",
50
        attn_selector_config: "AttentionSelectorConfig",
51
        num_heads: int | None = None,
52
    ) -> str:
53
54
55
56
57
58
59
60
        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."
        )

61
        dtype = attn_selector_config.dtype
62
        if attn_selector_config.use_sparse:
63
            raise NotImplementedError("Sparse Attention is not supported on XPU.")
64
65
66
        if attn_selector_config.use_mla:
            logger.info_once("Using Triton MLA backend on V1 engine.")
            return AttentionBackendEnum.TRITON_MLA.get_path()
67
        if selected_backend == AttentionBackendEnum.TRITON_ATTN:
68
            logger.info_once("Using Triton backend.")
69
            return AttentionBackendEnum.TRITON_ATTN.get_path()
70
71
72
73
74
75
        elif dtype == torch.float32:
            logger.warning_once(
                "Flash Attention on XPU does not support float32 dtype. "
                "Falling back to Triton Attention backend."
            )
            return AttentionBackendEnum.TRITON_ATTN.get_path()
76
        elif selected_backend == AttentionBackendEnum.FLASH_ATTN:
77
            logger.info_once("Using Flash Attention backend.")
78
            return AttentionBackendEnum.FLASH_ATTN.get_path()
79
80
81
        elif selected_backend:
            raise ValueError(
                f"Invalid attention backend for {cls.device_name}, "
82
                f"with use_mla: {attn_selector_config.use_mla}"
83
            )
84

85
        logger.info("Using Flash Attention backend.")
86
        return AttentionBackendEnum.FLASH_ATTN.get_path()
87

88
89
90
91
    @classmethod
    def get_supported_vit_attn_backends(cls) -> list["AttentionBackendEnum"]:
        return [
            AttentionBackendEnum.FLASH_ATTN,
92
            AttentionBackendEnum.TORCH_SDPA,
93
94
95
96
97
98
99
        ]

    @classmethod
    def get_vit_attn_backend(
        cls,
        head_size: int,
        dtype: torch.dtype,
100
        backend: "AttentionBackendEnum | None" = None,
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    ) -> "AttentionBackendEnum":
        if backend is not None:
            assert backend in cls.get_supported_vit_attn_backends(), (
                f"Backend {backend} is not supported for vit attention. "
                f"Supported backends are: "
                f"{cls.get_supported_vit_attn_backends()}."
            )
            logger.info_once(f"Using backend {backend} for vit attention")
            return backend

        logger.info_once(
            f"Using backend {AttentionBackendEnum.FLASH_ATTN} for vit attention"
        )
        return AttentionBackendEnum.FLASH_ATTN

116
117
118
119
120
121
122
    @classmethod
    def set_device(cls, device: torch.device) -> None:
        """
        Set the device for the current platform.
        """
        torch.xpu.set_device(device)

123
    @classmethod
124
    def get_device_capability(
125
126
        cls,
        device_id: int = 0,
127
    ) -> DeviceCapability | None:
128
129
130
        # capacity format differs from cuda's and will cause unexpected
        # failure, so use None directly
        return None
131

132
133
    @classmethod
    def get_device_name(cls, device_id: int = 0) -> str:
134
        return torch.xpu.get_device_name(device_id)
135

136
137
    @classmethod
    def get_punica_wrapper(cls) -> str:
138
139
140
141
142
        xpu_use_triton_kernel = os.getenv("XPU_USE_TRITON_KERNEL", "0") == "1"
        if not xpu_use_triton_kernel:
            return "vllm.lora.punica_wrapper.punica_xpu.PunicaWrapperXPU"
        else:
            return "vllm.lora.punica_wrapper.punica_gpu.PunicaWrapperGPU"
143

144
145
146
147
    @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
148

149
150
    @classmethod
    def inference_mode(cls):
151
        return torch.no_grad()
152
153
154

    @classmethod
    def check_and_update_config(cls, vllm_config: VllmConfig) -> None:
155
        cache_config = vllm_config.cache_config
156
        model_config = vllm_config.model_config
157
        # in V1(or with chunked prefill) block_size is 64
158
        if cache_config and cache_config.block_size is None:
159
            cache_config.block_size = 64
160

161
        # lazy import to avoid circular import
162
        from vllm.config import CompilationMode, CUDAGraphMode
163

164
        compilation_config = vllm_config.compilation_config
165
166
        if compilation_config.compile_sizes is None:
            compilation_config.compile_sizes = []
167

168
        assert compilation_config.cudagraph_mode == CUDAGraphMode.NONE, (
169
            "CUDA graph mode should be NONE on XPU"
170
        )
171

172
        if vllm_config.lora_config is not None:
173
            compilation_config.mode = CompilationMode.NONE
174
175
176
        # decrease triton kernel compilation scratch space for speculative decoding
        if vllm_config.speculative_config is not None:
            os.environ["IGC_ForceOCLSIMDWidth"] = "16"  # noqa: SIM112
177
178
        # check and update parallel config
        parallel_config = vllm_config.parallel_config
179
180
181
182
        # Only override worker_cls if it's still the default "auto"
        # This allows custom workers (like vllm-omni workers) to be used on XPU
        if parallel_config.worker_cls == "auto":
            parallel_config.worker_cls = "vllm.v1.worker.xpu_worker.XPUWorker"
183
184
        if vllm_config.kv_transfer_config is not None:
            vllm_config.kv_transfer_config.enable_permute_local_kv = True
185

186
        if model_config and model_config.use_mla:
187
188
            logger.info(
                "MLA is enabled on a non-GPU platform; forcing chunked "
189
190
                "prefill and prefix caching to be disabled."
            )
191
192
            vllm_config.scheduler_config.enable_chunked_prefill = False
            vllm_config.scheduler_config.max_num_batched_tokens = max(
193
                vllm_config.model_config.max_model_len,
194
                vllm_config.scheduler_config.DEFAULT_MAX_NUM_BATCHED_TOKENS,
195
            )
196

197
198
199
200
    @classmethod
    def support_hybrid_kv_cache(cls) -> bool:
        return True

201
202
203
204
    @classmethod
    def support_static_graph_mode(cls) -> bool:
        return False

205
206
    @classmethod
    def is_pin_memory_available(cls):
207
        return True
208
209

    @classmethod
210
    def get_current_memory_usage(
211
        cls, device: torch.types.Device | None = None
212
    ) -> float:
213
214
        torch.xpu.reset_peak_memory_stats(device)
        return torch.xpu.max_memory_allocated(device)
215

216
217
    @classmethod
    def fp8_dtype(cls) -> torch.dtype:
218
        return torch.float8_e4m3fn
219

220
221
222
223
224
    @classmethod
    def is_data_center_gpu(cls) -> bool:
        device_name = cls.get_device_name().lower()
        return device_name.count("data center gpu") > 0

225
226
    @classmethod
    def get_device_communicator_cls(cls) -> str:
227
228
229
230
231
232
233
        from vllm.utils.torch_utils import supports_xccl

        if not supports_xccl():
            logger.warning(
                "xccl is not enabled in this torch build, communication"
                " is not available."
            )
234
        return "vllm.distributed.device_communicators.xpu_communicator.XpuCommunicator"  # noqa
235
236
237

    @classmethod
    def device_count(cls) -> int:
238
        return torch.xpu.device_count()
239
240

    @classmethod
241
242
    def check_if_supports_dtype(cls, dtype: torch.dtype):
        if dtype == torch.bfloat16:  # noqa: SIM102
243
244
245
246
247
248
            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 "
249
250
                    "`dtype` flag in CLI, for example: --dtype=half."
                )
251
252
253
254

    @classmethod
    def opaque_attention_op(cls) -> bool:
        return True
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278

    @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]
        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]
        dst_cache[:, dst_block_indices] = _src_cache.cpu()