| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | # Copyright (c) 2025 FlyDSL Project Contributors |
| 4 | """Correctness test for the FlyDSL TurboQuant 4-bit KV decode kernel. |
| 5 | |
| 6 | The kernel is validated against a pure-PyTorch full-precision attention |
| 7 | oracle rather than another kernel: the synthetic KV cache is built from |
| 8 | known centroid indices, K-norms and V-scales/zeros, so we can dequantize |
| 9 | the exact stored values and run fp32 softmax attention as ground truth. |
| 10 | Both sides therefore see identical quantized values; the only difference |
| 11 | is bf16-vs-fp32 accumulation, which is bounded by ``ATOL`` below. |
| 12 | |
| 13 | Skipped unless running on ROCm/gfx950 with FlyDSL importable. |
| 14 | """ |
| 15 | |
| 16 | import pytest |
| 17 | import torch |
| 18 | |
| 19 | from vllm.platforms import current_platform |
| 20 | |
| 21 | # Guard the ROCm-only import: `vllm.platforms.rocm` pulls in amdsmi and other |
| 22 | # ROCm-specific modules that are not importable on non-ROCm platforms, so it |
| 23 | # must not be imported at module load time on CUDA/CPU CI. |
| 24 | if not current_platform.is_rocm(): |
| 25 | pytest.skip( |
| 26 | "TurboQuant FlyDSL decode only runs on ROCm gfx950.", |
| 27 | allow_module_level=True, |
| 28 | ) |
| 29 | |
| 30 | from vllm.platforms.rocm import on_gfx950 # noqa: E402 |
| 31 | |
| 32 | if not on_gfx950(): |
| 33 | pytest.skip( |
| 34 | "TurboQuant FlyDSL decode only runs on ROCm gfx950.", |
| 35 | allow_module_level=True, |
| 36 | ) |
| 37 | |
| 38 | from vllm.v1.attention.ops.flydsl_turboquant_decode import ( # noqa: E402 |
| 39 | flydsl_turboquant_decode_attention, |
| 40 | is_flydsl_available, |
| 41 | is_flydsl_gqa6_available, |
| 42 | ) |
| 43 | |
| 44 | if not is_flydsl_available(): |
| 45 | pytest.skip("FlyDSL runtime is not available.", allow_module_level=True) |
| 46 | |
| 47 | HEAD_SIZE = 128 |
| 48 | N_CENTROIDS = 16 |
| 49 | KEY_DATA_BYTES = HEAD_SIZE // 2 # 4-bit packed key nibbles |
| 50 | DATA_BYTES_PER_SLOT = HEAD_SIZE # packed K (64) + packed V (64) |
| 51 | NUM_SOA_FIELDS = 3 |
| 52 | SOA_K_NORM, SOA_V_SCALE, SOA_V_ZERO = 0, 1, 2 |
| 53 | |
| 54 | # bf16-vs-fp32 accumulation tolerance (FlyDSL test_pa.py default). |
| 55 | ATOL = 5e-3 |
| 56 | |
| 57 | |
| 58 | def _build_cache( |
| 59 | num_seqs, num_kv_heads, seq_len, qg, kv_block_size, seed=0xC0FFEE, device="cuda" |
| 60 | ): |
| 61 | """Vectorized builder for a SoA-layout 4-bit KV cache + fp32 ground truth. |
| 62 | |
| 63 | Returns ``(centroids, q_bf16, kv_cache_4d, block_table, seq_lens, |
| 64 | K_ref, V_ref)`` where ``K_ref``/``V_ref`` are the dequantized |
| 65 | full-precision keys/values used by the reference attention. |
| 66 | """ |
| 67 | g = torch.Generator(device=device).manual_seed(seed) |
| 68 | hk = num_kv_heads |
| 69 | hq = hk * qg |
| 70 | |
| 71 | centroids = ( |
| 72 | torch.randn(N_CENTROIDS, generator=g, dtype=torch.float32, device=device) * 0.5 |
| 73 | ) |
| 74 | q = ( |
| 75 | torch.randn( |
| 76 | num_seqs, hq, HEAD_SIZE, generator=g, dtype=torch.float32, device=device |
| 77 | ) |
| 78 | * 0.1 |
| 79 | ) |
| 80 | q_bf16 = q.to(torch.bfloat16) |
| 81 | |
| 82 | blocks_per_seq = (seq_len + kv_block_size - 1) // kv_block_size |
| 83 | max_bps = blocks_per_seq + 4 |
| 84 | block_table = torch.zeros(num_seqs, max_bps, dtype=torch.int32, device=device) |
| 85 | block_table[:, :blocks_per_seq] = ( |
| 86 | torch.arange( |
| 87 | num_seqs * blocks_per_seq, dtype=torch.int32, device=device |
| 88 | ).reshape(num_seqs, blocks_per_seq) |
| 89 | + 1 |
| 90 | ) |
| 91 | total_blocks = num_seqs * blocks_per_seq + 8 |
| 92 | |
| 93 | slot_size_aligned = (KEY_DATA_BYTES + 2) + (KEY_DATA_BYTES + 4) # 134 |
| 94 | if slot_size_aligned % 2: |
| 95 | slot_size_aligned += 1 |
| 96 | bytes_per_block = kv_block_size * hk * slot_size_aligned |
| 97 | |
| 98 | k_idx = torch.randint( |
| 99 | 0, |
| 100 | N_CENTROIDS, |
| 101 | (num_seqs, hk, seq_len, HEAD_SIZE), |
| 102 | generator=g, |
| 103 | dtype=torch.uint8, |
| 104 | device=device, |
| 105 | ) |
| 106 | v_idx = torch.randint( |
| 107 | 0, |
| 108 | N_CENTROIDS, |
| 109 | (num_seqs, hk, seq_len, HEAD_SIZE), |
| 110 | generator=g, |
| 111 | dtype=torch.uint8, |
| 112 | device=device, |
| 113 | ) |
| 114 | knorm = ( |
| 115 | torch.rand(num_seqs, hk, seq_len, generator=g, device=device) * 0.5 + 0.5 |
| 116 | ).to(torch.float16) |
| 117 | vscale = ( |
| 118 | torch.rand(num_seqs, hk, seq_len, generator=g, device=device) * 0.05 + 0.01 |
| 119 | ).to(torch.float16) |
| 120 | vzero = ( |
| 121 | (torch.rand(num_seqs, hk, seq_len, generator=g, device=device) - 0.5) * 0.1 |
| 122 | ).to(torch.float16) |
| 123 | |
| 124 | k_ref = centroids[k_idx.long()].float() * knorm.float().unsqueeze(-1) |
| 125 | v_ref = v_idx.float() * vscale.float().unsqueeze(-1) + vzero.float().unsqueeze(-1) |
| 126 | |
| 127 | k_packed = k_idx[..., 0::2] | (k_idx[..., 1::2] << 4) |
| 128 | v_packed = v_idx[..., 0::2] | (v_idx[..., 1::2] << 4) |
| 129 | |
| 130 | kv_cache = torch.zeros( |
| 131 | total_blocks, bytes_per_block, dtype=torch.uint8, device=device |
| 132 | ) |
| 133 | |
| 134 | seq_ax = ( |
| 135 | torch.arange(num_seqs, device=device) |
| 136 | .view(num_seqs, 1) |
| 137 | .expand(num_seqs, seq_len) |
| 138 | ) |
| 139 | tok_ax = ( |
| 140 | torch.arange(seq_len, device=device).view(1, seq_len).expand(num_seqs, seq_len) |
| 141 | ) |
| 142 | blk_for_tok = block_table[seq_ax, tok_ax // kv_block_size] |
| 143 | slot_for_tok = tok_ax % kv_block_size |
| 144 | |
| 145 | h_ax = torch.arange(hk, device=device) |
| 146 | base_data = ( |
| 147 | slot_for_tok.unsqueeze(1) * hk * DATA_BYTES_PER_SLOT |
| 148 | + h_ax.view(1, hk, 1) * DATA_BYTES_PER_SLOT |
| 149 | ) |
| 150 | blk_b = blk_for_tok.unsqueeze(1).expand(num_seqs, hk, seq_len) |
| 151 | dst_base = blk_b * bytes_per_block + base_data |
| 152 | rng_k = torch.arange(KEY_DATA_BYTES, device=device) |
| 153 | rng_v = torch.arange(KEY_DATA_BYTES, device=device) + KEY_DATA_BYTES |
| 154 | k_dst = (dst_base.unsqueeze(-1) + rng_k.view(1, 1, 1, -1)).reshape(-1) |
| 155 | v_dst = (dst_base.unsqueeze(-1) + rng_v.view(1, 1, 1, -1)).reshape(-1) |
| 156 | flat = kv_cache.view(-1) |
| 157 | flat[k_dst] = k_packed.reshape(-1) |
| 158 | flat[v_dst] = v_packed.reshape(-1) |
| 159 | |
| 160 | meta_off = kv_block_size * hk * DATA_BYTES_PER_SLOT |
| 161 | meta_view = kv_cache.view(torch.float16).view(total_blocks, -1) |
| 162 | meta_off_hw = meta_off // 2 |
| 163 | common = h_ax.view( |
| 164 | 1, hk, 1 |
| 165 | ) * NUM_SOA_FIELDS * kv_block_size + slot_for_tok.unsqueeze(1) |
| 166 | blk_flat = blk_for_tok.unsqueeze(1).expand(num_seqs, hk, seq_len) |
| 167 | knorm_off = meta_off_hw + common + SOA_K_NORM * kv_block_size |
| 168 | vscale_off = meta_off_hw + common + SOA_V_SCALE * kv_block_size |
| 169 | vzero_off = meta_off_hw + common + SOA_V_ZERO * kv_block_size |
| 170 | meta_view[blk_flat.reshape(-1).long(), knorm_off.reshape(-1).long()] = ( |
| 171 | knorm.reshape(-1) |
| 172 | ) |
| 173 | meta_view[blk_flat.reshape(-1).long(), vscale_off.reshape(-1).long()] = ( |
| 174 | vscale.reshape(-1) |
| 175 | ) |
| 176 | meta_view[blk_flat.reshape(-1).long(), vzero_off.reshape(-1).long()] = ( |
| 177 | vzero.reshape(-1) |
| 178 | ) |
| 179 | |
| 180 | seq_lens = torch.full((num_seqs,), seq_len, dtype=torch.int32, device=device) |
| 181 | kv_cache_4d = kv_cache.view(total_blocks, kv_block_size, hk, slot_size_aligned) |
| 182 | return ( |
| 183 | centroids, |
| 184 | q_bf16, |
| 185 | kv_cache_4d, |
| 186 | block_table, |
| 187 | seq_lens, |
| 188 | k_ref.cpu(), |
| 189 | v_ref.cpu(), |
| 190 | ) |
| 191 | |
| 192 | |
| 193 | def _reference_attention(q_bf16, k_ref, v_ref, seq_lens, scale): |
| 194 | """fp32 softmax attention on dequantized keys/values (ground truth).""" |
| 195 | num_seqs, hq, d = q_bf16.shape |
| 196 | hk = k_ref.shape[1] |
| 197 | qg = hq // hk |
| 198 | q = q_bf16.float().reshape(num_seqs, hk, qg, d) |
| 199 | out = torch.zeros(num_seqs, hq, d, dtype=torch.float32) |
| 200 | for s in range(num_seqs): |
| 201 | for h in range(hk): |
| 202 | ql = int(seq_lens[s].item()) |
| 203 | k = k_ref[s, h, :ql] |
| 204 | v = v_ref[s, h, :ql] |
| 205 | scores = (q[s, h] @ k.T) * scale |
| 206 | m = scores.max(dim=-1, keepdim=True).values |
| 207 | e = torch.exp(scores - m) |
| 208 | p = e / e.sum(dim=-1, keepdim=True) |
| 209 | out[s, h * qg : (h + 1) * qg] = p @ v |
| 210 | return out |
| 211 | |
| 212 | |
| 213 | @pytest.mark.parametrize("num_seqs", [1, 4, 16]) |
| 214 | @pytest.mark.parametrize("seq_len", [256, 1024, 4096]) |
| 215 | @pytest.mark.parametrize( |
| 216 | "num_kv_heads,qg", |
| 217 | [ |
| 218 | (8, 8), # Qwen2.5-72B class |
| 219 | (8, 16), # Qwen3-32B class |
| 220 | pytest.param( |
| 221 | 4, |
| 222 | 6, # MiniMax-M2.5 class (GQA-6 sibling kernel) |
| 223 | marks=pytest.mark.skipif( |
| 224 | not is_flydsl_gqa6_available(), |
| 225 | reason="FlyDSL GQA-6 sibling kernel not available", |
| 226 | ), |
| 227 | ), |
| 228 | ], |
| 229 | ) |
| 230 | @pytest.mark.parametrize("kv_block_size", [16, 32]) |
| 231 | def test_flydsl_matches_reference(num_seqs, seq_len, num_kv_heads, qg, kv_block_size): |
| 232 | """FlyDSL decode must match fp32 attention on dequantized KV.""" |
| 233 | centroids, q_bf16, kv_cache, block_table, seq_lens, k_ref, v_ref = _build_cache( |
| 234 | num_seqs, num_kv_heads, seq_len, qg, kv_block_size |
| 235 | ) |
| 236 | scale = 1.0 / (HEAD_SIZE**0.5) |
| 237 | identity = torch.eye(HEAD_SIZE, dtype=torch.float32, device="cuda") |
| 238 | |
| 239 | out = flydsl_turboquant_decode_attention( |
| 240 | query=q_bf16, |
| 241 | kv_cache=kv_cache, |
| 242 | block_table=block_table, |
| 243 | seq_lens=seq_lens, |
| 244 | Pi=identity, |
| 245 | centroids=centroids, |
| 246 | scale=scale, |
| 247 | mse_bits=4, |
| 248 | key_packed_size=KEY_DATA_BYTES + 2, |
| 249 | value_quant_bits=4, |
| 250 | value_packed_size=KEY_DATA_BYTES + 4, |
| 251 | key_fp8=False, |
| 252 | norm_correction=False, |
| 253 | PiT=identity.T.contiguous(), |
| 254 | max_seq_len=seq_len, |
| 255 | max_num_kv_splits=32, |
| 256 | sinks=None, |
| 257 | ) |
| 258 | |
| 259 | ref = _reference_attention(q_bf16.cpu(), k_ref, v_ref, seq_lens.cpu(), scale) |
| 260 | |
| 261 | torch.testing.assert_close(out.cpu().float(), ref, atol=ATOL, rtol=0.0) |