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

4
from unittest.mock import patch
5
6
7
8

import pytest
import torch

9
from vllm.attention.selector import _cached_get_attn_backend, get_attn_backend
10
11
12
from vllm.platforms.cpu import CpuPlatform
from vllm.platforms.cuda import CudaPlatform
from vllm.platforms.rocm import RocmPlatform
13
from vllm.utils import STR_BACKEND_ENV_VAR, STR_FLASH_ATTN_VAL, STR_INVALID_VAL
14
15


16
17
@pytest.fixture(autouse=True)
def clear_cache():
18
    """Clear lru cache to ensure each test case runs without caching."""
19
20
21
    _cached_get_attn_backend.cache_clear()


22
23
# Define MLA and non-MLA backends separately
DEVICE_MLA_BACKENDS = {
24
    "cuda": [
25
26
27
28
29
        "TRITON_MLA",
        "FLASHMLA",
        "FLASHINFER_MLA",
        "FLASH_ATTN_MLA",
        "CUTLASS_MLA",
30
    ],
31
32
33
34
35
    "hip": ["TRITON_MLA", "ROCM_AITER_MLA"],
    "cpu": [],
}

DEVICE_REGULAR_ATTN_BACKENDS = {
36
    "cuda": ["XFORMERS", "FLASHINFER", "FLASH_ATTN"],
37
    "hip": ["ROCM_ATTN"],
38
39
40
41
42
43
    "cpu": ["TORCH_SDPA"],
}

DEVICE_MLA_BLOCK_SIZES = {
    "cuda": [16, 64],  # CUDA supports both standard and extended block sizes
    "hip": [16, 1],  # HIP requires special handling for block_size=1
44
    # "cpu": [16]  # CPU uses fixed block size from test cases
45
    "cpu": [],  # FIXME(woosuk): Temporarily disable CPU tests
46
47
48
49
50
51
52
}


def generate_params():
    params = []
    for use_mla in [True, False]:
        for device in ["cuda", "hip", "cpu"]:
53
54
55
56
57
            backends = (
                DEVICE_MLA_BACKENDS[device]
                if use_mla
                else DEVICE_REGULAR_ATTN_BACKENDS[device]
            )
58
            for name in backends:
59
                block_sizes = DEVICE_MLA_BLOCK_SIZES[device] if use_mla else [16]
60
61
62
63
64
65
66
                for block_size in block_sizes:
                    params.append(
                        pytest.param(
                            device,
                            name,
                            use_mla,
                            block_size,
67
68
69
                            id=f"{device}_{name}_mla_{str(use_mla)[0]}_blks{block_size}",
                        )
                    )
70
71
72
    return params


73
@pytest.mark.parametrize("device, name, use_mla, block_size", generate_params())
74
def test_env(
75
    device: str,
76
    name: str,
77
78
    use_mla: bool,
    block_size: int,
79
80
    monkeypatch: pytest.MonkeyPatch,
):
81
    """Test attention backend selection with valid device-backend pairs."""
82
83
    with monkeypatch.context() as m:
        m.setenv(STR_BACKEND_ENV_VAR, name)
84
        m.setenv("VLLM_MLA_DISABLE", "1" if use_mla else "0")
85
86

        if device == "cpu":
87
            with patch("vllm.platforms.current_platform", CpuPlatform()):
88
                backend = get_attn_backend(16, torch.float16, None, block_size)
89
            assert backend.get_name() == "TORCH_SDPA"
90

91
        elif device == "hip":
92
            with patch("vllm.platforms.current_platform", RocmPlatform()):
93
                if use_mla:
94
95
96
97
98
99
100
101
                    # ROCm MLA backend logic:
                    # - TRITON_MLA: supported when block_size != 1
                    # - ROCM_AITER_MLA: supported when block_size == 1
                    # If backend is forced but doesn't match block_size,
                    # should raise ValueError

                    if name == "TRITON_MLA" and block_size == 1:
                        # TRITON_MLA doesn't support block_size == 1
102
                        with pytest.raises(ValueError) as exc_info:
103
104
105
106
                            get_attn_backend(
                                16, torch.float16, None, block_size, use_mla=use_mla
                            )
                        assert f"The selected backend, {name}" in str(exc_info.value)
107
108
                    else:
                        # Valid backend-block_size combination
109
110
111
                        backend = get_attn_backend(
                            16, torch.float16, None, block_size, use_mla=use_mla
                        )
112
                        expected = name
113
                        assert backend.get_name() == expected
114
                else:
115
116
117
                    backend = get_attn_backend(
                        16, torch.float16, None, block_size, use_mla=use_mla
                    )
118
                    expected = "ROCM_ATTN"
119
120
121
                    assert backend.get_name() == expected

        elif device == "cuda":
122
            with patch("vllm.platforms.current_platform", CudaPlatform()):
123
                if use_mla:
124
125
126
                    # CUDA MLA backend logic:
                    # - CUTLASS_MLA: only supported with block_size == 128
                    #   and Blackwell GPUs (SM 10.0), V1 only
127
128
                    # - FLASHINFER_MLA: only supported on Blackwell GPUs
                    #   (SM 10.0+), V1 only
129
130
131
132
133
                    # - FLASHMLA: only supported with block_size == 64
                    # - FLASH_ATTN_MLA: V1 only
                    # - TRITON_MLA: fallback for other cases

                    if name == "CUTLASS_MLA":
134
                        if block_size != 128:
135
                            # CUTLASS_MLA only supports block_size == 128
136
                            pytest.skip("CUTLASS_MLA only supports block_size 128")
137
                        else:
138
139
140
                            backend = get_attn_backend(
                                16, torch.float16, None, block_size, use_mla=use_mla
                            )
141
                            expected = "CUTLASS_MLA"
142
                            assert backend.get_name() == expected
143
                    elif name == "FLASHINFER_MLA":
144
                        if block_size not in [32, 64]:
145
146
                            # FlashInfer MLA only supports block_size 32 or 64
                            pytest.skip(
147
148
                                "FlashInfer MLA only supports block_size 32 or 64"
                            )
149
                        else:
150
151
152
                            backend = get_attn_backend(
                                16, torch.float16, None, block_size, use_mla=use_mla
                            )
153
154
                            expected = "FLASHINFER_MLA"
                            assert backend.get_name() == expected
155
156
157
158
159
                    elif name == "FLASHMLA":
                        if block_size != 64:
                            # FlashMLA only supports block_size == 64
                            pytest.skip("FlashMLA only supports block_size 64")
                        else:
160
                            from vllm.v1.attention.backends.mla.flashmla import (
161
                                is_flashmla_dense_supported,
162
163
                            )

164
                            is_supported, _ = is_flashmla_dense_supported()
165
                            if not is_supported:
166
                                pytest.skip("FlashMLA not supported on this platform")
167
                            else:
168
169
170
                                backend = get_attn_backend(
                                    16, torch.float16, None, block_size, use_mla=use_mla
                                )
171
                                expected = name
172
173
                                assert backend.get_name() == expected
                    elif name == "FLASH_ATTN_MLA":
174
175
176
                        backend = get_attn_backend(
                            16, torch.float16, None, block_size, use_mla=use_mla
                        )
177
178
                        expected = "FLASH_ATTN_MLA"
                        assert backend.get_name() == expected
179
                    else:
180
                        # TRITON_MLA or other fallback
181
182
183
                        backend = get_attn_backend(
                            16, torch.float16, None, block_size, use_mla=use_mla
                        )
184
                        expected = "TRITON_MLA"
185
                        assert backend.get_name() == expected
186
                elif name == "FLASHINFER":
187
188
189
                    backend = get_attn_backend(
                        16, torch.float16, None, block_size, use_mla=use_mla
                    )
190
                    expected = "FLASHINFER"
191
                    assert backend.get_name() == expected
192
                elif name == "XFORMERS":
