Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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: 9 additions & 0 deletions release_notes/fragments/23038.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pr: 23038
entries:
- category: feature
hardware: [A3, A5]
model: Kimi-K3.1-Pro
text: >-
Added experimental HiSparse support for Kimi K3.1 on Ascend A3 and A5
with Model Runner V2. Enable it with `hisparse_config` and
`HiSparseConnector`, using INT8 C8 KV on A3 or FP8 C8 KV on A5.
76 changes: 76 additions & 0 deletions tests/ut/attention/test_kimi_hisparse_sfa.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

from types import SimpleNamespace

import pytest
import torch

pytest.importorskip("vllm.v1.hisparse.backend")

from vllm_ascend.attention.sfa_hisparse import AscendHiSparseImpl # noqa: E402


def test_cold_mixed_prefill_masks_padded_topk():
block_size, topk = 128, 2048
num_input_tokens = 5
query_start_loc = torch.tensor([0, 1, 2, 4], dtype=torch.int32)
physical_decode = torch.full((2, topk), -1, dtype=torch.int32)
physical_decode[:, 0] = torch.tensor([5, 6], dtype=torch.int32)
slab = torch.empty((2, block_size, 656), dtype=torch.float8_e4m3fn)
staged_table = torch.tensor([[1]], dtype=torch.int32)
metadata = SimpleNamespace(
num_actual_tokens=4,
num_decode_tokens=2,
num_decodes=2,
num_prefills=1,
num_reqs=3,
block_size=block_size,
hisparse_for_capture=False,
query_start_loc=query_start_loc,
prefill_valid_token_mask=torch.arange(num_input_tokens, dtype=torch.int32)[:, None] < query_start_loc[-1],
# The metadata builder maps padding to the last request.
req_id_per_token=torch.tensor([0, 1, 2, 2, 2], dtype=torch.int32),
prefill=SimpleNamespace(host_staging_plan=SimpleNamespace(block_size=block_size)),
)

def stage_prefill_rows(layer_index, host, metadata):
reqs = metadata.req_id_per_token[metadata.num_decode_tokens :] - metadata.num_decodes
return slab, staged_table, reqs

def read_physical_indices(query, query_rope, packed_cache, physical_topk, **kwargs):
# Treat the first selected address as the attention result so the test
# can check the actual address translation without launching QSFA.
first = physical_topk[:, 0].to(query.dtype)
return first[:, None, None].expand_as(query)

impl = AscendHiSparseImpl.__new__(AscendHiSparseImpl)
impl.enable_sparse_sfa_c8 = True
impl.index_group_index = 0
impl.index_group = SimpleNamespace(
set_logical_topk_ready=lambda layer_index: None,
physical_kv_cache=lambda layer_index: slab,
stage_prefill_rows=stage_prefill_rows,
)
impl.hisparse_cache = SimpleNamespace(
source_block_table=torch.zeros((3, 1), dtype=torch.int32),
swap_in=lambda *args, **kwargs: physical_decode,
runtime=SimpleNamespace(
host_cache=slab.view(-1, 656),
cache_ops=SimpleNamespace(
attention_lengths=(torch.arange(3, dtype=torch.int32), torch.tensor([256], dtype=torch.int32)),
attention_capacity=256,
),
),
)
impl._attention_physical = read_physical_indices

query = torch.empty((num_input_tokens, 12, 512), dtype=torch.bfloat16)
query_tail = torch.empty((num_input_tokens, 12, 64), dtype=torch.bfloat16)
logical = torch.full((num_input_tokens, 1, topk), -1, dtype=torch.int32)
logical[2:, 0, 0] = torch.tensor([1, 2, 127], dtype=torch.int32)
result = impl._execute_sparse_flash_attention_process(
query, query_tail, (), logical, metadata, metadata.query_start_loc[1:], torch.ones(3, dtype=torch.int32)
)

