From 29fd39dff5a66c73ba89d9f37b042a55503bc11a Mon Sep 17 00:00:00 2001 From: Lucas Wilkinson Date: Thu, 17 Sep 2026 09:04:26 -0500 Subject: [PATCH 1/5] [PCP][DCP] Support DCP target model with non-DCP Dspark (#56723) Net diff of vllm-project/vllm#56723 at 903e47e4fd, applied unchanged as the base for the ROCm moonmath DCP change; it is not part of that PR. Signed-off-by: Lucas Wilkinson --- tests/v1/attention/test_attention_backends.py | 3 +- tests/v1/core/test_kv_cache_utils.py | 151 ++++++++++++++++-- tests/v1/core/test_prefix_caching.py | 19 ++- .../draft_model/test_draft_model.py | 33 ++++ .../unit/test_decode_bench_connector.py | 3 +- tests/v1/simple_kv_offload/test_scheduler.py | 4 +- .../spec_decode/test_dflash_prepare_inputs.py | 91 +++++++---- .../test_eagle_draft_attn_metadata.py | 10 +- tests/v1/worker/test_cp_utils.py | 34 ++++ tests/v1/worker/test_dspark_utils.py | 71 ++++++++ tests/v1/worker/test_gpu_block_table.py | 16 +- tests/v1/worker/test_gpu_pcp_manager.py | 18 +++ .../kv_connector/v1/decode_bench_connector.py | 9 +- .../layers/attention/attention.py | 6 + vllm/v1/attention/backend.py | 19 ++- vllm/v1/attention/backends/flash_attn.py | 12 +- vllm/v1/attention/backends/flashinfer.py | 40 +++-- vllm/v1/attention/backends/utils.py | 24 ++- vllm/v1/core/kv_cache_coordinator.py | 26 +-- vllm/v1/core/kv_cache_utils.py | 95 +++++------ vllm/v1/core/single_type_kv_cache_manager.py | 12 +- vllm/v1/kv_cache_interface.py | 37 +++-- vllm/v1/simple_kv_offload/manager.py | 8 +- vllm/v1/spec_decode/draft_model.py | 9 +- vllm/v1/worker/cp_utils.py | 2 + vllm/v1/worker/gpu/block_table.py | 11 ++ vllm/v1/worker/gpu/model_runner.py | 3 + vllm/v1/worker/gpu/pcp_manager.py | 5 +- .../gpu/spec_decode/dflash/speculator.py | 20 ++- vllm/v1/worker/gpu/spec_decode/speculator.py | 7 +- 30 files changed, 588 insertions(+), 210 deletions(-) diff --git a/tests/v1/attention/test_attention_backends.py b/tests/v1/attention/test_attention_backends.py index b02c85f68202..6a482ff16b7c 100644 --- a/tests/v1/attention/test_attention_backends.py +++ b/tests/v1/attention/test_attention_backends.py @@ -938,8 +938,6 @@ def test_flashinfer_xqa_single_token_decode_preserves_cudagraph_padding(monkeypa impl.o_sf_scale = None impl.window_left = -1 impl.sinks = None - impl.cache_config = unittest.mock.Mock() - impl.cache_config.get_resolved_kv_cache_layout.return_value = KVCacheLayout.LBHNC layer = unittest.mock.Mock( _q_scale=torch.tensor(1.0), @@ -955,6 +953,7 @@ def test_flashinfer_xqa_single_token_decode_preserves_cudagraph_padding(monkeypa q_len_per_req=1, ) attn_metadata = flashinfer_backend.FlashInferMetadata( + kv_cache_layout=KVCacheLayout.LBHNC, num_actual_tokens=2, slot_mapping=torch.empty(0, dtype=torch.int64), q_data_type_prefill=torch.bfloat16, diff --git a/tests/v1/core/test_kv_cache_utils.py b/tests/v1/core/test_kv_cache_utils.py index 3c82180474f6..e74fed35fd0d 100644 --- a/tests/v1/core/test_kv_cache_utils.py +++ b/tests/v1/core/test_kv_cache_utils.py @@ -1552,19 +1552,138 @@ def test_project_kv_cache_groups_to_worker(): assert set(proj_spec.kv_cache_specs.keys()) == {"layer1", "layer3"} -def test_dcp_world_size_for_kv_cache_spec_shards_full_attention_only(): - dcp = 8 - full = FullAttentionSpec( - block_size=16, num_kv_heads=1, head_size=1, dtype=torch.float32 +@pytest.mark.parametrize("sliding_window", [None, 256]) +@pytest.mark.parametrize("disable_hybrid", [False, True]) +@pytest.mark.parametrize("pcp_size", [1, 4]) +def test_dcp_target_allocates_replicated_draft_independently( + monkeypatch, sliding_window, disable_hybrid, pcp_size +): + """A draft must retain all positions even when the target shards them.""" + from vllm.v1.attention.backends.utils import resolve_kv_cache_layout + + monkeypatch.delenv("VLLM_KV_CACHE_LAYOUT", raising=False) + config = VllmConfig(model_config=ModelConfig(max_model_len=1024)) + config.parallel_config.decode_context_parallel_size = 4 + config.parallel_config.prefill_context_parallel_size = pcp_size + config.scheduler_config.disable_hybrid_kv_cache_manager = disable_hybrid + config.cache_config.block_size = 16 + config.cache_config.kv_cache_layout = None + draft_args = dict( + block_size=16, + num_kv_heads=8, + head_size=64, + dtype=torch.bfloat16, + dcp_sharded=False, + ) + draft = ( + FullAttentionSpec(**draft_args) + if sliding_window is None + else SlidingWindowSpec(**draft_args, sliding_window=sliding_window) ) - mla = new_mla_spec() - mamba = new_mamba_spec() - uniform_mla = UniformTypeKVCacheSpecs(block_size=16, kv_cache_specs={"layer": mla}) - assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(full, dcp) == dcp - assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(mla, dcp) == dcp - assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(uniform_mla, dcp) == dcp - assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(mamba, dcp) == 1 - assert kv_cache_utils.dcp_world_size_for_kv_cache_spec(full, 1) == 1 + specs = {"target": new_mla_spec(), "draft": draft} + layout = resolve_kv_cache_layout(config, [["LBHNC", "BLHNC"]], specs.values()) + assert layout == KVCacheLayout.BLHNC + groups = get_kv_cache_groups(config, specs) + assert [group.layer_names for group in groups] == [["target"], ["draft"]] + widths = [g.kv_cache_spec.max_num_blocks_per_req(config, 1024) for g in groups] + assert widths == [16, 64] + + cache_config = kv_cache_utils.get_kv_cache_config_from_groups( + config, groups, available_memory=16 * 1024 * 1024 + ) + scheduler_config = generate_scheduler_kv_cache_config([cache_config]) + assert get_max_concurrency_for_kv_cache_config(config, cache_config) > 0 + assert get_max_concurrency_for_kv_cache_config(config, cache_config) == ( + get_max_concurrency_for_kv_cache_config(config, scheduler_config) + ) + manager = KVCacheManager( + scheduler_config, + max_model_len=1024, + hash_block_size=16, + scheduler_block_size=64, + dcp_world_size=4, + pcp_world_size=pcp_size, + enable_caching=True, + ) + assert manager.coordinator.group_block_sizes == (64, 16) + request = make_request("replicated-draft", [1] * 65, block_size=16, hash_fn=sha256) + blocks = manager.allocate_slots(request, 65) + assert blocks is not None + assert [len(group) for group in blocks.blocks] == [2, 5] + manager.cache_blocks(request, 64) + cached_request = make_request( + "cached-draft", [1] * 65, block_size=16, hash_fn=sha256 + ) + cached_blocks, num_cached, _ = manager.get_computed_blocks(cached_request) + assert num_cached == 64 + assert [len(group) for group in cached_blocks.blocks] == [1, 4] + + +@pytest.mark.parametrize("use_mla", [False, True]) +def test_full_attention_merge_preserves_replicated_cache_geometry(use_mla): + config = VllmConfig(model_config=ModelConfig(max_model_len=1024)) + config.parallel_config.decode_context_parallel_size = 4 + draft = replace( + new_mla_spec() if use_mla else new_kv_cache_spec(), + block_size=16, + dcp_sharded=False, + ) + merged = type(draft).merge([draft, draft]) + wrapped = UniformTypeKVCacheSpecs.from_specs({"draft": merged}) + assert wrapped is not None and not wrapped.dcp_sharded + assert merged.max_num_blocks_per_req(config, 1024) == 64 + assert merged.max_memory_usage_bytes(config) == 64 * draft.page_size_bytes + assert kv_cache_utils.resolve_dcp_kv_block_size(merged, 4) == 16 + with pytest.raises(AssertionError): + type(draft).merge([draft, replace(draft, dcp_sharded=True)]) + + +@pytest.mark.parametrize("with_draft", [False, True]) +def test_sparse_mla_preserves_physical_row_addressing(with_draft): + from vllm.v1.attention.backends.mla.sparse_utils import flat_kv_row_view + from vllm.v1.worker.utils import allocate_kv_cache + + config = VllmConfig(model_config=ModelConfig(max_model_len=1024)) + config.cache_config.kv_cache_layout = "BLHNC" + config.parallel_config.decode_context_parallel_size = 4 + common = dict(block_size=64, num_kv_heads=1, dtype=torch.uint8) + specs = { + "target": MLAAttentionSpec( + **common, + head_size=576, + state_content_bytes=656, + cache_dtype_str="fp8_ds_mla", + is_index_group_leader=True, + ), + "indexer": MLAAttentionSpec( + **common, + head_size=132, + cache_role=SparseCacheRole.INDEXER, + ), + "draft": SlidingWindowSpec( + block_size=64, + num_kv_heads=64, + head_size=64, + dtype=torch.bfloat16, + sliding_window=2048, + dcp_sharded=False, + ), + } + if not with_draft: + del specs["draft"] + groups = get_kv_cache_groups(config, specs) + cache_config = kv_cache_utils.get_kv_cache_config_from_groups( + config, groups, available_memory=8 * 1024 * 1024 + ) + caches = allocate_kv_cache( + cache_config, torch.device("cpu"), KVCacheLayout.BLHNC, [64] * len(groups) + ) + for name in ("target", "indexer"): + cache = caches[name].squeeze(1) + rows, stride_rows = flat_kv_row_view(cache, 64) + cache[1, 0].fill_(7) + torch.testing.assert_close(rows[stride_rows], cache[1, 0]) + assert torch.all(rows[stride_rows] == 7) @pytest.mark.parametrize( @@ -3768,6 +3887,8 @@ def test_unify_hybrid_kv_cache_specs(): "layer_1": before_spec_1, "layer_2": before_spec_2, } + kv_cache_spec["draft_layer_1"] = replace(before_spec_1, dcp_sharded=False) + kv_cache_spec["draft_layer_2"] = replace(before_spec_2, dcp_sharded=False) kv_cache_utils.unify_hybrid_kv_cache_specs(kv_cache_spec) expected_spec_1 = new_kv_cache_spec(block_size=64) expected_spec_2 = new_kv_cache_spec( @@ -3776,6 +3897,7 @@ def test_unify_hybrid_kv_cache_specs(): assert kv_cache_spec["layer_1"] == expected_spec_1 assert kv_cache_spec["layer_2"] == expected_spec_2 assert kv_cache_spec["layer_2"].page_size_bytes == 64 * 1024 + assert kv_cache_spec["draft_layer_2"] == replace(expected_spec_2, dcp_sharded=False) # 2. has_full_attention and has_chunked_local_attention before_spec_1 = new_kv_cache_spec() @@ -3827,6 +3949,11 @@ def test_unify_hybrid_kv_cache_specs(): with pytest.raises(ValueError): kv_cache_utils.unify_hybrid_kv_cache_specs(kv_cache_spec) + # Replicated Mamba state still requires the hybrid cache manager. + kv_cache_spec = {"attention": new_kv_cache_spec(), "mamba": new_mamba_spec()} + with pytest.raises(ValueError): + kv_cache_utils.unify_hybrid_kv_cache_specs(kv_cache_spec) + def test_unify_kv_cache_spec_page_size_mamba(): """Regression test for https://github.com/vllm-project/vllm/issues/43626. diff --git a/tests/v1/core/test_prefix_caching.py b/tests/v1/core/test_prefix_caching.py index 01bf73b6e7fa..c569cc9b2feb 100644 --- a/tests/v1/core/test_prefix_caching.py +++ b/tests/v1/core/test_prefix_caching.py @@ -1248,12 +1248,12 @@ def make_kv_cache_config_three_types( ) -def test_prefix_cache_hit_uses_per_group_dcp_geometry(): +@pytest.mark.parametrize("draft_sharded", [True, False]) +def test_prefix_cache_hit_uses_per_group_dcp_geometry(draft_sharded): """Prefix lookup must use each group's DCP size, not the process-wide one. - Target and draft MLA are both sharded (DCP=8); Mamba stays replicated - (DCP=1). Hits then align to the sharded full-attention block, not the - unsharded page size. + Target MLA is sharded; draft MLA can opt out and Mamba stays replicated. + Hits must align to the target block in either case. """ block_size = 16 dcp = 8 @@ -1274,6 +1274,7 @@ def test_prefix_cache_hit_uses_per_group_dcp_geometry(): KVCacheGroupSpec( ["draft_mla"], MLAAttentionSpec( + dcp_sharded=draft_sharded, block_size=block_size, num_kv_heads=1, head_size=1, @@ -1300,10 +1301,10 @@ def test_prefix_cache_hit_uses_per_group_dcp_geometry(): ) target_mgr, draft_mgr, mamba_mgr = manager.coordinator.single_type_managers assert target_mgr.dcp_world_size == dcp - assert draft_mgr.dcp_world_size == dcp + assert draft_mgr.dcp_world_size == (dcp if draft_sharded else 1) assert mamba_mgr.dcp_world_size == 1 assert target_mgr.block_size == sharded_block - assert draft_mgr.block_size == sharded_block + assert draft_mgr.block_size == (sharded_block if draft_sharded else block_size) assert mamba_mgr.block_size == block_size hash_fn = sha256 @@ -1319,7 +1320,11 @@ def test_prefix_cache_hit_uses_per_group_dcp_geometry(): req1 = make_request("1", common_token_ids + [100] * 5, block_size, hash_fn) computed_blocks, num_computed_tokens, _ = manager.get_computed_blocks(req1) assert num_computed_tokens == 2 * sharded_block - assert [len(group) for group in computed_blocks.blocks] == [2, 2, 16] + assert [len(group) for group in computed_blocks.blocks] == [ + 2, + 2 if draft_sharded else 16, + 16, + ] manager.free(req0) manager.free(req1) diff --git a/tests/v1/e2e/spec_decode/draft_model/test_draft_model.py b/tests/v1/e2e/spec_decode/draft_model/test_draft_model.py index 3a474ac2039c..d2c2ac87b786 100644 --- a/tests/v1/e2e/spec_decode/draft_model/test_draft_model.py +++ b/tests/v1/e2e/spec_decode/draft_model/test_draft_model.py @@ -11,6 +11,7 @@ from vllm.config.kernel import MoEBackend from vllm.engine.arg_utils import EngineArgs from vllm.platforms import current_platform +from vllm.v1.spec_decode.draft_model import DraftModelProposer from ..utils import ( Messages, @@ -196,6 +197,38 @@ def test_draft_model_engine_args_tensor_parallelism(): assert draft_config.quant_config is None +@pytest.mark.cpu_test +@pytest.mark.parametrize("dcp_size", [1, 2]) +def test_draft_model_inherits_target_dcp_config(monkeypatch, dcp_size): + monkeypatch.setattr(current_platform, "device_count", lambda: 16) + target_config = EngineArgs( + model="Qwen/Qwen3-1.7B", + tensor_parallel_size=16, + decode_context_parallel_size=dcp_size, + cp_kv_cache_interleave_size=16, + dcp_comm_backend="ag_rs", + distributed_executor_backend="mp", + speculative_config={ + "model": "Qwen/Qwen3-0.6B", + "method": "draft_model", + "num_speculative_tokens": 3, + }, + ).create_engine_config() + proposer = object.__new__(DraftModelProposer) + proposer.vllm_config = target_config + proposer.speculative_config = target_config.speculative_config + draft_config = proposer._create_draft_vllm_config() + draft_parallel = draft_config.parallel_config + assert draft_parallel.decode_context_parallel_size == dcp_size + assert draft_parallel.cp_kv_cache_interleave_size == 16 + assert draft_parallel.dcp_comm_backend == "ag_rs" + assert ( + draft_parallel.dcp_q_replicate == target_config.parallel_config.dcp_q_replicate + ) + assert draft_parallel is not target_config.parallel_config + assert target_config.parallel_config.decode_context_parallel_size == dcp_size + + def _apply_draft_moe_backend(vllm_config: VllmConfig) -> VllmConfig: """Replicate SpecDecodeBaseProposer._create_draft_vllm_config logic so we can test it without instantiating a full proposer.""" diff --git a/tests/v1/kv_connector/unit/test_decode_bench_connector.py b/tests/v1/kv_connector/unit/test_decode_bench_connector.py index e1054d9ef86f..6fb39be3cf10 100644 --- a/tests/v1/kv_connector/unit/test_decode_bench_connector.py +++ b/tests/v1/kv_connector/unit/test_decode_bench_connector.py @@ -491,7 +491,7 @@ def test_decode_bench_connector_skips_null_padding(): def test_decode_bench_connector_uses_per_group_dcp_block_sizes(): - """DCP scales full-attention blocks but not sliding-window blocks.""" + """DCP scales target blocks but not the replicated draft's window.""" block_size = 16 dcp_world_size = 2 vllm_config = create_vllm_config( @@ -506,6 +506,7 @@ def test_decode_bench_connector_uses_per_group_dcp_block_sizes(): dtype=torch.float32, ) sliding_window = SlidingWindowSpec( + dcp_sharded=False, block_size=block_size, num_kv_heads=1, head_size=1, diff --git a/tests/v1/simple_kv_offload/test_scheduler.py b/tests/v1/simple_kv_offload/test_scheduler.py index ffc8b204787f..12c9bdfa7b02 100644 --- a/tests/v1/simple_kv_offload/test_scheduler.py +++ b/tests/v1/simple_kv_offload/test_scheduler.py @@ -2214,8 +2214,8 @@ def _make_hybrid_attention_mamba_scheduler( def test_hybrid_store_uses_resolved_group_block_sizes() -> None: """Replicated groups must not be scaled by the DCP world size. - ``dcp_world_size_for_kv_cache_spec`` gives full attention the process DCP - size and every other spec 1. Reconstructing a group's geometry as + The spec's ``dcp_sharded`` flag controls its effective block size. + Reconstructing a group's geometry as ``spec.block_size * cp_world_size`` over-scales the replicated groups, so the eager store scan believes far fewer of their blocks are ready and silently offloads only a fraction of them. diff --git a/tests/v1/spec_decode/test_dflash_prepare_inputs.py b/tests/v1/spec_decode/test_dflash_prepare_inputs.py index 16d6d8e516df..d69f3d1b2b91 100644 --- a/tests/v1/spec_decode/test_dflash_prepare_inputs.py +++ b/tests/v1/spec_decode/test_dflash_prepare_inputs.py @@ -9,7 +9,7 @@ from vllm.v1.attention.backends.utils import PAD_SLOT_ID from vllm.v1.worker.gpu.spec_decode.dflash.speculator import ( - prepare_dflash_inputs, + DFlashSpeculator, ) pytestmark = pytest.mark.skipif( @@ -24,6 +24,7 @@ def _run_prepare( cp_rank: int = 0, cp_size: int = 1, cp_interleave: int = 1, + draft_dcp_size: int | None = None, ): device = torch.device("cuda") max_num_reqs = 4 @@ -40,7 +41,9 @@ def _run_prepare( ) input_batch = SimpleNamespace( num_reqs=1, + num_tokens=4, num_scheduled_tokens=np.array([4], dtype=np.int32), + seq_lens_cpu_upper_bound=torch.tensor([target_positions[-1] + 1]), positions=torch.tensor(target_positions, dtype=torch.int64, device=device), query_start_loc=torch.tensor([0, 4], dtype=torch.int32, device=device), idx_mapping=torch.tensor([2], dtype=torch.int32, device=device), @@ -74,36 +77,59 @@ def _run_prepare( next_prefill_tokens = torch.zeros_like(last_sampled) block_table = torch.tensor([block_table_values], dtype=torch.int32, device=device) - prepare_dflash_inputs( - input_buffers, - query_slot_mapping, - context_positions, - context_slot_mapping, - sample_indices, - sample_pos, - sample_idx_mapping, - temperature, - seeds, - input_batch, - torch.tensor([1], dtype=torch.int32, device=device), - torch.tensor([2], dtype=torch.int32, device=device), - last_sampled, - next_prefill_tokens, - input_temperature, - input_seeds, - block_table, - 4, - cp_rank, - cp_size, - cp_interleave, - 123, - num_speculative_steps, - num_speculative_steps, - max_num_reqs, - max_num_tokens, - 128, + class InputsPrepared(Exception): + pass + + def stop_before_model(*args): + raise InputsPrepared + + draft = SimpleNamespace( + input_buffers=input_buffers, + context_positions=context_positions, + _context_slot_mappings=context_slot_mapping.unsqueeze(0), + sample_indices=sample_indices, + sample_pos=sample_pos, + sample_idx_mapping=sample_idx_mapping, + temperature=temperature, + seeds=seeds, + hidden_states=torch.zeros(4, 1, device=device), + model=SimpleNamespace(precompute_and_store_context_kv=stop_before_model), + pcp_manager=None, + draft_kv_cache_group_id=0, + draft_kv_cache_group_ids=[0], + _layer_group_idx=None, + block_tables=SimpleNamespace( + slot_mappings=query_slot_mapping.unsqueeze(0), + input_block_tables=[block_table], + kernel_block_sizes=[4], + cp_rank=cp_rank, + cp_size=cp_size, + cp_interleave=cp_interleave, + ), + dcp_size=cp_size if draft_dcp_size is None else draft_dcp_size, + parallel_drafting_token_id=123, + num_query_per_req=num_speculative_steps, + num_speculative_steps=num_speculative_steps, + max_num_reqs=max_num_reqs, + max_num_tokens=max_num_tokens, + max_model_len=128, sample_from_anchor=True, ) + with pytest.raises(InputsPrepared): + DFlashSpeculator.propose( + draft, + input_batch, + {}, + {}, + draft.hidden_states, + None, + torch.tensor([1], dtype=torch.int32, device=device), + torch.tensor([2], dtype=torch.int32, device=device), + last_sampled, + next_prefill_tokens, + input_temperature, + input_seeds, + ) torch.accelerator.synchronize() return SimpleNamespace( input_buffers=input_buffers, @@ -118,12 +144,17 @@ def _run_prepare( ) -def test_prepare_dflash_inputs_excludes_rejected_context_suffix(): +@pytest.mark.parametrize("cp_rank,cp_size", [(0, 1), (0, 2), (1, 2)]) +def test_prepare_dflash_inputs_excludes_rejected_context_suffix(cp_rank, cp_size): # Positions 10/11 use physical block 7. Rejected positions 12/13 would use # block 8, but must be PAD context rather than contaminating draft KV. out = _run_prepare( target_positions=[10, 11, 12, 13], block_table_values=[0, 0, 7, 8, 9, 10, 11, 12], + cp_rank=cp_rank, + cp_size=cp_size, + cp_interleave=2, + draft_dcp_size=1, ) assert out.context_positions[:4].tolist() == [10, 11, 0, 0] diff --git a/tests/v1/spec_decode/test_eagle_draft_attn_metadata.py b/tests/v1/spec_decode/test_eagle_draft_attn_metadata.py index 0cc78f3371c2..5c768924c73b 100644 --- a/tests/v1/spec_decode/test_eagle_draft_attn_metadata.py +++ b/tests/v1/spec_decode/test_eagle_draft_attn_metadata.py @@ -17,6 +17,7 @@ from unittest.mock import patch import numpy as np +import pytest import torch from vllm.config.compilation import CUDAGraphMode @@ -53,6 +54,7 @@ def _make_fake_speculator( arange_np=np.arange(max_num_reqs + 1, dtype=np.int32), draft_is_prefilling=torch.zeros(max_num_reqs, dtype=torch.bool), block_tables=fake_block_tables, + dcp_size=1, input_buffers=fake_input_buffers, attn_groups=[], kv_cache_config=SimpleNamespace(kv_cache_groups=[]), @@ -152,14 +154,17 @@ def test_build_draft_attn_metadata_clamps_to_max_model_len(): assert torch.equal(bound, torch.tensor([1024, 503], dtype=torch.int32)) -def test_build_draft_attn_metadata_recomputes_dcp_local_seq_lens(): +@pytest.mark.parametrize("draft_dcp_size", [1, 2]) +def test_build_draft_attn_metadata_recomputes_dcp_local_seq_lens(draft_dcp_size): fake = _make_fake_speculator() + fake.dcp_size = draft_dcp_size fake.block_tables.cp_size = 2 fake.block_tables.cp_rank = 1 fake.block_tables.cp_interleave = 4 fake.input_buffers.seq_lens[:3] = torch.tensor([5, 9, 16]) def fake_prepare(out, seq_lens, num_reqs, dcp_size, dcp_rank, cp_interleave): + assert draft_dcp_size > 1 assert seq_lens is fake.input_buffers.seq_lens assert (num_reqs, dcp_size, dcp_rank, cp_interleave) == (3, 2, 1, 4) out[:num_reqs].copy_(torch.tensor([1, 4, 8], dtype=torch.int32)) @@ -178,6 +183,9 @@ def fake_prepare(out, seq_lens, num_reqs, dcp_size, dcp_rank, cp_interleave): ) local = captured["dcp_local_seq_lens"] + if draft_dcp_size == 1: + assert local is None + return assert isinstance(local, torch.Tensor) assert local.data_ptr() == fake.input_buffers.dcp_local_seq_lens.data_ptr() assert local.tolist() == [1, 4, 8, 0] diff --git a/tests/v1/worker/test_cp_utils.py b/tests/v1/worker/test_cp_utils.py index b38ae4d0636c..d477ace479b9 100644 --- a/tests/v1/worker/test_cp_utils.py +++ b/tests/v1/worker/test_cp_utils.py @@ -1,5 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project +from types import SimpleNamespace + import pytest import torch @@ -7,6 +9,38 @@ from vllm.v1.worker.cp_utils import should_skip_dcp_context_attention +def test_cp_checks_allow_a_replicated_draft_backend_without_dcp(monkeypatch): + from vllm.v1.worker import cp_utils + + config = SimpleNamespace( + parallel_config=SimpleNamespace( + prefill_context_parallel_size=1, + decode_context_parallel_size=4, + cp_kv_cache_interleave_size=16, + ), + speculative_config=object(), + ) + target = SimpleNamespace( + impl=SimpleNamespace( + dcp_world_size=4, + supports_mtp_with_cp_non_trivial_interleave_size=True, + need_to_return_lse_for_decode=True, + ) + ) + draft = SimpleNamespace( + impl=SimpleNamespace( + dcp_world_size=1, + supports_mtp_with_cp_non_trivial_interleave_size=False, + need_to_return_lse_for_decode=False, + ) + ) + layers = {"target": target, "draft": draft} + monkeypatch.setattr(cp_utils, "get_layers_from_vllm_config", lambda *args: layers) + cp_utils.check_attention_cp_compatibility(config, target_layer_names={"target"}) + with pytest.raises(AssertionError, match="MTP with cp_kv_cache_interleave_size"): + cp_utils.check_attention_cp_compatibility(config) + + def test_skip_gate_only_for_zero_context(): assert should_skip_dcp_context_attention(torch.zeros(3, dtype=torch.int32)) assert not should_skip_dcp_context_attention( diff --git a/tests/v1/worker/test_dspark_utils.py b/tests/v1/worker/test_dspark_utils.py index 94655f192c89..1906b858f647 100644 --- a/tests/v1/worker/test_dspark_utils.py +++ b/tests/v1/worker/test_dspark_utils.py @@ -2,8 +2,14 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass, field +from types import SimpleNamespace +import pytest + +from vllm.config import ParallelConfig +from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator from vllm.v1.worker.gpu.spec_decode.dspark.utils import _get_dspark_parallel_config +from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator @dataclass @@ -49,3 +55,68 @@ def test_dspark_parallel_config_disables_eplb_atomically(): assert draft_config.eplb_config.num_redundant_experts == 0 assert not draft_config.enable_elastic_ep assert draft_config.eplb_config is not target_config.eplb_config + + +@pytest.mark.parametrize("pcp_size", [1, 4]) +@pytest.mark.parametrize("dcp_size", [1, 4]) +@pytest.mark.parametrize("use_mla", [False, True]) +def test_draft_context_parallelism_without_changing_target( + monkeypatch, pcp_size, dcp_size, use_mla +): + target_parallel = ParallelConfig( + tensor_parallel_size=4, + prefill_context_parallel_size=pcp_size, + decode_context_parallel_size=dcp_size, + cp_kv_cache_interleave_size=16, + distributed_executor_backend="mp", + ) + target_config = SimpleNamespace( + parallel_config=target_parallel, + speculative_config=SimpleNamespace( + draft_model_config=SimpleNamespace(use_mla=use_mla) + ), + ) + + class CapturedConfig(Exception): + pass + + def capture_init(self, config, device): + raise CapturedConfig(config) + + monkeypatch.setattr(DraftModelSpeculator, "__init__", capture_init) + with pytest.raises(CapturedConfig) as captured: + DFlashSpeculator(target_config, device=None) + draft_parallel = captured.value.args[0].parallel_config + assert draft_parallel.tensor_parallel_size == 4 + assert draft_parallel.prefill_context_parallel_size == 1 + assert draft_parallel.decode_context_parallel_size == (dcp_size if use_mla else 1) + assert draft_parallel.cp_kv_cache_interleave_size == 16 + assert target_parallel.prefill_context_parallel_size == pcp_size + assert target_parallel.decode_context_parallel_size == dcp_size + assert target_parallel.cp_kv_cache_interleave_size == 16 + + +@pytest.mark.parametrize("configured_dcp", [1, 4]) +def test_attention_uses_draft_dcp_setting_inside_target_process_group( + monkeypatch, configured_dcp +): + import vllm.config as config_module + from vllm.distributed import parallel_state + from vllm.v1.attention.backend import AttentionImplBase + + config = SimpleNamespace( + parallel_config=SimpleNamespace(decode_context_parallel_size=configured_dcp) + ) + monkeypatch.setattr( + config_module, "get_current_vllm_config_or_none", lambda: config + ) + + def get_dcp_group(): + if configured_dcp == 1: + pytest.fail("Replicated draft should not access the DCP group") + return SimpleNamespace(world_size=4, rank_in_group=2) + + monkeypatch.setattr(parallel_state, "get_dcp_group", get_dcp_group) + impl = AttentionImplBase() + assert impl.dcp_world_size == configured_dcp + assert impl.dcp_rank == (0 if configured_dcp == 1 else 2) diff --git a/tests/v1/worker/test_gpu_block_table.py b/tests/v1/worker/test_gpu_block_table.py index e77156eef901..7ea227e99bd6 100644 --- a/tests/v1/worker/test_gpu_block_table.py +++ b/tests/v1/worker/test_gpu_block_table.py @@ -170,22 +170,23 @@ def test_block_tables_skip_custom_slot_mapping_groups(): @pytest.mark.parametrize("cp_rank", range(4)) def test_dcp_slot_mapping_with_smaller_kernel_blocks(cp_rank: int): - """DCP interleave is expressed in logical-block token coordinates.""" + """Only sharded groups use DCP interleave in logical-block coordinates.""" device = torch.device("cuda") block_tables = BlockTables( - block_sizes=[128], + block_sizes=[128, 128], max_num_reqs=1, max_num_batched_tokens=1024, - max_num_blocks_per_group=[2], + max_num_blocks_per_group=[2, 8], device=device, - kernel_block_sizes=[64], + kernel_block_sizes=[64, 64], + dcp_sharded=[True, False], cp_size=4, cp_rank=cp_rank, cp_interleave=128, ) block_tables.append_block_ids( req_index=0, - new_block_ids=([5, 9],), + new_block_ids=([5, 9], list(range(10, 18))), overwrite=True, ) block_tables.apply_staged_writes() @@ -198,7 +199,7 @@ def test_dcp_slot_mapping_with_smaller_kernel_blocks(cp_rank: int): query_start_loc, positions, num_tokens_padded=1024, - )[0] + ) expected = torch.full((1024,), -1, dtype=torch.int64, device=device) first_start = cp_rank * 128 @@ -209,7 +210,8 @@ def test_dcp_slot_mapping_with_smaller_kernel_blocks(cp_rank: int): expected[second_start : second_start + 128] = torch.arange( 9 * 128, 10 * 128, dtype=torch.int64, device=device ) - assert torch.equal(actual, expected) + assert torch.equal(actual[0], expected) + assert torch.equal(actual[1], positions + 10 * 128) def test_v1_block_table_move_row_clears_vacated_row(): diff --git a/tests/v1/worker/test_gpu_pcp_manager.py b/tests/v1/worker/test_gpu_pcp_manager.py index 2bd7be2cfa34..1018be8b83c1 100644 --- a/tests/v1/worker/test_gpu_pcp_manager.py +++ b/tests/v1/worker/test_gpu_pcp_manager.py @@ -76,6 +76,24 @@ def test_validate_config_rejects_full_graph_for_prefills(): ) +@pytest.mark.parametrize("draft_uses_mla", [False, True]) +@pytest.mark.parametrize("dcp_size", [1, 2, 4]) +def test_validate_config_dcp_for_dspark(draft_uses_mla, dcp_size): + config = _make_config(CUDAGraphMode.NONE) + config.parallel_config.prefill_context_parallel_size = 4 + config.parallel_config.decode_context_parallel_size = dcp_size + config.model_config.hf_text_config.index_topk = 1 + config.speculative_config = SimpleNamespace( + use_dspark=lambda: True, + draft_model_config=SimpleNamespace(use_mla=draft_uses_mla), + ) + if draft_uses_mla and dcp_size == 2: + with pytest.raises(NotImplementedError, match="requires DCP=1 or DCP=PCP"): + PCPManager.validate_config(config, supports_mm_inputs=False) + return + PCPManager.validate_config(config, supports_mm_inputs=False) + + def test_replicated_decode_piecewise_graph_padding(monkeypatch): manager = PCPManager( pcp_world_size=2, diff --git a/vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py b/vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py index cff2367966fc..5fc30894fab3 100644 --- a/vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py +++ b/vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py @@ -48,7 +48,6 @@ from vllm.utils.math_utils import cdiv from vllm.v1.attention.backend import AttentionMetadata from vllm.v1.core.kv_cache_utils import ( - dcp_world_size_for_kv_cache_spec, resolve_dcp_kv_block_size, ) from vllm.v1.kv_cache_interface import CircularBufferSpec, iter_layer_specs @@ -194,13 +193,7 @@ def __init__(self, vllm_config: "VllmConfig", kv_cache_config: "KVCacheConfig"): dcp_world_size = vllm_config.parallel_config.decode_context_parallel_size self.kv_cache_groups = kv_cache_config.kv_cache_groups self.group_block_sizes = tuple( - resolve_dcp_kv_block_size( - group.kv_cache_spec, - dcp_world_size_for_kv_cache_spec( - group.kv_cache_spec, - dcp_world_size, - ), - ) + resolve_dcp_kv_block_size(group.kv_cache_spec, dcp_world_size) for group in self.kv_cache_groups ) diff --git a/vllm/model_executor/layers/attention/attention.py b/vllm/model_executor/layers/attention/attention.py index 79012a4a5cfd..a962a791cf34 100644 --- a/vllm/model_executor/layers/attention/attention.py +++ b/vllm/model_executor/layers/attention/attention.py @@ -602,6 +602,10 @@ def get_attn_backend(self) -> type[AttentionBackend]: def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec | None: # Block size may get updated after model loading, refresh it block_size = vllm_config.cache_config.block_size + dcp_sharded = ( + vllm_config.parallel_config.decode_context_parallel_size == 1 + or self.impl.dcp_world_size > 1 + ) # Encoder-only attention is prefill-only and keeps no autoregressive KV # cache. In hybrid models (e.g. Qwen3.5 / ColQwen3.5: GatedDeltaNet # linear_attention interleaved with full_attention) the runner iterates @@ -654,6 +658,7 @@ def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec | None: head_size_v=self.head_size_v, dtype=self.kv_cache_torch_dtype, kv_quant_mode=quant_mode, + dcp_sharded=dcp_sharded, sliding_window=self.sliding_window, page_size_padded=shared_page, ) @@ -665,6 +670,7 @@ def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec | None: head_size_v=self.head_size_v, dtype=self.kv_cache_torch_dtype, kv_quant_mode=quant_mode, + dcp_sharded=dcp_sharded, ) diff --git a/vllm/v1/attention/backend.py b/vllm/v1/attention/backend.py index afafa3c92565..5cfa36334be7 100644 --- a/vllm/v1/attention/backend.py +++ b/vllm/v1/attention/backend.py @@ -829,15 +829,22 @@ class AttentionImplBase(ABC, Generic[T]): def __new__(cls, *args, **kwargs): # use __new__ so that all subclasses will call this self = super().__new__(cls) - try: - from vllm.distributed.parallel_state import get_dcp_group + from vllm.config import get_current_vllm_config_or_none + from vllm.distributed.parallel_state import get_dcp_group - self.dcp_world_size = get_dcp_group().world_size - self.dcp_rank = get_dcp_group().rank_in_group + config = get_current_vllm_config_or_none() + self.dcp_world_size, self.dcp_rank = 1, 0 + try: + if ( + config is None + or config.parallel_config.decode_context_parallel_size > 1 + ): + dcp_group = get_dcp_group() + self.dcp_world_size = dcp_group.world_size + self.dcp_rank = dcp_group.rank_in_group except AssertionError: # DCP might not be initialized in testing - self.dcp_world_size = 1 - self.dcp_rank = 0 + pass try: from vllm.distributed.parallel_state import get_pcp_group diff --git a/vllm/v1/attention/backends/flash_attn.py b/vllm/v1/attention/backends/flash_attn.py index b57af3fd295e..a4576edf01fa 100755 --- a/vllm/v1/attention/backends/flash_attn.py +++ b/vllm/v1/attention/backends/flash_attn.py @@ -671,15 +671,15 @@ def __init__( num_qo_heads=self.num_heads_q, ) + self.dcp_world_size, self.dcp_rank = 1, 0 try: - from vllm.distributed.parallel_state import get_dcp_group - - self.dcp_world_size = get_dcp_group().world_size - self.dcp_rank = get_dcp_group().rank_in_group + if kv_cache_spec.dcp_sharded: + dcp_group = get_dcp_group() + self.dcp_world_size = dcp_group.world_size + self.dcp_rank = dcp_group.rank_in_group except AssertionError: # DCP might not be initialized in testing - self.dcp_world_size = 1 - self.dcp_rank = 0 + pass # Fused draft decode reuses the captured metadata object across draft # steps. For DCP, build-time host-side decisions such as diff --git a/vllm/v1/attention/backends/flashinfer.py b/vllm/v1/attention/backends/flashinfer.py index 3113c261dd98..5c265ee868b9 100755 --- a/vllm/v1/attention/backends/flashinfer.py +++ b/vllm/v1/attention/backends/flashinfer.py @@ -640,6 +640,7 @@ class FlashInferTrtllmAPIDecode: @dataclass class FlashInferMetadata: + kv_cache_layout: KVCacheLayout num_actual_tokens: int """Total number of tokens in the batch (excluding padding).""" @@ -746,17 +747,19 @@ def __init__( self._decode_cudagraph_max_bs, self.compilation_config.max_cudagraph_capture_size, ) + self.dcp_world_size, self.dcp_rank = 1, 0 + self.dcp_kv_cache_interleave_size = 1 try: - self.dcp_world_size = get_dcp_group().world_size - self.dcp_rank = get_dcp_group().rank_in_group - self.dcp_kv_cache_interleave_size = ( - vllm_config.parallel_config.cp_kv_cache_interleave_size - ) + if kv_cache_spec.dcp_sharded: + dcp_group = get_dcp_group() + self.dcp_world_size = dcp_group.world_size + self.dcp_rank = dcp_group.rank_in_group + self.dcp_kv_cache_interleave_size = ( + vllm_config.parallel_config.cp_kv_cache_interleave_size + ) except AssertionError: # DCP might not be initialized in testing - self.dcp_world_size = 1 - self.dcp_rank = 0 - self.dcp_kv_cache_interleave_size = 1 + pass self.use_dcp = self.dcp_world_size > 1 self.dcp_a2a = ( self.use_dcp and vllm_config.parallel_config.dcp_comm_backend == "a2a" @@ -1385,6 +1388,7 @@ def build( # Leave prefill/decode/cascade_wrapper empty, to be populated # case by case depending on the batch contents and backend selection. attn_metadata = FlashInferMetadata( + kv_cache_layout=self.kv_cache_layout, num_actual_tokens=num_actual_tokens, slot_mapping=common_attn_metadata.slot_mapping, q_data_type_prefill=self.q_data_type_prefill, @@ -1844,8 +1848,6 @@ def __init__( num_heads, num_kv_heads, is_prefill=False ) vllm_config = get_current_vllm_config_or_none() - # The layout is resolved after model construction, so read it lazily. - self.cache_config = vllm_config.cache_config if vllm_config else None # Query pre-quantization needs a single dtype for the whole query tensor. # SM90 XQA needs BF16/FP16-Q for decode and FP8 for prefill, # so only enable this for SM100 trtllm-gen where both use FP8-Q. @@ -1881,11 +1883,6 @@ def __init__( else: self.dcp_combine = partial(cp_lse_ag_out_rs, is_lse_base_on_e=False) - @property - def kv_cache_layout(self) -> KVCacheLayout: - assert self.cache_config is not None - return self.cache_config.get_resolved_kv_cache_layout() - def fused_output_quant_supported(self, quant_key: QuantKey): if quant_key == kNvfp4Dynamic and self.is_kvcache_nvfp4: logger.warning_once( @@ -2051,6 +2048,7 @@ def forward( # performance to make sure it does not introduce any overhead. num_actual_tokens = attn_metadata.num_actual_tokens + kv_cache_layout = attn_metadata.kv_cache_layout # FlashInfer treats uint8 KV cache as NVFP4. vLLM stores FP8 KV cache # as uint8 bytes, so pass FP8 caches with their logical dtype. @@ -2074,7 +2072,7 @@ def forward( if attn_metadata.use_cascade: # Cascade attention (rare case). assert attn_metadata.cascade_wrapper is not None - stride_order = self.kv_cache_layout.layer_view_order + stride_order = kv_cache_layout.layer_view_order if self.is_kvcache_nvfp4: kv_cache_views = tuple( cache.permute(*stride_order) @@ -2094,7 +2092,7 @@ def forward( num_decode_tokens = attn_metadata.num_decode_tokens num_prefill_tokens = attn_metadata.num_prefill_tokens - stride_order = self.kv_cache_layout.layer_view_order + stride_order = kv_cache_layout.layer_view_order kv_cache_permute = kv_cache.permute(*stride_order) # HND and contiguous # Fix degenerate strides on any size-1 dimension (e.g. num_kv_heads=1 # with TP=8). PyTorch permits non-canonical strides on size-1 dims; @@ -2251,7 +2249,7 @@ def forward( seq_lens_prefill = attn_metadata.prefill.seq_lens # This path needs to be enabled with VLLM_KV_CACHE_LAYOUT = HND - assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND" + assert get_flashinfer_layout_string(kv_cache_layout) == "HND" assert is_strictly_contiguous(prefill_query) assert is_strictly_contiguous(workspace_buffer) assert is_strictly_contiguous(block_tables_prefill) @@ -2441,7 +2439,7 @@ def forward( # trtllm-gen needs HND layout on SM100. XQA is selected # separately on SM90 and does not use this SM100 layout gate. if decode_with_trtllm_gen: - assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND" + assert get_flashinfer_layout_string(kv_cache_layout) == "HND" else: assert decode_with_xqa assert is_strictly_contiguous(decode_query) @@ -2487,7 +2485,7 @@ def forward( window_left=self.window_left, out=output_padded[:decode_query_tokens], sinks=self.sinks, - kv_layout=get_flashinfer_layout_string(self.kv_cache_layout), + kv_layout=get_flashinfer_layout_string(kv_cache_layout), q_len_per_req=q_len_per_req, mask=attn_metadata.decode.mask, q_cu_seq_lens=attn_metadata.decode.q_cu_seq_lens, @@ -2554,7 +2552,7 @@ def forward( sinks=self.sinks, o_sf_scale=self.o_sf_scale, out=out, - kv_layout=get_flashinfer_layout_string(self.kv_cache_layout), + kv_layout=get_flashinfer_layout_string(kv_cache_layout), backend=attn_metadata.decode.kernel.value, q_len_per_req=q_len_per_req, max_q_len=max_q_len, diff --git a/vllm/v1/attention/backends/utils.py b/vllm/v1/attention/backends/utils.py index 3413c5ad00ca..a567389e9208 100644 --- a/vllm/v1/attention/backends/utils.py +++ b/vllm/v1/attention/backends/utils.py @@ -21,7 +21,12 @@ from vllm.utils.gpu_sync_debug import gpu_sync_allowed from vllm.utils.math_utils import cdiv from vllm.utils.torch_utils import PIN_MEMORY, async_tensor_h2d, np_to_pinned_tensor -from vllm.v1.kv_cache_interface import KVCacheLayout, KVCacheSpec, MambaSpec +from vllm.v1.kv_cache_interface import ( + AttentionSpec, + KVCacheLayout, + KVCacheSpec, + MambaSpec, +) if TYPE_CHECKING: from vllm.v1.core.sched.output import SchedulerOutput @@ -286,9 +291,10 @@ def resolve_kv_cache_layout( # specs can re-interpret HNC with different sizes as long as the total number of # bytes is the same. If not block-compact, each spec must agree on HNC to alias # the same page (this aliasing is done by the Hybrid Memory Allocator, HMA). + kv_cache_specs = tuple(kv_cache_specs or ()) hnc_shapes = { (spec.num_heads, spec.num_states, spec.page_size_bytes) - for spec in kv_cache_specs or () + for spec in kv_cache_specs } if len(hnc_shapes) > 1: candidates = [m for m in candidates if m.is_block_compact] @@ -298,6 +304,20 @@ def resolve_kv_cache_layout( f"none is in every supported set: {supported_layouts}." ) + dcp_sharding = { + spec.dcp_sharded for spec in kv_cache_specs if isinstance(spec, AttentionSpec) + } + page_sizes = {spec.page_size_bytes for spec in kv_cache_specs} + if len(dcp_sharding) > 1 and len(page_sizes) > 1: + # Sharded target and replicated draft caches need independent groups. + # Block-outer layouts can pack those groups without equalizing pages. + candidates = [layout for layout in candidates if layout.is_block_outermost] + if not candidates: + raise ValueError( + "DCP with a replicated draft and mixed KV page sizes requires " + f"a block-outer KV cache layout; supported sets: {supported_layouts}." + ) + if (requested := envs.VLLM_KV_CACHE_LAYOUT) is not None: layout = _layout_from_name(requested) if layout not in candidates: diff --git a/vllm/v1/core/kv_cache_coordinator.py b/vllm/v1/core/kv_cache_coordinator.py index 8061999409c4..d69b2f5fb348 100644 --- a/vllm/v1/core/kv_cache_coordinator.py +++ b/vllm/v1/core/kv_cache_coordinator.py @@ -11,7 +11,6 @@ from vllm.v1.core.kv_cache_utils import ( BlockHash, KVCacheBlock, - dcp_world_size_for_kv_cache_spec, ) from vllm.v1.core.single_type_kv_cache_manager import ( CrossAttentionManager, @@ -20,6 +19,7 @@ get_manager_for_kv_cache_spec, ) from vllm.v1.kv_cache_interface import ( + AttentionSpec, FullAttentionSpec, KVCacheConfig, KVCacheSpec, @@ -140,9 +140,7 @@ def __init__( role=kv_cache_group.role, enable_caching=enable_caching, kv_cache_group_id=i, - dcp_world_size=dcp_world_size_for_kv_cache_spec( - kv_cache_group.kv_cache_spec, dcp_world_size - ), + dcp_world_size=dcp_world_size, pcp_world_size=pcp_world_size, scheduler_block_size=self.scheduler_block_size, needs_kv_cache_zeroing=self.kv_cache_config.needs_kv_cache_zeroing, @@ -664,16 +662,18 @@ def __init__( f"hash_block_size. block_sizes={cacheable_block_sizes}, " f"hash_block_size={hash_block_size}" ) - assert pcp_world_size == 1, "PCP not support hybrid attn now." - if dcp_world_size > 1: - # DCP shards full-attention KV across ranks and replicates Mamba - # state; other spec types (e.g. sliding window) have no DCP-aware - # handling yet, so reject them explicitly. - for g in kv_cache_config.kv_cache_groups: - assert isinstance(g.kv_cache_spec, (FullAttentionSpec, MambaSpec)), ( + for g in kv_cache_config.kv_cache_groups: + spec = g.kv_cache_spec + replicated = not spec.dcp_sharded + if pcp_world_size > 1: + assert isinstance(spec, FullAttentionSpec) or ( + isinstance(spec, AttentionSpec) and replicated + ), "PCP only supports full attention and replicated draft groups." + if dcp_world_size > 1: + assert isinstance(spec, FullAttentionSpec) or replicated, ( "DCP with hybrid KV cache layouts only supports " - "full-attention and Mamba groups, got: " - f"{type(g.kv_cache_spec).__name__}." + "full-attention, Mamba, and replicated draft groups, got: " + f"{type(spec).__name__}." ) # Fine-grained hash hits require Mamba "align" and compatible cache # managers in every group. TP needs hashing finer than the Mamba block; diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index 656765c89604..74b05038ae7a 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -681,12 +681,7 @@ def hash_block_tokens( def resolve_dcp_kv_block_size(spec: KVCacheSpec, dcp_world_size: int) -> int: """Return the token span of a cache block under DCP.""" - layer_specs = iter_layer_specs(spec) - if len(layer_specs) > 0 and all( - isinstance(layer_spec, AttentionSpec) for layer_spec in layer_specs - ): - return spec.block_size * dcp_world_size - return spec.block_size + return spec.block_size * (dcp_world_size if spec.dcp_sharded else 1) def resolve_dcp_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> KVCacheSpec: @@ -706,28 +701,6 @@ def resolve_dcp_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> KVCache return replace(spec, block_size=block_size) -def dcp_world_size_for_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> int: - """Return the DCP size that owns this group's block geometry. - - Full-attention KV (including MLA) is sharded across DCP ranks, so prefix - hashing and manager ``block_size`` use the process DCP size. Other specs - keep replicated per-rank state (Mamba, sliding window, chunked-local) and - must keep ``dcp_world_size=1`` even when the process runs with DCP > 1. - - Draft MLA groups on the sharded DSpark path are ``FullAttentionSpec`` / - ``MLAAttentionSpec`` and therefore keep the process DCP size. A replicated - draft group would need a different spec, not this helper. - """ - if dcp_world_size <= 1: - return 1 - inner = spec - if isinstance(spec, UniformTypeKVCacheSpecs): - inner = next(iter(spec.kv_cache_specs.values())) - if isinstance(inner, FullAttentionSpec): - return dcp_world_size - return 1 - - def resolve_kv_cache_block_sizes( kv_cache_config: KVCacheConfig, vllm_config: VllmConfig, @@ -751,6 +724,8 @@ def resolve_kv_cache_block_sizes( groups = kv_cache_config.kv_cache_groups if len(groups) <= 1: + if groups and not groups[0].kv_cache_spec.dcp_sharded: + dcp = 1 bs = cache_config.block_size * dcp return bs, bs @@ -1604,23 +1579,25 @@ def _get_kv_cache_bytes_per_block( for group in kv_cache_groups ) assert bytes_per_block > 0 - hot_page_sizes = [ + # Sparse MLA addresses whole rows within the shared pool's block stride. + alignment_sizes = [ + spec.state_content_size_bytes + for group in kv_cache_groups + for spec in iter_layer_specs(group.kv_cache_spec) + if isinstance(spec, MLAAttentionSpec) + ] + alignment_sizes.extend( group.kv_cache_spec.page_size_bytes for group in kv_cache_groups if isinstance(group.kv_cache_spec, HiSparseHotSpec) - ] - if hot_page_sizes: - bytes_per_block = round_up(bytes_per_block, math.lcm(*hot_page_sizes)) - stride_alignments = [ + ) + alignment_sizes.extend( spec.block_stride_alignment for group in kv_cache_groups - for layer_name in group.layer_names - if isinstance(spec := _get_per_layer_spec(group, layer_name), MLAAttentionSpec) - and spec.block_stride_alignment - ] - if stride_alignments: - bytes_per_block = round_up(bytes_per_block, math.lcm(*stride_alignments)) - return bytes_per_block + for spec in iter_layer_specs(group.kv_cache_spec) + if isinstance(spec, MLAAttentionSpec) and spec.block_stride_alignment + ) + return round_up(bytes_per_block, math.lcm(*alignment_sizes)) def validate_kv_cache_layout( @@ -1937,18 +1914,21 @@ def unify_hybrid_kv_cache_specs(kv_cache_spec: dict[str, KVCacheSpec]): kv_cache_spec: The kv cache spec of each attention layer in the model """ - if is_kv_cache_spec_uniform( - kv_cache_spec - ) or UniformTypeKVCacheSpecs.is_uniform_type(kv_cache_spec): - return - - logger.warning( - "Hybrid KV cache manager is disabled for this hybrid model, " - "This means we do not enable any optimizations for saving KV cache " - "memory (e.g., dropping the KV cache outside the sliding window). " - "The compute of layers like sliding window is still saved." - ) - kv_cache_spec.update(_promote_local_kv_cache_specs(kv_cache_spec)) + groups: defaultdict[bool, dict[str, KVCacheSpec]] = defaultdict(dict) + for name, spec in kv_cache_spec.items(): + replicated = isinstance(spec, AttentionSpec) and not spec.dcp_sharded + groups[replicated][name] = spec + for specs in groups.values(): + promoted_specs = _promote_local_kv_cache_specs(specs) + if promoted_specs == specs: + continue + logger.warning( + "Hybrid KV cache manager is disabled for this hybrid model, " + "This means we do not enable any optimizations for saving KV cache " + "memory (e.g., dropping the KV cache outside the sliding window). " + "The compute of layers like sliding window is still saved." + ) + kv_cache_spec.update(promoted_specs) def _approximate_gcd(values: Sequence[int], *, lower_bound: int | None = None) -> int: @@ -2255,10 +2235,15 @@ def _ensure_min_page_size( scaled: list[KVCacheGroupSpec] = [] for g in groups: s = g.kv_cache_spec - kw: dict[str, int] = {"block_size": s.block_size * scale} if isinstance(s, (AttentionSpec, MambaSpec)) and s.page_size_padded is not None: - kw["page_size_padded"] = s.page_size_padded * scale - scaled.append(KVCacheGroupSpec(g.layer_names, replace(s, **kw))) + s = replace( + s, + block_size=s.block_size * scale, + page_size_padded=s.page_size_padded * scale, + ) + else: + s = replace(s, block_size=s.block_size * scale) + scaled.append(KVCacheGroupSpec(g.layer_names, s)) return scaled, common_page diff --git a/vllm/v1/core/single_type_kv_cache_manager.py b/vllm/v1/core/single_type_kv_cache_manager.py index 9ad0a38ed550..cd65135678b3 100644 --- a/vllm/v1/core/single_type_kv_cache_manager.py +++ b/vllm/v1/core/single_type_kv_cache_manager.py @@ -106,11 +106,9 @@ def __init__( # managers have been validated by the coordinator. self.cache_hit_alignment_tokens = scheduler_block_size # The block size for this manager; used for actual block allocation. - self.block_size = kv_cache_spec.block_size - self.dcp_world_size = dcp_world_size - self.pcp_world_size = pcp_world_size - if dcp_world_size > 1: - self.block_size *= dcp_world_size + self.dcp_world_size = dcp_world_size if kv_cache_spec.dcp_sharded else 1 + self.pcp_world_size = pcp_world_size if kv_cache_spec.dcp_sharded else 1 + self.block_size = kv_cache_spec.block_size * self.dcp_world_size self.kv_cache_spec = kv_cache_spec self.block_pool = block_pool self.enable_caching = enable_caching @@ -1453,10 +1451,6 @@ def __init__( self, kv_cache_spec: MambaSpec, block_pool: BlockPool, **kwargs ) -> None: super().__init__(kv_cache_spec, block_pool, **kwargs) - # Mamba layers use TP instead of DCP, so each rank holds the full - # recurrent state. Undo the DCP/PCP block_size scaling that the base - # class applies for attention groups whose KV cache is partitioned. - self.block_size = kv_cache_spec.block_size self.mamba_cache_mode = kv_cache_spec.mamba_cache_mode self.num_speculative_blocks: int = kv_cache_spec.num_speculative_blocks self.has_prefill_checkpoint_blocks = ( diff --git a/vllm/v1/kv_cache_interface.py b/vllm/v1/kv_cache_interface.py index 17771d9ae67a..6dec53b1767e 100644 --- a/vllm/v1/kv_cache_interface.py +++ b/vllm/v1/kv_cache_interface.py @@ -6,7 +6,7 @@ import copy from collections import Counter from collections.abc import Collection, Sequence -from dataclasses import dataclass, fields, replace +from dataclasses import dataclass, field, fields, replace from enum import Enum, IntEnum from fractions import Fraction from functools import cached_property @@ -158,6 +158,8 @@ class KVCacheSpec: # number of tokens in a block block_size: int + dcp_sharded: bool = field(default=False, kw_only=True) + """Whether DCP shards this cache's token positions across ranks.""" @property def prefix_cacheable(self) -> bool: @@ -469,6 +471,7 @@ def has_layer_views(self) -> bool: @dataclass(frozen=True, kw_only=True) class AttentionSpec(KVCacheSpec): + dcp_sharded: bool = True num_kv_heads: int head_size: int dtype: torch.dtype @@ -523,7 +526,9 @@ def real_page_size_bytes(self) -> int: def max_num_blocks_per_req(self, vllm_config: VllmConfig, max_len: int) -> int: parallel_config = vllm_config.parallel_config - kv_shard_count = parallel_config.decode_context_parallel_size + kv_shard_count = ( + parallel_config.decode_context_parallel_size if self.dcp_sharded else 1 + ) return cdiv(max_len, self.block_size * kv_shard_count) @@ -553,11 +558,10 @@ class FullAttentionSpec(AttentionSpec): """ def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: - max_model_len = vllm_config.model_config.max_model_len - dcp_world_size = vllm_config.parallel_config.decode_context_parallel_size - if dcp_world_size > 1: - max_model_len = cdiv(max_model_len, dcp_world_size) - return cdiv(max_model_len, self.block_size) * self.page_size_bytes + max_blocks = self.max_num_blocks_per_req( + vllm_config, vllm_config.model_config.max_model_len + ) + return max_blocks * self.page_size_bytes @classmethod def merge_window_sizes(cls, window_sizes: set[int]) -> int | None: @@ -598,6 +602,7 @@ def merge(cls, specs: list[Self]) -> Self: head_size_v=specs[0].head_size_v, dtype=specs[0].dtype, kv_quant_mode=specs[0].kv_quant_mode, + dcp_sharded=specs[0].dcp_sharded, page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, @@ -690,6 +695,7 @@ def merge(cls, specs: list[Self]) -> Self: head_size=specs[0].head_size, dtype=specs[0].dtype, kv_quant_mode=specs[0].kv_quant_mode, + dcp_sharded=specs[0].dcp_sharded, page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, @@ -751,6 +757,7 @@ def merge(cls, specs: list[RSWASpec]) -> RSWASpec: head_size_v=base.head_size_v, dtype=base.dtype, kv_quant_mode=base.kv_quant_mode, + dcp_sharded=base.dcp_sharded, page_size_padded=base.page_size_padded, num_head_slots=base.num_head_slots, state_content_bytes=base.state_content_bytes, @@ -841,9 +848,10 @@ def max_admission_blocks_per_request( return cdiv(num_tokens, self.block_size) + 1 def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int: - assert vllm_config.parallel_config.decode_context_parallel_size == 1, ( - "DCP not support sliding window." - ) + assert ( + not self.dcp_sharded + or vllm_config.parallel_config.decode_context_parallel_size == 1 + ), "DCP not support sliding window." max_blocks = self.max_admission_blocks_per_request( max_in_flight_tokens=vllm_config.max_in_flight_tokens, max_model_len=vllm_config.model_config.max_model_len, @@ -930,6 +938,7 @@ def merge(cls, specs: list[Self]) -> Self: model_version_set = set(spec.model_version for spec in specs) sliding_window_set = set(spec.sliding_window for spec in specs) extra_retained_set = set(spec.extra_retained_tokens for spec in specs) + assert len({spec.dcp_sharded for spec in specs}) == 1 assert ( len(cache_dtype_str_set) == 1 and len(tokens_per_state_set) == 1 @@ -946,6 +955,7 @@ def merge(cls, specs: list[Self]) -> Self: num_kv_heads=specs[0].num_kv_heads, head_size=specs[0].head_size, dtype=specs[0].dtype, + dcp_sharded=specs[0].dcp_sharded, page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, @@ -1155,6 +1165,7 @@ def merge(cls, specs: list[Self]) -> Self: sink_len=specs[0].sink_len, dtype=specs[0].dtype, kv_quant_mode=specs[0].kv_quant_mode, + dcp_sharded=specs[0].dcp_sharded, page_size_padded=specs[0].page_size_padded, num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, @@ -1187,6 +1198,10 @@ class UniformTypeKVCacheSpecs(KVCacheSpec): kv_cache_specs: dict[str, KVCacheSpec] + def __post_init__(self): + if self.kv_cache_specs: + object.__setattr__(self, "dcp_sharded", self.first_spec.dcp_sharded) + @property def prefix_cacheable(self) -> bool: return all(spec.prefix_cacheable for spec in self.kv_cache_specs.values()) @@ -1236,6 +1251,8 @@ def is_uniform_type(cls, kv_cache_specs: dict[str, KVCacheSpec]) -> bool: if len(block_sizes) > 1: # Different block sizes, not uniform. return False + if len({spec.dcp_sharded for spec in kv_cache_specs.values()}) > 1: + return False first_spec = next(iter(kv_cache_specs.values())) return first_spec.is_uniform_with_collection(kv_cache_specs) diff --git a/vllm/v1/simple_kv_offload/manager.py b/vllm/v1/simple_kv_offload/manager.py index 85dde88f2d55..cc1cfb8dbc0c 100644 --- a/vllm/v1/simple_kv_offload/manager.py +++ b/vllm/v1/simple_kv_offload/manager.py @@ -27,13 +27,13 @@ from vllm.v1.core.kv_cache_utils import ( BlockHashWithGroupId, ExternalBlockHash, - dcp_world_size_for_kv_cache_spec, generate_block_hash_extra_keys, get_block_hash, get_group_id, make_block_hash_with_group_id, maybe_convert_block_hash, resolve_block_hashes, + resolve_dcp_kv_block_size, ) from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.kv_cache_interface import ( @@ -299,11 +299,7 @@ def _estimate_lazy_target_blocks( target = 0 for g in kv_cache_config.kv_cache_groups: spec = g.kv_cache_spec - # Only full attention is sharded across DCP ranks; replicated specs - # (mamba, sliding window, chunked-local) keep their own block size. - block_size = spec.block_size * dcp_world_size_for_kv_cache_spec( - spec, cp_world_size - ) + block_size = resolve_dcp_kv_block_size(spec, cp_world_size) if isinstance(spec, MambaSpec): target += 2 elif isinstance(spec, SlidingWindowSpec): diff --git a/vllm/v1/spec_decode/draft_model.py b/vllm/v1/spec_decode/draft_model.py index 08542f03a1a0..17be2732e67c 100644 --- a/vllm/v1/spec_decode/draft_model.py +++ b/vllm/v1/spec_decode/draft_model.py @@ -81,13 +81,20 @@ def _raise_if_draft_tp_mismatch(self): def _create_draft_vllm_config(self) -> VllmConfig: base = super()._create_draft_vllm_config() spec = self.speculative_config + target_parallel = base.parallel_config return replace( base, quant_config=None, parallel_config=replace( spec.draft_parallel_config, - rank=self.vllm_config.parallel_config.rank, + rank=target_parallel.rank, + decode_context_parallel_size=( + target_parallel.decode_context_parallel_size + ), + cp_kv_cache_interleave_size=target_parallel.cp_kv_cache_interleave_size, + dcp_comm_backend=target_parallel.dcp_comm_backend, + dcp_q_replicate=target_parallel.dcp_q_replicate, ), model_config=spec.draft_model_config, ) diff --git a/vllm/v1/worker/cp_utils.py b/vllm/v1/worker/cp_utils.py index 79651759aad4..bcf56dc0bf78 100644 --- a/vllm/v1/worker/cp_utils.py +++ b/vllm/v1/worker/cp_utils.py @@ -40,6 +40,8 @@ def check_attention_cp_compatibility( layer_impl = getattr(layer, "impl", None) if layer_impl is None: continue + if not check_pcp and layer_impl.dcp_world_size == 1: + continue if vllm_config.speculative_config is not None and interleave_size > 1: assert layer_impl.supports_mtp_with_cp_non_trivial_interleave_size, ( "MTP with cp_kv_cache_interleave_size > 1 is not " diff --git a/vllm/v1/worker/gpu/block_table.py b/vllm/v1/worker/gpu/block_table.py index c01895e63545..b6cce6d86a2e 100644 --- a/vllm/v1/worker/gpu/block_table.py +++ b/vllm/v1/worker/gpu/block_table.py @@ -27,6 +27,7 @@ def __init__( cp_rank: int = 0, cp_interleave: int = 1, slot_mapping_enabled: list[bool] | None = None, + dcp_sharded: list[bool] | None = None, ): self.block_sizes = block_sizes self.kernel_block_sizes = kernel_block_sizes @@ -44,6 +45,10 @@ def __init__( slot_mapping_enabled = [True] * self.num_kv_cache_groups assert len(slot_mapping_enabled) == self.num_kv_cache_groups self._slot_mapping_enabled = slot_mapping_enabled + if dcp_sharded is None: + dcp_sharded = [True] * self.num_kv_cache_groups + assert len(dcp_sharded) == self.num_kv_cache_groups + self.dcp_sharded = torch.tensor(dcp_sharded, dtype=torch.bool, device=device) self.blocks_per_kv_block = [ bs // kbs for bs, kbs in zip(block_sizes, kernel_block_sizes) @@ -211,6 +216,7 @@ def compute_slot_mappings( self.block_sizes_tensor, self.kernel_block_sizes_tensor, self.slot_mapping_enabled, + self.dcp_sharded, slot_mappings, slot_mappings.stride(0), self.cp_rank, @@ -284,6 +290,7 @@ def _compute_slot_mappings_kernel( block_sizes, # [num_kv_cache_groups] kernel_block_sizes, # [num_kv_cache_groups] slot_mapping_enabled, # [num_kv_cache_groups] + dcp_sharded, # [num_kv_cache_groups] slot_mappings_ptr, # [num_kv_cache_groups, max_num_tokens] slot_mappings_stride, cp_rank, @@ -313,6 +320,8 @@ def _compute_slot_mappings_kernel( kv_block_size = tl.load(block_sizes + group_id) kernel_block_size = tl.load(kernel_block_sizes + group_id) mapping_enabled = tl.load(slot_mapping_enabled + group_id) + if CP_SIZE != 1: + sharded = tl.load(dcp_sharded + group_id) req_state_idx = tl.load(idx_mapping + batch_idx) start_idx = tl.load(query_start_loc + batch_idx) @@ -335,6 +344,8 @@ def _compute_slot_mappings_kernel( remainder = virtual_block_offsets % CP_INTERLEAVE local_offsets = rounds * CP_INTERLEAVE + remainder local_positions = virtual_block_indices * kv_block_size + local_offsets + local_positions = tl.where(sharded, local_positions, positions) + is_local = ~sharded | is_local block_indices = tl.where( mapping_enabled, local_positions // kernel_block_size, 0 diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index 97571df8a901..46b4e5bf0f19 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -588,6 +588,7 @@ def initialize_kv_cache( block_sizes = [] max_num_blocks_per_group = [] slot_mapping_enabled = [] + dcp_sharded = [] for kv_cache_group in kv_cache_config.kv_cache_groups: spec = kv_cache_group.kv_cache_spec block_sizes.append(spec.block_size) @@ -595,6 +596,7 @@ def initialize_kv_cache( spec.first_spec if isinstance(spec, UniformTypeKVCacheSpecs) else spec ) slot_mapping_enabled.append(layer_spec.uses_slot_mapping) + dcp_sharded.append(spec.dcp_sharded) # Let each cache type account for CP. Attention KV is DCP-sharded, # while Mamba/GDN recurrent state is replicated across DCP ranks. max_num_blocks = spec.max_num_blocks_per_req( @@ -659,6 +661,7 @@ def initialize_kv_cache( device=self.device, kernel_block_sizes=self.kernel_block_sizes, slot_mapping_enabled=slot_mapping_enabled, + dcp_sharded=dcp_sharded, cp_size=self.dcp_size, cp_rank=self.dcp_rank, cp_interleave=self.cp_interleave, diff --git a/vllm/v1/worker/gpu/pcp_manager.py b/vllm/v1/worker/gpu/pcp_manager.py index 376e0f251012..eeac6608b42a 100644 --- a/vllm/v1/worker/gpu/pcp_manager.py +++ b/vllm/v1/worker/gpu/pcp_manager.py @@ -145,7 +145,10 @@ def validate_config( if speculative_config is not None: if speculative_config.use_dspark(): dcp_size = parallel_config.decode_context_parallel_size - if dcp_size not in (1, pcp_size): + if ( + dcp_size not in (1, pcp_size) + and speculative_config.draft_model_config.use_mla + ): raise NotImplementedError( "MRV2 PCP DSpark requires DCP=1 or DCP=PCP; got " f"DCP={dcp_size}, PCP={pcp_size}." diff --git a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py index a5710829e0ff..98c4abe56539 100644 --- a/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/dflash/speculator.py @@ -37,12 +37,18 @@ class DFlashSpeculator(DraftModelSpeculator): def __init__(self, vllm_config: VllmConfig, device: torch.device): parallel_config = vllm_config.parallel_config - if parallel_config.prefill_context_parallel_size > 1: - vllm_config = copy.copy(vllm_config) - vllm_config.parallel_config = replace( - parallel_config, - prefill_context_parallel_size=1, - ) + speculative_config = vllm_config.speculative_config + assert speculative_config is not None + vllm_config = copy.copy(vllm_config) + vllm_config.parallel_config = replace( + parallel_config, + prefill_context_parallel_size=1, + decode_context_parallel_size=( + parallel_config.decode_context_parallel_size + if speculative_config.draft_model_config.use_mla + else 1 + ), + ) super().__init__(vllm_config, device) self.hidden_states = torch.zeros( @@ -396,7 +402,7 @@ def propose( self.block_tables.input_block_tables[gid], self.block_tables.kernel_block_sizes[gid], self.block_tables.cp_rank, - self.block_tables.cp_size, + self.dcp_size, self.block_tables.cp_interleave, self.parallel_drafting_token_id, self.num_query_per_req, diff --git a/vllm/v1/worker/gpu/spec_decode/speculator.py b/vllm/v1/worker/gpu/spec_decode/speculator.py index 299cac641620..4bc4bf80c241 100644 --- a/vllm/v1/worker/gpu/spec_decode/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/speculator.py @@ -134,9 +134,10 @@ def __init__(self, vllm_config: VllmConfig, device: torch.device): self.speculative_config.use_local_argmax_reduction ) - # DP configuration + # Parallel configuration self.dp_size = vllm_config.parallel_config.data_parallel_size self.dp_rank = vllm_config.parallel_config.data_parallel_rank + self.dcp_size = vllm_config.parallel_config.decode_context_parallel_size self.eplb_state: EplbState | None = None @@ -335,14 +336,14 @@ def _build_attn_metadata( out=draft_seq_lens_cpu_upper_bound[:num_reqs], ) draft_seq_lens_cpu_upper_bound[:num_reqs].clamp_(max=self.max_model_len) - if dcp_local_seq_lens is None and self.block_tables.cp_size > 1: + if dcp_local_seq_lens is None and self.dcp_size > 1: # Draft steps advance and rewind their own global sequence lengths, # so the target model's DCP-local lengths may already be stale. dcp_local_seq_lens = maybe_prepare_dcp_local_seq_lens( self.input_buffers.dcp_local_seq_lens, self.input_buffers.seq_lens, num_reqs, - self.block_tables.cp_size, + self.dcp_size, self.block_tables.cp_rank, self.block_tables.cp_interleave, ) From 83bb72caaacc3fc4ee3aa0606e7a7f7bce3a3092 Mon Sep 17 00:00:00 2001 From: Tarik Sarac Date: Wed, 16 Sep 2026 10:07:11 -0500 Subject: [PATCH 2/5] [ROCm][Kimi-K3] Add optional moonmath kernels for gfx942 MXFP4 SiTU MoE and MLA decode Signed-off-by: Tarik Sarac --- tests/kernels/attention/test_rocm_aiter_fa.py | 22 +- tests/kernels/moe/test_ocp_mx_moe.py | 66 +++++ tests/v1/worker/test_attn_utils.py | 44 +++ .../fused_moe/experts/moonmath_mxfp4_moe.py | 266 ++++++++++++++++++ .../layers/fused_moe/oracle/mxfp4.py | 14 +- vllm/platforms/rocm.py | 8 +- vllm/utils/import_utils.py | 5 + vllm/v1/attention/backend.py | 6 + .../v1/attention/backends/mla/moonmath_mla.py | 128 +++++++++ vllm/v1/attention/backends/registry.py | 1 + vllm/v1/attention/backends/rocm_aiter_fa.py | 13 +- vllm/v1/worker/utils.py | 30 ++ 12 files changed, 587 insertions(+), 16 deletions(-) create mode 100644 vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py create mode 100644 vllm/v1/attention/backends/mla/moonmath_mla.py diff --git a/tests/kernels/attention/test_rocm_aiter_fa.py b/tests/kernels/attention/test_rocm_aiter_fa.py index dd2870ccf178..f5824a38dc14 100644 --- a/tests/kernels/attention/test_rocm_aiter_fa.py +++ b/tests/kernels/attention/test_rocm_aiter_fa.py @@ -689,12 +689,15 @@ def test_aiter_fa_sliding_window_matches_reference(): @pytest.mark.skipif(not on_mi3xx(), reason="MI300/MI350 ROCm only") @pytest.mark.parametrize( - "shuffle,sliding_window", [(False, None), (False, 16), (True, None)] + "shuffle,sliding_window,block_size", + # 64-token pages are served whole only when a block cannot be split; their + # single-token decode goes to unified_attention. + [(False, None, 16), (False, 16, 16), (True, None, 16), (False, None, 64)], ) @pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"]) @pytest.mark.parametrize("batch", ["prefill", "extend", "mixed"]) def test_aiter_fa_shared_kv_matches_reference( - monkeypatch, shuffle, sliding_window, kv_cache_dtype, batch + monkeypatch, shuffle, sliding_window, block_size, kv_cache_dtype, batch ): """Shared layers read cached K/V for prefill and extend without modifying it.""" from tests.v1.attention.utils import ( @@ -725,6 +728,7 @@ def test_aiter_fa_shared_kv_matches_reference( max_num_batched_tokens=1024, ) config.cache_config.cache_dtype = kv_cache_dtype + config.cache_config.block_size = block_size num_heads = config.model_config.get_num_attention_heads(config.parallel_config) num_kv_heads = config.model_config.get_num_kv_heads(config.parallel_config) head_size = config.model_config.get_head_size() @@ -758,18 +762,18 @@ def test_aiter_fa_shared_kv_matches_reference( torch.device("cuda"), ) common = create_common_attn_metadata( - batch_spec, BLOCK_SIZE, torch.device("cuda"), max_block_idx=32 + batch_spec, block_size, torch.device("cuda"), max_block_idx=32 ) cache_dtype = ( current_platform.fp8_dtype() if kv_cache_dtype == "fp8" else torch.bfloat16 ) kv_cache = ( torch.empty( - 2, 32, BLOCK_SIZE, num_kv_heads * head_size, dtype=cache_dtype + 2, 32, block_size, num_kv_heads * head_size, dtype=cache_dtype ).transpose(0, 1) if shuffle else torch.empty( - 32, num_kv_heads, BLOCK_SIZE, 2 * head_size, dtype=cache_dtype + 32, num_kv_heads, block_size, 2 * head_size, dtype=cache_dtype ) ) target.kv_cache = kv_cache @@ -780,7 +784,7 @@ def test_aiter_fa_shared_kv_matches_reference( attn_layer._k_scale.fill_(k_scale) attn_layer._v_scale.fill_(v_scale) key = torch.randn( - 32 * BLOCK_SIZE, num_kv_heads, head_size, dtype=torch.bfloat16 + 32 * block_size, num_kv_heads, head_size, dtype=torch.bfloat16 ) value = torch.randn_like(key) target.impl.do_kv_cache_update( @@ -788,14 +792,14 @@ def test_aiter_fa_shared_kv_matches_reference( key, value, kv_cache, - torch.arange(32 * BLOCK_SIZE, dtype=torch.int64), + torch.arange(32 * block_size, dtype=torch.int64), ) key_cache = ((key / k_scale).to(cache_dtype).to(key.dtype) * k_scale).reshape( - 32, BLOCK_SIZE, num_kv_heads, head_size + 32, block_size, num_kv_heads, head_size ) value_cache = ( (value / v_scale).to(cache_dtype).to(value.dtype) * v_scale - ).reshape(32, BLOCK_SIZE, num_kv_heads, head_size) + ).reshape(32, block_size, num_kv_heads, head_size) with torch.device("cpu"): metadata = builder.build(0, common) cache_before = kv_cache.view(torch.uint8).clone() diff --git a/tests/kernels/moe/test_ocp_mx_moe.py b/tests/kernels/moe/test_ocp_mx_moe.py index d513a14f775a..febd15622e45 100644 --- a/tests/kernels/moe/test_ocp_mx_moe.py +++ b/tests/kernels/moe/test_ocp_mx_moe.py @@ -1821,6 +1821,72 @@ def test_mxfp4_emulation_rounds_up_to_block_size( assert rounded_intermediate % OCP_MX_BLOCK_SIZE == 0 +# Both AITER MXFP4 A16W4 backends serve K3's native intermediate size, so they +# must align it the same way; gfx942 can only take the Triton one. The generic +# ROCm 256 round-up inflates K3's 384/partition to 512 (+33% MoE weights), which +# OOMs before any KV cache is allocated. The exemption is scoped to the SiTU and +# SILU kernels, so every other activation must keep the 256 round-up. +@pytest.mark.skipif(not ROCM_AVAILABLE, reason="AITER MXFP4 backends target ROCm") +@pytest.mark.parametrize( + "backend_name,activation_name,expected", + [ + ("AITER_MXFP4_BF16", "SITU", (3584, 384)), + ("AITER_MXFP4_BF16", "SILU", (3584, 384)), + ("AITER_TRITON_MXFP4_BF16", "SITU", (3584, 384)), + ("AITER_TRITON_MXFP4_BF16", "SILU", (3584, 384)), + ("AITER_TRITON_MXFP4_BF16", "SWIGLUOAI", (3584, 512)), + ], +) +def test_aiter_mxfp4_a16w4_alignment( + backend_name: str, activation_name: str, expected: tuple[int, int] +): + """K3 at TP8: hidden 3584, intermediate 384/partition, both 128-aligned.""" + from vllm.model_executor.layers.fused_moe.activation import MoEActivation + from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import ( + Mxfp4MoeBackend, + mxfp4_round_up_hidden_size_and_intermediate_size, + ) + + assert ( + mxfp4_round_up_hidden_size_and_intermediate_size( + getattr(Mxfp4MoeBackend, backend_name), + 3584, + 384, + getattr(MoEActivation, activation_name), + ) + == expected + ) + + +# The moonmath kernels are an optional package. Without them there is no SiTU +# a16w4 kernel at all, so the class must DECLINE the activation and let the +# oracle fall through to AITER, rather than be selected and fail at weight load. +@pytest.mark.parametrize("installed", [True, False]) +def test_aiter_w4a16_claims_situ_only_with_the_moonmath_kernels( + monkeypatch: pytest.MonkeyPatch, installed: bool +): + from vllm.model_executor.layers.fused_moe.activation import MoEActivation + from vllm.model_executor.layers.fused_moe.experts import ( + moonmath_mxfp4_moe as experts, + ) + from vllm.model_executor.layers.fused_moe.experts.aiter_mxfp4_w4a16_moe import ( + AiterW4A16ExpertsMonolithic, + ) + + monkeypatch.setattr(experts, "has_moonmath_amd", lambda: installed) + + assert ( + experts.MoonmathW4A16SituExperts._supports_activation(MoEActivation.SITU) + is installed + ) + # The AITER class is untouched: it never claims SiTU, and still serves the + # activations it always did, so a fall-through is unaffected either way. + aiter_cls = AiterW4A16ExpertsMonolithic + assert not aiter_cls._supports_activation(MoEActivation.SITU) + assert aiter_cls._supports_activation(MoEActivation.SILU) + assert aiter_cls._supports_activation(MoEActivation.SWIGLUOAI) + + def test_select_mxfp4_moe_backend_raises_with_unsupported_reasons( monkeypatch: pytest.MonkeyPatch, ): diff --git a/tests/v1/worker/test_attn_utils.py b/tests/v1/worker/test_attn_utils.py index 2dadc8c980e6..21ecb68fae2b 100644 --- a/tests/v1/worker/test_attn_utils.py +++ b/tests/v1/worker/test_attn_utils.py @@ -37,6 +37,7 @@ AttentionGroup, allocate_kv_cache, copy_kv_cache_blocks_inplace, + prepare_kernel_block_sizes, ) @@ -345,6 +346,49 @@ def test_reshape_padded_kv_cache_strides_by_padded_page(): assert kv_cache[0].is_contiguous() +@pytest.mark.parametrize( + ("padded", "supports_unsplit", "expected"), + [(False, True, 16), (True, False, 16), (True, True, 64)], +) +def test_prepare_kernel_block_sizes_serves_unsplittable_block_whole( + padded: bool, supports_unsplit: bool, expected: int +): + """A padded block cannot be split into kernel blocks, so a backend that can + read it whole gets it whole; dense blocks keep splitting as before.""" + + class Backend: + @staticmethod + def get_supported_kernel_block_sizes(): + return [16] + + @classmethod + def supports_unsplit_block_size(cls, block_size: int) -> bool: + return supports_unsplit + + spec = FullAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=2, + dtype=torch.float32, + page_size_padded=1536 if padded else None, + ) + kv_cache_config = KVCacheConfig( + num_blocks=2, + kv_cache_tensors=[ + KVCacheTensor( + size=2 * spec.page_size_bytes, + layers=["layer.0"], + layer_stride=2 * spec.page_size_bytes, + block_stride=spec.page_size_bytes, + ) + ], + kv_cache_groups=[KVCacheGroupSpec(["layer.0"], spec)], + ) + attn_groups = [[SimpleNamespace(backend=Backend)]] + + assert prepare_kernel_block_sizes(kv_cache_config, attn_groups) == [expected] + + @pytest.mark.parametrize( ( "kernel_block_sizes", diff --git a/vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py b/vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py new file mode 100644 index 000000000000..3da3ac99a12d --- /dev/null +++ b/vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py @@ -0,0 +1,266 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""MXFP4 SiTU MoE on the optional `moonmath_amd` CDNA3 kernels. + +AITER's A16W4 grouped GEMM has no in-kernel SiTU, so a SiTU MXFP4 MoE +(Kimi-K3) has no native ROCm kernel without this one, which fuses the +activation into the gate/up epilogue. + +`MoonmathW4A16SituExperts` subclasses the AITER W4A16 experts to inherit its +weight format -- the kernels read the layout `oracle/mxfp4.py` already prepares +for AITER's Triton path -- and claims ONLY the SITU activation, and only when +the optional package is installed. The oracle lists it after the AITER class, +which does not claim SiTU, so every other configuration stays on AITER. +""" + +import torch + +from vllm.logger import init_logger +from vllm.model_executor.layers.fused_moe.activation import MoEActivation +from vllm.model_executor.layers.fused_moe.config import ( + FusedMoEConfig, + FusedMoEQuantConfig, + RoutingMethodType, +) +from vllm.model_executor.layers.fused_moe.experts.aiter_mxfp4_w4a16_moe import ( + AiterW4A16ExpertsMonolithic, +) +from vllm.model_executor.layers.quantization.utils.mxfp4_utils import weight_mx_scale +from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey +from vllm.utils.import_utils import has_moonmath_amd + +logger = init_logger(__name__) + +__all__ = ["MoonmathW4A16SituExperts"] + + +class MoonmathW4A16SituExperts(AiterW4A16ExpertsMonolithic): + def __init__( + self, + moe_config: FusedMoEConfig, + quant_config: FusedMoEQuantConfig, + ): + super().__init__(moe_config, quant_config) + # DeepSeekV3 (noaux_tc, e.g. Kimi-K3) divides by the selected sum. + self.renormalize = self.renormalize or ( + moe_config.routing_method == RoutingMethodType.DeepSeekV3 + ) + self._mm = None + + @staticmethod + def _supports_activation(activation: MoEActivation) -> bool: + # Only SiTU, and only with the kernels: anything else must fall through + # to the AITER class rather than be claimed and then fail at load. + if activation != MoEActivation.SITU: + return False + if not has_moonmath_amd(): + # The generic "does not support SITU" reason would not tell anyone + # that a kernel exists for it. + logger.info_once( + "SiTU MXFP4 MoE: no ROCm kernel is active. Install the optional " + "`moonmath-amd` package to enable the fused-SiTU A16W4 kernels." + ) + return False + return True + + @staticmethod + def _supports_routing_method( + routing_method: RoutingMethodType, + weight_key: QuantKey | None, + activation_key: QuantKey | None, + ) -> bool: + return routing_method == RoutingMethodType.DeepSeekV3 or ( + AiterW4A16ExpertsMonolithic._supports_routing_method( + routing_method, weight_key, activation_key + ) + ) + + def process_weights_after_loading(self, layer) -> None: + # aiter's swizzle leaves [E, K/2, N] stride(-2)==1; transpose back. + raw = [ + t.storage.data.view(torch.uint8).transpose(-2, -1) + for t in ( + layer.w13_weight, + weight_mx_scale(self.quant_config.w1_precision), + layer.w2_weight, + weight_mx_scale(self.quant_config.w2_precision), + ) + ] + self._mm = repack_weights(*raw) + + def apply( + self, + hidden_states: torch.Tensor, + w1: torch.Tensor, + w2: torch.Tensor, + router_logits: torch.Tensor, + activation: MoEActivation, + global_num_experts: int, + expert_map: torch.Tensor | None, + a1q_scale: torch.Tensor | None, + apply_router_weight_on_input: bool, + num_expert_group: int | None = None, + e_score_correction_bias: torch.Tensor | None = None, + routed_scaling_factor: float | None = None, + topk_group: int | None = None, + ) -> torch.Tensor: + # The weights are in moonmath layout, so AITER must never see them. + assert expert_map is None, ( + "moonmath MXFP4 MoE serves SiTU without expert parallelism only" + ) + # score_mode None is plain softmax top-k, which IGNORES the router bias. + score_mode = { + RoutingMethodType.DeepseekV4: "sqrtsoftplus", + RoutingMethodType.DeepSeekV3: "sigmoid", + }.get(self.moe_config.routing_method) + return situ_moe_forward( + self._mm, + hidden_states, + router_logits, + self.topk, + self.renormalize, + score_mode, + e_score_correction_bias, + routed_scaling_factor, + self.moe_config.activation_situ_beta, + self.moe_config.activation_situ_linear_beta, + apply_router_weight_on_input, + ) + + +def repack_weights(w13, w13s, w2, w2s) -> tuple: + """Rewrite the four MXFP4 weight tensors in place; return the run plan. + + Must run at weight load: the kernels read moonmath's layout directly and + stock weights give wrong numbers rather than an error. + """ + import moonmath_amd as ma + + E, N13, _ = w13.shape + inter_dim, H = N13 // 2, w2.shape[1] + return ( + _repack_(w13, ma.repack_mxfp4, (E, H // 32, N13, 16), True), + _repack_(w13s, ma.repack_mxfp4_scales, (E, H // 32, N13), True), + _repack_(w2, ma.repack_mxfp4, (E, inter_dim // 32, H, 16)), + _repack_(w2s, ma.repack_mxfp4_scales, (E, inter_dim // 32, H)), + E, + inter_dim, + H, + torch.cuda.get_device_properties(w13.device).multi_processor_count, + ) + + +def _repack_(stock: torch.Tensor, fn, out_shape, deinterleave=False, chunk=32): + """Rewrite `stock` storage into moonmath's layout IN PLACE, returning a view. + + Out of place would double the MoE weights (~170 GB/rank for K3). Both + repacks permute within an expert slab, so chunking over E is exact. + """ + E = stock.shape[0] + # view(), not reshape(): reshape would silently copy and lose the aliasing. + flat = stock.view(-1) + per = flat.numel() // E + for s in range(0, E, chunk): + e = min(s + chunk, E) + src = stock[s:e] + if deinterleave: + # The oracle interleaves w13 as (g0,u0,g1,u1,...) for AITER, but + # the fused SiTU epilogue pairs the [gate | up] HALVES. Backwards + # here multiplies mismatched columns: garbage, never an error. + v = src.view(e - s, src.shape[1] // 2, 2, src.shape[2]) + src = torch.cat((v[:, :, 0], v[:, :, 1]), dim=1) + flat[s * per : e * per].copy_(fn(src).reshape(-1)) + return flat.view(*out_shape) + + +def situ_moe_forward( + mm: tuple, + hidden_states: torch.Tensor, + gating_output: torch.Tensor, + topk: int, + renormalize: bool, + score_mode: str | None, + e_score_correction_bias: torch.Tensor | None, + routed_scaling_factor: float | None, + situ_beta: float, + situ_linear_beta: float, + apply_router_weight_on_input: bool, +) -> torch.Tensor: + """One MXFP4 SiTU MoE layer: routing, then the two grouped GEMMs.""" + import moonmath_amd as ma + from aiter.ops.triton.moe.moe_routing.topk import topk as aiter_topk + + from vllm.model_executor.layers.fused_moe.moe_align_block_size import ( + moe_align_block_size, + ) + + w13, w13s, w2, w2s, E, inter_dim, H, num_cus = mm + # AITER routing()'s math, with its sort replaced by moe_align_block_size. + scal, indx, _ = aiter_topk( + gating_output, + topk, + apply_softmax=False, + score_mode=score_mode, + bias=e_score_correction_bias, + renorm=renormalize, + routed_scaling_factor=( + routed_scaling_factor if routed_scaling_factor is not None else 1.0 + ), + ) + ids = indx.to(torch.int32) + T = hidden_states.shape[0] + rows = T * topk + dt, dev = hidden_states.dtype, hidden_states.device + assert hidden_states.is_contiguous(), ( + "moonmath MoE reads A by row; a strided [T, K] reads the wrong ones" + ) + tw = scal.reshape(-1).to(dt) + + bm_g = ma.mxfp4_moe_gateup_block_m(rows, E) + sg, eg, ng = moe_align_block_size(ids, bm_g, E) + inter = torch.empty((rows, inter_dim), dtype=dt, device=dev) + ma.mxfp4_moe_gateup( + hidden_states, + w13, + w13s, + inter, + tw, + sg, + eg, + ng, + eg.numel(), + bm_g, + rows, + topk, + epilogue=ma.EPI_SITU, + mul_routed_weight=apply_router_weight_on_input, + situ_beta=situ_beta, + situ_linear_beta=situ_linear_beta, + ) + + bm_d = ma.mxfp4_moe_down_block_m(rows, E, inter_dim) + assert bm_d, f"moonmath has no down tile for K={inter_dim}" + sd, ed, nd = (sg, eg, ng) if bm_d == bm_g else moe_align_block_size(ids, bm_d, E) + nt = ma.mxfp4_moe_down_nt(rows, E) + ns = ma.mxfp4_moe_down_n_steps(ed.numel(), H, num_cus, bm_d, nt) + down = torch.empty((rows, H), dtype=dt, device=dev) + # top_k=1 on purpose: down's A already has one row per (token, expert). + ma.mxfp4_moe_down( + inter, + w2, + w2s, + down, + tw, + sd, + ed, + nd, + ed.numel(), + bm_d, + ns, + nt, + rows, + 1, + mul_routed_weight=not apply_router_weight_on_input, + ) + # down writes one row per (token, expert); AITER scattered in-kernel. + return torch.sum(down.view(T, topk, H), dim=1, dtype=torch.float32).to(dt) diff --git a/vllm/model_executor/layers/fused_moe/oracle/mxfp4.py b/vllm/model_executor/layers/fused_moe/oracle/mxfp4.py index ce19ba39bfc9..fb78634adc86 100644 --- a/vllm/model_executor/layers/fused_moe/oracle/mxfp4.py +++ b/vllm/model_executor/layers/fused_moe/oracle/mxfp4.py @@ -261,8 +261,11 @@ def backend_to_kernel_cls( from vllm.model_executor.layers.fused_moe.experts.aiter_mxfp4_w4a16_moe import ( AiterW4A16ExpertsMonolithic, ) + from vllm.model_executor.layers.fused_moe.experts.moonmath_mxfp4_moe import ( + MoonmathW4A16SituExperts, + ) - return [AiterW4A16ExpertsMonolithic] + return [AiterW4A16ExpertsMonolithic, MoonmathW4A16SituExperts] elif backend == Mxfp4MoeBackend.AITER_MXFP4_FP8: from vllm.model_executor.layers.fused_moe.experts.aiter_mxfp4_w4a8_moe import ( @@ -769,9 +772,12 @@ def mxfp4_round_up_hidden_size_and_intermediate_size( intermediate_size = round_up(intermediate_size, 128) hidden_size = round_up(hidden_size, 128) elif current_platform.is_rocm(): - if backend == Mxfp4MoeBackend.AITER_MXFP4_BF16 and ( - activation == MoEActivation.SITU or activation == MoEActivation.SILU - ): + if backend in ( + Mxfp4MoeBackend.AITER_MXFP4_BF16, + # gfx942 can only take the Triton path; without it K3's 384/partition + # intermediate takes the 256 round-up to 512 (+33% weights) and OOMs. + Mxfp4MoeBackend.AITER_TRITON_MXFP4_BF16, + ) and (activation == MoEActivation.SITU or activation == MoEActivation.SILU): # K3's AITER A16W4 SiTU kernel handles K3's native intermediate size # (moe_intermediate 3072; e.g. 384/partition at TP8). Align to 128 (a # no-op for K3's shapes) rather than the generic ROCm 256 round-up, diff --git a/vllm/platforms/rocm.py b/vllm/platforms/rocm.py index 9474ec4835df..d711bb69eee9 100644 --- a/vllm/platforms/rocm.py +++ b/vllm/platforms/rocm.py @@ -451,13 +451,19 @@ def _get_backend_priorities( use_kv_connector: bool = False, ) -> list[AttentionBackendEnum]: from vllm._aiter_ops import is_aiter_found_and_supported, rocm_aiter_ops + from vllm.utils.import_utils import has_moonmath_amd if use_sparse: return [AttentionBackendEnum.ROCM_AITER_MLA_SPARSE] if use_mla: if rocm_aiter_ops.is_mla_enabled(): - return [ + # Moonmath serves only the decode and defers the rest to AITER, + # so it is offered first and falls back by itself. + moonmath = ( + [AttentionBackendEnum.ROCM_MOONMATH_MLA] if has_moonmath_amd() else [] + ) + return moonmath + [ AttentionBackendEnum.ROCM_AITER_MLA, AttentionBackendEnum.TRITON_MLA, AttentionBackendEnum.ROCM_AITER_TRITON_MLA, diff --git a/vllm/utils/import_utils.py b/vllm/utils/import_utils.py index 4e90367a3e6c..d519f1467c13 100644 --- a/vllm/utils/import_utils.py +++ b/vllm/utils/import_utils.py @@ -512,6 +512,11 @@ def has_nixl_ep() -> bool: return _has_module("nixl_ep") +def has_moonmath_amd() -> bool: + """Whether the optional `moonmath_amd` CDNA3 kernel package is available.""" + return _has_module("moonmath_amd") + + def is_numba_available() -> bool: """Whether the optional `numba` package is available.""" return _has_module("numba") diff --git a/vllm/v1/attention/backend.py b/vllm/v1/attention/backend.py index 5cfa36334be7..47a4966066fa 100644 --- a/vllm/v1/attention/backend.py +++ b/vllm/v1/attention/backend.py @@ -72,6 +72,12 @@ class AttentionBackend(ABC): def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [MultipleOf(1)] + @classmethod + def supports_unsplit_block_size(cls, block_size: int) -> bool: + """Whether a manager block that cannot be split into supported kernel + blocks (its pages are not dense) can be served whole.""" + return False + @staticmethod @abstractmethod def get_name() -> str: diff --git a/vllm/v1/attention/backends/mla/moonmath_mla.py b/vllm/v1/attention/backends/mla/moonmath_mla.py new file mode 100644 index 000000000000..ba1e6979fe39 --- /dev/null +++ b/vllm/v1/attention/backends/mla/moonmath_mla.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""A16W8 MLA decode on the optional `moonmath_amd` CDNA3 kernels. + +Replaces ONLY the decode, single-token and speculative verify alike: a bf16 +query against the fp8 KV cache, with the whole draft window resident in one +CTA, so the KV is read once for the window instead of once per position. +AITER's only bf16xfp8 gqa=16 object is qSeqLen=4 and pads a smaller head count +up to 16. + +Prefill, metadata and cudagraph buffers are inherited from `AiterMLABackend` +unchanged; a batch outside the kernel's domain falls back to it. The package is +optional and imported lazily, so this module is safe to import without it; +`_get_backend_priorities` only offers the backend when `has_moonmath_amd()`. +""" + +from __future__ import annotations + +import torch + +from vllm.config import get_current_vllm_config +from vllm.utils.math_utils import cdiv +from vllm.v1.attention.backend import AttentionLayer +from vllm.v1.attention.backends.mla.rocm_aiter_mla import ( + AiterMLABackend, + AiterMLAImpl, + AiterMLAMetadata, + AiterMLAMetadataBuilder, +) + +_LAT, _ROPE = 512, 64 +# Kernel domain: H <= 128, and B * ceil(q_len * H / 96) <= 304 query row slices. +_MAX_HEADS, _ROWS_PER_SLICE, _MAX_ROW_SLICES = 128, 96, 304 + + +class MoonmathMLAMetadataBuilder(AiterMLAMetadataBuilder): + def __init__(self, kv_cache_spec, layer_names, vllm_config, device): + super().__init__(kv_cache_spec, layer_names, vllm_config, device) + # The query is bf16 here (supports_quant_query_input=False), so pin + # q_dtype rather than let the inherited env gate disagree with it. + self._mla_q_dtype = self.decode_attn_out_dtype + + +class MoonmathMLAImpl(AiterMLAImpl): + """Aiter MLA with the decode on the moonmath kernel.""" + + def __init__(self, *args, **kwargs) -> None: + super().__init__(*args, **kwargs) + # a16w8: bf16 query vs fp8 KV. Set after super(), which assigns True. + self.supports_quant_query_input = False + self._mm_kv_scale: float | None = None + self._max_model_len = get_current_vllm_config().model_config.max_model_len + + def forward_mqa( + self, + q: torch.Tensor | tuple[torch.Tensor, torch.Tensor], + kv_c_and_k_pe_cache: torch.Tensor, + attn_metadata: AiterMLAMetadata, + layer: AttentionLayer, + ) -> tuple[torch.Tensor, torch.Tensor | None]: + decode = attn_metadata.decode + assert decode is not None + assert isinstance(q, tuple), ( + "moonmath MLA is a16w8 and needs the unfused BF16 (nope, pe) query; " + "supports_quant_query_input must stay False on this impl." + ) + q_lat, q_pe = q + # Routing reads only shapes and the causal flag, so it is fixed per + # captured graph. + num_tokens, heads, _ = q_lat.shape + num_reqs = decode.seq_lens.size(0) + q_len = num_tokens // num_reqs + if ( + not attn_metadata.causal + or decode.paged_kv_indices is None + or heads > _MAX_HEADS + or num_tokens != num_reqs * q_len + or num_reqs * cdiv(q_len * heads, _ROWS_PER_SLICE) > _MAX_ROW_SLICES + ): + return super().forward_mqa(q, kv_c_and_k_pe_cache, attn_metadata, layer) + + assert kv_c_and_k_pe_cache.dtype == torch.float8_e4m3fnuz, ( + "moonmath MLA needs an fp8_e4m3fnuz KV cache (--kv-cache-dtype fp8), " + f"got {kv_c_and_k_pe_cache.dtype}" + ) + # Both halves arrive as transposed views; the kernel takes contiguous + # [B*q_len, H, dim] rows, request b owning [b*q_len, (b+1)*q_len). + q_lat = q_lat.contiguous() + q_pe = q_pe.contiguous() + out = torch.empty_like(q_lat) + + if self._mm_kv_scale is None: + # Static load-time constant, read once: .item() is illegal inside + # graph capture (the first call is always the eager dummy run). + k = getattr(layer, "_k_scale_float", None) + self._mm_kv_scale = float(layer._k_scale if k is None else k) + + import moonmath_amd as ma + + # The kernel plans its KV split from kv_indices' length (the mean KV + # length per request), so hand it the persistent buffer cut at the + # configured ceiling: a shape-only slice, fixed at graph capture. + ma.mla_decode_a16w8( + q_lat, + q_pe, + kv_c_and_k_pe_cache.view(-1, 1, _LAT + _ROPE), + out, + decode.seq_lens, + decode.paged_kv_indices[: num_reqs * self._max_model_len], + decode.paged_kv_indptr, + self.scale, + self._mm_kv_scale, + ) + return out, None + + +class MoonmathMLABackend(AiterMLABackend): + @staticmethod + def get_name() -> str: + return "MOONMATH_MLA" + + @staticmethod + def get_impl_cls() -> type[MoonmathMLAImpl]: + return MoonmathMLAImpl + + @staticmethod + def get_builder_cls() -> type[MoonmathMLAMetadataBuilder]: + return MoonmathMLAMetadataBuilder diff --git a/vllm/v1/attention/backends/registry.py b/vllm/v1/attention/backends/registry.py index 32e2fabeb567..c24665591db3 100644 --- a/vllm/v1/attention/backends/registry.py +++ b/vllm/v1/attention/backends/registry.py @@ -54,6 +54,7 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta): ) ROCM_ATTN = "vllm.v1.attention.backends.rocm_attn.RocmAttentionBackend" ROCM_AITER_MLA = "vllm.v1.attention.backends.mla.rocm_aiter_mla.AiterMLABackend" + ROCM_MOONMATH_MLA = "vllm.v1.attention.backends.mla.moonmath_mla.MoonmathMLABackend" ROCM_AITER_TRITON_MLA = ( "vllm.v1.attention.backends.mla.aiter_triton_mla.AiterTritonMLABackend" ) diff --git a/vllm/v1/attention/backends/rocm_aiter_fa.py b/vllm/v1/attention/backends/rocm_aiter_fa.py index 4ce8b23d3119..272a60952712 100644 --- a/vllm/v1/attention/backends/rocm_aiter_fa.py +++ b/vllm/v1/attention/backends/rocm_aiter_fa.py @@ -870,6 +870,11 @@ def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: return [16, 32, 128] return [16, 32] + @classmethod + def supports_unsplit_block_size(cls, block_size: int) -> bool: + # Pages the paged decode kernels cannot read go to unified_attention. + return not rocm_aiter_ops.is_shuffle_kv_cache_enabled() and block_size % 16 == 0 + @classmethod def get_supported_head_sizes(cls) -> list[int]: return [64, 128, 256] @@ -1453,12 +1458,16 @@ def forward( return # The ll4mi kernel in paged_attention_v1 requires - # HEAD_SIZE >= 16 * NWARPS (= 64 on ROCm with NWARPS=4). + # HEAD_SIZE >= 16 * NWARPS (= 64 on ROCm with NWARPS=4) + # and 16- or 32-token pages. # For smaller head sizes or sliding window attention, # fall back to the unified_attention triton kernel which # handles both correctly. _MIN_HEAD_SIZE_FOR_LL4MI = 64 - use_unified_attention = self.head_size < _MIN_HEAD_SIZE_FOR_LL4MI + use_unified_attention = self.head_size < _MIN_HEAD_SIZE_FOR_LL4MI or ( + not rocm_aiter_ops.is_shuffle_kv_cache_enabled() + and key_cache.shape[1] not in (16, 32) + ) if use_unified_attention: k_descale, v_descale = self._get_kv_cache_descales( diff --git a/vllm/v1/worker/utils.py b/vllm/v1/worker/utils.py index 6c2a05a6260d..3133ed7b791e 100644 --- a/vllm/v1/worker/utils.py +++ b/vllm/v1/worker/utils.py @@ -37,6 +37,7 @@ MambaSpec, MLAAttentionSpec, UniformTypeKVCacheSpecs, + compute_layer_kv_cache_shape_bytes, create_kv_cache_views, ) from vllm.v1.worker.block_table import get_block_table_width @@ -455,6 +456,26 @@ def allocate_kv_cache( return kv_caches +def _stores_dense_pages( + kv_cache_config: KVCacheConfig, kv_cache_group: KVCacheGroupSpec +) -> bool: + """Whether every block of the group is one dense page, which splitting it + into kernel blocks requires (see ``create_kv_cache_views``).""" + spec = kv_cache_group.kv_cache_spec + for tensor in kv_cache_config.kv_cache_tensors: + layer_name = tensor.layers[0] + if layer_name not in kv_cache_group.layer_names: + continue + if isinstance(spec, UniformTypeKVCacheSpecs): + layer_spec = spec.kv_cache_specs[layer_name] + else: + layer_spec = spec + page = math.prod(compute_layer_kv_cache_shape_bytes(layer_spec, 1)[1:]) + if tensor.block_stride != page: + return False + return True + + def prepare_kernel_block_sizes( kv_cache_config: KVCacheConfig, attn_groups: list[list[AttentionGroup]] ) -> list[int]: @@ -490,6 +511,15 @@ def prepare_kernel_block_sizes( selected_kernel_size = select_common_block_size( kv_manager_block_size, group_backends ) + if ( + selected_kernel_size != kv_manager_block_size + and not _stores_dense_pages(kv_cache_config, kv_cache_group) + and all( + backend.supports_unsplit_block_size(kv_manager_block_size) + for backend in group_backends + ) + ): + selected_kernel_size = kv_manager_block_size kernel_block_sizes.append(selected_kernel_size) elif isinstance(kv_cache_spec, MambaSpec): # This is likely Mamba or other non-attention cache, no splitting. From d71163c2011f93a59f14c5c4570e1f1bc8dba8d0 Mon Sep 17 00:00:00 2001 From: Tarik Sarac Date: Wed, 16 Sep 2026 14:17:03 -0500 Subject: [PATCH 3/5] [ROCm][Kimi-K3] Serve the moonmath MLA decode under decode context parallelism Builds on #56723, which runs the dense DSpark drafter at DCP=1 next to a DCP target. On gfx942 the moonmath kernel now serves decode and verify for a DCP target: each rank attends its own KV shard, with the causal limit taken from the global lengths, and returns its LSE, converted from base 2 to the natural log the merge expects. - moonmath_mla: accept the fused query DCP gathers, pass the global lengths and CP rank, and return the LSE. - rocm_aiter_mla: segmented_dcp_verify lets a subclass keep varlen DCP verify on the flat per-token view instead of AITER's segmented metadata. - Layout: the AITER backends have no block-outer KV layout, so a replicated draft next to a sharded target falls back to padded pages rather than failing. Signed-off-by: Tarik Sarac --- tests/kernels/attention/test_moonmath_mla.py | 83 +++++++++++++++++++ .../v1/attention/backends/mla/moonmath_mla.py | 39 +++++++-- .../attention/backends/mla/rocm_aiter_mla.py | 22 +++-- vllm/v1/attention/backends/utils.py | 12 ++- 4 files changed, 134 insertions(+), 22 deletions(-) create mode 100644 tests/kernels/attention/test_moonmath_mla.py diff --git a/tests/kernels/attention/test_moonmath_mla.py b/tests/kernels/attention/test_moonmath_mla.py new file mode 100644 index 000000000000..080beb652cc8 --- /dev/null +++ b/tests/kernels/attention/test_moonmath_mla.py @@ -0,0 +1,83 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""ROCM_MOONMATH_MLA decode under decode context parallelism.""" + +import math +from types import SimpleNamespace + +import pytest +import torch + +from vllm.platforms import current_platform +from vllm.utils.import_utils import has_moonmath_amd + +pytestmark = pytest.mark.skipif( + not (current_platform.is_rocm() and has_moonmath_amd()), + reason="ROCM_MOONMATH_MLA requires ROCm and moonmath_amd", +) + +_LAT, _ROPE = 512, 64 + + +@pytest.fixture(autouse=True) +def _cuda_default_device(): + with torch.device("cuda"): + yield + + +def test_dcp_shards_merge_to_reference(): + """Each rank attends its round-robin KV shard; merging the outputs by the + returned LSE must reproduce unsharded causal attention over the whole KV.""" + from vllm.v1.attention.backends.mla.moonmath_mla import MoonmathMLAImpl + + world, num_reqs, seq_len, q_len, heads = 2, 2, 257, 4, 12 + num_tokens = num_reqs * q_len + scale = 1.0 / math.sqrt(_LAT + _ROPE) + torch.manual_seed(0) + q = torch.randn(num_tokens, heads, _LAT + _ROPE, dtype=torch.bfloat16) + kv = (torch.randn(num_reqs, seq_len, _LAT + _ROPE) * 4).to(torch.float8_e4m3fnuz) + + impl = MoonmathMLAImpl.__new__(MoonmathMLAImpl) + impl.scale = scale + impl._mm_kv_scale = 1.0 + impl._max_model_len = seq_len + impl.dcp_world_size = world + + outs, lses = [], [] + for rank in range(world): + shard = kv[:, rank::world] + local_len = shard.shape[1] + decode = SimpleNamespace( + seq_lens=torch.full((num_reqs,), local_len, dtype=torch.int32), + paged_kv_indices=torch.arange(num_reqs * local_len, dtype=torch.int32), + paged_kv_indptr=torch.arange( + 0, (num_reqs + 1) * local_len, local_len, dtype=torch.int32 + ), + dcp_tot_seq_lens=torch.full((num_reqs,), seq_len, dtype=torch.int32), + ) + impl.dcp_rank = rank + out, lse = impl.forward_mqa( + q, + shard.reshape(-1, _LAT + _ROPE).contiguous(), + SimpleNamespace(decode=decode, causal=True), + layer=None, + ) + outs.append(out.float()) + lses.append(lse) + weights = torch.softmax(torch.stack(lses), dim=0).unsqueeze(-1) + merged = (weights * torch.stack(outs)).sum(dim=0) + + latent, rope = kv[..., :_LAT].float(), kv[..., _LAT:].float() + q_lat, q_pe = q.float().split((_LAT, _ROPE), dim=-1) + ref = torch.empty_like(merged) + for req in range(num_reqs): + for pos in range(q_len): + row = req * q_len + pos + visible = seq_len - (q_len - 1 - pos) + scores = ( + q_lat[row] @ latent[req, :visible].T + q_pe[row] @ rope[req, :visible].T + ) * scale + ref[row] = torch.softmax(scores, dim=-1) @ latent[req, :visible] + + rel_err = (merged - ref).abs().max() / ref.abs().max() + assert rel_err < 1e-2, f"relative error {rel_err:.3e}" diff --git a/vllm/v1/attention/backends/mla/moonmath_mla.py b/vllm/v1/attention/backends/mla/moonmath_mla.py index ba1e6979fe39..cf3b6942026e 100644 --- a/vllm/v1/attention/backends/mla/moonmath_mla.py +++ b/vllm/v1/attention/backends/mla/moonmath_mla.py @@ -9,13 +9,18 @@ up to 16. Prefill, metadata and cudagraph buffers are inherited from `AiterMLABackend` -unchanged; a batch outside the kernel's domain falls back to it. The package is -optional and imported lazily, so this module is safe to import without it; -`_get_backend_priorities` only offers the backend when `has_moonmath_amd()`. +unchanged; a batch outside the kernel's domain falls back to it. Under decode +context parallelism each rank attends its own KV shard, with the causal limit +taken from the global lengths, and returns its LSE for the cross-rank merge. +The package is optional and imported lazily, so this module is safe to import +without it; `_get_backend_priorities` only offers the backend when +`has_moonmath_amd()`. """ from __future__ import annotations +import math + import torch from vllm.config import get_current_vllm_config @@ -34,6 +39,10 @@ class MoonmathMLAMetadataBuilder(AiterMLAMetadataBuilder): + # Verify reads the flat per-token view; the kernel places each row's causal + # window on the rank's shard from the global lengths. + segmented_dcp_verify = False + def __init__(self, kv_cache_spec, layer_names, vllm_config, device): super().__init__(kv_cache_spec, layer_names, vllm_config, device) # The query is bf16 here (supports_quant_query_input=False), so pin @@ -60,18 +69,18 @@ def forward_mqa( ) -> tuple[torch.Tensor, torch.Tensor | None]: decode = attn_metadata.decode assert decode is not None - assert isinstance(q, tuple), ( - "moonmath MLA is a16w8 and needs the unfused BF16 (nope, pe) query; " - "supports_quant_query_input must stay False on this impl." - ) - q_lat, q_pe = q + # A bf16 (nope, pe) pair (supports_quant_query_input is False); DCP + # concatenates the halves before gathering the query heads. + q_lat, q_pe = q if isinstance(q, tuple) else q.split((_LAT, _ROPE), dim=-1) # Routing reads only shapes and the causal flag, so it is fixed per # captured graph. num_tokens, heads, _ = q_lat.shape num_reqs = decode.seq_lens.size(0) q_len = num_tokens // num_reqs + dcp = self.dcp_world_size > 1 if ( not attn_metadata.causal + or (dcp and decode.dcp_tot_seq_lens is None) or decode.paged_kv_indices is None or heads > _MAX_HEADS or num_tokens != num_reqs * q_len @@ -88,6 +97,11 @@ def forward_mqa( q_lat = q_lat.contiguous() q_pe = q_pe.contiguous() out = torch.empty_like(q_lat) + lse = ( + torch.empty(num_tokens, heads, dtype=torch.float32, device=q_lat.device) + if dcp + else None + ) if self._mm_kv_scale is None: # Static load-time constant, read once: .item() is illegal inside @@ -110,8 +124,15 @@ def forward_mqa( decode.paged_kv_indptr, self.scale, self._mm_kv_scale, + lse=lse, + glen=decode.dcp_tot_seq_lens if dcp else None, + cp_rank=self.dcp_rank, + cp_world=self.dcp_world_size, ) - return out, None + if lse is None: + return out, None + # The kernel's LSE is base 2; the DCP merge reads aiter's natural log. + return out, lse.mul_(math.log(2)) class MoonmathMLABackend(AiterMLABackend): diff --git a/vllm/v1/attention/backends/mla/rocm_aiter_mla.py b/vllm/v1/attention/backends/mla/rocm_aiter_mla.py index 75173e59a3c4..eb93d0b620f2 100644 --- a/vllm/v1/attention/backends/mla/rocm_aiter_mla.py +++ b/vllm/v1/attention/backends/mla/rocm_aiter_mla.py @@ -436,6 +436,10 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]): # Set from the common metadata every build; a batch is causal unless the # drafter says otherwise. _decode_causal: bool = True + # DCP multi-token verify runs on AITER's segmented MLA decode. A subclass + # whose kernel takes the flat per-token view and the global lengths serves + # it without, so it keeps varlen DCP and skips the segmented metadata. + segmented_dcp_verify: ClassVar[bool] = True @staticmethod def _uniform_padded_mtp_qo_len( @@ -485,19 +489,25 @@ def __init__( device: torch.device, ): parallel_config = vllm_config.parallel_config - supports_segmented_dcp_verify = _segmented_dcp_verify_supported( - parallel_config.decode_context_parallel_size, - parallel_config.cp_kv_cache_interleave_size, - ) + dcp_world_size = parallel_config.decode_context_parallel_size + cp_interleave = parallel_config.cp_kv_cache_interleave_size + if self.segmented_dcp_verify: + supports_dcp_with_varlen = _segmented_dcp_verify_supported( + dcp_world_size, cp_interleave + ) + else: + supports_dcp_with_varlen = dcp_world_size > 1 and cp_interleave == 1 super().__init__( kv_cache_spec, layer_names, vllm_config, device, AiterMLAMetadata, - supports_dcp_with_varlen=supports_segmented_dcp_verify, + supports_dcp_with_varlen=supports_dcp_with_varlen, + ) + self._supports_segmented_dcp_verify = ( + self.segmented_dcp_verify and supports_dcp_with_varlen ) - self._supports_segmented_dcp_verify = supports_segmented_dcp_verify self.compilation_config = vllm_config.compilation_config self.decode_attn_out_dtype = vllm_config.model_config.dtype diff --git a/vllm/v1/attention/backends/utils.py b/vllm/v1/attention/backends/utils.py index a567389e9208..973ec8f11ee6 100644 --- a/vllm/v1/attention/backends/utils.py +++ b/vllm/v1/attention/backends/utils.py @@ -310,13 +310,11 @@ def resolve_kv_cache_layout( page_sizes = {spec.page_size_bytes for spec in kv_cache_specs} if len(dcp_sharding) > 1 and len(page_sizes) > 1: # Sharded target and replicated draft caches need independent groups. - # Block-outer layouts can pack those groups without equalizing pages. - candidates = [layout for layout in candidates if layout.is_block_outermost] - if not candidates: - raise ValueError( - "DCP with a replicated draft and mixed KV page sizes requires " - f"a block-outer KV cache layout; supported sets: {supported_layouts}." - ) + # Block-outer layouts can pack those groups without equalizing pages; + # a backend without one pads the replicated attention pages instead. + candidates = [ + layout for layout in candidates if layout.is_block_outermost + ] or candidates if (requested := envs.VLLM_KV_CACHE_LAYOUT) is not None: layout = _layout_from_name(requested) From 951b481ea1bae103dad7e48469ba6328745cc3ac Mon Sep 17 00:00:00 2001 From: Tarik Sarac Date: Thu, 17 Sep 2026 03:04:21 -0500 Subject: [PATCH 4/5] [ROCm][Kimi-K3] moonmath: skip unused AITER MLA schedule, reduce MoE in fp32 - MLA: the AITER MLA builder gets _decode_reads_aiter_schedule. The moonmath builder skips get_mla_metadata_v1 for batches its kernel serves, using the same routing predicate as the impl (5 fewer launches per decode step). - MoE: the down GEMM no longer applies a bf16 copy of the routing weight; one Triton kernel sums each token's top-k rows weighted in fp32 (2 fewer kernels per MoE layer, and the weight keeps the router's precision). Signed-off-by: Tarik Sarac --- tests/kernels/moe/test_ocp_mx_moe.py | 22 ++++++++++ .../test_rocm_aiter_mla_mtp_split.py | 30 ++++++++++++++ .../fused_moe/experts/moonmath_mxfp4_moe.py | 41 +++++++++++++++++-- .../v1/attention/backends/mla/moonmath_mla.py | 19 ++++++++- .../attention/backends/mla/rocm_aiter_mla.py | 14 +++++-- 5 files changed, 118 insertions(+), 8 deletions(-) diff --git a/tests/kernels/moe/test_ocp_mx_moe.py b/tests/kernels/moe/test_ocp_mx_moe.py index febd15622e45..5f560c45676c 100644 --- a/tests/kernels/moe/test_ocp_mx_moe.py +++ b/tests/kernels/moe/test_ocp_mx_moe.py @@ -1887,6 +1887,28 @@ def test_aiter_w4a16_claims_situ_only_with_the_moonmath_kernels( assert aiter_cls._supports_activation(MoEActivation.SWIGLUOAI) +@pytest.mark.skipif(not current_platform.is_cuda_alike(), reason="needs a GPU") +@pytest.mark.parametrize("num_tokens,hidden", [(1, 7), (32, 7168)]) +def test_moonmath_weighted_topk_sum_matches_fp32_reference(num_tokens, hidden): + from vllm.model_executor.layers.fused_moe.experts import ( + moonmath_mxfp4_moe as experts, + ) + from vllm.triton_utils import triton + + topk = 16 + down = torch.randn(num_tokens * topk, hidden, device="cuda", dtype=torch.bfloat16) + weights = torch.rand(num_tokens, topk, device="cuda", dtype=torch.float32) + out = torch.empty(num_tokens, hidden, device="cuda", dtype=torch.bfloat16) + experts._weighted_topk_sum_kernel[ + (num_tokens, triton.cdiv(hidden, experts._REDUCE_BLOCK_H)) + ](down, weights, out, hidden, TOPK=topk, BLOCK_H=experts._REDUCE_BLOCK_H) + + ref = torch.zeros(num_tokens, hidden, device="cuda", dtype=torch.float32) + for k in range(topk): + ref += down.view(num_tokens, topk, hidden)[:, k].float() * weights[:, k, None] + torch.testing.assert_close(out, ref.to(torch.bfloat16)) + + def test_select_mxfp4_moe_backend_raises_with_unsupported_reasons( monkeypatch: pytest.MonkeyPatch, ): diff --git a/tests/v1/attention/test_rocm_aiter_mla_mtp_split.py b/tests/v1/attention/test_rocm_aiter_mla_mtp_split.py index b8ba46d8dec6..94037b82b006 100644 --- a/tests/v1/attention/test_rocm_aiter_mla_mtp_split.py +++ b/tests/v1/attention/test_rocm_aiter_mla_mtp_split.py @@ -140,6 +140,9 @@ def _builder( stub._fill_dcp_verify_page_table = ( AiterMLAMetadataBuilder._fill_dcp_verify_page_table.__get__(stub) ) + stub._decode_reads_aiter_schedule = ( + AiterMLAMetadataBuilder._decode_reads_aiter_schedule.__get__(stub) + ) return stub @@ -1044,3 +1047,30 @@ def test_a_two_token_bf16_block_is_allowed(monkeypatch): monkeypatch, num_heads=12, kv_cache_dtype="auto", qlen=2, mtp_qlen=8 ) assert metadata.has_persistent_metadata + + +@pytest.mark.parametrize( + "num_reqs,qo_len,uniform,causal,heads,reads_schedule", + [ + (8, 4, True, True, 12, False), + (8, 1, True, True, 96, False), + (8, 4, False, True, 12, True), + (8, 4, True, False, 12, True), + (8, 4, True, True, 160, True), + (400, 4, True, True, 12, True), + ], +) +def test_moonmath_skips_aiter_schedule_only_for_batches_it_serves( + num_reqs, qo_len, uniform, causal, heads, reads_schedule +): + from vllm.v1.attention.backends.mla.moonmath_mla import ( + MoonmathMLAMetadataBuilder, + ) + + builder = SimpleNamespace(_decode_num_heads=heads) + assert ( + MoonmathMLAMetadataBuilder._decode_reads_aiter_schedule( + builder, num_reqs, qo_len, uniform, causal + ) + is reads_schedule + ) diff --git a/vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py b/vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py index 3da3ac99a12d..eaa4ab31853a 100644 --- a/vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py +++ b/vllm/model_executor/layers/fused_moe/experts/moonmath_mxfp4_moe.py @@ -27,12 +27,35 @@ ) from vllm.model_executor.layers.quantization.utils.mxfp4_utils import weight_mx_scale from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey +from vllm.triton_utils import tl, triton from vllm.utils.import_utils import has_moonmath_amd logger = init_logger(__name__) __all__ = ["MoonmathW4A16SituExperts"] +_REDUCE_BLOCK_H = 512 + + +@triton.jit +def _weighted_topk_sum_kernel( + down_ptr, + weight_ptr, + out_ptr, + H, + TOPK: tl.constexpr, + BLOCK_H: tl.constexpr, +): + t = tl.program_id(0).to(tl.int64) + offs = tl.program_id(1) * BLOCK_H + tl.arange(0, BLOCK_H) + mask = offs < H + acc = tl.zeros([BLOCK_H], dtype=tl.float32) + for k in tl.static_range(TOPK): + w = tl.load(weight_ptr + t * TOPK + k).to(tl.float32) + v = tl.load(down_ptr + (t * TOPK + k) * H + offs, mask=mask, other=0.0) + acc += v.to(tl.float32) * w + tl.store(out_ptr + t * H + offs, acc.to(out_ptr.dtype.element_ty), mask=mask) + class MoonmathW4A16SituExperts(AiterW4A16ExpertsMonolithic): def __init__( @@ -214,7 +237,7 @@ def situ_moe_forward( assert hidden_states.is_contiguous(), ( "moonmath MoE reads A by row; a strided [T, K] reads the wrong ones" ) - tw = scal.reshape(-1).to(dt) + tw = scal.reshape(-1).to(dt) if apply_router_weight_on_input else None bm_g = ma.mxfp4_moe_gateup_block_m(rows, E) sg, eg, ng = moe_align_block_size(ids, bm_g, E) @@ -260,7 +283,19 @@ def situ_moe_forward( nt, rows, 1, - mul_routed_weight=not apply_router_weight_on_input, + mul_routed_weight=False, ) # down writes one row per (token, expert); AITER scattered in-kernel. - return torch.sum(down.view(T, topk, H), dim=1, dtype=torch.float32).to(dt) + if apply_router_weight_on_input: + return torch.sum(down.view(T, topk, H), dim=1, dtype=torch.float32).to(dt) + out = torch.empty((T, H), dtype=dt, device=dev) + _weighted_topk_sum_kernel[(T, triton.cdiv(H, _REDUCE_BLOCK_H))]( + down, + scal.contiguous(), + out, + H, + TOPK=topk, + BLOCK_H=_REDUCE_BLOCK_H, + num_warps=4, + ) + return out diff --git a/vllm/v1/attention/backends/mla/moonmath_mla.py b/vllm/v1/attention/backends/mla/moonmath_mla.py index cf3b6942026e..45d3217d4101 100644 --- a/vllm/v1/attention/backends/mla/moonmath_mla.py +++ b/vllm/v1/attention/backends/mla/moonmath_mla.py @@ -38,6 +38,13 @@ _MAX_HEADS, _ROWS_PER_SLICE, _MAX_ROW_SLICES = 128, 96, 304 +def _kernel_serves(num_reqs: int, q_len: int, heads: int) -> bool: + return ( + heads <= _MAX_HEADS + and num_reqs * cdiv(q_len * heads, _ROWS_PER_SLICE) <= _MAX_ROW_SLICES + ) + + class MoonmathMLAMetadataBuilder(AiterMLAMetadataBuilder): # Verify reads the flat per-token view; the kernel places each row's causal # window on the rank's shard from the global lengths. @@ -49,6 +56,15 @@ def __init__(self, kv_cache_spec, layer_names, vllm_config, device): # q_dtype rather than let the inherited env gate disagree with it. self._mla_q_dtype = self.decode_attn_out_dtype + def _decode_reads_aiter_schedule( + self, num_reqs: int, qo_len: int, uniform_qo_len: bool, causal: bool + ) -> bool: + return not ( + causal + and uniform_qo_len + and _kernel_serves(num_reqs, qo_len, self._decode_num_heads) + ) + class MoonmathMLAImpl(AiterMLAImpl): """Aiter MLA with the decode on the moonmath kernel.""" @@ -82,9 +98,8 @@ def forward_mqa( not attn_metadata.causal or (dcp and decode.dcp_tot_seq_lens is None) or decode.paged_kv_indices is None - or heads > _MAX_HEADS or num_tokens != num_reqs * q_len - or num_reqs * cdiv(q_len * heads, _ROWS_PER_SLICE) > _MAX_ROW_SLICES + or not _kernel_serves(num_reqs, q_len, heads) ): return super().forward_mqa(q, kv_c_and_k_pe_cache, attn_metadata, layer) diff --git a/vllm/v1/attention/backends/mla/rocm_aiter_mla.py b/vllm/v1/attention/backends/mla/rocm_aiter_mla.py index eb93d0b620f2..5522292d93d2 100644 --- a/vllm/v1/attention/backends/mla/rocm_aiter_mla.py +++ b/vllm/v1/attention/backends/mla/rocm_aiter_mla.py @@ -1009,6 +1009,12 @@ def _fill_dcp_verify_page_table( per_req_page_table.unsqueeze(1) ) + def _decode_reads_aiter_schedule( + self, num_reqs: int, qo_len: int, uniform_qo_len: bool, causal: bool + ) -> bool: + """Whether this decode batch may read get_mla_metadata_v1's schedule.""" + return True + def _build_decode( self, block_table_tensor: torch.Tensor, @@ -1136,6 +1142,7 @@ def _build_decode( else: qo_indptr = query_start_loc_device[: 1 + num_kernel_reqs] + uniform_qo_len = pad_uniform_mtp or bool(torch.all(qo_len == max_qo_len)) has_persistent_metadata = False # Only the asm decode consumes the schedule, so gate on the routing # rather than on num_heads >= 16, which denies it to a padded rank @@ -1160,6 +1167,9 @@ def _build_decode( ) and max_qo_len >= 1 and max_qo_len <= self._mtp_decode_qlen + and self._decode_reads_aiter_schedule( + num_kernel_reqs, int(max_qo_len), uniform_qo_len, causal + ) ) if ( not causal @@ -1182,9 +1192,7 @@ def _build_decode( if use_persistent_metadata: from aiter import get_mla_metadata_v1 - uni_qo_len = ( - max_qo_len if pad_uniform_mtp or torch.all(qo_len == max_qo_len) else -1 - ) + uni_qo_len = max_qo_len if uniform_qo_len else -1 get_mla_metadata_v1( qo_indptr, paged_kv_indptr, From 020da5b1aaa1a9ede69a93015f206d9a5c5f11e8 Mon Sep 17 00:00:00 2001 From: Tarik Sarac Date: Thu, 17 Sep 2026 08:52:38 -0500 Subject: [PATCH 5/5] [ROCm] AITER MLA: keep each layer's KV cache contiguous AITER MLA decode, and moonmath's decode built on it, flattens each layer's cache with .view(), which fails when the layout does not keep the layer's pages contiguous. The backend did not declare that, so under DCP with a replicated drafter whose backend has a block-outer layout (e.g. TRITON_ATTN), #56723's layout preference picked BLNHC and decode crashed at startup. Declare the layer-contiguous layouts, as the sparse AITER MLA backend does. Signed-off-by: Tarik Sarac --- tests/v1/core/test_kv_cache_utils.py | 26 +++++++++++++++++++ .../attention/backends/mla/rocm_aiter_mla.py | 12 ++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/tests/v1/core/test_kv_cache_utils.py b/tests/v1/core/test_kv_cache_utils.py index e74fed35fd0d..fc9c51875aa3 100644 --- a/tests/v1/core/test_kv_cache_utils.py +++ b/tests/v1/core/test_kv_cache_utils.py @@ -1619,6 +1619,32 @@ def test_dcp_target_allocates_replicated_draft_independently( assert [len(group) for group in cached_blocks.blocks] == [1, 4] +@pytest.mark.parametrize("draft_backend", ["TRITON_ATTN", "ROCM_AITER_FA"]) +def test_dcp_aiter_mla_target_keeps_layer_contiguous_layout(monkeypatch, draft_backend): + """AITER MLA decode views each layer's cache as one run, so a replicated draft + must not pull a DCP target into a block-outer layout.""" + from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLABackend + from vllm.v1.attention.backends.registry import AttentionBackendEnum + from vllm.v1.attention.backends.utils import ( + get_supported_kv_cache_layouts, + resolve_kv_cache_layout, + ) + + monkeypatch.delenv("VLLM_KV_CACHE_LAYOUT", raising=False) + config = SimpleNamespace(cache_config=CacheConfig(), kv_transfer_config=None) + draft = FullAttentionSpec( + block_size=16, + num_kv_heads=8, + head_size=64, + dtype=torch.bfloat16, + dcp_sharded=False, + ) + backends = [AiterMLABackend, AttentionBackendEnum[draft_backend].get_class()] + supported = [layout.name for layout in get_supported_kv_cache_layouts(backends)] + layout = resolve_kv_cache_layout(config, [supported], [new_mla_spec(), draft]) + assert layout.is_layer_compact + + @pytest.mark.parametrize("use_mla", [False, True]) def test_full_attention_merge_preserves_replicated_cache_geometry(use_mla): config = VllmConfig(model_config=ModelConfig(max_model_len=1024)) diff --git a/vllm/v1/attention/backends/mla/rocm_aiter_mla.py b/vllm/v1/attention/backends/mla/rocm_aiter_mla.py index 5522292d93d2..a6cd27a59304 100644 --- a/vllm/v1/attention/backends/mla/rocm_aiter_mla.py +++ b/vllm/v1/attention/backends/mla/rocm_aiter_mla.py @@ -36,7 +36,11 @@ from vllm.v1.attention.ops.rocm_aiter_mla_merge import ( merge_mla_segments_triton, ) -from vllm.v1.kv_cache_interface import AttentionSpec, is_quantized_kv_cache +from vllm.v1.kv_cache_interface import ( + AttentionSpec, + KVCacheLayout, + is_quantized_kv_cache, +) if TYPE_CHECKING: from vllm.platforms.interface import DeviceCapability @@ -265,6 +269,12 @@ def get_supported_kernel_block_sizes() -> list[int | MultipleOf]: # into per-token flat indices in the metadata builder. return [MultipleOf(1)] + @classmethod + def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]: + # Decode flattens each layer's cache with .view(), so the layer's pages + # must be contiguous. + return (KVCacheLayout.LBNHC, KVCacheLayout.LBHNC) + @staticmethod def get_name() -> str: return "ROCM_AITER_MLA"