193
194
195
                    backend = get_attn_backend(
                        32, torch.float16, None, block_size, use_mla=use_mla
                    )
196
                    expected = "XFORMERS"
197
                    assert backend.get_name() == expected
198
                elif name == "FLASH_ATTN":
199
200
201
                    backend = get_attn_backend(
                        32, torch.float16, None, block_size, use_mla=use_mla
                    )
202
203
                    expected = "FLASH_ATTN"
                    assert backend.get_name() == expected
204

205

206
@pytest.mark.parametrize("device", ["cpu", "cuda"])
207
def test_fp32_fallback(device: str):
208
    """Test attention backend selection with fp32."""
209
    if device == "cpu":
210
        with patch("vllm.platforms.current_platform", CpuPlatform()):
211
212
            backend = get_attn_backend(16, torch.float32, None, 16)
        assert backend.get_name() == "TORCH_SDPA"
213

214
    elif device == "cuda":
215
        with patch("vllm.platforms.current_platform", CudaPlatform()):
216
217
            backend = get_attn_backend(16, torch.float32, None, 16)
        assert backend.get_name() == "FLEX_ATTENTION"
218
219


220
def test_flash_attn(monkeypatch: pytest.MonkeyPatch):
221
    """Test FlashAttn validation."""
222
223
224
225
    pytest.skip(
        "Skipping as current backend selector does not "
        "handle fallbacks when a backend is set via env var."
    )
226

227
228
    with monkeypatch.context() as m:
        m.setenv(STR_BACKEND_ENV_VAR, STR_FLASH_ATTN_VAL)
229

230
        # Unsupported CUDA arch
231
        monkeypatch.setattr(torch.cuda, "get_device_capability", lambda _=None: (7, 5))
232
        backend = get_attn_backend(16, torch.float16, None, 16)
233
        assert backend.get_name() != STR_FLASH_ATTN_VAL
234

235
236
        # Reset the monkeypatch for subsequent tests
        monkeypatch.undo()
237

238
        # Unsupported data type
239
        backend = get_attn_backend(16, torch.float8_e4m3fn, None, 16)
240
        assert backend.get_name() != STR_FLASH_ATTN_VAL
241

242
        # Unsupported kv cache data type
243
        backend = get_attn_backend(16, torch.float16, "fp8", 16)
244
        assert backend.get_name() != STR_FLASH_ATTN_VAL
245

246
        # Unsupported block size
247
        backend = get_attn_backend(16, torch.float16, None, 8)
248
249
250
251
        assert backend.get_name() != STR_FLASH_ATTN_VAL

        # flash-attn is not installed
        import sys
252
253
254

        original_module = sys.modules.get("vllm_flash_attn")
        monkeypatch.setitem(sys.modules, "vllm_flash_attn", None)
255
        backend = get_attn_backend(16, torch.float16, None, 16)
256
        assert backend.get_name() != STR_FLASH_ATTN_VAL
257

258
259
        # Restore the original module if it existed
        if original_module is not None:
260
            monkeypatch.setitem(sys.modules, "vllm_flash_attn", original_module)
261
        else:
262
            monkeypatch.delitem(sys.modules, "vllm_flash_attn", raising=False)
263

264
        # Unsupported head size
265
        backend = get_attn_backend(17, torch.float16, None, 16)
266
        assert backend.get_name() != STR_FLASH_ATTN_VAL
267
268


269
def test_invalid_env(monkeypatch: pytest.MonkeyPatch):
270
    """Test that invalid attention backend names raise ValueError."""
271
272
    with (
        monkeypatch.context() as m,
273
        patch("vllm.platforms.current_platform", CudaPlatform()),
274
    ):
275
        m.setenv(STR_BACKEND_ENV_VAR, STR_INVALID_VAL)
276

277
278
        # Should raise ValueError for invalid backend
        with pytest.raises(ValueError) as exc_info:
279
            get_attn_backend(32, torch.float16, None, 16)
280
        assert "Invalid value 'INVALID'" in str(exc_info.value)