torch.testing.assert_close(result[:, 0, 0], torch.tensor([5, 6, 129, 130, -1], dtype=torch.bfloat16))
218 changes: 211 additions & 7 deletions tests/ut/core/test_kv_cache_config_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
# ruff: noqa: E402
"""Dispatch contract of ``AscendKVCacheConfigBuilder``.

Locks the grouping precedence (GLM-Next, Qwen4-Exp MTP, Ascend shared-tuple
layouts, Kimi-K3 DSpark, then vLLM's generic grouping) and the TurboQuant pool
accounting, all of which now live in the builder rather than in a monkey patch.
Covers hybrid HiSparse dispatch and device layout, ordinary grouping precedence,
and TurboQuant pool accounting.
"""

from dataclasses import replace
from types import SimpleNamespace
from unittest.mock import Mock

Expand All @@ -20,19 +20,32 @@

import torch
from vllm.config import KVTransferConfig
from vllm.v1.core.kv_cache_planning import DefaultKVCacheConfigBuilder
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.core.kv_cache_planning import (
DefaultKVCacheConfigBuilder,
_get_kv_cache_bytes_per_block,
_max_memory_usage_bytes_from_groups,
_pool_bytes_per_block_from_builder,
)
from vllm.v1.core.single_type_kv_cache_manager import register_all_kvcache_specs
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
HiSparseHotSpec,
HiSparseResidentSpec,
KVCacheConfig,
KVCacheGroupRole,
KVCacheGroupSpec,
MambaSpec,
MLAAttentionSpec,
SparseCacheRole,
UniformTypeKVCacheSpecs,
)
from vllm.v1.kv_cache_layout import KVCacheLayout

from vllm_ascend.core import kv_cache_config_builder as builder_module
from vllm_ascend.core.kv_cache_config_builder import AscendKVCacheConfigBuilder
from vllm_ascend.core.kv_cache_interface import (
AscendSFAIndexerCacheSpec,
AscendSlidingWindowMLASpec,
register_ascend_kv_cache_specs,
)
Expand Down Expand Up @@ -62,6 +75,49 @@ def make_runtime():
)


def make_hisparse_runtime(model_type="mixed_sparse_model", layout=None):
runtime = make_runtime()
runtime.model_config.hf_config.model_type = model_type
runtime.model_config.hf_config.index_topk = 2048
runtime.model_config.hf_text_config = SimpleNamespace(index_topk=2048)
runtime.model_config.max_model_len = 2048
runtime.attention_config.hisparse_config = SimpleNamespace(device_buffer_size=None, eager_host_mirror=True)
runtime.speculative_config = None
runtime.max_in_flight_tokens = 1024
runtime.parallel_config = SimpleNamespace(decode_context_parallel_size=1)
runtime.cache_config = SimpleNamespace(
kv_cache_layout=layout,
mamba_cache_mode="align",
get_resolved_kv_cache_layout=lambda: layout,
)
return runtime


def sparse_attention_specs():
return {
"main": MLAAttentionSpec(
block_size=128,
num_kv_heads=1,
head_size=656,
dtype=torch.float8_e4m3fn,
cache_role=SparseCacheRole.SPARSE,
state_content_bytes=656,
block_stride_alignment=128 * 656,
is_index_group_leader=True,
),
"indexer": AscendSFAIndexerCacheSpec(
block_size=128,
num_kv_heads=1,
head_size=128,
dtype=torch.float8_e4m3fn,
cache_role=SparseCacheRole.INDEXER,
cache_sparse_li_c8=True,
scale_dim=1,
scale_dtype=torch.float32,
),
}


def generic_specs():
spec = FullAttentionSpec(block_size=16, num_kv_heads=1, head_size=16, dtype=torch.bfloat16)
return {"layer.a": spec, "layer.b": spec}
Expand All @@ -85,16 +141,164 @@ def test_kimi_k31_grouping_precedes_generic_hybrid_promotion(monkeypatch):
def test_kimi_k31_builder_uses_paired_grouping_and_pool_accounting(monkeypatch):
runtime = make_runtime()
runtime.model_config.hf_config.model_type = "kimi_k31"
specs, groups = generic_specs(), [Mock()]
specs = generic_specs()
groups = [KVCacheGroupSpec(list(specs), specs["layer.a"])]
paired = Mock(return_value=groups)
pool = Mock(return_value=14487552)
bytes_per_block = 14487552
pool = Mock(return_value=bytes_per_block)
num_blocks = 2
expected = KVCacheConfig(num_blocks=num_blocks, kv_cache_tensors=[], kv_cache_groups=groups)
place = Mock(return_value=expected)
monkeypatch.setattr(builder_module, "paired_sfa_cache_groups", paired)
monkeypatch.setattr(builder_module, "paired_sfa_pool_bytes", pool)
monkeypatch.setattr(builder_module, "paired_sfa_cache_config", place)
builder = AscendKVCacheConfigBuilder()
assert builder.get_kv_cache_groups(runtime, specs) is groups
assert builder._get_pool_bytes_per_block(runtime, groups) == 14487552
assert builder._get_pool_bytes_per_block(runtime, groups) == bytes_per_block
paired.assert_called_once_with(runtime, specs)
pool.assert_called_once_with(groups)
assert builder.get_kv_cache_config_from_groups(runtime, groups, num_blocks) is expected
place.assert_called_once_with(runtime, groups, num_blocks * bytes_per_block)


@pytest.mark.parametrize("model_type", ["kimi_k31", "mixed_sparse_model"])
def test_hybrid_hisparse_uses_native_indexer_page_and_separate_recurrent_groups(model_type):
runtime = make_hisparse_runtime(model_type)
state = MambaSpec(
block_size=128,
shapes=((32, 64), (16, 64, 64)),
dtypes=(torch.bfloat16, torch.float32),
mamba_type=MambaAttentionBackendEnum.GDN_ATTN,
)
groups = AscendKVCacheConfigBuilder().get_kv_cache_groups(
runtime, {**sparse_attention_specs(), "state.0": state, "state.1": state}
)

host, pooled_indexer, resident, hot, *states = groups
assert host.host_resident and host.role is KVCacheGroupRole.HISPARSE_SOURCE
assert host.layer_names == ["main"]
assert pooled_indexer.role is KVCacheGroupRole.HISPARSE_INDEXER and not pooled_indexer.host_resident
assert pooled_indexer.kv_cache_spec.block_size == 128
indexer = pooled_indexer.kv_cache_spec.kv_cache_specs["indexer"]
assert (indexer.block_table_block_size or indexer.block_size) == 128
assert isinstance(resident.kv_cache_spec, HiSparseResidentSpec)
assert isinstance(hot.kv_cache_spec, HiSparseHotSpec)
assert hot.kv_cache_spec.get_block_stride_alignment() == hot.kv_cache_spec.page_size_bytes == 128 * 656
assert [group.layer_names for group in states] == [["state.0"], ["state.1"]]
assert all(group.kv_cache_spec == state for group in states)
assert all(not group.host_resident for group in states)


@pytest.mark.parametrize("draft_from_config", [False, True])
def test_hybrid_hisparse_rejects_draft_caches(draft_from_config):
runtime = make_hisparse_runtime("kimi_k31")
specs = sparse_attention_specs()
specs["state"] = MambaSpec(block_size=128, shapes=((32,),), dtypes=(torch.float32,))
if draft_from_config:
runtime.speculative_config = object()
else:
specs["main"] = replace(specs["main"], is_draft=True)

with pytest.raises(ValueError, match="does not support draft caches"):
AscendKVCacheConfigBuilder().get_kv_cache_groups(runtime, specs)


def test_hybrid_hisparse_rejects_unsupported_attention():
runtime = make_hisparse_runtime("kimi_k31")
state = MambaSpec(block_size=128, shapes=((32,),), dtypes=(torch.float32,))
specs = {**sparse_attention_specs(), "state": state, **generic_specs()}

with pytest.raises(ValueError, match=r"Unsupported cache spec in Ascend hybrid SFA HiSparse: layer\.a"):
AscendKVCacheConfigBuilder().get_kv_cache_groups(runtime, specs)


def test_hybrid_hisparse_groups_recurrent_layers_by_resolved_device_stride():
runtime = make_hisparse_runtime()
sparse = sparse_attention_specs()
state = MambaSpec(
block_size=128,
shapes=((25_000,),),
dtypes=(torch.bfloat16,),
mamba_type=MambaAttentionBackendEnum.GDN_ATTN,
)
specs = {f"{name}.{i}": spec for i in range(6) for name, spec in {**sparse, "state": state}.items()}
builder = AscendKVCacheConfigBuilder()
baseline = builder.get_kv_cache_groups(runtime, specs)

