Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
f00e943
[HiSparse] Support Kimi-K3.1's hybrid KDA + DSA layout
MatthewBonanni Nov 12, 2026
ece197b
[Kimi K3.1] Derive indexer write slots without the group slot mapping
MatthewBonanni Nov 12, 2026
a13816c
[HiSparse] Keep the packed block only for self-addressed indexers
MatthewBonanni Nov 12, 2026
7b8a238
[Bugfix][KV Connector] Pass attention metadata to the connector on pi…
MatthewBonanni Nov 12, 2026
e089867
Merge upstream/main into hisparse-kimi-k31
MatthewBonanni Nov 13, 2026
375136a
[HiSparse] Spread indexer pages only when every indexer layer fits
MatthewBonanni Nov 13, 2026
683228a
Merge remote-tracking branch 'upstream/main' into hisparse-kimi-k31
MatthewBonanni Nov 13, 2026
09ae85d
[Bugfix] FlashMLA sparse: align quantized KV block strides to 64-toke…
MatthewBonanni Nov 13, 2026
05d3541
[HiSparse] Spread indexer pages only in whole rows
MatthewBonanni Nov 13, 2026
7db47bb
Merge remote-tracking branch 'upstream/main' into hisparse-kimi-k31
MatthewBonanni Nov 16, 2026
cfc04ec
[Kimi K3.1] Warm up and test the self-addressed indexer slot mapping
MatthewBonanni Nov 16, 2026
8879346
Drop runner connector test already covered by main's behavior
MatthewBonanni Nov 16, 2026
d11ced0
Check self-addressed warmup key against the runtime dispatch key
MatthewBonanni Nov 17, 2026
9d0ee5e
Bound the manager-block view by its kernel blocks instead of whole-ro…
MatthewBonanni Nov 17, 2026
b1baf1e
Fit HiSparse K3.1 device memory per request within the no-HiSparse bu…
MatthewBonanni Nov 18, 2026
52bd211
Merge remote-tracking branch 'upstream/main' into hisparse-kimi-k31
MatthewBonanni Nov 24, 2026
b362768
Keep resident blocks pinned until the hot region is allocated
MatthewBonanni Nov 24, 2026
090cc01
Merge remote-tracking branch 'upstream/main' into hisparse-kimi-k31
MatthewBonanni Nov 24, 2026
8839a13
Merge remote-tracking branch 'upstream/main' into hisparse-kimi-k31
MatthewBonanni Nov 24, 2026
841f8cb
Merge remote-tracking branch 'upstream/main' into hisparse-kimi-k31
MatthewBonanni Nov 25, 2026
88fb108
[HiSparse] Account joint device peak via a generic manager hook
MatthewBonanni Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions tests/v1/attention/test_indexer_deepseek_v4_slot_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,9 +479,11 @@ def test_compressed_slot_mapping_inherits_padded_token_slots():


@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_compressed_slot_mapping_dcp_uses_rank_local_state_positions():
@pytest.mark.parametrize("self_addressed", [False, True])
def test_compressed_slot_mapping_dcp_uses_rank_local_state_positions(self_addressed):
"""Under DCP each rank writes only the states it owns, at the state's
rank-local position."""
rank-local position, whether ownership comes from the tokens' slots or,
for a self-addressed cache, from the rank."""
device = torch.device("cuda")
dcp, interleave, ratio, block_size = 2, 4, 2, 4
num_tokens = 32
Expand All @@ -494,14 +496,15 @@ def test_compressed_slot_mapping_dcp_uses_rank_local_state_positions():
slot_mapping = torch.where(owned, 0, -1).to(torch.int64).to(device)
compressed = get_compressed_slot_mapping(
num_tokens,
slot_mapping,
None if self_addressed else slot_mapping,
query_start_loc,
seq_lens,
block_table,
block_size=block_size,
compress_ratio=ratio,
dcp_world_size=dcp,
cp_interleave=interleave,
dcp_rank=rank,
)
local_pos = pos // (interleave * dcp) * interleave + pos % interleave
state = local_pos // ratio
Expand Down
11 changes: 8 additions & 3 deletions tests/v1/core/test_kv_cache_config_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,16 @@ def test_model_classmethod_owns_grouping(self):
cfg = _make_vllm_config(supports_grouping=True)
assert DefaultKVCacheConfigBuilder().get_kv_cache_groups(cfg, {}) == []

def test_model_grouping_rejects_hisparse(self):
def test_hisparse_owns_grouping_over_model(self):
cfg = _make_vllm_config(supports_grouping=True)
cfg.attention_config.hisparse_config = object()
with pytest.raises(ValueError, match="HiSparse"):
DefaultKVCacheConfigBuilder().get_kv_cache_groups(cfg, {})
with patch(
"vllm.v1.core.kv_cache_planning.get_kv_cache_groups",
return_value=["default"],
):
groups = DefaultKVCacheConfigBuilder().get_kv_cache_groups(cfg, {})
assert groups == ["default"]
cfg.model_config.registry.resolve_model_cls.assert_not_called()


class TestCoreChecksGrouping:
Expand Down
47 changes: 47 additions & 0 deletions tests/v1/core/test_kv_cache_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,53 @@ def test_hisparse_derived_specs_do_not_affect_kv_cache_layout(monkeypatch):
assert layouts[0] == layouts[1]


def test_hisparse_hybrid_state_groups_fit_indexer_row():
"""A hybrid model's state layers split into groups no wider than the
indexer group, and hot pages need only kernel-row alignment, so the device
row stays the indexer page instead of padding to a state group or hot page."""
block_size = 256
specs: dict[str, KVCacheSpec] = {}
for i in range(6):
specs[f"model.layers.{i}.self_attn"] = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=576,
dtype=torch.bfloat16,
is_index_group_leader=True,
)
specs[f"model.layers.{i}.self_attn.indexer"] = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=144,
dtype=torch.bfloat16,
cache_role=SparseCacheRole.INDEXER,
)
for i in range(6, 16):
specs[f"model.layers.{i}.linear_attn"] = MambaSpec(
block_size=block_size, shapes=((25000,),), dtypes=(torch.float32,)
)
config = VllmConfig(model_config=ModelConfig(max_model_len=1024))
config.attention_config.hisparse_config = HiSparseConfig()
config.model_config.hf_config.index_topk = 128

groups = get_hisparse_kv_cache_groups(config, specs)
assert groups is not None
device_groups = [group for group in groups if not group.host_resident]
indexer_page = 6 * block_size * 144 * 2
assert sorted(
name
for group in device_groups
for name in group.layer_names
if "linear_attn" in name
) == sorted(name for name in specs if "linear_attn" in name)
assert (
kv_cache_planning._get_kv_cache_bytes_per_block(
device_groups, KVCacheLayout.BLHNC
)
== indexer_page
)


def test_hisparse_rejects_deepseek_v4():
full_specs = {
"model.layers.0.attn": MLAAttentionSpec(
Expand Down
30 changes: 30 additions & 0 deletions tests/v1/kv_connector/unit/test_hisparse_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from vllm.v1.hisparse.coordinator import get_hisparse_coordinator
from vllm.v1.hisparse.runtime import (
HiSparseCacheHandle,
PagedCacheView,
update_hisparse_residency,
)
from vllm.v1.hisparse.types import (
Expand Down Expand Up @@ -65,6 +66,35 @@ def test_cache_manager_binding_preserves_hisparse_and_legacy_pool_hooks(nested):
legacy.bind_gpu_block_pool.assert_called_once_with(manager.block_pool)


def test_paged_cache_view_flat_rows_follow_unaligned_block_stride():
"""Attention addresses hot rows as `block * attention_block_stride + row`,
which must hold when the block stride is not a whole number of pages."""
block_size, row_width, num_blocks = 4, 2, 3
row_bytes = row_width * 2
block_stride = 6 * row_bytes
raw = torch.zeros(num_blocks * block_stride, dtype=torch.uint8)
view = PagedCacheView.bind(
raw,
dtype=torch.bfloat16,
row_width=row_width,
byte_offset=row_bytes,
block_stride=block_stride,
num_blocks=num_blocks,
block_size=block_size,
)
view.cache.copy_(
torch.arange(view.cache.numel(), dtype=torch.bfloat16).view_as(view.cache)
)
assert view.attention_cache.is_contiguous()
rows = view.attention_cache.view(-1, row_width)
for block in range(num_blocks):
for row in range(block_size):
assert torch.equal(
rows[block * view.attention_block_stride + row],
view.cache[block, row],
)


def test_hisparse_requires_block_outermost_device_layout():
assert HiSparseConnector.get_required_kvcache_layout(MagicMock()) == "BLHNC"

Expand Down
23 changes: 11 additions & 12 deletions tests/v1/worker/test_attn_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
)
from vllm.config.compilation import CompilationConfig, CUDAGraphMode
from vllm.models.kimi_k3.common.dsa_cache import SelfAddressedMLASpec
from vllm.v1.attention.backend import AttentionBackend, AttentionCGSupport, MultipleOf
from vllm.v1.attention.backend import AttentionBackend, AttentionCGSupport
from vllm.v1.core.kv_cache_utils import KVCacheBlockCopy
from vllm.v1.hisparse.backend import CUDAHiSparseBackend
from vllm.v1.hisparse.binding import allocate_hisparse_kv_caches
Expand Down Expand Up @@ -58,19 +58,18 @@


@pytest.mark.parametrize(
("enabled", "block_size", "main_sizes", "indexer_sizes", "expected"),
("enabled", "block_size", "main_sizes", "indexer_sizes", "supported"),
[
(True, 256, [64], [64], 64),
(True, 64, [32, 64], [16, 32], 32),
(True, 64, [MultipleOf(16)], [32], 32),
(True, 64, [64], [32], None),
(False, 256, [64], [64], 256),
(True, 256, [64], [64], True),
(True, 64, [64], [32], False),
(False, 256, [64], [64], True),
],
)
def test_get_kv_cache_spec_resolves_hisparse_block_size(
monkeypatch, enabled, block_size, main_sizes, indexer_sizes, expected
def test_get_kv_cache_spec_keeps_hisparse_scheduler_block_size(
monkeypatch, enabled, block_size, main_sizes, indexer_sizes, supported
):
"""Resolve shared MLA geometry before planning; leave other specs alone."""
"""HiSparse pages at the scheduler block once its backends share a kernel
block; other specs are left alone."""
specs = {
"main": MLAAttentionSpec(
block_size=block_size, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
Expand Down Expand Up @@ -106,13 +105,13 @@ def test_get_kv_cache_spec_resolves_hisparse_block_size(
config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=object() if enabled else None)
)
if expected is None:
if not supported:
with pytest.raises(ValueError, match="supported by every sparse"):
attn_utils.get_kv_cache_spec(config)
return

resolved = attn_utils.get_kv_cache_spec(config)
assert resolved["main"].block_size == resolved["indexer"].block_size == expected
assert resolved["main"].block_size == resolved["indexer"].block_size == block_size
dense_backend = layers["dense"].get_attn_backend()
assert resolved["dense"] == customize_attention_spec(dense_backend, specs["dense"])
assert all(spec.block_size == block_size for spec in specs.values())
Expand Down
3 changes: 2 additions & 1 deletion vllm/models/kimi_k3/common/dsa_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def build(
) -> DeepseekV32IndexerMetadata:
slot_mapping = get_compressed_slot_mapping(
common_attn_metadata.num_actual_tokens,
common_attn_metadata.slot_mapping,
None,
common_attn_metadata.query_start_loc,
common_attn_metadata.seq_lens,
common_attn_metadata.block_table_tensor,
Expand All @@ -107,6 +107,7 @@ def build(
out=self.slot_mapping_buffer,
dcp_world_size=self.dcp_world_size,
cp_interleave=self.cp_kv_cache_interleave_size,
dcp_rank=self.dcp_rank,
)
metadata = super().build(
common_prefix_len,
Expand Down
51 changes: 38 additions & 13 deletions vllm/v1/attention/backends/mla/compressor_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ class CompileKey:
triton_block_size: int
block_size: int
dcp_world_size: int
dcp_rank: int
cp_interleave: int
has_slot_mapping: bool

@staticmethod
@triton.jit(do_not_specialize=["block_table_stride"])
Expand All @@ -57,10 +59,12 @@ def kernel(
block_table_stride,
block_size,
dcp_world_size,
dcp_rank,
cp_interleave,
COMPRESS_RATIO: tl.constexpr,
PAD_ID: tl.constexpr,
TRITON_BLOCK_SIZE: tl.constexpr,
HAS_SLOT_MAPPING: tl.constexpr,
):
batch_idx = tl.program_id(0)

Expand All @@ -76,15 +80,18 @@ def kernel(
mask = offset < query_len

pos = start_pos + i + tl.arange(0, TRITON_BLOCK_SIZE)
# A replayed token has a PAD slot (SWA bounded replay: its KV is
# cached already); its compressed KV is cached too, so PAD here.
slot = tl.load(
slot_mapping_ptr + query_start + offset, mask=mask, other=PAD_ID
)
is_valid = ((pos + 1) % COMPRESS_RATIO == 0) & (slot != PAD_ID)
# Under DCP a PAD slot also marks tokens owned by other ranks; the
# interleave is a multiple of COMPRESS_RATIO, so a state lives
# entirely on the rank owning its last token.
is_valid = (pos + 1) % COMPRESS_RATIO == 0
# The interleave is a multiple of COMPRESS_RATIO, so under DCP a
# state lives entirely on the rank owning its last token.
if HAS_SLOT_MAPPING:
# A PAD slot marks a token owned by another DCP rank, or one SWA
# bounded replay recomputes: its compressed KV is cached too.
slot = tl.load(
slot_mapping_ptr + query_start + offset, mask=mask, other=PAD_ID
)
is_valid &= slot != PAD_ID
else:
is_valid &= pos // cp_interleave % dcp_world_size == dcp_rank
local_pos = (
pos // (cp_interleave * dcp_world_size) * cp_interleave
+ pos % cp_interleave
Expand Down Expand Up @@ -112,14 +119,18 @@ def dispatch( # type: ignore[override]
compress_ratio: int,
block_size: int,
dcp_world_size: int,
dcp_rank: int,
cp_interleave: int,
HAS_SLOT_MAPPING: bool,
) -> CompileKey:
return self.CompileKey(
compress_ratio=compress_ratio,
triton_block_size=self.TRITON_BLOCK_SIZE,
block_size=triton_scalar_specialization_rep(block_size),
dcp_world_size=triton_scalar_specialization_rep(dcp_world_size),
dcp_rank=triton_scalar_specialization_rep(dcp_rank),
cp_interleave=triton_scalar_specialization_rep(cp_interleave),
has_slot_mapping=HAS_SLOT_MAPPING,
)

def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
Expand All @@ -141,7 +152,9 @@ def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
compress_ratio=ratio,
block_size=vllm_config.cache_config.block_size // ratio,
dcp_world_size=parallel_config.decode_context_parallel_size,
dcp_rank=0,
cp_interleave=parallel_config.cp_kv_cache_interleave_size,
HAS_SLOT_MAPPING=True,
)
for ratio in compress_ratios
)
Expand All @@ -152,28 +165,36 @@ def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
int32_ptr = TritonWarmupTensor(torch.int32)
return dict(
compressed_slot_mapping=TritonWarmupTensor(torch.int64),
slot_mapping=TritonWarmupTensor(torch.int64),
slot_mapping=(
TritonWarmupTensor(torch.int64)
if compile_key.has_slot_mapping
else None
),
query_start_loc=int32_ptr,
seq_lens=int32_ptr,
block_table=int32_ptr,
block_size=compile_key.block_size,
compress_ratio=compile_key.compress_ratio,
dcp_world_size=compile_key.dcp_world_size,
dcp_rank=compile_key.dcp_rank,
cp_interleave=compile_key.cp_interleave,
HAS_SLOT_MAPPING=compile_key.has_slot_mapping,
)

@kernel_launcher
def __call__(
self,
compressed_slot_mapping: torch.Tensor,
slot_mapping: torch.Tensor,
slot_mapping: torch.Tensor | None,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
block_table: torch.Tensor,
block_size: int,
compress_ratio: int,
dcp_world_size: int,
dcp_rank: int,
cp_interleave: int,
HAS_SLOT_MAPPING: bool,
) -> LaunchSpec:
return (block_table.shape[0],), dict(
block_table_stride=block_table.stride(0),
Expand All @@ -185,7 +206,7 @@ def __call__(

def get_compressed_slot_mapping(
num_tokens: int,
slot_mapping: torch.Tensor,
slot_mapping: torch.Tensor | None,
query_start_loc: torch.Tensor,
seq_lens: torch.Tensor,
block_table: torch.Tensor,
Expand All @@ -194,14 +215,16 @@ def get_compressed_slot_mapping(
out: torch.Tensor | None = None,
dcp_world_size: int = 1,
cp_interleave: int = 1,
dcp_rank: int = 0,
) -> torch.Tensor:
"""Slot mapping for writing the compressed states of `num_tokens` tokens.

