Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
586 changes: 382 additions & 204 deletions csrc/libtorch_stable/hisparse_kernels.cu

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions docs/design/hisparse.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,10 @@ path. The resolver consumes the existing graph-stable request mapping from
attention metadata; neither the worker nor individual cache handles keep a
duplicate mapping.

Speculative decoding resolves and consumes each verification step in order.
Each step receives distinct replayable plan rows while sharing the request's
hot-cache state, so a later step cannot reuse a hot row before an earlier step
has consumed it.
Speculative decoding resolves all verification rows of a request in one pass:
one block resolves the union of the rows' top-k against the request's hot-cache
state, so rows that select the same host row share its hot row and no row
evicts a hot row another row of the step still reads.

## P/D import target

Expand Down
231 changes: 125 additions & 106 deletions tests/v1/attention/test_sparse_mla_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@
from vllm.v1.attention.backends.mla import index_group as index_group_module
from vllm.v1.attention.backends.mla.flashattn_mla_sparse import (
FlashAttnMLASparseImpl,
FlashAttnMLASparseMetadataBuilder,
)
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseImpl,
FlashInferMLASparseMetadataBuilder,
FlashInferMLASparseTRTLLMBackend,
)
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm120 import (
Expand Down Expand Up @@ -2015,6 +2015,73 @@ def test_hisparse_maps_speculative_rows_through_request_state():
assert physical.tolist() == [[block_size]] * 4


@requires_hisparse_ops
@pytest.mark.parametrize(
"num_rows,row_stride,top_k",
[(2, 128, 128), (8, 128, 128), (4, 32, 128), (8, 2048, 2048)],
ids=["2", "8", "overlap", "long_mtp"],
)
def test_hisparse_speculative_rows_resolve_host_misses_consistently(
num_rows, row_stride, top_k
):
"""Verification rows of one request must agree on its hot-buffer slots.

Each row resolved residency in its own thread block against the request's
shared slot ownership and LRU, so rows missing on different host rows could
claim the same free slot. One row's hot index then pointed at a slot holding
another row's KV. Overlapping rows must share one slot per host row.
long_mtp's 16k-row hot buffer must fit the union table in shared memory.
"""
device = torch.device(DEVICE_TYPE)
block_size, row_width = 64, 64
num_blocks = 2 * num_rows * top_k // block_size

kv_pool = torch.randn(
(num_blocks + 1, block_size, row_width), dtype=torch.float32
).pin_memory()
flat_pool = kv_pool.reshape(-1, row_width)
runtime = _make_hisparse_runtime(
top_k=top_k,
device_buffer_size=num_rows * top_k,
max_num_reqs=1,
row_width=row_width,
block_size=block_size,
max_swap_rows=num_rows,
)
runtime.bind_source_cache(kv_pool)
cache = HiSparseCacheHandle(runtime)
cache.all_context_pages_resident = False

block_table = torch.arange(
1, num_blocks + 1, dtype=torch.int32, device=device
).view(1, num_blocks)
req_ids = torch.zeros(num_rows, dtype=torch.int32, device=device)
rows = torch.arange(num_rows, dtype=torch.int32, device=device)[:, None]
base = torch.arange(top_k, dtype=torch.int32, device=device)[None, :]
for step in range(4):
runtime.begin_forward()
# Rows start row_stride apart (disjoint at row_stride == top_k) and
# shift by half a top-k per step: all misses first, then a mix.
topk = (rows * row_stride + base + step * (top_k // 2)) % (
num_blocks * block_size
)
hot_indices = cache.swap_in(
req_id_per_token=req_ids,
block_table=block_table,
logical_topk_indices=topk.clone(),
block_size=block_size,
)
torch.accelerator.synchronize()

global_ref = _triton_convert_reference_impl(
req_ids, block_table, topk, block_size, top_k
)
gathered = runtime.hot.attention_cache.reshape(-1, row_width)[
hot_indices.to(torch.long)
].cpu()
torch.testing.assert_close(gathered, flat_pool[global_ref.cpu().to(torch.long)])


@requires_hisparse_ops
def test_hisparse_resident_rows_bypass_hot_lru():
device = torch.device(DEVICE_TYPE)
Expand Down Expand Up @@ -3001,8 +3068,8 @@ def test_hisparse_gather_prefill_cache_prefers_resident_rows():
torch.testing.assert_close(staged_flat[i], expected)


def test_hisparse_fp8_decode_resolves_steps_then_runs_batched_attention(monkeypatch):
"""FP8 decode must use active dimensions when common metadata is padded."""
def test_hisparse_fp8_decode_resolves_rows_once_then_runs_batched_attention():
"""Verification rows resolve in one swap_in; FP8 attention sees them batched."""
device = torch.device("cpu")
num_decodes = 2
query_len = 3
Expand All @@ -3013,133 +3080,108 @@ def test_hisparse_fp8_decode_resolves_steps_then_runs_batched_attention(monkeypa
.view(-1, 1)
.expand(-1, 4)
)
steps: list[int] = []
kernel_shapes: list[torch.Size] = []

def swap_in(req_ids, *, logical_topk_indices, **kwargs): # noqa: ARG001
steps.append(int(logical_topk_indices[0, 0]))
output = kwargs["attention_indices_out"]
if output is not None:
output.copy_(logical_topk_indices + 10)
return topk[:num_decodes]
return logical_topk_indices + 10

def run_kernel(self, *, q, **kwargs): # noqa: ARG001
kernel_shapes.append(q.shape)
return q[..., :1], None

runtime = SimpleNamespace(
hot=SimpleNamespace(attention_cache=torch.empty(1, device=device))
)
leader_cache = SimpleNamespace(
runtime=runtime,
source_block_table=torch.empty(
num_decodes, 1, dtype=torch.int32, device=device
cache = SimpleNamespace(
runtime=SimpleNamespace(
hot=SimpleNamespace(attention_cache=torch.empty(1, device=device))
),
swap_in=MagicMock(side_effect=swap_in),
)
follower_cache = SimpleNamespace(
runtime=runtime,
source_block_table=torch.empty(
num_decodes, 1, dtype=torch.int32, device=device
),
swap_in=MagicMock(side_effect=swap_in),
)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [leader_cache, follower_cache]
index_group.caches = [cache]
index_group.physical_topk_indices = torch.empty(
(num_tokens + 1, 4), dtype=torch.int32, device=device
)
index_group.valid_topk_counts = torch.empty(
num_tokens + 1, dtype=torch.int32, device=device
)
index_group.request_ids = torch.arange(
num_decodes, dtype=torch.int32, device=device
)
index_group.row_indices = torch.arange(num_tokens, dtype=torch.int32, device=device)
impl = SimpleNamespace(
kv_lora_rank=1,
index_group=index_group,
index_group_index=0,
)
impl._fp8_flash_mla_kernel = MethodType(run_kernel, impl)
metadata = SimpleNamespace(
num_decodes=num_tokens,
num_decode_tokens=num_tokens,
decode_max_query_len=1,
query_start_loc=torch.arange(
0,
num_tokens + 1,
query_len,
dtype=torch.int32,
device=device,
0, num_tokens + 1, query_len, dtype=torch.int32, device=device
),
block_table=torch.empty(num_decodes, 1, dtype=torch.int32, device=device),
req_id_per_token=torch.arange(
num_decodes, dtype=torch.int32, device=device
).repeat_interleave(query_len),
block_size=64,
)

output = FlashMLASparseImpl._host_backed_fp8_decode(
impl,
q,
topk,
metadata,
SimpleNamespace(),
num_decodes,
query_len,
impl, q, topk, metadata, SimpleNamespace(), num_decodes
)

assert steps == [0, 1, 2]
assert kernel_shapes == [(num_decodes, query_len, 2, 4)]
assert output.shape == (num_tokens, 2, 1)
cache.swap_in.assert_called_once()
torch.testing.assert_close(
cache.swap_in.call_args.args[0], metadata.req_id_per_token
)
torch.testing.assert_close(
index_group.physical_topk_indices[:num_tokens], topk + 10
cache.swap_in.call_args.kwargs["logical_topk_indices"], topk
)
assert kernel_shapes == [(num_decodes, query_len, 2, 4)]
assert output.shape == (num_tokens, 2, 1)

follower_indices = index_group.convert_decode_logical_to_physical_topk(
1,
topk,
metadata,
return_valid_counts=False,
num_decodes=num_decodes,
decode_query_len=query_len,

def test_hisparse_keeps_speculative_rows_as_decodes():
"""HiSparse limits decodes to verification requests, not short extends.

FlashAttn sparse MLA used to classify MTP verification as prefill under
HiSparse, whose residency-dependent route a FULL CUDA graph freezes at
capture.
"""
builder = object.__new__(FlashAttnMLASparseMetadataBuilder)
builder.vllm_config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=object()),
speculative_config=SimpleNamespace(
num_speculative_tokens=3, parallel_drafting=False
),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
use_v2_model_runner=True,
)
assert steps == [0, 1, 2, 0, 1, 2]
torch.testing.assert_close(follower_indices, topk + 10)

builder._init_reorder_batch_threshold(256, supports_spec_as_decode=True)

def test_hisparse_varlen_decode_uses_canonical_request_rows():
"""Graph metadata's query upper bound must preserve packed token rows."""
num_decodes = 2
topk = torch.arange(18, dtype=torch.int32).view(9, 2)
assert builder.reorder_batch_threshold == 4

def swap_in(_request_ids, *, logical_topk_indices, **_kwargs):
return logical_topk_indices + 10

def test_hisparse_decode_skips_padding_rows():
"""CUDA-graph padding rows map to request 0 and must not resolve against it."""
topk = torch.arange(20, dtype=torch.int32).view(10, 2)
cache = SimpleNamespace(
source_block_table=torch.zeros((num_decodes, 1), dtype=torch.int32),
swap_in=MagicMock(side_effect=swap_in),
source_block_table=torch.zeros((2, 1), dtype=torch.int32),
swap_in=MagicMock(return_value=topk),
)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [cache]
index_group.physical_topk_indices = torch.empty((10, 2), dtype=torch.int32)
index_group.valid_topk_counts = torch.empty(10, dtype=torch.int32)
index_group.request_ids = torch.arange(num_decodes, dtype=torch.int32)
index_group.physical_topk_indices = torch.empty((11, 2), dtype=torch.int32)
index_group.row_indices = torch.arange(10, dtype=torch.int32)
metadata = SimpleNamespace(
num_decodes=num_decodes,
num_decode_tokens=topk.shape[0],
decode_max_query_len=15,
query_start_loc=torch.tensor([0, 8, 9], dtype=torch.int32),
req_id_per_token=torch.tensor([0] * 8 + [1, 0], dtype=torch.int32),
block_size=64,
)

physical_topk = index_group.convert_decode_logical_to_physical_topk(
0,
topk,
metadata,
return_valid_counts=False,
index_group.convert_logical_to_physical_topk(
0, topk, metadata, block_stride_rows=None, return_valid_counts=False
)

torch.testing.assert_close(physical_topk, topk + 10)
request_rows = cache.swap_in.call_args_list[0].args[0]
torch.testing.assert_close(request_rows, index_group.request_ids)
torch.testing.assert_close(
cache.swap_in.call_args.args[0],
torch.tensor([0] * 8 + [1, -1], dtype=torch.int32),
)


def test_flashinfer_hisparse_decode_runs_batched_attention():
Expand Down Expand Up @@ -3168,7 +3210,7 @@ def run_kernel(self, q, cache, indices, counts): # noqa: ARG001
)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [cache_handle]
index_group.convert_decode_logical_to_physical_topk = MethodType(
index_group.convert_logical_to_physical_topk = MethodType(
convert_decode, index_group
)
impl = object.__new__(FlashInferMLASparseImpl)
Expand Down Expand Up @@ -3200,7 +3242,7 @@ def test_flashattn_hisparse_decode_uses_index_group():
physical = topk.clone()
counts = torch.full((num_tokens,), 4, dtype=torch.int32, device=DEVICE_TYPE)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.convert_decode_logical_to_physical_topk = MagicMock(
index_group.convert_logical_to_physical_topk = MagicMock(
return_value=(physical, counts)
)
index_group.physical_kv_cache = MagicMock(
Expand All @@ -3223,7 +3265,7 @@ def test_flashattn_hisparse_decode_uses_index_group():

assert output.shape == (num_tokens, 2, 1)
assert lse is None
index_group.convert_decode_logical_to_physical_topk.assert_called_once()
index_group.convert_logical_to_physical_topk.assert_called_once()
impl._run_mqa_kernel.assert_called_once()


Expand All @@ -3233,9 +3275,7 @@ def test_flashinfer_sm120_hisparse_decode_uses_index_group():
topk = torch.zeros(num_tokens, 4, dtype=torch.int32, device=DEVICE_TYPE)
physical = topk.clone()
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.convert_decode_logical_to_physical_topk = MagicMock(
return_value=physical
)
index_group.convert_logical_to_physical_topk = MagicMock(return_value=physical)
index_group.physical_kv_cache = MagicMock(
return_value=torch.empty(1, device=DEVICE_TYPE)
)
Expand All @@ -3259,7 +3299,7 @@ def test_flashinfer_sm120_hisparse_decode_uses_index_group():

assert output.shape == (num_tokens, 2, 1)
assert lse is None
index_group.convert_decode_logical_to_physical_topk.assert_called_once()
index_group.convert_logical_to_physical_topk.assert_called_once()
impl._run_mqa_kernel.assert_called_once()


Expand Down Expand Up @@ -3291,27 +3331,6 @@ def test_hisparse_resident_prefill_uses_attention_block_stride():
assert index_group._convert_once.call_args.kwargs["block_stride_rows"] == 832


def test_hisparse_shared_sparse_builder_routes_multi_token_chunks_to_prefill():
"""Default sparse backends must route multi-token chunks to prefill."""
builder = object.__new__(FlashInferMLASparseMetadataBuilder)
builder.vllm_config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=object()),
speculative_config=SimpleNamespace(
num_speculative_tokens=4,
parallel_drafting=False,
),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
)

builder._init_reorder_batch_threshold(
1024,
supports_spec_as_decode=True,
supports_dcp_with_varlen=True,
)

assert builder.reorder_batch_threshold == 1


def test_hisparse_flashmla_reorders_full_speculative_window_as_decode():
builder = object.__new__(FlashMLASparseMetadataBuilder)
builder.vllm_config = SimpleNamespace(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,6 @@ class SparseMLACommonMetadata(MLACommonMetadata[MLACommonDecodeMetadata]):
class SparseMLACommonMetadataBuilder(AttentionMetadataBuilder[T]):
metadata_cls: type[T]
require_uniform_decodes: ClassVar[bool] = False
hisparse_supports_multi_token_decode: ClassVar[bool] = False

def __init__(
self,
Expand Down Expand Up @@ -259,8 +258,6 @@ def _init_reorder_batch_threshold(
) -> None:
if self.vllm_config.attention_config.hisparse_config is not None:
reorder_batch_threshold = 1
if not self.hisparse_supports_multi_token_decode:
supports_spec_as_decode = False
super()._init_reorder_batch_threshold(
reorder_batch_threshold,
supports_spec_as_decode,
Expand Down
Loading
Loading