[3/N] HiSparse: host-resident sparse-MLA decode hot-buffering (#53781)

Signed-off-by: Matthew Bonanni <mbonanni@redhat.com>
Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com>
Signed-off-by: Lucas Wilkinson <lwilkinson@neuralmagic.com>
Signed-off-by: Matthew Bonanni <matthew@neuralmagic.com>
Signed-off-by: Nicolò Lucchesi <nicolo.lucchesi@mistral.ai>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com>
Co-authored-by: Lucas Wilkinson <lwilkinson@neuralmagic.com>
Co-authored-by: Nicolò Lucchesi <nicolo.lucchesi@mistral.ai>
Co-authored-by: OpenAI Codex <noreply@openai.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com>
This commit is contained in:
Matthew Bonanni
2026-09-12 00:36:47 -04:00
committed by GitHub
co-authored by OpenAI Codex Lucas Wilkinson Lucas Wilkinson Nicolò Lucchesi OpenAI Codex Claude Opus 5 Lucas Wilkinson
parent 120ec4ebd2
commit d43bb2f37f
124 changed files with 14262 additions and 906 deletions
+5
View File
@@ -22,6 +22,7 @@ if TYPE_CHECKING:
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm.model_executor.layers.quantization.utils.quant_utils import QuantKey
from vllm.platforms.interface import DeviceCapability
from vllm.v1.hisparse.runtime import HiSparseCacheHandle
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
@@ -838,6 +839,9 @@ class AttentionImplBase(ABC, Generic[T]):
def process_weights_after_loading(self, act_dtype: torch.dtype):
pass
def prepare_for_batch(self, attn_metadata: T | None) -> None:
"""Prepare implementation-specific state for the current batch."""
class AttentionImpl(AttentionImplBase[T], Generic[T]):
"""Standard attention implementation with forward method."""
@@ -956,6 +960,7 @@ class AttentionImpl(AttentionImplBase[T], Generic[T]):
class MLAAttentionImpl(AttentionImplBase[T], Generic[T]):
"""MLA attention implementation with forward_mqa and forward_mha methods."""
hisparse_cache: "HiSparseCacheHandle | None" = None
supports_pcp: bool = True
@abstractmethod
@@ -8,9 +8,9 @@ import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.model_executor.layers.attention.mla_attention import MLACommonPrefillMetadata
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonImpl,
SparseMLACommonMetadata,
SparseMLACommonMetadataBuilder,
)
from vllm.platforms.interface import DeviceCapability
@@ -18,11 +18,11 @@ from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionLayer,
AttentionMetadata,
MLAAttentionImpl,
MultipleOf,
)
from vllm.v1.attention.backends.fa_utils import flash_attn_supports_mla
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
triton_convert_req_index_to_global_index,
@@ -106,26 +106,8 @@ class FlashAttnMLASparseBackend(AttentionBackend):
@dataclass
class FlashAttnMLASparseMetadata(AttentionMetadata):
num_reqs: int
max_query_len: int
max_seq_len: int
num_actual_tokens: int
query_start_loc: torch.Tensor
slot_mapping: torch.Tensor
block_table: torch.Tensor
req_id_per_token: torch.Tensor
seq_lens: torch.Tensor
block_size: int = 64
topk_tokens: int = 2048
num_decodes: int = 0
num_prefills: int = 0
num_decode_tokens: int = 0
prefill_max_seq_len: int = 0
prefill: MLACommonPrefillMetadata | None = None
cp_kv_cache_interleave_size: int = 1
class FlashAttnMLASparseMetadata(SparseMLACommonMetadata):
pass
class FlashAttnMLASparseMetadataBuilder(
@@ -214,6 +196,76 @@ class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[:num_actual_toks]
index_group = self.index_group
if isinstance(index_group, HiSparseMLAIndexGroup):
num_decode_tokens = attn_metadata.num_decode_tokens
outputs = []
if num_decode_tokens:
physical_topk, valid_counts = (
index_group.convert_decode_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
return_valid_counts=True,
)
)
outputs.append(
self._run_mqa_kernel(
q_nope[:num_decode_tokens],
q_rope[:num_decode_tokens],
index_group.physical_kv_cache(self.index_group_index).view(
kv_c_and_k_pe_cache.dtype
),
physical_topk,
valid_counts,
attn_metadata.block_size,
)
)
if num_decode_tokens < num_actual_toks:
cache = index_group.cache(self.index_group_index)
if num_decode_tokens == 0 and cache.all_context_pages_resident:
physical_topk, valid_counts = (
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
)
prefill_cache = index_group.physical_kv_cache(
self.index_group_index
).view(kv_c_and_k_pe_cache.dtype)
else:
prefill_cache, block_table, req_ids = (
index_group.stage_prefill_rows(
self.index_group_index,
kv_c_and_k_pe_cache,
attn_metadata,
)
)
physical_topk, valid_counts = (
triton_convert_req_index_to_global_index(
req_ids,
block_table,
topk_indices[num_decode_tokens:],
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
)
outputs.append(
self._run_mqa_kernel(
q_nope[num_decode_tokens:],
q_rope[num_decode_tokens:],
prefill_cache,
physical_topk,
valid_counts,
attn_metadata.block_size,
)
)
return torch.cat(outputs) if len(outputs) > 1 else outputs[0], None
kv_rows, block_stride_rows = flat_kv_row_view(
kv_c_and_k_pe_cache, attn_metadata.block_size
)
@@ -226,9 +278,36 @@ class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
return (
self._run_mqa_kernel(
q_nope,
q_rope,
kv_rows,
topk_indices,
valid_counts,
attn_metadata.block_size,
cache_is_flat=True,
),
None,
)
def _run_mqa_kernel(
self,
q_nope: torch.Tensor,
q_rope: torch.Tensor,
kv_cache: torch.Tensor,
topk_indices: torch.Tensor,
valid_counts: torch.Tensor,
block_size: int,
*,
cache_is_flat: bool = False,
) -> torch.Tensor:
kv_rows = (
kv_cache if cache_is_flat else flat_kv_row_view(kv_cache, block_size)[0]
)
cu_seqlens_q = torch.arange(
0, num_actual_toks + 1, dtype=torch.int32, device=q_rope.device
0, q_rope.shape[0] + 1, dtype=torch.int32, device=q_rope.device
)
k_cache = kv_rows[:, self.kv_lora_rank :].unsqueeze(1).unsqueeze(1)
v_cache = kv_rows[:, : self.kv_lora_rank].unsqueeze(1).unsqueeze(1)
@@ -247,4 +326,4 @@ class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
causal=True,
fa_version=3,
)
return out, None
return out
@@ -11,22 +11,23 @@ from vllm import envs
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import MLACommonPrefillMetadata
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonImpl,
SparseMLACommonMetadata,
SparseMLACommonMetadataBuilder,
)
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionLayer,
AttentionMetadata,
AttentionType,
MLAAttentionImpl,
MultipleOf,
)
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
triton_convert_req_index_to_global_index,
@@ -224,33 +225,9 @@ class FlashInferMLASparseSM120Backend(_FlashInferMLASparseBackendBase):
@dataclass
class FlashInferMLASparseMetadata(AttentionMetadata):
class FlashInferMLASparseMetadata(SparseMLACommonMetadata):
"""Attention metadata for FlashInfer MLA Sparse backend."""
num_reqs: int
max_query_len: int
max_seq_len: int
num_actual_tokens: int
# Query start locations
query_start_loc: torch.Tensor
slot_mapping: torch.Tensor
block_table: torch.Tensor
req_id_per_token: torch.Tensor
# Sequence lengths for all requests (context + query)
seq_lens: torch.Tensor
num_decodes: int
num_prefills: int
num_decode_tokens: int
prefill_max_seq_len: int = 0
prefill: MLACommonPrefillMetadata | None = None
# Sparse-specific
block_size: int = 64
topk_tokens: int = 2048
cp_kv_cache_interleave_size: int = 1
class FlashInferMLASparseMetadataBuilder(
SparseMLACommonMetadataBuilder[FlashInferMLASparseMetadata]
@@ -286,6 +263,7 @@ class FlashInferMLASparseTRTLLMMetadataBuilder(FlashInferMLASparseMetadataBuilde
"""Metadata builder for the SM100 TRT-LLM sparse MLA kernel."""
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
hisparse_supports_multi_token_decode: ClassVar[bool] = True
def _build_req_id_per_token(
self,
@@ -402,6 +380,78 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[:num_actual_toks]
self._prepare_mqa_kernel(layer, q.device)
index_group = self.index_group
if isinstance(index_group, HiSparseMLAIndexGroup):
num_decode_tokens = attn_metadata.num_decode_tokens
decode_out: torch.Tensor | None = None
decode_lse: torch.Tensor | None = None
if num_decode_tokens > 0:
physical_topk, valid_counts = (
index_group.convert_decode_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
return_valid_counts=True,
)
)
decode_out, decode_lse = self._run_mqa_kernel(
q[:num_decode_tokens],
index_group.physical_kv_cache(self.index_group_index).view(
kv_c_and_k_pe_cache.dtype
),
physical_topk,
valid_counts,
)
if num_decode_tokens == num_actual_toks:
return decode_out, decode_lse
cache = index_group.cache(self.index_group_index)
if num_decode_tokens == 0 and cache.all_context_pages_resident:
physical_topk, valid_counts = (
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
)
return self._run_mqa_kernel(
q,
index_group.physical_kv_cache(self.index_group_index).view(
kv_c_and_k_pe_cache.dtype
),
physical_topk,
valid_counts,
)
prefill_cache, block_table, req_ids = index_group.stage_prefill_rows(
self.index_group_index, kv_c_and_k_pe_cache, attn_metadata
)
prefill_indices, prefill_lens = triton_convert_req_index_to_global_index(
req_ids,
block_table,
topk_indices[num_decode_tokens:],
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
prefill_out, prefill_lse = self._run_mqa_kernel(
q[num_decode_tokens:],
prefill_cache,
prefill_indices,
prefill_lens,
)
if decode_out is None:
return prefill_out, prefill_lse
output = torch.cat((decode_out, prefill_out))
if decode_lse is None:
return output, None
assert prefill_lse is not None
return output, torch.cat((decode_lse, prefill_lse))
_, block_stride_rows = flat_kv_row_view(
kv_c_and_k_pe_cache, attn_metadata.block_size
)
@@ -420,18 +470,27 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
return_valid_counts=True,
)
else:
topk_indices_physical, seq_lens = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[:num_actual_toks],
attn_metadata.block_table,
topk_indices_physical, seq_lens = self._convert_logical_to_physical_topk(
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=topk_indices.shape[1],
attn_metadata,
block_stride_rows=block_stride_rows,
return_valid_counts=True,
)
return self._run_mqa_kernel(
q,
kv_c_and_k_pe_cache,
topk_indices_physical,
seq_lens,
)
def _prepare_mqa_kernel(
self,
layer: AttentionLayer,
device: torch.device,
) -> None:
if self._workspace_buffer is None:
self._workspace_buffer = _get_workspace_buffer(q.device)
self._workspace_buffer = _get_workspace_buffer(device)
if self.bmm1_scale is None:
self.bmm1_scale = self.scale
@@ -442,15 +501,71 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
if is_quantized_kv_cache(self.kv_cache_dtype):
self.bmm2_scale *= layer._k_scale_float
def autotune_hisparse_decode(self, layer: AttentionLayer) -> None:
"""Autotune the largest legal HiSparse decode batch."""
assert isinstance(self.index_group, HiSparseMLAIndexGroup)
cache = self.index_group.cache(self.index_group_index)
assert self.topk_indices_buffer is not None
runtime = cache.runtime
kv_cache = runtime.hot.attention_cache
num_tokens = runtime.max_num_reqs
topk_tokens = self.topk_indices_buffer.shape[1]
self._prepare_mqa_kernel(layer, kv_cache.device)
q_dtype = (
current_platform.fp8_dtype()
if is_quantized_kv_cache(self.kv_cache_dtype)
else kv_cache.dtype
)
q = torch.zeros(
(
num_tokens,
self.num_heads,
self.kv_lora_rank + self.qk_rope_head_dim,
),
dtype=q_dtype,
device=kv_cache.device,
)
topk_indices = (
torch.arange(
topk_tokens,
dtype=torch.int32,
device=kv_cache.device,
)
.expand(num_tokens, -1)
.contiguous()
)
seq_lens = torch.full(
(num_tokens,),
topk_tokens,
dtype=torch.int32,
device=kv_cache.device,
)
self._run_mqa_kernel(q, kv_cache, topk_indices, seq_lens)
def _run_mqa_kernel(
self,
q: torch.Tensor,
kv_cache: torch.Tensor,
topk_indices: torch.Tensor,
seq_lens: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor | None]:
assert self._workspace_buffer is not None
assert self.bmm1_scale is not None
assert self.bmm2_scale is not None
from flashinfer.decode import trtllm_batch_decode_with_kv_cache_mla
kv_cache = kv_cache.view(q.dtype)
# Single-token sparse decode. trtllm-gen requires the q_len_per_request
# dim, but the sparse attention mask is fully per-token (each query token
# carries its own top-k index row), so unsqueeze is sufficient and
# correct. The MTP/multi-token q_len grouping is a perf-only layout and is
# deferred until MTP is validated end-to-end for this backend.
query = q.unsqueeze(1)
block_tables = topk_indices_physical.unsqueeze(1)
block_tables = topk_indices.unsqueeze(1)
seq_lens_arg = seq_lens
# page_table width = topk buffer width, which kpool widens past
@@ -460,7 +575,7 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
# count), so the -1 padding slots past seq_lens are never attended to.
# Use the actual buffer width instead of the fixed topk_tokens, which
# mismatches the page_table when index_kpool > 1.
sparse_topk_capacity = topk_indices_physical.shape[1]
sparse_topk_capacity = topk_indices.shape[1]
extra_kwargs: dict[str, torch.Tensor] = {}
empty_rows: torch.Tensor | None = None
@@ -473,14 +588,12 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
# valid indices into a contiguous prefix, which is what the kernel
# requires of the page table.
empty_rows = seq_lens == 0
topk_indices_physical[:, 0] = topk_indices_physical[:, 0].masked_fill(
empty_rows, 0
)
topk_indices[:, 0] = topk_indices[:, 0].masked_fill(empty_rows, 0)
extra_kwargs["sparse_mla_top_k_lens"] = seq_lens.clamp(min=1)
kernel_out = trtllm_batch_decode_with_kv_cache_mla(
query=query,
kv_cache=kv_c_and_k_pe_cache.unsqueeze(1),
kv_cache=kv_cache.unsqueeze(1),
workspace_buffer=self._workspace_buffer,
qk_nope_head_dim=self.qk_nope_head_dim,
kv_lora_rank=self.kv_lora_rank,
@@ -506,7 +619,7 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
if lse is not None:
lse = self._normalize_lse(lse, out.shape[0], out.shape[1])
if empty_rows is None and lse is not None:
empty_rows = (topk_indices_physical == -1).all(dim=-1)
empty_rows = (topk_indices == -1).all(dim=-1)
if empty_rows is not None:
out.masked_fill_(empty_rows.view(-1, 1, 1), 0.0)
if lse is not None:
@@ -7,17 +7,14 @@ from typing import TYPE_CHECKING, cast
import torch
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SharedTopkIndicesBuffer,
)
from vllm.v1.attention.backend import (
AttentionLayer,
AttentionType,
MLAAttentionImpl,
SparseMLACommonImpl,
)
from vllm.v1.attention.backend import AttentionLayer, AttentionType
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseMetadata,
_get_workspace_buffer,
)
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
from vllm.v1.attention.backends.mla.sparse_utils import (
triton_convert_req_index_to_global_index,
)
@@ -32,9 +29,7 @@ def _kv_scale_format_for_model(model_type: str | None) -> str:
return "pow2_fp32"
class FlashInferMLASparseSM120Impl(
MLAAttentionImpl[FlashInferMLASparseMetadata], SharedTopkIndicesBuffer
):
class FlashInferMLASparseSM120Impl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
"""SM120 FlashInfer sparse-MLA implementation."""
is_sparse = True
@@ -65,20 +60,28 @@ class FlashInferMLASparseSM120Impl(
"FLASHINFER_MLA_SPARSE_SM120 only supports decoder self-attention"
)
self.num_heads = num_heads
self.head_size = head_size
self.scale = float(scale)
self.num_kv_heads = num_kv_heads
self.kv_cache_dtype = kv_cache_dtype
if self.kv_cache_dtype != "fp8_ds_mla":
if kv_cache_dtype != "fp8_ds_mla":
raise NotImplementedError(
"FLASHINFER_MLA_SPARSE_SM120 requires the packed fp8_ds_mla "
f"KV cache layout; got kv_cache_dtype={kv_cache_dtype!r}."
)
self.kv_lora_rank: int = mla_args["kv_lora_rank"]
self.qk_nope_head_dim: int = mla_args["qk_nope_head_dim"]
self.qk_rope_head_dim: int = mla_args["qk_rope_head_dim"]
topk_indices_buffer = mla_args.pop("topk_indices_buffer", None)
super().__init__(
num_heads,
head_size,
scale,
num_kv_heads,
alibi_slopes,
sliding_window,
kv_cache_dtype,
logits_soft_cap,
attn_type,
kv_sharing_target_layer_name,
indexer=indexer,
topk_indices_buffer=topk_indices_buffer,
**mla_args,
)
from vllm.config import get_current_vllm_config
vllm_config = get_current_vllm_config()
@@ -89,9 +92,6 @@ class FlashInferMLASparseSM120Impl(
)
self.kv_scale_format = _kv_scale_format_for_model(model_type)
# Skip-topk layers are built with indexer=None and get the shared
# buffer via mla_args instead (cf. FLASHMLA_SPARSE).
self.init_topk_indices_buffer(indexer, mla_args.get("topk_indices_buffer"))
from vllm.utils.flashinfer import has_flashinfer_sparse_mla_sm120
if not has_flashinfer_sparse_mla_sm120():
@@ -118,6 +118,70 @@ class FlashInferMLASparseSM120Impl(
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[:num_actual_toks]
index_group = self.index_group
if isinstance(index_group, HiSparseMLAIndexGroup):
num_decode_tokens = attn_metadata.num_decode_tokens
outputs = []
if num_decode_tokens:
topk_indices_physical = cast(
torch.Tensor,
index_group.convert_decode_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
return_valid_counts=False,
),
)
outputs.append(
self._run_mqa_kernel(
q[:num_decode_tokens],
index_group.physical_kv_cache(self.index_group_index),
topk_indices_physical,
)
)
if num_decode_tokens < num_actual_toks:
cache = index_group.cache(self.index_group_index)
if num_decode_tokens == 0 and cache.all_context_pages_resident:
topk_indices_physical = cast(
torch.Tensor,
index_group.convert_logical_to_physical_topk(
self.index_group_index,
topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=False,
),
)
prefill_cache = index_group.physical_kv_cache(
self.index_group_index
)
else:
prefill_cache, block_table, req_ids = (
index_group.stage_prefill_rows(
self.index_group_index,
kv_c_and_k_pe_cache,
attn_metadata,
)
)
topk_indices_physical = cast(
torch.Tensor,
triton_convert_req_index_to_global_index(
req_ids,
block_table,
topk_indices[num_decode_tokens:],
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
),
)
outputs.append(
self._run_mqa_kernel(
q[num_decode_tokens:],
prefill_cache,
topk_indices_physical,
)
)
output = torch.cat(outputs) if len(outputs) > 1 else outputs[0]
return output, None
topk_indices_physical = cast(
torch.Tensor,
@@ -129,6 +193,22 @@ class FlashInferMLASparseSM120Impl(
NUM_TOPK_TOKENS=topk_indices.shape[1],
),
)
return (
self._run_mqa_kernel(
q,
kv_c_and_k_pe_cache,
topk_indices_physical,
),
None,
)
def _run_mqa_kernel(
self,
q: torch.Tensor,
kv_cache: torch.Tensor,
topk_indices_physical: torch.Tensor,
) -> torch.Tensor:
num_actual_toks = q.shape[0]
output = q.new_empty(
(num_actual_toks, self.num_heads, self.kv_lora_rank),
@@ -142,20 +222,21 @@ class FlashInferMLASparseSM120Impl(
flashinfer_trtllm_batch_decode_with_kv_cache_mla,
)
sparse_capacity = topk_indices_physical.shape[1]
out = flashinfer_trtllm_batch_decode_with_kv_cache_mla(
query=q.unsqueeze(1),
kv_cache=kv_c_and_k_pe_cache.view(torch.uint8).unsqueeze(1),
kv_cache=kv_cache.view(torch.uint8).unsqueeze(1),
workspace_buffer=self._workspace_buffer,
qk_nope_head_dim=self.qk_nope_head_dim,
kv_lora_rank=self.kv_lora_rank,
qk_rope_head_dim=self.qk_rope_head_dim,
block_tables=topk_indices_physical.unsqueeze(1),
seq_lens=None,
max_seq_len=attn_metadata.topk_tokens,
max_seq_len=sparse_capacity,
out=output.unsqueeze(1),
bmm1_scale=self.scale,
bmm2_scale=1.0,
sparse_mla_top_k=attn_metadata.topk_tokens,
sparse_mla_top_k=sparse_capacity,
kv_scale_format=self.kv_scale_format,
)
return out.squeeze(1), None
return out.squeeze(1)
+225 -91
View File
@@ -9,23 +9,23 @@ from vllm import _custom_ops as ops
from vllm.config import VllmConfig, get_current_vllm_config
from vllm.config.cache import CacheDType
from vllm.logger import init_logger
from vllm.model_executor.layers.attention.mla_attention import MLACommonPrefillMetadata
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonImpl,
SparseMLACommonMetadata,
SparseMLACommonMetadataBuilder,
)
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.platform_utils import num_compute_units
from vllm.utils.torch_utils import is_quantized_kv_cache
from vllm.utils.torch_utils import current_stream, is_quantized_kv_cache
from vllm.v1.attention.backend import (
AttentionBackend,
AttentionCGSupport,
AttentionLayer,
AttentionMetadata,
CommonAttentionMetadata,
MultipleOf,
)
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
from vllm.v1.attention.backends.mla.sparse_utils import (
flat_kv_row_view,
triton_convert_req_index_to_global_index,
@@ -172,28 +172,7 @@ class FlashMLASparseBackend(AttentionBackend):
@dataclass
class FlashMLASparseMetadata(AttentionMetadata):
num_reqs: int
max_query_len: int
max_seq_len: int
num_actual_tokens: int # Number of tokens excluding padding.
query_start_loc: torch.Tensor
slot_mapping: torch.Tensor
block_table: torch.Tensor
req_id_per_token: torch.Tensor
block_size: int = 64
topk_tokens: int = 2048
num_decodes: int = 0
num_prefills: int = 0
num_decode_tokens: int = 0
seq_lens: torch.Tensor | None = None
prefill_max_seq_len: int = 0
prefill: MLACommonPrefillMetadata | None = None
cp_kv_cache_interleave_size: int = 1
class FlashMLASparseMetadata(SparseMLACommonMetadata):
@dataclass
class FP8KernelMetadata:
scheduler_metadata: FlashMLASchedMeta
@@ -233,6 +212,7 @@ class FlashMLASparseMetadata(AttentionMetadata):
req_start_idx: int
workspace_starts: torch.Tensor
chunk_tot_seqlen: int
seq_lens: torch.Tensor | None = None
chunks: list[Chunk]
@@ -263,6 +243,7 @@ class FlashMLASparseMetadataBuilder(
):
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
require_uniform_decodes: ClassVar[bool] = True
hisparse_supports_multi_token_decode: ClassVar[bool] = True
metadata_cls = FlashMLASparseMetadata
def __init__(
@@ -283,6 +264,9 @@ class FlashMLASparseMetadataBuilder(
)
else:
threshold = {16: 128, 32: 128, 64: 256, 128: 256}.get(num_q_heads, 256)
self.use_hisparse = vllm_config.attention_config.hisparse_config is not None
if self.use_hisparse:
threshold = 1
# Varlen decodes are safe under DCP: causality comes from the
# indexer's top-k indices, not from the kernel metadata.
self._init_reorder_batch_threshold(
@@ -347,7 +331,9 @@ class FlashMLASparseMetadataBuilder(
device=device,
)
self.fp8_use_mixed_batch = self.num_heads < MIN_HEADS_FOR_BF16_PREFILL
self.fp8_use_mixed_batch = (
self.num_heads < MIN_HEADS_FOR_BF16_PREFILL and not self.use_hisparse
)
if parallel_config.decode_context_parallel_size > 1:
if parallel_config.dcp_comm_backend != "ag_rs":
@@ -385,37 +371,21 @@ class FlashMLASparseMetadataBuilder(
def _build_fp8_mixed_decode_prefill(
self,
common_attn_metadata: CommonAttentionMetadata,
) -> "FlashMLASparseMetadata.FP8KernelMetadata":
) -> FlashMLASparseMetadata.FP8KernelMetadata:
"""Build FP8 metadata treating MQA tokens as one batch.
The scheduler initializes lazily from the runtime query shape, which may
be the full batch or only decodes when prefills use dense MHA. This avoids
the BF16 prefill kernel's head-padding overhead at high TP.
"""
num_tokens = common_attn_metadata.num_actual_tokens
# Use padded head count since that's what the kernel will see
padded_heads = self.fp8_decode_padded_heads
# Build metadata for all tokens as a single batch
scheduler_metadata, _ = get_mla_metadata(
cache_seqlens=self.topk_tokens_tensor[:1], # Single batch
num_q_tokens_per_head_k=num_tokens * padded_heads,
topk=self.topk_tokens,
num_heads_q=padded_heads,
num_heads_k=1,
is_fp8_kvcache=True,
)
fp8_metadata = FlashMLASparseMetadata.FP8KernelMetadata(
scheduler_metadata, _ = get_mla_metadata()
return FlashMLASparseMetadata.FP8KernelMetadata(
scheduler_metadata=scheduler_metadata,
cache_lens=self.max_model_len_tensor[:1],
dummy_block_table=self.dummy_block_table[:1],
)
return fp8_metadata
def _build_fp8_separate_prefill_decode(
self,
common_attn_metadata: CommonAttentionMetadata,
@@ -520,6 +490,9 @@ class FlashMLASparseMetadataBuilder(
chunk_block_table = common_attn_metadata.block_table_tensor[
num_decodes + chunk_start : num_decodes + chunk_end
]
chunk_seq_lens = common_attn_metadata.seq_lens[
num_decodes + chunk_start : num_decodes + chunk_end
]
prefill_chunks.append(
FP8Meta.Prefill.Chunk(
@@ -528,6 +501,7 @@ class FlashMLASparseMetadataBuilder(
req_start_idx=chunk_start,
workspace_starts=chunk_workspace_starts,
chunk_tot_seqlen=chunk_tot_seqlen,
seq_lens=chunk_seq_lens,
)
)
@@ -569,9 +543,7 @@ class FlashMLASparseMetadataBuilder(
metadata.fp8_use_mixed_batch = self.fp8_use_mixed_batch
if self.use_fp8_kv_cache:
if self.fp8_use_mixed_batch:
metadata.fp8_extra_metadata = self._build_fp8_mixed_decode_prefill(
common_attn_metadata
)
metadata.fp8_extra_metadata = self._build_fp8_mixed_decode_prefill()
else:
metadata.fp8_extra_metadata = self._build_fp8_separate_prefill_decode(
common_attn_metadata, metadata
@@ -679,30 +651,83 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
topk_indices: torch.Tensor,
attn_metadata: FlashMLASparseMetadata,
actual_num_heads: int,
) -> tuple[torch.Tensor, torch.Tensor]:
# Convert per-request indices to global slots (decode) or workspace
# offsets (prefill). req_id_per_token covers the whole batch; slice it
# to the MQA tokens (q may exclude prefill tokens routed to dense MHA).
) -> tuple[torch.Tensor, torch.Tensor | None]:
index_group = self.index_group
if isinstance(index_group, HiSparseMLAIndexGroup):
cache = index_group.cache(self.index_group_index)
else:
cache = None
block_table = attn_metadata.block_table
# req_id_per_token covers the whole batch; slice it to the MQA tokens
# (q may exclude prefill tokens routed to dense MHA).
req_id_per_token = attn_metadata.req_id_per_token[: topk_indices.shape[0]]
decode_out: torch.Tensor | None = None
if cache is not None:
assert isinstance(index_group, HiSparseMLAIndexGroup)
num_decode_tokens = attn_metadata.num_decode_tokens
if num_decode_tokens > 0:
decode_topk, decode_lengths = (
index_group.convert_decode_logical_to_physical_topk(
self.index_group_index,
topk_indices[:num_decode_tokens],
attn_metadata,
return_valid_counts=True,
)
)
decode_out, _ = self._bf16_flash_mla_kernel(
q[:num_decode_tokens],
index_group.physical_kv_cache(self.index_group_index),
decode_topk,
decode_lengths,
actual_num_heads,
)
if num_decode_tokens == q.shape[0]:
return decode_out, None
q = q[num_decode_tokens:]
topk_indices = topk_indices[num_decode_tokens:]
kv_c_and_k_pe_cache, block_table, req_id_per_token = (
index_group.stage_prefill_rows(
self.index_group_index, kv_c_and_k_pe_cache, attn_metadata
)
)
# Convert per-request indices to global slots (decode) or workspace offsets.
kv_rows, block_stride_rows = flat_kv_row_view(
kv_c_and_k_pe_cache, attn_metadata.block_size
)
topk_indices, topk_length = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
decode_only = (
attn_metadata.num_decode_tokens
== attn_metadata.num_actual_tokens
== topk_indices.shape[0]
)
uses_host_cache = isinstance(index_group, HiSparseMLAIndexGroup)
if not uses_host_cache and decode_only:
topk_indices, topk_length = self._convert_logical_to_physical_topk(
topk_indices,
attn_metadata,
block_stride_rows=block_stride_rows,
return_valid_counts=True,
)
else:
topk_indices, topk_length = triton_convert_req_index_to_global_index(
req_id_per_token,
block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=topk_indices.shape[1],
return_valid_counts=True,
)
return self._bf16_flash_mla_kernel(
attn_out, lse = self._bf16_flash_mla_kernel(
q,
kv_rows,
topk_indices,
topk_length,
actual_num_heads,
)
if decode_out is None:
return attn_out, lse
return torch.cat([decode_out, attn_out], dim=0), None
def _forward_fp8_kv_separate_prefill_decode(
self,
@@ -721,6 +746,28 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
"FP8 sparse MLA expects either the decode subset or the full batch"
)
decode_topk: torch.Tensor | None = None
index_group = self.index_group
uses_host_cache = isinstance(index_group, HiSparseMLAIndexGroup)
if uses_host_cache and num_decode_tokens > 0:
decode_topk = topk_indices[:num_decode_tokens]
prefill_ready = None
if num_prefill_tokens > 0 and uses_host_cache:
assert fp8_metadata.prefill is not None
first_chunk = fp8_metadata.prefill.chunks[0]
assert isinstance(index_group, HiSparseMLAIndexGroup)
prefill_ready = index_group.gather_fp8_prefill(
self.index_group_index,
kv_c_and_k_pe_cache,
self.prefill_bf16_workspace[: first_chunk.chunk_tot_seqlen],
first_chunk.block_table,
first_chunk.workspace_starts,
len(first_chunk.block_table),
attn_metadata,
first_chunk.req_start_idx,
)
prefill_request_ids = None
prefill_workspace_starts = None
has_prefill_workspace = False
@@ -736,17 +783,26 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
# For BF16 cache: always use global cache slots (no workspace)
# prefill_workspace_starts has been adjusted in-place per chunk so
# prefill indices automatically come out chunk-local
topk_indices, topk_length = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
HAS_PREFILL_WORKSPACE=has_prefill_workspace,
prefill_workspace_request_ids=prefill_request_ids,
prefill_workspace_starts=prefill_workspace_starts,
return_valid_counts=True,
)
topk_length = None
if num_prefill_tokens == 0 and not uses_host_cache:
topk_indices, topk_length = self._convert_logical_to_physical_topk(
topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=True,
)
elif num_prefill_tokens > 0:
topk_indices, topk_length = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
HAS_PREFILL_WORKSPACE=has_prefill_workspace,
prefill_workspace_request_ids=prefill_request_ids,
prefill_workspace_starts=prefill_workspace_starts,
return_valid_counts=True,
)
fp8_metadata = attn_metadata.fp8_extra_metadata
assert isinstance(fp8_metadata, FlashMLASparseMetadata.FP8SeparatePrefillDecode)
@@ -755,6 +811,16 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
q: torch.Tensor,
topk_indices: torch.Tensor,
) -> torch.Tensor:
assert fp8_metadata.decode is not None
if uses_host_cache:
return self._host_backed_fp8_decode(
q,
topk_indices,
attn_metadata,
fp8_metadata.decode.kernel_metadata,
num_decodes,
fp8_metadata.decode.decode_query_len,
)
# Reshape q: (num_decode_tokens, num_heads, head_dim)
# -> (num_decodes, seq_len, num_heads, head_dim)
q = reshape_query_for_spec_decode(q, num_decodes)
@@ -762,7 +828,6 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
# Reshape topk_indices: (num_decode_tokens, topk)
# -> (num_decodes, seq_len, topk)
topk_indices = topk_indices.view(num_decodes, seq_len, -1)
assert fp8_metadata.decode is not None
attn_out, _ = self._fp8_flash_mla_kernel(
q=q,
kv_c_and_k_pe_cache=kv_c_and_k_pe_cache,
@@ -776,7 +841,9 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
# Pure decode: direct call without allocation
if num_decode_tokens > 0 and num_prefill_tokens == 0:
assert fp8_metadata.decode is not None
attn_out = _fp8_decode(q, topk_indices)
attn_out = _fp8_decode(
q, decode_topk if decode_topk is not None else topk_indices
)
else:
# Mixed or pure prefill: allocate output tensor
attn_out = q.new_empty(
@@ -788,13 +855,30 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
if num_decode_tokens > 0:
attn_out[:num_decode_tokens] = _fp8_decode(
q[:num_decode_tokens],
topk_indices[:num_decode_tokens],
decode_topk
if decode_topk is not None
else topk_indices[:num_decode_tokens],
)
assert fp8_metadata.prefill is not None
for chunk in fp8_metadata.prefill.chunks:
for chunk_index, chunk in enumerate(fp8_metadata.prefill.chunks):
chunk_workspace = self.prefill_bf16_workspace[: chunk.chunk_tot_seqlen]
if self.kv_cache_dtype == "fp8_ds_mla":
if uses_host_cache and chunk_index > 0:
assert isinstance(index_group, HiSparseMLAIndexGroup)
prefill_ready = index_group.gather_fp8_prefill(
self.index_group_index,
kv_c_and_k_pe_cache,
chunk_workspace,
chunk.block_table,
chunk.workspace_starts,
len(chunk.block_table),
attn_metadata,
chunk.req_start_idx,
)
if uses_host_cache:
assert prefill_ready is not None
current_stream().wait_event(prefill_ready)
elif self.kv_cache_dtype == "fp8_ds_mla":
ops.cp_gather_and_upconvert_fp8_kv_cache(
kv_c_and_k_pe_cache,
chunk_workspace,
@@ -813,6 +897,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
chunk_q = q[chunk.tokens_slice]
chunk_topk_indices_workspace = topk_indices[chunk.tokens_slice]
assert topk_length is not None
chunk_topk_length = topk_length[chunk.tokens_slice]
attn_out[chunk.tokens_slice], _ = self._bf16_flash_mla_kernel(
@@ -839,6 +924,17 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
The lse is only returned when DCP needs it, otherwise None.
"""
assert attn_metadata.fp8_extra_metadata is not None
assert isinstance(
attn_metadata.fp8_extra_metadata,
FlashMLASparseMetadata.FP8KernelMetadata,
)
fp8_metadata = attn_metadata.fp8_extra_metadata
block_table = attn_metadata.block_table
# req_id_per_token covers the whole batch; slice it to the MQA tokens
# (q may exclude prefill tokens routed to dense MHA).
req_id_per_token = attn_metadata.req_id_per_token[: topk_indices.shape[0]]
if self.dcp_world_size > 1:
# The indexer emits global token ids; keep this rank's shard and
# convert to local slots. compact_valid_to_front=False keeps the
@@ -846,8 +942,8 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
# empty-row neutralization below relies on. req_id is sliced to
# topk_indices rows (the converter grids from req_id).
topk_indices = triton_filter_and_convert_dcp_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
req_id_per_token,
block_table,
topk_indices,
dcp_size=self.dcp_world_size,
dcp_rank=self.dcp_rank,
@@ -859,19 +955,26 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
else:
# Convert per-request indices to global slots (decode) or workspace
# offsets (prefill).
topk_indices = triton_convert_req_index_to_global_index(
attn_metadata.req_id_per_token[: topk_indices.shape[0]],
attn_metadata.block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
decode_only = (
attn_metadata.num_decode_tokens
== attn_metadata.num_actual_tokens
== topk_indices.shape[0]
)
assert attn_metadata.fp8_extra_metadata is not None
assert isinstance(
attn_metadata.fp8_extra_metadata, FlashMLASparseMetadata.FP8KernelMetadata
)
fp8_metadata = attn_metadata.fp8_extra_metadata
if decode_only:
topk_indices = self._convert_logical_to_physical_topk(
topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=False,
)
else:
topk_indices = triton_convert_req_index_to_global_index(
req_id_per_token,
block_table,
topk_indices,
BLOCK_SIZE=attn_metadata.block_size,
NUM_TOPK_TOKENS=topk_indices.shape[1],
)
_attn_out, _lse = self._fp8_flash_mla_kernel(
q=q.unsqueeze(0), # unsqueeze to add batch_dim: (T, H, D) -> (1, T, H, D)
@@ -937,6 +1040,37 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
return out, lse
def _host_backed_fp8_decode(
self,
q: torch.Tensor,
topk_indices: torch.Tensor,
attn_metadata: FlashMLASparseMetadata,
kernel_metadata: FlashMLASparseMetadata.FP8KernelMetadata,
num_decodes: int,
decode_query_len: int,
) -> torch.Tensor:
assert isinstance(self.index_group, HiSparseMLAIndexGroup)
physical_topk = self.index_group.convert_decode_logical_to_physical_topk(
self.index_group_index,
topk_indices,
attn_metadata,
return_valid_counts=False,
num_decodes=num_decodes,
decode_query_len=decode_query_len,
)
assert isinstance(physical_topk, torch.Tensor)
q = reshape_query_for_spec_decode(q, num_decodes)
physical_topk = physical_topk.view(num_decodes, q.shape[1], -1)
output, _ = self._fp8_flash_mla_kernel(
q=q,
kv_c_and_k_pe_cache=self.index_group.physical_kv_cache(
self.index_group_index
),
topk_indices=physical_topk,
kernel_metadata=kernel_metadata,
)
return reshape_attn_output_for_spec_decode(output)
def _bf16_flash_mla_kernel(
self,
q: torch.Tensor,
@@ -0,0 +1,503 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any
import torch
from vllm import _custom_ops as ops
from vllm.config import VllmConfig
from vllm.utils.torch_utils import current_stream
from vllm.v1.attention.backends.mla.sparse_utils import (
triton_convert_req_index_to_global_index,
)
from vllm.v1.hisparse.runtime import (
FP8_DS_MLA_ROW_BYTES,
HiSparseCacheHandle,
HiSparsePrefillStagingPlan,
create_hisparse_cache_handle,
)
def _create_side_stream(device: torch.device) -> torch.Stream:
return torch.Stream(device=device)
def _create_event() -> torch.Event:
return torch.Event()
@dataclass
class SparseMLAIndexGroup:
"""Layers that consume one sparse-indexer result."""
logical_topk_indices: torch.Tensor
physical_topk_indices: torch.Tensor
valid_topk_counts: torch.Tensor
request_ids: torch.Tensor
side_stream: torch.Stream
logical_topk_ready: torch.Event
physical_topk_ready: torch.Event
has_indexer: bool
num_layers: int = 0
def register_layer(
self,
vllm_config: VllmConfig | None = None,
*,
head_size: int | None = None,
kv_cache_dtype: str | None = None,
) -> int:
layer_index = self.num_layers
self.num_layers += 1
return layer_index
def set_logical_topk_ready(self, layer_index: int) -> None:
if layer_index == 0 and self.has_indexer:
self.logical_topk_ready.record(current_stream())
def prepare_for_batch(self, layer_index: int, attn_metadata: Any | None) -> None:
pass
def gather_fp8_prefill(
self,
layer_index: int,
source_cache: torch.Tensor,
dst: torch.Tensor,
block_table: torch.Tensor,
workspace_starts: torch.Tensor,
batch_size: int,
attn_metadata: Any,
request_start: int,
) -> torch.Event | None:
ops.cp_gather_and_upconvert_fp8_kv_cache(
source_cache,
dst,
block_table,
workspace_starts,
batch_size,
)
return None
def convert_logical_to_physical_topk(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
attn_metadata: Any,
*,
block_stride_rows: int | None,
return_valid_counts: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""Convert one index result once for all layers in this group."""
return self._convert_once(
layer_index,
logical_topk_indices,
attn_metadata.req_id_per_token[: logical_topk_indices.shape[0]],
attn_metadata.block_table,
attn_metadata.block_size,
block_stride_rows=block_stride_rows,
return_valid_counts=return_valid_counts,
)
def _convert_once(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
req_id_per_token: torch.Tensor,
block_table: torch.Tensor,
block_size: int,
*,
block_stride_rows: int | None,
return_valid_counts: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
num_tokens = logical_topk_indices.shape[0]
if num_tokens > self.physical_topk_indices.shape[0]:
return triton_convert_req_index_to_global_index(
req_id_per_token,
block_table,
logical_topk_indices,
BLOCK_SIZE=block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=logical_topk_indices.shape[1],
return_valid_counts=return_valid_counts,
)
physical_topk_indices = self.physical_topk_indices[:num_tokens]
valid_topk_counts = self.valid_topk_counts[:num_tokens]
compute_stream = current_stream()
if layer_index == 0:
if self.has_indexer:
self.side_stream.wait_event(self.logical_topk_ready)
else:
self.side_stream.wait_stream(compute_stream)
with self.side_stream:
triton_convert_req_index_to_global_index(
req_id_per_token,
block_table,
logical_topk_indices,
BLOCK_SIZE=block_size,
BLOCK_STRIDE_ROWS=block_stride_rows,
NUM_TOPK_TOKENS=logical_topk_indices.shape[1],
return_valid_counts=return_valid_counts,
out=physical_topk_indices,
valid_counts_out=(
valid_topk_counts if return_valid_counts else None
),
)
self.physical_topk_ready.record(self.side_stream)
compute_stream.wait_event(self.physical_topk_ready)
if return_valid_counts:
return physical_topk_indices, valid_topk_counts
return physical_topk_indices
@dataclass
class HiSparseMLAIndexGroup(SparseMLAIndexGroup):
"""Sparse index group with per-layer host-backed KV caches."""
caches: list[HiSparseCacheHandle] = field(default_factory=list)
hisparse_group: Any | None = None
prefill_stream: torch.Stream | None = None
prefill_ready_events: list[torch.Event] = field(default_factory=list)
def register_layer(
self,
vllm_config: VllmConfig | None = None,
*,
head_size: int | None = None,
kv_cache_dtype: str | None = None,
) -> int:
assert vllm_config is not None
assert head_size is not None
assert kv_cache_dtype is not None
layer_index = super().register_layer()
if self.prefill_stream is None:
self.prefill_stream = _create_side_stream(self.logical_topk_indices.device)
if kv_cache_dtype == "fp8_ds_mla":
row_width = FP8_DS_MLA_ROW_BYTES
kv_dtype = torch.uint8
else:
from vllm.utils.torch_utils import kv_cache_dtype_str_to_dtype
row_width = head_size
kv_dtype = kv_cache_dtype_str_to_dtype(
kv_cache_dtype, vllm_config.model_config
)
cache = create_hisparse_cache_handle(
vllm_config,
self.logical_topk_indices.shape[1],
is_index_group_leader=layer_index == 0,
row_width=row_width,
kv_dtype=kv_dtype,
index_group=self,
)
assert cache is not None
self.caches.append(cache)
cache.index_group_caches = self.caches
self.prefill_ready_events.append(_create_event())
return layer_index
def cache(self, layer_index: int) -> HiSparseCacheHandle:
return self.caches[layer_index]
def physical_kv_cache(self, layer_index: int) -> torch.Tensor:
cache = self.cache(layer_index)
return cache.runtime.hot.attention_cache
def prepare_for_batch(self, layer_index: int, attn_metadata: Any | None) -> None:
if layer_index == 0:
self.cache(0).prepare_group_for_batch(attn_metadata)
def convert_logical_to_physical_topk(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
attn_metadata: Any,
*,
block_stride_rows: int | None,
return_valid_counts: bool,
req_id_per_token: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
cache = self.cache(layer_index)
num_tokens = logical_topk_indices.shape[0]
if req_id_per_token is None:
req_id_per_token = attn_metadata.req_id_per_token[:num_tokens]
if num_tokens > self.physical_topk_indices.shape[0]:
# Prefill-sized batches do not fit the decode residency workspace.
# Non-resident prefills are staged before reaching this path.
assert cache.all_context_pages_resident
leader = self.cache(0)
assert leader.view is not None and leader.block_table is not None
return self._convert_once(
layer_index,
logical_topk_indices,
req_id_per_token,
leader.block_table,
leader.view.block_size,
block_stride_rows=leader.view.attention_block_stride,
return_valid_counts=return_valid_counts,
)
source_block_table = cache.source_block_table
assert source_block_table is not None
return cache.swap_in(
req_id_per_token,
block_table=source_block_table,
logical_topk_indices=logical_topk_indices,
block_size=attn_metadata.block_size,
return_valid_counts=return_valid_counts,
)
def convert_decode_logical_to_physical_topk(
self,
layer_index: int,
logical_topk_indices: torch.Tensor,
attn_metadata: Any,
*,
return_valid_counts: bool,
num_decodes: int | None = None,
decode_query_len: int | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
num_tokens = logical_topk_indices.shape[0]
if num_decodes is None:
num_decodes = attn_metadata.num_decodes
if decode_query_len is None:
decode_query_len = attn_metadata.decode_max_query_len
if decode_query_len == 1:
return self.convert_logical_to_physical_topk(
layer_index,
logical_topk_indices,
attn_metadata,
block_stride_rows=None,
return_valid_counts=return_valid_counts,
req_id_per_token=self.request_ids[:num_decodes],
)
if num_tokens != num_decodes * decode_query_len:
query_start_loc = attn_metadata.query_start_loc[: num_decodes + 1]
physical_topk_indices = self.physical_topk_indices[: num_tokens + 1]
valid_topk_counts = self.valid_topk_counts[: num_tokens + 1]
request_ids = self.request_ids[:num_decodes]
cache = self.cache(layer_index)
source_block_table = cache.source_block_table
assert source_block_table is not None
for step in range(decode_query_len):
token_indices = query_start_loc[:-1] + step
active = (token_indices < query_start_loc[1:]) & (
token_indices < num_tokens
)
output_indices = torch.where(
active, token_indices, torch.full_like(token_indices, num_tokens)
).long()
token_indices = token_indices.clamp(0, num_tokens - 1).long()
step_topk = logical_topk_indices.index_select(
0, token_indices
).masked_fill(~active.unsqueeze(1), -1)
step_result = cache.swap_in(
request_ids,
block_table=source_block_table,
logical_topk_indices=step_topk,
block_size=attn_metadata.block_size,
return_valid_counts=return_valid_counts,
)
if layer_index == 0:
if return_valid_counts:
step_indices, step_counts = step_result
valid_topk_counts.index_copy_(0, output_indices, step_counts)
else:
step_indices = step_result
physical_topk_indices.index_copy_(0, output_indices, step_indices)
physical_topk_indices = physical_topk_indices[:num_tokens]
if return_valid_counts:
return physical_topk_indices, valid_topk_counts[:num_tokens]
return physical_topk_indices
assert num_tokens == num_decodes * decode_query_len
logical_topk_by_request = logical_topk_indices.view(
num_decodes, decode_query_len, -1
)
physical_topk_by_request = self.physical_topk_indices[:num_tokens].view(
num_decodes, decode_query_len, -1
)
valid_topk_by_request = self.valid_topk_counts[:num_tokens].view(
num_decodes, decode_query_len
)
request_ids = self.request_ids[:num_decodes]
for step in range(decode_query_len):
cache = self.cache(layer_index)
source_block_table = cache.source_block_table
assert source_block_table is not None
cache.swap_in(
request_ids,
block_table=source_block_table,
logical_topk_indices=logical_topk_by_request[:, step],
block_size=attn_metadata.block_size,
return_valid_counts=return_valid_counts,
attention_indices_out=(
physical_topk_by_request[:, step] if layer_index == 0 else None
),
valid_counts_out=(
valid_topk_by_request[:, step]
if layer_index == 0 and return_valid_counts
else None
),
)
physical_topk_indices = physical_topk_by_request.view(num_tokens, -1)
if return_valid_counts:
return physical_topk_indices, valid_topk_by_request.view(num_tokens)
return physical_topk_indices
def stage_prefill_rows(
self, layer_index: int, kv_cache: torch.Tensor, attn_metadata: Any
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
cache = self.cache(layer_index)
prefill = attn_metadata.prefill
staging_plan = prefill.host_staging_plan if prefill is not None else None
assert staging_plan is not None
resident_cache = None
if cache.view is not None and cache.block_table is not None:
staging_plan.ensure_gpu_sources(
cache.block_table[attn_metadata.num_decodes :],
cache.view.block_size,
)
resident_cache = cache.view.cache
staged_cache = cache.runtime.gather_prefill_cache(
kv_cache,
staging_plan,
resident_cache=resident_cache,
)
req_ids = attn_metadata.req_id_per_token[attn_metadata.num_decode_tokens :]
if attn_metadata.num_decodes > 0:
req_ids = req_ids - attn_metadata.num_decodes
return staged_cache, staging_plan.block_table, req_ids
def _prefill_gather_plan(
self, layer_index: int, attn_metadata: Any
) -> HiSparsePrefillStagingPlan:
cache = self.cache(layer_index)
prefill = attn_metadata.prefill
plan = prefill.host_staging_plan if prefill is not None else None
assert plan is not None
assert cache.view is not None and cache.block_table is not None
plan.ensure_gpu_sources(
cache.block_table[attn_metadata.num_decodes :],
cache.view.block_size,
)
assert plan.gpu_row_ids is not None
return plan
def gather_fp8_prefill(
self,
layer_index: int,
source_cache: torch.Tensor,
dst: torch.Tensor,
block_table: torch.Tensor,
workspace_starts: torch.Tensor,
batch_size: int,
attn_metadata: Any,
request_start: int,
) -> torch.Event | None:
cache = self.cache(layer_index)
plan = self._prefill_gather_plan(layer_index, attn_metadata)
assert cache.view is not None and plan.gpu_row_ids is not None
row_width = source_cache.shape[-1]
prefill_stream = self.prefill_stream
assert prefill_stream is not None
block_table = plan.block_table[request_start : request_start + batch_size]
prefill_stream.wait_stream(current_stream())
with prefill_stream:
ops.cp_gather_and_upconvert_fp8_kv_cache(
cache.view.cache,
dst,
block_table,
workspace_starts,
batch_size,
host_cache=source_cache.view(-1, row_width),
host_row_ids=plan.row_ids,
device_row_ids=plan.gpu_row_ids,
)
ready = self.prefill_ready_events[layer_index]
ready.record(prefill_stream)
return ready
class SparseMLAIndexGroupBuilder:
"""Assign sparse MLA layers to their index-producing layer."""
def __init__(
self, logical_topk_indices: torch.Tensor, max_decode_rows: int | None = None
) -> None:
self.logical_topk_indices = logical_topk_indices
self.max_decode_rows = (
logical_topk_indices.shape[0]
if max_decode_rows is None
else max_decode_rows
)
self.current_group: SparseMLAIndexGroup | None = None
def register_layer(
self,
is_index_producing_layer: bool,
vllm_config: VllmConfig | None = None,
*,
head_size: int | None = None,
kv_cache_dtype: str | None = None,
) -> tuple[SparseMLAIndexGroup, int]:
if is_index_producing_layer or self.current_group is None:
group_cls = (
HiSparseMLAIndexGroup
if vllm_config is not None
and vllm_config.attention_config.hisparse_config is not None
else SparseMLAIndexGroup
)
workspace_rows = self.max_decode_rows
physical_topk_indices = torch.empty(
(workspace_rows + 1, self.logical_topk_indices.shape[1]),
dtype=self.logical_topk_indices.dtype,
device=self.logical_topk_indices.device,
)
self.current_group = group_cls(
logical_topk_indices=self.logical_topk_indices,
physical_topk_indices=physical_topk_indices,
valid_topk_counts=torch.empty(
workspace_rows + 1,
dtype=torch.int32,
device=self.logical_topk_indices.device,
),
request_ids=torch.arange(
workspace_rows,
dtype=torch.int32,
device=self.logical_topk_indices.device,
),
side_stream=_create_side_stream(self.logical_topk_indices.device),
logical_topk_ready=_create_event(),
physical_topk_ready=_create_event(),
has_indexer=is_index_producing_layer,
)
group = self.current_group
group_index = group.register_layer(
vllm_config,
head_size=head_size,
kv_cache_dtype=kv_cache_dtype,
)
return group, group_index
def get_sparse_mla_index_group_max_rows(vllm_config: VllmConfig) -> int:
max_query_len = 1
speculative_config = vllm_config.speculative_config
if (
speculative_config is not None
and speculative_config.num_speculative_tokens is not None
):
max_query_len += speculative_config.num_speculative_tokens * (
2 if speculative_config.parallel_drafting else 1
)
scheduler_config = vllm_config.scheduler_config
return min(
scheduler_config.max_num_batched_tokens,
scheduler_config.max_num_seqs * max_query_len,
)
+28 -6
View File
@@ -407,6 +407,8 @@ def triton_convert_req_index_to_global_index(
prefill_workspace_request_ids: torch.Tensor | None = None,
prefill_workspace_starts: torch.Tensor | None = None,
return_valid_counts: bool = False,
out: torch.Tensor | None = None,
valid_counts_out: torch.Tensor | None = None,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
"""
out[token_id, indice_id] =
@@ -462,16 +464,36 @@ def triton_convert_req_index_to_global_index(
# contiguous prefix [0, valid_count) and leaves the tail unwritten, so
# pre-fill -1 there. flash_mla_sparse_fwd then bounds attention to
# [:topk_length] == exactly the valid set (no dropped tokens).
if return_valid_counts:
out = torch.full_like(token_indices_c, -1)
if out is None:
out = (
torch.full_like(token_indices_c, -1)
if return_valid_counts
else torch.empty_like(token_indices_c)
)
else:
out = torch.empty_like(token_indices_c)
assert out.dtype == token_indices_c.dtype
assert out.device == token_indices_c.device
assert out.shape == token_indices_c.shape
assert out.is_contiguous()
if return_valid_counts:
out.fill_(-1)
valid_counts: torch.Tensor | None = None
if return_valid_counts:
# Zero-init only matters for the atomic accumulation path.
alloc = torch.empty if single_tile else torch.zeros
valid_counts = alloc(num_tokens, dtype=torch.int32, device=token_indices.device)
if valid_counts_out is None:
# Zero-init only matters for the atomic accumulation path.
alloc = torch.empty if single_tile else torch.zeros
valid_counts = alloc(
num_tokens, dtype=torch.int32, device=token_indices.device
)
else:
assert valid_counts_out.dtype == torch.int32
assert valid_counts_out.device == token_indices.device
assert valid_counts_out.shape == (num_tokens,)
assert valid_counts_out.is_contiguous()
valid_counts = valid_counts_out
if not single_tile:
valid_counts.zero_()
# Prepare prefill pointers
if HAS_PREFILL_WORKSPACE:
+51 -5
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from collections.abc import Callable, Iterable, Sequence
from typing import Any
from vllm.distributed.kv_events import (
@@ -157,6 +157,7 @@ class BlockPool:
actual block size can be a multiple of hash_block_size.
enable_kv_cache_events: Whether to enable kv cache events.
metrics_collector: Optional metrics collector for tracking block residency.
medium: Storage medium reported in KV cache events.
"""
def __init__(
@@ -166,14 +167,16 @@ class BlockPool:
hash_block_size: int,
enable_kv_cache_events: bool = False,
metrics_collector: KVCacheMetricsCollector | None = None,
medium: str = MEDIUM_GPU,
):
assert isinstance(num_gpu_blocks, int) and num_gpu_blocks > 0
self.num_gpu_blocks = num_gpu_blocks
self.medium = medium
self.enable_caching = enable_caching
self.hash_block_size = hash_block_size
# All kv-cache blocks.
self.blocks: list[KVCacheBlock] = [
KVCacheBlock(idx) for idx in range(num_gpu_blocks)
KVCacheBlock(idx, pool=self) for idx in range(num_gpu_blocks)
]
# Free block queue that constructs and manipulates a doubly linked
# list of free blocks (including eviction candidates when caching is
@@ -194,6 +197,9 @@ class BlockPool:
self.kv_event_queue: list[KVCacheEvent] = []
self.metrics_collector = metrics_collector
# Callbacks for blocks released with ``unpin_blocks`` whose contents
# are still being read until the pool reuses them.
self._reuse_watchers: dict[int, Callable[[KVCacheBlock], None]] = {}
def get_cached_block(
self, block_hash: BlockHash, kv_cache_group_ids: list[int]
@@ -364,7 +370,7 @@ class BlockPool:
token_ids=request.all_token_ids[start_token_idx:end_token_idx],
block_size=block_size,
lora_id=request.lora_request.adapter_id if request.lora_request else None,
medium=MEDIUM_GPU,
medium=self.medium,
lora_name=request.lora_request.name if request.lora_request else None,
extra_keys=extra_keys_list if extra_keys_list else None,
group_idx=kv_cache_group_id,
@@ -543,7 +549,7 @@ class BlockPool:
lora_id=request.lora_request.adapter_id
if request.lora_request
else None,
medium=MEDIUM_GPU,
medium=self.medium,
lora_name=request.lora_request.name
if request.lora_request
else None,
@@ -610,7 +616,7 @@ class BlockPool:
self.kv_event_queue.append(
BlockRemoved(
block_hashes=[maybe_convert_block_hash(get_block_hash(block_hash))],
medium=MEDIUM_GPU,
medium=self.medium,
group_idx=get_group_id(block_hash),
)
)
@@ -671,6 +677,9 @@ class BlockPool:
ret: list[KVCacheBlock] = self.free_block_queue.popleft_n(num_blocks)
if self._reuse_watchers:
self._notify_reuse(ret)
# In order to only iterate the list once, we duplicated code a bit
if self.enable_caching:
for block in ret:
@@ -687,6 +696,33 @@ class BlockPool:
self.metrics_collector.on_block_allocated(block)
return ret
def _notify_reuse(self, blocks: Iterable[KVCacheBlock]) -> None:
for block in blocks:
watcher = self._reuse_watchers.pop(block.block_id, None)
if watcher is not None:
watcher(block)
def unpin_blocks(
self,
blocks: Iterable[KVCacheBlock],
on_reuse: Callable[[KVCacheBlock], None],
) -> None:
"""Release references to blocks that stay readable until reused.
The blocks become last-resort eviction candidates regardless of prefix
caching: they join the tail of the free queue and count as free.
``on_reuse`` fires when ``get_new_blocks`` hands a block out (or the
cache is reset), so the caller can stop reading it.
"""
released: list[KVCacheBlock] = []
for block in blocks:
assert block.ref_cnt > 0 and not block.is_null
block.ref_cnt -= 1
self._reuse_watchers[block.block_id] = on_reuse
if block.ref_cnt == 0:
released.append(block)
self.free_block_queue.append_n(released)
def _maybe_evict_cached_block(self, block: KVCacheBlock) -> bool:
"""
If a block is cached in `cached_block_hash_to_block`, we reset its hash
@@ -742,7 +778,11 @@ class BlockPool:
# Identify blocks with hash (LRU cache) and without it (never match APC)
blocks_to_evict_last = []
blocks_to_evict_first = []
other_pools: dict[BlockPool, list[KVCacheBlock]] = {}
for block in ordered_blocks:
if block.pool is not None and block.pool is not self:
other_pools.setdefault(block.pool, []).append(block)
continue
block.ref_cnt -= 1
if block.ref_cnt == 0 and not block.is_null:
if block.block_hash is None or not self.enable_caching:
@@ -756,6 +796,8 @@ class BlockPool:
self.free_block_queue.prepend_n(blocks_to_evict_first)
# Blocks to reuse last are appended to the end of the free queue.
self.free_block_queue.append_n(blocks_to_evict_last)
for pool, blocks in other_pools.items():
pool.free_blocks(blocks)
def evict_blocks(self, block_ids: set[int]) -> None:
"""evict blocks from the prefix cache by their block IDs.
@@ -797,6 +839,10 @@ class BlockPool:
# Remove all hashes so that no new blocks will hit.
self.cached_block_hash_to_block = BlockHashToBlockMap()
self.cached_block_hashes_by_block.clear()
if self._reuse_watchers:
self._notify_reuse(
[self.blocks[block_id] for block_id in list(self._reuse_watchers)]
)
# Remove all hashes from all blocks.
for block in self.blocks:
+39 -8
View File
@@ -139,6 +139,7 @@ class KVCacheCoordinator(ABC):
max_in_flight_tokens=max_in_flight_tokens,
max_model_len=max_model_len,
block_pool=self.block_pool,
role=kv_cache_group.role,
enable_caching=enable_caching,
kv_cache_group_id=i,
dcp_world_size=dcp_world_size_for_kv_cache_spec(
@@ -179,7 +180,7 @@ class KVCacheCoordinator(ABC):
apply_admission_cap: bool = False,
) -> int:
"""
Get the number of blocks needed to be allocated for the request.
Get the number of device blocks needed to be allocated for the request.
Args:
request_id: The request ID.
@@ -343,6 +344,8 @@ class KVCacheCoordinator(ABC):
"""
boundaries = self.get_replay_boundaries(request)
for manager in self.single_type_managers:
if not manager.enable_caching:
continue
# Only cache tokens with finalized KV. The last num_reprefillable_tokens
# tokens can be re-prefilled during multi-module MTP.
num_tokens_to_cache = max(
@@ -355,6 +358,27 @@ class KVCacheCoordinator(ABC):
replay_boundaries=boundaries,
)
def emit_cached_block_events(
self, request: Request, computed_blocks: tuple[list[KVCacheBlock], ...]
) -> None:
for group_idx, group_blocks in enumerate(computed_blocks):
if group_blocks:
manager = self.single_type_managers[group_idx]
group = self.kv_cache_config.kv_cache_groups[group_idx]
manager.block_pool.emit_cached_block_events(
request,
len(group_blocks),
group.kv_cache_spec.block_size,
group_idx,
)
def reset_prefix_cache(self) -> bool:
"""Reset each manager's pool once."""
pools = dict.fromkeys(
manager.block_pool for manager in self.single_type_managers
)
return all([pool.reset_prefix_cache() for pool in pools])
def free(self, request_id: str) -> None:
"""
Free the blocks for the request.
@@ -728,10 +752,12 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
# Try to find an existing group with the same spec
for idx, group in enumerate(self.attention_groups):
if group.spec == spec:
assert manager_cls is group.manager_cls, (
"Expected same manager class for identical KV cache specs."
)
if (
group.spec == spec
and group.manager_cls is manager_cls
and self.single_type_managers[group.group_ids[0]].block_pool
is self.single_type_managers[i].block_pool
):
group.group_ids.append(i)
if use_eagle and not group.use_eagle:
self.attention_groups[idx] = group._replace(use_eagle=True)
@@ -782,6 +808,8 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
cached_num_computed_tokens = self._align_cacheable(num_computed_tokens)
boundaries = self.get_replay_boundaries(request)
for manager in self.single_type_managers:
if not manager.enable_caching:
continue
num_tokens_to_cache = cached_num_computed_tokens
# EAGLE groups match one block past each aligned boundary and drop
# it, so make that lookahead block eligible to be cached.
@@ -895,7 +923,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
block_hashes=block_hashes,
max_length=_max_length,
kv_cache_group_ids=group_ids,
block_pool=self.block_pool,
block_pool=self.single_type_managers[first_group_id].block_pool,
kv_cache_spec=spec,
drop_eagle_block=drop_eagle_block,
alignment_tokens=self._cache_hit_alignment_tokens,
@@ -929,7 +957,10 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
for group in self.attention_groups:
if not isinstance(group.spec, FullAttentionSpec):
continue
group_block_size = self.single_type_managers[group.group_ids[0]].block_size
manager = self.single_type_managers[group.group_ids[0]]
if manager.retains_longer_hit:
continue
group_block_size = manager.block_size
num_blocks = cdiv(hit_length, group_block_size)
for group_id in group.group_ids:
if (blks := hit_blocks_by_group[group_id]) is not None:
@@ -966,7 +997,7 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
block_hashes=block_hashes,
max_length=max_cache_hit_length,
kv_cache_group_ids=group_ids,
block_pool=self.block_pool,
block_pool=manager.block_pool,
kv_cache_spec=spec,
drop_eagle_block=use_eagle,
alignment_tokens=self._cache_hit_alignment_tokens,
+20 -13
View File
@@ -183,6 +183,11 @@ class KVCacheManager:
manager.fine_grained_prefix_cache = True
self.num_kv_cache_groups = len(kv_cache_config.kv_cache_groups)
self.block_pool = self.coordinator.block_pool
self.retained_hit_group_ids = tuple(
manager.kv_cache_group_id
for manager in self.coordinator.single_type_managers
if manager.retains_longer_hit
)
self.kv_cache_config = kv_cache_config
# Watermark: minimum number of KV cache blocks to keep free when
@@ -287,17 +292,7 @@ class KVCacheManager:
and self.enable_kv_cache_events
and getattr(request, "kv_cache_report_mode", "incremental") == "full"
):
for group_idx, group_blocks in enumerate(computed_blocks):
num_blocks = len(group_blocks)
if num_blocks > 0:
group = self.kv_cache_config.kv_cache_groups[group_idx]
block_size = group.kv_cache_spec.block_size
self.block_pool.emit_cached_block_events(
request,
num_blocks,
block_size,
group_idx,
)
self.coordinator.emit_cached_block_events(request, computed_blocks)
# The junction to pin is where the lagging sparse-retention group stops
# (``num_new_computed_tokens``) plus the uncached shared prefix -- i.e.
@@ -463,6 +458,16 @@ class KVCacheManager:
if new_computed_blocks is not None:
new_computed_block_list = new_computed_blocks.blocks
if self.retained_hit_group_ids:
# Only retain the prefix covered by the local and external hits.
reused = num_new_computed_tokens + num_external_computed_tokens
groups = list(new_computed_block_list)
for group_id in self.retained_hit_group_ids:
manager = self.coordinator.single_type_managers[group_id]
groups[group_id] = groups[group_id][
: cdiv(reused, manager.block_size)
]
new_computed_block_list = tuple(groups)
else:
new_computed_block_list = self.empty_kv_cache_blocks.blocks
@@ -564,7 +569,7 @@ class KVCacheManager:
# P/D: delay caching blocks if we have to recv from
# remote. Update state for locally cached blocks.
if not self.enable_caching or delay_cache_blocks:
if delay_cache_blocks:
return self.create_kv_cache_blocks(new_blocks)
# NOTE(woosuk): We want to commit (cache) up to num_local_computed_tokens
@@ -639,7 +644,7 @@ class KVCacheManager:
bool: True if the prefix cache is successfully reset,
False otherwise.
"""
if not self.block_pool.reset_prefix_cache():
if not self.coordinator.reset_prefix_cache():
return False
if self.log_stats:
assert self.prefix_cache_stats is not None
@@ -741,6 +746,8 @@ class KVCacheManager:
self.kv_cache_config.kv_cache_groups,
self.get_blocks(request.request_id).blocks,
):
if not group.kv_cache_spec.prefix_cacheable:
continue
if isinstance(
group.kv_cache_spec,
(CrossAttentionSpec, EncoderOnlyAttentionSpec),
+74 -10
View File
@@ -8,23 +8,30 @@ import math
import os
from collections import defaultdict
from collections.abc import Callable, Iterable, Iterator, Sequence
from dataclasses import dataclass, replace
from dataclasses import dataclass, field, replace
from functools import partial
from typing import Any, NamedTuple, NewType, TypeAlias, cast, overload
from typing import TYPE_CHECKING, Any, NamedTuple, NewType, TypeAlias, cast, overload
from vllm import envs
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.utils.hashing import xxhash, xxhash_cbor
from vllm.utils.math_utils import cdiv
from vllm.utils.math_utils import cdiv, round_up
from vllm.utils.mem_utils import format_gib
from vllm.utils.torch_utils import get_dtype_size
from vllm.v1.hisparse.layout import (
get_hisparse_gpu_memory_usage,
get_hisparse_host_pool_bytes,
get_hisparse_kv_cache_config,
get_hisparse_kv_cache_groups,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
ChunkedLocalAttentionSpec,
CircularBufferSpec,
FullAttentionSpec,
HiddenStateCacheSpec,
HiSparseHotSpec,
KpoolTailSpec,
KVCacheConfig,
KVCacheGroupSpec,
@@ -44,6 +51,10 @@ from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
from vllm.v1.request import Request
from vllm.v1.utils import tensor_data
if TYPE_CHECKING:
from vllm.v1.core.block_pool import BlockPool
# BlockHash represents the hash of a single KV-cache block used for
# prefix caching. Treating it as a distinct type from `bytes` helps
# catch accidental misuse when passing around raw byte strings.
@@ -169,6 +180,10 @@ class KVCacheBlock:
block_id: int
# Reference count.
ref_cnt: int = 0
# Deferred frees may contain blocks from multiple pools.
pool: "BlockPool | None" = field(
default=None, repr=False, compare=False, kw_only=True
)
# The hash key (block hash + group id) of the block, only available
# when the block is full and cached.
_block_hash: BlockHashWithGroupId | None = None
@@ -1057,21 +1072,32 @@ def get_max_concurrency_for_kv_cache_config(
A request at max_model_len consumes whole blocks from each group's block
table — cdiv(per-request bytes, page bytes) of the group's spec — and all
groups draw those block ids from one shared pool, so the per-request
device groups draw those block ids from one shared pool, so the per-request
total is the sum over groups. The memory/page ratio is identical whether
a group carries an aggregated UniformTypeKVCacheSpecs (worker config) or
a representative per-layer spec (scheduler config), so both capacity
call sites agree.
Host groups use a separate pool; the smaller concurrency limit applies.
"""
num_blocks_per_request = sum(
cdiv(
num_blocks_per_request = 0
host_blocks_per_request = 0
for group in kv_cache_config.kv_cache_groups:
required = cdiv(
group.kv_cache_spec.max_memory_usage_bytes(vllm_config),
group.kv_cache_spec.page_size_bytes,
)
for group in kv_cache_config.kv_cache_groups
)
max_concurrency = kv_cache_config.num_blocks / num_blocks_per_request
return max_concurrency
if group.host_resident:
host_blocks_per_request += required
else:
num_blocks_per_request += required
limits = [kv_cache_config.num_blocks / num_blocks_per_request]
if host_blocks_per_request:
assert kv_cache_config.hisparse_host_num_blocks is not None
limits.append(
kv_cache_config.hisparse_host_num_blocks / host_blocks_per_request
)
return min(limits)
def may_override_num_blocks(vllm_config: VllmConfig, num_blocks: int) -> int:
@@ -1575,6 +1601,13 @@ def _get_kv_cache_bytes_per_block(
for group in kv_cache_groups
)
assert bytes_per_block > 0
hot_page_sizes = [
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))
return bytes_per_block
@@ -1640,6 +1673,12 @@ def get_kv_cache_config_from_groups(
),
)
if vllm_config.attention_config.hisparse_config is not None:
host_budget = get_hisparse_host_pool_bytes(vllm_config)
return get_hisparse_kv_cache_config(
vllm_config, kv_cache_groups, available_memory, host_budget
)
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
(
attn_group,
@@ -2210,6 +2249,9 @@ def get_kv_cache_groups(
# attention free models.
return []
if hisparse_groups := get_hisparse_kv_cache_groups(vllm_config, kv_cache_spec):
return hisparse_groups
if is_kv_cache_spec_uniform(kv_cache_spec):
# KV cache of all layers are the same, which is true for
# most models. Allocate the same amount of memory for
@@ -2287,6 +2329,10 @@ def generate_scheduler_kv_cache_config(
assert all(
[cfg.num_blocks == kv_cache_configs[0].num_blocks for cfg in kv_cache_configs]
)
assert all(
cfg.hisparse_host_num_blocks == kv_cache_configs[0].hisparse_host_num_blocks
for cfg in kv_cache_configs
)
# All workers have the same kv_cache_config except layer names, so use
# an arbitrary one to initialize the scheduler.
cfg = copy.deepcopy(kv_cache_configs[0])
@@ -2347,6 +2393,9 @@ def _max_memory_usage_bytes_from_groups(
if not kv_cache_groups:
return 0
if vllm_config.attention_config.hisparse_config is not None:
return get_hisparse_gpu_memory_usage(vllm_config, kv_cache_groups)
if (glm5_layout := _glm5_next_tensor_layout(kv_cache_groups)) is not None:
(
attn_group,
@@ -2396,9 +2445,21 @@ def _estimate_max_model_len_from_groups(
Returns 0 if even 1 token doesn't fit.
"""
original_max = vllm_config.model_config.max_model_len
hisparse_enabled = (
vllm_config.attention_config.hisparse_config is not None
and bool(kv_cache_groups)
)
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
)
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
@@ -2629,6 +2690,9 @@ def get_kv_cache_configs(
adjusted_memory.append(override * bytes_per_block)
available_memory = adjusted_memory
if vllm_config.attention_config.hisparse_config is not None:
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.
+3
View File
@@ -294,6 +294,9 @@ class SchedulerOutput:
# CoW copies to apply after zeroing new blocks and before forward.
kv_cache_block_copies: list[KVCacheBlockCopy] | None = None
# Complete block-table rows that replace incrementally appended block IDs.
block_table_updates: dict[str, tuple[list[int], ...]] | None = None
# Scheduler-local; always None by the time this reaches a worker.
kv_connector_block_state: KVConnectorBlockState | None = None
+33 -7
View File
@@ -316,10 +316,9 @@ class Scheduler(SchedulerInterface):
self.cache_config.enable_mamba_fine_grained_prefix_cache
),
)
# Bind GPU block pool to the KV connector. This must happen after
# kv_cache_manager is constructed so block_pool is available.
# Bind after construction so connectors can access the cache manager.
if self.connector is not None:
self.connector.bind_gpu_block_pool(self.kv_cache_manager.block_pool)
self.connector.bind_kv_cache_manager(self.kv_cache_manager)
self.use_pp = self.parallel_config.pipeline_parallel_size > 1
self.use_v2_model_runner = vllm_config.use_v2_model_runner
@@ -738,6 +737,12 @@ class Scheduler(SchedulerInterface):
# The request can be scheduled.
break
if (
self.connector is not None
and self.connector.has_pending_block_frees()
):
break
# The request cannot be scheduled.
# Preempt the lowest-priority request.
if self.policy == SchedulingPolicy.PRIORITY:
@@ -1895,14 +1900,20 @@ class Scheduler(SchedulerInterface):
outputs: dict[int, list[EngineCoreOutput]] = defaultdict(list)
spec_decoding_stats: SpecDecodingStats | None = None
failed_kv_load_req_ids = None
failed_kv_load_req_ids: set[str] = set()
if kv_connector_output and kv_connector_output.failed_recving:
failed_kv_load_req_ids.update(
self._handle_failed_recving(kv_connector_output.failed_recving)
)
if kv_connector_output and kv_connector_output.invalid_block_ids:
# These blocks contain externally computed tokens that failed to
# load. Identify affected requests and adjust their computed token
# count to trigger recomputation of the invalid blocks.
failed_kv_load_req_ids = self._handle_invalid_blocks(
kv_connector_output.invalid_block_ids,
num_scheduled_tokens,
failed_kv_load_req_ids.update(
self._handle_invalid_blocks(
kv_connector_output.invalid_block_ids,
num_scheduled_tokens,
)
)
# Persist per-step routed experts into the scheduler-side slot
@@ -3135,6 +3146,21 @@ class Scheduler(SchedulerInterface):
return affected_req_ids, total_affected_tokens, blocks_to_evict
def _handle_failed_recving(self, failed_req_ids: set[str]) -> set[str]:
"""Fail closed for layouts whose block IDs are not globally unique."""
affected_req_ids: set[str] = set()
for req_id in failed_req_ids:
request = self.requests.get(req_id)
if (
request is not None
and request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
):
affected_req_ids.add(req_id)
if self.recompute_kv_load_failures:
request.num_computed_tokens = 0
self.failed_recving_kv_req_ids.add(req_id)
return set() if self.recompute_kv_load_failures else affected_req_ids
def _handle_invalid_blocks(
self, invalid_block_ids: set[int], num_scheduled_tokens: dict[str, int]
) -> set[str]:
+405 -3
View File
@@ -4,8 +4,9 @@ import itertools
from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Sequence
from typing import ClassVar
from typing import TYPE_CHECKING, ClassVar
from vllm.distributed.kv_events import MEDIUM_CPU
from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv
from vllm.v1.core.block_pool import BlockPool
@@ -16,6 +17,7 @@ from vllm.v1.core.kv_cache_utils import (
KVCacheBlock,
resolve_block_hashes,
)
from vllm.v1.hisparse.block_pool import SharedEventQueueBlockPool
from vllm.v1.kv_cache_interface import (
AttentionSpec,
ChunkedLocalAttentionSpec,
@@ -23,7 +25,10 @@ from vllm.v1.kv_cache_interface import (
CrossAttentionSpec,
FullAttentionSpec,
HiddenStateCacheSpec,
HiSparseHotSpec,
HiSparseResidentSpec,
KpoolTailSpec,
KVCacheGroupRole,
KVCacheSpec,
MambaSpec,
MLAAttentionSpec,
@@ -37,6 +42,9 @@ from vllm.v1.kv_cache_interface import (
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
from vllm.v1.request import Request
if TYPE_CHECKING:
from vllm.v1.hisparse.coordinator import HiSparseCoordinator
logger = init_logger(__name__)
@@ -48,6 +56,9 @@ class SingleTypeKVCacheManager(ABC):
supports_fine_grained_hash_lookup: ClassVar[bool] = False
# Keep this group's longer prefix until external cache lookup completes.
retains_longer_hit: bool = False
@property
def has_positionally_stable_blocks(self) -> bool:
"""Whether positional offload scans can follow this block table.
@@ -2191,10 +2202,388 @@ class SinkFullAttentionManager(FullAttentionManager):
assert sink_len is not None and sink_len > 0 and sink_len % self.block_size == 0
class HiSparseSourceManager(FullAttentionManager):
"""Host-tier manager with a private pool; publishes hashes once durable.
Host capacity is best effort: a page that cannot get a host block keeps a
null host entry, so its GPU copy is never written back and stays pinned.
"""
coordinator: "HiSparseCoordinator | None" = None
# The host tier keeps prefixes the device groups have already lost.
retains_longer_hit = True
@property
def records_new_block_ids(self) -> bool:
return False
def take_new_block_ids(self) -> list[int]:
self.new_block_ids = []
return []
def bind_host_pool(self, num_blocks: int) -> None:
"""Replace the device pool this group was built with by a host one."""
device_pool = self.block_pool
self.block_pool = SharedEventQueueBlockPool(
num_gpu_blocks=num_blocks,
enable_caching=self.enable_caching and self.kv_cache_spec.prefix_cacheable,
hash_block_size=device_pool.hash_block_size,
enable_kv_cache_events=device_pool.enable_kv_cache_events,
metrics_collector=device_pool.metrics_collector,
medium=MEDIUM_CPU,
event_owner=device_pool,
)
self._null_block = self.block_pool.null_block
def take_pending_cow_copies(self) -> list[tuple[KVCacheBlock, KVCacheBlock]]:
"""Host copies never reach the worker's generic block-copy path."""
return []
def take_host_cow_copies(self) -> list[tuple[KVCacheBlock, KVCacheBlock]]:
"""Drain host copies for the coordinator to hand to the connector."""
copies = self._pending_cow_copies
self._pending_cow_copies = []
return copies
def get_num_blocks_to_allocate(
self,
request_id: str,
num_tokens: int,
new_computed_blocks: Sequence[KVCacheBlock],
total_computed_tokens: int,
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
) -> int:
if (
total_computed_tokens > num_local_computed_tokens
or self._has_partial_local_hit(
new_computed_blocks, num_local_computed_tokens
)
):
# External loads need real destinations; future GPU-computed pages
# remain best effort. Use the same admission sentinel as Mamba.
required = super().get_num_blocks_to_allocate(
request_id,
total_computed_tokens,
new_computed_blocks,
total_computed_tokens,
num_local_computed_tokens,
total_computed_tokens,
)
if required > self.block_pool.get_num_free_blocks():
assert self.coordinator is not None
assert self.coordinator.gpu_pool is not None
return self.coordinator.gpu_pool.num_gpu_blocks + 1
return 0
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
req_blocks = self.req_to_blocks[request_id]
num_required = cdiv(num_tokens, self.block_size)
num_free = self.block_pool.get_num_free_blocks()
if request_id in self._partial_hit_reqs:
num_free -= 1
fit_blocks = min(num_required, len(req_blocks) + max(0, num_free))
new_blocks = super().allocate_new_blocks(
request_id,
fit_blocks * self.block_size,
min(num_tokens_main_model, fit_blocks * self.block_size),
)
req_blocks.extend([self._null_block] * (num_required - len(req_blocks)))
return new_blocks
def allocate_external_computed_blocks(
self,
request_id: str,
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
if num_external_computed_tokens <= 0:
return
# The connector writes these pages; only a successful receive makes
# them readable, not advancing the request's computed-token count.
assert self.coordinator is not None
self.coordinator.record_pending_host_import(
request_id, num_local_computed_tokens + num_external_computed_tokens
)
super().allocate_external_computed_blocks(
request_id, num_local_computed_tokens, num_external_computed_tokens
)
def cache_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
assert self.coordinator is not None
self.coordinator.publish_when_ready(
request,
num_tokens,
retention_interval,
replay_boundaries=replay_boundaries,
)
def publish_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
super().cache_blocks(
request,
num_tokens,
retention_interval=retention_interval,
replay_boundaries=replay_boundaries,
)
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
assert self.coordinator is not None
self.coordinator.free(request_id)
return super().pop_blocks_for_free(request_id)
class _HiSparseAuxiliaryManager(SingleTypeKVCacheManager):
"""Base for ephemeral groups whose host source owns prefix caching."""
coordinator: "HiSparseCoordinator | None" = None
def __init__(self, kv_cache_spec: KVCacheSpec, **kwargs) -> None:
# Never prefix-cached, but the per-step ``cache_blocks`` hook is where
# residency work runs, so stay opted in regardless of prefix caching.
kwargs["enable_caching"] = True
super().__init__(kv_cache_spec, **kwargs)
def cache_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
return None
def get_num_common_prefix_blocks(self, running_request_id: str) -> int:
return 0
@classmethod
def find_longest_cache_hit(
cls,
block_hashes: BlockHashList,
max_length: int,
kv_cache_group_ids: list[int],
block_pool: BlockPool,
kv_cache_spec: KVCacheSpec,
drop_eagle_block: bool,
alignment_tokens: int,
dcp_world_size: int = 1,
pcp_world_size: int = 1,
) -> tuple[tuple[list[KVCacheBlock], ...], int]:
return tuple([] for _ in kv_cache_group_ids), 0
class HiSparseHotManager(_HiSparseAuxiliaryManager):
"""Allocate a hot region only after a request acquires CPU-only history."""
def __init__(self, kv_cache_spec: HiSparseHotSpec, **kwargs) -> None:
super().__init__(kv_cache_spec, **kwargs)
self.blocks_per_request = kv_cache_spec.blocks_per_request
self.hot_required: set[str] = set()
def require_hot(self, request_id: str) -> None:
self.hot_required.add(request_id)
def has_hot(self, request_id: str) -> bool:
return len(self.req_to_blocks.get(request_id, ())) == self.blocks_per_request
def get_num_blocks_to_allocate(
self,
request_id: str,
num_tokens: int,
new_computed_blocks: Sequence[KVCacheBlock],
total_computed_tokens: int,
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
) -> int:
assert not new_computed_blocks
# A hot region is needed to read host-backed history: an external
# import, a new request resuming a host prefix, or one already asked
# to transition. Running requests keep their earlier answer.
host_import = total_computed_tokens > num_local_computed_tokens
resumes_host_prefix = (
num_local_computed_tokens > 0 and request_id not in self.num_cached_block
)
if host_import or resumes_host_prefix or request_id in self.hot_required:
return self.get_num_required_blocks(request_id)
return 0
def get_num_required_blocks(self, request_id: str) -> int:
return max(
self.blocks_per_request - len(self.req_to_blocks.get(request_id, ())),
0,
)
def add_local_computed_blocks(
self,
request_id: str,
new_computed_blocks: Sequence[KVCacheBlock],
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
assert not new_computed_blocks
self.num_cached_block[request_id] = 0
assert self.coordinator is not None
if num_local_computed_tokens > 0 or not self.coordinator.resident_managers:
self.require_hot(request_id)
def allocate_external_computed_blocks(
self,
request_id: str,
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
self.require_hot(request_id)
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
# Cold admissions can bypass add_local_computed_blocks.
self.num_cached_block[request_id] = 0
if request_id not in self.hot_required:
return []
req_blocks = self.req_to_blocks[request_id]
num_new_blocks = self.blocks_per_request - len(req_blocks)
if num_new_blocks <= 0:
return []
new_blocks = self.block_pool.get_new_blocks(num_new_blocks)
req_blocks.extend(new_blocks)
return new_blocks
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
self.hot_required.discard(request_id)
return super().pop_blocks_for_free(request_id)
class HiSparseResidentManager(_HiSparseAuxiliaryManager):
"""Track GPU-resident pages for otherwise host-backed KV."""
def get_num_blocks_to_allocate(
self,
request_id: str,
num_tokens: int,
new_computed_blocks: Sequence[KVCacheBlock],
total_computed_tokens: int,
num_local_computed_tokens: int,
num_tokens_main_model: int,
apply_admission_cap: bool = False,
) -> int:
del num_tokens_main_model
assert not new_computed_blocks
if total_computed_tokens > num_local_computed_tokens:
if total_computed_tokens % self.block_size != 0:
raise ValueError(
"A host-only HiSparse import must end on a cache-block boundary."
)
imported_pages = total_computed_tokens // self.block_size
return max(cdiv(num_tokens, self.block_size) - imported_pages, 0)
existing = len(self.req_to_blocks.get(request_id, ()))
host_pages = cdiv(num_local_computed_tokens, self.block_size)
required = cdiv(num_tokens, self.block_size)
if apply_admission_cap:
assert self._max_admission_blocks_per_request is not None
required = min(required, self._max_admission_blocks_per_request)
return max(required - max(existing, host_pages), 0)
def allocate_external_computed_blocks(
self,
request_id: str,
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
"""Represent imported host history with null resident pages."""
assert num_external_computed_tokens > 0
num_tokens = num_local_computed_tokens + num_external_computed_tokens
blocks = self.req_to_blocks[request_id]
tail_page = cdiv(num_tokens, self.block_size) - 1
if len(blocks) <= tail_page:
blocks.extend([self._null_block] * (tail_page + 1 - len(blocks)))
def add_local_computed_blocks(
self,
request_id: str,
new_computed_blocks: Sequence[KVCacheBlock],
num_local_computed_tokens: int,
num_external_computed_tokens: int,
) -> None:
assert not new_computed_blocks
req_blocks = self.req_to_blocks[request_id]
assert not req_blocks
num_host_pages = cdiv(num_local_computed_tokens, self.block_size)
req_blocks.extend([self._null_block] * num_host_pages)
self.num_cached_block[request_id] = 0
assert self.coordinator is not None
self.coordinator.commit_computed_blocks(request_id, num_host_pages)
def cache_blocks(
self,
request: Request,
num_tokens: int,
retention_interval: int | None = None,
*,
replay_boundaries: Sequence[int],
) -> None:
assert self.coordinator is not None
self.coordinator.plan_prefix_materialization(request.request_id, num_tokens)
self.coordinator.update_residency(request.request_id)
def allocate_new_blocks(
self, request_id: str, num_tokens: int, num_tokens_main_model: int
) -> list[KVCacheBlock]:
del num_tokens_main_model
req_blocks = self.req_to_blocks[request_id]
num_new_blocks = cdiv(num_tokens, self.block_size) - len(req_blocks)
if num_new_blocks <= 0:
return []
new_blocks = self.block_pool.get_new_blocks(num_new_blocks)
req_blocks.extend(new_blocks)
return new_blocks
def pop_blocks_for_free(self, request_id: str) -> list[KVCacheBlock]:
assert self.coordinator is not None
self.coordinator.free(request_id)
return super().pop_blocks_for_free(request_id)
def adopt_resident_page(
self, request_id: str, block_idx: int, block: KVCacheBlock
) -> bool:
"""Point a null prefix page at a pinned GPU copy of its contents."""
blocks = self.req_to_blocks.get(request_id)
if blocks is None or block_idx >= len(blocks) or not blocks[block_idx].is_null:
return False
blocks[block_idx] = block
return True
def get_resident_page(self, request_id: str, block_idx: int) -> KVCacheBlock | None:
blocks = self.req_to_blocks.get(request_id)
if blocks is None or block_idx >= len(blocks):
return None
block = blocks[block_idx]
return None if block.is_null else block
def get_manager_for_kv_cache_spec(
kv_cache_spec: KVCacheSpec,
max_in_flight_tokens: int,
max_model_len: int,
role: str | None = None,
**kwargs,
) -> SingleTypeKVCacheManager:
"""
@@ -2212,7 +2601,7 @@ def get_manager_for_kv_cache_spec(
Returns:
An instance of the appropriate SingleTypeKVCacheManager subclass
"""
manager_class = KVCacheSpecRegistry.get_manager_class(kv_cache_spec)
manager_class = KVCacheSpecRegistry.get_manager_class(kv_cache_spec, role)
assert manager_class is not None, (
f"No manager registered for KVCacheSpec {type(kv_cache_spec)}"
)
@@ -2224,7 +2613,7 @@ def get_manager_for_kv_cache_spec(
# FullAttentionSpec sizing without a separate admission cap.
if isinstance(
kv_cache_spec,
(SlidingWindowSpec, ChunkedLocalAttentionSpec),
(SlidingWindowSpec, ChunkedLocalAttentionSpec, HiSparseResidentSpec),
):
kwargs["max_admission_blocks_per_request"] = (
kv_cache_spec.max_admission_blocks_per_request(
@@ -2238,11 +2627,24 @@ def get_manager_for_kv_cache_spec(
def register_all_kvcache_specs(vllm_config):
"""Built-in spec registration"""
KVCacheSpecRegistry.register_role_manager(
KVCacheGroupRole.HISPARSE_SOURCE, HiSparseSourceManager
)
KVCacheSpecRegistry.register(
FullAttentionSpec,
FullAttentionManager,
uniform_type_base_spec=FullAttentionSpec,
)
KVCacheSpecRegistry.register(
HiSparseHotSpec,
HiSparseHotManager,
uniform_type_base_spec=HiSparseHotSpec,
)
KVCacheSpecRegistry.register(
HiSparseResidentSpec,
HiSparseResidentManager,
uniform_type_base_spec=HiSparseResidentSpec,
)
KVCacheSpecRegistry.register(
SlidingWindowSpec,
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
+277
View File
@@ -0,0 +1,277 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Worker-side wiring of HiSparse caches to attention layers."""
from collections.abc import Mapping
from copy import copy
from typing import TYPE_CHECKING, Any
import torch
from vllm.config import VllmConfig
from vllm.v1.hisparse.layout import (
HISPARSE_HOT_SUFFIX,
HISPARSE_RESIDENT_SUFFIX,
)
from vllm.v1.hisparse.runtime import (
HiSparseCacheHandle,
HiSparseHostPool,
initialize_hisparse_runtime_buffers,
release_pinned_state,
)
from vllm.v1.kv_cache_interface import (
HiSparseHotSpec,
HiSparseResidentSpec,
KVCacheConfig,
KVCacheLayout,
KVCacheSpec,
MLAAttentionSpec,
UniformTypeKVCacheSpecs,
create_kv_cache_views,
)
from vllm.v1.worker.utils import allocate_kv_cache, select_common_block_size
if TYPE_CHECKING:
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.v1.worker.gpu.block_table import BlockTables
def resolve_hisparse_block_size(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
attn_layers: Mapping[str, "AttentionLayerBase"],
) -> None:
"""Resolve a common kernel block size in-place for HiSparse MLA specs."""
if vllm_config.attention_config.hisparse_config is None:
return
mla_specs = {
name: spec
for name, spec in kv_cache_spec.items()
if isinstance(spec, MLAAttentionSpec)
}
if not mla_specs:
return
block_sizes = {spec.block_size for spec in mla_specs.values()}
if len(block_sizes) != 1:
raise ValueError("HiSparse requires one scheduler block size.")
backends = [attn_layers[name].get_attn_backend() for name in mla_specs]
try:
block_size = select_common_block_size(block_sizes.pop(), backends)
except ValueError as error:
raise ValueError(
"HiSparse requires a GPU block size supported by every sparse "
f"attention and indexer backend: {error}"
) from error
kv_cache_spec.update(
(name, spec.copy_with_new_block_size(block_size))
for name, spec in mla_specs.items()
)
def allocate_hisparse_kv_caches(
kv_cache_config: KVCacheConfig,
device: torch.device,
layout: KVCacheLayout,
kernel_block_sizes: list[int],
host_pool: HiSparseHostPool,
) -> dict[str, torch.Tensor]:
"""Allocate the host pool separately from the shared device backing."""
device_config = copy(kv_cache_config)
device_config.kv_cache_tensors = [
tensor
for tensor in kv_cache_config.kv_cache_tensors
if not tensor.host_resident
]
kv_caches = allocate_kv_cache(device_config, device, layout, kernel_block_sizes)
host_tensors = [
tensor for tensor in kv_cache_config.kv_cache_tensors if tensor.host_resident
]
(host_size,) = {tensor.size for tensor in host_tensors}
backing = host_pool.allocate(host_size)
(host_group_id,) = kv_cache_config.host_group_ids
host_spec = kv_cache_config.kv_cache_groups[host_group_id].kv_cache_spec
for tensor in host_tensors:
spec = (
host_spec.kv_cache_specs[tensor.layers[0]]
if isinstance(host_spec, UniformTypeKVCacheSpecs)
else host_spec
)
kernel_block_size = kernel_block_sizes[host_group_id]
if isinstance(spec, MLAAttentionSpec) and spec.storage_block_size is not None:
kernel_block_size = spec.storage_block_size
views = create_kv_cache_views(
backing,
spec,
kv_cache_config.num_blocks_of(tensor),
layout,
tensor,
kernel_block_size=kernel_block_size,
)
kv_caches.update(zip(tensor.layers, views))
return kv_caches
def init_hisparse_kv_cache(
kv_cache_config: KVCacheConfig,
device: torch.device,
kernel_block_sizes: list[int],
vllm_config: VllmConfig,
forward_context: dict[str, Any],
block_tables: "BlockTables",
) -> dict[str, torch.Tensor]:
"""Allocate and bind HiSparse caches within the caller's allocation context."""
host_pool = HiSparseHostPool()
kv_caches = allocate_hisparse_kv_caches(
kv_cache_config,
device,
vllm_config.cache_config.get_resolved_kv_cache_layout(),
kernel_block_sizes,
host_pool,
)
cache_handles = bind_hisparse_kv_caches(
forward_context=forward_context,
kv_cache_config=kv_cache_config,
kv_caches=kv_caches,
block_tables=block_tables,
host_pool=host_pool,
)
initialize_hisparse_runtime_buffers(
cache_handles,
max_num_reqs=vllm_config.scheduler_config.max_num_seqs,
max_num_batched_tokens=vllm_config.scheduler_config.max_num_batched_tokens,
)
return kv_caches
def _get_hisparse_cache(
forward_context: dict[str, Any], layer_name: str
) -> HiSparseCacheHandle:
attention_layer = forward_context[layer_name]
hisparse_cache = attention_layer.hisparse_cache
assert hisparse_cache is not None
return hisparse_cache
def release_hisparse_profiling_cache(forward_context: dict[str, Any]) -> None:
cache_handles = [
cache
for layer in forward_context.values()
if (cache := getattr(layer, "hisparse_cache", None)) is not None
]
runtimes = {
id(cache.runtime): cache.runtime
for cache in cache_handles
if hasattr(cache.runtime, "_host_cache")
}
if not runtimes:
return
registered_pools = list(
{
runtime.registered_host_pool.data_ptr(): runtime.registered_host_pool
for runtime in runtimes.values()
}.values()
)
release_pinned_state(list(runtimes.values()), registered_pools)
for cache in cache_handles:
cache.mirror_staging_cache = None
cache.mirror_staging_slots = None
def bind_hisparse_kv_caches(
*,
forward_context: dict[str, Any],
kv_cache_config: KVCacheConfig,
kv_caches: dict[str, torch.Tensor],
block_tables: "BlockTables",
host_pool: HiSparseHostPool,
) -> list[HiSparseCacheHandle]:
"""Bind existing cache storage and block tables; return the bound handles."""
assert host_pool.registered is not None
tensor_configs = {
name: tensor_config
for tensor_config in kv_cache_config.kv_cache_tensors
for name in tensor_config.layers
}
resident_source_index = 0
for group_id, group in enumerate(kv_cache_config.kv_cache_groups):
if not isinstance(group.kv_cache_spec, HiSparseResidentSpec):
continue
for cache_name in group.layer_names:
assert cache_name.endswith(HISPARSE_RESIDENT_SUFFIX)
layer_name = cache_name[: -len(HISPARSE_RESIDENT_SUFFIX)]
tensor_config = tensor_configs[cache_name]
assert not tensor_config.host_resident
cache_handle = _get_hisparse_cache(forward_context, layer_name)
cache_handle.bind_cache(
kv_caches[cache_name],
byte_offset=tensor_config.offset,
block_stride=tensor_config.block_stride,
num_blocks=kv_cache_config.num_blocks,
block_size=group.kv_cache_spec.block_size,
block_table=block_tables.input_block_tables[group_id],
slot_mapping=block_tables.slot_mappings[group_id],
)
assert cache_handle.view is not None
kv_caches[cache_name] = cache_handle.view.cache
cache_handle.runtime.resident_source_index = resident_source_index
resident_source_index += 1
hot_backing: torch.Tensor | None = None
cache_handles: list[HiSparseCacheHandle] = []
for group_id, group in enumerate(kv_cache_config.kv_cache_groups):
if not isinstance(group.kv_cache_spec, HiSparseHotSpec):
continue
for cache_name in group.layer_names:
assert cache_name.endswith(HISPARSE_HOT_SUFFIX)
raw_tensor = kv_caches[cache_name]
if hot_backing is None:
hot_backing = raw_tensor
elif hot_backing.untyped_storage().data_ptr() != (
raw_tensor.untyped_storage().data_ptr()
):
raise RuntimeError("HiSparse hot tensors must share one GPU backing.")
layer_name = cache_name[: -len(HISPARSE_HOT_SUFFIX)]
cache_handle = _get_hisparse_cache(forward_context, layer_name)
tensor_config = tensor_configs[cache_name]
assert not tensor_config.host_resident
cache_handle.runtime.bind_hot_cache(
raw_tensor,
byte_offset=tensor_config.offset,
block_stride=tensor_config.block_stride,
num_blocks=kv_cache_config.num_blocks,
block_size=group.kv_cache_spec.block_size,
block_table=block_tables.input_block_tables[group_id],
)
resident = cache_handle.view
hot = cache_handle.runtime.hot
assert resident is not None
if (
resident.cache.untyped_storage().data_ptr()
!= hot.cache.untyped_storage().data_ptr()
or resident.cache.data_ptr() != hot.cache.data_ptr()
or resident.cache.stride() != hot.cache.stride()
):
raise RuntimeError("HiSparse resident and hot layouts must match.")
source_cache = kv_caches[layer_name]
assert source_cache.untyped_storage().data_ptr() == (
host_pool.registered.untyped_storage().data_ptr()
)
cache_handle.runtime.bind_source_cache(
source_cache,
registered_host_pool=host_pool.registered,
)
cache_handles.append(cache_handle)
# The hot slab is raw storage owned by the runtime, not a layer
# cache: nothing downstream binds or registers it.
del kv_caches[cache_name]
if hot_backing is None or not cache_handles:
raise RuntimeError("HiSparse found no hot-cache handles.")
(source_group_id,) = kv_cache_config.host_group_ids
for cache_handle in cache_handles:
cache_handle.source_block_table = block_tables.input_block_tables[
source_group_id
]
cache_handle.mirror_slot_mapping = block_tables.slot_mappings[source_group_id]
return cache_handles
+27
View File
@@ -0,0 +1,27 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.distributed.kv_events import KVCacheEvent
from vllm.v1.core.block_pool import BlockPool
class SharedEventQueueBlockPool(BlockPool):
"""A pool that publishes into another pool's live KV event queue.
The owner rebinds its queue on every drain, so this reads it through the
owner rather than holding a reference.
"""
def __init__(self, *args, event_owner: BlockPool, **kwargs) -> None:
self._event_owner = event_owner
super().__init__(*args, **kwargs)
@property
def kv_event_queue(self) -> list[KVCacheEvent]:
return self._event_owner.kv_event_queue
@kv_event_queue.setter
def kv_event_queue(self, events: list[KVCacheEvent]) -> None:
# ``BlockPool.__init__`` seeds an empty queue and ``take_events``
# swaps in a fresh one; both belong to the owner, which drains it.
assert not events
+752
View File
@@ -0,0 +1,752 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from vllm.utils.math_utils import cdiv
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.kv_cache_utils import (
BlockHashWithGroupId,
KVCacheBlock,
KVCacheBlockCopy,
)
from vllm.v1.core.single_type_kv_cache_manager import (
HiSparseHotManager,
HiSparseResidentManager,
HiSparseSourceManager,
SingleTypeKVCacheManager,
)
from vllm.v1.hisparse.types import (
SparseKVOffloadCommand,
SparseKVPageTransfer,
SparseKVRowMirror,
)
from vllm.v1.kv_cache_interface import (
HiSparseResidentSpec,
KVCacheConfig,
)
from vllm.v1.request import Request
if TYPE_CHECKING:
from vllm.v1.core.kv_cache_manager import KVCacheManager
# Sealed pages this many positions behind the block-table tail stay pinned so
# a page written by an in-flight step is never handed out under it.
_ACTIVE_TAIL_PAGES = 2
@dataclass
class _PendingPublication:
request: Request
num_computed_tokens: int
num_pages: int
retention_interval: int | None
replay_boundaries: Sequence[int]
@dataclass
class _HiSparseRequestState:
"""Residency bookkeeping for one request.
A resident page moves through three states: dirty (only the GPU copy
exists), clean (``valid_pages``: the host copy is complete) and unpinned
(``unpinned_pages``: clean, and its allocation reference was released so
the pool may reuse it). ``pinned_clean`` tracks clean pages still holding
their reference, which only happens before the request can read from host.
"""
valid_pages: set[int] = field(default_factory=set)
ready_prefix_pages: int = 0
pending_pages: dict[int, int] = field(default_factory=dict)
publication: _PendingPublication | None = None
copies_recorded_blocks: int = 0
pinned_clean: set[int] = field(default_factory=set)
unpinned_pages: set[int] = field(default_factory=set)
@dataclass
class _PendingSpill:
transfer_id: int
page: tuple[str, int]
request_state: _HiSparseRequestState
host_block: KVCacheBlock
resident_blocks: tuple[KVCacheBlock, ...]
expected_worker_completions: int = 0
worker_completions: int = 0
enqueue_applied: bool = False
class HiSparseCoordinator:
"""Own HiSparse host allocation, host publication, spills, and GPU residency.
GPU-resident pages are a write-back cache of the host tier. Once a page's
host copy is durable and its owner can read from host (it has, or has
asked for, a hot region), the page's allocation reference is released with
``BlockPool.unpin_blocks``: the block stays in the block table and keeps
being read, but the pool counts it as free and may hand it out, at which
point the owner's page is nulled and its block table republished.
"""
def __init__(
self,
kv_cache_config: KVCacheConfig,
managers: tuple[SingleTypeKVCacheManager, ...],
max_model_len: int,
) -> None:
self.managers = managers
self.max_model_len = max_model_len
groups = kv_cache_config.kv_cache_groups
resident_managers: list[HiSparseResidentManager] = []
hot_managers: list[HiSparseHotManager] = []
resident_group_ids: list[int] = []
for group_id, (group, manager) in enumerate(zip(groups, managers)):
if isinstance(group.kv_cache_spec, HiSparseResidentSpec):
if not isinstance(manager, HiSparseResidentManager):
raise TypeError(
"HiSparse resident specs require resident cache managers."
)
resident_managers.append(manager)
resident_group_ids.append(group_id)
assert not group.host_resident
if isinstance(manager, HiSparseHotManager):
hot_managers.append(manager)
assert not group.host_resident
if isinstance(manager, (HiSparseHotManager, HiSparseResidentManager)):
manager.coordinator = self
self.resident_managers = tuple(resident_managers)
self.hot_managers = tuple(hot_managers)
self.host_manager: HiSparseSourceManager | None = None
self.host_group_id: int | None = None
self.max_spill_pages = 0
for group_id, manager in enumerate(managers):
if isinstance(manager, HiSparseSourceManager):
if self.host_manager is not None:
raise ValueError("Only one HiSparse host group is supported.")
num_host_blocks = kv_cache_config.hisparse_host_num_blocks
if num_host_blocks is None:
raise ValueError("HiSparse host group needs host capacity.")
self.host_group_id = group_id
self.host_manager = manager
manager.coordinator = self
manager.bind_host_pool(num_host_blocks)
self.has_host_cache = self.host_manager is not None
self.gpu_pool: BlockPool | None = None
self.transition_watermark = 0
if self.resident_managers:
assert self.host_manager is not None
assert self.host_group_id is not None
if self.host_group_id > min(resident_group_ids):
raise ValueError("HiSparse host group must precede resident groups.")
resident_block_sizes = {
manager.block_size for manager in self.resident_managers
}
if len(resident_block_sizes) != 1:
raise ValueError(
"HiSparse resident cache groups must use one block size."
)
resident_block_size = resident_block_sizes.pop()
if self.host_manager.block_size != resident_block_size:
raise ValueError("HiSparse host and resident block sizes must match.")
self.max_spill_pages = max_model_len // resident_block_size
self.gpu_pool = self.resident_managers[0].block_pool
# Requests start reading from host once the shared pool runs this
# low, so admissions find evictable pages rather than pinned ones.
hot_cost = sum(manager.blocks_per_request for manager in hot_managers)
self.transition_watermark = max(hot_cost, kv_cache_config.num_blocks // 10)
# Host copies handed to the worker, by destination block id, until it
# reports having run them.
self._retained_copies: dict[int, tuple[KVCacheBlock, KVCacheBlock]] = {}
# request -> prefix length an external load is still filling in.
self._pending_imports: dict[str, int] = {}
self.block_table_updates: set[str] = set()
self.spills_to_send: list[SparseKVPageTransfer] = []
self.pending_spills: dict[int, _PendingSpill] = {}
self.request_states: dict[str, _HiSparseRequestState] = {}
self.next_spill_id = 0
# Published host block hash -> GPU copies of that page, readable until
# the pool reuses them. Lets a host prefix hit come back GPU-resident.
self.copies: dict[BlockHashWithGroupId, tuple[KVCacheBlock, ...]] = {}
self._copy_by_block: dict[int, BlockHashWithGroupId] = {}
# Unpinned GPU block id -> (request, page) pairs still reading it.
self._owners: dict[int, set[tuple[str, int]]] = {}
def _get_request_state(self, request_id: str) -> _HiSparseRequestState:
state = self.request_states.get(request_id)
if state is None:
state = _HiSparseRequestState()
self.request_states[request_id] = state
return state
def commit_computed_blocks(self, request_id: str, num_host_pages: int) -> None:
"""Account for a prefix hit on host pages the request now references."""
if not self.resident_managers or self.host_manager is None:
return
host_blocks = self.host_manager.req_to_blocks.get(request_id, ())
num_host_pages = min(num_host_pages, len(host_blocks))
if num_host_pages == 0:
return
state = self._get_request_state(request_id)
state.valid_pages.update(range(num_host_pages))
state.ready_prefix_pages = max(num_host_pages, state.ready_prefix_pages)
self._adopt_copies(request_id, state, host_blocks[:num_host_pages])
state.copies_recorded_blocks = max(state.copies_recorded_blocks, num_host_pages)
def take_host_block_copies(self) -> tuple[KVCacheBlockCopy, ...]:
"""Drain host copy-on-write work, retaining both endpoints.
The worker runs the copies in the step that carries them, so the
endpoints are released when that step's output comes back.
"""
if self.host_manager is None:
return ()
pairs = self.host_manager.take_host_cow_copies()
for source_block, cow_block in pairs:
self._retained_copies[cow_block.block_id] = (source_block, cow_block)
return tuple(
KVCacheBlockCopy(
src_block_id=source_block.block_id,
dst_block_id=cow_block.block_id,
)
for source_block, cow_block in pairs
)
def release_completed_host_copies(self, dst_block_ids: Iterable[int]) -> None:
"""Release the endpoints of host copies the worker reports having run."""
blocks: list[KVCacheBlock] = []
for dst_block_id in dst_block_ids:
pair = self._retained_copies.pop(dst_block_id, None)
if pair is not None:
blocks.extend(pair)
if not blocks:
return
assert self.host_manager is not None
self.host_manager.block_pool.free_blocks(reversed(blocks))
def get_host_block_pool(self) -> BlockPool | None:
manager = self.host_manager
return manager.block_pool if manager is not None else None
# ------------------------------------------------------------------
# GPU copies of published host pages
# ------------------------------------------------------------------
def _adopt_copies(
self,
request_id: str,
state: _HiSparseRequestState,
host_blocks: Sequence[KVCacheBlock],
) -> None:
"""Point null prefix pages at readable GPU copies of their contents.
Runs after the hit length is fully reconciled, so copy hits and misses
can be scattered per page without affecting the prefix hit.
"""
if not self.copies:
return
for host_idx, host_block in enumerate(host_blocks):
if host_block.is_null or host_block.block_hash is None:
continue
blocks = self.copies.get(host_block.block_hash)
if blocks is None:
continue
for manager, block in zip(self.resident_managers, blocks):
if manager.adopt_resident_page(request_id, host_idx, block):
manager.block_pool.touch([block])
state.pinned_clean.add(host_idx)
def _record_copies(self, request_id: str, num_computed_tokens: int) -> None:
"""Index the GPU copies of just-published host blocks for later hits."""
if not self.resident_managers:
return
assert self.host_manager is not None
host_blocks = self.host_manager.req_to_blocks.get(request_id)
if not host_blocks:
return
state = self._get_request_state(request_id)
num_host_blocks = min(
num_computed_tokens // self.host_manager.block_size, len(host_blocks)
)
for host_idx in range(state.copies_recorded_blocks, num_host_blocks):
host_block = host_blocks[host_idx]
if host_block.is_null or host_block.block_hash is None:
continue
blocks: list[KVCacheBlock] = []
for manager in self.resident_managers:
block = manager.get_resident_page(request_id, host_idx)
if block is None:
break
blocks.append(block)
if len(blocks) != len(self.resident_managers):
continue
self._drop_copy(host_block.block_hash)
self.copies[host_block.block_hash] = tuple(blocks)
for block in blocks:
self._copy_by_block[block.block_id] = host_block.block_hash
state.copies_recorded_blocks = max(
state.copies_recorded_blocks, num_host_blocks
)
def _drop_copy(self, host_hash: BlockHashWithGroupId) -> None:
blocks = self.copies.pop(host_hash, None)
if blocks is None:
return
for block in blocks:
self._copy_by_block.pop(block.block_id, None)
# ------------------------------------------------------------------
# Residency: pinning, unpinning and losing pages
# ------------------------------------------------------------------
def _can_read_from_host(self, request_id: str) -> bool:
"""Whether resident pages may be dropped under the request."""
return bool(self.hot_managers) and all(
manager.has_hot(request_id) for manager in self.hot_managers
)
def _resident_page_blocks(
self, request_id: str, page_idx: int
) -> list[KVCacheBlock] | None:
blocks: list[KVCacheBlock] = []
for manager in self.resident_managers:
req_blocks = manager.req_to_blocks.get(request_id)
if (
req_blocks is None
or page_idx >= len(req_blocks) - _ACTIVE_TAIL_PAGES
or req_blocks[page_idx].is_null
):
return None
blocks.append(req_blocks[page_idx])
return blocks
def _unpin_page(
self, request_id: str, state: _HiSparseRequestState, page_idx: int
) -> bool:
if page_idx in state.pending_pages or page_idx not in state.valid_pages:
return False
blocks = self._resident_page_blocks(request_id, page_idx)
if blocks is None:
return False
for manager, block in zip(self.resident_managers, blocks):
self._owners.setdefault(block.block_id, set()).add((request_id, page_idx))
manager.block_pool.unpin_blocks([block], self._on_block_reused)
state.pinned_clean.discard(page_idx)
state.unpinned_pages.add(page_idx)
return True
def _unpin_clean_pages(self, request_id: str, state: _HiSparseRequestState) -> None:
for page_idx in sorted(state.pinned_clean):
self._unpin_page(request_id, state, page_idx)
def _page_became_clean(
self, request_id: str, state: _HiSparseRequestState, page_idx: int
) -> None:
state.pinned_clean.add(page_idx)
if self._can_read_from_host(request_id):
self._unpin_page(request_id, state, page_idx)
def _on_block_reused(self, block: KVCacheBlock) -> None:
host_hash = self._copy_by_block.get(block.block_id)
if host_hash is not None:
self._drop_copy(host_hash)
for request_id, page_idx in self._owners.pop(block.block_id, ()):
self._lose_page(request_id, page_idx)
def _lose_page(self, request_id: str, page_idx: int) -> None:
state = self.request_states.get(request_id)
if state is None:
return
for manager in self.resident_managers:
blocks = manager.req_to_blocks.get(request_id)
if blocks is None or page_idx >= len(blocks) or blocks[page_idx].is_null:
continue
block = blocks[page_idx]
blocks[page_idx] = manager._null_block
owners = self._owners.get(block.block_id)
if owners is not None:
owners.discard((request_id, page_idx))
state.unpinned_pages.discard(page_idx)
self.block_table_updates.add(request_id)
for hot_manager in self.hot_managers:
hot_manager.require_hot(request_id)
def update_residency(self, request_id: str) -> None:
"""Per-step residency policy for a scheduled request.
A request that can read from host releases every clean sealed page to
the pool. One that cannot keeps its pages pinned until the shared pool
runs low, then asks for a hot region. Pages remain pinned until that region
is allocated on a subsequent scheduling pass.
"""
if not self.resident_managers:
return
state = self._get_request_state(request_id)
if not self._can_read_from_host(request_id):
assert self.gpu_pool is not None
if self.gpu_pool.get_num_free_blocks() >= self.transition_watermark:
return
for manager in self.hot_managers:
manager.require_hot(request_id)
return
self._unpin_clean_pages(request_id, state)
# ------------------------------------------------------------------
# Host publication and spills
# ------------------------------------------------------------------
def plan_prefix_materialization(
self, request_id: str, num_computed_tokens: int
) -> None:
"""Eagerly write back every sealed page that has no host copy yet."""
if not self.resident_managers:
return
assert self.host_manager is not None
host_block_size = self.host_manager.block_size
num_pages = num_computed_tokens // host_block_size
state = self._get_request_state(request_id)
budget = max(self.max_spill_pages - len(self.spills_to_send), 0)
for page_idx in range(num_pages):
if budget == 0:
break
if page_idx in state.pending_pages:
continue
if page_idx in state.valid_pages:
continue
if not all(
manager.get_resident_page(request_id, page_idx) is not None
for manager in self.resident_managers
):
continue
if self._plan_spill(request_id, page_idx, after_forward=True):
budget -= 1
def publish_when_ready(
self,
request: Request,
num_computed_tokens: int,
retention_interval: int | None,
*,
replay_boundaries: Sequence[int],
) -> None:
"""Publish host-source hashes only after their pages are durable."""
manager = self.host_manager
if manager is None:
return
num_pages = num_computed_tokens // manager.block_size
request_id = request.request_id
state = self._get_request_state(request_id)
if state.ready_prefix_pages >= num_pages:
manager.publish_blocks(
request,
num_computed_tokens,
retention_interval=retention_interval,
replay_boundaries=replay_boundaries,
)
self._record_copies(request_id, num_computed_tokens)
state.publication = None
return
state.publication = _PendingPublication(
request=request,
num_computed_tokens=num_computed_tokens,
num_pages=num_pages,
retention_interval=retention_interval,
replay_boundaries=replay_boundaries,
)
def _publish_host_blocks_if_ready(self, request_id: str) -> None:
state = self.request_states.get(request_id)
if state is None:
return
publication = state.publication
if publication is None or state.ready_prefix_pages < publication.num_pages:
return
assert self.host_manager is not None
self.host_manager.publish_blocks(
publication.request,
publication.num_computed_tokens,
retention_interval=publication.retention_interval,
replay_boundaries=publication.replay_boundaries,
)
self._record_copies(request_id, publication.num_computed_tokens)
state.publication = None
def record_pending_host_import(self, request_id: str, num_tokens: int) -> None:
"""Note a prefix an external load is populating in host pages."""
self._pending_imports[request_id] = num_tokens
def finish_host_import(self, request_id: str, *, failed: bool) -> None:
num_tokens = self._pending_imports.pop(request_id, None)
if num_tokens is not None and not failed:
self.complete_host_import(request_id, num_tokens)
def complete_host_import(self, request_id: str, num_computed_tokens: int) -> None:
"""Publish externally populated host pages after connector completion."""
if not self.resident_managers:
return
block_size = self.resident_managers[0].block_size
num_pages = num_computed_tokens // block_size
state = self._get_request_state(request_id)
state.valid_pages = set(range(num_pages))
state.ready_prefix_pages = num_pages
self._publish_host_blocks_if_ready(request_id)
def _plan_spill(
self,
request_id: str,
page_idx: int,
*,
after_forward: bool,
) -> bool:
assert self.host_manager is not None
state = self._get_request_state(request_id)
host_blocks = self.host_manager.req_to_blocks.get(request_id)
if host_blocks is None or page_idx >= len(host_blocks):
return False
host_block = host_blocks[page_idx]
if host_block.is_null:
return False
blocks: list[KVCacheBlock] = []
for manager in self.resident_managers:
block = manager.get_resident_page(request_id, page_idx)
if block is None:
return False
blocks.append(block)
self.host_manager.block_pool.touch([host_block])
for manager, block in zip(self.resident_managers, blocks):
manager.block_pool.touch([block])
spill_id = self.next_spill_id
self.next_spill_id += 1
plan = SparseKVPageTransfer(
transfer_id=spill_id,
destination_block_id=host_block.block_id,
source_block_ids=tuple(block.block_id for block in blocks),
after_forward=after_forward,
)
self.pending_spills[spill_id] = _PendingSpill(
transfer_id=spill_id,
page=(request_id, page_idx),
request_state=state,
host_block=host_block,
resident_blocks=tuple(blocks),
)
state.pending_pages[page_idx] = spill_id
self.spills_to_send.append(plan)
return True
# ------------------------------------------------------------------
# Worker-facing views
# ------------------------------------------------------------------
def build_row_mirrors(
self,
requests: Iterable[tuple[str, int, int]],
) -> tuple[SparseKVRowMirror, ...]:
"""Map scheduled rows to scheduler-owned resident and host blocks."""
if not self.resident_managers or self.host_manager is None:
return ()
block_size = self.resident_managers[0].block_size
mirrors: list[SparseKVRowMirror] = []
for request_id, num_computed_tokens, num_scheduled_tokens in requests:
host_blocks = self.host_manager.req_to_blocks.get(request_id)
resident_blocks = [
manager.req_to_blocks.get(request_id)
for manager in self.resident_managers
]
if host_blocks is None or any(blocks is None for blocks in resident_blocks):
continue
token_position = num_computed_tokens
end_position = token_position + num_scheduled_tokens
while token_position < end_position:
page_idx, row_offset = divmod(token_position, block_size)
num_rows = min(block_size - row_offset, end_position - token_position)
# A page without a GPU copy has no mirror source, and a page
# without a host block has no destination. Skip just that page:
# its neighbours in the window are still mirrorable, and a
# window only ever moves forward, so dropping them here would
# leave their host rows permanently stale.
source_starts = []
for blocks in resident_blocks:
assert blocks is not None
if page_idx >= len(blocks) or blocks[page_idx].is_null:
break
source_starts.append(
blocks[page_idx].block_id * block_size + row_offset
)
if len(source_starts) != len(resident_blocks):
token_position += num_rows
continue
host_block_idx = page_idx
if host_block_idx >= len(host_blocks):
token_position += num_rows
continue
host_block = host_blocks[host_block_idx]
if host_block.is_null:
token_position += num_rows
continue
mirrors.append(
SparseKVRowMirror(
source_starts=tuple(source_starts),
destination_start=(
host_block.block_id * block_size + row_offset
),
num_rows=num_rows,
)
)
token_position += num_rows
return tuple(mirrors)
def all_context_pages_resident(
self,
requests: Iterable[tuple[str, int, int]],
) -> bool:
"""Return whether every scheduled request can read only resident KV."""
if not self.resident_managers:
return False
block_size = self.resident_managers[0].block_size
for request_id, num_computed_tokens, num_scheduled_tokens in requests:
num_pages = cdiv(num_computed_tokens + num_scheduled_tokens, block_size)
for page_idx in range(num_pages):
if any(
manager.get_resident_page(request_id, page_idx) is None
for manager in self.resident_managers
):
return False
return True
def take_block_table_updates(self) -> dict[str, tuple[list[int], ...]]:
updates = {
request_id: tuple(
[block.block_id for block in manager.req_to_blocks.get(request_id, [])]
for manager in self.managers
)
for request_id in self.block_table_updates
}
self.block_table_updates.clear()
return updates
def build_offload_command(self) -> SparseKVOffloadCommand | None:
"""Package residency decisions for the worker connector."""
if not self.resident_managers:
return None
command = SparseKVOffloadCommand(page_transfers=self.spills_to_send)
self.spills_to_send = []
return command
def has_pending_reclamation(self) -> bool:
"""Whether an in-flight spill will free GPU blocks on completion."""
return any(
pending.page[0] in self.request_states
and self._can_read_from_host(pending.page[0])
for pending in self.pending_spills.values()
)
def has_pending_work(self) -> bool:
return bool(self.spills_to_send or self.pending_spills or self._retained_copies)
def update_spills(
self,
enqueued_counts: Mapping[int, int],
completed_counts: Mapping[int, int],
) -> None:
for spill_id, count in enqueued_counts.items():
pending = self.pending_spills.get(spill_id)
if pending is not None and pending.expected_worker_completions == 0:
pending.expected_worker_completions = count
for spill_id, count in completed_counts.items():
pending = self.pending_spills.get(spill_id)
if pending is not None:
pending.worker_completions += count
self._apply_enqueued_spills()
self._complete_host_writes()
def _apply_enqueued_spills(self) -> None:
"""Drop the DMA pins once the worker has enqueued a spill."""
for pending in self.pending_spills.values():
if (
pending.enqueue_applied
or not pending.expected_worker_completions
or pending.worker_completions < pending.expected_worker_completions
):
continue
for manager, block in zip(self.resident_managers, pending.resident_blocks):
manager.block_pool.free_blocks([block])
pending.enqueue_applied = True
def _complete_host_writes(self) -> None:
completed = [
pending
for pending in self.pending_spills.values()
if pending.enqueue_applied
and pending.expected_worker_completions
and pending.worker_completions >= pending.expected_worker_completions
]
completed_request_ids: set[str] = set()
for pending in completed:
self.pending_spills.pop(pending.transfer_id, None)
request_id, page_idx = pending.page
pending.request_state.pending_pages.pop(page_idx, None)
if self.request_states.get(request_id) is pending.request_state:
pending.request_state.valid_pages.add(page_idx)
self._page_became_clean(request_id, pending.request_state, page_idx)
completed_request_ids.add(request_id)
assert self.host_manager is not None
self.host_manager.block_pool.free_blocks([pending.host_block])
for request_id in completed_request_ids:
state = self.request_states[request_id]
while state.ready_prefix_pages in state.valid_pages:
state.ready_prefix_pages += 1
self._publish_host_blocks_if_ready(request_id)
def free(self, request_id: str) -> None:
"""Detach the request; its clean pages stay readable copies in the pool."""
self._pending_imports.pop(request_id, None)
state = self.request_states.pop(request_id, None)
if state is None:
return
for manager in self.resident_managers:
blocks = manager.req_to_blocks.get(request_id)
if not blocks:
continue
for page_idx, block in enumerate(blocks):
if block.is_null:
continue
if page_idx in state.unpinned_pages:
owners = self._owners.get(block.block_id)
if owners is not None:
owners.discard((request_id, page_idx))
elif (
page_idx in state.valid_pages
and page_idx not in state.pending_pages
):
manager.block_pool.unpin_blocks([block], self._on_block_reused)
else:
continue
blocks[page_idx] = manager._null_block
def get_hisparse_coordinator(
kv_cache_manager: "KVCacheManager",
) -> HiSparseCoordinator:
"""Return the coordinator shared by a KV cache manager's HiSparse groups.
Built on first call and memoised on the HiSparse managers it binds itself
to. Must run before the first request is admitted.
"""
managers = tuple(kv_cache_manager.coordinator.single_type_managers)
for manager in managers:
coordinator = getattr(manager, "coordinator", None)
if coordinator is not None:
assert isinstance(coordinator, HiSparseCoordinator)
return coordinator
coordinator = HiSparseCoordinator(
kv_cache_manager.kv_cache_config, managers, kv_cache_manager.max_model_len
)
if coordinator.host_manager is None:
raise ValueError("No HiSparse cache group is configured.")
return coordinator
+345
View File
@@ -0,0 +1,345 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import defaultdict
from dataclasses import dataclass
from typing import cast
from vllm.config import VllmConfig
from vllm.config.kv_transfer import hisparse_host_pool_gib
from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv
from vllm.v1.hisparse.runtime import ResolvedHiSparseConfig
from vllm.v1.kv_cache_interface import (
HiSparseHotSpec,
HiSparseResidentSpec,
KVCacheConfig,
KVCacheGroupRole,
KVCacheGroupSpec,
KVCacheSpec,
KVCacheTensor,
MLAAttentionSpec,
SparseCacheRole,
UniformTypeKVCacheSpecs,
compute_layout_strides,
)
from vllm.v1.kv_cache_layout import KVCacheLayout
logger = init_logger(__name__)
HISPARSE_HOT_SUFFIX = ".hisparse_hot"
HISPARSE_RESIDENT_SUFFIX = ".hisparse_resident"
@dataclass(frozen=True)
class HiSparseLayout:
source_group: KVCacheGroupSpec
device_groups: list[KVCacheGroupSpec]
host_num_blocks: int
def get_hisparse_kv_cache_groups(
vllm_config: VllmConfig, kv_cache_spec: dict[str, KVCacheSpec]
) -> list[KVCacheGroupSpec] | None:
attention_config = getattr(vllm_config, "attention_config", None)
if attention_config is None or attention_config.hisparse_config is None:
return None
mla_specs: dict[str, KVCacheSpec] = {
name: spec
for name, spec in kv_cache_spec.items()
if isinstance(spec, MLAAttentionSpec)
}
other_specs = {
name: spec
for name, spec in kv_cache_spec.items()
if not isinstance(spec, MLAAttentionSpec)
}
if not mla_specs or not other_specs:
return None
from vllm.v1.core.kv_cache_utils import get_kv_cache_groups
mla_group_spec = UniformTypeKVCacheSpecs.from_specs(mla_specs)
assert mla_group_spec is not None
mla_group = KVCacheGroupSpec(list(mla_specs), mla_group_spec)
return [mla_group, *get_kv_cache_groups(vllm_config, other_specs)]
def get_hisparse_host_pool_bytes(vllm_config: VllmConfig) -> int:
host_pool_gib = hisparse_host_pool_gib(vllm_config.kv_transfer_config)
if host_pool_gib is None:
raise ValueError("HiSparse requires HiSparseConnector with host_pool_gib")
return int(host_pool_gib * 2**30)
def _partition_hisparse_specs(
groups: list[KVCacheGroupSpec],
) -> tuple[dict[str, MLAAttentionSpec], dict[str, MLAAttentionSpec]]:
group_spec = groups[0].kv_cache_spec
if not isinstance(group_spec, UniformTypeKVCacheSpecs):
raise ValueError("HiSparse requires uniform sparse-MLA cache specs.")
specs = group_spec.kv_cache_specs
if any(
isinstance(spec, MLAAttentionSpec) and spec.model_version == "deepseek_v4"
for spec in specs.values()
):
raise ValueError("HiSparse does not support DeepSeek V4.")
if not all(isinstance(spec, MLAAttentionSpec) for spec in specs.values()):
raise ValueError("HiSparse requires its first cache group to contain MLA only.")
source_specs = {
name: spec
for name, spec in specs.items()
if isinstance(spec, MLAAttentionSpec)
and spec.cache_role is SparseCacheRole.SPARSE
}
indexer_specs = {
name: spec
for name, spec in specs.items()
if isinstance(spec, MLAAttentionSpec)
and spec.cache_role is SparseCacheRole.INDEXER
}
if not source_specs or not indexer_specs:
raise ValueError("HiSparse requires sparse-MLA and indexer cache specs.")
return source_specs, indexer_specs
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:]
)
def create_hisparse_layout(
vllm_config: VllmConfig,
groups: list[KVCacheGroupSpec],
host_budget: int,
) -> HiSparseLayout:
source_specs, indexer_specs = _partition_hisparse_specs(groups)
block_sizes = {
spec.block_size for spec in (*source_specs.values(), *indexer_specs.values())
}
if len(block_sizes) != 1:
raise ValueError("HiSparse requires one resolved GPU block size.")
gpu_block_size = block_sizes.pop()
config = ResolvedHiSparseConfig.from_vllm_config(
vllm_config,
vllm_config.model_config.hf_config.index_topk,
gpu_block_size,
)
assert config is not None
indexer_group_spec = UniformTypeKVCacheSpecs.from_specs(
cast(dict[str, KVCacheSpec], indexer_specs)
)
assert indexer_group_spec is not None
indexer_group = KVCacheGroupSpec(
list(indexer_specs),
indexer_group_spec,
enable_kv_transfer=True,
role=KVCacheGroupRole.HISPARSE_INDEXER,
)
indexer_page = sum(spec.page_size_bytes for spec in indexer_specs.values())
hot_blocks_per_request = cdiv(config.device_buffer_size, gpu_block_size)
hot_units: list[list[tuple[str, MLAAttentionSpec]]] = []
for layer_name, layer_spec in source_specs.items():
if layer_spec.is_index_group_leader or not hot_units:
hot_units.append([])
hot_units[-1].append((f"{layer_name}{HISPARSE_HOT_SUFFIX}", layer_spec))
resident_groups: list[KVCacheGroupSpec] = []
hot_groups: list[KVCacheGroupSpec] = []
def append_hot_group(layers: list[tuple[str, MLAAttentionSpec]]) -> None:
page_sizes = {spec.page_size_bytes for _, spec in layers}
if len(page_sizes) != 1:
raise ValueError(
"HiSparse hot-cache groups require one page size, got "
f"{sorted(page_sizes)}."
)
page_size = page_sizes.pop()
names = [name for name, _ in layers]
resident_groups.append(
KVCacheGroupSpec(
[
name[: -len(HISPARSE_HOT_SUFFIX)] + HISPARSE_RESIDENT_SUFFIX
for name in names
],
HiSparseResidentSpec(
block_size=gpu_block_size,
page_size=page_size,
),
enable_kv_transfer=False,
)
)
hot_groups.append(
KVCacheGroupSpec(
names,
HiSparseHotSpec(
block_size=gpu_block_size,
page_size=page_size,
blocks_per_request=hot_blocks_per_request,
),
enable_kv_transfer=False,
)
)
current: list[tuple[str, MLAAttentionSpec]] = []
current_page = 0
for unit in hot_units:
unit_page = sum(spec.page_size_bytes for _, spec in unit)
if current and current_page + unit_page > indexer_page:
append_hot_group(current)
current = []
current_page = 0
current.extend(unit)
current_page += unit_page
if current:
append_hot_group(current)
source_group_spec = UniformTypeKVCacheSpecs.from_specs(
cast(dict[str, KVCacheSpec], source_specs)
)
assert source_group_spec is not None
source_group = KVCacheGroupSpec(
list(source_specs),
source_group_spec,
role=KVCacheGroupRole.HISPARSE_SOURCE,
host_resident=True,
enable_kv_transfer=True,
)
regular_groups = groups[1:]
gpu_groups = [indexer_group, *resident_groups, *hot_groups, *regular_groups]
host_num_blocks = host_budget // sum(
spec.page_size_bytes for spec in source_specs.values()
)
if host_num_blocks <= 0:
raise ValueError("HiSparse has no allocatable host blocks.")
return HiSparseLayout(
source_group=source_group,
device_groups=gpu_groups,
host_num_blocks=host_num_blocks,
)
def _build_hisparse_kv_cache_tensors(
kv_cache_groups: list[KVCacheGroupSpec],
num_blocks: int,
size: int,
layout: KVCacheLayout,
bytes_per_block: int,
*,
host_resident: bool = False,
) -> list[KVCacheTensor]:
interleaved_block_stride = bytes_per_block if layout.is_block_outermost else None
tensors: list[KVCacheTensor] = []
for group in kv_cache_groups:
group_spec = group.kv_cache_spec
layers_by_spec: defaultdict[KVCacheSpec, list[str]] = defaultdict(list)
if isinstance(group_spec, UniformTypeKVCacheSpecs):
for layer_name, spec in group_spec.kv_cache_specs.items():
layers_by_spec[spec].append(layer_name)
elif group.layer_names:
layers_by_spec[group_spec].extend(group.layer_names)
byte_offset = 0
for spec, layer_names in layers_by_spec.items():
if isinstance(spec, (HiSparseHotSpec, HiSparseResidentSpec)):
if not layout.is_block_outermost:
raise ValueError("HiSparse requires a block-outermost KV layout.")
layer_stride = spec.page_size_bytes
block_stride = bytes_per_block
else:
layer_stride, block_stride, _, _, _ = compute_layout_strides(
spec,
num_blocks,
len(layer_names),
layout,
fixed_strides=(None, interleaved_block_stride, None, None, None),
)
offset = (
byte_offset
* max(layer_stride, spec.page_size_bytes)
// spec.page_size_bytes
)
tensors.append(
KVCacheTensor(
size=size,
layers=layer_names,
layer_stride=layer_stride,
block_stride=block_stride,
offset=offset,
host_resident=host_resident,
)
)
byte_offset += len(layer_names) * spec.page_size_bytes
return tensors
def get_hisparse_kv_cache_config(
vllm_config: VllmConfig,
kv_cache_groups: list[KVCacheGroupSpec],
available_memory: int,
host_budget: int,
) -> KVCacheConfig:
from vllm.v1.core.kv_cache_utils import (
_get_kv_cache_bytes_per_block,
may_override_num_blocks,
validate_kv_cache_layout,
)
hisparse_layout = create_hisparse_layout(vllm_config, kv_cache_groups, host_budget)
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)
num_blocks = may_override_num_blocks(
vllm_config, available_memory // bytes_per_block
)
size = bytes_per_block * num_blocks
kv_cache_tensors = _build_hisparse_kv_cache_tensors(
device_groups, num_blocks, size, layout, bytes_per_block
)
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_size = host_bytes_per_block * hisparse_layout.host_num_blocks
kv_cache_tensors[:0] = _build_hisparse_kv_cache_tensors(
host_groups,
hisparse_layout.host_num_blocks,
host_size,
host_layout,
host_bytes_per_block,
host_resident=True,
)
logger.info_once(
"HiSparse HMA: %.1f GiB host source (%d blocks), %.1f GiB shared "
"GPU indexer/resident/hot pool (%d blocks).",
host_size / 2**30,
hisparse_layout.host_num_blocks,
size / 2**30,
num_blocks,
)
return KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=kv_cache_tensors,
kv_cache_groups=[*host_groups, *device_groups],
hisparse_host_num_blocks=hisparse_layout.host_num_blocks,
prefix_cache_retention_interval=(
vllm_config.cache_config.prefix_cache_retention_interval
),
)
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
@dataclass(frozen=True)
class SparseKVPageTransfer:
"""Copy one logical KV page between cache-manager and worker-owned tiers."""
transfer_id: int
destination_block_id: int
source_block_ids: tuple[int, ...]
after_forward: bool
@dataclass(frozen=True)
class SparseKVRowMirror:
"""Mirror one contiguous resident-row span into the host cache."""
source_starts: tuple[int, ...]
destination_start: int
num_rows: int
@dataclass
class SparseKVOffloadCommand:
"""Opaque scheduler-to-worker command for one model step."""
page_transfers: list[SparseKVPageTransfer]
+154 -3
View File
@@ -147,6 +147,11 @@ class KVCacheSpecKind(str, Enum):
UNKNOWN = "unknown"
class SparseCacheRole(str, Enum):
SPARSE = "sparse"
INDEXER = "indexer"
@dataclass(frozen=True)
class KVCacheSpec:
"""
@@ -192,6 +197,10 @@ class KVCacheSpec:
return kernel_block_size // self.tokens_per_state
return 1
@property
def block_table_token_alignment(self) -> int | None:
return 128
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
"""
The maximum possible memory usage of this KV cache in bytes.
@@ -245,6 +254,25 @@ class KVCacheSpec:
isinstance(spec, uniform_type_base_spec) for spec in kv_cache_specs.values()
)
@property
def has_layer_views(self) -> bool:
"""Whether generic allocation creates per-layer cache views.
Specs without a per-layer shape keep the raw backing tensor and lay it
out themselves. They also have no attention module of their own, so
they take no part in attention-backend or kernel-block selection.
"""
return True
@property
def uses_slot_mapping(self) -> bool:
"""Whether the worker computes a per-token slot mapping for this spec.
Specs that address their pages themselves (raw storage, ring buffers)
take no slot mapping row.
"""
return True
def group_kernel_blocks(cache: torch.Tensor, num_blocks: int) -> torch.Tensor:
"""View a kernel-block-granular layer cache with manager blocks as dim 0.
@@ -383,6 +411,70 @@ def create_kv_cache_views(
return views
@dataclass(frozen=True, kw_only=True)
class HiSparseHotSpec(KVCacheSpec):
"""Ephemeral per-request HiSparse hot-cache allocation."""
page_size: int
blocks_per_request: int
@property
def prefix_cacheable(self) -> bool:
return False
@property
def page_size_bytes(self) -> int:
return self.page_size
@property
def block_table_token_alignment(self) -> int | None:
return None
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
return self.blocks_per_request * self.page_size
def max_num_blocks_per_req(self, vllm_config: VllmConfig, max_len: int) -> int:
return self.blocks_per_request
@property
def has_layer_views(self) -> bool:
return False
@property
def uses_slot_mapping(self) -> bool:
return False
@dataclass(frozen=True, kw_only=True)
class HiSparseResidentSpec(KVCacheSpec):
"""Reclaimable GPU-resident pages for host-backed HiSparse KV."""
page_size: int
@property
def prefix_cacheable(self) -> bool:
return False
@property
def page_size_bytes(self) -> int:
return self.page_size
def max_admission_blocks_per_request(
self, max_in_flight_tokens: int, max_model_len: int
) -> int:
num_tokens = min(max_in_flight_tokens, max_model_len)
return cdiv(num_tokens, self.block_size)
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
return cdiv(vllm_config.model_config.max_model_len, self.block_size) * (
self.page_size
)
@property
def has_layer_views(self) -> bool:
return False
@dataclass(frozen=True, kw_only=True)
class AttentionSpec(KVCacheSpec):
num_kv_heads: int
@@ -557,6 +649,8 @@ class MLAAttentionSpec(FullAttentionSpec):
# 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
cache_role: SparseCacheRole = SparseCacheRole.SPARSE
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."""
# Group capability enabled when any member flattens a non-causal query block
@@ -577,16 +671,20 @@ class MLAAttentionSpec(FullAttentionSpec):
cache_dtype_str_set = set(spec.cache_dtype_str for spec in specs)
tokens_per_state_set = set(spec.tokens_per_state for spec in specs)
model_version_set = set(spec.model_version for spec in specs)
cache_role_set = {spec.cache_role for spec in specs}
index_group_leader_set = {spec.is_index_group_leader for spec in specs}
storage_block_size_set = set(spec.storage_block_size for spec in specs)
assert (
len(cache_dtype_str_set) == 1
and len(tokens_per_state_set) == 1
and len(model_version_set) == 1
and len(cache_role_set) == 1
and len(index_group_leader_set) == 1
and len(storage_block_size_set) == 1
), (
"All attention layers in the same KV cache group must use the same "
"quantization method, tokens per state, model version, and storage "
"block size."
"quantization method, tokens per state, model version, cache role, "
"index-sharing role, and storage block size."
)
merged_spec = cls(
block_size=specs[0].block_size,
@@ -600,6 +698,8 @@ class MLAAttentionSpec(FullAttentionSpec):
cache_dtype_str=cache_dtype_str_set.pop(),
tokens_per_state=tokens_per_state_set.pop(),
model_version=model_version_set.pop(),
cache_role=cache_role_set.pop(),
is_index_group_leader=index_group_leader_set.pop(),
storage_block_size=storage_block_size_set.pop(),
non_causal_multi_token_decode=any(
spec.non_causal_multi_token_decode for spec in specs
@@ -772,6 +872,10 @@ class CircularBufferSpec(AttentionSpec):
reads the open group's committed keys from the ring.
"""
@property
def block_table_token_alignment(self) -> int | None:
return None
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
# The ring occupies one block per request for its whole lifetime.
del vllm_config
@@ -792,6 +896,10 @@ class CircularBufferSpec(AttentionSpec):
def prefix_cacheable(self) -> bool:
return False
@property
def uses_slot_mapping(self) -> bool:
return False
@dataclass(frozen=True, kw_only=True)
class SlidingWindowMLASpec(SlidingWindowSpec):
@@ -919,6 +1027,10 @@ class MambaSpec(KVCacheSpec):
return self.page_size_padded
return page_size
@property
def block_table_token_alignment(self) -> int | None:
return None
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
if vllm_config.cache_config.mamba_cache_mode == "all":
max_model_len = vllm_config.model_config.max_model_len
@@ -1093,6 +1205,10 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
def page_size_bytes(self) -> int:
return sum(spec.page_size_bytes for spec in self.kv_cache_specs.values())
@property
def block_table_token_alignment(self) -> int | None:
return self.first_spec.block_table_token_alignment
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
max_num_pages = max(
cdiv(spec.max_memory_usage_bytes(vllm_config), spec.page_size_bytes)
@@ -1154,6 +1270,10 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
for spec in self.kv_cache_specs.values()
)
@property
def uses_slot_mapping(self) -> bool:
return self.first_spec.uses_slot_mapping
def iter_layer_specs(kv_cache_spec: KVCacheSpec) -> Collection[KVCacheSpec]:
"""The per-layer specs a KV cache group spec covers.
@@ -1259,6 +1379,13 @@ class KVCacheTensor:
layer_stride: int
block_stride: int
offset: int = 0 # byte offset of layers[0]'s block 0
host_resident: bool = False
class KVCacheGroupRole(str, Enum):
DEFAULT = "default"
HISPARSE_SOURCE = "hisparse_source"
HISPARSE_INDEXER = "hisparse_indexer"
@dataclass
@@ -1274,8 +1401,13 @@ class KVCacheGroupSpec:
kv_cache_spec: KVCacheSpec
# Whether this group contains EAGLE/MTP draft attention layers.
is_eagle_group: bool = False
# Host groups use the dedicated HiSparse pool; others share the device pool.
host_resident: bool = False
# Whether this group is part of the externally transferable KV state.
# Ephemeral accelerator-side replicas are rebuilt from their transferable
# source group after a connector load.
enable_kv_transfer: bool = True
role: KVCacheGroupRole = KVCacheGroupRole.DEFAULT
@dataclass
@@ -1300,6 +1432,8 @@ class KVCacheConfig:
"""Resolved retention policy for local prefix-cache checkpoints."""
kv_cache_layout: str | None = None
"""The KV cache layout resolved by the engine core, adopted by all workers."""
hisparse_host_num_blocks: int | None = None
"""Capacity of the dedicated HiSparse host-block manager, when enabled."""
@cached_property
def transfer_group_ids(self) -> tuple[int, ...]:
@@ -1337,6 +1471,21 @@ class KVCacheConfig:
)
return tuple(block_ids[group_id] for group_id in self.transfer_group_ids)
@property
def host_group_ids(self) -> tuple[int, ...]:
return tuple(
group_id
for group_id, group in enumerate(self.kv_cache_groups)
if group.host_resident
)
def num_blocks_of(self, tensor: KVCacheTensor) -> int:
"""Number of blocks addressable by the pool backing ``tensor``."""
if not tensor.host_resident:
return self.num_blocks
assert self.hisparse_host_num_blocks is not None
return self.hisparse_host_num_blocks
@property
def has_mamba_layers(self) -> bool:
return any(
@@ -1347,9 +1496,11 @@ class KVCacheConfig:
@property
def has_mixed_precision_kv_cache(self) -> bool:
"""Whether attention groups store their KV cache at more than one precision."""
"""Whether device attention caches use more than one precision."""
kv_cache_precisions: set[tuple[torch.dtype, KVQuantMode]] = set()
for group in self.kv_cache_groups:
if group.host_resident:
continue
kv_cache_precisions.update(
(spec.dtype, spec.kv_quant_mode)
for spec in iter_layer_specs(group.kv_cache_spec)
+16 -1
View File
@@ -34,6 +34,7 @@ class KVCacheSpecMetadata:
_REGISTRY_KVCACHESPEC_LIST: dict[type["KVCacheSpec"], KVCacheSpecMetadata] = {}
_REGISTRY_ROLE_MANAGERS: dict[str, type["SingleTypeKVCacheManager"]] = {}
class KVCacheSpecRegistry:
@@ -102,20 +103,34 @@ class KVCacheSpecRegistry:
uniform_type_base_spec=uniform_type_base_spec,
)
@classmethod
def register_role_manager(
cls, role: str, manager_class: type["SingleTypeKVCacheManager"]
) -> None:
"""Select ``manager_class`` for every group with the given role."""
registered = _REGISTRY_ROLE_MANAGERS.get(role)
assert registered is None or registered is manager_class, (
f"Conflicting manager registration for group role {role}"
)
_REGISTRY_ROLE_MANAGERS[role] = manager_class
@classmethod
def get_manager_class(
cls, kvcache_spec: "KVCacheSpec"
cls, kvcache_spec: "KVCacheSpec", role: str | None = None
) -> type["SingleTypeKVCacheManager"] | None:
"""
Get the single type kvcache manager class for a given kvcache spec instance.
Args:
kvcache_spec: A KVCacheSpec instance
role: The group's role; a role-registered manager takes precedence.
Returns:
The SingleTypeKVCacheManager class to use for this kvcache_spec
"""
cls._ensure_registered()
if role is not None and (manager_class := _REGISTRY_ROLE_MANAGERS.get(role)):
return manager_class
kvcache_spec_cls = type(kvcache_spec)
# Walk up the MRO to find a registered base class
+2
View File
@@ -14,6 +14,8 @@ class OffloadingGroupConfig:
tokens_per_block: int
# Layer names belonging to this group.
layer_names: tuple[str, ...]
# Original KVCacheConfig group index.
group_id: int
@dataclass(frozen=True)
+4
View File
@@ -281,6 +281,9 @@ class KVConnectorOutput:
# IDs of externally computed KV blocks that failed to load.
# Requests referencing these blocks should be rescheduled to recompute them
invalid_block_ids: set[int] = field(default_factory=set)
# Receive failures keyed by request identity. This remains unambiguous for
# hybrid/multi-pool cache layouts where numeric block IDs overlap.
failed_recving: set[str] = field(default_factory=set)
# Configuration describing how many finished sending/receiving
# notifications should be expected for each request. This allows
# handshake-based connectors like Nixl to update the KVOutputAggregator.
@@ -295,6 +298,7 @@ class KVConnectorOutput:
and not self.kv_connector_stats
and not self.kv_cache_events
and not self.invalid_block_ids
and not self.failed_recving
and not self.kv_connector_worker_meta
)
+36 -11
View File
@@ -18,6 +18,10 @@ from vllm.v1.attention.backend import (
CommonAttentionMetadata,
)
from vllm.v1.attention.backends.utils import create_fast_prefill_custom_backend
from vllm.v1.hisparse.binding import (
init_hisparse_kv_cache,
resolve_hisparse_block_size,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheConfig,
@@ -30,11 +34,12 @@ from vllm.v1.worker.utils import (
AttentionGroup,
add_kv_sharing_layers_to_kv_cache_groups,
allocate_kv_cache,
bind_kv_cache,
bind_kv_cache_to_layers,
prepare_kernel_block_sizes,
)
if TYPE_CHECKING:
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.cudagraph_utils import (
BatchExecutionDescriptor,
CudaGraphManager,
@@ -132,6 +137,7 @@ def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]:
if isinstance(spec, AttentionSpec):
spec = attn_module.get_attn_backend().customize_spec(spec)
kv_cache_spec[layer_name] = spec
resolve_hisparse_block_size(vllm_config, kv_cache_spec, attn_layers)
return kv_cache_spec
@@ -198,6 +204,9 @@ def init_attn_backend(
kv_cache_config.kv_cache_groups
):
layer_names = kv_cache_group_spec.layer_names
if not kv_cache_group_spec.kv_cache_spec.has_layer_views:
attn_groups.append([])
continue
if active_layer_names is not None:
layer_names = list(active_layer_names.intersection(layer_names))
@@ -316,22 +325,34 @@ def get_query_lens_mismatch_unsupported_backend(
def init_kv_cache(
runner_kv_caches: list[torch.Tensor | list[torch.Tensor]],
forward_context: dict[str, Any],
kv_cache_config: KVCacheConfig,
device: torch.device,
kernel_block_sizes: list[int],
vllm_config: VllmConfig,
kv_cache_allocation_context: AbstractContextManager | None = None,
*,
block_tables: "BlockTables | None" = None,
) -> dict[str, Any]:
allocation_context = kv_cache_allocation_context or nullcontext()
with allocation_context:
kv_caches = allocate_kv_cache(
kv_cache_config,
device,
vllm_config.cache_config.get_resolved_kv_cache_layout(),
kernel_block_sizes,
)
if vllm_config.attention_config.hisparse_config is not None:
assert block_tables is not None
kv_caches = init_hisparse_kv_cache(
kv_cache_config,
device,
kernel_block_sizes,
vllm_config,
forward_context,
block_tables,
)
else:
kv_caches = allocate_kv_cache(
kv_cache_config,
device,
vllm_config.cache_config.get_resolved_kv_cache_layout(),
kernel_block_sizes,
)
for layer_name, target in get_shared_kv_cache_layers(vllm_config).items():
kv_caches[layer_name] = kv_caches[target]
# Dual-attention models (e.g. LongCat-Flash) put two Attention modules per
@@ -342,10 +363,12 @@ def init_kv_cache(
in ("longcat_flash", "longcat_flash_ngram")
else 1
)
bind_kv_cache(
kv_caches,
bindable_caches = {
name: cache for name, cache in kv_caches.items() if name in forward_context
}
bind_kv_cache_to_layers(
bindable_caches,
forward_context,
runner_kv_caches,
num_attn_module,
kv_cache_groups=kv_cache_config.kv_cache_groups,
)
@@ -396,6 +419,8 @@ def build_attn_metadata(
attn_metadata: dict[str, Any] = {}
num_kv_cache_groups = len(kv_cache_config.kv_cache_groups)
for i in range(num_kv_cache_groups):
if not attn_groups[i]:
continue
block_table = block_tables[i]
slot_mapping = slot_mappings[i]
# Per-group causal for hybrid drafters (mixed SWA/full attention).
+2
View File
@@ -34,6 +34,7 @@ from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from vllm.utils.math_utils import round_up
from vllm.utils.torch_utils import current_stream
from vllm.v1.hisparse.binding import release_hisparse_profiling_cache
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.spec_decode.dynamic.utils import build_dynamic_sd_schedule_lookup
from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer
@@ -931,6 +932,7 @@ def _teardown_profiling_state(runner: "GPUModelRunner") -> None:
if (model := getattr(runner, "model", None)) is not None:
layers = itertools.chain(layers, model.modules())
clear_layer_kv_caches(layers)
release_hisparse_profiling_cache(runner.compilation_config.static_forward_context)
runner.cache_config.num_gpu_blocks = None
runner.maybe_remove_all_loras(runner.lora_config)
gc.collect()
+31 -15
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
import torch
@@ -29,7 +29,10 @@ if TYPE_CHECKING:
class KVConnector:
"""KVConnector interface used by GPUModelRunner."""
def pre_forward(self, scheduler_output: "SchedulerOutput") -> None:
def pre_forward(self, scheduler_output: "SchedulerOutput", **kwargs: Any) -> None:
pass
def finish_forward(self) -> None:
pass
def post_forward(
@@ -43,6 +46,9 @@ class KVConnector:
def set_disabled(self, disabled: bool) -> None:
pass
def reset_capture_state(self) -> None:
pass
class ActiveKVConnector(KVConnector):
def __init__(
@@ -54,10 +60,10 @@ class ActiveKVConnector(KVConnector):
self.kv_connector.register_kv_caches(kv_caches_dict)
self.kv_connector.set_host_xfer_buffer_ops(copy_kv_blocks)
self._pending_load_start = False
self._pending_load_kwargs: dict[str, Any] | None = None
self._disabled = False
def pre_forward(self, scheduler_output: "SchedulerOutput") -> None:
def pre_forward(self, scheduler_output: "SchedulerOutput", **kwargs: Any) -> None:
if self._disabled:
return
@@ -65,23 +71,31 @@ class ActiveKVConnector(KVConnector):
assert kv_connector_metadata is not None
self.kv_connector.handle_preemptions(kv_connector_metadata)
self.kv_connector.bind_connector_metadata(kv_connector_metadata)
self._pending_load_kwargs = kwargs
if scheduler_output.has_sync_kv_loads:
# Sync loads need to run before this step's forward.
self._start_load_kv()
else:
# Start any async loads in post-forward instead, keeping
# their host-side submission cost off the critical path.
self._pending_load_start = True
# Otherwise start the async load after forward to keep submission
# off the critical path.
def _start_load_kv(self) -> None:
self._pending_load_start = False
load_kwargs = self._pending_load_kwargs
assert load_kwargs is not None
self._pending_load_kwargs = None
# TODO: sort out KV Connectors' use of forward_context
if is_forward_context_available():
self.kv_connector.start_load_kv(get_forward_context())
self.kv_connector.start_load_kv(get_forward_context(), **load_kwargs)
else:
with set_forward_context(None, self.vllm_config):
self.kv_connector.start_load_kv(get_forward_context())
self.kv_connector.start_load_kv(get_forward_context(), **load_kwargs)
def finish_forward(self) -> None:
if not self._disabled:
self.kv_connector.finish_forward()
def reset_capture_state(self) -> None:
self.kv_connector.reset_capture_state()
def post_forward(
self, finished_req_ids: set[str], wait_for_save: bool = True
@@ -89,15 +103,16 @@ class ActiveKVConnector(KVConnector):
if self._disabled:
return None
if self._pending_load_start:
if self._pending_load_kwargs is not None:
self._start_load_kv()
output = KVConnectorOutput()
if wait_for_save:
self.kv_connector.wait_for_save()
output.finished_sending, output.finished_recving = (
self.kv_connector.get_finished(finished_req_ids)
)
transfer_results = self.kv_connector.get_transfer_results(finished_req_ids)
output.finished_sending = transfer_results.finished_sending or None
output.finished_recving = transfer_results.finished_recving or None
output.failed_recving = transfer_results.failed_recving
output.invalid_block_ids = self.kv_connector.get_block_ids_with_load_errors()
output.kv_connector_stats = self.kv_connector.get_kv_connector_stats()
output.kv_cache_events = self.kv_connector.get_kv_connector_kv_cache_events()
@@ -112,6 +127,7 @@ class ActiveKVConnector(KVConnector):
return EMPTY_MODEL_RUNNER_OUTPUT
self.pre_forward(scheduler_output)
self.finish_forward()
finished_req_ids = scheduler_output.finished_req_ids
kv_connector_output = self.post_forward(finished_req_ids, wait_for_save=False)
return ModelRunnerOutput.with_kv_conn_output_only(kv_connector_output)
+29 -13
View File
@@ -67,7 +67,6 @@ from vllm.utils.mem_utils import DeviceMemoryProfiler, format_gib
from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE
from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput
from vllm.v1.kv_cache_interface import (
CircularBufferSpec,
KVCacheConfig,
MambaSpec,
UniformTypeKVCacheSpecs,
@@ -590,7 +589,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
layer_spec = (
spec.first_spec if isinstance(spec, UniformTypeKVCacheSpecs) else spec
)
slot_mapping_enabled.append(not isinstance(layer_spec, CircularBufferSpec))
slot_mapping_enabled.append(layer_spec.uses_slot_mapping)
# Let each cache type account for CP. Attention KV is DCP-sharded,
# while Mamba/GDN recurrent state is replicated across DCP ranks.
max_num_blocks = spec.max_num_blocks_per_req(
@@ -598,12 +597,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
# Preserve each cache type's alignment requirements after applying
# its topology-aware block-table width.
if isinstance(layer_spec, (MambaSpec, CircularBufferSpec)):
max_num_blocks = get_block_table_width(
max_num_blocks, spec.block_size, token_alignment=None
)
else:
max_num_blocks = get_block_table_width(max_num_blocks, spec.block_size)
max_num_blocks = get_block_table_width(
max_num_blocks,
spec.block_size,
token_alignment=spec.block_table_token_alignment,
)
max_num_blocks_per_group.append(max_num_blocks)
target_attn_layer_names = None
@@ -722,18 +720,20 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# to its own attention support.
self.speculator.init_cudagraph_manager(cudagraph_mode)
self.kv_caches: list[torch.Tensor] = []
# Capture warmup providers that depend on allocated KV-cache strides.
with self.jit_warmup_registry.activate():
kv_caches_dict = init_kv_cache(
self.kv_caches,
self.compilation_config.static_forward_context,
self.kv_cache_config,
self.device,
self.kernel_block_sizes,
self.vllm_config,
kv_cache_allocation_context=kv_cache_allocation_context,
block_tables=self.block_tables,
)
self.kv_caches = [
cache for cache in kv_caches_dict.values() if cache.device == self.device
]
if is_profiling:
self.kv_connector = NO_OP_KV_CONNECTOR
else:
@@ -1014,6 +1014,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
):
self._dummy_run(**batch)
self.adaptive_verification.set_initial_cost_curves(timings)
self.kv_connector.reset_capture_state()
end_free_gpu_memory = torch.accelerator.get_memory_info()[0]
@@ -1141,13 +1142,17 @@ class GPUModelRunner(LoRAModelRunnerMixin):
def update_requests(self, scheduler_output: SchedulerOutput) -> None:
# Add new blocks and update num_computed_tokens for the existing requests.
reqs = scheduler_output.scheduled_cached_reqs
table_updates = scheduler_output.block_table_updates or {}
for req_id, block_ids in table_updates.items():
if (idx := self.req_states.req_id_to_index.get(req_id)) is not None:
self.block_tables.append_block_ids(idx, block_ids, overwrite=True)
num_computed_tokens_np = self.req_states.num_computed_tokens_np
for req_id, num_computed_tokens, req_new_block_ids in zip(
reqs.req_ids, reqs.num_computed_tokens, reqs.new_block_ids
):
req_index = self.req_states.req_id_to_index[req_id]
num_computed_tokens_np[req_index] = num_computed_tokens
if req_new_block_ids is not None:
if req_new_block_ids is not None and req_id not in table_updates:
self.block_tables.append_block_ids(
req_index, req_new_block_ids, overwrite=False
)
@@ -1841,13 +1846,22 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
self.step_timing.forward_start()
connector_kwargs = dict(
scheduler_output=scheduler_output,
request_state_indices=input_batch.idx_mapping,
request_ids=input_batch.req_ids,
num_tokens=input_batch.num_tokens,
)
# Run model.
if batch_desc.cg_mode == CUDAGraphMode.FULL:
# Use explicit cudagraph replay for FULL mode.
# NOTE(woosuk): Here, we don't need to pass the input tensors,
# because they are already copied to the CUDA graph input buffers.
assert self.cudagraph_manager is not None
self.kv_connector.pre_forward(scheduler_output)
self.kv_connector.pre_forward(
**connector_kwargs, attn_metadata=attn_metadata
)
model_output = self.cudagraph_manager.run_fullgraph(batch_desc)
else:
# For piecewise and eager mode, just call model().
@@ -1871,7 +1885,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
skip_compiled=skip_compiled,
is_padding=input_batch.is_padding,
):
self.kv_connector.pre_forward(scheduler_output)
self.kv_connector.pre_forward(**connector_kwargs)
if ubatch_state is not None:
assert self.ubatch_runner is not None
model_output = self.ubatch_runner.run(
@@ -1889,6 +1903,8 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# Eager (NONE): call the raw model directly.
model_output = self.model(**model_inputs)
self.kv_connector.finish_forward()
if self.is_last_pp_rank:
if self.use_aux_hidden_state_outputs:
assert isinstance(model_output, tuple)
+10
View File
@@ -224,10 +224,20 @@ def warmup_kernels(
# fixed draft counts here, then restore the manager for capture and serving.
adaptive_verification = model_runner.adaptive_verification
model_runner.adaptive_verification = None
rejection_sampler = model_runner.rejection_sampler
adaptive_sampling = (
rejection_sampler is not None and rejection_sampler.enable_adaptive_verification
)
if adaptive_sampling:
assert rejection_sampler is not None
rejection_sampler.enable_adaptive_verification = False
try:
_warmup_kernels(model_runner, worker_execute_model, worker_sample_tokens)
finally:
model_runner.adaptive_verification = adaptive_verification
if adaptive_sampling:
assert rejection_sampler is not None
rejection_sampler.enable_adaptive_verification = True
def _warmup_kernels(
@@ -94,9 +94,12 @@ class KVConnectorModelRunnerMixin:
if wait_for_save and not defer_finalize:
kv_connector.wait_for_save()
output.finished_sending, output.finished_recving = (
kv_connector.get_finished(scheduler_output.finished_req_ids)
transfer_results = kv_connector.get_transfer_results(
scheduler_output.finished_req_ids
)
output.finished_sending = transfer_results.finished_sending
output.finished_recving = transfer_results.finished_recving
output.failed_recving = transfer_results.failed_recving
output.invalid_block_ids = kv_connector.get_block_ids_with_load_errors()
output.kv_connector_stats = kv_connector.get_kv_connector_stats()
+36 -25
View File
@@ -166,6 +166,8 @@ class KVBlockZeroer:
kv = static_forward_context[layer_name].kv_cache
if not isinstance(kv, torch.Tensor):
continue
if kv.device.type != self.device.type:
continue
dp = kv.data_ptr()
assert kv.shape[0] % num_blocks == 0, (
@@ -366,32 +368,22 @@ def select_common_block_size(
return False
return True
# Case 1: if the block_size of kv cache manager is supported by all backends,
# return it directly.
if block_size_is_supported(backends, kv_manager_block_size):
return kv_manager_block_size
# Case 2: otherwise, the block_size must be an `int`-format supported size of
# at least one backend. Iterate over all `int`-format supported sizes in
# descending order and return the first one that is supported by all backends.
# Simple proof:
# If the supported size b is in MultipleOf(x_i) format for all attention
# backends i, and b a factor of kv_manager_block_size, then
# kv_manager_block_size also satisfies MultipleOf(x_i) for all i. We will
# return kv_manager_block_size in case 1.
all_int_supported_sizes = set(
supported_size
# MultipleOf constraints also accept the manager size if they accept a divisor.
# Any remaining candidate must therefore be an explicit size from a backend.
candidates = {
size
for backend in backends
for supported_size in backend.get_supported_kernel_block_sizes()
if isinstance(supported_size, int)
)
for size in backend.get_supported_kernel_block_sizes()
if isinstance(size, int) and kv_manager_block_size % size == 0
}
for supported_size in sorted(all_int_supported_sizes, reverse=True):
if kv_manager_block_size % supported_size != 0:
continue
if block_size_is_supported(backends, supported_size):
return supported_size
raise ValueError(f"No common block size for {kv_manager_block_size}. ")
for size in sorted(candidates, reverse=True):
if block_size_is_supported(backends, size):
return size
raise ValueError(f"No common block size for {kv_manager_block_size}.")
def allocate_kv_cache(
@@ -440,7 +432,11 @@ def allocate_kv_cache(
if isinstance(spec, UniformTypeKVCacheSpecs):
spec = spec.kv_cache_specs[layer_name]
num_blocks = kv_cache_config.num_blocks
if not spec.has_layer_views:
kv_caches.update((name, buf) for name in tensor.layers)
continue
num_blocks = kv_cache_config.num_blocks_of(tensor)
kernel_block_size = None
if kernel_block_sizes is not None and group_id < len(kernel_block_sizes):
kernel_block_size = kernel_block_sizes[group_id]
@@ -485,7 +481,9 @@ def prepare_kernel_block_sizes(
kv_cache_spec = next(iter(kv_cache_spec.kv_cache_specs.values()))
if isinstance(kv_cache_spec, EncoderOnlyAttentionSpec):
continue
if isinstance(kv_cache_spec, AttentionSpec):
if not kv_cache_spec.has_layer_views:
kernel_block_sizes.append(kv_cache_spec.block_size)
elif isinstance(kv_cache_spec, AttentionSpec):
# This is an attention backend that supports virtual block splitting.
kv_manager_block_size = kv_cache_group.kv_cache_spec.block_size
group_backends = [g.backend for g in attn_groups[kv_cache_gid]]
@@ -621,7 +619,6 @@ def bind_kv_cache(
for layer_name in kv_caches:
index2name[extract_layer_index(layer_name, num_attn_module)].append(layer_name)
ordered_layer_names: list[str] = []
for layer_index in sorted(index2name.keys()):
layer_names = index2name[layer_index]
if len(layer_names) > 1:
@@ -635,8 +632,19 @@ def bind_kv_cache(
current_platform.check_runner_kv_caches_multi_layer()
for layer_name in layer_names:
runner_kv_caches.append(kv_caches[layer_name])
ordered_layer_names.append(layer_name)
bind_kv_cache_to_layers(
kv_caches, forward_context, num_attn_module, kv_cache_groups
)
def bind_kv_cache_to_layers(
kv_caches: dict[str, torch.Tensor],
forward_context: dict[str, Attention],
num_attn_module: int = 1,
kv_cache_groups: Sequence[KVCacheGroupSpec] | None = None,
) -> None:
"""Bind layer caches and share ReplaySSM trackers in model-layer order."""
# Bind kv_caches to forward context. Each layer's bind_kv_cache unpacks
# its raw allocation into the per-layer view(s) it needs (e.g. Mamba
# splits conv/ssm), so the kv_caches dict can hold a single tensor per
@@ -644,6 +652,9 @@ def bind_kv_cache(
for layer_name, kv_cache in kv_caches.items():
forward_context[layer_name].bind_kv_cache(kv_cache)
ordered_layer_names = sorted(
kv_caches, key=lambda name: extract_layer_index(name, num_attn_module)
)
share_replayssm_ring_trackers(ordered_layer_names, forward_context, kv_cache_groups)