From 38eccab0db1808347040a704e68a991e23d3773c Mon Sep 17 00:00:00 2001 From: Fangzhou Ai Date: Thu, 17 Sep 2026 19:07:06 +0000 Subject: [PATCH 1/3] [ROCm][DSv4.1][Perf] Fuse the inverse RoPE into the sparse decode reduce The decode reduce stores its combined output only for the standalone inverse RoPE kernel to read the whole [T, H, 512] tensor back, rotate the trailing rope lanes and write it out again -- a full round trip per layer for an epilogue on data that was already in registers. Rotate in the reduce instead. Reshaping the row into adjacent pairs puts the rope lanes in the last 32 of 256 pairs, so feeding cos=1/sin=0 to the NoPE pairs covers the whole row with one expression. _o_proj then rotates only the rows the kernel reports it did not, which on a decode-only step is none of them, and does it in place. FlashMLA's mega-attention kernel already folds this rotation (and the FP8 cast) into its epilogue on SM100; this gives the ROCm Triton path the same shape. Co-authored-by: Cursor Agent Signed-off-by: Fangzhou Ai --- .../test_dsv41_rocm_fused_inv_rope.py | 60 +++++++++ vllm/models/deepseek_v41/amd/rocm.py | 14 +- .../v1/attention/ops/rocm_aiter_mla_sparse.py | 126 +++++++++++++++--- 3 files changed, 177 insertions(+), 23 deletions(-) create mode 100644 tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py diff --git a/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py b/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py new file mode 100644 index 000000000000..d320ead77abb --- /dev/null +++ b/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""The decode reduce epilogue must reproduce the standalone inverse RoPE. + +Guards the lane arithmetic of the fused epilogue in +``_sparse_attn_decode_reduce_kernel``: it rotates a whole [H, nope + rope] row +with one expression by feeding cos=1/sin=0 to the NoPE lanes, which only works +if the pair-split boundary lands exactly on ``nope_head_dim // 2``. +""" + +import pytest +import torch + +NOPE = 448 +ROPE = 64 +COMB = NOPE + ROPE + + +def _reference_inverse_rope(o, positions, cos_sin_cache): + """What ``_inverse_rope_gptj_kernel`` computes, lane by lane.""" + out = o.clone() + cos = cos_sin_cache[positions, : ROPE // 2] + sin = cos_sin_cache[positions, ROPE // 2 :] + a = o[..., NOPE::2] + b = o[..., NOPE + 1 :: 2] + out[..., NOPE::2] = a * cos[:, None, :] + b * sin[:, None, :] + out[..., NOPE + 1 :: 2] = b * cos[:, None, :] - a * sin[:, None, :] + return out + + +def _fused_epilogue(o, positions, cos_sin_cache): + """The tile arithmetic of the fused epilogue, in torch.""" + pair_idx = torch.arange(COMB // 2) - NOPE // 2 + is_rope = pair_idx >= 0 + k = torch.where(is_rope, pair_idx, torch.zeros_like(pair_idx)) + row = cos_sin_cache[positions] + cos = torch.where(is_rope, row[:, k], torch.ones(1)) + sin = torch.where(is_rope, row[:, ROPE // 2 + k], torch.zeros(1)) + even, odd = o.reshape(*o.shape[:-1], COMB // 2, 2).unbind(-1) + cos = cos[:, None, :] + sin = sin[:, None, :] + return torch.stack( + (even * cos + odd * sin, odd * cos - even * sin), dim=-1 + ).reshape(o.shape) + + +@pytest.mark.parametrize("num_heads", [1, 8]) +def test_fused_epilogue_matches_standalone_inverse_rope(num_heads): + torch.manual_seed(0) + num_tokens, max_pos = 7, 64 + o = torch.randn(num_tokens, num_heads, COMB, dtype=torch.float32) + positions = torch.randint(0, max_pos, (num_tokens,)) + cos_sin_cache = torch.randn(max_pos, ROPE, dtype=torch.float32) + + fused = _fused_epilogue(o, positions, cos_sin_cache) + torch.testing.assert_close( + fused, _reference_inverse_rope(o, positions, cos_sin_cache) + ) + # NoPE lanes must come through bit-exact, not merely close. + assert torch.equal(fused[..., :NOPE], o[..., :NOPE]) diff --git a/vllm/models/deepseek_v41/amd/rocm.py b/vllm/models/deepseek_v41/amd/rocm.py index b3d80f8d2591..159b73d458c6 100644 --- a/vllm/models/deepseek_v41/amd/rocm.py +++ b/vllm/models/deepseek_v41/amd/rocm.py @@ -498,6 +498,9 @@ def __init__(self, *args, **kwargs): self._fused_compressor_weight: torch.Tensor | None self.register_buffer("_fused_compressor_weight", None, persistent=False) self._fused_compressor_split_sizes: tuple[int, int] | None = None + # Leading rows of the attention output that the decode reduce already + # inverse-RoPE'd, so _o_proj rotates only the prefill tail. + self._inv_roped_decode_rows = 0 @classmethod def get_padded_num_q_heads(cls, num_heads: int) -> int: @@ -647,6 +650,7 @@ def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tens self.n_local_groups, self.o_lora_rank, self.wo_a, + rotate_start=self._inv_roped_decode_rows, ) zf = z.flatten(1) if self._wo_b_scale is not None and zf.dim() == 2: @@ -688,6 +692,7 @@ def forward_mqa( ((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16), ) output.zero_() + self._inv_roped_decode_rows = 0 return assert isinstance(attn_metadata, dict) @@ -710,6 +715,9 @@ def forward_mqa( num_decodes = swa_metadata.num_decodes num_prefills = swa_metadata.num_prefills num_decode_tokens = swa_metadata.num_decode_tokens + # Only a decode kernel that fuses the inverse RoPE relieves _o_proj of + # it, and only for its own rows; _forward_decode reports how many. + self._inv_roped_decode_rows = 0 if num_prefills > 0: self._forward_prefill( @@ -724,6 +732,7 @@ def forward_mqa( if num_decodes > 0: self._forward_decode( q=q[:num_decode_tokens], + positions=positions[:num_decode_tokens], kv_cache=self_kv_cache, swa_metadata=swa_metadata, attn_metadata=rocm_metadata, @@ -734,6 +743,7 @@ def forward_mqa( def _forward_decode( self, q: torch.Tensor, + positions: torch.Tensor, kv_cache: torch.Tensor | None, swa_metadata: DeepseekV4ROCMAiterSparseSWAMetadata, attn_metadata: DeepseekV4FlashMLAMetadata | None, @@ -765,7 +775,7 @@ def _forward_decode( is_valid, ) - rocm_sparse_attn_decode( + self._inv_roped_decode_rows = rocm_sparse_attn_decode( q=q, kv_cache=kv_cache, swa_k_cache=self.swa_cache_layer.kv_cache, @@ -784,6 +794,8 @@ def _forward_decode( nope_head_dim=self.nope_head_dim, rope_head_dim=self.rope_head_dim, output=output, + inv_rope_positions=positions, + inv_rope_cos_sin_cache=self.rotary_emb.cos_sin_cache, extra_cache_nan_free=_trust_dsv4_extra_cache_nan_free( self.kv_cache_dtype, self._has_kv_transfer, diff --git a/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py b/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py index 3d891c8ce0f7..cad3ff1c750d 100644 --- a/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py +++ b/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py @@ -29,8 +29,6 @@ logger = init_logger(__name__) -FP8_DTYPE = current_platform.fp8_dtype() - @functools.cache def _get_aiter_topk_ops() -> tuple[Callable[..., None], Callable[..., None]] | None: @@ -262,7 +260,8 @@ def indexer_k_quant_and_cache_triton( # In real layout, we store the first portion as kv cache value # and second portion as kv cache scale kv_cache = kv_cache.view(num_blocks, -1) - kv_cache_value = kv_cache[:, : block_size * head_dim].view(FP8_DTYPE) + fp8_dtype = current_platform.fp8_dtype() + kv_cache_value = kv_cache[:, : block_size * head_dim].view(fp8_dtype) kv_cache_scale = kv_cache[:, block_size * head_dim :].view(torch.float32) head_tile_size = head_tile_size // kv_cache.element_size() layout = "NORMAL" if block_size == 1 else "SHUFFLE" @@ -280,7 +279,7 @@ def indexer_k_quant_and_cache_triton( layout, block_tile_size, head_tile_size, - IS_FNUZ=torch.float8_e4m3fnuz == FP8_DTYPE, + IS_FNUZ=current_platform.fp8_dtype() == torch.float8_e4m3fnuz, USE_UE8M0=scale_fmt == "ue8m0", ) @@ -466,7 +465,8 @@ def cp_gather_indexer_k_quant_cache_triton( num_blocks = k_cache.shape[0] # we assume the kv cache already been split to 2 portion k_cache = k_cache.view(num_blocks, -1) - k_cache_value = k_cache[:, : block_size * head_dim].view(FP8_DTYPE) + fp8_dtype = current_platform.fp8_dtype() + k_cache_value = k_cache[:, : block_size * head_dim].view(fp8_dtype) k_cache_scale = k_cache[:, block_size * head_dim :].view(torch.float32) grid = (num_tokens,) k_fp8_scale = k_fp8_scale.view(torch.float32) @@ -516,6 +516,7 @@ def fp8_paged_mqa_logits_torch( ): from vllm.utils.math_utils import cdiv + fp8_dtype = current_platform.fp8_dtype() batch_size, next_n, _, dim = q.size() if next_n == 1: block_size = kv_cache.shape[1] @@ -539,7 +540,7 @@ def fp8_paged_mqa_logits_torch( cache = kv_cache_flat[pages] scale_offset = block_size * dim cache_value = ( - cache[..., :scale_offset].view(dtype=FP8_DTYPE).to(torch.float32) + cache[..., :scale_offset].view(dtype=fp8_dtype).to(torch.float32) ) cache_scale = ( cache[..., scale_offset:].view(dtype=torch.float32).contiguous() @@ -557,7 +558,7 @@ def fp8_paged_mqa_logits_torch( kv_cache, scale = kv_cache[..., :dim], kv_cache[..., dim:] scale = scale.contiguous().view(torch.float) q = q.float() - kv_cache = kv_cache.view(FP8_DTYPE).float() * scale + kv_cache = kv_cache.view(fp8_dtype).float() * scale num_block, block_size, _, dim = kv_cache.size() logits = torch.full( [batch_size * next_n, max_model_len], @@ -1020,6 +1021,7 @@ def rocm_aiter_sparse_attn_indexer( # careful! this will be None in dummy run forward_context = get_forward_context() attn_metadata = forward_context.attn_metadata + fp8_dtype = current_platform.fp8_dtype() from vllm.utils.torch_utils import _resolve_layer_name k_cache_prefix = _resolve_layer_name(k_cache_prefix) @@ -1035,7 +1037,7 @@ def rocm_aiter_sparse_attn_indexer( # Prefill k_fp8 and k_scale buffers, used by # rocm_aiter_sparse_attn_indexer's prefill path workspace_manager.get_simultaneous( - ((total_seq_lens, head_dim), FP8_DTYPE), + ((total_seq_lens, head_dim), fp8_dtype), ((total_seq_lens, 4), torch.uint8), ) @@ -1115,7 +1117,7 @@ def rocm_aiter_sparse_attn_indexer( workspace_manager = current_workspace_manager() k_fp8_full, k_scale_full = workspace_manager.get_simultaneous( - ((total_seq_lens, head_dim), FP8_DTYPE), + ((total_seq_lens, head_dim), fp8_dtype), ((total_seq_lens, 4), torch.uint8), ) for chunk in prefill_metadata.chunks: @@ -1390,8 +1392,15 @@ def _fused_inverse_rope_gptj( positions: torch.Tensor, cos_sin_cache: torch.Tensor, rope_head_dim: int, + rotate_start: int = 0, ) -> torch.Tensor: - """bf16 inverse GPT-J RoPE via a single fused Triton kernel.""" + """bf16 inverse GPT-J RoPE via a single fused Triton kernel. + + Rows below ``rotate_start`` were rotated by the decode attention epilogue + already; the rotation is a per-row bijection that reads both lanes of a + pair before storing, so a bf16 input is rotated in place and the untouched + rows cost nothing. + """ assert o.dim() == 3 and o.stride(-1) == 1, ( "_fused_inverse_rope_gptj expects a [T, H, D] input with a contiguous last dim" ) @@ -1403,15 +1412,24 @@ def _fused_inverse_rope_gptj( f"[P, {rope_head_dim}] = cos | sin, got {tuple(cos_sin_cache.shape)}" ) num_tokens, num_heads, head_dim = o.shape - out = torch.empty( - (num_tokens, num_heads, head_dim), dtype=torch.bfloat16, device=o.device - ) - if num_tokens == 0: + inplace = rotate_start > 0 + if inplace: + assert o.dtype == torch.bfloat16, ( + "partial inverse RoPE rotates in place, so the attention output " + f"must already be bf16, got {o.dtype}" + ) + out = o + else: + out = torch.empty( + (num_tokens, num_heads, head_dim), dtype=torch.bfloat16, device=o.device + ) + num_rows = num_tokens - rotate_start + if num_rows <= 0: return out - _inverse_rope_gptj_kernel[(num_tokens, num_heads)]( - o, - out, - positions, + _inverse_rope_gptj_kernel[(num_rows, num_heads)]( + o[rotate_start:], + out[rotate_start:], + positions[rotate_start:], cos_sin_cache, o.stride(0), o.stride(1), @@ -1482,16 +1500,18 @@ def rocm_inv_rope_einsum( n_local_groups: int, o_lora_rank: int, wo_a: torch.nn.Module, + rotate_start: int = 0, ) -> torch.Tensor: """Inverse-RoPE + WO_A bmm path used on ROCm. Fuses the inverse GPT-J RoPE into one Triton kernel and caches the bf16 - wo_a weight so the per-step dequant disappears. + wo_a weight so the per-step dequant disappears. ``rotate_start`` skips the + leading rows whose rotation the decode attention epilogue already did. """ o_ref = _fused_inverse_rope_gptj( - o, positions, rotary_emb.cos_sin_cache, rope_head_dim + o, positions, rotary_emb.cos_sin_cache, rope_head_dim, rotate_start ) - o_ref = o_ref.view(o.shape[0], n_local_groups, -1) + o_ref = o_ref.reshape(o.shape[0], n_local_groups, -1) wo_a_weight = _get_cached_wo_a_bf16( wo_a, n_local_groups, o_lora_rank, o_ref.shape[-1] @@ -2707,6 +2727,8 @@ def _sparse_attn_decode_reduce_kernel( part_acc_ptr, attn_sink_ptr, out_ptr, + pos_ptr, + cos_sin_ptr, out_stride0, out_stride1, pm_stride0, @@ -2714,6 +2736,7 @@ def _sparse_attn_decode_reduce_kernel( pa_stride0, pa_stride_s, pa_stride_h, + cs_stride, num_heads, HAS_ATTN_SINK: tl.constexpr, ADAPTIVE_SPLITS: tl.constexpr, @@ -2721,6 +2744,9 @@ def _sparse_attn_decode_reduce_kernel( BLOCK_H: tl.constexpr, NUM_SPLITS: tl.constexpr, SPLITS_PAD: tl.constexpr, + FUSE_INV_ROPE: tl.constexpr, + NOPE: tl.constexpr, + HALF: tl.constexpr, ): query_idx = tl.program_id(0) pid_h = tl.program_id(1) @@ -2810,6 +2836,26 @@ def _sparse_attn_decode_reduce_kernel( out = tl.where(l_final[:, None] > 0.0, acc / denom[:, None], 0.0) + if FUSE_INV_ROPE: + # Inverse GPT-J RoPE on the trailing rope lanes, straight out of the + # combine registers: out_even = a*cos + b*sin, out_odd = b*cos - a*sin. + # NoPE lanes take cos=1/sin=0 so one expression covers the whole row + # and the o_proj rotation pass disappears for these tokens. + pos = tl.load(pos_ptr + query_idx).to(tl.int64) + pair_idx = tl.arange(0, COMB_DIM // 2) - (NOPE // 2) + is_rope = pair_idx >= 0 + k = tl.where(is_rope, pair_idx, 0) + cos = tl.where(is_rope, tl.load(cos_sin_ptr + pos * cs_stride + k), 1.0) + sin = tl.where(is_rope, tl.load(cos_sin_ptr + pos * cs_stride + HALF + k), 0.0) + even, odd = tl.split(tl.reshape(out, (BLOCK_H, COMB_DIM // 2, 2))) + out = tl.reshape( + tl.join( + even * cos[None, :] + odd * sin[None, :], + odd * cos[None, :] - even * sin[None, :], + ), + (BLOCK_H, COMB_DIM), + ) + out_row_ptr = ( out_ptr + query_idx * out_stride0 + head_offsets[:, None] * out_stride1 ) @@ -3130,6 +3176,8 @@ def _rocm_sparse_attn_decode_ragged_triton( out: torch.Tensor | None = None, extra_cache_nan_free: bool = False, adaptive_splits: bool = False, + inv_rope_positions: torch.Tensor | None = None, + inv_rope_cos_sin_cache: torch.Tensor | None = None, ) -> torch.Tensor: assert q.ndim == 3, f"expected q=[b,h,d], got {q.shape}" assert main_cache.ndim == 3, ( @@ -3372,12 +3420,27 @@ def _rocm_sparse_attn_decode_ragged_triton( num_warps=4, ) + fuse_inv_rope = inv_rope_positions is not None + if fuse_inv_rope: + assert inv_rope_cos_sin_cache is not None + assert inv_rope_cos_sin_cache.shape[-1] == rope_head_dim, ( + "fused inverse RoPE expects cos_sin_cache laid out as " + f"[P, {rope_head_dim}] = cos | sin, got " + f"{tuple(inv_rope_cos_sin_cache.shape)}" + ) + assert nope_head_dim % 2 == 0 and rope_head_dim % 2 == 0, ( + "fused inverse RoPE pairs adjacent lanes, so both head dims must " + f"be even, got nope={nope_head_dim} rope={rope_head_dim}" + ) + _sparse_attn_decode_reduce_kernel[(num_queries, num_heads)]( part_m, part_l, part_acc, attn_sink, out, + inv_rope_positions, + inv_rope_cos_sin_cache, out.stride(0), out.stride(1), part_m.stride(0), @@ -3385,6 +3448,7 @@ def _rocm_sparse_attn_decode_ragged_triton( part_acc.stride(0), part_acc.stride(1), part_acc.stride(2), + inv_rope_cos_sin_cache.stride(0) if inv_rope_cos_sin_cache is not None else 0, num_heads, HAS_ATTN_SINK=has_attn_sink, ADAPTIVE_SPLITS=adaptive_splits, @@ -3392,6 +3456,9 @@ def _rocm_sparse_attn_decode_ragged_triton( BLOCK_H=1, NUM_SPLITS=num_splits, SPLITS_PAD=triton.next_power_of_2(num_splits), + FUSE_INV_ROPE=fuse_inv_rope, + NOPE=nope_head_dim, + HALF=rope_head_dim // 2, num_warps=4, ) return out @@ -3416,6 +3483,8 @@ def _rocm_sparse_attn_decode_triton( out: torch.Tensor | None = None, extra_cache_nan_free: bool = False, adaptive_splits: bool = False, + inv_rope_positions: torch.Tensor | None = None, + inv_rope_cos_sin_cache: torch.Tensor | None = None, ) -> torch.Tensor: if main_ragged_indices is None or main_ragged_indptr is None: main_ragged_indices, main_ragged_indptr = build_ragged_indices_from_dense( @@ -3454,6 +3523,8 @@ def _rocm_sparse_attn_decode_triton( out=out, extra_cache_nan_free=extra_cache_nan_free, adaptive_splits=adaptive_splits, + inv_rope_positions=inv_rope_positions, + inv_rope_cos_sin_cache=inv_rope_cos_sin_cache, ) @@ -3555,7 +3626,15 @@ def rocm_sparse_attn_decode( output: torch.Tensor, extra_cache_nan_free: bool = False, adaptive_splits: bool = False, -) -> None: + inv_rope_positions: torch.Tensor | None = None, + inv_rope_cos_sin_cache: torch.Tensor | None = None, +) -> int: + """Run sparse MLA decode into ``output``. + + Returns the number of leading rows whose inverse RoPE the kernel already + applied, so the caller knows what its output projection still owes. Zero + unless ``inv_rope_positions`` was given and a fusing kernel ran. + """ assert swa_k_cache.dtype == torch.uint8, ( "ROCm Triton sparse decode expects uint8 fp8_ds_mla SWA cache, " f"got {swa_k_cache.dtype}" @@ -3604,6 +3683,9 @@ def rocm_sparse_attn_decode( out=direct_out, extra_cache_nan_free=extra_cache_nan_free, adaptive_splits=adaptive_splits, + inv_rope_positions=inv_rope_positions, + inv_rope_cos_sin_cache=inv_rope_cos_sin_cache, ) if direct_out is None: output.copy_(attn_out.to(output.dtype)) + return output.shape[0] if inv_rope_positions is not None else 0 From 800e461f596293f3f16ba7eccf9ebaf7ea390870 Mon Sep 17 00:00:00 2001 From: Fangzhou Ai Date: Thu, 17 Sep 2026 21:51:56 +0000 Subject: [PATCH 2/3] [ROCm][DSv4.1] Rotate prefill rows in the eager attention segment The decode reduce rotates the rows it produces, so only prefill rows still owe an inverse RoPE. Handing that row count to _o_proj was unsound: o_proj runs inside the compiled region, and vLLM compiles with skip_all_guards_unsafe, so the value froze at its trace-time value and rows ended up rotated zero or two times. GSM8K fell to 0.087 against a 0.902 baseline, with fluent output and no error. Resolving the split in the eager attention segment keeps it correct per step and still drops the separate pass entirely on decode-only steps. Co-authored-by: Cursor Signed-off-by: Fangzhou Ai Co-authored-by: Cursor --- .../test_dsv41_rocm_fused_inv_rope.py | 37 ++++----- .../attention/test_rocm_triton_attn_dsv4.py | 6 ++ vllm/models/deepseek_v41/amd/rocm.py | 29 ++++--- .../v1/attention/ops/rocm_aiter_mla_sparse.py | 79 ++++++++++++------- 4 files changed, 90 insertions(+), 61 deletions(-) diff --git a/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py b/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py index d320ead77abb..de5d9cfcd5d2 100644 --- a/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py +++ b/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py @@ -2,13 +2,11 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """The decode reduce epilogue must reproduce the standalone inverse RoPE. -Guards the lane arithmetic of the fused epilogue in -``_sparse_attn_decode_reduce_kernel``: it rotates a whole [H, nope + rope] row -with one expression by feeding cos=1/sin=0 to the NoPE lanes, which only works -if the pair-split boundary lands exactly on ``nope_head_dim // 2``. +The epilogue in ``_sparse_attn_decode_reduce_kernel`` rotates a whole +[H, nope + rope] row with one expression by feeding cos=1/sin=0 to the NoPE +lanes, which only holds if the pair split lands on ``nope_head_dim // 2``. """ -import pytest import torch NOPE = 448 @@ -16,45 +14,40 @@ COMB = NOPE + ROPE -def _reference_inverse_rope(o, positions, cos_sin_cache): +def _standalone(o, positions, cos_sin_cache): """What ``_inverse_rope_gptj_kernel`` computes, lane by lane.""" out = o.clone() - cos = cos_sin_cache[positions, : ROPE // 2] - sin = cos_sin_cache[positions, ROPE // 2 :] + cos = cos_sin_cache[positions, : ROPE // 2][:, None, :] + sin = cos_sin_cache[positions, ROPE // 2 :][:, None, :] a = o[..., NOPE::2] b = o[..., NOPE + 1 :: 2] - out[..., NOPE::2] = a * cos[:, None, :] + b * sin[:, None, :] - out[..., NOPE + 1 :: 2] = b * cos[:, None, :] - a * sin[:, None, :] + out[..., NOPE::2] = a * cos + b * sin + out[..., NOPE + 1 :: 2] = b * cos - a * sin return out -def _fused_epilogue(o, positions, cos_sin_cache): +def _epilogue(o, positions, cos_sin_cache): """The tile arithmetic of the fused epilogue, in torch.""" pair_idx = torch.arange(COMB // 2) - NOPE // 2 is_rope = pair_idx >= 0 k = torch.where(is_rope, pair_idx, torch.zeros_like(pair_idx)) row = cos_sin_cache[positions] - cos = torch.where(is_rope, row[:, k], torch.ones(1)) - sin = torch.where(is_rope, row[:, ROPE // 2 + k], torch.zeros(1)) + cos = torch.where(is_rope, row[:, k], torch.ones(1))[:, None, :] + sin = torch.where(is_rope, row[:, ROPE // 2 + k], torch.zeros(1))[:, None, :] even, odd = o.reshape(*o.shape[:-1], COMB // 2, 2).unbind(-1) - cos = cos[:, None, :] - sin = sin[:, None, :] return torch.stack( (even * cos + odd * sin, odd * cos - even * sin), dim=-1 ).reshape(o.shape) -@pytest.mark.parametrize("num_heads", [1, 8]) -def test_fused_epilogue_matches_standalone_inverse_rope(num_heads): +def test_fused_epilogue_matches_standalone_inverse_rope(): torch.manual_seed(0) - num_tokens, max_pos = 7, 64 + num_tokens, num_heads, max_pos = 7, 8, 64 o = torch.randn(num_tokens, num_heads, COMB, dtype=torch.float32) positions = torch.randint(0, max_pos, (num_tokens,)) cos_sin_cache = torch.randn(max_pos, ROPE, dtype=torch.float32) - fused = _fused_epilogue(o, positions, cos_sin_cache) - torch.testing.assert_close( - fused, _reference_inverse_rope(o, positions, cos_sin_cache) - ) + fused = _epilogue(o, positions, cos_sin_cache) + torch.testing.assert_close(fused, _standalone(o, positions, cos_sin_cache)) # NoPE lanes must come through bit-exact, not merely close. assert torch.equal(fused[..., :NOPE], o[..., :NOPE]) diff --git a/tests/kernels/attention/test_rocm_triton_attn_dsv4.py b/tests/kernels/attention/test_rocm_triton_attn_dsv4.py index f0ac4d838511..505713f08bbc 100644 --- a/tests/kernels/attention/test_rocm_triton_attn_dsv4.py +++ b/tests/kernels/attention/test_rocm_triton_attn_dsv4.py @@ -265,6 +265,8 @@ def _launch_sparse_decode_reduce( part_acc, attn_sink, out, + None, + None, out.stride(0), out.stride(1), part_m.stride(0), @@ -272,6 +274,7 @@ def _launch_sparse_decode_reduce( part_acc.stride(0), part_acc.stride(1), part_acc.stride(2), + 0, num_heads, HAS_ATTN_SINK=False, ADAPTIVE_SPLITS=adaptive_splits, @@ -279,6 +282,9 @@ def _launch_sparse_decode_reduce( BLOCK_H=1, NUM_SPLITS=num_splits, SPLITS_PAD=1 << (num_splits - 1).bit_length(), + FUSE_INV_ROPE=False, + NOPE=NOPE_HEAD_DIM, + HALF=ROPE_HEAD_DIM // 2, num_warps=4, ) return out diff --git a/vllm/models/deepseek_v41/amd/rocm.py b/vllm/models/deepseek_v41/amd/rocm.py index 159b73d458c6..5a56661c3415 100644 --- a/vllm/models/deepseek_v41/amd/rocm.py +++ b/vllm/models/deepseek_v41/amd/rocm.py @@ -34,6 +34,7 @@ from vllm.v1.attention.ops.rocm_aiter_mla_sparse import ( build_ragged_indices_from_dense, rocm_inv_rope_einsum, + rocm_inverse_rope_rows_, rocm_sparse_attn_decode, rocm_sparse_attn_prefill, ) @@ -498,9 +499,6 @@ def __init__(self, *args, **kwargs): self._fused_compressor_weight: torch.Tensor | None self.register_buffer("_fused_compressor_weight", None, persistent=False) self._fused_compressor_split_sizes: tuple[int, int] | None = None - # Leading rows of the attention output that the decode reduce already - # inverse-RoPE'd, so _o_proj rotates only the prefill tail. - self._inv_roped_decode_rows = 0 @classmethod def get_padded_num_q_heads(cls, num_heads: int) -> int: @@ -650,7 +648,7 @@ def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tens self.n_local_groups, self.o_lora_rank, self.wo_a, - rotate_start=self._inv_roped_decode_rows, + inverse_rope=False, ) zf = z.flatten(1) if self._wo_b_scale is not None and zf.dim() == 2: @@ -692,7 +690,6 @@ def forward_mqa( ((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16), ) output.zero_() - self._inv_roped_decode_rows = 0 return assert isinstance(attn_metadata, dict) @@ -715,9 +712,6 @@ def forward_mqa( num_decodes = swa_metadata.num_decodes num_prefills = swa_metadata.num_prefills num_decode_tokens = swa_metadata.num_decode_tokens - # Only a decode kernel that fuses the inverse RoPE relieves _o_proj of - # it, and only for its own rows; _forward_decode reports how many. - self._inv_roped_decode_rows = 0 if num_prefills > 0: self._forward_prefill( @@ -729,8 +723,9 @@ def forward_mqa( attn_metadata=rocm_metadata, swa_metadata=swa_metadata, ) + rotated = 0 if num_decodes > 0: - self._forward_decode( + rotated = self._forward_decode( q=q[:num_decode_tokens], positions=positions[:num_decode_tokens], kv_cache=self_kv_cache, @@ -739,6 +734,17 @@ def forward_mqa( swa_only=swa_only, output=output[:num_decode_tokens], ) + # Only the decode reduce rotates its own rows, and only the leading + # `rotated` of them; prefill rows and any decode path that did not + # fuse still owe the standalone pass. Settle that here rather than in + # _o_proj: the split is batch-dependent and _o_proj runs compiled, + # where such a value freezes at its trace-time value. + rocm_inverse_rope_rows_( + output[rotated:, : self.n_local_heads, :], + positions[rotated:], + self.rotary_emb.cos_sin_cache, + self.rope_head_dim, + ) def _forward_decode( self, @@ -749,7 +755,8 @@ def _forward_decode( attn_metadata: DeepseekV4FlashMLAMetadata | None, swa_only: bool, output: torch.Tensor, - ) -> None: + ) -> int: + """Returns how many leading rows the decode epilogue inverse-RoPE'd.""" num_decodes = swa_metadata.num_decodes num_decode_tokens = swa_metadata.num_decode_tokens @@ -775,7 +782,7 @@ def _forward_decode( is_valid, ) - self._inv_roped_decode_rows = rocm_sparse_attn_decode( + return rocm_sparse_attn_decode( q=q, kv_cache=kv_cache, swa_k_cache=self.swa_cache_layer.kv_cache, diff --git a/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py b/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py index cad3ff1c750d..63d50005c497 100644 --- a/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py +++ b/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py @@ -1392,14 +1392,12 @@ def _fused_inverse_rope_gptj( positions: torch.Tensor, cos_sin_cache: torch.Tensor, rope_head_dim: int, - rotate_start: int = 0, + out: torch.Tensor | None = None, ) -> torch.Tensor: """bf16 inverse GPT-J RoPE via a single fused Triton kernel. - Rows below ``rotate_start`` were rotated by the decode attention epilogue - already; the rotation is a per-row bijection that reads both lanes of a - pair before storing, so a bf16 input is rotated in place and the untouched - rows cost nothing. + ``out`` may alias ``o``: the rotation is a per-row bijection whose kernel + reads both lanes of a pair before storing either. """ assert o.dim() == 3 and o.stride(-1) == 1, ( "_fused_inverse_rope_gptj expects a [T, H, D] input with a contiguous last dim" @@ -1412,24 +1410,20 @@ def _fused_inverse_rope_gptj( f"[P, {rope_head_dim}] = cos | sin, got {tuple(cos_sin_cache.shape)}" ) num_tokens, num_heads, head_dim = o.shape - inplace = rotate_start > 0 - if inplace: - assert o.dtype == torch.bfloat16, ( - "partial inverse RoPE rotates in place, so the attention output " - f"must already be bf16, got {o.dtype}" - ) - out = o - else: + if out is None: out = torch.empty( (num_tokens, num_heads, head_dim), dtype=torch.bfloat16, device=o.device ) - num_rows = num_tokens - rotate_start - if num_rows <= 0: + else: + assert out.dtype == torch.bfloat16, ( + f"inverse RoPE writes bf16, got an output buffer of {out.dtype}" + ) + if num_tokens == 0: return out - _inverse_rope_gptj_kernel[(num_rows, num_heads)]( - o[rotate_start:], - out[rotate_start:], - positions[rotate_start:], + _inverse_rope_gptj_kernel[(num_tokens, num_heads)]( + o, + out, + positions, cos_sin_cache, o.stride(0), o.stride(1), @@ -1444,6 +1438,25 @@ def _fused_inverse_rope_gptj( return out +def rocm_inverse_rope_rows_( + o: torch.Tensor, + positions: torch.Tensor, + cos_sin_cache: torch.Tensor, + rope_head_dim: int, +) -> None: + """Inverse-RoPE attention output rows in place. + + For rows no attention kernel rotated in its epilogue. Call it from the + eager attention segment: which rows still owe a rotation depends on the + prefill/decode split, and the o_proj that used to do this runs inside the + compiled region, where a batch-dependent Python value would be frozen at + trace time. + """ + if o.shape[0] == 0: + return + _fused_inverse_rope_gptj(o, positions, cos_sin_cache, rope_head_dim, out=o) + + def _get_cached_wo_a_bf16( wo_a: torch.nn.Module, n_local_groups: int, @@ -1500,17 +1513,26 @@ def rocm_inv_rope_einsum( n_local_groups: int, o_lora_rank: int, wo_a: torch.nn.Module, - rotate_start: int = 0, + inverse_rope: bool = True, ) -> torch.Tensor: """Inverse-RoPE + WO_A bmm path used on ROCm. Fuses the inverse GPT-J RoPE into one Triton kernel and caches the bf16 - wo_a weight so the per-step dequant disappears. ``rotate_start`` skips the - leading rows whose rotation the decode attention epilogue already did. + wo_a weight so the per-step dequant disappears. Callers whose attention + already rotated every row pass ``inverse_rope=False``; that is a property + of the attention backend, not of the batch, so it stays constant across + steps and is safe to read from compiled code. """ - o_ref = _fused_inverse_rope_gptj( - o, positions, rotary_emb.cos_sin_cache, rope_head_dim, rotate_start - ) + if inverse_rope: + o_ref = _fused_inverse_rope_gptj( + o, positions, rotary_emb.cos_sin_cache, rope_head_dim + ) + else: + assert o.dtype == torch.bfloat16, ( + "a pre-rotated attention output feeds the wo_a bmm directly, so it " + f"must already be bf16, got {o.dtype}" + ) + o_ref = o o_ref = o_ref.reshape(o.shape[0], n_local_groups, -1) wo_a_weight = _get_cached_wo_a_bf16( @@ -3631,9 +3653,10 @@ def rocm_sparse_attn_decode( ) -> int: """Run sparse MLA decode into ``output``. - Returns the number of leading rows whose inverse RoPE the kernel already - applied, so the caller knows what its output projection still owes. Zero - unless ``inv_rope_positions`` was given and a fusing kernel ran. + Passing ``inv_rope_positions`` folds the inverse RoPE into the reduce + epilogue. Returns how many leading rows of ``output`` came back rotated, + so a caller mixing in a decode path that does not fuse still knows what it + owes the standalone pass. Read it from the eager attention segment only. """ assert swa_k_cache.dtype == torch.uint8, ( "ROCm Triton sparse decode expects uint8 fp8_ds_mla SWA cache, " From 61abd6cbc5ccb41b7db344ad0cc90df09eaaabc5 Mon Sep 17 00:00:00 2001 From: Fangzhou Ai Date: Mon, 21 Sep 2026 01:58:20 +0000 Subject: [PATCH 3/3] [ROCm][DSv4.1] Test the fused inverse RoPE through the reduce kernel Review feedback on #57435. The test added with the fusion compared two torch reimplementations of the rotation against each other, so it proved the index algebra self-consistent and nothing about the kernel that ships. Meanwhile the reduce kernel's own harness only ever passed FUSE_INV_ROPE=False, leaving the new epilogue with no coverage at all. Drive the epilogue through `_sparse_attn_decode_reduce_kernel` instead: reduce once with the epilogue off and rotate with the standalone `_fused_inverse_rope_gptj`, reduce again with it on, and require the two to agree. The NoPE lanes must match the unrotated output bit for bit, which is what pins the pair split to `nope_head_dim // 2`, and the RoPE lanes must not, which an epilogue that quietly did nothing would fail. Both arms run against adaptive and fixed splits. The torch-only file goes away. Also restore the module-level `FP8_DTYPE`: replacing it with per-call `current_platform.fp8_dtype()` put a host-side platform query back in the prefill path, and it was never part of this change. Tested on MI355X (gfx950), ROCm 7.2.3: pytest tests/kernels/attention/test_rocm_triton_attn_dsv4.py -q 70 passed Signed-off-by: Fangzhou Ai Co-authored-by: Cursor --- .../test_dsv41_rocm_fused_inv_rope.py | 53 ------------------- .../attention/test_rocm_triton_attn_dsv4.py | 51 ++++++++++++++++-- .../v1/attention/ops/rocm_aiter_mla_sparse.py | 20 ++++--- 3 files changed, 56 insertions(+), 68 deletions(-) delete mode 100644 tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py diff --git a/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py b/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py deleted file mode 100644 index de5d9cfcd5d2..000000000000 --- a/tests/kernels/attention/test_dsv41_rocm_fused_inv_rope.py +++ /dev/null @@ -1,53 +0,0 @@ -# SPDX-License-Identifier: Apache-2.0 -# SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""The decode reduce epilogue must reproduce the standalone inverse RoPE. - -The epilogue in ``_sparse_attn_decode_reduce_kernel`` rotates a whole -[H, nope + rope] row with one expression by feeding cos=1/sin=0 to the NoPE -lanes, which only holds if the pair split lands on ``nope_head_dim // 2``. -""" - -import torch - -NOPE = 448 -ROPE = 64 -COMB = NOPE + ROPE - - -def _standalone(o, positions, cos_sin_cache): - """What ``_inverse_rope_gptj_kernel`` computes, lane by lane.""" - out = o.clone() - cos = cos_sin_cache[positions, : ROPE // 2][:, None, :] - sin = cos_sin_cache[positions, ROPE // 2 :][:, None, :] - a = o[..., NOPE::2] - b = o[..., NOPE + 1 :: 2] - out[..., NOPE::2] = a * cos + b * sin - out[..., NOPE + 1 :: 2] = b * cos - a * sin - return out - - -def _epilogue(o, positions, cos_sin_cache): - """The tile arithmetic of the fused epilogue, in torch.""" - pair_idx = torch.arange(COMB // 2) - NOPE // 2 - is_rope = pair_idx >= 0 - k = torch.where(is_rope, pair_idx, torch.zeros_like(pair_idx)) - row = cos_sin_cache[positions] - cos = torch.where(is_rope, row[:, k], torch.ones(1))[:, None, :] - sin = torch.where(is_rope, row[:, ROPE // 2 + k], torch.zeros(1))[:, None, :] - even, odd = o.reshape(*o.shape[:-1], COMB // 2, 2).unbind(-1) - return torch.stack( - (even * cos + odd * sin, odd * cos - even * sin), dim=-1 - ).reshape(o.shape) - - -def test_fused_epilogue_matches_standalone_inverse_rope(): - torch.manual_seed(0) - num_tokens, num_heads, max_pos = 7, 8, 64 - o = torch.randn(num_tokens, num_heads, COMB, dtype=torch.float32) - positions = torch.randint(0, max_pos, (num_tokens,)) - cos_sin_cache = torch.randn(max_pos, ROPE, dtype=torch.float32) - - fused = _epilogue(o, positions, cos_sin_cache) - torch.testing.assert_close(fused, _standalone(o, positions, cos_sin_cache)) - # NoPE lanes must come through bit-exact, not merely close. - assert torch.equal(fused[..., :NOPE], o[..., :NOPE]) diff --git a/tests/kernels/attention/test_rocm_triton_attn_dsv4.py b/tests/kernels/attention/test_rocm_triton_attn_dsv4.py index 505713f08bbc..ae4b50750c7b 100644 --- a/tests/kernels/attention/test_rocm_triton_attn_dsv4.py +++ b/tests/kernels/attention/test_rocm_triton_attn_dsv4.py @@ -249,7 +249,10 @@ def _launch_sparse_decode_reduce( part_l: torch.Tensor, part_acc: torch.Tensor, adaptive_splits: bool, + positions: torch.Tensor | None = None, + cos_sin_cache: torch.Tensor | None = None, ) -> torch.Tensor: + """Run the reduce kernel, with the inverse-RoPE epilogue if given positions.""" from vllm.v1.attention.ops import rocm_aiter_mla_sparse as mod num_queries, num_splits, num_heads = part_m.shape @@ -265,8 +268,8 @@ def _launch_sparse_decode_reduce( part_acc, attn_sink, out, - None, - None, + positions, + cos_sin_cache, out.stride(0), out.stride(1), part_m.stride(0), @@ -274,7 +277,7 @@ def _launch_sparse_decode_reduce( part_acc.stride(0), part_acc.stride(1), part_acc.stride(2), - 0, + cos_sin_cache.stride(0) if cos_sin_cache is not None else 0, num_heads, HAS_ATTN_SINK=False, ADAPTIVE_SPLITS=adaptive_splits, @@ -282,7 +285,7 @@ def _launch_sparse_decode_reduce( BLOCK_H=1, NUM_SPLITS=num_splits, SPLITS_PAD=1 << (num_splits - 1).bit_length(), - FUSE_INV_ROPE=False, + FUSE_INV_ROPE=positions is not None, NOPE=NOPE_HEAD_DIM, HALF=ROPE_HEAD_DIM // 2, num_warps=4, @@ -1004,6 +1007,46 @@ def test_sparse_attn_decode_gfx950_adaptive_reduce_ignores_stale_scratch() -> No assert torch.equal(actual, torch.full_like(actual, 2)) +@requires_gfx950 +@pytest.mark.parametrize("adaptive_splits", [False, True]) +@torch.inference_mode() +def test_sparse_attn_decode_reduce_inverse_rope_epilogue(adaptive_splits: bool) -> None: + """FUSE_INV_ROPE must land where the standalone rotation would. + + The epilogue rotates a whole [H, nope + rope] row with one expression by + feeding cos=1/sin=0 to the NoPE lanes, which only holds if the pair split + lands on ``nope_head_dim // 2``; the NoPE lanes therefore have to come + back untouched, not merely close. + """ + from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _fused_inverse_rope_gptj + + device = torch.device("cuda") + torch.manual_seed(7) + num_queries, num_splits, num_heads, max_pos = 5, 4, 8, 64 + shape = (num_queries, num_splits, num_heads) + part_m = torch.randn(shape, dtype=torch.float32, device=device) + part_l = torch.rand(shape, dtype=torch.float32, device=device) + 0.5 + part_acc = torch.randn((*shape, HEAD_DIM), dtype=torch.float32, device=device) + positions = torch.randint( + 0, max_pos, (num_queries,), dtype=torch.int64, device=device + ) + angle = torch.randn(max_pos, ROPE_HEAD_DIM // 2, device=device) + cos_sin_cache = torch.cat((angle.cos(), angle.sin()), dim=-1).contiguous() + + unfused = _launch_sparse_decode_reduce(part_m, part_l, part_acc, adaptive_splits) + expected = _fused_inverse_rope_gptj( + unfused, positions, cos_sin_cache, ROPE_HEAD_DIM + ) + actual = _launch_sparse_decode_reduce( + part_m, part_l, part_acc, adaptive_splits, positions, cos_sin_cache + ) + + torch.testing.assert_close(actual, expected, atol=2e-2, rtol=2e-2) + assert torch.equal(actual[..., :NOPE_HEAD_DIM], unfused[..., :NOPE_HEAD_DIM]) + # An epilogue that quietly did nothing would satisfy everything above. + assert not torch.equal(actual[..., NOPE_HEAD_DIM:], unfused[..., NOPE_HEAD_DIM:]) + + @requires_gfx950 @pytest.mark.parametrize("extra_len", [0, 1, 31, 32, 33, 63, 64, 65]) @torch.inference_mode() diff --git a/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py b/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py index 63d50005c497..2e790898e683 100644 --- a/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py +++ b/vllm/v1/attention/ops/rocm_aiter_mla_sparse.py @@ -29,6 +29,8 @@ logger = init_logger(__name__) +FP8_DTYPE = current_platform.fp8_dtype() + @functools.cache def _get_aiter_topk_ops() -> tuple[Callable[..., None], Callable[..., None]] | None: @@ -260,8 +262,7 @@ def indexer_k_quant_and_cache_triton( # In real layout, we store the first portion as kv cache value # and second portion as kv cache scale kv_cache = kv_cache.view(num_blocks, -1) - fp8_dtype = current_platform.fp8_dtype() - kv_cache_value = kv_cache[:, : block_size * head_dim].view(fp8_dtype) + kv_cache_value = kv_cache[:, : block_size * head_dim].view(FP8_DTYPE) kv_cache_scale = kv_cache[:, block_size * head_dim :].view(torch.float32) head_tile_size = head_tile_size // kv_cache.element_size() layout = "NORMAL" if block_size == 1 else "SHUFFLE" @@ -279,7 +280,7 @@ def indexer_k_quant_and_cache_triton( layout, block_tile_size, head_tile_size, - IS_FNUZ=current_platform.fp8_dtype() == torch.float8_e4m3fnuz, + IS_FNUZ=torch.float8_e4m3fnuz == FP8_DTYPE, USE_UE8M0=scale_fmt == "ue8m0", ) @@ -465,8 +466,7 @@ def cp_gather_indexer_k_quant_cache_triton( num_blocks = k_cache.shape[0] # we assume the kv cache already been split to 2 portion k_cache = k_cache.view(num_blocks, -1) - fp8_dtype = current_platform.fp8_dtype() - k_cache_value = k_cache[:, : block_size * head_dim].view(fp8_dtype) + k_cache_value = k_cache[:, : block_size * head_dim].view(FP8_DTYPE) k_cache_scale = k_cache[:, block_size * head_dim :].view(torch.float32) grid = (num_tokens,) k_fp8_scale = k_fp8_scale.view(torch.float32) @@ -516,7 +516,6 @@ def fp8_paged_mqa_logits_torch( ): from vllm.utils.math_utils import cdiv - fp8_dtype = current_platform.fp8_dtype() batch_size, next_n, _, dim = q.size() if next_n == 1: block_size = kv_cache.shape[1] @@ -540,7 +539,7 @@ def fp8_paged_mqa_logits_torch( cache = kv_cache_flat[pages] scale_offset = block_size * dim cache_value = ( - cache[..., :scale_offset].view(dtype=fp8_dtype).to(torch.float32) + cache[..., :scale_offset].view(dtype=FP8_DTYPE).to(torch.float32) ) cache_scale = ( cache[..., scale_offset:].view(dtype=torch.float32).contiguous() @@ -558,7 +557,7 @@ def fp8_paged_mqa_logits_torch( kv_cache, scale = kv_cache[..., :dim], kv_cache[..., dim:] scale = scale.contiguous().view(torch.float) q = q.float() - kv_cache = kv_cache.view(fp8_dtype).float() * scale + kv_cache = kv_cache.view(FP8_DTYPE).float() * scale num_block, block_size, _, dim = kv_cache.size() logits = torch.full( [batch_size * next_n, max_model_len], @@ -1021,7 +1020,6 @@ def rocm_aiter_sparse_attn_indexer( # careful! this will be None in dummy run forward_context = get_forward_context() attn_metadata = forward_context.attn_metadata - fp8_dtype = current_platform.fp8_dtype() from vllm.utils.torch_utils import _resolve_layer_name k_cache_prefix = _resolve_layer_name(k_cache_prefix) @@ -1037,7 +1035,7 @@ def rocm_aiter_sparse_attn_indexer( # Prefill k_fp8 and k_scale buffers, used by # rocm_aiter_sparse_attn_indexer's prefill path workspace_manager.get_simultaneous( - ((total_seq_lens, head_dim), fp8_dtype), + ((total_seq_lens, head_dim), FP8_DTYPE), ((total_seq_lens, 4), torch.uint8), ) @@ -1117,7 +1115,7 @@ def rocm_aiter_sparse_attn_indexer( workspace_manager = current_workspace_manager() k_fp8_full, k_scale_full = workspace_manager.get_simultaneous( - ((total_seq_lens, head_dim), fp8_dtype), + ((total_seq_lens, head_dim), FP8_DTYPE), ((total_seq_lens, 4), torch.uint8), ) for chunk in prefill_metadata.chunks: