main
py 2,347 lines 87.8 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 """Round-trip tests for compressor → FP8 quant + KV cache insert → gather + dequant.
4
5 These tests cover:
6 A) DeepseekV4 Attention: head_dim=512 (448 FP8 nope + 64 bf16 rope), quant_block=64
7 B) Fused dequant+gather K cache
8 C) Indexer: head_dim=128 (all FP8), quant_block=128
9 D) DeepseekV4 Attention magnitude range: correctness across small/large values
10 E) Indexer fused Triton kernel: compress+norm+rope+quant+insert
11 F) Indexer fused two-stage Triton kernel: head=512 cr>=128 (no-overlap)
12 """
13
14 import math
15 from types import SimpleNamespace
16
17 import pytest
18 import torch
19
20 from vllm import _custom_ops as ops
21 from vllm.models.deepseek_v4.common.ops import (
22 dequantize_and_gather_k_cache,
23 quantize_and_insert_k_cache,
24 )
25 from vllm.models.deepseek_v4.common.ops.fused_compress_quant_cache import (
26 _fused_kv_compress_norm_rope_insert_indexer_attn,
27 _fused_kv_compress_norm_rope_insert_indexer_mxfp4_attn,
28 _launch_two_stage_sparse_attn_compressor,
29 compress_norm_rope_store_triton,
30 )
31 from vllm.models.deepseek_v4.compressor import _get_c128_boundary
32 from vllm.platforms import current_platform
33 from vllm.v1.attention.backends.mla.compressor_utils import (
34 get_dspark_swa_index_width,
35 )
36 from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
37 cp_gather_indexer_k_quant_cache_triton,
38 indexer_k_quant_and_cache_triton,
39 )
40
41 from .test_fused_indexer_q_rope_quant import quantize_to_mxfp4
42
43
44 @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
45 @pytest.mark.parametrize(
46 "cache_dtype,kv_mxfp8",
47 [
48 (torch.uint8, False),
49 (torch.uint8, True),
50 (torch.bfloat16, False),
51 (torch.float8_e4m3fn, False),
52 ],
53 )
54 @pytest.mark.parametrize("num_tokens", [1, 17, 1023, 1024])
55 @pytest.mark.parametrize("use_graph", [False, True])
56 def test_dspark_context_kv_matches_query_insert(
57 cache_dtype, kv_mxfp8, num_tokens, use_graph
58 ):
59 """KV-only insertion must preserve every cache byte, including graph replay."""
60 from vllm.models.deepseek_v41.nvidia.dspark import _insert_context_kv
61
62 torch.manual_seed(42)
63 block_size = 256
64 num_blocks = math.ceil((num_tokens + 7) / block_size)
65 row_size = (528 if kv_mxfp8 else 584) if cache_dtype == torch.uint8 else 512
66 page_stride = math.ceil(block_size * row_size / 576) * 576 + 576
67 backing = torch.full((num_blocks, page_stride), 3, device="cuda").to(cache_dtype)
68 cache = backing.as_strided(
69 (num_blocks, block_size, row_size), (page_stride, row_size, 1)
70 )
71 reference_backing = backing.clone()
72 reference = reference_backing.as_strided(cache.shape, cache.stride())
73 kv = torch.randn(num_tokens + 3, 512, device="cuda", dtype=torch.bfloat16)
74 positions = torch.arange(num_tokens + 3, device="cuda") + 7
75 angles = torch.randn(num_tokens + 16, 32, device="cuda")
76 cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
77 slots = torch.randperm(num_blocks * block_size, device="cuda")[:num_tokens]
78 slots[::5] = -1
79 scale = torch.tensor([0.7], device="cuda")
80 # Only what _insert_context_kv actually reads: the record width comes off
81 # the cache tensor, so no per-record width attribute is stubbed here.
82 attn = SimpleNamespace(
83 swa_cache_layer=SimpleNamespace(kv_cache=cache, block_size=block_size),
84 kv_mxfp8=kv_mxfp8,
85 rotary_emb=SimpleNamespace(cos_sin_cache=cos_sin),
86 _flashinfer_fp8_kv_scale=scale,
87 )
88
89 def legacy_insert():
90 q = torch.zeros(kv.shape[0], 8, 512, dtype=kv.dtype, device="cuda")
91 if cache_dtype == torch.uint8:
92 torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert(
93 q,
94 kv,
95 reference.view(num_blocks, -1),
96 slots,
97 positions,
98 cos_sin,
99 8,
100 1e-20,
101 block_size,
102 True,
103 kv_mxfp8,
104 )
105 elif cache_dtype == torch.bfloat16:
106 torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_bf16_insert(
107 q,
108 kv,
109 reference,
110 slots,
111 positions,
112 cos_sin,
113 1e-20,
114 block_size,
115 )
116 else:
117 q_fp8 = torch.empty_like(q, dtype=cache_dtype)
118 torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_full_cache_fp8_insert(
119 q,
120 kv,
121 q_fp8,
122 reference,
123 slots,
124 positions,
125 cos_sin,
126 scale,
127 scale,
128 1e-20,
129 block_size,
130 )
131
132 def insert():
133 _insert_context_kv(attn, kv, positions, slots)
134
135 insert()
136 graph = None
137 if use_graph:
138 graph = torch.cuda.CUDAGraph()
139 with torch.cuda.graph(graph):
140 insert()
141 for iteration in range(3):
142 kv.normal_()
143 positions.add_(1)
144 if iteration == 2:
145 slots.fill_(-1)
146 backing.view(torch.uint8).fill_(165)
147 reference_backing.copy_(backing)
148 before = kv.clone()
149 legacy_insert()
150 insert() if graph is None else graph.replay()
151 torch.testing.assert_close(
152 backing.view(torch.uint8),
153 reference_backing.view(torch.uint8),
154 rtol=0,
155 atol=0,
156 )
157 torch.testing.assert_close(kv, before, rtol=0, atol=0)
158
159
160 @pytest.mark.skipif(
161 not current_platform.is_cuda_alike(), reason="graph capture coverage"
162 )
163 @pytest.mark.parametrize("compress_ratio", [1, 2])
164 @pytest.mark.parametrize("use_graph", [False, True])
165 @pytest.mark.parametrize(
166 "lengths",
167 [(1, 5, 13), (1, 1, 1), (1, 2, 0), (7, 8, 8), (2, 3, 3)],
168 ids=["prefill", "decode", "empty", "wrap_threshold", "packed_boundary"],
169 )
170 def test_v41_fused_save_compress_and_insert(
171 compress_ratio: int, use_graph: bool, lengths: tuple[int, ...]
172 ):
173 """Ring states: a group boundary whose previous token is outside the chunk
174 pools the ring row that chunk left behind, even when this chunk overwrites
175 that row; only the last ``capacity`` tokens of a chunk are stored.
176
177 Exercise historical group starts, adjacent requests, a chunk longer than
178 the ring, single-token decode pairs, empty requests, wrap thresholds at
179 odd and even starts, padded graph rows, and padded physical pages against
180 a Torch reference with BF16 rounding before RoPE. Replays change both
181 inputs and history so stale scratch/cache values cannot satisfy the test.
182 """
183 from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
184 fused_save_compress_norm,
185 rope_quant_insert,
186 )
187
188 torch.manual_seed(42)
189 device = "cuda"
190 capacity = 8
191 starts = [7, 8, 13]
192 actual = sum(lengths)
193 num_tokens = actual + 5
194 positions = torch.zeros(num_tokens, dtype=torch.int64, device=device)
195 req_ids = torch.zeros(actual + 2, dtype=torch.int32, device=device)
196 state_slots = torch.full((actual + 2,), -1, dtype=torch.int64, device=device)
197 cache_slots = torch.full_like(state_slots, -1)
198 query_start_loc = torch.tensor(
199 [0, *torch.tensor(lengths).cumsum(0).tolist()], dtype=torch.int32
200 ).to(device)
201 ring_blocks = torch.randperm(6, device=device)[:3]
202 raw = torch.randn(num_tokens, 512 * compress_ratio, device=device)
203 norm = torch.randn(512, dtype=torch.bfloat16, device=device)
204 latent = torch.empty(num_tokens, 512, dtype=torch.bfloat16, device=device)
205 angles = torch.randn(32, 32, device=device)
206 cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
207 # capacity x 1024 floats rounded up to 576-byte alignment.
208 state_backing = torch.empty(6, 8208, device=device)
209 state = state_backing.as_strided((6, capacity, 1024), (8208, 1024, 1))
210 cache_block = 256 // compress_ratio
211 cache_stride = math.ceil(cache_block * 584 / 576) * 576
212 cache_backing = torch.empty(3, cache_stride, dtype=torch.uint8, device=device)
213 cache = cache_backing.as_strided((3, cache_block, 584), (cache_stride, 584, 1))
214 cursor = 0
215 for req, (start, length) in enumerate(zip(starts, lengths)):
216 pos = torch.arange(start, start + length, device=device)
217 rows = slice(cursor, cursor + length)
218 positions[rows] = pos
219 req_ids[rows] = req
220 state_slots[rows] = ring_blocks[req] * capacity + pos % capacity
221 cache_slots[rows] = (2 - req) * cache_block + pos // compress_ratio
222 cursor += length
223
224 has_ring = compress_ratio == 2
225
226 def run():
227 fused_save_compress_norm(
228 raw,
229 positions,
230 state if has_ring else None,
231 state_slots,
232 query_start_loc if has_ring else None,
233 req_ids if has_ring else None,
234 norm,
235 1e-20,
236 compress_ratio,
237 latent,
238 )
239 rope_quant_insert(
240 latent, positions, cos_sin, cache, cache_slots, compress_ratio
241 )
242
243 state_backing.normal_()
244 run()
245 graph = None
246 if use_graph:
247 stream = torch.cuda.Stream()
248 stream.wait_stream(torch.cuda.current_stream())
249 with torch.cuda.stream(stream):
250 run()
251 torch.cuda.current_stream().wait_stream(stream)
252 graph = torch.cuda.CUDAGraph()
253 with torch.cuda.graph(graph):
254 run()
255
256 for _ in range(3):
257 raw.normal_()
258 state_backing.normal_()
259 history = state.clone()
260 expected_state = state_backing.clone()
261 expected_rows = expected_state.as_strided((6, capacity, 1024), (8208, 1024, 1))
262 cache_backing.fill_(165)
263 expected_cache = cache_backing.clone()
264 latent.fill_(float("nan"))
265 # Ratio 1 has no ring; ratio 2 stores each chunk's last `capacity` rows.
266 for t in range(actual if has_ring else 0):
267 req = req_ids[t].item()
268 if query_start_loc[req + 1].item() - t > capacity:
269 continue
270 slot = state_slots[t].item()
271 expected_rows[slot // capacity, slot % capacity, :512] = raw[t, :512]
272 expected_rows[slot // capacity, slot % capacity, 512:] = raw[t, 512:]
273
274 if graph is None:
275 run()
276 else:
277 graph.replay()
278
279 torch.testing.assert_close(state_backing, expected_state, rtol=0, atol=0)
280 for t in range(num_tokens):
281 pos = positions[t].item()
282 if t >= actual or (pos + 1) % compress_ratio:
283 assert torch.isnan(latent[t]).all()
284 continue
285 req = req_ids[t].item()
286 group_rows = []
287 for k in range(compress_ratio - 1, -1, -1):
288 if t - k >= query_start_loc[req].item():
289 kv_score = raw[t - k]
290 if compress_ratio == 1:
291 kv_score = torch.cat((kv_score, torch.zeros_like(kv_score)))
292 group_rows.append(kv_score)
293 else:
294 ring = ring_blocks[req].item()
295 group_rows.append(history[ring, (pos - k) % capacity])
296 group = torch.stack(group_rows)
297 pooled = (group[:, :512] * group[:, 512:].softmax(0)).sum(0)
298 normed = pooled * torch.rsqrt(pooled.square().mean() + 1e-20) * norm
299 torch.testing.assert_close(latent[t].float(), normed, rtol=0.004, atol=1e-6)
300
301 slot = cache_slots[t].item()
302 page, row = divmod(slot, cache_block)
303 values = expected_cache[page, row * 576 : (row + 1) * 576]
304 quantized, scales = _ue8m0_reference(latent[t, :448], 64, 448.0)
305 values[:448] = quantized.view(torch.uint8)
306 c, s = cos_sin[pos // compress_ratio * compress_ratio].chunk(2)
307 rope_input = latent[t, 448:].float()
308 rotated = (
309 torch.stack(
310 (
311 rope_input[0::2] * c - rope_input[1::2] * s,
312 rope_input[1::2] * c + rope_input[0::2] * s,
313 ),
314 dim=-1,
315 )
316 .flatten()
317 .to(torch.bfloat16)
318 )
319 actual_rope = cache_backing[page, row * 576 + 448 : (row + 1) * 576].view(
320 torch.bfloat16
321 )
322 torch.testing.assert_close(actual_rope, rotated, rtol=0.008, atol=1e-6)
323 values[448:] = actual_rope.view(torch.uint8)
324 scale_offset = cache_block * 576 + row * 8
325 expected_cache[page, scale_offset : scale_offset + 7] = (
326 scales.log2() + 127
327 ).to(torch.uint8)
328 expected_cache[page, scale_offset + 7] = 0
329 # Includes unwritten rows, page padding, quantized values and scales.
330 torch.testing.assert_close(cache_backing, expected_cache, rtol=0, atol=0)
331
332
333 def _rotate_rope_tail(
334 latent_row: torch.Tensor, cos_sin_row: torch.Tensor
335 ) -> torch.Tensor:
336 """GPT-J RoPE of one latent row's last 64 dims, in fp32."""
337 row = latent_row.float()
338 c, s = cos_sin_row.chunk(2)
339 rotated = row.clone()
340 even, odd = row[448::2], row[449::2]
341 rotated[448::2] = even * c - odd * s
342 rotated[449::2] = odd * c + even * s
343 return rotated
344
345
346 def _mxfp8_record_reference(
347 latent_row: torch.Tensor, cos_sin_row: torch.Tensor
348 ) -> tuple[torch.Tensor, torch.Tensor]:
349 """Reference V4.1 record for one token: 512 fp8 bytes + 16 UE8M0 scales.
350
351 Mirrors FlashMLA's ``KVCacheLayout.V41_FP8Sparse`` quantizer: rotate the
352 RoPE tail first, then scale every 32-dim tile, RoPE tiles included.
353 """
354 rotated = _rotate_rope_tail(latent_row, cos_sin_row)
355 quantized, scales = _ue8m0_reference(rotated, 32, 448.0)
356 return quantized.view(torch.uint8), (scales.log2() + 127).to(torch.uint8)
357
358
359 @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
360 @pytest.mark.parametrize("compress_ratio", [1, 2])
361 def test_v41_rope_insert_mxfp8_record(compress_ratio: int):
362 """The 528-byte V4.1 record quantizes the RoPE dims instead of keeping them
363 in bf16, so a page is [block_size x 512 fp8][block_size x 16 UE8M0].
364
365 Byte-exact against the reference quantizer, including the rows and page
366 padding the kernel must leave alone.
367 """
368 from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
369 rope_quant_insert,
370 )
371
372 torch.manual_seed(7)
373 device = "cuda"
374 cache_block = 64
375 cache_stride = math.ceil(cache_block * 528 / 512) * 512
376 num_tokens = 12
377
378 positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
379 latent = torch.randn(num_tokens, 512, dtype=torch.bfloat16, device=device)
380 angles = torch.randn(64, 32, device=device)
381 cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
382
383 cache_backing = torch.full((2, cache_stride), 165, dtype=torch.uint8, device=device)
384 cache = cache_backing.as_strided((2, cache_block, 528), (cache_stride, 528, 1))
385 # Leave one token unmapped so the kernel's negative-slot skip is covered.
386 slots = torch.arange(num_tokens, dtype=torch.int64, device=device)
387 slots[3] = -1
388
389 rope_quant_insert(latent, positions, cos_sin, cache, slots, compress_ratio)
390
391 expected = torch.full_like(cache_backing, 165)
392 for t in range(num_tokens):
393 slot = slots[t].item()
394 pos = positions[t].item()
395 if slot < 0 or (pos + 1) % compress_ratio:
396 continue
397 page, row = divmod(slot, cache_block)
398 values, scales = _mxfp8_record_reference(
399 latent[t], cos_sin[pos // compress_ratio * compress_ratio]
400 )
401 expected[page, row * 512 : (row + 1) * 512] = values
402 scale_offset = cache_block * 512 + row * 16
403 expected[page, scale_offset : scale_offset + 16] = scales
404
405 torch.testing.assert_close(cache_backing, expected, rtol=0, atol=0)
406
407
408 @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
409 def test_v41_mxfp8_cache_round_trip():
410 """quantize_and_insert -> dequantize_and_gather recovers the V4.1 record.
411
412 The RoPE dims now go through fp8, so they carry quantization error too --
413 the check is that every dim survives within one MXFP8 tile step, and that
414 the bytes on the way match the reference quantizer.
415 """
416 from vllm.models.deepseek_v41.common.ops import (
417 dequantize_and_gather_k_cache,
418 quantize_and_insert_k_cache,
419 )
420
421 torch.manual_seed(11)
422 device = "cuda"
423 block_size = 64
424 num_tokens = 70
425 num_blocks = 4
426 page_bytes = math.ceil(block_size * 528 / 512) * 512
427
428 k = torch.randn(num_tokens, 512, dtype=torch.bfloat16, device=device)
429 cache = torch.zeros(num_blocks, page_bytes, dtype=torch.uint8, device=device)
430 slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
431 quantize_and_insert_k_cache(
432 k, cache, slot_mapping, block_size=block_size, bytes_per_token=528
433 )
434
435 for t in (0, 1, block_size, num_tokens - 1):
436 values, scales = _ue8m0_reference(k[t].float(), 32, 448.0)
437 page, row = divmod(t, block_size)
438 torch.testing.assert_close(
439 cache[page, row * 512 : (row + 1) * 512],
440 values.view(torch.uint8),
441 rtol=0,
442 atol=0,
443 )
444 scale_offset = block_size * 512 + row * 16
445 torch.testing.assert_close(
446 cache[page, scale_offset : scale_offset + 16],
447 (scales.log2() + 127).to(torch.uint8),
448 rtol=0,
449 atol=0,
450 )
451
452 out = torch.zeros(1, num_tokens, 512, dtype=torch.bfloat16, device=device)
453 dequantize_and_gather_k_cache(
454 out,
455 cache.view(num_blocks, block_size, 528),
456 seq_lens=torch.tensor([num_tokens], dtype=torch.int32, device=device),
457 gather_lens=None,
458 block_table=torch.arange(num_blocks, dtype=torch.int32, device=device).view(
459 1, -1
460 ),
461 block_size=block_size,
462 offset=0,
463 )
464 # Half an e4m3 ULP at the top of the range (16 units) bounds the error.
465 tile_amax = k.float().abs().view(num_tokens, 16, 32).amax(-1).clamp(min=1e-4)
466 tolerance = 16.0 * (tile_amax / 448.0).log2().ceil().exp2()
467 error = (out[0].float() - k.float()).abs()
468 assert (error <= tolerance.repeat_interleave(32, dim=-1)).all()
469
470
471 # e2m1 magnitudes indexed by the low 3 bits of a code; bit 3 is the sign.
472 _E2M1_MAGNITUDES = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0]
473
474
475 def _decode_nvfp4_row(packed: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
476 """Unpack e2m1 rows and apply their e4m3 tile scales."""
477 mags = torch.tensor(_E2M1_MAGNITUDES, device=packed.device)
478 codes = torch.empty(
479 (*packed.shape[:-1], 512), dtype=torch.uint8, device=packed.device
480 )
481 codes[..., 0::2] = packed & 0xF # even element in the low nibble
482 codes[..., 1::2] = packed >> 4
483 vals = mags[(codes & 7).long()] * torch.where(codes >= 8, -1.0, 1.0)
484 return (
485 vals.reshape(*packed.shape[:-1], 32, 16)
486 * scales.view(torch.float8_e4m3fn).float().reshape(*packed.shape[:-1], 32, 1)
487 ).flatten(-2)
488
489
490 @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
491 @pytest.mark.parametrize("compress_ratio", [1, 2])
492 def test_v41_rope_insert_nvfp4_record(compress_ratio: int):
493 """The 288-byte V4.1 NVFP4 record: 256 B of e2m1 pairs then 32 e4m3 scales.
494
495 Scales are byte-exact against the reference (``amax / 6`` clamped to the
496 e4m3 range); values are checked as round-to-nearest on the e2m1 grid, whose
497 coarsest step is 2 between 4 and 6, so half a step is ``1.0 * scale``.
498 """
499 from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
500 rope_quant_insert,
501 )
502
503 torch.manual_seed(13)
504 device = "cuda"
505 cache_block = 64
506 cache_stride = math.ceil(cache_block * 288 / 512) * 512
507 num_tokens = 12
508
509 positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
510 latent = torch.randn(num_tokens, 512, dtype=torch.bfloat16, device=device)
511 angles = torch.randn(64, 32, device=device)
512 cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
513
514 cache_backing = torch.full((2, cache_stride), 165, dtype=torch.uint8, device=device)
515 cache = cache_backing.as_strided((2, cache_block, 288), (cache_stride, 288, 1))
516 slots = torch.arange(num_tokens, dtype=torch.int64, device=device)
517 slots[3] = -1 # covers the negative-slot skip
518
519 rope_quant_insert(latent, positions, cos_sin, cache, slots, compress_ratio)
520
521 untouched = torch.full_like(cache_backing, 165)
522 for t in range(num_tokens):
523 slot = slots[t].item()
524 pos = positions[t].item()
525 if slot < 0 or (pos + 1) % compress_ratio:
526 continue
527 page, row = divmod(slot, cache_block)
528 cs = cos_sin[pos // compress_ratio * compress_ratio]
529 rotated = _rotate_rope_tail(latent[t], cs)
530 amax = rotated.view(32, 16).abs().amax(-1)
531 scale = (amax / 6.0).clamp(2.0**-9, 448.0).to(torch.float8_e4m3fn)
532
533 got_scales = cache_backing[page, cache_block * 256 + row * 32 :][:32]
534 torch.testing.assert_close(got_scales, scale.view(torch.uint8), rtol=0, atol=0)
535 decoded = _decode_nvfp4_row(
536 cache_backing[page, row * 256 : (row + 1) * 256], got_scales
537 )
538 step = scale.float().repeat_interleave(16)
539 assert ((decoded - rotated).abs() <= step).all()
540 untouched[page, row * 256 : (row + 1) * 256] = cache_backing[
541 page, row * 256 : (row + 1) * 256
542 ]
543 untouched[page, cache_block * 256 + row * 32 :][:32] = got_scales
544 # Rows the kernel must not have touched, page padding included.
545 torch.testing.assert_close(cache_backing, untouched, rtol=0, atol=0)
546
547
548 @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
549 @pytest.mark.parametrize("num_reqs", [1, 8, 32])
550 @pytest.mark.parametrize("num_tokens", [70, 128, 129, 2051])
551 @pytest.mark.parametrize("partial", [False, True])
552 def test_v41_nvfp4_gather_matches_insert(num_reqs, num_tokens, partial):
553 """The NVFP4 gather dequantizes exactly what the insert kernel wrote."""
554 from vllm.models.deepseek_v41.common.ops import dequantize_and_gather_k_cache
555 from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
556 rope_quant_insert,
557 )
558
559 torch.manual_seed(17)
560 device = "cuda"
561 block_size = 64
562 num_blocks = math.ceil(num_tokens / block_size)
563 page_bytes = math.ceil(block_size * 288 / 512) * 512
564
565 positions = torch.arange(num_tokens, dtype=torch.int64, device=device)
566 latent = torch.randn(num_tokens, 512, dtype=torch.bfloat16, device=device)
567 angles = torch.randn(num_tokens, 32, device=device)
568 cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
569 backing = torch.zeros(num_blocks, page_bytes, dtype=torch.uint8, device=device)
570 cache = backing.as_strided((num_blocks, block_size, 288), (page_bytes, 288, 1))
571 slots = torch.arange(num_tokens, dtype=torch.int64, device=device)
572 rope_quant_insert(latent, positions, cos_sin, cache, slots, 1)
573
574 offset = 7 if partial else 0
575 seq_lens = num_tokens - torch.arange(num_reqs, dtype=torch.int32, device=device)
576 gather_lens = seq_lens - 3 if partial else None
577 storage = torch.full(
578 (num_reqs, num_tokens + offset + 16, 512),
579 -123.0,
580 dtype=torch.bfloat16,
581 device=device,
582 )
583 out = storage[:, : num_tokens + offset]
584 block_table = torch.arange(num_blocks, dtype=torch.int32, device=device).repeat(
585 num_reqs, 1
586 )
587
588 def gather():
589 dequantize_and_gather_k_cache(
590 out,
591 cache,
592 seq_lens=seq_lens,
593 gather_lens=gather_lens,
594 block_table=block_table,
595 block_size=block_size,
596 offset=offset,
597 )
598
599 expected = _decode_nvfp4_row(
600 backing[:, : block_size * 256].reshape(-1, 256),
601 backing[:, block_size * 256 : block_size * 288].reshape(-1, 32),
602 )
603
604 def check(shorter_by):
605 assert (storage[:, num_tokens + offset :] == -123).all()
606 for req in range(num_reqs):
607 start = 3 if partial else 0
608 length = num_tokens - req - start - shorter_by
609 assert (out[req, :offset] == -123).all()
610 assert (out[req, offset + length :] == -123).all()
611 torch.testing.assert_close(
612 out[req, offset : offset + length].float(),
613 expected[start : start + length],
614 rtol=0,
615 atol=0,
616 )
617
618 gather()
619 check(0)
620 graph = torch.cuda.CUDAGraph()
621 with torch.cuda.graph(graph):
622 gather()
623 storage.fill_(-123)
624 seq_lens.sub_(1)
625 if gather_lens is not None:
626 gather_lens.sub_(1)
627 graph.replay()
628 check(1)
629
630
631 @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA only")
632 @pytest.mark.parametrize("compress_ratio", [1, 2])
633 @pytest.mark.parametrize("store_fp8", [False, True])
634 def test_v41_rope_insert_plain_row(compress_ratio: int, store_fp8: bool):
635 """The FlashInfer plain-row compressed cache gets [448 NoPE | 64 RoPE] rows.
636
637 bf16 caches store the latent verbatim with the RoPE tail rotated; per-tensor
638 fp8 caches scale the bf16-rounded row by 1/fp8_scale and clamp to e4m3.
639 Non-boundary positions, negative slots and untouched rows must keep their
640 prior contents.
641 """
642 from vllm.models.deepseek_v41.common.ops.fused_compress_quant_cache import (
643 rope_quant_insert,
644 )
645
646 torch.manual_seed(3)
647 device = "cuda"
648 num_tokens = 9
649 cache_block = 4
650 positions = torch.arange(5, 5 + num_tokens, dtype=torch.int64, device=device)
651 cache_slots = torch.randperm(3 * cache_block, device=device)[:num_tokens]
652 cache_slots[2] = -1
653 latent = torch.randn(num_tokens, 512, device=device).to(torch.bfloat16)
654 angles = torch.randn(32, 32, device=device)
655 cos_sin = torch.cat((angles.cos(), angles.sin()), dim=-1)
656 dtype = torch.float8_e4m3fn if store_fp8 else torch.bfloat16
657 # Pad the page stride so the kernel must honour strides, not shape.
658 cache_backing = torch.full((3, (cache_block + 1) * 512), 3.0, device=device)
659 cache_backing = cache_backing.to(dtype)
660 cache = cache_backing.as_strided(
661 (3, cache_block, 512), ((cache_block + 1) * 512, 512, 1)
662 )
663 fp8_scale = torch.tensor([0.5], dtype=torch.float32, device=device)
664 expected = cache_backing.clone().float()
665
666 rope_quant_insert(
667 latent,
668 positions,
669 cos_sin,
670 cache,
671 cache_slots,
672 compress_ratio,
673 fp8_scale=fp8_scale if store_fp8 else None,
674 )
675
676 for t in range(num_tokens):
677 pos = positions[t].item()
678 slot = cache_slots[t].item()
679 if slot < 0 or (pos + 1) % compress_ratio:
680 continue
681 c, s = cos_sin[pos // compress_ratio * compress_ratio].chunk(2)
682 rope_input = latent[t, 448:].float()
683 rotated = torch.stack(
684 (
685 rope_input[0::2] * c - rope_input[1::2] * s,
686 rope_input[1::2] * c + rope_input[0::2] * s,
687 ),
688 dim=-1,
689 ).flatten()
690 row = torch.cat((latent[t, :448], rotated.to(torch.bfloat16))).float()
691 if store_fp8:
692 row = (row * (1.0 / fp8_scale)).clamp(-448.0, 448.0)
693 row = row.to(torch.float8_e4m3fn).float()
694 page, idx = divmod(slot, cache_block)
695 expected[page, idx * 512 : (idx + 1) * 512] = row
696
697 actual = cache_backing.float()
698 if store_fp8:
699 # One e4m3 ulp of slack for FMA-vs-separate rounding in the RoPE tail.
700 torch.testing.assert_close(actual, expected, rtol=0.13, atol=1e-2)
701 else:
702 nope = torch.arange(512, device=device) < 448
703 nope = nope.repeat(cache_block + 1)
704 torch.testing.assert_close(actual[:, nope], expected[:, nope], rtol=0, atol=0)
705 torch.testing.assert_close(
706 actual[:, ~nope], expected[:, ~nope], rtol=0.008, atol=1e-6
707 )
708
709
710 @pytest.mark.skipif(not current_platform.is_cuda(), reason="Triton kernel")
711 def test_v41_compressor_metadata_maps_tokens_to_their_ring():
712 """The ring group's generic slot mapping is disabled (all PAD), so the
713 builder must map every real token to ``ring_block * capacity + pos %
714 capacity`` and keep padding tokens at PAD."""
715 from unittest.mock import MagicMock
716
717 from vllm.models.deepseek_v41.compressor import CompressorMetadataBuilder
718 from vllm.v1.attention.backend import CommonAttentionMetadata
719 from vllm.v1.kv_cache_interface import CircularBufferSpec
720
721 capacity = 8
722 vllm_config = MagicMock()
723 vllm_config.scheduler_config.max_num_batched_tokens = 16
724 spec = CircularBufferSpec(
725 block_size=capacity,
726 num_kv_heads=1,
727 head_size=1024,
728 head_size_v=0,
729 dtype=torch.float32,
730 )
731 device = torch.device("cuda")
732 builder = CompressorMetadataBuilder(spec, ["state"], vllm_config, device)
733
734 # Two requests: 3 tokens at positions 13..15 on ring block 5, then 2
735 # tokens at positions 7..8 on ring block 2; three padding tokens.
736 query_start_loc = torch.tensor([0, 3, 5], dtype=torch.int32, device=device)
737 positions = torch.tensor([13, 14, 15, 7, 8, 0, 0, 0], device=device)
738 block_table = torch.tensor([[5], [2]], dtype=torch.int32, device=device)
739 common = CommonAttentionMetadata(
740 query_start_loc=query_start_loc,
741 query_start_loc_cpu=query_start_loc.cpu(),
742 seq_lens=torch.tensor([16, 9], dtype=torch.int32, device=device),
743 num_reqs=2,
744 num_actual_tokens=5,
745 max_query_len=3,
746 max_seq_len=16,
747 block_table_tensor=block_table,
748 slot_mapping=torch.full((8,), -1, dtype=torch.int64, device=device),
749 positions=positions,
750 )
751 metadata = builder.build(0, common)
752
753 expected = [5 * 8 + 5, 5 * 8 + 6, 5 * 8 + 7, 2 * 8 + 7, 2 * 8 + 0, -1, -1, -1]
754 assert metadata.slot_mapping.tolist() == expected
755 assert metadata.query_start_loc is query_start_loc
756 assert metadata.token_to_req_indices.tolist() == [0, 0, 0, 1, 1]
757
758
759 @pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA stream coverage")
760 @pytest.mark.parametrize(
761 "use_aux,use_graph", [(False, False), (True, False), (True, True)]
762 )
763 @torch.inference_mode()
764 def test_v41_attention_joins_cache_writes_before_consumption(use_aux, use_graph):
765 """Both reused-event joins must publish this forward's states and cache rows."""
766 from vllm.forward_context import ForwardContext, override_forward_context
767 from vllm.models.deepseek_v41.attention import (
768 DeepseekV4Attention,
769 DeepseekV4Indexer,
770 )
771 from vllm.models.deepseek_v41.compressor import DeepseekCompressor
772
773 torch.manual_seed(43)
774 raw = torch.randn(19, 1024, device="cuda")
775 q = torch.zeros(19, 512, dtype=torch.bfloat16, device="cuda")
776 positions = torch.arange(7, 26, device="cuda")
777 state_slots = positions.clone()
778 state_slots[-2:] = -1
779 cache_slots = torch.where(state_slots >= 0, positions // 2, -1)
780 state = torch.empty(4, 8, 1024, device="cuda")
781 main = torch.empty(1, 128, 584, dtype=torch.uint8, device="cuda")
782 index = torch.empty(1, 128, 132, dtype=torch.uint8, device="cuda")
783 caches = (state, main, index)
784 observed = tuple(torch.empty_like(cache) for cache in caches)
785 rotary = SimpleNamespace(cos_sin_cache=torch.randn(32, 64, device="cuda"))
786 metadata = {
787 "state": SimpleNamespace(
788 slot_mapping=state_slots,
789 query_start_loc=torch.tensor([0, 19], dtype=torch.int32, device="cuda"),
790 token_to_req_indices=torch.zeros(19, dtype=torch.int32, device="cuda"),
791 ),
792 "main": SimpleNamespace(slot_mapping=cache_slots),
793 "index": SimpleNamespace(slot_mapping=cache_slots),
794 }
795 context = ForwardContext({}, metadata, {})
796 compressor = DeepseekCompressor.__new__(DeepseekCompressor)
797 torch.nn.Module.__init__(compressor)
798 compressor.head_dim, compressor.rope_head_dim, compressor.compress_ratio = (
799 512,
800 64,
801 2,
802 )
803 compressor.rms_norm_eps = 1e-20
804 compressor.norm = SimpleNamespace(
805 weight=torch.ones(512, dtype=torch.bfloat16, device="cuda")
806 )
807 compressor.state_cache = SimpleNamespace(prefix="state", kv_cache=state)
808 compressor.k_cache_prefix = "main"
809 compressor._static_forward_context = {"main": SimpleNamespace(kv_cache=main)}
810 indexer_weight = torch.randn(128, 512, dtype=torch.bfloat16, device="cuda")
811 indexer = SimpleNamespace(
812 owns_k=True,
813 wk=lambda latent: (torch.nn.functional.linear(latent, indexer_weight), None),
814 k_norm=SimpleNamespace(
815 weight=torch.ones(128, dtype=torch.bfloat16, device="cuda"),
816 variance_epsilon=1e-20,
817 ),
818 k_cache=SimpleNamespace(prefix="index", kv_cache=index),
819 compress_ratio=2,
820 use_fp4_kv=False,
821 )
822
823 def prepare_indexer(qr, latent, weights, positions, rotary, qr_scale):
824 DeepseekV4Indexer._produce_k(indexer, latent, positions, rotary)
825 return None, None, None
826
827 def observe(*args):
828 for output, cache in zip(observed, caches):
829 output.copy_(cache)
830
831 auxiliary = [torch.cuda.Stream()] if use_aux else None
832 attention = SimpleNamespace(
833 compressor=compressor,
834 indexer=prepare_indexer,
835 aux_stream_list=auxiliary,
836 ln_events=[torch.cuda.Event(), torch.cuda.Event()],
837 rotary_emb=rotary,
838 indexer_rotary_emb=rotary,
839 n_local_heads=1,
840 head_dim=512,
841 _wq_b_proj=lambda qr, scale: qr.clone(),
842 _fused_qnorm_rope_kv_insert=lambda q, kv, pos, meta: q,
843 _sparse_indexer_and_attn=observe,
844 )
845
846 def run():
847 with override_forward_context(context):
848 DeepseekV4Attention._prepare_and_attn(
849 attention, q, q, q, None, raw, q, positions, q
850 )
851
852 def reset():
853 state.zero_()
854 main.fill_(165)
855 index.fill_(165)
856
857 reset()
858 run()
859 graph = None
860 if use_graph:
861 stream = torch.cuda.Stream()
862 stream.wait_stream(torch.cuda.current_stream())
863 with torch.cuda.stream(stream):
864 run()
865 torch.cuda.current_stream().wait_stream(stream)
866 graph = torch.cuda.CUDAGraph()
867 with torch.cuda.graph(graph):
868 run()
869
870 previous = None
871 for _ in range(3):
872 raw.normal_()
873 reset()
874 attention.aux_stream_list = None
875 run()
876 expected = tuple(output.clone() for output in observed)
877 reset()
878 attention.aux_stream_list = auxiliary
879 if graph is None:
880 run()
881 else:
882 graph.replay()
883 for actual, reference in zip(observed, expected):
884 torch.testing.assert_close(actual, reference, rtol=0, atol=0)
885 if previous is not None:
886 assert all(not torch.equal(a, b) for a, b in zip(expected, previous))
887 previous = expected
888
889
890 def _on_gfx950() -> bool:
891 if not current_platform.is_rocm():
892 return False
893 try:
894 from vllm.platforms.rocm import _ON_GFX950
895
896 return _ON_GFX950
897 except Exception:
898 return False
899
900
901 @pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm-only dispatch")
902 def test_cp_gather_despecialized_kernel_is_gfx950_only(monkeypatch):
903 from vllm.v1.attention.ops import rocm_aiter_mla_sparse as mod
904
905 class FakeKernel:
906 def __init__(self):
907 self.calls = []
908
909 def __getitem__(self, grid):
910 def launch(*args):
911 self.calls.append((grid, args))
912
913 return launch
914
915 legacy_kernel = FakeKernel()
916 gfx950_kernel = FakeKernel()
917 monkeypatch.setattr(mod, "_cp_gather_indexer_quant_cache_kernel", legacy_kernel)
918 monkeypatch.setattr(
919 mod,
920 "_cp_gather_indexer_quant_cache_gfx950_kernel",
921 gfx950_kernel,
922 )
923
924 k_cache = torch.zeros((4, 1, 132), dtype=torch.uint8)
925 k_fp8 = torch.empty((5, 128), dtype=current_platform.fp8_dtype())
926 k_scale = torch.empty((5, 4), dtype=torch.uint8)
927 block_table = torch.zeros((2, 7), dtype=torch.int32)
928 cu_seqlen = torch.tensor([0, 2, 5], dtype=torch.int32)
929 token_to_seq = torch.tensor([0, 0, 1, 1, 1], dtype=torch.int32)
930 args = (k_cache, k_fp8, k_scale, block_table, cu_seqlen, token_to_seq)
931
932 monkeypatch.setattr(mod, "_ON_GFX950", True)
933 mod.cp_gather_indexer_k_quant_cache_triton(*args)
934 assert len(gfx950_kernel.calls) == 1
935 assert not legacy_kernel.calls
936 gfx950_grid, gfx950_args = gfx950_kernel.calls[0]
937 assert gfx950_grid == (5,)
938 assert len(gfx950_args) == 18
939 assert gfx950_args[-3:] == (2, 7, 4)
940
941 monkeypatch.setattr(mod, "_ON_GFX950", False)
942 mod.cp_gather_indexer_k_quant_cache_triton(*args)
943 assert len(legacy_kernel.calls) == 1
944 legacy_grid, legacy_args = legacy_kernel.calls[0]
945 assert legacy_grid == (5,)
946 assert len(legacy_args) == 19
947 assert legacy_args[-4:] == (5, 2, 7, 4)
948
949
950 @pytest.mark.parametrize(
951 ("window_size", "num_speculative_tokens", "expected"),
952 [(128, 5, 192), (512, 5, 576), (1024, 0, 1024)],
953 )
954 def test_get_dspark_swa_index_width(
955 window_size: int, num_speculative_tokens: int, expected: int
956 ):
957 assert get_dspark_swa_index_width(window_size, num_speculative_tokens) == expected
958
959
960 def _ue8m0_reference(x: torch.Tensor, block_size: int, fp8_max: float):
961 """PyTorch reference for UE8M0 FP8 quantization (per-block, power-of-2 scale).
962
963 Returns (x_fp8, scales) where x_fp8 is float8_e4m3fn and scales are float32.
964 """
965 assert x.dim() == 1
966 n = x.numel()
967 n_blocks = math.ceil(n / block_size)
968 x_fp8 = torch.zeros(n, dtype=torch.float8_e4m3fn, device=x.device)
969 scales = torch.zeros(n_blocks, dtype=torch.float32, device=x.device)
970
971 for i in range(n_blocks):
972 start = i * block_size
973 end = min(start + block_size, n)
974 block = x[start:end].float()
975 amax = block.abs().max().clamp(min=1e-4)
976 raw_scale = amax / fp8_max
977 exponent = math.ceil(math.log2(raw_scale.item()))
978 scale = 2.0**exponent
979 scales[i] = scale
980 quantized = (block / scale).clamp(-fp8_max, fp8_max)
981 x_fp8[start:end] = quantized.to(torch.float8_e4m3fn)
982
983 return x_fp8, scales
984
985
986 def _decode_dsv4_cache_row(
987 cache: torch.Tensor, block_size: int, scrub_nan: bool
988 ) -> torch.Tensor:
989 flat = cache.flatten()
990 nope = flat[:448].view(torch.float8_e4m3fn).to(torch.bfloat16)
991 encoded = flat[block_size * 576 : block_size * 576 + 7]
992 scales = torch.exp2(encoded.to(torch.float32) - 127.0).to(torch.bfloat16)
993 nope = nope * scales.repeat_interleave(64)
994 rope = flat[448:576].view(torch.bfloat16)
995 decoded = torch.cat((nope, rope))
996 if scrub_nan:
997 decoded = torch.where(decoded == decoded, decoded, 0.0)
998 return decoded
999
1000
1001 def _assert_nan_free_cache_matches_legacy_scrub(
1002 cache: torch.Tensor, block_size: int
1003 ) -> None:
1004 flat = cache.flatten()
1005 scale_base = block_size * 576
1006 scale_codes = flat[scale_base : scale_base + 8]
1007 assert scale_codes[0].item() == 254
1008 assert scale_codes[1].item() == 247
1009 assert scale_codes[:7].max().item() <= 254
1010 nope_bytes = flat[:448]
1011 assert not ((nope_bytes == 0x7F) | (nope_bytes == 0xFF)).any()
1012
1013 rope = flat[448:576].view(torch.bfloat16)
1014 assert not torch.isnan(rope).any()
1015 assert torch.isposinf(rope[0])
1016 assert torch.equal(rope[1:4], torch.zeros_like(rope[1:4]))
1017
1018 legacy_cache = cache.clone()
1019 legacy_flat = legacy_cache.flatten()
1020 legacy_flat[scale_base] = 255
1021 legacy_rope = legacy_flat[448:576].view(torch.bfloat16)
1022 legacy_rope[1:4] = float("nan")
1023 canonical = _decode_dsv4_cache_row(cache, block_size, scrub_nan=False)
1024 legacy = _decode_dsv4_cache_row(legacy_cache, block_size, scrub_nan=True)
1025 torch.testing.assert_close(canonical, legacy, rtol=0, atol=0)
1026 assert torch.isinf(canonical[0])
1027 assert torch.isposinf(canonical[64])
1028
1029
1030 @pytest.mark.skipif(
1031 not _on_gfx950(),
1032 reason="NaN-free fp8_ds_mla compressed-cache contract is gfx950-only",
1033 )
1034 @pytest.mark.parametrize("writer", ["single_pass", "two_stage_finalizer"])
1035 def test_gfx950_compressed_cache_canonicalizes_nonfinite(writer: str) -> None:
1036 head_dim = 512
1037 rope_dim = 64
1038 block_size = 4
1039 device = "cuda"
1040
1041 positions = torch.zeros(1, dtype=torch.int64, device=device)
1042 slot_mapping = torch.zeros(1, dtype=torch.int64, device=device)
1043 rms_weight = torch.ones(head_dim, dtype=torch.bfloat16, device=device)
1044 rms_weight[0] = float("inf")
1045 rms_weight[64] = torch.finfo(torch.bfloat16).max
1046 rms_weight[448] = float("inf")
1047 rms_weight[450] = float("nan")
1048 cos_sin_cache = torch.zeros(1, rope_dim, dtype=torch.float32, device=device)
1049 cos_sin_cache[:, : rope_dim // 2] = 1.0
1050 cache = torch.zeros(1, block_size, 584, dtype=torch.uint8, device=device)
1051
1052 state_cache = torch.zeros(1, 1, 2 * head_dim, dtype=torch.float32, device=device)
1053 state_cache[..., :head_dim] = 1.0
1054 token_to_req = torch.zeros(1, dtype=torch.int32, device=device)
1055 block_table = torch.zeros(1, 1, dtype=torch.int32, device=device)
1056
1057 if writer == "single_pass":
1058 compress_norm_rope_store_triton(
1059 state_cache=state_cache,
1060 num_actual=1,
1061 token_to_req_indices=token_to_req,
1062 positions=positions,
1063 slot_mapping=slot_mapping,
1064 block_table=block_table,
1065 block_size=1,
1066 state_width=head_dim,
1067 cos_sin_cache=cos_sin_cache,
1068 kv_cache=cache,
1069 k_cache_metadata=SimpleNamespace(slot_mapping=slot_mapping),
1070 pdl_kwargs={},
1071 head_dim=head_dim,
1072 rope_head_dim=rope_dim,
1073 compress_ratio=1,
1074 overlap=False,
1075 use_fp4_cache=False,
1076 rms_norm_weight=rms_weight,
1077 rms_norm_eps=1e-6,
1078 quant_block=64,
1079 token_stride=576,
1080 scale_dim=8,
1081 )
1082 else:
1083 _launch_two_stage_sparse_attn_compressor(
1084 state_cache,
1085 token_to_req,
1086 positions,
1087 slot_mapping,
1088 block_table,
1089 1,
1090 head_dim,
1091 1,
1092 cos_sin_cache,
1093 cache,
1094 slot_mapping,
1095 rms_weight,
1096 1e-6,
1097 64,
1098 576,
1099 8,
1100 head_dim,
1101 rope_dim,
1102 1,
1103 torch.empty(1, head_dim, dtype=torch.float32, device=device),
1104 )
1105
1106 _assert_nan_free_cache_matches_legacy_scrub(cache, block_size)
1107
1108
1109 @pytest.mark.parametrize(
1110 ("starts", "query_start_loc", "expected"),
1111 [
1112 ([0], [0, 127], False),
1113 ([0], [0, 128], True),
1114 ([127], [0, 1], True),
1115 ([128], [0, 127], False),
1116 ([1, 255], [0, 1, 2], True),
1117 (None, [0, 1], None),
1118 ],
1119 )
1120 def test_get_c128_boundary(starts, query_start_loc, expected):
1121 query_start_loc_tensor = torch.tensor(query_start_loc)
1122 query_lens = query_start_loc_tensor[1:] - query_start_loc_tensor[:-1]
1123 metadata = SimpleNamespace(
1124 seq_lens_cpu_upper_bound=(
1125 None if starts is None else torch.tensor(starts) + query_lens
1126 ),
1127 query_start_loc_cpu=query_start_loc_tensor,
1128 )
1129 assert _get_c128_boundary(metadata) is expected
1130
1131
1132 # ── Test A: DeepseekV4 Attention path ──────────────────────────────────────────────
1133
1134
1135 @pytest.mark.parametrize("num_tokens", [1, 4, 8, 17])
1136 @pytest.mark.parametrize("block_size", [16, 64])
1137 def test_deepseek_v4_attention_quant_cache_roundtrip(num_tokens: int, block_size: int):
1138 """compressed_kv → quantize_and_insert_k_cache → dequantize_and_gather_k_cache
1139 → compare against original."""
1140 HEAD_DIM = 512
1141 NOPE_DIM = 448
1142 HEAD_BYTES = 584 # 448 fp8 + 128 bf16 + 8 uint8 scale
1143 FP8_MAX = 448.0
1144 QUANT_BLOCK = 64
1145
1146 num_blocks = (num_tokens + block_size - 1) // block_size + 1
1147 device = "cuda"
1148
1149 # Random compressed_kv (simulates compressor output)
1150 compressed_kv = torch.randn(
1151 num_tokens, HEAD_DIM, dtype=torch.bfloat16, device=device
1152 )
1153
1154 # ── Quant + insert ──────────────────────────────────────────────────
1155 k_cache = torch.zeros(
1156 num_blocks, block_size, HEAD_BYTES, dtype=torch.uint8, device=device
1157 )
1158 k_cache_2d = k_cache.view(num_blocks, -1)
1159
1160 # Sequential slot mapping: token i → slot i
1161 slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
1162
1163 quantize_and_insert_k_cache(
1164 compressed_kv, k_cache_2d, slot_mapping, block_size=block_size
1165 )
1166
1167 # ── Gather + dequant ────────────────────────────────────────────────
1168 num_reqs = 1
1169 max_blocks_per_seq = num_blocks
1170 out = torch.zeros(
1171 num_reqs, num_tokens, HEAD_DIM, dtype=torch.bfloat16, device=device
1172 )
1173 seq_lens = torch.tensor([num_tokens], dtype=torch.int32, device=device)
1174 # block_table: request 0 uses physical blocks 0, 1, ...
1175 block_table = torch.arange(
1176 max_blocks_per_seq, dtype=torch.int32, device=device
1177 ).unsqueeze(0)
1178
1179 dequantize_and_gather_k_cache(
1180 out, k_cache, seq_lens, None, block_table, block_size, offset=0
1181 )
1182
1183 recovered = out[0, :num_tokens]
1184
1185 # ── NoPE portion (first 448): FP8 quantized, expect UE8M0 error ──
1186 nope_orig = compressed_kv[:, :NOPE_DIM].float()
1187 nope_recv = recovered[:, :NOPE_DIM].float()
1188 nope_diff = (nope_recv - nope_orig).abs()
1189
1190 # Per-token check: FP8 e4m3 (3-bit mantissa) worst-case error is
1191 # half-ULP at the largest representable value. At y ≈ 448 (max),
1192 # ULP = 2^(8-3) = 32, so error ≤ 16 * scale.
1193 for t in range(num_tokens):
1194 _, scales = _ue8m0_reference(
1195 compressed_kv[t, :NOPE_DIM].float(), QUANT_BLOCK, FP8_MAX
1196 )
1197 max_allowed = 16.0 * scales.max().item()
1198 token_diff = nope_diff[t].max().item()
1199 assert token_diff <= max_allowed, (
1200 f"Token {t} nope diff {token_diff} exceeds max_allowed "
1201 f"{max_allowed} (scale={scales.max().item()})"
1202 )
1203
1204 # ── RoPE portion (last 64): stored as bf16, should be exact ─────
1205 rope_diff = (recovered[:, NOPE_DIM:] - compressed_kv[:, NOPE_DIM:]).abs()
1206 assert rope_diff.max().item() == 0.0, (
1207 f"RoPE portion should be exact but got max diff {rope_diff.max().item()}"
1208 )
1209
1210
1211 # ── Test B: Fused dequant+gather K cache ────────────────────────────────────
1212
1213
1214 def _dequantize_and_gather_k_cache_reference(
1215 out: torch.Tensor,
1216 k_cache: torch.Tensor,
1217 seq_lens: torch.Tensor,
1218 gather_lens: torch.Tensor | None,
1219 block_table: torch.Tensor,
1220 block_size: int,
1221 offset: int,
1222 ) -> None:
1223 fp8_dim = 448
1224 bf16_dim = 64
1225 scale_dim = 8
1226 quant_block = 64
1227 token_data_size = fp8_dim + bf16_dim * 2
1228
1229 for req_id in range(seq_lens.shape[0]):
1230 seq_len = seq_lens[req_id].item()
1231 gather_len = gather_lens[req_id].item() if gather_lens is not None else seq_len
1232 start_pos = seq_len - gather_len
1233
1234 for i in range(gather_len):
1235 pos = start_pos + i
1236 pos_in_block = pos % block_size
1237 block_idx = block_table[req_id, pos // block_size].item()
1238 cache_block = k_cache[block_idx].view(-1)
1239
1240 token_data_start = pos_in_block * token_data_size
1241 fp8_bytes = cache_block[token_data_start : token_data_start + fp8_dim]
1242 fp8_vals = fp8_bytes.view(torch.float8_e4m3fn).float()
1243
1244 scale_start = block_size * token_data_size + pos_in_block * scale_dim
1245 encoded_scales = cache_block[scale_start : scale_start + scale_dim]
1246 scales = torch.exp2(encoded_scales[:7].float() - 127.0)
1247 dequant = fp8_vals * scales.repeat_interleave(quant_block)
1248
1249 bf16_start = token_data_start + fp8_dim
1250 bf16_bytes = cache_block[bf16_start : bf16_start + bf16_dim * 2]
1251 bf16_tail = bf16_bytes.view(torch.bfloat16)
1252
1253 out[req_id, offset + i, :fp8_dim] = dequant
1254 out[req_id, offset + i, fp8_dim:] = bf16_tail
1255
1256
1257 @pytest.mark.parametrize(
1258 ("seq_lens_host", "gather_lens_host", "offset"),
1259 [
1260 ([9, 23, 7], None, 0),
1261 ([19, 8, 257], [6, 8, 129], 5),
1262 ],
1263 )
1264 def test_dequantize_and_gather_k_cache(
1265 seq_lens_host: list[int],
1266 gather_lens_host: list[int] | None,
1267 offset: int,
1268 ):
1269 block_size = 64
1270 head_dim = 512
1271 nope_dim = 448
1272 scale_dim = 8
1273 head_bytes = nope_dim + (head_dim - nope_dim) * 2 + scale_dim
1274 device = "cuda"
1275 num_reqs = len(seq_lens_host)
1276 num_tokens = sum(seq_lens_host)
1277 max_gather_len = max(gather_lens_host or seq_lens_host)
1278 max_blocks_per_seq = math.ceil(max(seq_lens_host) / block_size)
1279 num_blocks = sum(math.ceil(seq_len / block_size) for seq_len in seq_lens_host)
1280
1281 compressed_kv = torch.randn(
1282 num_tokens, head_dim, dtype=torch.bfloat16, device=device
1283 )
1284
1285 # Randomize physical pages so the test covers block-table translation.
1286 # Keep padded block-table entries invalid to catch accidental reads.
1287 physical_blocks = torch.randperm(num_blocks, device=device)
1288 block_table = torch.full(
1289 (num_reqs, max_blocks_per_seq), int(-1e6), dtype=torch.int32, device=device
1290 )
1291 start = 0
1292 for req_id, seq_len in enumerate(seq_lens_host):
1293 num_req_blocks = math.ceil(seq_len / block_size)
1294 req_blocks = physical_blocks[start : start + num_req_blocks]
1295 block_table[req_id, :num_req_blocks] = req_blocks
1296 start += num_req_blocks
1297
1298 # Build slot_mapping for quantize_and_insert_k_cache.
1299 slot_mapping = torch.empty(num_tokens, dtype=torch.int64, device=device)
1300 start = 0
1301 for req_id, seq_len in enumerate(seq_lens_host):
1302 logical_pos = torch.arange(seq_len, dtype=torch.int64, device=device)
1303 block_idx = block_table[req_id, logical_pos // block_size].to(torch.int64)
1304 token_slots = block_idx * block_size + logical_pos % block_size
1305 slot_mapping[start : start + seq_len] = token_slots
1306 start += seq_len
1307
1308 # Insert compressed K into the paged cache layout used by the gather op.
1309 k_cache = torch.empty(
1310 num_blocks, block_size, head_bytes, dtype=torch.uint8, device=device
1311 )
1312 k_cache_2d = k_cache.view(num_blocks, -1)
1313 quantize_and_insert_k_cache(compressed_kv, k_cache_2d, slot_mapping, block_size)
1314
1315 out_shape = (num_reqs, offset + max_gather_len + 3, head_dim)
1316 ref_out = torch.empty(out_shape, dtype=torch.bfloat16, device=device)
1317 actual_out = torch.empty_like(ref_out)
1318 seq_lens = torch.tensor(seq_lens_host, dtype=torch.int32, device=device)
1319 gather_lens = (
1320 torch.tensor(gather_lens_host, dtype=torch.int32, device=device)
1321 if gather_lens_host is not None
1322 else None
1323 )
1324
1325 # Compare production gather against a PyTorch reference for valid output rows.
1326 _dequantize_and_gather_k_cache_reference(
1327 ref_out, k_cache, seq_lens, gather_lens, block_table, block_size, offset
1328 )
1329 dequantize_and_gather_k_cache(
1330 actual_out, k_cache, seq_lens, gather_lens, block_table, block_size, offset
1331 )
1332 torch.accelerator.synchronize()
1333
1334 # only check non-padded content
1335 for req_id, seq_len in enumerate(seq_lens_host):
1336 gather_len = (
1337 gather_lens_host[req_id] if gather_lens_host is not None else seq_len
1338 )
1339 actual = actual_out[req_id, offset : offset + gather_len]
1340 expected = ref_out[req_id, offset : offset + gather_len]
1341 torch.testing.assert_close(actual, expected, rtol=0, atol=0)
1342
1343
1344 # ── Test C: Indexer path ────────────────────────────────────────────────────
1345
1346
1347 @pytest.mark.parametrize("num_tokens", [1, 4, 8, 17])
1348 @pytest.mark.parametrize("block_size", [16, 64])
1349 def test_indexer_quant_cache_roundtrip(num_tokens: int, block_size: int):
1350 """K → indexer_k_quant_and_cache → cp_gather_indexer_k_quant_cache
1351 → manual dequant → compare against original."""
1352 HEAD_DIM = 128
1353 QUANT_BLOCK_SIZE = 128
1354 # cache_stride = head_dim + (head_dim * 4 / quant_block_size) = 128 + 4 = 132
1355 CACHE_STRIDE = HEAD_DIM + HEAD_DIM * 4 // QUANT_BLOCK_SIZE
1356
1357 num_blocks = (num_tokens + block_size - 1) // block_size + 1
1358 device = "cuda"
1359
1360 # Random K (simulates compressor output for indexer)
1361 k = torch.randn(num_tokens, HEAD_DIM, dtype=torch.bfloat16, device=device)
1362
1363 # ── Quant + insert ──────────────────────────────────────────────────
1364 kv_cache = torch.zeros(
1365 num_blocks, block_size, CACHE_STRIDE, dtype=torch.uint8, device=device
1366 )
1367 slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
1368
1369 ops.indexer_k_quant_and_cache(k, kv_cache, slot_mapping, QUANT_BLOCK_SIZE, "ue8m0")
1370
1371 # ── Gather ──────────────────────────────────────────────────────────
1372 max_blocks_per_seq = num_blocks
1373 block_table = torch.arange(
1374 max_blocks_per_seq, dtype=torch.int32, device=device
1375 ).unsqueeze(0)
1376 cu_seq_lens = torch.tensor([0, num_tokens], dtype=torch.int32, device=device)
1377
1378 # dst_k: [total_seq_len, head_dim] as uint8 (raw FP8 bytes)
1379 dst_k = torch.zeros(num_tokens, HEAD_DIM, dtype=torch.uint8, device=device)
1380 # dst_scale: [total_seq_len, head_dim/quant_block*4] as uint8 (raw float32 bytes)
1381 num_scale_bytes = HEAD_DIM * 4 // QUANT_BLOCK_SIZE # 4
1382 dst_scale = torch.zeros(
1383 num_tokens, num_scale_bytes, dtype=torch.uint8, device=device
1384 )
1385
1386 ops.cp_gather_indexer_k_quant_cache(
1387 kv_cache, dst_k, dst_scale, block_table, cu_seq_lens
1388 )
1389
1390 # ── Manual dequant ──────────────────────────────────────────────────
1391 k_fp8 = dst_k.view(torch.float8_e4m3fn).float() # [num_tokens, 128]
1392 scale = dst_scale.view(torch.float32) # [num_tokens, 1]
1393 k_recovered = k_fp8 * scale # [num_tokens, 128]
1394
1395 # ── Compare ─────────────────────────────────────────────────────────
1396 diff = (k_recovered - k.float()).abs()
1397 k_abs = k.float().abs()
1398
1399 for t in range(num_tokens):
1400 amax = k_abs[t].max().clamp(min=1e-4).item()
1401 # UE8M0: scale = 2^ceil(log2(amax / 448))
1402 exponent = math.ceil(math.log2(amax / 448.0))
1403 ue8m0_scale = 2.0**exponent
1404 # FP8 e4m3 (3-bit mantissa): worst-case error = 16 * scale
1405 max_allowed = 16.0 * ue8m0_scale
1406 token_diff = diff[t].max().item()
1407 assert token_diff <= max_allowed, (
1408 f"Token {t} diff {token_diff} exceeds max_allowed "
1409 f"{max_allowed} (scale={ue8m0_scale})"
1410 )
1411
1412
1413 def test_indexer_gather_accepts_upper_bound_output():
1414 """Gather only exact cu_seq_lens even when dst is over-allocated."""
1415 head_dim = 128
1416 quant_block_size = 128
1417 cache_stride = head_dim + head_dim * 4 // quant_block_size
1418 valid_tokens = 9
1419 upper_bound_tokens = 13
1420 block_size = 16
1421 num_seqs = 3
1422 num_blocks = num_seqs
1423 sentinel = 123
1424 device = "cuda"
1425
1426 k = torch.randn(valid_tokens, head_dim, dtype=torch.bfloat16, device=device)
1427 kv_cache = torch.zeros(
1428 num_blocks, block_size, cache_stride, dtype=torch.uint8, device=device
1429 )
1430 slot_mapping = torch.tensor(
1431 [0, 1, 2, 16, 17, 18, 32, 33, 34], dtype=torch.int64, device=device
1432 )
1433 ops.indexer_k_quant_and_cache(k, kv_cache, slot_mapping, quant_block_size, "ue8m0")
1434
1435 block_table = torch.arange(num_blocks, dtype=torch.int32, device=device).unsqueeze(
1436 1
1437 )
1438 cu_seq_lens = torch.tensor([0, 3, 6, 9], dtype=torch.int32, device=device)
1439 dst_k = torch.full(
1440 (upper_bound_tokens, head_dim), sentinel, dtype=torch.uint8, device=device
1441 )
1442 num_scale_bytes = head_dim * 4 // quant_block_size
1443 dst_scale = torch.full(
1444 (upper_bound_tokens, num_scale_bytes),
1445 sentinel,
1446 dtype=torch.uint8,
1447 device=device,
1448 )
1449
1450 ops.cp_gather_indexer_k_quant_cache(
1451 kv_cache, dst_k, dst_scale, block_table, cu_seq_lens
1452 )
1453
1454 if current_platform.is_rocm():
1455 triton_kv_cache = torch.zeros_like(kv_cache)
1456 indexer_k_quant_and_cache_triton(
1457 k,
1458 triton_kv_cache,
1459 slot_mapping,
1460 quant_block_size,
1461 "ue8m0",
1462 )
1463 triton_dst_k = torch.full_like(dst_k, sentinel)
1464 triton_dst_scale = torch.full_like(dst_scale, sentinel)
1465 token_to_seq = torch.cat(
1466 (
1467 torch.repeat_interleave(
1468 torch.arange(num_seqs, dtype=torch.int32, device=device), 3
1469 ),
1470 torch.full(
1471 (upper_bound_tokens - valid_tokens,),
1472 -1,
1473 dtype=torch.int32,
1474 device=device,
1475 ),
1476 )
1477 )
1478 cp_gather_indexer_k_quant_cache_triton(
1479 triton_kv_cache,
1480 triton_dst_k.view(current_platform.fp8_dtype()),
1481 triton_dst_scale,
1482 block_table,
1483 cu_seq_lens,
1484 token_to_seq,
1485 )
1486 torch.accelerator.synchronize()
1487
1488 if current_platform.is_rocm():
1489 triton_recovered = triton_dst_k[:valid_tokens].view(
1490 current_platform.fp8_dtype()
1491 ).float() * triton_dst_scale[:valid_tokens].view(torch.float32)
1492 triton_error = (triton_recovered - k.float()).abs().amax(dim=1)
1493 max_triton_error = (
1494 16.0 * triton_dst_scale[:valid_tokens].view(torch.float32).flatten()
1495 )
1496 assert torch.all(triton_error <= max_triton_error)
1497 assert torch.all(triton_dst_k[valid_tokens:] == sentinel)
1498 assert torch.all(triton_dst_scale[valid_tokens:] == sentinel)
1499 k_recovered = dst_k[:valid_tokens].view(torch.float8_e4m3fn).float() * dst_scale[
1500 :valid_tokens
1501 ].view(torch.float32)
1502 diff = (k_recovered - k.float()).abs()
1503 max_allowed = (16.0 * dst_scale[:valid_tokens].view(torch.float32).max()).item()
1504 assert diff.max().item() <= max_allowed
1505 assert torch.all(dst_k[valid_tokens:] == sentinel)
1506 assert torch.all(dst_scale[valid_tokens:] == sentinel)
1507
1508
1509 # ── Test D: DeepseekV4 attention with values at different magnitudes ───────────
1510
1511
1512 def test_deepseek_v4_quant_magnitude_range():
1513 """Test that quantization handles a range of magnitudes correctly."""
1514 HEAD_DIM = 512
1515 NOPE_DIM = 448
1516 HEAD_BYTES = 584
1517 block_size = 16
1518 num_tokens = 4
1519 num_blocks = 2
1520 device = "cuda"
1521
1522 # Create inputs with varying magnitudes: small, medium, large
1523 compressed_kv = torch.zeros(
1524 num_tokens, HEAD_DIM, dtype=torch.bfloat16, device=device
1525 )
1526 compressed_kv[0] = 0.001 # very small
1527 compressed_kv[1] = 1.0 # unit scale
1528 compressed_kv[2] = 100.0 # large
1529 compressed_kv[3] = torch.randn(HEAD_DIM, dtype=torch.bfloat16, device=device)
1530
1531 k_cache = torch.zeros(
1532 num_blocks, block_size, HEAD_BYTES, dtype=torch.uint8, device=device
1533 )
1534 slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
1535
1536 quantize_and_insert_k_cache(
1537 compressed_kv, k_cache.view(num_blocks, -1), slot_mapping, block_size
1538 )
1539
1540 out = torch.zeros(1, num_tokens, HEAD_DIM, dtype=torch.bfloat16, device=device)
1541 seq_lens = torch.tensor([num_tokens], dtype=torch.int32, device=device)
1542 block_table = torch.arange(num_blocks, dtype=torch.int32, device=device).unsqueeze(
1543 0
1544 )
1545
1546 dequantize_and_gather_k_cache(
1547 out, k_cache, seq_lens, None, block_table, block_size, offset=0
1548 )
1549
1550 recovered = out[0, :num_tokens]
1551
1552 # RoPE portion must be exact
1553 rope_diff = (recovered[:, NOPE_DIM:] - compressed_kv[:, NOPE_DIM:]).abs().max()
1554 assert rope_diff.item() == 0.0, f"RoPE diff {rope_diff.item()}"
1555
1556 # NoPE: relative error should be reasonable
1557 for t in range(num_tokens):
1558 orig = compressed_kv[t, :NOPE_DIM].float()
1559 recv = recovered[t, :NOPE_DIM].float()
1560 abs_diff = (recv - orig).abs().max().item()
1561 magnitude = orig.abs().max().item()
1562 if magnitude > 0.01:
1563 rel_err = abs_diff / magnitude
1564 assert rel_err < 0.15, (
1565 f"Token {t}: rel_err={rel_err:.4f}, abs_diff={abs_diff:.6f}, "
1566 f"magnitude={magnitude:.4f}"
1567 )
1568
1569
1570 # ── Test E: Indexer fused K-cache insert (Triton kernels) ────────────────────
1571 #
1572 # Both kernels share the same Triton signature; use_fp4 selects between them.
1573 # Full pipeline: state-cache gather → softmax-weighted compress → RMSNorm →
1574 # GPT-J RoPE → quant (MXFP4 or FP8) → paged cache insert.
1575
1576
1577 def _reference_kv_compress_norm_rope(
1578 state_cache: torch.Tensor,
1579 block_table: torch.Tensor,
1580 positions: torch.Tensor,
1581 rms_weight: torch.Tensor,
1582 cos_sin_cache: torch.Tensor,
1583 compress_ratio: int = 1,
1584 overlap: int = 0,
1585 use_fp4: bool = False,
1586 rms_eps: float = 1e-6,
1587 fp8_max: float = 448.0,
1588 return_full_cache: bool = False,
1589 ):
1590 """Compress → RMSNorm → GPT-J RoPE → quantize.
1591
1592 Gathers (1+overlap)*compress_ratio state entries per output token, applies
1593 per-element softmax over the scores, and computes the weighted kv sum.
1594 Returns (quantized_values, scale) matching the kernel's output layout.
1595 """
1596 device = state_cache.device
1597 head_dim = rms_weight.shape[0]
1598 rope_dim = cos_sin_cache.shape[-1]
1599 state_block_size = state_cache.shape[1]
1600 state_width = state_cache.shape[-1] // 2
1601 nope_dim = head_dim - rope_dim
1602 total = (1 + overlap) * compress_ratio
1603 results = []
1604 for pos in positions.tolist():
1605 src = torch.arange(pos - total + 1, pos + 1, dtype=torch.int64, device=device)
1606 valid = src >= 0
1607 idx = src.clamp(min=0)
1608 pages = block_table[0, idx // state_block_size]
1609 offsets = idx % state_block_size
1610 raw = state_cache[pages, offsets].float() # [total, state_dim]
1611
1612 # Group 0 (tokens 0..cr-1): kv[:H], score[SW:SW+H]
1613 # Group 1 (tokens cr..2cr-1): kv[H:2H], score[SW+H:SW+2H]
1614 if overlap:
1615 sw = state_width
1616 g0_kv = raw[:compress_ratio, :head_dim]
1617 g1_kv = raw[compress_ratio:, head_dim : 2 * head_dim]
1618 g0_scores = raw[:compress_ratio, sw : sw + head_dim]
1619 g1_scores = raw[compress_ratio:, sw + head_dim : sw + 2 * head_dim]
1620 kv = torch.cat([g0_kv, g1_kv])
1621 scores = torch.cat([g0_scores, g1_scores])
1622 else:
1623 kv = raw[:, :head_dim]
1624 scores = raw[:, state_width : state_width + head_dim]
1625
1626 scores[~valid] = float("-inf")
1627 kv[~valid] = 0.0
1628 weights = torch.softmax(scores, dim=0)
1629 compressed = (kv * weights).sum(dim=0) # [H]
1630 var = (compressed * compressed).mean()
1631 normed = compressed * torch.rsqrt(var + rms_eps) * rms_weight.float()
1632 compressed_pos = (pos // compress_ratio) * compress_ratio
1633 cos, sin = cos_sin_cache[compressed_pos].float().chunk(2)
1634 nope, rope = normed.split([nope_dim, rope_dim])
1635 rope = torch.stack(
1636 [rope[0::2] * cos - rope[1::2] * sin, rope[1::2] * cos + rope[0::2] * sin],
1637 dim=-1,
1638 ).reshape(rope_dim)
1639 results.append(torch.cat([nope, rope]).to(state_cache.dtype))
1640 result = torch.stack(results)
1641
1642 if return_full_cache:
1643 # Contiguous 512-wide bf16 row (nope unrotated + rope rotated), matching
1644 # the FlashInfer full-cache layout before any per-tensor fp8 quant. The
1645 # kernel rounds the fp32 result to bf16 once at the store.
1646 return result.to(torch.bfloat16)
1647
1648 if use_fp4:
1649 return quantize_to_mxfp4(result)
1650 else:
1651 pairs = [
1652 _ue8m0_reference(result[t], head_dim, fp8_max) for t in range(len(result))
1653 ]
1654 quants, scales = zip(*pairs)
1655 return torch.stack(quants), torch.cat(scales)
1656
1657
1658 @pytest.mark.parametrize("num_tokens", [1, 7, 32])
1659 @pytest.mark.parametrize("kv_block_size", [16, 32])
1660 @pytest.mark.parametrize(
1661 "use_fp4",
1662 [
1663 False,
1664 pytest.param(
1665 True,
1666 marks=pytest.mark.skipif(
1667 not (
1668 current_platform.is_cuda()
1669 and current_platform.is_device_capability_family(100)
1670 ),
1671 reason="MXFP4 indexer cache requires an SM100-family GPU",
1672 ),
1673 ),
1674 ],
1675 )
1676 def test_fused_kv_insert_indexer(num_tokens: int, kv_block_size: int, use_fp4: bool):
1677 """Fused K compress+norm+rope+quant+insert for the indexer KV cache."""
1678 HEAD_DIM = 128
1679 ROPE_DIM = 64
1680 BLOCK_SIZE = 16
1681 RMS_EPS = 1e-6
1682 FP8_MAX = 448.0
1683
1684 device = "cuda"
1685 torch.manual_seed(42)
1686 compress_ratio = 4
1687
1688 if use_fp4:
1689 TOKEN_STRIDE = HEAD_DIM // 2 # packed nibbles: 64 bytes
1690 SCALE_DIM = HEAD_DIM // 32 # ue8m0 bytes: 4
1691 QUANT_BLOCK = 32
1692 kernel = _fused_kv_compress_norm_rope_insert_indexer_mxfp4_attn
1693 else:
1694 TOKEN_STRIDE = HEAD_DIM # FP8 bytes: 128
1695 SCALE_DIM = 4 # 1 float32: 4 bytes
1696 QUANT_BLOCK = HEAD_DIM
1697 kernel = _fused_kv_compress_norm_rope_insert_indexer_attn
1698
1699 # overlap=1 whenever compress_ratio==4, matching DeepseekCompressor logic.
1700 overlap = 1 if compress_ratio == 4 else 0
1701 coff = 1 + overlap # multiplier for state_dim per entry
1702
1703 num_pages = (compress_ratio * num_tokens - 1) // BLOCK_SIZE + 2
1704 state_cache = torch.randn(
1705 num_pages,
1706 BLOCK_SIZE,
1707 2 * coff * HEAD_DIM, # kv_state + score_state, each coff*HEAD_DIM wide
1708 dtype=torch.bfloat16,
1709 device=device,
1710 )
1711 block_table = torch.arange(num_pages, dtype=torch.int32, device=device).unsqueeze(0)
1712 token_to_req = torch.zeros(num_tokens, dtype=torch.int32, device=device)
1713 slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
1714 positions = torch.arange(
1715 compress_ratio - 1,
1716 compress_ratio * num_tokens,
1717 compress_ratio,
1718 dtype=torch.int64,
1719 device=device,
1720 )
1721 rms_weight = torch.randn(HEAD_DIM, dtype=torch.bfloat16, device=device)
1722 cos_sin_cache = torch.randn(compress_ratio * num_tokens, ROPE_DIM, device=device)
1723
1724 kv_n_blocks = (num_tokens + kv_block_size - 1) // kv_block_size + 1
1725 kv_cache = torch.zeros(
1726 kv_n_blocks,
1727 kv_block_size * (TOKEN_STRIDE + SCALE_DIM),
1728 dtype=torch.uint8,
1729 device=device,
1730 )
1731
1732 kernel[(num_tokens,)](
1733 state_cache,
1734 state_cache.stride(0),
1735 state_cache.stride(1),
1736 token_to_req,
1737 positions,
1738 slot_mapping,
1739 block_table,
1740 block_table.stride(0),
1741 BLOCK_SIZE,
1742 rms_weight,
1743 RMS_EPS,
1744 cos_sin_cache,
1745 cos_sin_cache.stride(0),
1746 kv_cache,
1747 slot_mapping,
1748 kv_block_size,
1749 HEAD_SIZE=HEAD_DIM,
1750 TRITON_BLOCK_SIZE=HEAD_DIM,
1751 STATE_WIDTH=coff * HEAD_DIM,
1752 COMPRESS_RATIO=compress_ratio,
1753 OVERLAP=overlap,
1754 ROPE_HEAD_DIM=ROPE_DIM,
1755 FP8_MAX=FP8_MAX,
1756 QUANT_BLOCK=QUANT_BLOCK,
1757 TOKEN_STRIDE=TOKEN_STRIDE,
1758 SCALE_DIM=SCALE_DIM,
1759 KV_BLOCK_STRIDE=kv_cache.stride(0),
1760 num_warps=1,
1761 )
1762
1763 k_quant, scale = _reference_kv_compress_norm_rope(
1764 state_cache,
1765 block_table,
1766 positions,
1767 rms_weight,
1768 cos_sin_cache,
1769 compress_ratio,
1770 overlap,
1771 use_fp4,
1772 rms_eps=RMS_EPS,
1773 fp8_max=FP8_MAX,
1774 )
1775
1776 if use_fp4:
1777 for i in range(num_tokens):
1778 blk, pos = i // kv_block_size, i % kv_block_size
1779 val_off = pos * TOKEN_STRIDE
1780 fp4_actual = kv_cache[blk, val_off : val_off + TOKEN_STRIDE]
1781 assert torch.equal(k_quant[i], fp4_actual), (
1782 f"token {i}: packed nibbles differ, "
1783 f"{(k_quant[i] != fp4_actual).sum()} "
1784 f"/ {TOKEN_STRIDE}"
1785 )
1786
1787 scale_off = kv_block_size * TOKEN_STRIDE + pos * SCALE_DIM
1788 scale_actual = kv_cache[blk, scale_off : scale_off + SCALE_DIM]
1789 assert torch.equal(scale_actual, scale[i]), (
1790 f"token {i}: ue8m0 {scale_actual.tolist()} != {scale[i].tolist()}"
1791 )
1792
1793 else:
1794 k_quant = k_quant.view(torch.uint8)
1795 for i in range(num_tokens):
1796 blk, pos = i // kv_block_size, i % kv_block_size
1797 val_off = pos * TOKEN_STRIDE
1798 assert torch.equal(
1799 k_quant[i], kv_cache[blk, val_off : val_off + TOKEN_STRIDE]
1800 ), f"token {i}: FP8 bytes differ"
1801
1802 scale_off = kv_block_size * TOKEN_STRIDE + pos * SCALE_DIM
1803 actual_scale = kv_cache[blk, scale_off : scale_off + SCALE_DIM].view(
1804 torch.float32
1805 )
1806 assert torch.equal(actual_scale, scale[i : i + 1]), (
1807 f"token {i}: scale {actual_scale.item()} != {scale[i].item()}"
1808 )
1809
1810
1811 @pytest.mark.parametrize("compress_ratio", [4, 128])
1812 @pytest.mark.parametrize("store_fp8", [False, True])
1813 def test_cutedsl_full_cache_store(compress_ratio: int, store_fp8: bool):
1814 """CuTeDSL compressor full-cache (FlashInfer) store parity for head=512.
1815
1816 Exercises the contiguous bf16 / per-tensor fp8 store branch of both the C4
1817 fused kernel and the C128 split kernel against the PyTorch reference.
1818 """
1819 cutedsl = pytest.importorskip("cutlass") # noqa: F841
1820 from vllm.models.deepseek_v4.nvidia.ops.sparse_attn_compress_cutedsl import (
1821 fused_kv_compress_norm_rope_insert_sparse_attn_cutedsl,
1822 split_kv_compress_norm_rope_insert_sparse_attn_cutedsl,
1823 )
1824
1825 HEAD_DIM = 512
1826 ROPE_DIM = 64
1827 RMS_EPS = 1e-6
1828 FP8_MAX = 448.0
1829 # C128 compress (Block8 kernel) requires state-cache block_size=8; C4 uses 16.
1830 BLOCK_SIZE = 8 if compress_ratio == 128 else 16
1831 KV_BLOCK_SIZE = 64
1832 device = "cuda"
1833 torch.manual_seed(7)
1834
1835 overlap = 1 if compress_ratio == 4 else 0
1836 coff = 1 + overlap
1837 num_tokens = 8
1838
1839 num_pages = (compress_ratio * num_tokens - 1) // BLOCK_SIZE + 2
1840 # The production CompressorStateCache is fp32.
1841 state_cache = torch.randn(
1842 num_pages, BLOCK_SIZE, 2 * coff * HEAD_DIM, dtype=torch.float32, device=device
1843 )
1844 block_table = torch.arange(num_pages, dtype=torch.int32, device=device).unsqueeze(0)
1845 token_to_req = torch.zeros(num_tokens, dtype=torch.int32, device=device)
1846 slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
1847 positions = torch.arange(
1848 compress_ratio - 1,
1849 compress_ratio * num_tokens,
1850 compress_ratio,
1851 dtype=torch.int64,
1852 device=device,
1853 )
1854 rms_weight = torch.randn(HEAD_DIM, dtype=torch.bfloat16, device=device)
1855 cos_sin_cache = torch.randn(
1856 compress_ratio * num_tokens, ROPE_DIM, dtype=torch.float32, device=device
1857 )
1858
1859 dtype = torch.float8_e4m3fn if store_fp8 else torch.bfloat16
1860 kv_n_blocks = (num_tokens + KV_BLOCK_SIZE - 1) // KV_BLOCK_SIZE + 1
1861 k_cache = torch.zeros(
1862 kv_n_blocks, KV_BLOCK_SIZE, HEAD_DIM, dtype=dtype, device=device
1863 )
1864 fp8_scale = torch.tensor(
1865 [0.5 if store_fp8 else 1.0], dtype=torch.float32, device=device
1866 )
1867
1868 if compress_ratio == 4:
1869 fused_kv_compress_norm_rope_insert_sparse_attn_cutedsl(
1870 state_cache,
1871 token_to_req,
1872 positions,
1873 slot_mapping,
1874 block_table,
1875 BLOCK_SIZE,
1876 rms_weight,
1877 RMS_EPS,
1878 cos_sin_cache,
1879 k_cache,
1880 slot_mapping,
1881 KV_BLOCK_SIZE,
1882 k_cache.stride(0),
1883 head_size=HEAD_DIM,
1884 state_width=coff * HEAD_DIM,
1885 rope_head_dim=ROPE_DIM,
1886 fp8_max=FP8_MAX,
1887 quant_block=64,
1888 token_stride=576,
1889 scale_dim=8,
1890 compress_ratio=compress_ratio,
1891 overlap=True,
1892 store_full_kv=True,
1893 store_full_fp8=store_fp8,
1894 fp8_scale=fp8_scale,
1895 )
1896 else:
1897 compressed_kv = torch.empty(
1898 (num_tokens, HEAD_DIM), dtype=torch.float32, device=device
1899 )
1900 split_kv_compress_norm_rope_insert_sparse_attn_cutedsl(
1901 state_cache,
1902 token_to_req,
1903 positions,
1904 slot_mapping,
1905 block_table,
1906 BLOCK_SIZE,
1907 compressed_kv,
1908 rms_weight,
1909 RMS_EPS,
1910 cos_sin_cache,
1911 k_cache,
1912 slot_mapping,
1913 KV_BLOCK_SIZE,
1914 k_cache.stride(0),
1915 head_size=HEAD_DIM,
1916 state_width=coff * HEAD_DIM,
1917 rope_head_dim=ROPE_DIM,
1918 fp8_max=FP8_MAX,
1919 quant_block=64,
1920 token_stride=576,
1921 scale_dim=8,
1922 compress_ratio=compress_ratio,
1923 overlap=bool(overlap),
1924 store_full_kv=True,
1925 store_full_fp8=store_fp8,
1926 fp8_scale=fp8_scale,
1927 )
1928
1929 ref = _reference_kv_compress_norm_rope(
1930 state_cache,
1931 block_table,
1932 positions,
1933 rms_weight,
1934 cos_sin_cache,
1935 compress_ratio,
1936 overlap,
1937 rms_eps=RMS_EPS,
1938 return_full_cache=True,
1939 ) # [num_tokens, HEAD_DIM] bf16
1940
1941 actual = torch.stack(
1942 [k_cache[i // KV_BLOCK_SIZE, i % KV_BLOCK_SIZE] for i in range(num_tokens)]
1943 )
1944 if store_fp8:
1945 ref_fp8 = torch.clamp(ref.float() / fp8_scale, -FP8_MAX, FP8_MAX).to(
1946 torch.float8_e4m3fn
1947 )
1948 torch.testing.assert_close(actual.float(), ref_fp8.float(), rtol=0.0, atol=0.3)
1949 else:
1950 torch.testing.assert_close(actual.float(), ref.float(), rtol=3e-2, atol=3e-2)
1951
1952
1953 # ── Test F: DeepseekV4 Attention two-stage split compressor (Triton) ─────────
1954 #
1955 # Same full pipeline as Test E (state-cache gather -> softmax-weighted compress
1956 # -> RMSNorm -> GPT-J RoPE -> quant -> paged insert), but for the head=512
1957 # fp8_ds_mla layout via the two-stage split
1958
1959
1960 @pytest.mark.skipif(
1961 not current_platform.is_rocm(),
1962 reason="two-stage split compressor is only enabled for ROCm at the moment",
1963 )
1964 @pytest.mark.parametrize("num_tokens", [1, 4, 8, 17])
1965 @pytest.mark.parametrize("kv_block_size", [16, 64])
1966 def test_fused_kv_insert_split(num_tokens: int, kv_block_size: int):
1967 """Two-stage split compress+norm+rope+quant+insert for the head=512 KV cache."""
1968 HEAD_DIM = 512
1969 NOPE_DIM = 448
1970 ROPE_DIM = 64
1971 HEAD_BYTES = 584 # 448 fp8 + 128 bf16 + 8 uint8 scale
1972 RMS_EPS = 1e-6
1973 FP8_MAX = 448.0
1974 QUANT_BLOCK = 64
1975 TOKEN_STRIDE = 576
1976 SCALE_DIM = 8
1977 STATE_BLOCK_SIZE = 8 # CompressorStateCache block_size for cr=128
1978
1979 device = "cuda"
1980 torch.manual_seed(42)
1981 compress_ratio = 128
1982 overlap = 0 # no overlap for cr=128
1983 coff = 1 + overlap
1984
1985 num_pages = (compress_ratio * num_tokens - 1) // STATE_BLOCK_SIZE + 2
1986 state_cache = torch.randn(
1987 num_pages,
1988 STATE_BLOCK_SIZE,
1989 2 * coff * HEAD_DIM, # kv_state + score_state
1990 dtype=torch.float32,
1991 device=device,
1992 )
1993 block_table = torch.arange(num_pages, dtype=torch.int32, device=device).unsqueeze(0)
1994 token_to_req = torch.zeros(num_tokens, dtype=torch.int32, device=device)
1995 slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
1996 positions = torch.arange(
1997 compress_ratio - 1,
1998 compress_ratio * num_tokens,
1999 compress_ratio,
2000 dtype=torch.int64,
2001 device=device,
2002 )
2003 rms_weight = torch.randn(HEAD_DIM, dtype=torch.bfloat16, device=device)
2004 cos_sin_cache = torch.randn(
2005 compress_ratio * num_tokens, ROPE_DIM, dtype=torch.float32, device=device
2006 )
2007
2008 kv_n_blocks = (num_tokens + kv_block_size - 1) // kv_block_size + 1
2009 kv_cache = torch.zeros(
2010 kv_n_blocks, kv_block_size, HEAD_BYTES, dtype=torch.uint8, device=device
2011 )
2012 compress_scratch = torch.empty(
2013 num_tokens, HEAD_DIM, dtype=torch.float32, device=device
2014 )
2015
2016 _launch_two_stage_sparse_attn_compressor(
2017 state_cache,
2018 token_to_req,
2019 positions,
2020 slot_mapping,
2021 block_table,
2022 STATE_BLOCK_SIZE,
2023 coff * HEAD_DIM,
2024 compress_ratio,
2025 cos_sin_cache,
2026 kv_cache,
2027 slot_mapping,
2028 rms_weight,
2029 RMS_EPS,
2030 QUANT_BLOCK,
2031 TOKEN_STRIDE,
2032 SCALE_DIM,
2033 HEAD_DIM,
2034 ROPE_DIM,
2035 num_tokens,
2036 compress_scratch,
2037 )
2038
2039 # PyTorch reference: compress -> RMSNorm -> GPT-J RoPE (pre-quant bf16 row).
2040 ref = _reference_kv_compress_norm_rope(
2041 state_cache,
2042 block_table,
2043 positions,
2044 rms_weight,
2045 cos_sin_cache,
2046 compress_ratio,
2047 overlap,
2048 rms_eps=RMS_EPS,
2049 fp8_max=FP8_MAX,
2050 return_full_cache=True,
2051 ) # [num_tokens, HEAD_DIM] bf16
2052
2053 # Dequant + gather the fp8_ds_mla cache back to bf16 (Test B op).
2054 out = torch.zeros(1, num_tokens, HEAD_DIM, dtype=torch.bfloat16, device=device)
2055 seq_lens = torch.tensor([num_tokens], dtype=torch.int32, device=device)
2056 gather_block_table = torch.arange(
2057 kv_n_blocks, dtype=torch.int32, device=device
2058 ).unsqueeze(0)
2059 dequantize_and_gather_k_cache(
2060 out, kv_cache, seq_lens, None, gather_block_table, kv_block_size, offset=0
2061 )
2062 recovered = out[0, :num_tokens]
2063
2064 # NoPE (first 448): FP8 quantized, expect UE8M0 error (same bound as Test A).
2065 nope_diff = (recovered[:, :NOPE_DIM].float() - ref[:, :NOPE_DIM].float()).abs()
2066 for t in range(num_tokens):
2067 _, scales = _ue8m0_reference(ref[t, :NOPE_DIM].float(), QUANT_BLOCK, FP8_MAX)
2068 max_allowed = 16.0 * scales.max().item()
2069 token_diff = nope_diff[t].max().item()
2070 assert token_diff <= max_allowed, (
2071 f"Token {t} nope diff {token_diff} exceeds max_allowed "
2072 f"{max_allowed} (scale={scales.max().item()})"
2073 )
2074
2075 # RoPE (last 64): stored as bf16. The kernel recomputes the rotation, so it
2076 # is bf16-close to the reference rather than bit-exact (cf. test_cutedsl).
2077 torch.testing.assert_close(recovered[:, NOPE_DIM:], ref[:, NOPE_DIM:])
2078
2079
2080 @pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm stream coverage")
2081 def test_v41_rocm_csa2_full_pipeline():
2082 """_forward_csa2_full: one fork, then K write and q-side after the join.
2083
2084 The default chain must run first on the current stream, the compressor
2085 chain on aux 0 and the indexer weights projection on aux 1; the join must
2086 publish both cache writes before _produce_k / forward_q run.
2087 """
2088 from vllm.forward_context import ForwardContext, override_forward_context
2089 from vllm.models.deepseek_v41.amd.rocm import DeepseekV41ROCMAiterMLAAttention
2090 from vllm.models.deepseek_v41.compressor import DeepseekCompressor
2091
2092 torch.manual_seed(43)
2093 num_tokens = 19
2094 hidden_states = torch.randn(num_tokens, 1024, device="cuda")
2095 positions = torch.arange(7, 26, device="cuda")
2096 qr_kv = torch.zeros(num_tokens, 1536, device="cuda")
2097 qr = torch.zeros(num_tokens, 4, device="cuda")
2098 kv = torch.zeros(num_tokens, 512, device="cuda")
2099 q = torch.zeros(num_tokens, 512, device="cuda")
2100 latent = torch.ones(num_tokens, 512, dtype=torch.bfloat16, device="cuda")
2101 weights = torch.randn(num_tokens, 32, device="cuda")
2102 index_q = torch.full((num_tokens, 32, 128), 2.0, device="cuda")
2103 index_q_scale = torch.full((num_tokens, 32), 3.0, device="cuda")
2104 index_weights_out = torch.full((num_tokens, 32), 4.0, device="cuda")
2105 main_cache = torch.full((1, 128, 584), 165, dtype=torch.uint8, device="cuda")
2106 index_cache = torch.full((1, 128, 132), 165, dtype=torch.uint8, device="cuda")
2107
2108 order: list[str] = []
2109 streams: dict[str, torch.cuda.Stream] = {}
2110
2111 compressor = DeepseekCompressor.__new__(DeepseekCompressor)
2112 torch.nn.Module.__init__(compressor)
2113 compressor.fused_wkv_wgate = SimpleNamespace(
2114 weight=torch.randn(1024, 1024, device="cuda")
2115 )
2116
2117 def compressor_forward(kv_score, positions_):
2118 order.append("compressor")
2119 streams["compressor"] = torch.cuda.current_stream()
2120 return latent
2121
2122 def compressor_insert(latent_, positions_, rotary_emb):
2123 order.append("insert_cache")
2124 streams["insert_cache"] = torch.cuda.current_stream()
2125 main_cache.fill_(5)
2126
2127 compressor.forward = compressor_forward
2128 compressor.insert_cache = compressor_insert
2129
2130 def weights_proj(hidden_states_):
2131 order.append("weights_proj")
2132 streams["weights_proj"] = torch.cuda.current_stream()
2133 return weights, None
2134
2135 def produce_k(latent_, positions_, rotary_emb):
2136 order.append("produce_k")
2137 streams["produce_k"] = torch.cuda.current_stream()
2138 index_cache.fill_(7)
2139
2140 def forward_q(qr_, qr_scale, indexer_weights, positions_, rotary_emb):
2141 order.append("forward_q")
2142 streams["forward_q"] = torch.cuda.current_stream()
2143 return index_q, index_q_scale, index_weights_out
2144
2145 indexer = SimpleNamespace(
2146 weights_proj=weights_proj,
2147 _produce_k=produce_k,
2148 forward_q=forward_q,
2149 )
2150 rotary = SimpleNamespace(cos_sin_cache=torch.randn(32, 64, device="cuda"))
2151 aux_streams = [torch.cuda.Stream(), torch.cuda.Stream()]
2152
2153 def wq_b(qr_, qr_scale):
2154 order.append("wq_b")
2155 streams["wq_b"] = torch.cuda.current_stream()
2156 return q
2157
2158 def qnorm_insert(q_, kv_, positions_, attn_metadata):
2159 order.append("qnorm_insert")
2160 streams["qnorm_insert"] = torch.cuda.current_stream()
2161 return q_
2162
2163 attention = SimpleNamespace(
2164 compressor=compressor,
2165 indexer=indexer,
2166 aux_stream_list=aux_streams,
2167 ln_events=[torch.cuda.Event() for _ in range(4)],
2168 rotary_emb=rotary,
2169 indexer_rotary_emb=rotary,
2170 n_local_heads=1,
2171 head_dim=512,
2172 _fused_wqa_wkv_gemm=lambda hidden_states_: qr_kv,
2173 _split_qkv_and_norm=lambda qr_kv_: (qr, None, kv),
2174 _wq_b_proj=wq_b,
2175 _fused_qnorm_rope_kv_insert=qnorm_insert,
2176 )
2177
2178 context = ForwardContext({}, {}, {})
2179 with override_forward_context(context):
2180 result = DeepseekV41ROCMAiterMLAAttention._forward_csa2_full(
2181 attention, hidden_states, positions
2182 )
2183
2184 q_out, kv_out, index_q_out, index_q_scale_out, index_weights_out_out = result
2185 assert torch.equal(
2186 q_out, q.view(num_tokens, attention.n_local_heads, attention.head_dim)
2187 )
2188 assert torch.equal(kv_out, kv)
2189 assert torch.equal(index_q_out, index_q)
2190 assert torch.equal(index_q_scale_out, index_q_scale)
2191 assert torch.equal(index_weights_out_out, index_weights_out)
2192 # Join publishes the aux-0 cache insert and orders the post-join K write.
2193 assert torch.equal(main_cache, torch.full_like(main_cache, 5))
2194 assert torch.equal(index_cache, torch.full_like(index_cache, 7))
2195
2196 assert order == [
2197 "wq_b",
2198 "qnorm_insert",
2199 "compressor",
2200 "insert_cache",
2201 "weights_proj",
2202 "produce_k",
2203 "forward_q",
2204 ]
2205 current = torch.cuda.current_stream()
2206 for name in ("wq_b", "qnorm_insert", "produce_k", "forward_q"):
2207 assert streams[name] == current, name
2208 for name in ("compressor", "insert_cache"):
2209 assert streams[name] == aux_streams[0], name
2210 assert streams["weights_proj"] == aux_streams[1]
2211
2212
2213 @pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm stream coverage")
2214 def test_v41_rocm_csa2_reindex_pipeline():
2215 """_forward_csa2_reindex: serial projections, then SWA q path vs q-side."""
2216 from vllm.forward_context import ForwardContext, override_forward_context
2217 from vllm.models.deepseek_v41.amd.rocm import DeepseekV41ROCMAiterMLAAttention
2218
2219 torch.manual_seed(45)
2220 num_tokens = 19
2221 hidden_states = torch.randn(num_tokens, 1024, device="cuda")
2222 positions = torch.arange(7, 26, device="cuda")
2223 qr_kv = torch.zeros(num_tokens, 1536, device="cuda")
2224 qr = torch.zeros(num_tokens, 4, device="cuda")
2225 kv = torch.zeros(num_tokens, 512, device="cuda")
2226 q = torch.zeros(num_tokens, 512, device="cuda")
2227 indexer_weights = torch.randn(num_tokens, 32, device="cuda")
2228 index_q = torch.full((num_tokens, 32, 128), 2.0, device="cuda")
2229 index_q_scale = torch.full((num_tokens, 32), 3.0, device="cuda")
2230 index_weights_out = torch.full((num_tokens, 32), 4.0, device="cuda")
2231
2232 order: list[str] = []
2233 streams: dict[str, torch.cuda.Stream] = {}
2234
2235 def forward_q(qr_, qr_scale, indexer_weights_, positions_, rotary_emb):
2236 order.append("forward_q")
2237 streams["forward_q"] = torch.cuda.current_stream()
2238 return index_q, index_q_scale, index_weights_out
2239
2240 indexer = SimpleNamespace(forward_q=forward_q)
2241 rotary = SimpleNamespace(cos_sin_cache=torch.randn(32, 64, device="cuda"))
2242 aux0 = torch.cuda.Stream()
2243
2244 def wq_b(qr_, qr_scale):
2245 order.append("wq_b")
2246 streams["wq_b"] = torch.cuda.current_stream()
2247 return q
2248
2249 def qnorm_insert(q_, kv_, positions_, attn_metadata):
2250 order.append("qnorm_insert")
2251 streams["qnorm_insert"] = torch.cuda.current_stream()
2252 return q_
2253
2254 attention = SimpleNamespace(
2255 indexer=indexer,
2256 aux_stream_list=[aux0],
2257 ln_events=[torch.cuda.Event() for _ in range(2)],
2258 indexer_rotary_emb=rotary,
2259 n_local_heads=1,
2260 head_dim=512,
2261 _run_parallel_input_projections=lambda hidden_states_: (
2262 qr_kv,
2263 None,
2264 indexer_weights,
2265 ),
2266 _split_qkv_and_norm=lambda qr_kv_: (qr, None, kv),
2267 _wq_b_proj=wq_b,
2268 _fused_qnorm_rope_kv_insert=qnorm_insert,
2269 )
2270
2271 context = ForwardContext({}, {}, {})
2272 with override_forward_context(context):
2273 result = DeepseekV41ROCMAiterMLAAttention._forward_csa2_reindex(
2274 attention, hidden_states, positions
2275 )
2276
2277 q_out, kv_out, index_q_out, index_q_scale_out, index_weights_out_out = result
2278 assert torch.equal(
2279 q_out, q.view(num_tokens, attention.n_local_heads, attention.head_dim)
2280 )
2281 assert torch.equal(kv_out, kv)
2282 assert torch.equal(index_q_out, index_q)
2283 assert torch.equal(index_q_scale_out, index_q_scale)
2284 assert torch.equal(index_weights_out_out, index_weights_out)
2285
2286 assert order == ["wq_b", "qnorm_insert", "forward_q"]
2287 current = torch.cuda.current_stream()
2288 for name in ("wq_b", "qnorm_insert"):
2289 assert streams[name] == current, name
2290 assert streams["forward_q"] == aux0
2291
2292
2293 @pytest.mark.parametrize("quant_tuple", [False, True])
2294 def test_v41_indexer_forward_q(quant_tuple):
2295 """forward_q runs wq_b then the fused RoPE/quant and unpacks both shapes."""
2296 from unittest.mock import patch
2297
2298 from vllm.models.deepseek_v41.attention import DeepseekV4Indexer
2299
2300 num_tokens, n_head, head_dim = 5, 32, 128
2301 qr = torch.randn(num_tokens, 1280)
2302 q = torch.randn(num_tokens, n_head * head_dim)
2303 positions = torch.arange(num_tokens)
2304 indexer_weights = torch.randn(num_tokens, n_head)
2305 rotary = SimpleNamespace(cos_sin_cache=torch.randn(32, 64))
2306 fake = SimpleNamespace(
2307 n_head=n_head,
2308 head_dim=head_dim,
2309 softmax_scale=head_dim**-0.5,
2310 use_fp4_kv=False,
2311 indexer_weights_dtype=torch.float32,
2312 _wq_b_proj=lambda qr_, qr_scale: q,
2313 )
2314 q_quant = torch.randn(num_tokens, n_head, head_dim)
2315 q_scale = torch.randn(num_tokens, n_head)
2316 weights_out = torch.randn(num_tokens, n_head)
2317 if quant_tuple:
2318 fused_return = ((q_quant, q_scale), weights_out)
2319 expected = (q_quant, q_scale, weights_out)
2320 else:
2321 fused_return = (q_quant, weights_out)
2322 expected = (q_quant, None, weights_out)
2323
2324 with patch(
2325 "vllm.models.deepseek_v41.attention.fused_indexer_q_rope_quant",
2326 return_value=fused_return,
2327 ) as mock_fused:
2328 result = DeepseekV4Indexer.forward_q(
2329 fake, qr, None, indexer_weights, positions, rotary
2330 )
2331
2332 assert torch.equal(result[0], expected[0])
2333 assert (result[1] is None) == (expected[1] is None)
2334 if expected[1] is not None:
2335 assert torch.equal(result[1], expected[1])
2336 assert torch.equal(result[2], expected[2])
2337 args = mock_fused.call_args.args
2338 assert args[0] is positions
2339 torch.testing.assert_close(args[1], q.view(-1, n_head, head_dim))
2340 assert args[2] is rotary.cos_sin_cache
2341 assert args[3] is indexer_weights
2342 assert args[4] == head_dim**-0.5
2343 assert args[5] == n_head**-0.5
2344 assert mock_fused.call_args.kwargs == {
2345 "use_fp4": False,
2346 "weights_out_dtype": torch.float32,
2347 }