Every `compress_ratio` tokens share one compressed state, written by the
last of them: that token maps to the state's slot, the others to PAD. A
token whose own `slot_mapping` entry is PAD maps to PAD too: SWA bounded
replay recomputes tokens whose KV is cached already, and their compressed
states must not be rewritten either.
states must not be rewritten either. A self-addressed cache, whose group
may have no slot mapping, passes None and keeps the tokens `dcp_rank` owns.
"""
if out is not None:
# Guard: for padded / invalid sequences.
Expand All @@ -224,7 +247,9 @@ def get_compressed_slot_mapping(
block_size,
compress_ratio,
dcp_world_size,
dcp_rank,
cp_interleave,
slot_mapping is not None,
)
return compressed_slot_mapping

Expand Down
14 changes: 6 additions & 8 deletions vllm/v1/core/kv_cache_planning.py
Original file line number Diff line number Diff line change
Expand Up @@ -1784,16 +1784,14 @@ def get_kv_cache_groups(
"""See `KVCacheConfigBuilder.get_kv_cache_groups`.

A model implementing `SupportsKVCacheGrouping` owns the grouping
decision; otherwise the default grouping is used.
decision unless HiSparse, which owns its own grouping, is enabled;
otherwise the default grouping is used.
"""
if not vllm_config.model_config.supports_kv_cache_grouping:
if (
not vllm_config.model_config.supports_kv_cache_grouping
or vllm_config.attention_config.hisparse_config is not None
):
return get_kv_cache_groups(vllm_config, kv_cache_spec)
if vllm_config.attention_config.hisparse_config is not None:
raise ValueError(
"A model-declared get_kv_cache_groups cannot be combined "
"with HiSparse, which owns its own KV cache grouping. "
"Remove one of them."
)
model_cls, _ = vllm_config.model_config.registry.resolve_model_cls(
vllm_config.model_config.architectures,
vllm_config.model_config,
Expand Down
Loading