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

4
5
import random

6
import pytest
7
8
import torch

9
from tests.kernels.allclose_default import get_default_atol, get_default_rtol
10
from tests.kernels.utils import opcheck
11
from vllm import _custom_ops as ops
12
13
from vllm.attention.layer import Attention
from vllm.attention.layers.mm_encoder_attention import MMEncoderAttention
14
from vllm.platforms import current_platform
15
from vllm.utils.mem_utils import get_max_shared_memory_bytes
16
from vllm.utils.torch_utils import set_random_seed
17

18
19
20
21
FLOAT32_BYTES = torch.finfo(torch.float).bits // 8
# This will change depending on the compute capability.
# - 512 as a buffer
MAX_SEQ_LEN = get_max_shared_memory_bytes() // FLOAT32_BYTES - 512
22
23
24
# There may not be enough gpu memory due to large NUM_BLOCKS.
# Reduce NUM_BLOCKS when it happens.
NUM_BLOCKS = 4321  # Arbitrary values for testing
25
PARTITION_SIZE = 512
26
PARTITION_SIZE_ROCM = 256
27
DTYPES = [torch.bfloat16]
28
NUM_GEN_SEQS = [7]  # Arbitrary values for testing
29
NUM_PREFILL_SEQS = [3]  # Arbitrary values for testing
30
NUM_HEADS = [(40, 40), (64, 8)]  # Arbitrary values for testing
31

32
33
# This should be sync with get_supported_head_sizes() in
# vllm.attention.ops.paged_attn.PagedAttention
34
HEAD_SIZES = [32, 80, 128, 256]
35

36
BLOCK_SIZES = [16, 32]
37
USE_ALIBI = [False, True]
38
KV_CACHE_DTYPE = ["auto", "fp8"]
39
SEEDS = [0]
40
CUDA_DEVICES = [f"cuda:{i}" for i in range(1 if torch.cuda.device_count() == 1 else 2)]
41

42
43
44
45
46
47

def ref_masked_attention(
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    scale: float,
48
    attn_mask: torch.Tensor | None = None,
49
) -> torch.Tensor:
50
    attn_weights = scale * torch.einsum("qhd,khd->hqk", query, key).float()
51
    if attn_mask is not None:
52
53
54
        attn_weights = attn_weights + attn_mask.float()
    attn_weights = torch.softmax(attn_weights, dim=-1).to(value.dtype)
    out = torch.einsum("hqk,khd->qhd", attn_weights, value)
55
56
57
58
59
60
    return out


def ref_single_query_cached_kv_attention(
    output: torch.Tensor,
    query: torch.Tensor,
61
    num_queries_per_kv: int,
62
63
64
    key_cache: torch.Tensor,
    value_cache: torch.Tensor,
    block_tables: torch.Tensor,
65
    seq_lens: torch.Tensor,
66
    scale: float,
67
    alibi_slopes: torch.Tensor | None,
68
) -> None:
69
70
    num_query_heads = query.shape[1]
    num_kv_heads = value_cache.shape[1]
71
72
    head_size = value_cache.shape[2]
    block_size = value_cache.shape[3]
73
    num_seqs = query.shape[0]
74

75
76
    block_tables_lst = block_tables.cpu().tolist()
    seq_lens_lst = seq_lens.cpu().tolist()
77
    for i in range(num_seqs):
78
        q = query[i].unsqueeze(0)
79
80
        block_table = block_tables_lst[i]
        seq_len = int(seq_lens_lst[i])
81

82
83
        keys_lst: list[torch.Tensor] = []
        values_lst: list[torch.Tensor] = []
84
        for j in range(seq_len):
