Skip to content
Open
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
22 changes: 19 additions & 3 deletions docs/source/user_guide/feature_guide/hisparse.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ serving path or change the existing non-HiSparse BF16 path.

| Category | Constraint |
| --- | --- |
| Hardware and software | A2/A3 with the arch22 custom operators, or 950PR&950DT Products with a SIMT-capable CANN 9.2 toolchain. |
| Hardware and software | A2/A3 with the arch22 custom operators, or 950PR&950DT Products with a SIMT-capable CANN 9.2 toolchain. Requires a vLLM build with the platform HiSparse backend interface. |
| Cache formats | A2/A3: INT8 C8. 950PR&950DT Products: BF16 or native E4M3FN C8. C4 and TurboQuant are outside the current support scope. |
| Parallelism and transport | Supports PCP (prefill and decode request sharding). DCP and external P/D transport are outside the current support scope. |
| Host storage | Use private Host pools per tensor-parallel rank and Core eager Host mirroring. |
| Host storage | Use private Host pools per tensor-parallel rank. Core mirrors Host KV eagerly by default. |
| TopK | The existing SFA requirement of divisibility by 128 applies. |
| Feature mutual exclusion | HiSparse and `additional_config.sparse_kv_offload_config.enabled` cannot be enabled together. |

Expand Down Expand Up @@ -84,6 +84,22 @@ For a `MultiConnector` configuration, put `transfer_backend` in the
`HiSparseConnector` child's extra configuration. This setting selects
the private Host allocator. Omitting it uses native ACL Host-memory registration.

#### GLM-5.3-Flash on 950DT

Start from the [950DT single-node deployment](../../tutorials/models/GLM5.3-Flash.md#glm53-flash-5-1-950dt).
Keep Model Runner V2, FP8 main KV, the hybrid KV cache manager, and one rank
for each of DP, PP, PCP and DCP. The hybrid layout requires the verified
vLLM main pin with Mamba cache fitting. Replace the recipe's indexer attention
option and add the local HiSparse connector:

```bash
--attention-config '{"indexer_kv_dtype":"fp8","hisparse_config":{"eager_host_mirror":false}}' \
--kv-transfer-config '{"kv_connector":"HiSparseConnector","kv_role":"kv_both","kv_connector_extra_config":{"host_pool_gib":8}}'
```

The host pool stores target DSA pages. The KeyPool index and KDA state stay
on device and keep the existing MTP5 cache lifecycle.

### Verifying the Feature

Send a request and check the server's metrics endpoint for the HiSparse miss
Expand All @@ -98,7 +114,7 @@ curl -fsS http://127.0.0.1:8000/metrics | grep '^vllm:hisparse_cache_misses_tota
| Parameter | Meaning |
| --- | --- |
| `hisparse_config` | Enables Core HiSparse for the supported sparse Attention backend. |
| `eager_host_mirror` | Keep `true` for this foundation; Core maintains the Host KV mirror. |
| `eager_host_mirror` | Defaults to `true` for eager Host mirroring. Set it to `false` for lazy Host mirroring. |
| `host_pool_gib` | Host pool size in GiB per tensor-parallel rank. Size it for the planned context lengths and concurrency; the example reserves 4 GiB per rank. |
| `device_buffer_size` | Per-request Hot capacity in KV rows. It must hold the deduplicated union of rows selected during speculative verification and fit the resolver's on-chip UB budget. |
| `kv_cache_dtype` / `indexer_kv_dtype` | Select main and Indexer KV formats independently from model-weight quantization. |
4 changes: 4 additions & 0 deletions release_notes/fragments/23263.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pr: 23142
entries:
- category: feature
text: Added opt-in HiSparse for single-node GLM-5.3-Flash inference on Ascend 950DT with FP8 KV cache. The existing HiSparse configuration also recognizes compatible native SFA and recurrent-state layouts when speculative decoding is disabled. Both layouts require the verified vLLM main pin with Mamba cache fitting.
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,10 @@ def run_resolver(
host_rows=64,
attention_capacity=0,
attention_block_stride=0,
valid_rows=None,
):
device = torch.device("npu:0")
num_valid_rows = None if valid_rows is None else torch.tensor([valid_rows], dtype=torch.int32, device=device)
tensors = [t.npu() for t in (logical_cpu, hot_table_cpu, requests_cpu, states_cpu, source_cpu, resident_cpu)]
logical, hot_table, requests, states, source, resident = tensors
dgi = dgi_cpu.npu()
Expand Down Expand Up @@ -150,7 +152,7 @@ def run_resolver(
states,
source,
resident,
None,
num_valid_rows,
dgi,
lru,
output,
Expand Down Expand Up @@ -266,6 +268,50 @@ def test_resolver_matches_torch_reference_all_resident(attention_capacity):
assert_matches_reference(actual, expected)


@pytest.mark.parametrize("cold", [False, True])
def test_flash_resident_rows_and_cold_fallback(cold):
block, topk, hot_size, stride = 128, 2176, 15232, 1152
rows, valid_rows = 7, 6
logical = torch.arange(rows * topk, dtype=torch.int32).view(rows, topk) % 4096
logical[:, 1::31] = -1
requests = torch.zeros(rows, dtype=torch.int32)
states = torch.zeros(1, dtype=torch.int32)
source = torch.arange(1, 33, dtype=torch.int32)[None]
resident = source.clone()
if cold:
resident[0, 1] = 0
hot_table = torch.arange(33, 33 + hot_size // block, dtype=torch.int32)[None]
tags = torch.full((1, hot_size), -1, dtype=torch.int32)
lru = torch.arange(hot_size, dtype=torch.int16)[None]
live_requests = requests.clone()
live_requests[valid_rows:] = -1
expected = reference(logical, live_requests, states, source, resident, hot_table, tags, lru, block)
actual, attention = run_resolver(
logical,
hot_table,
requests,
states,
source,
resident,
tags,
lru,
block=block,
union_rows=topk * valid_rows,
host_rows=33 * block,
attention_capacity=160 * stride,
attention_block_stride=stride,
valid_rows=valid_rows,
)
assert_matches_reference(actual, expected)
mapped = expected[0].clone()
for row in mapped:
active = row[row >= 0]
row.fill_(-1)
row[: active.numel()] = active // block * stride + active % block
torch.testing.assert_close(attention.cpu(), mapped)
assert bool(actual[-1][1].item()) == cold


def test_resolver_matches_torch_reference_single_warp_scan():
"""One state, a full LRU turn and duplicates; tiles<=32 register scan."""
block = 16
Expand Down
271 changes: 271 additions & 0 deletions tests/ut/core/test_native_hybrid_hisparse_layout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,271 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Ascend project

from dataclasses import replace
from types import SimpleNamespace

import pytest
import torch

pytest.importorskip("vllm.v1.hisparse.backend")
from vllm.v1.core.kv_cache_planning import (
DefaultKVCacheConfigBuilder,
_max_memory_usage_bytes_from_groups,
_pool_bytes_per_block,
_pool_bytes_per_block_from_builder,
)
from vllm.v1.core.single_type_kv_cache_manager import register_all_kvcache_specs
from vllm.v1.hisparse import layout as core_layout
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
HiSparseHotSpec,
HiSparseResidentSpec,
KVCacheGroupRole,
MambaSpec,
MLAAttentionSpec,
SparseCacheRole,
)
from vllm.v1.kv_cache_layout import KVCacheLayout

from vllm_ascend.core.kv_cache_interface import AscendSFAIndexerCacheSpec, register_ascend_kv_cache_specs
from vllm_ascend.hisparse import supports_hybrid_hisparse_core
from vllm_ascend.hisparse.layout import get_hybrid_sfa_hisparse_groups, has_hybrid_sfa_hisparse_groups

requires_hybrid_core = pytest.mark.skipif(
not supports_hybrid_hisparse_core(), reason="The runtime layout requires Core Mamba page fitting"
)


@pytest.fixture(autouse=True)
def registered_specs():
register_all_kvcache_specs(None)
register_ascend_kv_cache_specs()


def make_runtime(model_type="unregistered_sparse_model", layout=None):
return SimpleNamespace(
attention_config=SimpleNamespace(
hisparse_config=SimpleNamespace(device_buffer_size=None, eager_host_mirror=True),
),
cache_config=SimpleNamespace(
kv_cache_layout=layout,
mamba_cache_mode="align",
num_gpu_blocks_override=None,
prefix_cache_retention_interval=None,
get_resolved_kv_cache_layout=lambda: layout,
),
model_config=SimpleNamespace(hf_config=SimpleNamespace(model_type=model_type), max_model_len=2048),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
speculative_config=None,
max_in_flight_tokens=1024,
)


def make_specs():
return {
"sparse": 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,
topk_buffer_width=2048,
),
"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,
),
"state": MambaSpec(
block_size=128,
shapes=((25_000,),),
dtypes=(torch.bfloat16,),
),
}


@pytest.mark.parametrize("model_type", ["kimi_k31", "unregistered_sparse_model"])
@requires_hybrid_core
def test_native_hybrid_retains_separate_cache_geometry(model_type):
specs = make_specs()
groups = get_hybrid_sfa_hisparse_groups(make_runtime(model_type), specs)

host, indexer, resident, hot, state = groups
assert host.host_resident and host.role is KVCacheGroupRole.HISPARSE_SOURCE
assert host.layer_names == ["sparse"]
assert indexer.role is KVCacheGroupRole.HISPARSE_INDEXER
native_indexer = indexer.kv_cache_spec.kv_cache_specs["indexer"]
assert native_indexer.block_size == native_indexer.block_table_block_size == 128
assert native_indexer.page_size_bytes == 128 * (128 + 4)
assert isinstance(resident.kv_cache_spec, HiSparseResidentSpec)
assert isinstance(hot.kv_cache_spec, HiSparseHotSpec)
assert hot.kv_cache_spec.get_block_stride_alignment() == 128 * 656
assert state.layer_names == ["state"]
assert state.kv_cache_spec == specs["state"]
assert all(not group.host_resident for group in groups[1:])
assert has_hybrid_sfa_hisparse_groups(groups)
assert has_hybrid_sfa_hisparse_groups(groups[1:])


@requires_hybrid_core
def test_layout_feedback_fits_more_state_layers_within_same_stride(monkeypatch):
specs = {f"{name}.{i}": spec for i in range(6) for name, spec in make_specs().items()}
provisional = get_hybrid_sfa_hisparse_groups(make_runtime(), specs)
runtime = make_runtime(layout=KVCacheLayout.BLHNC)
resolved = get_hybrid_sfa_hisparse_groups(runtime, specs)

def state_counts(groups):
return [len(group.layer_names) for group in groups if isinstance(group.kv_cache_spec, MambaSpec)]

assert state_counts(provisional) == [2, 2, 2]
assert state_counts(resolved) == [3, 3]
assert _pool_bytes_per_block(runtime, provisional) == _pool_bytes_per_block(runtime, resolved)
builder = DefaultKVCacheConfigBuilder()
assert _max_memory_usage_bytes_from_groups(builder, runtime, resolved) < _max_memory_usage_bytes_from_groups(
builder, runtime, provisional
)

monkeypatch.setattr(core_layout, "use_shared_hisparse_host_pool", lambda _: False)
stride = _pool_bytes_per_block(runtime, resolved)
materialized = core_layout.get_hisparse_kv_cache_config(runtime, resolved, 64 * stride, 1 << 30)
assert materialized.num_blocks == 64
assert all(
tensor.block_stride == stride and tensor.size == 64 * stride
for tensor in materialized.kv_cache_tensors
if not tensor.host_resident
)


@pytest.mark.parametrize("model_type", ["kimi_k31", "unregistered_sparse_model"])
@requires_hybrid_core
def test_ascend_builder_routes_native_hybrid_to_core_placement(model_type, monkeypatch):
from vllm_ascend.core import kv_cache_config_builder as builder_module

runtime = make_runtime(model_type, layout=KVCacheLayout.BLHNC)
runtime.kv_transfer_config = SimpleNamespace(
kv_connector="HiSparseConnector",
kv_connector_extra_config={"host_pool_gib": 1},
)

def fail_paired_layout(*args):
pytest.fail("HiSparse must not enter the ordinary paired SFA layout.")

monkeypatch.setattr(builder_module, "paired_sfa_cache_groups", fail_paired_layout)
monkeypatch.setattr(builder_module, "paired_sfa_cache_config", fail_paired_layout)
monkeypatch.setattr(core_layout, "use_shared_hisparse_host_pool", lambda _: False)
builder = builder_module.AscendKVCacheConfigBuilder()
specs = make_specs()
groups = builder.get_kv_cache_groups(runtime, specs)
assert groups == get_hybrid_sfa_hisparse_groups(runtime, specs)

