From c9a6a9e4cd612024b4ec2f8e1749fda6dcec04c2 Mon Sep 17 00:00:00 2001 From: lz <145014769+200lz@users.noreply.github.com> Date: Sun, 6 Sep 2026 12:18:08 +0900 Subject: [PATCH 1/6] [Bugfix][KV Cache][MLA] Align packed block strides for V3.2 sparse MLA Align block-outermost packed KV strides to the physical row-addressing requirements of V3.2 sparse MLA and its indexer. Preserve integer-row sparse addressing while accounting for the aligned physical stride in allocation and capacity planning. Co-authored-by: OpenAI Codex Signed-off-by: lz <145014769+200lz@users.noreply.github.com> --- docs/features/nixl_connector_compatibility.md | 6 + .../v1/attention/test_indexer_dcp_localize.py | 2 +- .../v1/attention/test_sparse_mla_backends.py | 104 ++++- .../test_sparse_mla_kv_cache_layout.py | 415 ++++++++++++++++++ tests/v1/core/test_contiguous_kv_packing.py | 185 ++++++++ tests/v1/core/test_kv_cache_utils.py | 47 ++ .../unit/offloading_connector/test_worker.py | 89 ++++ .../unit/test_nixl_desc_geometry.py | 70 +++ .../layers/attention/mla_attention.py | 7 +- vllm/model_executor/models/deepseek_v2.py | 4 +- .../backends/mla/flashinfer_mla_sparse.py | 12 +- .../attention/backends/mla/flashmla_sparse.py | 12 +- vllm/v1/attention/backends/mla/indexer.py | 9 + vllm/v1/core/kv_cache_utils.py | 35 +- vllm/v1/kv_cache_interface.py | 16 +- 15 files changed, 996 insertions(+), 17 deletions(-) create mode 100644 tests/v1/attention/test_sparse_mla_kv_cache_layout.py diff --git a/docs/features/nixl_connector_compatibility.md b/docs/features/nixl_connector_compatibility.md index 031fba5b2f04..2eb454bff5e3 100644 --- a/docs/features/nixl_connector_compatibility.md +++ b/docs/features/nixl_connector_compatibility.md @@ -104,6 +104,12 @@ By default, a **compatibility hash** is checked during handshake. P and D instan - `LBNHC` (token-major, formerly `NHD`) layout is supported but does **not** allow heterogeneous TP head splitting. - Experimental `LBHNC` ↔ `LBNHC` permute: enable via `--kv-transfer-config '{"enable_permute_local_kv": true}'`. Not supported with HMA. +For ordinary V3.2 sparse MLA and indexer caches with native 64-token blocks, +`VLLM_KV_CACHE_LAYOUT=BLHNC` enables shared block-outermost storage. The allocator +aligns the total block stride to every segment's physical row width, adding +bounded tail padding and accounting for it in KV capacity. Individual page sizes +and sparse row-index units are unchanged. Padding depends on the cache inventory. + ### Quantized KV cache [Quantized KV cache](quantization/quantized_kvcache.md) (e.g., FP8) requires both P and D instances to use the **same** `cache_dtype`. Mismatched cache dtypes will fail the compatibility hash check during handshake. diff --git a/tests/v1/attention/test_indexer_dcp_localize.py b/tests/v1/attention/test_indexer_dcp_localize.py index 7f7c20d53e96..5e39c5f83e5a 100644 --- a/tests/v1/attention/test_indexer_dcp_localize.py +++ b/tests/v1/attention/test_indexer_dcp_localize.py @@ -642,7 +642,7 @@ def build(dcp_world_size, dcp_rank, interleave=1): @pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA") -@pytest.mark.parametrize("block_stride_rows", [None, 12]) +@pytest.mark.parametrize("block_stride_rows", [None, 12, 99, 492]) def test_dcp_filter_compacts_valid_slots_for_sparse_kernel( block_stride_rows: int | None, ): diff --git a/tests/v1/attention/test_sparse_mla_backends.py b/tests/v1/attention/test_sparse_mla_backends.py index b2490e391b01..a1c3040447de 100644 --- a/tests/v1/attention/test_sparse_mla_backends.py +++ b/tests/v1/attention/test_sparse_mla_backends.py @@ -327,7 +327,9 @@ def unpack_e2m1(packed: torch.Tensor) -> torch.Tensor: ["auto", "fp8", "fp8_ds_mla", "nvfp4_ds_mla"], ) @pytest.mark.parametrize("tensor_parallel_size", [1, 2, 4]) -@pytest.mark.parametrize("block_size", [32, 64]) +@pytest.mark.parametrize( + "block_size,kv_layout", [(32, "LBNHC"), (64, "LBNHC"), (64, "BLHNC")] +) @pytest.mark.parametrize(("q_scale", "k_scale"), [(1.0, 1.0), (2.0, 3.0)]) def test_sparse_backend_decode_correctness( default_vllm_config, @@ -337,9 +339,11 @@ def test_sparse_backend_decode_correctness( kv_cache_dtype, tensor_parallel_size, block_size, + kv_layout, workspace_init, q_scale: float, k_scale: float, + record_property, ): if kv_cache_dtype not in backend_cls.supported_kv_cache_dtypes: pytest.skip(f"{backend_cls.get_name()} does not support {kv_cache_dtype}") @@ -605,11 +609,60 @@ def test_sparse_backend_decode_correctness( device=device, num_blocks=vllm_config.cache_config.num_gpu_blocks, common_attn_metadata=common_attn_metadata, - randomize_blocks=False, + randomize_blocks=kv_layout == "BLHNC", kv_cache_dtype=kv_cache_dtype, scale=kv_cache_scale, ) + if kv_layout == "BLHNC": + from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups + from vllm.v1.kv_cache_interface import ( + KVCacheGroupSpec, + KVCacheLayout, + MLAAttentionSpec, + UniformTypeKVCacheSpecs, + ) + from vllm.v1.worker.utils import allocate_kv_cache + + row_bytes = kv_cache.shape[-1] * kv_cache.element_size() + specs = { + "mla": MLAAttentionSpec( + block_size=block_size, + num_kv_heads=1, + head_size=kv_cache.shape[-1], + dtype=kv_cache.dtype, + block_stride_alignment_bytes=row_bytes, + ), + "indexer": MLAAttentionSpec( + block_size=block_size, + num_kv_heads=1, + head_size=132, + dtype=torch.uint8, + block_stride_alignment_bytes=132, + ), + } + group = KVCacheGroupSpec( + list(specs), + UniformTypeKVCacheSpecs(block_size=block_size, kv_cache_specs=specs), + ) + vllm_config.cache_config.kv_cache_layout = kv_layout + vllm_config.cache_config.num_gpu_blocks_override = kv_cache.shape[0] + packed_config = get_kv_cache_config_from_groups(vllm_config, [group], 0) + views = allocate_kv_cache( + packed_config, device, KVCacheLayout.BLHNC, [block_size] + ) + views["mla"].copy_(kv_cache) + kv_cache = views["mla"] + views["indexer"].fill_(91) + stride = packed_config.kv_cache_tensors[0].block_stride + content = sum(spec.page_size_bytes for spec in specs.values()) + raw = torch.empty(0, dtype=torch.uint8, device=device).set_( + kv_cache.untyped_storage(), 0, (packed_config.num_blocks * stride,), (1,) + ) + tail = raw.view(packed_config.num_blocks, stride)[:, content:] + assert tail.numel() > 0 + tail.fill_(0xA5) + # The sparse builder clones the layer's dense-MHA prefill backend from # static_forward_context; register a mock layer carrying one. from vllm.v1.attention.backends.mla.prefill import get_mla_prefill_backend @@ -705,6 +758,53 @@ def test_sparse_backend_decode_correctness( assert backend_output.shape == sdpa_reference.shape assert backend_output.dtype == sdpa_reference.dtype assert torch.isfinite(backend_output).all() + record_property( + "max_absolute_error", (backend_output - sdpa_reference).abs().max().item() + ) + rtol, atol = (0.065, 0.05) if kv_cache_dtype.startswith("fp8") else (0.01, 0.01) + error = (backend_output.float() - sdpa_reference.float()).abs() + record_property( + "max_tolerance_ratio", + (error / (atol + rtol * sdpa_reference.float().abs())).max().item(), + ) + + if kv_layout == "BLHNC": + assert (tail == 0xA5).all() + assert (views["indexer"] == 91).all() + # Changing bytes outside this layer must not influence sparse reads. + eager_output = backend_output.clone() + tail.fill_(0x5A) + with torch.inference_mode(): + mock_layer.forward_impl( + query_vllm, kv_c_vllm, k_pe_vllm, kv_cache, metadata, out_buffer + ) + torch.testing.assert_close(out_buffer, eager_output, rtol=0, atol=0) + assert (tail == 0x5A).all() + assert (views["indexer"] == 91).all() + + # One representative batch per backend/format also exercises capture + # and replay after all JIT compilation has completed outside capture. + if batch_name == "mixed_small" and tensor_parallel_size == 2 and q_scale == 1: + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream), torch.inference_mode(): + for _ in range(2): + mock_layer.forward_impl( + query_vllm, kv_c_vllm, k_pe_vllm, kv_cache, metadata, out_buffer + ) + torch.cuda.current_stream().wait_stream(stream) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph), torch.inference_mode(): + mock_layer.forward_impl( + query_vllm, kv_c_vllm, k_pe_vllm, kv_cache, metadata, out_buffer + ) + for sentinel in (0xA5, 0x5A): + tail.fill_(sentinel) + graph.replay() + torch.testing.assert_close(out_buffer, eager_output, rtol=0, atol=0) + assert (tail == sentinel).all() + assert (views["indexer"] == 91).all() + record_property("cuda_graph_replays", 2) # FP8 quantization introduces some error, but should be within reasonable bounds # BF16 (auto) should be very accurate, FP8 allows slightly more tolerance diff --git a/tests/v1/attention/test_sparse_mla_kv_cache_layout.py b/tests/v1/attention/test_sparse_mla_kv_cache_layout.py new file mode 100644 index 000000000000..fc5ba921d8d0 --- /dev/null +++ b/tests/v1/attention/test_sparse_mla_kv_cache_layout.py @@ -0,0 +1,415 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""V3.2 sparse MLA layouts and physical row addressing (issue #55431).""" + +from types import SimpleNamespace + +import pytest +import torch + +import vllm.envs as envs +from vllm.config import CacheConfig +from vllm.model_executor.layers.attention.mla_attention import MLAAttention +from vllm.model_executor.models.deepseek_v2 import DeepseekV32IndexerCache +from vllm.platforms import current_platform +from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import ( + FlashInferMLASparseSM120Backend, + FlashInferMLASparseTRTLLMBackend, +) +from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm90 import ( + FlashInferMLASparseSM90Backend, +) +from vllm.v1.attention.backends.mla.flashmla_sparse import FlashMLASparseBackend +from vllm.v1.attention.backends.mla.indexer import ( + DeepseekV4IndexerBackend, + DeepseekV32IndexerBackend, + KpoolTailBackend, +) +from vllm.v1.attention.backends.utils import ( + get_supported_kv_cache_layouts, + resolve_kv_cache_layout, +) +from vllm.v1.kv_cache_layout import KVCacheLayout + +V32_SPARSE_BACKENDS = ( + FlashMLASparseBackend, + FlashInferMLASparseTRTLLMBackend, + FlashInferMLASparseSM120Backend, + DeepseekV32IndexerBackend, +) + +BLOCK_OUTERMOST = { + KVCacheLayout.BLHNC, + KVCacheLayout.BLNHC, + KVCacheLayout.BHLNC, +} + +pytestmark = pytest.mark.skip_global_cleanup + + +def _mixed_page_specs(cache_dtype="auto", backend=FlashInferMLASparseTRTLLMBackend): + config = SimpleNamespace( + cache_config=CacheConfig(block_size=64), + model_config=SimpleNamespace(dtype=torch.bfloat16), + ) + # Exercise the production spec factories without constructing model weights. + mla = SimpleNamespace( + kv_cache_dtype=cache_dtype, + head_size=576, + sliding_window=None, + attn_backend=backend, + non_causal_multi_token_decode=False, + ) + indexer = SimpleNamespace( + cache_config=config.cache_config, + head_dim=128 + 4, + dtype=torch.uint8, + ) + return [ + MLAAttention.get_kv_cache_spec(mla, config), + DeepseekV32IndexerCache.get_kv_cache_spec(indexer, config), + ] + + +def _resolve(backends, specs, monkeypatch, requested=None) -> KVCacheLayout: + supported = [layout.name for layout in get_supported_kv_cache_layouts(backends)] + monkeypatch.setattr(envs, "VLLM_KV_CACHE_LAYOUT", requested) + vllm_config = SimpleNamespace( + cache_config=SimpleNamespace(kv_cache_layout=None), + kv_transfer_config=None, + ) + return resolve_kv_cache_layout(vllm_config, [supported], specs) + + +@pytest.mark.parametrize("backend", V32_SPARSE_BACKENDS) +def test_backends_declare_only_validated_packed_layout(backend): + declared = backend.supported_kv_cache_layouts() + assert declared is not None + assert BLOCK_OUTERMOST.intersection(declared) == {KVCacheLayout.BLHNC} + assert all(layout.is_layer_compact for layout in declared[:-1]) + + +def test_combined_supported_set_preserves_default_preference(): + supported = get_supported_kv_cache_layouts(list(V32_SPARSE_BACKENDS)) + assert BLOCK_OUTERMOST.intersection(supported) == {KVCacheLayout.BLHNC} + assert supported[0] is KVCacheLayout.LBNHC + + +@pytest.mark.parametrize("name", ["BLNHC", "BHLNC"]) +def test_unadvertised_block_outermost_fails_fast(monkeypatch, name): + with pytest.raises(ValueError, match=name): + _resolve( + [FlashInferMLASparseTRTLLMBackend, DeepseekV32IndexerBackend], + _mixed_page_specs(), + monkeypatch, + requested=name, + ) + + +def test_default_resolution_unchanged(monkeypatch): + layout = _resolve( + [FlashInferMLASparseTRTLLMBackend, DeepseekV32IndexerBackend], + _mixed_page_specs(), + monkeypatch, + ) + assert layout is KVCacheLayout.LBNHC + + +@pytest.mark.parametrize("name", ["LBNHC", "LBHNC", "BLHNC"]) +def test_explicit_supported_layout_accepted(monkeypatch, name): + layout = _resolve( + [FlashInferMLASparseTRTLLMBackend, DeepseekV32IndexerBackend], + _mixed_page_specs(), + monkeypatch, + requested=name, + ) + assert layout.name == name + + +def test_sm90_pairing_still_resolves_lbhnc(): + supported = get_supported_kv_cache_layouts( + [FlashInferMLASparseSM90Backend, DeepseekV32IndexerBackend] + ) + assert supported == [KVCacheLayout.LBHNC] + + +def test_packing_layout_backends_unaffected(): + assert DeepseekV4IndexerBackend.supported_kv_cache_layouts() == ( + KVCacheLayout.BLHNC, + KVCacheLayout.BLNHC, + ) + assert KpoolTailBackend.supported_kv_cache_layouts() == (KVCacheLayout.LBHNC,) + + +@pytest.mark.parametrize( + "cache_dtype,row_bytes", + [ + ("fp8_ds_mla", 656), + ("nvfp4_ds_mla", 352), + ("auto", 1152), + ("fp8", 576), + ], +) +def test_sparse_spec_factories_require_physical_row_alignment(cache_dtype, row_bytes): + mla, indexer = _mixed_page_specs(cache_dtype) + assert mla.state_content_size_bytes == row_bytes + assert mla.block_stride_alignment_bytes == row_bytes + assert indexer.state_content_size_bytes == 132 + assert indexer.block_stride_alignment_bytes == 132 + for spec in (mla, indexer): + assert spec.page_size_padded is None + assert spec.page_size_bytes == 64 * spec.state_content_size_bytes + + +def test_dense_mla_does_not_request_packed_alignment(): + from vllm.v1.attention.backend import AttentionBackend + + mla, _ = _mixed_page_specs(backend=AttentionBackend) + assert mla.block_stride_alignment_bytes is None + + +@pytest.mark.parametrize("cache_dtype", ["auto", "fp8", "fp8_ds_mla", "nvfp4_ds_mla"]) +@pytest.mark.parametrize("warmup", [False, True]) +def test_bind_packed_cache_warmup_uses_physical_rows(monkeypatch, cache_dtype, warmup): + from vllm.model_executor.warmup.jit_warmup import JitWarmupRegistry + from vllm.triton_utils import triton + from vllm.utils.math_utils import next_power_of_2 + from vllm.v1.attention.backends.mla.sparse_utils import ( + _CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL as kernel, + ) + from vllm.v1.attention.backends.mla.sparse_utils import ( + ConvertReqIndexToGlobalIndexKernel, + flat_kv_row_view, + ) + from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups + from vllm.v1.kv_cache_interface import KVCacheGroupSpec, UniformTypeKVCacheSpecs + from vllm.v1.worker.utils import allocate_kv_cache + + mla, indexer = _mixed_page_specs(cache_dtype) + config = SimpleNamespace( + cache_config=CacheConfig(block_size=64), + kernel_config=SimpleNamespace(enable_jit_warmup=warmup), + parallel_config=SimpleNamespace( + decode_context_parallel_size=1, + cp_kv_cache_interleave_size=1, + ), + model_config=SimpleNamespace( + max_model_len=512, hf_config=SimpleNamespace(index_topk=128) + ), + ) + config.cache_config.kv_cache_layout = "BLHNC" + group = KVCacheGroupSpec( + ["mla", "indexer"], + UniformTypeKVCacheSpecs( + block_size=64, kv_cache_specs={"mla": mla, "indexer": indexer} + ), + ) + cache_config = get_kv_cache_config_from_groups(config, [group], 2**20) + view = allocate_kv_cache(cache_config, torch.device("cpu"), KVCacheLayout.BLHNC)[ + "mla" + ] + layer = SimpleNamespace(_vllm_config=config, attn_backend=FlashMLASparseBackend) + registry = JitWarmupRegistry(config) + keys: list[ConvertReqIndexToGlobalIndexKernel.CompileKey] = [] + # Expand real registration and dispatch keys; CUDA compilation is tested on GPU. + monkeypatch.setattr(kernel, "compile", keys.append) + # CPU builds use a Triton placeholder; key enumeration only needs this helper. + monkeypatch.setattr(triton, "next_power_of_2", next_power_of_2, raising=False) + monkeypatch.setattr("vllm.distributed.is_global_first_rank", lambda: False) + with registry.activate(): + MLAAttention.bind_kv_cache(layer, view) + registry.warmup() + rows, stride_rows = flat_kv_row_view(layer.kv_cache, 64) + assert rows.data_ptr() == view.data_ptr() + assert ( + stride_rows * mla.state_content_size_bytes + == cache_config.kv_cache_tensors[0].block_stride + ) + if warmup: + assert keys + assert {key.block_stride_rows for key in keys} == {stride_rows} + else: + assert not keys + + +@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA") +@pytest.mark.parametrize("cache_dtype", ["auto", "fp8", "fp8_ds_mla", "nvfp4_ds_mla"]) +@pytest.mark.parametrize("warmup", [False, True]) +def test_cuda_packed_sparse_binding_and_index_conversion( + dist_init, cache_dtype, warmup +): + from vllm.model_executor.warmup.jit_warmup import JitWarmupRegistry + from vllm.v1.attention.backends.mla.sparse_utils import ( + flat_kv_row_view, + triton_convert_req_index_to_global_index, + ) + from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups + from vllm.v1.kv_cache_interface import KVCacheGroupSpec, UniformTypeKVCacheSpecs + from vllm.v1.worker.utils import allocate_kv_cache + + mla, indexer = _mixed_page_specs(cache_dtype) + config = SimpleNamespace( + cache_config=CacheConfig(block_size=64), + kernel_config=SimpleNamespace(enable_jit_warmup=warmup), + parallel_config=SimpleNamespace( + decode_context_parallel_size=1, cp_kv_cache_interleave_size=1 + ), + model_config=SimpleNamespace( + max_model_len=256, hf_config=SimpleNamespace(index_topk=128) + ), + ) + config.cache_config.kv_cache_layout = "BLHNC" + config.cache_config.num_gpu_blocks_override = 11 + specs = {"mla": mla, "indexer": indexer} + group = KVCacheGroupSpec( + list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs) + ) + cache = get_kv_cache_config_from_groups(config, [group], 0) + views = allocate_kv_cache(cache, torch.device("cuda"), KVCacheLayout.BLHNC) + registry = JitWarmupRegistry(config) + with registry.activate(): + for view in views.values(): + layer = SimpleNamespace( + _vllm_config=config, attn_backend=FlashMLASparseBackend + ) + MLAAttention.bind_kv_cache(layer, view) + assert bool(len(registry)) == warmup + registry.warmup() # Real Triton compilation, with no compile/FFI mock. + + blocks = [9, 2, 7, 1] + tokens = [0, 63, 64, 127, 191, 255] + [-1] * 122 + table = torch.tensor([blocks], dtype=torch.int32, device="cuda") + indices = torch.tensor([tokens], dtype=torch.int32, device="cuda") + req_ids = torch.zeros(1, dtype=torch.int32, device="cuda") + for view in views.values(): + _, stride_rows = flat_kv_row_view(view.squeeze(1), 64) + expected = torch.tensor( + [ + [ + blocks[t // 64] * stride_rows + t % 64 if t >= 0 else -1 + for t in tokens + ] + ], + dtype=torch.int32, + device="cuda", + ) + actual = triton_convert_req_index_to_global_index( + req_ids, table, indices, BLOCK_STRIDE_ROWS=stride_rows, NUM_TOPK_TOKENS=128 + ) + torch.testing.assert_close(actual, expected) + + +@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA") +def test_cuda_sparse_rows_and_cache_offsets_above_two_gib(): + from vllm import _custom_ops as ops + from vllm.v1.attention.backends.mla.sparse_utils import ( + triton_convert_req_index_to_global_index, + ) + from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups + from vllm.v1.kv_cache_interface import KVCacheGroupSpec, UniformTypeKVCacheSpecs + from vllm.v1.worker.utils import allocate_kv_cache + + config = SimpleNamespace(cache_config=CacheConfig(block_size=64)) + config.cache_config.kv_cache_layout = "BLHNC" + config.cache_config.num_gpu_blocks_override = 20307 + req_ids = torch.zeros(1, dtype=torch.int32, device="cuda") + table = torch.tensor([[20306, 7, 20101, 3]], dtype=torch.int32, device="cuda") + tokens = [0, 63, 64, 127, 191, 255] + [-1] * 122 + indices = torch.tensor([tokens], dtype=torch.int32, device="cuda") + + # Convert production-scale coordinates without allocating the full inventory. + for cache_dtype in ("auto", "fp8", "fp8_ds_mla", "nvfp4_ds_mla"): + mla, indexer = _mixed_page_specs(cache_dtype) + specs = {f"mla.{i}": mla for i in range(100)} | {"indexer": indexer} + group = KVCacheGroupSpec( + list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs) + ) + cache = get_kv_cache_config_from_groups(config, [group], 0) + stride = cache.kv_cache_tensors[0].block_stride + for spec in (mla, indexer): + stride_rows = stride // spec.state_content_size_bytes + expected = [ + [20306, 7, 20101, 3][t // 64] * stride_rows + t % 64 if t >= 0 else -1 + for t in tokens + ] + assert max(expected) < torch.iinfo(torch.int32).max + assert max(expected) * spec.state_content_size_bytes > 2**31 + actual = triton_convert_req_index_to_global_index( + req_ids, + table, + indices, + BLOCK_STRIDE_ROWS=stride_rows, + NUM_TOPK_TOKENS=128, + ) + torch.testing.assert_close( + actual, torch.tensor([expected], dtype=torch.int32, device="cuda") + ) + + # Separately dereference >2 GiB offsets through native cache write AND gather + # kernels, using a small (~2 GiB) real allocation rather than a 101-layer pool. + mla, indexer = _mixed_page_specs("auto") + specs = {"mla": mla, "indexer": indexer} + group = KVCacheGroupSpec( + list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs) + ) + cache = get_kv_cache_config_from_groups(config, [group], 0) + stride = cache.kv_cache_tensors[0].block_stride + config.cache_config.num_gpu_blocks_override = 2**31 // stride + 2 + cache = get_kv_cache_config_from_groups(config, [group], 0) + views = allocate_kv_cache(cache, torch.device("cuda"), KVCacheLayout.BLHNC) + view = views["mla"].squeeze(1) + last = cache.num_blocks - 1 + assert last * stride > 2**31 + values = torch.arange(64 * 576, device="cuda", dtype=torch.float32) + values = (values.remainder(97) / 32).to(torch.bfloat16).view(64, 576) + slots = torch.arange(last * 64, (last + 1) * 64, device="cuda", dtype=torch.int64) + scale = torch.ones(1, dtype=torch.float32, device="cuda") + ops.concat_and_cache_mla( + values[:, :512], + values[:, 512:], + view, + slots, + kv_cache_dtype="auto", + scale=scale, + ) + gathered = torch.empty_like(values) + ops.gather_and_maybe_dequant_cache( + view, + gathered, + torch.tensor([[last]], dtype=torch.int32, device="cuda"), + torch.tensor([0, 64], dtype=torch.int32, device="cuda"), + torch.zeros(64, dtype=torch.int32, device="cuda"), + 64, + "auto", + scale, + ) + torch.testing.assert_close(gathered, values, rtol=0, atol=0) + + +def test_trtllm_native_32_row_packed_view(): + """Standalone TRTLLM supports 32 rows; the CUDA V3.2 indexer requires 64.""" + from dataclasses import replace + + from vllm.v1.attention.backends.mla.sparse_utils import flat_kv_row_view + from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups + from vllm.v1.kv_cache_interface import KVCacheGroupSpec + from vllm.v1.worker.utils import allocate_kv_cache + + assert 32 in FlashInferMLASparseTRTLLMBackend.get_supported_kernel_block_sizes() + spec = replace(_mixed_page_specs()[0], block_size=32) + config = SimpleNamespace(cache_config=CacheConfig(block_size=32)) + config.cache_config.kv_cache_layout = "BLHNC" + config.cache_config.num_gpu_blocks_override = 3 + cache = get_kv_cache_config_from_groups( + config, [KVCacheGroupSpec(["mla.0", "mla.1"], spec)], 0 + ) + views = allocate_kv_cache(cache, torch.device("cpu"), KVCacheLayout.BLHNC, [32]) + views["mla.0"].fill_(1) + views["mla.1"].fill_(2) + view = views["mla.0"].squeeze(1) + rows, stride_rows = flat_kv_row_view(view, 32) + assert stride_rows == 64 + assert rows.data_ptr() == views["mla.0"].data_ptr() + assert rows[stride_rows].data_ptr() == views["mla.0"][1].data_ptr() + torch.testing.assert_close(rows[stride_rows : stride_rows + 32], view[1]) + assert torch.all(views["mla.1"] == 2) diff --git a/tests/v1/core/test_contiguous_kv_packing.py b/tests/v1/core/test_contiguous_kv_packing.py index 5249de7f8c11..302c7ebaf020 100644 --- a/tests/v1/core/test_contiguous_kv_packing.py +++ b/tests/v1/core/test_contiguous_kv_packing.py @@ -10,12 +10,15 @@ """ from dataclasses import replace +from math import lcm +from random import Random from unittest.mock import MagicMock import pytest import torch from vllm.config import CacheConfig +from vllm.v1.attention.backends.mla.sparse_utils import flat_kv_row_view from vllm.v1.core.kv_cache_manager import KVCacheManager from vllm.v1.core.kv_cache_utils import ( _get_kv_cache_bytes_per_block, @@ -36,6 +39,7 @@ MLAAttentionSpec, SlidingWindowMLASpec, UniformTypeKVCacheSpecs, + create_kv_cache_views, iter_layer_specs, ) from vllm.v1.worker.utils import allocate_kv_cache @@ -546,5 +550,186 @@ def test_bound_views_round_trip(self, layout): assert views[name].shape[0] == config.num_blocks +@pytest.mark.parametrize( + "cache_dtype,dtype,row_bytes", + [ + ("fp8_ds_mla", torch.uint8, 656), + ("nvfp4_ds_mla", torch.uint8, 352), + ("auto", torch.bfloat16, 1152), + ], +) +def test_sparse_mla_packed_row_addresses(cache_dtype, dtype, row_bytes): + """Heterogeneous pages must remain addressable in whole physical rows.""" + mla = MLAAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=576, + dtype=dtype, + cache_dtype_str=cache_dtype, + state_content_bytes=row_bytes, + block_stride_alignment_bytes=row_bytes, + ) + indexer = replace(_mla(128 + 4), block_stride_alignment_bytes=132) + # A small heterogeneous inventory, not a claim about a model's layer count. + specs = {"mla.0": mla, "mla.1": mla, "idx.0": indexer} + groups = [_uniform_group(specs)] + real_bytes = sum(spec.page_size_bytes for spec in specs.values()) + alignment = lcm(row_bytes, indexer.state_content_size_bytes) + stride = (real_bytes + alignment - 1) // alignment * alignment + memory = 11 * stride + stride - 1 + config = get_kv_cache_config_from_groups(_mock_vllm_config("BLHNC"), groups, memory) + raw = torch.full((config.kv_cache_tensors[0].size,), -1, dtype=torch.int8) + random = Random(55431) + offset = 0 + for tensor in config.kv_cache_tensors: + spec = specs[tensor.layers[0]] + assert tensor.block_stride % spec.state_content_size_bytes == 0 + assert tensor.block_stride == stride + assert tensor.layer_stride == spec.page_size_bytes + assert tensor.offset == offset + views = create_kv_cache_views( + raw, + spec, + config.num_blocks, + KVCacheLayout.BLHNC, + tensor, + kernel_block_size=64, + ) + for i, view in enumerate(views): + layer_offset = offset + i * spec.page_size_bytes + assert view.data_ptr() == raw.data_ptr() + layer_offset + assert view.storage_offset() * view.element_size() == layer_offset + assert view.untyped_storage().data_ptr() == raw.data_ptr() + assert view.untyped_storage().nbytes() == config.num_blocks * stride + assert view.numel() * view.element_size() == ( + config.num_blocks * spec.page_size_bytes + ) + byte_view = view.view(torch.uint8) + width = spec.state_content_size_bytes + rows, stride_rows = flat_kv_row_view(byte_view.squeeze(1), 64) + assert stride_rows == stride // width + for block in [0, config.num_blocks - 1, 7, 2, 9, 1] + [ + random.randrange(config.num_blocks) for _ in range(20) + ]: + token = random.randrange(64) + column = random.randrange(width) + physical = layer_offset + block * stride + token * width + column + row = block * stride_rows + token + assert layer_offset + row * width + column == physical + assert rows[row, column].data_ptr() == raw.data_ptr() + physical + byte_view[block, 0, token, column] = 42 + assert raw[physical].item() == 42 + assert rows[row, column].item() == 42 + offset += len(tensor.layers) * spec.page_size_bytes + assert offset == real_bytes + assert config.num_blocks == memory // stride + assert torch.all(raw.view(config.num_blocks, stride)[:, real_bytes:] == -1) + + +@pytest.mark.parametrize("layout", ["LBNHC", "LBHNC", "BLHNC"]) +def test_packed_stride_alignment_leaves_dense_pages_unchanged(layout): + # Three NVFP4 pages plus one FP8 indexer page already satisfy both row widths. + specs = {f"mla.{i}": _mla(352) for i in range(3)} + specs["idx.0"] = _mla(132) + aligned = { + name: replace(spec, block_stride_alignment_bytes=spec.state_content_size_bytes) + for name, spec in specs.items() + } + config = _mock_vllm_config(layout) + before = get_kv_cache_config_from_groups(config, [_uniform_group(specs)], MEMORY) + after = get_kv_cache_config_from_groups(config, [_uniform_group(aligned)], MEMORY) + assert before.num_blocks == after.num_blocks + assert before.kv_cache_tensors == after.kv_cache_tensors + + +@pytest.mark.parametrize("layout", ["LBNHC", "LBHNC"]) +def test_layer_compact_ignores_packed_stride_alignment(layout): + specs = {"mla": _mla(656), "idx": _mla(132)} + aligned = { + name: replace(spec, block_stride_alignment_bytes=spec.state_content_size_bytes) + for name, spec in specs.items() + } + config = _mock_vllm_config(layout) + before = get_kv_cache_config_from_groups(config, [_uniform_group(specs)], MEMORY) + after = get_kv_cache_config_from_groups(config, [_uniform_group(aligned)], MEMORY) + assert before.num_blocks == after.num_blocks + assert before.kv_cache_tensors == after.kv_cache_tensors + + +def test_packed_stride_alignment_includes_smaller_overlaid_group(): + # The largest group determines content size, but every group constrains stride. + large = replace(_mla(656), block_stride_alignment_bytes=656) + small = replace(_mla(132), block_stride_alignment_bytes=132) + groups = [KVCacheGroupSpec(["large"], large), KVCacheGroupSpec(["small"], small)] + stride = 2 * lcm(656, 132) + config = get_kv_cache_config_from_groups(_mock_vllm_config("BLHNC"), groups, MEMORY) + assert config.num_blocks == MEMORY // stride + assert all( + t.block_stride == stride and t.offset == 0 for t in config.kv_cache_tensors + ) + + +def test_mla_merge_preserves_all_block_stride_requirements(): + spec = _mla(132) + merged = MLAAttentionSpec.merge( + [ + spec, + replace(spec, block_stride_alignment_bytes=132), + replace(spec, block_stride_alignment_bytes=16), + ] + ) + assert merged.block_stride_alignment_bytes == lcm(132, 16) + assert merged.page_size_bytes == spec.page_size_bytes + assert MLAAttentionSpec.merge([spec, spec]).block_stride_alignment_bytes is None + + +@pytest.mark.parametrize("alignment", [0, -1]) +def test_mla_rejects_invalid_block_stride_alignment(alignment): + with pytest.raises( + ValueError, match="block_stride_alignment_bytes must be positive" + ): + replace(_mla(132), block_stride_alignment_bytes=alignment) + + +def test_packed_sparse_mla_rejects_manager_block_splitting(): + specs = { + "mla": replace(_mla(656), block_size=128, block_stride_alignment_bytes=656), + "idx": replace(_mla(132), block_size=128, block_stride_alignment_bytes=132), + } + groups = [ + KVCacheGroupSpec( + list(specs), UniformTypeKVCacheSpecs(block_size=128, kv_cache_specs=specs) + ) + ] + config = get_kv_cache_config_from_groups(_mock_vllm_config("BLHNC"), groups, MEMORY) + with pytest.raises(ValueError, match="cannot be split into 2 kernel blocks of 64"): + allocate_kv_cache(config, torch.device("cpu"), KVCacheLayout.BLHNC, [64]) + + +@pytest.mark.parametrize("row_bytes", [352, 576, 656, 1152]) +def test_packed_sparse_row_coordinates_fit_int32_above_two_gib(row_bytes): + # A conservative 101-segment bound, not the production model's inventory: + # 100 wide pages plus one indexer maximize stride for these two row widths. + wide = replace(_mla(row_bytes), block_stride_alignment_bytes=row_bytes) + indexer = replace(_mla(132), block_stride_alignment_bytes=132) + specs = {f"mla.{i}": wide for i in range(100)} | {"idx": indexer} + config = _mock_vllm_config("BLHNC") + config.cache_config.num_gpu_blocks_override = 20307 + cache = get_kv_cache_config_from_groups(config, [_uniform_group(specs)], 0) + for tensor in cache.kv_cache_tensors: + spec = specs[tensor.layers[0]] + assert tensor.size > 2**31 + assert tensor.block_stride < 2**31 + raw = torch.empty(tensor.size, dtype=torch.int8, device="meta") + view = create_kv_cache_views( + raw, spec, cache.num_blocks, KVCacheLayout.BLHNC, tensor + )[-1] + rows, stride_rows = flat_kv_row_view(view.squeeze(1), 64) + max_row = (cache.num_blocks - 1) * stride_rows + 63 + assert max_row == rows.shape[0] - 1 + assert max_row < torch.iinfo(torch.int32).max + assert max_row * spec.state_content_size_bytes > 2**31 + + if __name__ == "__main__": pytest.main([__file__, "-v"]) diff --git a/tests/v1/core/test_kv_cache_utils.py b/tests/v1/core/test_kv_cache_utils.py index f0bd296b7183..cda1774f7ea3 100644 --- a/tests/v1/core/test_kv_cache_utils.py +++ b/tests/v1/core/test_kv_cache_utils.py @@ -59,6 +59,7 @@ KpoolTailSpec, KVCacheConfig, KVCacheGroupSpec, + KVCacheLayout, KVCacheSpec, KVCacheSpecKind, KVCacheTensor, @@ -1289,6 +1290,52 @@ def test_get_kv_cache_configs_pp_sharding(asymmetric_memory): ] +@pytest.mark.parametrize("override", [None, 11]) +def test_aligned_sparse_mla_capacity_and_pp_replanning(override): + """Every worker must retain the same block count after aligned re-planning.""" + config = VllmConfig(model_config=ModelConfig(max_model_len=64)) + config.cache_config.block_size = 64 + config.cache_config.kv_cache_layout = "BLHNC" + config.cache_config.num_gpu_blocks_override = override + workers = [ + { + f"stage{stage}.{name}": MLAAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=width, + dtype=torch.uint8, + block_stride_alignment_bytes=width, + ) + for name, width in [("mla", 656), ("indexer", 132)] + } + for stage in range(2) + ] + stride = 64944 # ceil(64 * (656 + 132) / lcm(656, 132)) * lcm(656, 132) + configs = get_kv_cache_configs(config, workers, [11 * stride, 20 * stride]) + for cache in configs: + assert cache.num_blocks == 11 + assert {t.size for t in cache.kv_cache_tensors} == {11 * stride} + assert {t.block_stride for t in cache.kv_cache_tensors} == {stride} + from vllm.v1.worker.utils import allocate_kv_cache + + views = allocate_kv_cache(cache, torch.device("cpu"), KVCacheLayout.BLHNC) + storage = next(iter(views.values())).untyped_storage() + assert storage.nbytes() == cache.num_blocks * stride + assert all( + v.untyped_storage().data_ptr() == storage.data_ptr() for v in views.values() + ) + config.model_config.original_max_model_len = -1 + config.model_config.max_model_len = 2048 + get_kv_cache_configs(config, workers, [11 * stride, 20 * stride]) + assert config.model_config.max_model_len == 10 * 64 + # Twelve blocks cover only eleven usable blocks once the null block is reserved. + config.cache_config.num_gpu_blocks_override = None + config.model_config.original_max_model_len = None + config.model_config.max_model_len = 12 * 64 + with pytest.raises(ValueError, match="max seq len"): + get_kv_cache_configs(config, workers, [12 * stride, 20 * stride]) + + def test_project_kv_cache_groups_to_worker(): spec_a = new_kv_cache_spec() spec_b = new_kv_cache_spec(num_kv_heads=4) diff --git a/tests/v1/kv_connector/unit/offloading_connector/test_worker.py b/tests/v1/kv_connector/unit/offloading_connector/test_worker.py index 366624e1d3b1..3d8736fc8609 100644 --- a/tests/v1/kv_connector/unit/offloading_connector/test_worker.py +++ b/tests/v1/kv_connector/unit/offloading_connector/test_worker.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from unittest.mock import MagicMock +import numpy as np import pytest import torch @@ -636,3 +637,91 @@ def test_register_kv_caches_uniform_type(backend): # opaque mapping rather than a certified, parallelism-agnostic one assert group_refs[0].mapping.parallelism_agnostic assert not group_refs[1].mapping.parallelism_agnostic + + +@pytest.mark.parametrize("dtype,row_width", [(torch.bfloat16, 576), (torch.uint8, 656)]) +def test_packed_tail_alignment_survives_registration_and_transfer(dtype, row_width): + """Offloading must copy whole physical blocks, including alignment tails.""" + from vllm.config import CacheConfig + from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups + from vllm.v1.kv_offload.cpu.gpu_worker import SingleDirectionOffloadingHandler + from vllm.v1.worker.utils import allocate_kv_cache + + specs = { + name: MLAAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=width, + dtype=dt, + block_stride_alignment_bytes=width * get_dtype_size(dt), + ) + for name, width, dt in [ + ("mla.0", row_width, dtype), + ("mla.1", row_width, dtype), + ("indexer", 132, torch.uint8), + ] + } + group = KVCacheGroupSpec( + list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs) + ) + config = _single_rank_vllm_config(1) + config.cache_config = CacheConfig(block_size=64) + config.cache_config.kv_cache_layout = "BLHNC" + config.cache_config.num_gpu_blocks_override = 3 + cache = get_kv_cache_config_from_groups(config, [group], 0) + views = allocate_kv_cache(cache, torch.device("cpu"), KVCacheLayout.BLHNC) + before = {name: (v.data_ptr(), v.shape, v.stride()) for name, v in views.items()} + for value, view in enumerate(views.values(), 1): + view.fill_(value) + + worker, spec = _make_worker(cache) + worker.vllm_config = config + worker.register_kv_caches(views) + canonical = spec.get_worker.call_args.args[0] + assert len(canonical.tensors) == 1 + packed = canonical.tensors[0] + stride = cache.kv_cache_tensors[0].block_stride + content = sum(s.page_size_bytes for s in specs.values()) + assert stride > content + assert packed.page_size_bytes == stride + assert packed.tensor.shape == (3, stride) + assert packed.tensor.stride() == (stride, 1) + assert packed.tensor.data_ptr() == views["mla.0"].untyped_storage().data_ptr() + assert canonical.group_data_refs == [[CanonicalKVCacheRef(0, stride)]] + packed.tensor[:, content:].fill_(91) + + # Exercise the real direct transfer descriptor builder on CPU; only CUDA + # stream allocation/dispatch is omitted. Registration/mapping is unmocked. + handler = object.__new__(SingleDirectionOffloadingHandler) + handler.src_tensors = [packed.tensor] + handler.dst_tensors = [torch.empty_like(packed.tensor)] + handler.src_blocks_per_chunk = handler.dst_blocks_per_chunk = 1 + handler.layer_refs_per_group = canonical.group_data_refs + src, dst, sizes = (np.empty(3, dtype=np.uint64) for _ in range(3)) + count, nbytes = handler._fill_direct_ops( + 0, + np.array([0, 1, 2]), + np.array([2, 0, 1]), + 3, + 0, + 0, + src, + dst, + sizes, + 0, + ) + assert count == 3 and nbytes == 3 * stride + assert sizes.tolist() == [stride] * 3 + assert src.tolist() == [packed.tensor.data_ptr() + b * stride for b in range(3)] + assert dst.tolist() == [ + handler.dst_tensors[0].data_ptr() + b * stride for b in (2, 0, 1) + ] + assert src[-1] + sizes[-1] == packed.tensor.data_ptr() + packed.tensor.numel() + offset = 0 + for value, (name, layer_spec) in enumerate(specs.items(), 1): + view = views[name] + assert (view.data_ptr(), view.shape, view.stride()) == before[name] + assert view[1].data_ptr() == packed.tensor[1].data_ptr() + offset + assert torch.all(view == value) + offset += layer_spec.page_size_bytes + assert torch.all(packed.tensor[:, content:] == 91) diff --git a/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py b/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py index 712a9d30c08d..94ff194cce28 100644 --- a/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py +++ b/tests/v1/kv_connector/unit/test_nixl_desc_geometry.py @@ -372,6 +372,76 @@ def test_register_compressed_indexer_uses_virtual_transfer_pages( ) +@pytest.mark.parametrize("layout,num_regions", [("LBHNC", 3), ("BLHNC", 1)]) +def test_sparse_mla_allocator_views_register_packed_region(layout, num_regions): + from unittest.mock import MagicMock + + from vllm.config import set_current_vllm_config + from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker as bw + from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import ( + NixlConnectorWorker, + ) + from vllm.v1.attention.backends.mla.flashmla_sparse import FlashMLASparseBackend + from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups + from vllm.v1.kv_cache_interface import ( + KVCacheGroupSpec, + KVCacheLayout, + MLAAttentionSpec, + UniformTypeKVCacheSpecs, + ) + from vllm.v1.worker.utils import allocate_kv_cache + + specs = { + name: MLAAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=width, + dtype=torch.uint8, + block_stride_alignment_bytes=width, + ) + for name, width in [("mla.0", 656), ("mla.1", 656), ("idx.0", 132)] + } + group = KVCacheGroupSpec( + list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs) + ) + config = create_vllm_config(block_size=64) + config.cache_config.kv_cache_layout = layout + config.cache_config.num_gpu_blocks_override = 11 + config.kv_transfer_config.kv_buffer_device = "cuda" + cache_config = get_kv_cache_config_from_groups(config, [group], 2**20) + caches = allocate_kv_cache(cache_config, torch.device("cpu"), KVCacheLayout[layout]) + fake_platform = MagicMock() + fake_platform.device_type = "cuda" + fake_platform.get_nixl_memory_type.return_value = "VRAM" + with ( + patch.object(bw, "NixlWrapper", _RecordingNixl), + patch.object(bw, "get_tensor_model_parallel_rank", return_value=0), + patch.object(bw, "get_tensor_model_parallel_world_size", return_value=1), + patch.object( + bw, "get_current_attn_backends", return_value=[FlashMLASparseBackend] + ), + patch.object(bw, "current_platform", fake_platform), + set_current_vllm_config(config), + ): + worker = NixlConnectorWorker(config, "local-engine", cache_config) + worker.use_mla = True + worker.register_kv_caches(caches) + assert worker.num_regions == num_regions + assert worker._region_is_mla == [True] * num_regions + if layout == "BLHNC": + storage = caches["mla.0"].untyped_storage() + stride = cache_config.kv_cache_tensors[0].block_stride + assert storage.nbytes() == cache_config.num_blocks * stride + assert worker.block_len_per_layer == worker.block_stride_per_layer == [stride] + assert worker._registered_descs[0] == [ + (storage.data_ptr(), storage.nbytes(), 0, "") + ] + np.testing.assert_array_equal( + worker.src_blocks_data, + [[storage.data_ptr() + b * stride, stride, 0] for b in range(11)], + ) + + def _make_remote_meta( worker, remote_block_size, diff --git a/vllm/model_executor/layers/attention/mla_attention.py b/vllm/model_executor/layers/attention/mla_attention.py index 00e10e914234..51f0abcfa3b3 100644 --- a/vllm/model_executor/layers/attention/mla_attention.py +++ b/vllm/model_executor/layers/attention/mla_attention.py @@ -1292,10 +1292,15 @@ def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec: **common_kwargs, sliding_window=self.sliding_window, ) - return MLAAttentionSpec( + spec = MLAAttentionSpec( **common_kwargs, non_causal_multi_token_decode=self.non_causal_multi_token_decode, ) + if self.attn_backend.is_sparse(): + spec = replace( + spec, block_stride_alignment_bytes=spec.state_content_size_bytes + ) + return spec def _v_up_proj(self, x: torch.Tensor, out: torch.Tensor): # Convert from (B, N, L) to (N, B, L) diff --git a/vllm/model_executor/models/deepseek_v2.py b/vllm/model_executor/models/deepseek_v2.py index bc99509c7f45..5b47b3ba1544 100644 --- a/vllm/model_executor/models/deepseek_v2.py +++ b/vllm/model_executor/models/deepseek_v2.py @@ -26,6 +26,7 @@ import typing from collections.abc import Callable, Iterable +from dataclasses import replace from itertools import islice import torch @@ -651,12 +652,13 @@ def bind_kv_cache(self, kv_cache: torch.Tensor) -> None: self.kv_cache = kv_cache.squeeze(1) def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec: - return MLAAttentionSpec( + spec = MLAAttentionSpec( block_size=self.cache_config.block_size, num_kv_heads=1, head_size=self.head_dim, dtype=self.dtype, ) # Only has one vector instead of K + V + return replace(spec, block_stride_alignment_bytes=spec.state_content_size_bytes) def forward(self): ... diff --git a/vllm/v1/attention/backends/mla/flashinfer_mla_sparse.py b/vllm/v1/attention/backends/mla/flashinfer_mla_sparse.py index 194db8edc3a8..d28f9b2d7684 100644 --- a/vllm/v1/attention/backends/mla/flashinfer_mla_sparse.py +++ b/vllm/v1/attention/backends/mla/flashinfer_mla_sparse.py @@ -32,7 +32,7 @@ triton_convert_req_index_to_global_index, triton_filter_and_convert_dcp_index, ) -from vllm.v1.kv_cache_interface import AttentionSpec +from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout if TYPE_CHECKING: from vllm.model_executor.models.deepseek_v2 import Indexer @@ -67,6 +67,16 @@ def is_mla(cls) -> bool: def is_sparse(cls) -> bool: return True + @classmethod + def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]: + # Sparse MLA specs align the packed stride to whole physical rows. + return ( + KVCacheLayout.LBNHC, + KVCacheLayout.LBHNC, + KVCacheLayout.LHBNC, + KVCacheLayout.BLHNC, + ) + class FlashInferMLASparseTRTLLMBackend(_FlashInferMLASparseBackendBase): """FlashInfer sparse MLA backend using the TRTLLM-gen launcher.""" diff --git a/vllm/v1/attention/backends/mla/flashmla_sparse.py b/vllm/v1/attention/backends/mla/flashmla_sparse.py index d8d8246423ab..1925027bf588 100644 --- a/vllm/v1/attention/backends/mla/flashmla_sparse.py +++ b/vllm/v1/attention/backends/mla/flashmla_sparse.py @@ -42,7 +42,7 @@ flash_mla_with_kvcache, get_mla_metadata, ) -from vllm.v1.kv_cache_interface import AttentionSpec +from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout from vllm.v1.worker.workspace import current_workspace_manager if TYPE_CHECKING: @@ -108,6 +108,16 @@ class FlashMLASparseBackend(AttentionBackend): + @classmethod + def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]: + # Sparse MLA specs align the packed stride to whole physical rows. + return ( + KVCacheLayout.LBNHC, + KVCacheLayout.LBHNC, + KVCacheLayout.LHBNC, + KVCacheLayout.BLHNC, + ) + supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16] supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [ "auto", diff --git a/vllm/v1/attention/backends/mla/indexer.py b/vllm/v1/attention/backends/mla/indexer.py index 6198c14eb738..505aef091bd7 100644 --- a/vllm/v1/attention/backends/mla/indexer.py +++ b/vllm/v1/attention/backends/mla/indexer.py @@ -227,6 +227,15 @@ def split_indexer_prefill_chunks( class DeepseekV32IndexerBackend(AttentionBackend): + @classmethod + def supported_kv_cache_layouts(cls) -> tuple[KVCacheLayout, ...]: + return ( + KVCacheLayout.LBNHC, + KVCacheLayout.LBHNC, + KVCacheLayout.LHBNC, + KVCacheLayout.BLHNC, + ) + @classmethod def supports_pcp(cls) -> bool: return True diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index 2fce0c0f4e2a..c6e3b27a2b55 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -978,7 +978,7 @@ def check_enough_kv_cache_memory( # of the specs since grouping may unify them in-place. groups = get_kv_cache_groups(vllm_config, dict(kv_cache_spec)) check_memory = ( - available_memory - _pool_bytes_per_block(groups) + available_memory - _pool_bytes_per_block(groups, vllm_config) if groups else available_memory ) @@ -1080,14 +1080,18 @@ def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int: return num_blocks -def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int: +def _pool_bytes_per_block( + kv_cache_groups: list[KVCacheGroupSpec], vllm_config: VllmConfig | None = None +) -> int: """ Bytes consumed by one block in the worker's shared KV cache pool, mirroring the divisor used by `get_kv_cache_config_from_groups` to convert `available_memory` into `num_blocks`. Used to compute the effective KV cache capacity once `num_gpu_blocks_override` is applied. """ - return _get_kv_cache_bytes_per_block(kv_cache_groups) + layout_name = vllm_config.cache_config.kv_cache_layout if vllm_config else None + layout = KVCacheLayout[layout_name] if layout_name is not None else None + return _get_kv_cache_bytes_per_block(kv_cache_groups, layout) def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int: @@ -1557,8 +1561,9 @@ def _get_per_layer_spec( def _get_kv_cache_bytes_per_block( kv_cache_groups: list[KVCacheGroupSpec], + layout: KVCacheLayout | None = None, ) -> int: - """Return the largest cache group's bytes per block.""" + """Return the largest group's bytes per block, including packed tail padding.""" if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None: _, _, mla_names, idx_names, mla_page, idx_page, _, _ = glm5_layout return len(mla_names) * mla_page + len(idx_names) * idx_page @@ -1571,6 +1576,16 @@ def _get_kv_cache_bytes_per_block( for group in kv_cache_groups ) assert bytes_per_block > 0 + if layout is not None and layout.is_block_outermost: + alignment = math.lcm( + *( + spec.block_stride_alignment_bytes or 1 + for group in kv_cache_groups + for spec in iter_layer_specs(group.kv_cache_spec) + if isinstance(spec, MLAAttentionSpec) + ) + ) + bytes_per_block = cdiv(bytes_per_block, alignment) * alignment return bytes_per_block @@ -1701,7 +1716,7 @@ def add_tensor(layer_name: str, spec: KVCacheSpec, offset: int) -> None: layout = vllm_config.cache_config.get_resolved_kv_cache_layout() validate_kv_cache_layout(layout, kv_cache_groups) - bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups) + bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups, layout) interleaved_block_stride = bytes_per_block if layout.is_block_outermost else None num_blocks = available_memory // bytes_per_block @@ -2359,7 +2374,7 @@ def _max_memory_usage_bytes_from_groups( total_blocks += 1 return total_blocks * (len(mla_names) * mla_page + len(idx_names) * idx_page) - bytes_per_block = _pool_bytes_per_block(kv_cache_groups) + bytes_per_block = _pool_bytes_per_block(kv_cache_groups, vllm_config) total_blocks = 0 for group in kv_cache_groups: spec = group.kv_cache_spec @@ -2608,7 +2623,7 @@ def get_kv_cache_configs( if not groups: adjusted_memory.append(avail_mem) continue - bytes_per_block = _pool_bytes_per_block(groups) + bytes_per_block = _pool_bytes_per_block(groups, vllm_config) logger.info( "Overriding num_gpu_blocks=%d with num_gpu_blocks_override=%d", avail_mem // bytes_per_block, @@ -2621,7 +2636,7 @@ def get_kv_cache_configs( # the capacity check both plan against usable blocks. Allocation below # still uses the full memory. check_memory = [ - avail_mem - _pool_bytes_per_block(groups) if groups else avail_mem + avail_mem - _pool_bytes_per_block(groups, vllm_config) if groups else avail_mem for groups, avail_mem in zip(projected_groups_per_worker, available_memory) ] @@ -2665,7 +2680,9 @@ def get_kv_cache_configs( # strides and offsets stay consistent with the shrunken allocation. groups = kv_cache_config.kv_cache_groups kv_cache_configs[i] = get_kv_cache_config_from_groups( - vllm_config, groups, min_num_blocks * _pool_bytes_per_block(groups) + vllm_config, + groups, + min_num_blocks * _pool_bytes_per_block(groups, vllm_config), ) return kv_cache_configs diff --git a/vllm/v1/kv_cache_interface.py b/vllm/v1/kv_cache_interface.py index bb9494d15c6c..3d2c5ad5a964 100644 --- a/vllm/v1/kv_cache_interface.py +++ b/vllm/v1/kv_cache_interface.py @@ -10,7 +10,7 @@ from enum import Enum, IntEnum from fractions import Fraction from functools import cached_property -from math import prod +from math import lcm, prod from typing import TYPE_CHECKING, TypeVar import torch @@ -554,6 +554,10 @@ def _apply_alignment_padding(spec: MLAAttentionSpec | SlidingWindowMLASpec): class MLAAttentionSpec(FullAttentionSpec): # TODO(Lucas/Chen): less hacky way to do this cache_dtype_str: str | None = None + block_stride_alignment_bytes: int | None = None + """Packed blocks must start a whole number of rows apart for row indexing. + Unlike page padding, this aligns only the total block-outermost stride. + """ # DeepseekV4 only fields. Non-DeepseekV4 MLA models leave these at defaults. alignment: int | None = None # Default to None for no padding. model_version: str | None = None @@ -567,6 +571,11 @@ class MLAAttentionSpec(FullAttentionSpec): def __post_init__(self): super().__post_init__() + if ( + self.block_stride_alignment_bytes is not None + and self.block_stride_alignment_bytes <= 0 + ): + raise ValueError("block_stride_alignment_bytes must be positive") _apply_alignment_padding(self) @classmethod @@ -598,6 +607,11 @@ def merge(cls, specs: list[Self]) -> Self: num_head_slots=specs[0].num_head_slots, state_content_bytes=specs[0].state_content_bytes, cache_dtype_str=cache_dtype_str_set.pop(), + block_stride_alignment_bytes=( + lcm(*(spec.block_stride_alignment_bytes or 1 for spec in specs)) + if any(spec.block_stride_alignment_bytes is not None for spec in specs) + else None + ), tokens_per_state=tokens_per_state_set.pop(), model_version=model_version_set.pop(), storage_block_size=storage_block_size_set.pop(), From 3cce9f9efdde7ca43e14199a8022f580e8dace13 Mon Sep 17 00:00:00 2001 From: lz <145014769+200lz@users.noreply.github.com> Date: Sun, 6 Sep 2026 12:48:05 +0900 Subject: [PATCH 2/6] [Bugfix][KV Cache] Use aligned group bytes for memory admission Use the existing group-aware demand and length estimate after reserving the physical null block. Cover admission and estimate boundaries against actual packed FP8 MLA/indexer allocation, and guard the large CUDA test by free memory. Co-authored-by: OpenAI Codex Signed-off-by: lz <145014769+200lz@users.noreply.github.com> --- .../test_sparse_mla_kv_cache_layout.py | 7 +++ tests/v1/core/test_kv_cache_utils.py | 51 +++++++++++++++++++ vllm/v1/core/kv_cache_utils.py | 4 +- 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/tests/v1/attention/test_sparse_mla_kv_cache_layout.py b/tests/v1/attention/test_sparse_mla_kv_cache_layout.py index fc5ba921d8d0..54e68fb7839a 100644 --- a/tests/v1/attention/test_sparse_mla_kv_cache_layout.py +++ b/tests/v1/attention/test_sparse_mla_kv_cache_layout.py @@ -356,6 +356,13 @@ def test_cuda_sparse_rows_and_cache_offsets_above_two_gib(): stride = cache.kv_cache_tensors[0].block_stride config.cache_config.num_gpu_blocks_override = 2**31 // stride + 2 cache = get_kv_cache_config_from_groups(config, [group], 0) + # All layer views share this allocation; leave 10% for scratch/allocator overhead. + required_free_bytes = cache.kv_cache_tensors[0].size * 11 // 10 + if torch.accelerator.get_memory_info()[0] < required_free_bytes: + pytest.skip( + f"Requires approximately {required_free_bytes / 2**30:.2f} GiB of free " + "CUDA memory (including 10% headroom)" + ) views = allocate_kv_cache(cache, torch.device("cuda"), KVCacheLayout.BLHNC) view = views["mla"].squeeze(1) last = cache.num_blocks - 1 diff --git a/tests/v1/core/test_kv_cache_utils.py b/tests/v1/core/test_kv_cache_utils.py index cda1774f7ea3..56b653586bec 100644 --- a/tests/v1/core/test_kv_cache_utils.py +++ b/tests/v1/core/test_kv_cache_utils.py @@ -3858,6 +3858,57 @@ def test_check_enough_kv_cache_memory_reserves_null_block(): ) +@pytest.mark.parametrize("logical_blocks,max_model_len", [(1, 64), (2, 192)]) +def test_check_enough_kv_cache_memory_uses_aligned_groups( + logical_blocks, max_model_len +): + """Admission and its estimate must match the allocator's usable blocks.""" + from vllm.v1.core.block_pool import BlockPool + from vllm.v1.worker.utils import allocate_kv_cache + + config = VllmConfig(model_config=ModelConfig(max_model_len=max_model_len)) + config.cache_config.block_size = 64 + config.cache_config.kv_cache_layout = "BLHNC" + # Ordinary FP8 MLA storage and its FP8 indexer (128 data + 4 scale bytes). + specs = { + name: MLAAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=width, + dtype=torch.uint8, + block_stride_alignment_bytes=width, + ) + for name, width in [("mla", 576), ("indexer", 132)] + } + groups = get_kv_cache_groups(config, specs) + logical_bytes = sum(spec.page_size_bytes for spec in specs.values()) + stride = kv_cache_utils._pool_bytes_per_block(groups, config) + assert stride > logical_bytes + available_memory = stride + logical_blocks * logical_bytes + cache = kv_cache_utils.get_kv_cache_config_from_groups( + config, groups, available_memory + ) + views = allocate_kv_cache(cache, torch.device("cpu"), KVCacheLayout.BLHNC) + assert ( + next(iter(views.values())).untyped_storage().nbytes() + == cache.num_blocks * stride + ) + pool = BlockPool(cache.num_blocks, enable_caching=False, hash_block_size=64) + usable_blocks = pool.get_num_free_blocks() + assert usable_blocks == logical_blocks - 1 + with pytest.raises(ValueError, match="max seq len") as exc: + check_enough_kv_cache_memory(config, specs, available_memory) + if usable_blocks: + assert f"estimated maximum model length is {usable_blocks * 64}." in str( + exc.value + ) + else: + assert "estimated maximum model length" not in str(exc.value) + assert config.model_config.max_model_len == max_model_len + # Exact physical capacity, including the reserved null block, is accepted. + check_enough_kv_cache_memory(config, specs, (max_model_len // 64 + 1) * stride) + + def test_is_full_attention_spec_unwraps_uniform_type_specs(): """``UniformTypeKVCacheSpecs`` is not a ``FullAttentionSpec``, so callers scanning groups with a bare isinstance miss DeepSeek-V4-shaped configs.""" diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index c6e3b27a2b55..01d3a1b55bd1 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -984,9 +984,9 @@ def check_enough_kv_cache_memory( ) _check_enough_kv_cache_memory( check_memory, - lambda: max_memory_usage_bytes(vllm_config, kv_cache_spec.values()), + partial(_max_memory_usage_bytes_from_groups, vllm_config, groups), vllm_config.model_config.max_model_len, - lambda am: estimate_max_model_len(vllm_config, kv_cache_spec, am), + partial(_estimate_max_model_len_from_groups, vllm_config, groups), ) From 758accb7008deb979839a6211c485c495e50e522 Mon Sep 17 00:00:00 2001 From: lz <145014769+200lz@users.noreply.github.com> Date: Sun, 6 Sep 2026 13:27:19 +0900 Subject: [PATCH 3/6] [Bugfix][KV Cache] Resolve layout aliases in capacity planning Use the standard layout resolver for pool-byte accounting while preserving unresolved defaults. Cover legacy aliases against real grouping and allocation, plus canonical BLHNC and unresolved-layout behavior. Co-authored-by: OpenAI Codex Signed-off-by: lz <145014769+200lz@users.noreply.github.com> --- tests/v1/core/test_contiguous_kv_packing.py | 34 +++++++++++++++++++++ vllm/v1/core/kv_cache_utils.py | 8 +++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/tests/v1/core/test_contiguous_kv_packing.py b/tests/v1/core/test_contiguous_kv_packing.py index 302c7ebaf020..a026eb9f7e7d 100644 --- a/tests/v1/core/test_contiguous_kv_packing.py +++ b/tests/v1/core/test_contiguous_kv_packing.py @@ -19,6 +19,7 @@ from vllm.config import CacheConfig from vllm.v1.attention.backends.mla.sparse_utils import flat_kv_row_view +from vllm.v1.attention.backends.utils import resolve_kv_cache_layout from vllm.v1.core.kv_cache_manager import KVCacheManager from vllm.v1.core.kv_cache_utils import ( _get_kv_cache_bytes_per_block, @@ -642,6 +643,39 @@ def test_packed_stride_alignment_leaves_dense_pages_unchanged(layout): assert before.kv_cache_tensors == after.kv_cache_tensors +@pytest.mark.parametrize( + "layout_name,resolved", + [ + ("NHD", KVCacheLayout.LBNHC), + ("HND", KVCacheLayout.LBHNC), + ("BLHNC", KVCacheLayout.BLHNC), + (None, None), + ], +) +def test_pool_bytes_resolves_layout_aliases(layout_name, resolved): + config = _mock_vllm_config(layout_name) + specs = { + name: replace(_mla(width), block_stride_alignment_bytes=width) + for name, width in [("mla", 576), ("idx", 132)] + } + if resolved is None: + groups = [_uniform_group(specs)] + expected = sum(spec.page_size_bytes for spec in specs.values()) + assert _pool_bytes_per_block(groups, config) == expected + assert _pool_bytes_per_block(groups) == expected + return + assert resolve_kv_cache_layout(config, [[resolved.name]]) == resolved + assert config.cache_config.kv_cache_layout == layout_name + groups = get_kv_cache_groups(config, specs) + cache = get_kv_cache_config_from_groups(config, groups, MEMORY) + views = allocate_kv_cache(cache, torch.device("cpu"), resolved) + allocation_bytes = views["mla"].untyped_storage().nbytes() + # Capacity accounting must accept the same names and bytes as allocation. + pool_bytes = _pool_bytes_per_block(groups, config) + assert allocation_bytes == cache.num_blocks * pool_bytes + assert cache.num_blocks == MEMORY // pool_bytes + + @pytest.mark.parametrize("layout", ["LBNHC", "LBHNC"]) def test_layer_compact_ignores_packed_stride_alignment(layout): specs = {"mla": _mla(656), "idx": _mla(132)} diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index 01d3a1b55bd1..e1999b495f7a 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -1089,8 +1089,12 @@ def _pool_bytes_per_block( `available_memory` into `num_blocks`. Used to compute the effective KV cache capacity once `num_gpu_blocks_override` is applied. """ - layout_name = vllm_config.cache_config.kv_cache_layout if vllm_config else None - layout = KVCacheLayout[layout_name] if layout_name is not None else None + layout = ( + vllm_config.cache_config.get_resolved_kv_cache_layout() + if vllm_config is not None + and vllm_config.cache_config.kv_cache_layout is not None + else None + ) return _get_kv_cache_bytes_per_block(kv_cache_groups, layout) From 5827abeae7d421ead97d676986c2abfa0548cde0 Mon Sep 17 00:00:00 2001 From: lz <145014769+200lz@users.noreply.github.com> Date: Tue, 22 Sep 2026 01:24:43 +0900 Subject: [PATCH 4/6] [Bugfix][KV Cache] Honor physical stride requirements for sparse MLA Publish generic block-stride requirements from backend, cache format and native hardware addressing. Combine packed stride and HiSparse hot-page constraints once and use physical pool strides consistently in capacity planning. Keep upstream fused indexer writes and current sparse layout capabilities. Distinguish flattened-row warmup from SM100 FlashMLA quantized TMA alignment. Co-authored-by: Codex Signed-off-by: lz <145014769+200lz@users.noreply.github.com> --- .../test_sparse_mla_kv_cache_layout.py | 119 ++++++++++++++++++ tests/v1/core/test_contiguous_kv_packing.py | 27 ++++ tests/v1/core/test_kv_cache_utils.py | 89 +++++++++++-- .../layers/attention/mla_attention.py | 26 ++-- vllm/v1/core/kv_cache_utils.py | 117 ++++++++++++----- vllm/v1/hisparse/layout.py | 31 +++-- vllm/v1/kv_cache_interface.py | 22 ++-- 7 files changed, 364 insertions(+), 67 deletions(-) create mode 100644 tests/v1/attention/test_sparse_mla_kv_cache_layout.py diff --git a/tests/v1/attention/test_sparse_mla_kv_cache_layout.py b/tests/v1/attention/test_sparse_mla_kv_cache_layout.py new file mode 100644 index 000000000000..cd3c9b218147 --- /dev/null +++ b/tests/v1/attention/test_sparse_mla_kv_cache_layout.py @@ -0,0 +1,119 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Sparse MLA allocation and warmup must agree on physical addressing.""" + +from types import MethodType, SimpleNamespace +from unittest.mock import MagicMock + +import pytest +import torch + +from vllm.config import CacheConfig +from vllm.model_executor.layers.attention.mla_attention import MLAAttention +from vllm.model_executor.models.deepseek_v2 import DeepseekV32IndexerCache +from vllm.platforms import current_platform +from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import ( + FlashInferMLASparseTRTLLMBackend, +) +from vllm.v1.attention.backends.mla.flashmla_sparse import FlashMLASparseBackend +from vllm.v1.attention.backends.mla.indexer import DeepseekV32IndexerBackend +from vllm.v1.attention.backends.mla.sparse_utils import ( + _CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL, + flat_kv_row_view, +) +from vllm.v1.attention.backends.utils import get_supported_kv_cache_layouts +from vllm.v1.core.kv_cache_utils import get_kv_cache_config_from_groups +from vllm.v1.kv_cache_interface import KVCacheGroupSpec, UniformTypeKVCacheSpecs +from vllm.v1.kv_cache_layout import KVCacheLayout +from vllm.v1.worker.utils import allocate_kv_cache + +pytestmark = pytest.mark.skip_global_cleanup + + +@pytest.mark.parametrize( + "device", + [ + "cpu", + pytest.param( + "cuda", + marks=pytest.mark.skipif( + not current_platform.is_cuda(), reason="CUDA only" + ), + ), + ], +) +@pytest.mark.parametrize( + "layout", [KVCacheLayout.BLHNC, KVCacheLayout.BLNHC, KVCacheLayout.LBNHC] +) +@pytest.mark.parametrize( + "backend,cache_dtype,sm100,stride_alignment", + [ + (FlashInferMLASparseTRTLLMBackend, "auto", True, 1152), + (FlashInferMLASparseTRTLLMBackend, "fp8", True, 576), + (FlashMLASparseBackend, "auto", True, 1152), + (FlashMLASparseBackend, "fp8_ds_mla", False, None), + (FlashMLASparseBackend, "fp8_ds_mla", True, 656), + (FlashMLASparseBackend, "nvfp4_ds_mla", True, 352), + ], +) +def test_allocation_and_warmup_follow_addressing_mode( + monkeypatch, layout, backend, cache_dtype, sm100, stride_alignment, device +): + monkeypatch.setattr( + current_platform, "is_device_capability_family", lambda family: sm100 + ) + config = SimpleNamespace( + cache_config=CacheConfig(block_size=64), + model_config=SimpleNamespace(dtype=torch.bfloat16), + attention_config=SimpleNamespace(hisparse_config=None), + kernel_config=SimpleNamespace(enable_jit_warmup=True), + ) + config.cache_config.kv_cache_layout = layout.name + layer = SimpleNamespace( + _vllm_config=config, + attn_backend=backend, + kv_cache_dtype=cache_dtype, + head_size=576, + sliding_window=None, + indexer=None, + non_causal_multi_token_decode=False, + ) + layer._uses_flat_kv_cache = MethodType(MLAAttention._uses_flat_kv_cache, layer) + spec = MLAAttention.get_kv_cache_spec(layer, config) + indexer = SimpleNamespace( + cache_config=config.cache_config, head_dim=132, dtype=torch.uint8 + ) + index_spec = DeepseekV32IndexerCache.get_kv_cache_spec(indexer, config) + assert spec.block_stride_alignment == stride_alignment + assert index_spec.block_stride_alignment is None + assert layout in get_supported_kv_cache_layouts( + [backend, DeepseekV32IndexerBackend] + ) + specs = {"mla": spec, "indexer": index_spec} + group = KVCacheGroupSpec( + list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs) + ) + cache = get_kv_cache_config_from_groups(config, [group], 2**20) + views = allocate_kv_cache(cache, torch.device(device), layout) + register = MagicMock() + monkeypatch.setattr( + _CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL, "register_warmup", register + ) + MLAAttention.bind_kv_cache(layer, views["mla"]) + DeepseekV32IndexerCache.bind_kv_cache(indexer, views["indexer"]) + assert indexer.kv_cache.stride(0) == views["indexer"].stride(0) + if stride_alignment is not None: + assert ( + views["mla"].stride(0) * views["mla"].element_size() % stride_alignment == 0 + ) + if not layer._uses_flat_kv_cache(): + register.assert_not_called() + else: + rows, stride = flat_kv_row_view(layer.kv_cache, 64) + register.assert_called_once_with(config, block_stride_rows=stride) + layer.kv_cache[1, 0].fill_(3) + torch.testing.assert_close(rows[stride], layer.kv_cache[1, 0]) + if stride_alignment is None: + assert cache.kv_cache_tensors[0].size == cache.num_blocks * sum( + item.page_size_bytes for item in specs.values() + ) diff --git a/tests/v1/core/test_contiguous_kv_packing.py b/tests/v1/core/test_contiguous_kv_packing.py index 58d4e20bf70c..610fe5c363bf 100644 --- a/tests/v1/core/test_contiguous_kv_packing.py +++ b/tests/v1/core/test_contiguous_kv_packing.py @@ -10,6 +10,7 @@ """ from dataclasses import replace +from math import lcm from unittest.mock import MagicMock import pytest @@ -26,9 +27,11 @@ get_kv_cache_groups, resolve_kv_cache_block_sizes, ) +from vllm.v1.hisparse.layout import _build_hisparse_kv_cache_tensors from vllm.v1.kv_cache_interface import ( CircularBufferSpec, FullAttentionSpec, + HiSparseHotSpec, KVCacheGroupSpec, KVCacheLayout, KVCacheSpec, @@ -79,6 +82,30 @@ def _mock_vllm_config(layout: str | None): return config +@pytest.mark.parametrize("layout", [KVCacheLayout.BLHNC, KVCacheLayout.BLNHC]) +def test_packed_alignment_preserves_hot_pages_and_generic_stride(layout): + """One shared stride must satisfy both constraints, regardless of rounding order.""" + spec = replace(_full(), block_stride_alignment=1152) + hot = HiSparseHotSpec(block_size=16, page_size=5120, blocks_per_request=2) + groups = [KVCacheGroupSpec(["attention"], spec), KVCacheGroupSpec(["hot"], hot)] + alignment = lcm(1152, hot.page_size_bytes) + stride = _pool_bytes_per_block(groups, layout) + assert stride == alignment + tensors = _build_hisparse_kv_cache_tensors(groups, 3, 3 * stride, layout, stride) + assert {tensor.block_stride for tensor in tensors} == {alignment} + assert {tensor.size for tensor in tensors} == {3 * alignment} + + +@pytest.mark.parametrize("spec", [_full(), _mla(128)]) +def test_block_alignment_survives_merge_and_rejects_incompatible_specs(spec): + aligned = replace(spec, block_stride_alignment=512) + assert type(spec).merge([aligned, aligned]).block_stride_alignment == 512 + with pytest.raises(AssertionError): + type(spec).merge([aligned, spec]) + with pytest.raises(ValueError, match="must be positive"): + replace(spec, block_stride_alignment=0) + + def _pages(groups) -> dict[str, int]: return { name: group.kv_cache_spec.kv_cache_specs[name].page_size_bytes diff --git a/tests/v1/core/test_kv_cache_utils.py b/tests/v1/core/test_kv_cache_utils.py index 07c222214586..9a5fc35d8e27 100644 --- a/tests/v1/core/test_kv_cache_utils.py +++ b/tests/v1/core/test_kv_cache_utils.py @@ -121,6 +121,11 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( group = KVCacheGroupSpec(list(specs), group_spec) config = SimpleNamespace( attention_config=SimpleNamespace(hisparse_config=HiSparseConfig()), + kv_transfer_config=KVTransferConfig( + kv_connector="HiSparseConnector", + kv_role="kv_both", + kv_connector_extra_config={"host_pool_gib": 1}, + ), model_config=SimpleNamespace( hf_config=SimpleNamespace(index_topk=128), max_model_len=gpu_block_size, @@ -140,11 +145,6 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC, ), ) - indexer_spec = specs["model.layers.0.self_attn.indexer"] - assert get_hisparse_gpu_memory_usage(config, [group]) == ( - indexer_spec.max_memory_usage_bytes(config) - ) - monkeypatch.setattr(kv_cache_utils, "get_hisparse_host_pool_bytes", lambda _: 2**30) cache_config = kv_cache_utils.get_kv_cache_config_from_groups( config, [group], available_memory=2**30 @@ -182,6 +182,20 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( assert indexer_group.kv_cache_spec.prefix_cacheable assert host_group.enable_kv_transfer auxiliary_specs = [group.kv_cache_spec for group in auxiliary_groups] + device_stride = next( + tensor.block_stride + for tensor in cache_config.kv_cache_tensors + if not tensor.host_resident + ) + hot_blocks = sum( + spec.blocks_per_request + for spec in auxiliary_specs + if isinstance(spec, HiSparseHotSpec) + ) + # One indexer and one resident block, plus the per-request hot pages. + assert get_hisparse_gpu_memory_usage(config, [group]) == ( + (2 + hot_blocks) * device_stride + ) assert any(isinstance(spec, HiSparseResidentSpec) for spec in auxiliary_specs) assert any(isinstance(spec, HiSparseHotSpec) for spec in auxiliary_specs) assert all( @@ -204,6 +218,51 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( assert scheduler_block_size == hash_block_size == gpu_block_size +def test_hisparse_pp_capacity_uses_each_physical_pool(monkeypatch): + monkeypatch.setattr( + hisparse_runtime_module.current_platform, "is_cuda_alike", lambda: True + ) + config = VllmConfig(model_config=ModelConfig(max_model_len=64)) + config.model_config.hf_config.index_topk = 128 + config.attention_config.hisparse_config = HiSparseConfig(device_buffer_size=256) + config.cache_config.kv_cache_layout = "BLHNC" + config.kv_transfer_config = KVTransferConfig( + kv_connector="HiSparseConnector", + kv_role="kv_both", + kv_connector_extra_config={"host_pool_gib": 0.01}, + ) + specs = {} + for i in range(3): + specs[f"mla.{i}"] = MLAAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=576, + dtype=torch.bfloat16, + block_stride_alignment=1152, + ) + specs[f"idx.{i}"] = MLAAttentionSpec( + block_size=64, + num_kv_heads=1, + head_size=132, + dtype=torch.uint8, + cache_role=SparseCacheRole.INDEXER, + ) + workers = [ + {k: v for k, v in specs.items() if k.endswith(".0")}, + {k: v for k, v in specs.items() if not k.endswith(".0")}, + ] + configs = get_kv_cache_configs(config, workers, [2**20, 2**20]) + assert configs[0].num_blocks == configs[1].num_blocks + assert configs[0].hisparse_host_num_blocks == configs[1].hisparse_host_num_blocks + for worker, cache in zip(workers, configs): + device = next(t for t in cache.kv_cache_tensors if not t.host_resident) + assert device.size == cache.num_blocks * device.block_stride + assert device.size <= 2**20 + groups = get_kv_cache_groups(config, worker) + required = get_hisparse_gpu_memory_usage(config, groups) + assert required <= (cache.num_blocks - 1) * device.block_stride + + def test_hisparse_rejects_deepseek_v4(): full_specs = { "model.layers.0.attn": MLAAttentionSpec( @@ -4065,7 +4124,8 @@ def test_auto_fit_max_model_len_reserves_null_block(): assert vllm_config.model_config.max_model_len == 63 * block_size -def test_check_enough_kv_cache_memory_reserves_null_block(): +@pytest.mark.parametrize("layout,alignment", [(None, None), ("BLHNC", 1152)]) +def test_check_enough_kv_cache_memory_reserves_null_block(layout, alignment): """The public admission check must reject a KV cache sized to exactly the blocks a max_model_len request needs. BlockPool keeps one block as the null block, so only num_blocks - 1 are usable; accepting @@ -4075,18 +4135,21 @@ def test_check_enough_kv_cache_memory_reserves_null_block(): block_size = 16 max_model_len = 512 # needs 512 / 16 = 32 blocks vllm_config = VllmConfig(model_config=ModelConfig(max_model_len=max_model_len)) - spec = new_kv_cache_spec(block_size=block_size) + vllm_config.cache_config.kv_cache_layout = layout + spec = replace( + new_kv_cache_spec(block_size=block_size), block_stride_alignment=alignment + ) + stride = kv_cache_utils._pool_bytes_per_block( + get_kv_cache_groups(vllm_config, {"layer1": spec}), + KVCacheLayout[layout] if layout else None, + ) # 32 blocks -> only 31 usable after the null block: one short -> reject. with pytest.raises(ValueError, match="max seq len"): - check_enough_kv_cache_memory( - vllm_config, {"layer1": spec}, spec.page_size_bytes * 32 - ) + check_enough_kv_cache_memory(vllm_config, {"layer1": spec}, stride * 32) # 33 blocks -> 32 usable after the null block -> accept. - check_enough_kv_cache_memory( - vllm_config, {"layer1": spec}, spec.page_size_bytes * 33 - ) + check_enough_kv_cache_memory(vllm_config, {"layer1": spec}, stride * 33) def test_is_full_attention_spec_unwraps_uniform_type_specs(): diff --git a/vllm/model_executor/layers/attention/mla_attention.py b/vllm/model_executor/layers/attention/mla_attention.py index 3104ac25c6ef..2baba4f3c2f0 100644 --- a/vllm/model_executor/layers/attention/mla_attention.py +++ b/vllm/model_executor/layers/attention/mla_attention.py @@ -717,13 +717,7 @@ def bind_kv_cache(self, kv_cache: torch.Tensor) -> None: self.kv_cache = kv_cache.squeeze(1) if ( self._vllm_config.kernel_config.enable_jit_warmup - and self.attn_backend.get_name() - in ( - "FLASHMLA_SPARSE", - "FLASHINFER_MLA_SPARSE", - "FLASHINFER_MLA_SPARSE_SM120", - "DEEPSEEK_V32_INDEXER", - ) + and self._uses_flat_kv_cache() ): from vllm.v1.attention.backends.mla.sparse_utils import ( _CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL, @@ -736,6 +730,13 @@ def bind_kv_cache(self, kv_cache: torch.Tensor) -> None: block_stride_rows=self.kv_cache.stride(0) // row_width, ) + def _uses_flat_kv_cache(self) -> bool: + backend = self.attn_backend.get_name() + return backend == "FLASHINFER_MLA_SPARSE" or ( + backend == "FLASHMLA_SPARSE" + and self.kv_cache_dtype not in ("fp8_ds_mla", "nvfp4_ds_mla") + ) + @property def chunked_prefill_workspace_size(self) -> int: if self._chunked_prefill_workspace_size is None: @@ -1367,11 +1368,20 @@ def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec: **common_kwargs, sliding_window=self.sliding_window, ) - return MLAAttentionSpec( + spec = MLAAttentionSpec( **common_kwargs, is_index_group_leader=self.indexer is not None, non_causal_multi_token_decode=self.non_causal_multi_token_decode, ) + # SM100 FlashMLA paged kernels also express TMA coordinates in token rows. + uses_tma_rows = ( + self.attn_backend.get_name() == "FLASHMLA_SPARSE" + and self.kv_cache_dtype in ("fp8_ds_mla", "nvfp4_ds_mla") + and current_platform.is_device_capability_family(100) + ) + if self._uses_flat_kv_cache() or uses_tma_rows: + spec = replace(spec, block_stride_alignment=spec.state_content_size_bytes) + return spec def _v_up_proj(self, x: torch.Tensor, out: torch.Tensor): # Convert from (B, N, L) to (N, B, L) diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index 656765c89604..ce67e43594a5 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -20,6 +20,7 @@ from vllm.utils.mem_utils import format_gib from vllm.utils.torch_utils import get_dtype_size from vllm.v1.hisparse.layout import ( + create_hisparse_layout, get_hisparse_gpu_memory_usage, get_hisparse_host_pool_bytes, get_hisparse_kv_cache_config, @@ -1006,16 +1007,22 @@ def check_enough_kv_cache_memory( # plans against usable blocks, as in get_kv_cache_configs. Group a copy # of the specs since grouping may unify them in-place. groups = get_kv_cache_groups(vllm_config, dict(kv_cache_spec)) + layout = ( + vllm_config.cache_config.get_resolved_kv_cache_layout() + if vllm_config.cache_config.kv_cache_layout is not None + else None + ) + device_groups = _device_kv_cache_groups(vllm_config, groups) check_memory = ( - available_memory - _pool_bytes_per_block(groups) + available_memory - _pool_bytes_per_block(device_groups, layout) if groups else available_memory ) _check_enough_kv_cache_memory( check_memory, - lambda: max_memory_usage_bytes(vllm_config, kv_cache_spec.values()), + partial(_max_memory_usage_bytes_from_groups, vllm_config, groups), vllm_config.model_config.max_model_len, - lambda am: estimate_max_model_len(vllm_config, kv_cache_spec, am), + partial(_estimate_max_model_len_from_groups, vllm_config, groups), ) @@ -1118,13 +1125,25 @@ def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int: return num_blocks -def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int: +def _device_kv_cache_groups( + vllm_config: VllmConfig, groups: list[KVCacheGroupSpec] +) -> list[KVCacheGroupSpec]: + if groups and vllm_config.attention_config.hisparse_config is not None: + return create_hisparse_layout( + vllm_config, groups, get_hisparse_host_pool_bytes(vllm_config) + ).device_groups + return groups + + +def _pool_bytes_per_block( + kv_cache_groups: list[KVCacheGroupSpec], layout: KVCacheLayout | None = None +) -> int: """Bytes consumed by one block in the worker's shared KV cache pool, mirroring the divisor used by `get_kv_cache_config_from_groups` to convert `available_memory` into `num_blocks`. Used to compute the effective KV cache capacity once `num_gpu_blocks_override` is applied. """ - return _get_kv_cache_bytes_per_block(kv_cache_groups) + return _get_kv_cache_bytes_per_block(kv_cache_groups, layout) def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int: @@ -1590,6 +1609,7 @@ def _get_per_layer_spec( def _get_kv_cache_bytes_per_block( kv_cache_groups: list[KVCacheGroupSpec], + layout: KVCacheLayout | None = None, ) -> int: """Return the largest cache group's bytes per block.""" if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None: @@ -1604,23 +1624,18 @@ def _get_kv_cache_bytes_per_block( for group in kv_cache_groups ) assert bytes_per_block > 0 - hot_page_sizes = [ + alignments = [ 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 = [ - 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 + if layout is not None and layout.is_block_outermost: + alignments.extend( + _get_per_layer_spec(group, layer_name).block_stride_alignment or 1 + for group in kv_cache_groups + for layer_name in group.layer_names + ) + return round_up(bytes_per_block, math.lcm(*alignments)) def validate_kv_cache_layout( @@ -1756,7 +1771,7 @@ def add_tensor(layer_name: str, spec: KVCacheSpec, offset: int) -> None: layout = vllm_config.cache_config.get_resolved_kv_cache_layout() validate_kv_cache_layout(layout, kv_cache_groups) - bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups) + bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups, layout) interleaved_block_stride = bytes_per_block if layout.is_block_outermost else None num_blocks = available_memory // bytes_per_block @@ -2454,7 +2469,12 @@ def _max_memory_usage_bytes_from_groups( total_blocks += 1 return total_blocks * (len(mla_names) * mla_page + len(idx_names) * idx_page) - bytes_per_block = _pool_bytes_per_block(kv_cache_groups) + layout = ( + vllm_config.cache_config.get_resolved_kv_cache_layout() + if vllm_config.cache_config.kv_cache_layout is not None + else None + ) + bytes_per_block = _pool_bytes_per_block(kv_cache_groups, layout) total_blocks = 0 for group in kv_cache_groups: spec = group.kv_cache_spec @@ -2487,12 +2507,12 @@ def fits(model_len: int) -> bool: vllm_config.model_config.max_model_len = model_len if hisparse_enabled: try: - config = get_kv_cache_config_from_groups( - vllm_config, kv_cache_groups, available_memory + return ( + _max_memory_usage_bytes_from_groups(vllm_config, kv_cache_groups) + <= available_memory ) except ValueError: return False - return get_max_concurrency_for_kv_cache_config(vllm_config, config) >= 1 return ( _max_memory_usage_bytes_from_groups(vllm_config, kv_cache_groups) <= available_memory @@ -2695,6 +2715,18 @@ def get_kv_cache_configs( for worker_spec in kv_cache_specs ] + layout = ( + vllm_config.cache_config.get_resolved_kv_cache_layout() + if vllm_config.cache_config.kv_cache_layout is not None + else None + ) + pool_strides = [ + _pool_bytes_per_block(_device_kv_cache_groups(vllm_config, groups), layout) + if groups + else 0 + for groups in projected_groups_per_worker + ] + # If `num_gpu_blocks_override` is set, the cache size that will actually # be allocated is decoupled from the profiled `available_memory`: # `may_override_num_blocks` in `get_kv_cache_config_from_groups` clamps @@ -2704,11 +2736,12 @@ def get_kv_cache_configs( override = vllm_config.cache_config.num_gpu_blocks_override if override is not None: adjusted_memory: list[int] = [] - for groups, avail_mem in zip(projected_groups_per_worker, available_memory): + for groups, avail_mem, bytes_per_block in zip( + projected_groups_per_worker, available_memory, pool_strides + ): if not groups: adjusted_memory.append(avail_mem) continue - bytes_per_block = _pool_bytes_per_block(groups) logger.info( "Overriding num_gpu_blocks=%d with num_gpu_blocks_override=%d", avail_mem // bytes_per_block, @@ -2718,14 +2751,18 @@ def get_kv_cache_configs( available_memory = adjusted_memory if vllm_config.attention_config.hisparse_config is not None: - available_memory = [min(available_memory)] * len(available_memory) + shared_blocks = min( + memory // stride + for memory, stride in zip(available_memory, pool_strides) + if stride + ) + available_memory = [shared_blocks * stride for stride in pool_strides] # Reserve the null block BlockPool permanently holds back, so auto-fit and # the capacity check both plan against usable blocks. Allocation below # still uses the full memory. check_memory = [ - avail_mem - _pool_bytes_per_block(groups) if groups else avail_mem - for groups, avail_mem in zip(projected_groups_per_worker, available_memory) + avail_mem - stride for avail_mem, stride in zip(available_memory, pool_strides) ] if vllm_config.model_config.original_max_model_len == -1: @@ -2761,14 +2798,32 @@ def get_kv_cache_configs( min_num_blocks = min( kv_cache_config.num_blocks for kv_cache_config in kv_cache_configs ) + host_counts = [ + config.hisparse_host_num_blocks + for config in kv_cache_configs + if config.hisparse_host_num_blocks is not None + ] + min_host_blocks = min(host_counts) if host_counts else None for i, kv_cache_config in enumerate(kv_cache_configs): - if kv_cache_config.num_blocks == min_num_blocks: + if ( + kv_cache_config.num_blocks == min_num_blocks + and kv_cache_config.hisparse_host_num_blocks == min_host_blocks + ): continue # Re-plan with exactly the memory the smallest rank can afford, so # strides and offsets stay consistent with the shrunken allocation. - groups = kv_cache_config.kv_cache_groups + groups = projected_groups_per_worker[i] + if min_host_blocks is not None: + assert kv_cache_config.hisparse_host_block_stride is not None + kv_cache_configs[i] = get_hisparse_kv_cache_config( + vllm_config, + groups, + min_num_blocks * pool_strides[i], + min_host_blocks * kv_cache_config.hisparse_host_block_stride, + ) + continue kv_cache_configs[i] = get_kv_cache_config_from_groups( - vllm_config, groups, min_num_blocks * _pool_bytes_per_block(groups) + vllm_config, groups, min_num_blocks * pool_strides[i] ) return kv_cache_configs diff --git a/vllm/v1/hisparse/layout.py b/vllm/v1/hisparse/layout.py index b3b45d3334a5..4fb1d82197f3 100644 --- a/vllm/v1/hisparse/layout.py +++ b/vllm/v1/hisparse/layout.py @@ -116,13 +116,28 @@ def get_hisparse_gpu_memory_usage( vllm_config: VllmConfig, kv_cache_groups: list[KVCacheGroupSpec], ) -> int: - _, indexer_specs = _partition_hisparse_specs(kv_cache_groups) - return sum( - spec.max_memory_usage_bytes(vllm_config) for spec in indexer_specs.values() - ) + sum( - group.kv_cache_spec.max_memory_usage_bytes(vllm_config) - for group in kv_cache_groups[1:] + from vllm.v1.core.kv_cache_utils import _get_kv_cache_bytes_per_block + + hisparse_layout = create_hisparse_layout( + vllm_config, kv_cache_groups, get_hisparse_host_pool_bytes(vllm_config) + ) + host_spec = hisparse_layout.source_group.kv_cache_spec + host_blocks = cdiv( + host_spec.max_memory_usage_bytes(vllm_config), host_spec.page_size_bytes + ) + if host_blocks >= hisparse_layout.host_num_blocks: + raise ValueError("HiSparse host cache cannot hold the request and null block.") + device_groups = hisparse_layout.device_groups + layout = vllm_config.cache_config.get_resolved_kv_cache_layout() + bytes_per_block = _get_kv_cache_bytes_per_block(device_groups, layout) + required_blocks = sum( + cdiv( + group.kv_cache_spec.max_memory_usage_bytes(vllm_config), + group.kv_cache_spec.page_size_bytes, + ) + for group in device_groups ) + return required_blocks * bytes_per_block def create_hisparse_layout( @@ -315,7 +330,7 @@ def get_hisparse_kv_cache_config( device_groups = hisparse_layout.device_groups layout = vllm_config.cache_config.get_resolved_kv_cache_layout() validate_kv_cache_layout(layout, device_groups) - bytes_per_block = _get_kv_cache_bytes_per_block(device_groups) + bytes_per_block = _get_kv_cache_bytes_per_block(device_groups, layout) num_blocks = may_override_num_blocks( vllm_config, available_memory // bytes_per_block ) @@ -327,7 +342,7 @@ def get_hisparse_kv_cache_config( host_groups = [hisparse_layout.source_group] host_layout = KVCacheLayout.LBNHC validate_kv_cache_layout(host_layout, host_groups) - host_bytes_per_block = _get_kv_cache_bytes_per_block(host_groups) + host_bytes_per_block = _get_kv_cache_bytes_per_block(host_groups, host_layout) host_size = host_bytes_per_block * hisparse_layout.host_num_blocks kv_cache_tensors[:0] = _build_hisparse_kv_cache_tensors( host_groups, diff --git a/vllm/v1/kv_cache_interface.py b/vllm/v1/kv_cache_interface.py index fc8b88921a39..499b50a3a257 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 @@ -159,6 +159,13 @@ class KVCacheSpec: # number of tokens in a block block_size: int + block_stride_alignment: int | None = field(default=None, kw_only=True) + """Required byte alignment between physical blocks, including packed layers.""" + + def __post_init__(self): + if self.block_stride_alignment is not None and self.block_stride_alignment <= 0: + raise ValueError("block_stride_alignment must be positive") + @property def prefix_cacheable(self) -> bool: """Whether this spec's group participates in prefix caching.""" @@ -492,6 +499,7 @@ class AttentionSpec(KVCacheSpec): token (Whisper block pooling: ``Fraction(1, block_pool_size)``).""" def __post_init__(self): + super().__post_init__() if self.head_size_v is None: object.__setattr__(self, "head_size_v", self.head_size) @@ -598,6 +606,7 @@ def merge(cls, specs: list[Self]) -> Self: ) merged_spec = cls( block_size=specs[0].block_size, + block_stride_alignment=specs[0].block_stride_alignment, num_kv_heads=specs[0].num_kv_heads, head_size=specs[0].head_size, head_size_v=specs[0].head_size_v, @@ -648,12 +657,6 @@ class MLAAttentionSpec(FullAttentionSpec): is_index_group_leader: bool = False storage_block_size: int | None = None """Token width used to view storage when it differs from the kernel block.""" - block_stride_alignment: int | None = None - """Required alignment, in bytes, of the distance between consecutive - blocks of this cache. In block-major layouts that distance is the whole - block (all layers' pages), so the allocator rounds the block up to it. - DeepGEMM's paged sparse MQA-logits kernels address pages as - ``base + page * stride`` and need it 512B-aligned.""" # Group capability enabled when any member flattens a non-causal query block # into decode rows. Runtime metadata still selects causal vs. non-causal mode. non_causal_multi_token_decode: bool = False @@ -751,6 +754,7 @@ def merge(cls, specs: list[RSWASpec]) -> RSWASpec: base = FullAttentionSpec.merge(specs) # type: ignore[arg-type] return cls( block_size=base.block_size, + block_stride_alignment=base.block_stride_alignment, num_kv_heads=base.num_kv_heads, head_size=base.head_size, head_size_v=base.head_size_v, @@ -945,6 +949,7 @@ def merge(cls, specs: list[Self]) -> Self: sliding_window_set = set(spec.sliding_window for spec in specs) extra_retained_set = set(spec.extra_retained_tokens for spec in specs) bounded_replay_set = set(spec.bounded_replay for spec in specs) + block_stride_alignment_set = {spec.block_stride_alignment for spec in specs} assert ( len(cache_dtype_str_set) == 1 and len(tokens_per_state_set) == 1 @@ -952,6 +957,7 @@ def merge(cls, specs: list[Self]) -> Self: and len(sliding_window_set) == 1 and len(extra_retained_set) == 1 and len(bounded_replay_set) == 1 + and len(block_stride_alignment_set) == 1 ), ( "All attention layers in the same KV cache group must use the same " "quantization method, tokens per state, model version, sliding " @@ -959,6 +965,7 @@ def merge(cls, specs: list[Self]) -> Self: ) return cls( block_size=specs[0].block_size, + block_stride_alignment=block_stride_alignment_set.pop(), num_kv_heads=specs[0].num_kv_heads, head_size=specs[0].head_size, dtype=specs[0].dtype, @@ -1175,6 +1182,7 @@ def merge(cls, specs: list[Self]) -> Self: head_size=specs[0].head_size, head_size_v=specs[0].head_size_v, sink_len=specs[0].sink_len, + block_stride_alignment=specs[0].block_stride_alignment, dtype=specs[0].dtype, kv_quant_mode=specs[0].kv_quant_mode, page_size_padded=specs[0].page_size_padded, From 1d45dcafade7903237c627d941fda7df26341d76 Mon Sep 17 00:00:00 2001 From: Lucas Wilkinson Date: Mon, 21 Sep 2026 20:50:50 +0000 Subject: [PATCH 5/6] [Bugfix][KV Cache][MLA] Minimize sparse MLA stride fix to the producer change Main already carries block_stride_alignment through spec merging and rounds the pool stride by it. The missing piece was that the V3.2 sparse MLA path never published the alignment. Keep the producer change, lift the field to KVCacheSpec so any spec can carry it, and fold the HiSparse hot-page and stride roundings into one LCM so one rounding cannot break the other. Drop the layout gating and its threading, the admission/auto-fit rewrites, and the HiSparse PP re-planning; those are independent of this fix and can land as follow-ups. Co-Authored-By: Claude Fable 5.1 Signed-off-by: Lucas Wilkinson Signed-off-by: Lucas Wilkinson --- tests/v1/core/test_contiguous_kv_packing.py | 8 +- tests/v1/core/test_kv_cache_utils.py | 89 +++------------- vllm/v1/core/kv_cache_utils.py | 107 +++++--------------- vllm/v1/hisparse/layout.py | 31 ++---- 4 files changed, 48 insertions(+), 187 deletions(-) diff --git a/tests/v1/core/test_contiguous_kv_packing.py b/tests/v1/core/test_contiguous_kv_packing.py index 610fe5c363bf..638deeedc579 100644 --- a/tests/v1/core/test_contiguous_kv_packing.py +++ b/tests/v1/core/test_contiguous_kv_packing.py @@ -82,15 +82,15 @@ def _mock_vllm_config(layout: str | None): return config -@pytest.mark.parametrize("layout", [KVCacheLayout.BLHNC, KVCacheLayout.BLNHC]) -def test_packed_alignment_preserves_hot_pages_and_generic_stride(layout): +def test_packed_alignment_preserves_hot_pages_and_generic_stride(): """One shared stride must satisfy both constraints, regardless of rounding order.""" - spec = replace(_full(), block_stride_alignment=1152) + spec = replace(_mla(128), block_stride_alignment=1152) hot = HiSparseHotSpec(block_size=16, page_size=5120, blocks_per_request=2) groups = [KVCacheGroupSpec(["attention"], spec), KVCacheGroupSpec(["hot"], hot)] alignment = lcm(1152, hot.page_size_bytes) - stride = _pool_bytes_per_block(groups, layout) + stride = _pool_bytes_per_block(groups) assert stride == alignment + layout = KVCacheLayout.BLHNC tensors = _build_hisparse_kv_cache_tensors(groups, 3, 3 * stride, layout, stride) assert {tensor.block_stride for tensor in tensors} == {alignment} assert {tensor.size for tensor in tensors} == {3 * alignment} diff --git a/tests/v1/core/test_kv_cache_utils.py b/tests/v1/core/test_kv_cache_utils.py index 9a5fc35d8e27..07c222214586 100644 --- a/tests/v1/core/test_kv_cache_utils.py +++ b/tests/v1/core/test_kv_cache_utils.py @@ -121,11 +121,6 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( group = KVCacheGroupSpec(list(specs), group_spec) config = SimpleNamespace( attention_config=SimpleNamespace(hisparse_config=HiSparseConfig()), - kv_transfer_config=KVTransferConfig( - kv_connector="HiSparseConnector", - kv_role="kv_both", - kv_connector_extra_config={"host_pool_gib": 1}, - ), model_config=SimpleNamespace( hf_config=SimpleNamespace(index_topk=128), max_model_len=gpu_block_size, @@ -145,6 +140,11 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC, ), ) + indexer_spec = specs["model.layers.0.self_attn.indexer"] + assert get_hisparse_gpu_memory_usage(config, [group]) == ( + indexer_spec.max_memory_usage_bytes(config) + ) + monkeypatch.setattr(kv_cache_utils, "get_hisparse_host_pool_bytes", lambda _: 2**30) cache_config = kv_cache_utils.get_kv_cache_config_from_groups( config, [group], available_memory=2**30 @@ -182,20 +182,6 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( assert indexer_group.kv_cache_spec.prefix_cacheable assert host_group.enable_kv_transfer auxiliary_specs = [group.kv_cache_spec for group in auxiliary_groups] - device_stride = next( - tensor.block_stride - for tensor in cache_config.kv_cache_tensors - if not tensor.host_resident - ) - hot_blocks = sum( - spec.blocks_per_request - for spec in auxiliary_specs - if isinstance(spec, HiSparseHotSpec) - ) - # One indexer and one resident block, plus the per-request hot pages. - assert get_hisparse_gpu_memory_usage(config, [group]) == ( - (2 + hot_blocks) * device_stride - ) assert any(isinstance(spec, HiSparseResidentSpec) for spec in auxiliary_specs) assert any(isinstance(spec, HiSparseHotSpec) for spec in auxiliary_specs) assert all( @@ -218,51 +204,6 @@ def test_hisparse_hma_uses_resolved_gpu_block_size( assert scheduler_block_size == hash_block_size == gpu_block_size -def test_hisparse_pp_capacity_uses_each_physical_pool(monkeypatch): - monkeypatch.setattr( - hisparse_runtime_module.current_platform, "is_cuda_alike", lambda: True - ) - config = VllmConfig(model_config=ModelConfig(max_model_len=64)) - config.model_config.hf_config.index_topk = 128 - config.attention_config.hisparse_config = HiSparseConfig(device_buffer_size=256) - config.cache_config.kv_cache_layout = "BLHNC" - config.kv_transfer_config = KVTransferConfig( - kv_connector="HiSparseConnector", - kv_role="kv_both", - kv_connector_extra_config={"host_pool_gib": 0.01}, - ) - specs = {} - for i in range(3): - specs[f"mla.{i}"] = MLAAttentionSpec( - block_size=64, - num_kv_heads=1, - head_size=576, - dtype=torch.bfloat16, - block_stride_alignment=1152, - ) - specs[f"idx.{i}"] = MLAAttentionSpec( - block_size=64, - num_kv_heads=1, - head_size=132, - dtype=torch.uint8, - cache_role=SparseCacheRole.INDEXER, - ) - workers = [ - {k: v for k, v in specs.items() if k.endswith(".0")}, - {k: v for k, v in specs.items() if not k.endswith(".0")}, - ] - configs = get_kv_cache_configs(config, workers, [2**20, 2**20]) - assert configs[0].num_blocks == configs[1].num_blocks - assert configs[0].hisparse_host_num_blocks == configs[1].hisparse_host_num_blocks - for worker, cache in zip(workers, configs): - device = next(t for t in cache.kv_cache_tensors if not t.host_resident) - assert device.size == cache.num_blocks * device.block_stride - assert device.size <= 2**20 - groups = get_kv_cache_groups(config, worker) - required = get_hisparse_gpu_memory_usage(config, groups) - assert required <= (cache.num_blocks - 1) * device.block_stride - - def test_hisparse_rejects_deepseek_v4(): full_specs = { "model.layers.0.attn": MLAAttentionSpec( @@ -4124,8 +4065,7 @@ def test_auto_fit_max_model_len_reserves_null_block(): assert vllm_config.model_config.max_model_len == 63 * block_size -@pytest.mark.parametrize("layout,alignment", [(None, None), ("BLHNC", 1152)]) -def test_check_enough_kv_cache_memory_reserves_null_block(layout, alignment): +def test_check_enough_kv_cache_memory_reserves_null_block(): """The public admission check must reject a KV cache sized to exactly the blocks a max_model_len request needs. BlockPool keeps one block as the null block, so only num_blocks - 1 are usable; accepting @@ -4135,21 +4075,18 @@ def test_check_enough_kv_cache_memory_reserves_null_block(layout, alignment): block_size = 16 max_model_len = 512 # needs 512 / 16 = 32 blocks vllm_config = VllmConfig(model_config=ModelConfig(max_model_len=max_model_len)) - vllm_config.cache_config.kv_cache_layout = layout - spec = replace( - new_kv_cache_spec(block_size=block_size), block_stride_alignment=alignment - ) - stride = kv_cache_utils._pool_bytes_per_block( - get_kv_cache_groups(vllm_config, {"layer1": spec}), - KVCacheLayout[layout] if layout else None, - ) + spec = new_kv_cache_spec(block_size=block_size) # 32 blocks -> only 31 usable after the null block: one short -> reject. with pytest.raises(ValueError, match="max seq len"): - check_enough_kv_cache_memory(vllm_config, {"layer1": spec}, stride * 32) + check_enough_kv_cache_memory( + vllm_config, {"layer1": spec}, spec.page_size_bytes * 32 + ) # 33 blocks -> 32 usable after the null block -> accept. - check_enough_kv_cache_memory(vllm_config, {"layer1": spec}, stride * 33) + check_enough_kv_cache_memory( + vllm_config, {"layer1": spec}, spec.page_size_bytes * 33 + ) def test_is_full_attention_spec_unwraps_uniform_type_specs(): diff --git a/vllm/v1/core/kv_cache_utils.py b/vllm/v1/core/kv_cache_utils.py index ce67e43594a5..d476e7e3eb9a 100644 --- a/vllm/v1/core/kv_cache_utils.py +++ b/vllm/v1/core/kv_cache_utils.py @@ -20,7 +20,6 @@ from vllm.utils.mem_utils import format_gib from vllm.utils.torch_utils import get_dtype_size from vllm.v1.hisparse.layout import ( - create_hisparse_layout, get_hisparse_gpu_memory_usage, get_hisparse_host_pool_bytes, get_hisparse_kv_cache_config, @@ -1007,22 +1006,16 @@ def check_enough_kv_cache_memory( # plans against usable blocks, as in get_kv_cache_configs. Group a copy # of the specs since grouping may unify them in-place. groups = get_kv_cache_groups(vllm_config, dict(kv_cache_spec)) - layout = ( - vllm_config.cache_config.get_resolved_kv_cache_layout() - if vllm_config.cache_config.kv_cache_layout is not None - else None - ) - device_groups = _device_kv_cache_groups(vllm_config, groups) check_memory = ( - available_memory - _pool_bytes_per_block(device_groups, layout) + available_memory - _pool_bytes_per_block(groups) if groups else available_memory ) _check_enough_kv_cache_memory( check_memory, - partial(_max_memory_usage_bytes_from_groups, vllm_config, groups), + lambda: max_memory_usage_bytes(vllm_config, kv_cache_spec.values()), vllm_config.model_config.max_model_len, - partial(_estimate_max_model_len_from_groups, vllm_config, groups), + lambda am: estimate_max_model_len(vllm_config, kv_cache_spec, am), ) @@ -1125,25 +1118,13 @@ def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int: return num_blocks -def _device_kv_cache_groups( - vllm_config: VllmConfig, groups: list[KVCacheGroupSpec] -) -> list[KVCacheGroupSpec]: - if groups and vllm_config.attention_config.hisparse_config is not None: - return create_hisparse_layout( - vllm_config, groups, get_hisparse_host_pool_bytes(vllm_config) - ).device_groups - return groups - - -def _pool_bytes_per_block( - kv_cache_groups: list[KVCacheGroupSpec], layout: KVCacheLayout | None = None -) -> int: +def _pool_bytes_per_block(kv_cache_groups: list[KVCacheGroupSpec]) -> int: """Bytes consumed by one block in the worker's shared KV cache pool, mirroring the divisor used by `get_kv_cache_config_from_groups` to convert `available_memory` into `num_blocks`. Used to compute the effective KV cache capacity once `num_gpu_blocks_override` is applied. """ - return _get_kv_cache_bytes_per_block(kv_cache_groups, layout) + return _get_kv_cache_bytes_per_block(kv_cache_groups) def get_uniform_page_size(kv_cache_specs: Iterable[KVCacheSpec]) -> int: @@ -1609,7 +1590,6 @@ def _get_per_layer_spec( def _get_kv_cache_bytes_per_block( kv_cache_groups: list[KVCacheGroupSpec], - layout: KVCacheLayout | None = None, ) -> int: """Return the largest cache group's bytes per block.""" if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None: @@ -1629,12 +1609,11 @@ def _get_kv_cache_bytes_per_block( for group in kv_cache_groups if isinstance(group.kv_cache_spec, HiSparseHotSpec) ] - if layout is not None and layout.is_block_outermost: - alignments.extend( - _get_per_layer_spec(group, layer_name).block_stride_alignment or 1 - for group in kv_cache_groups - for layer_name in group.layer_names - ) + alignments.extend( + _get_per_layer_spec(group, layer_name).block_stride_alignment or 1 + for group in kv_cache_groups + for layer_name in group.layer_names + ) return round_up(bytes_per_block, math.lcm(*alignments)) @@ -1771,7 +1750,7 @@ def add_tensor(layer_name: str, spec: KVCacheSpec, offset: int) -> None: layout = vllm_config.cache_config.get_resolved_kv_cache_layout() validate_kv_cache_layout(layout, kv_cache_groups) - bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups, layout) + bytes_per_block = _get_kv_cache_bytes_per_block(kv_cache_groups) interleaved_block_stride = bytes_per_block if layout.is_block_outermost else None num_blocks = available_memory // bytes_per_block @@ -2469,12 +2448,7 @@ def _max_memory_usage_bytes_from_groups( total_blocks += 1 return total_blocks * (len(mla_names) * mla_page + len(idx_names) * idx_page) - layout = ( - vllm_config.cache_config.get_resolved_kv_cache_layout() - if vllm_config.cache_config.kv_cache_layout is not None - else None - ) - bytes_per_block = _pool_bytes_per_block(kv_cache_groups, layout) + bytes_per_block = _pool_bytes_per_block(kv_cache_groups) total_blocks = 0 for group in kv_cache_groups: spec = group.kv_cache_spec @@ -2507,12 +2481,12 @@ def fits(model_len: int) -> bool: vllm_config.model_config.max_model_len = model_len if hisparse_enabled: try: - return ( - _max_memory_usage_bytes_from_groups(vllm_config, kv_cache_groups) - <= available_memory + config = get_kv_cache_config_from_groups( + vllm_config, kv_cache_groups, available_memory ) except ValueError: return False + return get_max_concurrency_for_kv_cache_config(vllm_config, config) >= 1 return ( _max_memory_usage_bytes_from_groups(vllm_config, kv_cache_groups) <= available_memory @@ -2715,18 +2689,6 @@ def get_kv_cache_configs( for worker_spec in kv_cache_specs ] - layout = ( - vllm_config.cache_config.get_resolved_kv_cache_layout() - if vllm_config.cache_config.kv_cache_layout is not None - else None - ) - pool_strides = [ - _pool_bytes_per_block(_device_kv_cache_groups(vllm_config, groups), layout) - if groups - else 0 - for groups in projected_groups_per_worker - ] - # If `num_gpu_blocks_override` is set, the cache size that will actually # be allocated is decoupled from the profiled `available_memory`: # `may_override_num_blocks` in `get_kv_cache_config_from_groups` clamps @@ -2736,12 +2698,11 @@ def get_kv_cache_configs( override = vllm_config.cache_config.num_gpu_blocks_override if override is not None: adjusted_memory: list[int] = [] - for groups, avail_mem, bytes_per_block in zip( - projected_groups_per_worker, available_memory, pool_strides - ): + for groups, avail_mem in zip(projected_groups_per_worker, available_memory): if not groups: adjusted_memory.append(avail_mem) continue + bytes_per_block = _pool_bytes_per_block(groups) logger.info( "Overriding num_gpu_blocks=%d with num_gpu_blocks_override=%d", avail_mem // bytes_per_block, @@ -2751,18 +2712,14 @@ def get_kv_cache_configs( available_memory = adjusted_memory if vllm_config.attention_config.hisparse_config is not None: - shared_blocks = min( - memory // stride - for memory, stride in zip(available_memory, pool_strides) - if stride - ) - available_memory = [shared_blocks * stride for stride in pool_strides] + available_memory = [min(available_memory)] * len(available_memory) # Reserve the null block BlockPool permanently holds back, so auto-fit and # the capacity check both plan against usable blocks. Allocation below # still uses the full memory. check_memory = [ - avail_mem - stride for avail_mem, stride in zip(available_memory, pool_strides) + avail_mem - _pool_bytes_per_block(groups) if groups else avail_mem + for groups, avail_mem in zip(projected_groups_per_worker, available_memory) ] if vllm_config.model_config.original_max_model_len == -1: @@ -2798,32 +2755,14 @@ def get_kv_cache_configs( min_num_blocks = min( kv_cache_config.num_blocks for kv_cache_config in kv_cache_configs ) - host_counts = [ - config.hisparse_host_num_blocks - for config in kv_cache_configs - if config.hisparse_host_num_blocks is not None - ] - min_host_blocks = min(host_counts) if host_counts else None for i, kv_cache_config in enumerate(kv_cache_configs): - if ( - kv_cache_config.num_blocks == min_num_blocks - and kv_cache_config.hisparse_host_num_blocks == min_host_blocks - ): + if kv_cache_config.num_blocks == min_num_blocks: continue # Re-plan with exactly the memory the smallest rank can afford, so # strides and offsets stay consistent with the shrunken allocation. - groups = projected_groups_per_worker[i] - if min_host_blocks is not None: - assert kv_cache_config.hisparse_host_block_stride is not None - kv_cache_configs[i] = get_hisparse_kv_cache_config( - vllm_config, - groups, - min_num_blocks * pool_strides[i], - min_host_blocks * kv_cache_config.hisparse_host_block_stride, - ) - continue + groups = kv_cache_config.kv_cache_groups kv_cache_configs[i] = get_kv_cache_config_from_groups( - vllm_config, groups, min_num_blocks * pool_strides[i] + vllm_config, groups, min_num_blocks * _pool_bytes_per_block(groups) ) return kv_cache_configs diff --git a/vllm/v1/hisparse/layout.py b/vllm/v1/hisparse/layout.py index 4fb1d82197f3..b3b45d3334a5 100644 --- a/vllm/v1/hisparse/layout.py +++ b/vllm/v1/hisparse/layout.py @@ -116,28 +116,13 @@ def get_hisparse_gpu_memory_usage( vllm_config: VllmConfig, kv_cache_groups: list[KVCacheGroupSpec], ) -> int: - from vllm.v1.core.kv_cache_utils import _get_kv_cache_bytes_per_block - - hisparse_layout = create_hisparse_layout( - vllm_config, kv_cache_groups, get_hisparse_host_pool_bytes(vllm_config) - ) - host_spec = hisparse_layout.source_group.kv_cache_spec - host_blocks = cdiv( - host_spec.max_memory_usage_bytes(vllm_config), host_spec.page_size_bytes - ) - if host_blocks >= hisparse_layout.host_num_blocks: - raise ValueError("HiSparse host cache cannot hold the request and null block.") - device_groups = hisparse_layout.device_groups - layout = vllm_config.cache_config.get_resolved_kv_cache_layout() - bytes_per_block = _get_kv_cache_bytes_per_block(device_groups, layout) - required_blocks = sum( - cdiv( - group.kv_cache_spec.max_memory_usage_bytes(vllm_config), - group.kv_cache_spec.page_size_bytes, - ) - for group in device_groups + _, indexer_specs = _partition_hisparse_specs(kv_cache_groups) + return sum( + spec.max_memory_usage_bytes(vllm_config) for spec in indexer_specs.values() + ) + sum( + group.kv_cache_spec.max_memory_usage_bytes(vllm_config) + for group in kv_cache_groups[1:] ) - return required_blocks * bytes_per_block def create_hisparse_layout( @@ -330,7 +315,7 @@ def get_hisparse_kv_cache_config( device_groups = hisparse_layout.device_groups layout = vllm_config.cache_config.get_resolved_kv_cache_layout() validate_kv_cache_layout(layout, device_groups) - bytes_per_block = _get_kv_cache_bytes_per_block(device_groups, layout) + bytes_per_block = _get_kv_cache_bytes_per_block(device_groups) num_blocks = may_override_num_blocks( vllm_config, available_memory // bytes_per_block ) @@ -342,7 +327,7 @@ def get_hisparse_kv_cache_config( host_groups = [hisparse_layout.source_group] host_layout = KVCacheLayout.LBNHC validate_kv_cache_layout(host_layout, host_groups) - host_bytes_per_block = _get_kv_cache_bytes_per_block(host_groups, host_layout) + host_bytes_per_block = _get_kv_cache_bytes_per_block(host_groups) host_size = host_bytes_per_block * hisparse_layout.host_num_blocks kv_cache_tensors[:0] = _build_hisparse_kv_cache_tensors( host_groups, From 0c8ac89fe453c954b2a92d3a3560f5a3a5a758c0 Mon Sep 17 00:00:00 2001 From: lz <145014769+200lz@users.noreply.github.com> Date: Tue, 22 Sep 2026 13:49:51 +0900 Subject: [PATCH 6/6] [Test] Fix MLA KV-cache spec fixture after backend-aware alignment get_kv_cache_spec needs the selected backend to determine sparse physical alignment. Production MLAAttention initializes attn_backend before layer registration, but this direct-method unit-test fake omitted that state. Supply the dense FlashMLA backend and bind the real _uses_flat_kv_cache helper. No production behavior changes. Co-authored-by: Codex Signed-off-by: lz <145014769+200lz@users.noreply.github.com> --- tests/v1/attention/test_mla_backends.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/v1/attention/test_mla_backends.py b/tests/v1/attention/test_mla_backends.py index 597ffb03fcf7..bf6cc5cf88fa 100644 --- a/tests/v1/attention/test_mla_backends.py +++ b/tests/v1/attention/test_mla_backends.py @@ -9,7 +9,7 @@ """ import sys -from types import SimpleNamespace +from types import MethodType, SimpleNamespace import pytest import torch @@ -218,12 +218,14 @@ def test_mla_kv_cache_spec_uses_layer_cache_dtype( cache_dtype: str, expected_quant_mode: KVQuantMode ): layer = SimpleNamespace( + attn_backend=flashmla_module.FlashMLABackend, kv_cache_dtype=cache_dtype, head_size=576, indexer=None, non_causal_multi_token_decode=False, sliding_window=None, ) + layer._uses_flat_kv_cache = MethodType(MLAAttention._uses_flat_kv_cache, layer) vllm_config = SimpleNamespace( cache_config=SimpleNamespace(block_size=64), model_config=None )