85
86
87
88
            block_number = int(block_table[j // block_size])
            block_offset = j % block_size

            k = key_cache[block_number, :, :, block_offset, :]
89
            k = k.reshape(num_kv_heads, head_size)
90
            keys_lst.append(k)
91
92

            v = value_cache[block_number, :, :, block_offset]
93
94
95
            values_lst.append(v)
        keys = torch.stack(keys_lst, dim=0)
        values = torch.stack(values_lst, dim=0)
96
97
98
99
100
101
102
103
        if num_queries_per_kv > 1:
            # Handle MQA and GQA
            keys = torch.repeat_interleave(keys, num_queries_per_kv, dim=1)
            values = torch.repeat_interleave(values, num_queries_per_kv, dim=1)

        alibi_bias = None
        if alibi_slopes is not None:
            # Create the ALiBi bias used in the paged attention kernel.
104
105
            position_ids = torch.arange(seq_len).int()
            alibi_bias = (position_ids - seq_len + 1).float()
106
            alibi_bias = alibi_slopes.view(-1, 1, 1) * alibi_bias.view(1, 1, -1)
107
108
109

        out = ref_masked_attention(q, keys, values, scale, alibi_bias)
        out = out.view(num_query_heads, head_size)
110
111
112
        output[i].copy_(out, non_blocking=True)


113
@pytest.mark.parametrize(
114
115
    "version", ["v1", "v2"] if not current_platform.is_rocm() else ["v1", "v2", "rocm"]
)
116
117
118
119
120
121
@pytest.mark.parametrize("num_seqs", NUM_GEN_SEQS)
@pytest.mark.parametrize("num_heads", NUM_HEADS)
@pytest.mark.parametrize("head_size", HEAD_SIZES)
@pytest.mark.parametrize("use_alibi", USE_ALIBI)
@pytest.mark.parametrize("block_size", BLOCK_SIZES)
@pytest.mark.parametrize("dtype", DTYPES)
122
@pytest.mark.parametrize("kv_cache_dtype", KV_CACHE_DTYPE)
123
@pytest.mark.parametrize("seed", SEEDS)
124
@pytest.mark.parametrize("device", CUDA_DEVICES)
125
def test_paged_attention(
126
    kv_cache_factory,
127
    version: str,
128
    num_seqs: int,
129
    num_heads: tuple[int, int],
130
    head_size: int,
131
    use_alibi: bool,
132
133
    block_size: int,
    dtype: torch.dtype,
134
    kv_cache_dtype: str,
135
    seed: int,
136
    device: str,
137
) -> None:
138
139
140
    if (kv_cache_dtype == "fp8" and head_size % 16) or (
        version == "rocm" and head_size not in (64, 128)
    ):
Joe's avatar
Joe committed
141
        pytest.skip()
142

143
144
145
146
147
148
149
    if (
        version == "rocm"
        and current_platform.is_navi()
        and (
            kv_cache_dtype == "fp8" or head_size != 128 or block_size != 16 or use_alibi
        )
    ):
150
151
        pytest.skip()

152
153
    global PARTITION_SIZE

154
    set_random_seed(seed)
155
    torch.set_default_device(device)
156
157
    scale = float(1.0 / (head_size**0.5))
    num_query_heads, num_kv_heads = num_heads
158
    query = torch.empty(num_seqs, num_query_heads, head_size, dtype=dtype)
159
160
161
162
163
164
    query.uniform_(-scale, scale)

    assert num_query_heads % num_kv_heads == 0
    num_queries_per_kv = num_query_heads // num_kv_heads
    alibi_slopes = None
    if use_alibi:
165
        alibi_slopes = torch.randn(num_query_heads, dtype=torch.float)
166

167
168
169
170
    seq_lens = [random.randint(1, MAX_SEQ_LEN) for _ in range(num_seqs)]
    seq_lens[-1] = MAX_SEQ_LEN
    max_seq_len = max(seq_lens)
    seq_lens = torch.tensor(seq_lens, dtype=torch.int)
171

172
    # Create the block tables.
173
    max_num_blocks_per_seq = (max_seq_len + block_size - 1) // block_size
174
    block_tables_lst: list[list[int]] = []
175
    for _ in range(num_seqs):
176
        block_table = [
177
            random.randint(0, NUM_BLOCKS - 1) for _ in range(max_num_blocks_per_seq)
178
        ]
179
180
181
        block_tables_lst.append(block_table)

    block_tables = torch.tensor(block_tables_lst, dtype=torch.int)
182

183
    # Create the KV caches.
184
185
186
187
188
189
190
191
192
193
194
    key_caches, value_caches = kv_cache_factory(
        NUM_BLOCKS,
        block_size,
        1,
        num_kv_heads,
        head_size,
        kv_cache_dtype,
        dtype,
        seed,
        device,
    )
195
    key_cache, value_cache = key_caches[0], value_caches[0]
Tao Peng's avatar
Tao Peng committed
196

197
    # Using default kv_scale
198
    k_scale = v_scale = torch.tensor(1.0, dtype=torch.float32, device=device)
199

200
201
    # Call the paged attention kernel.
    output = torch.empty_like(query)
202
    if version == "v1":
203
        ops.paged_attention_v1(
204
205
206
207
            output,
            query,
            key_cache,
            value_cache,
208
            num_kv_heads,
209
210
            scale,
            block_tables,
211
            seq_lens,
212
            block_size,
213
            max_seq_len,
214
            alibi_slopes,
215
            kv_cache_dtype,
216
217
            k_scale,
            v_scale,
218
        )
219

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
        opcheck(
            torch.ops._C.paged_attention_v1,
            (
                output,
                query,
                key_cache,
                value_cache,
                num_kv_heads,
                scale,
                block_tables,
                seq_lens,
                block_size,
                max_seq_len,
                alibi_slopes,
                kv_cache_dtype,
                k_scale,
                v_scale,
                0,
                0,
                0,
                64,
                0,
            ),
            cond=(head_size == HEAD_SIZES[0] and block_size == BLOCK_SIZES[0]),
        )
245

246
    elif version in ("v2", "rocm"):
247
248
249
        if current_platform.is_rocm() and version == "rocm":
            PARTITION_SIZE = PARTITION_SIZE_ROCM

250
        num_partitions = (max_seq_len + PARTITION_SIZE - 1) // PARTITION_SIZE
251
252
253
254
255
256
257
258
259
260
261
        assert PARTITION_SIZE % block_size == 0
        num_seqs, num_heads, head_size = output.shape
        tmp_output = torch.empty(
            size=(num_seqs, num_heads, num_partitions, head_size),
            dtype=output.dtype,
        )
        exp_sums = torch.empty(
            size=(num_seqs, num_heads, num_partitions),
            dtype=torch.float32,
        )
        max_logits = torch.empty_like(exp_sums)
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
        if version == "v2":
            ops.paged_attention_v2(
                output,
                exp_sums,
                max_logits,
                tmp_output,
                query,
                key_cache,
                value_cache,
                num_kv_heads,
                scale,
                block_tables,
                seq_lens,
                block_size,
                max_seq_len,
                alibi_slopes,
                kv_cache_dtype,
                k_scale,
                v_scale,
            )

283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
            opcheck(
                torch.ops._C.paged_attention_v2,
                (
                    output,
                    exp_sums,
                    max_logits,
                    tmp_output,
                    query,
                    key_cache,
                    value_cache,
                    num_kv_heads,
                    scale,
                    block_tables,
                    seq_lens,
                    block_size,
                    max_seq_len,
                    alibi_slopes,
                    kv_cache_dtype,
                    k_scale,
                    v_scale,
                    0,
                    0,
                    0,
                    64,
                    0,
                ),
                cond=(head_size == HEAD_SIZES[0] and block_size == BLOCK_SIZES[0]),
            )
311
312
313
314
315
316
317
318
319
320
321
322
323
324

        else:
            ops.paged_attention_rocm(
                output,
                exp_sums,
                max_logits,
                tmp_output,
                query,
                key_cache,
                value_cache,
                num_kv_heads,
                scale,
                block_tables,
                seq_lens,
325
                None,
326
327
328
329
330
331
332
333
                block_size,
                max_seq_len,
                alibi_slopes,
                kv_cache_dtype,
                k_scale,
                v_scale,
            )

334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
            opcheck(
                torch.ops._rocm_C.paged_attention,
                (
                    output,
                    exp_sums,
                    max_logits,
                    tmp_output,
                    query,
                    key_cache,
                    value_cache,
                    num_kv_heads,
                    scale,
                    block_tables,
                    seq_lens,
                    None,
                    block_size,
                    max_seq_len,
                    alibi_slopes,
                    kv_cache_dtype,
                    k_scale,
                    v_scale,
                ),
                cond=(head_size == HEAD_SIZES[0] and block_size == BLOCK_SIZES[0]),
            )
358

359
    else:
360
        raise AssertionError(f"Unknown version: {version}")
361

362
    # Run the reference implementation.
363
    if kv_cache_dtype == "fp8":
364
365
        # Convert cache data back to dtype.
        x = 16 // torch.tensor([], dtype=dtype).element_size()
366
367
368
369
        key_cache_shape = (NUM_BLOCKS, num_kv_heads, head_size // x, block_size, x)
        dequantized_key_cache = torch.empty(
            size=key_cache_shape, dtype=dtype, device=device
        )
370
        ops.convert_fp8(dequantized_key_cache, key_cache)
371
372
373
        key_cache = dequantized_key_cache

        value_cache_shape = value_cache.shape
374
375
376
        dequantized_value_cache = torch.empty(
            size=value_cache_shape, dtype=dtype, device=device
        )
377
        ops.convert_fp8(dequantized_value_cache, value_cache)
378
379
        value_cache = dequantized_value_cache

380
381
382
383
    ref_output = torch.empty_like(query)
    ref_single_query_cached_kv_attention(
        ref_output,
        query,
384
        num_queries_per_kv,
385
386
387
        key_cache,
        value_cache,
        block_tables,
388
        seq_lens,
389
390
        scale,
        alibi_slopes,
391
    )
392
393
394
395

    # NOTE(woosuk): Due to the kernel-level differences in the two
    # implementations, there is a small numerical difference in the two
    # outputs. Thus, we use a relaxed tolerance for the test.
396
397
    atol = get_default_atol(output) if current_platform.is_rocm() else 1e-3
    rtol = get_default_rtol(output) if current_platform.is_rocm() else 1e-5
398

399
400
    # NOTE(zhaoyang): FP8 KV Cache will introduce quantization error,
    # so we use a relaxed tolerance for the test.
401
402
    atol, rtol = 1e-3, 1e-5
    if kv_cache_dtype == "fp8":
403
        atol, rtol = 1e-2, 1e-5
404
    torch.testing.assert_close(output, ref_output, atol=atol, rtol=rtol)
405
406


407
def ref_multi_query_kv_attention(
408
    cu_seq_lens: list[int],
409
410
411
412
    query: torch.Tensor,
    key: torch.Tensor,
    value: torch.Tensor,
    scale: float,
413
    alibi_bias: list[torch.Tensor] | None,
414
415
416
    dtype: torch.dtype,
) -> torch.Tensor:
    num_seqs = len(cu_seq_lens) - 1
417
    ref_outputs: list[torch.Tensor] = []
418
419
    if alibi_bias:
        assert len(alibi_bias) == num_seqs
420
421
422
423
424
    for i in range(num_seqs):
        start_idx = cu_seq_lens[i]
        end_idx = cu_seq_lens[i + 1]
        seq_len = end_idx - start_idx

425
426
427
428
        # Create attention mask. ALiBi already includes a tril causal mask.
        if alibi_bias:
            attn_mask = alibi_bias[i]
        else:
429
430
431
            attn_mask = torch.triu(
                torch.ones(seq_len, seq_len, dtype=dtype), diagonal=1
            )
432
433
            attn_mask = attn_mask * torch.finfo(dtype).min
            attn_mask = attn_mask.to(dtype=dtype)
434
435
436
437
438
439
440
441
442

        ref_output = ref_masked_attention(
            query[start_idx:end_idx],
            key[start_idx:end_idx],
            value[start_idx:end_idx],
            scale,
            attn_mask=attn_mask,
        )
        ref_outputs.append(ref_output)
443
444

    return torch.cat(ref_outputs, dim=0)
445
446


447
@pytest.mark.parametrize("attention_cls", [Attention, MMEncoderAttention])
448
449
450
451
452
453
454
455
456
457
458
459
def test_num_heads_not_divisble_by_num_kv_heads(attention_cls: type) -> None:
    head_size = 64
    scale = float(1.0 / (head_size**0.5))
    num_heads = 16
    num_kv_heads = 5
    with pytest.raises(AssertionError):
        _ = attention_cls(
            num_heads=num_heads,
            head_size=head_size,
            scale=scale,
            num_kv_heads=num_kv_heads,
        )