stride = _pool_bytes_per_block_from_builder(builder, runtime, groups)
assert stride == _pool_bytes_per_block(runtime, groups)
materialized = builder.get_kv_cache_config_from_groups(runtime, groups, num_blocks=64)
assert materialized.num_blocks == 64
assert materialized.hisparse_host_num_blocks > 0
assert {name for tensor in materialized.kv_cache_tensors if tensor.host_resident for name in tensor.layers} == {
"sparse"
}
assert all(
tensor.block_stride == stride and tensor.size == 64 * stride
for tensor in materialized.kv_cache_tensors
if not tensor.host_resident
)


def test_native_provider_leaves_other_layouts_to_their_owners():
runtime = make_runtime()
specs = make_specs()
attention_specs = {name: spec for name, spec in specs.items() if name != "state"}
assert get_hybrid_sfa_hisparse_groups(runtime, attention_specs) is None
runtime.attention_config.hisparse_config = None
assert get_hybrid_sfa_hisparse_groups(runtime, specs) is None


def test_native_hybrid_requires_core_page_fitting(monkeypatch):
from vllm_ascend import hisparse

monkeypatch.setattr(hisparse, "supports_hybrid_hisparse_core", lambda: False)

with pytest.raises(ValueError, match="verified vLLM main pin"):
get_hybrid_sfa_hisparse_groups(make_runtime(), make_specs())


@pytest.mark.parametrize("draft_source", ["config", "indexer", "state"])
@requires_hybrid_core
def test_native_hybrid_rejects_speculative_and_draft_caches(draft_source):
runtime = make_runtime()
specs = make_specs()
if draft_source == "config":
runtime.speculative_config = SimpleNamespace(method="mtp")
elif draft_source == "state":
specs["state"] = replace(specs["state"], num_speculative_blocks=1)
else:
specs["indexer"] = replace(specs["indexer"], is_draft=True)
with pytest.raises(ValueError, match="does not support speculative decoding or draft caches"):
get_hybrid_sfa_hisparse_groups(runtime, specs)


@requires_hybrid_core
def test_native_hybrid_rejects_unsupported_attention_cache():
specs = make_specs()
specs["dense"] = FullAttentionSpec(block_size=128, num_kv_heads=1, head_size=128, dtype=torch.bfloat16)
with pytest.raises(ValueError, match=r"Unsupported cache spec.*dense"):
get_hybrid_sfa_hisparse_groups(make_runtime(), specs)


@pytest.mark.parametrize(("rope_dim", "row_bytes"), [(0, 528), (64, 656)])
@requires_hybrid_core
def test_worker_native_hybrid_uses_runtime_row_width(rope_dim, row_bytes, monkeypatch):
from vllm.v1.attention.backend import AttentionBackend

from vllm_ascend.attention.utils import get_sfa_qsfa_packed_head_dim
from vllm_ascend.worker.v2 import attn_utils

class Backend(AttentionBackend):
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None):
return [128]

runtime = make_runtime()
runtime.cache_config.mamba_cache_mode = "none"
runtime.cache_config.mamba_page_size_padded = None
specs = make_specs()
specs["sparse"] = replace(specs["sparse"], state_content_bytes=None, block_stride_alignment=None)

def layer_attributes(spec):
return {
"get_attn_backend": lambda: Backend,
"get_kv_cache_spec": lambda _: spec,
"is_draft_layer": False,
}

layers = {name: SimpleNamespace(**layer_attributes(spec)) for name, spec in specs.items()}
sparse = attn_utils.MLAAttention.__new__(attn_utils.MLAAttention)
torch.nn.Module.__init__(sparse)
for name, value in layer_attributes(specs["sparse"]).items():
setattr(sparse, name, value)
packed_dim = get_sfa_qsfa_packed_head_dim(512, rope_dim)
sparse.impl = SimpleNamespace(
enable_sparse_sfa_c8=True,
sfa_qsfa_packed_kv_head_dim=packed_dim,
c8_cache_dtype=torch.float8_e4m3fn,
)
sparse.hisparse_cache = SimpleNamespace(runtime=SimpleNamespace(is_group_leader=True))
layers["sparse"] = sparse
monkeypatch.setattr(attn_utils, "get_layers_from_vllm_config", lambda *_: layers)

collected = attn_utils.get_kv_cache_spec(runtime)

assert collected["sparse"].head_size == row_bytes
assert collected["sparse"].block_stride_alignment == 128 * row_bytes
[hot] = [spec for spec in collected.values() if isinstance(spec, HiSparseHotSpec)]
assert hot.page_size_bytes == hot.block_stride_alignment == 128 * row_bytes
Loading
Loading