| 1 | # Adapted from: https://github.com/deepseek-ai/FlashMLA/blob/main/tests/test_flash_mla.py |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 4 | import math |
| 5 | import random |
| 6 | |
| 7 | import pytest |
| 8 | import torch |
| 9 | |
| 10 | from vllm.triton_utils import triton |
| 11 | from vllm.v1.attention.ops.flashmla import ( |
| 12 | flash_mla_with_kvcache, |
| 13 | flash_mla_with_kvcache_fp8, |
| 14 | get_mla_metadata, |
| 15 | get_mla_metadata_dense_fp8, |
| 16 | is_flashmla_dense_supported, |
| 17 | ) |
| 18 | |
| 19 | pytestmark = pytest.mark.skip_global_cleanup |
| 20 | |
| 21 | |
| 22 | def cal_diff( |
| 23 | x: torch.Tensor, y: torch.Tensor, name: str, use_fp8: bool = False |
| 24 | ) -> None: |
| 25 | x, y = x.double(), y.double() |
| 26 | cos_diff = 1 - 2 * (x * y).sum().item() / max((x * x + y * y).sum().item(), 1e-12) |
| 27 | if use_fp8: |
| 28 | assert cos_diff < 1e-4 |
| 29 | else: |
| 30 | assert cos_diff < 1e-5 |
| 31 | |
| 32 | |
| 33 | FLASH_MLA_UNSUPPORTED_REASON = ( |
| 34 | is_flashmla_dense_supported()[1] |
| 35 | if not is_flashmla_dense_supported()[0] |
| 36 | else "FlashMLA is supported" |
| 37 | ) |
| 38 | |
| 39 | |
| 40 | @pytest.mark.skipif( |
| 41 | not is_flashmla_dense_supported()[0], reason=FLASH_MLA_UNSUPPORTED_REASON |
| 42 | ) |
| 43 | @pytest.mark.parametrize("b", [128]) |
| 44 | @pytest.mark.parametrize("s_q", [1, 2]) |
| 45 | @pytest.mark.parametrize("mean_sk", [4096, 8192, 16384]) |
| 46 | @pytest.mark.parametrize("h_q", [16, 32, 64, 128]) |
| 47 | @pytest.mark.parametrize("h_kv", [1]) |
| 48 | @pytest.mark.parametrize("d", [576]) |
| 49 | @pytest.mark.parametrize("dv", [512]) |
| 50 | @pytest.mark.parametrize("block_size", [64]) |
| 51 | @pytest.mark.parametrize("causal", [True]) |
| 52 | @pytest.mark.parametrize("varlen", [False, True]) |
| 53 | @pytest.mark.parametrize( |
| 54 | "torch_dtype", [torch.bfloat16, torch.float16, torch.float8_e4m3fn] |
| 55 | ) |
| 56 | @torch.inference_mode() |
| 57 | def test_flash_mla( |
| 58 | b, s_q, mean_sk, h_q, h_kv, d, dv, block_size, causal, varlen, torch_dtype |
| 59 | ): |
| 60 | device = torch.device("cuda:0") |
| 61 | init_dtype = torch.bfloat16 if torch_dtype == torch.float8_e4m3fn else torch_dtype |
| 62 | torch.set_default_dtype(init_dtype) |
| 63 | torch.set_default_device(device) |
| 64 | torch.accelerator.set_device_index(device) |
| 65 | torch.manual_seed(0) |
| 66 | random.seed(0) |
| 67 | |
| 68 | print( |
| 69 | f"{b=}, {s_q=}, {mean_sk=}, {h_q=}, {h_kv=}, " |
| 70 | f"{d=}, {dv=}, {causal=}, {varlen=}, {torch_dtype=}" |
| 71 | ) |
| 72 | |
| 73 | use_fp8 = torch_dtype == torch.float8_e4m3fn |
| 74 | cache_seqlens = torch.full((b,), mean_sk, dtype=torch.int32) |
| 75 | if varlen: |
| 76 | for i in range(b): |
| 77 | cache_seqlens[i] = max(random.normalvariate(mean_sk, mean_sk / 2), s_q) |
| 78 | total_seqlens = cache_seqlens.sum().item() |
| 79 | max_seqlen = cache_seqlens.max().item() |
| 80 | max_seqlen_pad = triton.cdiv(max_seqlen, 256) * 256 |
| 81 | |
| 82 | q = torch.randn(b, s_q, h_q, d) |
| 83 | block_table = torch.arange( |
| 84 | b * max_seqlen_pad // block_size, dtype=torch.int32 |
| 85 | ).view(b, max_seqlen_pad // block_size) |
| 86 | blocked_k = torch.randn(block_table.numel(), block_size, h_kv, d) |
| 87 | for i in range(b): |
| 88 | blocked_k.view(b, max_seqlen_pad, h_kv, d)[i, cache_seqlens[i].item() :] = ( |
| 89 | float("nan") |
| 90 | ) |
| 91 | blocked_v = blocked_k[..., :dv] |
| 92 | |
| 93 | if use_fp8: |
| 94 | tile_scheduler_metadata, num_splits = get_mla_metadata_dense_fp8( |
| 95 | cache_seqlens, s_q * h_q // h_kv, h_kv |
| 96 | ) |
| 97 | else: |
| 98 | tile_scheduler_metadata, num_splits = get_mla_metadata( |
| 99 | cache_seqlens, s_q * h_q // h_kv, h_kv |
| 100 | ) |
| 101 | |
| 102 | init_dtype = q.dtype |
| 103 | if use_fp8: |
| 104 | fp8_dtype = torch.float8_e4m3fn |
| 105 | descale_q = torch.ones((1), dtype=torch.float32) |
| 106 | descale_k = torch.ones((1), dtype=torch.float32) |
| 107 | |
| 108 | q = q.to(fp8_dtype) |
| 109 | blocked_k = blocked_k.to(fp8_dtype) |
| 110 | blocked_v = blocked_v.to(fp8_dtype) |
| 111 | else: |
| 112 | descale_q = None |
| 113 | descale_k = None |
| 114 | |
| 115 | def flash_mla(): |
| 116 | if use_fp8: |
| 117 | return flash_mla_with_kvcache_fp8( |
| 118 | q, |
| 119 | blocked_k, |
| 120 | block_table, |
| 121 | cache_seqlens, |
| 122 | dv, |
| 123 | tile_scheduler_metadata, |
| 124 | num_splits, |
| 125 | causal=causal, |
| 126 | descale_q=descale_q, |
| 127 | descale_k=descale_k, |
| 128 | ) |
| 129 | return flash_mla_with_kvcache( |
| 130 | q, |
| 131 | blocked_k, |
| 132 | block_table, |
| 133 | cache_seqlens, |
| 134 | dv, |
| 135 | tile_scheduler_metadata, |
| 136 | num_splits, |
| 137 | causal=causal, |
| 138 | ) |
| 139 | |
| 140 | def scaled_dot_product_attention(query, key, value, is_causal=False): |
| 141 | query = query.float() |
| 142 | key = key.float() |
| 143 | value = value.float() |
| 144 | key = key.repeat_interleave(h_q // h_kv, dim=0) |
| 145 | value = value.repeat_interleave(h_q // h_kv, dim=0) |
| 146 | attn_weight = query @ key.transpose(-2, -1) / math.sqrt(query.size(-1)) |
| 147 | if is_causal: |
| 148 | s_q = query.shape[-2] |
| 149 | s_k = key.shape[-2] |
| 150 | attn_bias = torch.zeros(s_q, s_k, dtype=query.dtype) |
| 151 | temp_mask = torch.ones(s_q, s_k, dtype=torch.bool).tril(diagonal=s_k - s_q) |
| 152 | attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf")) |
| 153 | attn_bias.to(query.dtype) |
| 154 | attn_weight += attn_bias |
| 155 | lse = attn_weight.logsumexp(dim=-1) |
| 156 | attn_weight = torch.softmax(attn_weight, dim=-1, dtype=torch.float32) |
| 157 | return attn_weight @ value, lse |
| 158 | |
| 159 | def ref_mla(): |
| 160 | q_ = (q.to(torch.float) * descale_q).to(init_dtype) if use_fp8 else q |
| 161 | blocked_k_ = ( |
| 162 | (blocked_k.to(torch.float) * descale_k).to(init_dtype) |
| 163 | if use_fp8 |
| 164 | else blocked_k |
| 165 | ) |
| 166 | blocked_v_ = ( |
| 167 | (blocked_v.to(torch.float) * descale_k).to(init_dtype) |
| 168 | if use_fp8 |
| 169 | else blocked_v |
| 170 | ) |
| 171 | out = torch.empty(b, s_q, h_q, dv, dtype=torch.float32) |
| 172 | lse = torch.empty(b, h_q, s_q, dtype=torch.float32) |
| 173 | for i in range(b): |
| 174 | begin = i * max_seqlen_pad |
| 175 | end = begin + cache_seqlens[i] |
| 176 | out_i, lse_i = scaled_dot_product_attention( |
| 177 | q_[i].transpose(0, 1), |
| 178 | blocked_k_.view(-1, h_kv, d)[begin:end].transpose(0, 1), |
| 179 | blocked_v_.view(-1, h_kv, dv)[begin:end].transpose(0, 1), |
| 180 | is_causal=causal, |
| 181 | ) |
| 182 | out[i] = out_i.transpose(0, 1) |
| 183 | lse[i] = lse_i |
| 184 | return out, lse |
| 185 | |
| 186 | out_flash, lse_flash = flash_mla() |
| 187 | out_torch, lse_torch = ref_mla() |
| 188 | cal_diff(out_flash, out_torch, "out", use_fp8) |
| 189 | cal_diff(lse_flash, lse_torch, "lse") |
| 190 | |
| 191 | t = triton.testing.do_bench(flash_mla) |
| 192 | FLOPS = s_q * total_seqlens * h_q * (d + dv) * 2 |
| 193 | bytes = (total_seqlens * h_kv * d + b * s_q * h_q * d) * ( |
| 194 | torch.finfo(torch_dtype).bits // 8 |
| 195 | ) + (b * s_q * h_q * dv) * (torch.finfo(init_dtype).bits // 8) |
| 196 | print( |
| 197 | f"{t:.3f} ms, {FLOPS / 10**9 / t:.0f} TFLOPS,", f"{bytes / 10**6 / t:.0f} GB/s" |
| 198 | ) |