layout = KVCacheLayout.BLHNC
runtime = make_hisparse_runtime(layout=layout)
selected = builder.get_kv_cache_groups(runtime, specs)

# The six Indexer pages occupy 101,376 bytes. Aligning to a full MLA
# page already costs 167,936 bytes, enough for a third state per block.
baseline_device = [group for group in baseline if not group.host_resident]
selected_device = [group for group in selected if not group.host_resident]
assert _get_kv_cache_bytes_per_block(baseline_device, layout) == _get_kv_cache_bytes_per_block(
selected_device, layout
)
assert _max_memory_usage_bytes_from_groups(builder, runtime, selected) < _max_memory_usage_bytes_from_groups(
builder, runtime, baseline
)
old_states = [group for group in baseline if isinstance(group.kv_cache_spec, MambaSpec)]
new_states = [group for group in selected if isinstance(group.kv_cache_spec, MambaSpec)]
assert [len(group.layer_names) for group in old_states] == [2, 2, 2]
assert [len(group.layer_names) for group in new_states] == [3, 3]
assert {name for group in new_states for name in group.layer_names} == {f"state.{i}" for i in range(6)}
(indexer,) = [group for group in selected if group.role is KVCacheGroupRole.HISPARSE_INDEXER]
assert indexer.kv_cache_spec.block_size == 128


@pytest.mark.parametrize("model_type", ["kimi_k31", "mixed_sparse_model"])
def test_hisparse_without_recurrent_state_preserves_upstream_grouping(model_type):
runtime = make_hisparse_runtime(model_type)
specs = sparse_attention_specs()
expected = DefaultKVCacheConfigBuilder().get_kv_cache_groups(runtime, specs)
assert AscendKVCacheConfigBuilder().get_kv_cache_groups(runtime, specs) == expected


@pytest.mark.parametrize(
"model_type, include_recurrent",
[("mixed_sparse_model", True), ("kimi_k31", False), ("kimi_k31", True)],
)
def test_hisparse_placement_uses_the_core_device_block_stride(monkeypatch, model_type, include_recurrent):
from vllm.v1.hisparse import layout as hisparse_layout

layout = KVCacheLayout.BLHNC
runtime = make_hisparse_runtime(model_type, layout=layout)
runtime.cache_config.num_gpu_blocks_override = None
runtime.cache_config.prefix_cache_retention_interval = None
runtime.kv_transfer_config = SimpleNamespace(
kv_connector="HiSparseConnector",
kv_connector_extra_config={"host_pool_gib": 1},
)
monkeypatch.setattr(hisparse_layout, "use_shared_hisparse_host_pool", lambda _: False)
specs = sparse_attention_specs()
if include_recurrent:
specs["state"] = MambaSpec(block_size=128, shapes=((65_536,),), dtypes=(torch.float32,))
builder = AscendKVCacheConfigBuilder()
groups = builder.get_kv_cache_groups(runtime, specs)

device_groups = [group for group in groups if not group.host_resident]
stride = _get_kv_cache_bytes_per_block(device_groups, layout)
assert _pool_bytes_per_block_from_builder(builder, runtime, device_groups) == stride
assert _max_memory_usage_bytes_from_groups(builder, runtime, groups) > 0

num_blocks = 64
config = builder.get_kv_cache_config_from_groups(runtime, groups, num_blocks)
assert config.num_blocks == num_blocks
assert config.hisparse_host_num_blocks > 0
assert {layer for tensor in config.kv_cache_tensors if tensor.host_resident for layer in tensor.layers} == {"main"}
device_layers = {layer for tensor in config.kv_cache_tensors if not tensor.host_resident for layer in tensor.layers}
assert "indexer" in device_layers
if include_recurrent:
assert "state" in device_layers
(state_group,) = [group for group in device_groups if isinstance(group.kv_cache_spec, MambaSpec)]
assert state_group.layer_names == ["state"]
assert all(
tensor.block_stride == stride and tensor.size == stride * num_blocks
for tensor in config.kv_cache_tensors
if not tensor.host_resident
)


@pytest.mark.parametrize("draft_sharded", [True, False])
Expand Down
Loading
Loading