Merge remote-tracking branch 'upstream/main' into patches

This commit is contained in:
2026-09-28 12:06:52 +07:00
170 changed files with 7605 additions and 1142 deletions
+7 -8
View File
@@ -870,15 +870,14 @@ class AttentionImplBase(ABC, Generic[T]):
def __new__(cls, *args, **kwargs):
# use __new__ so that all subclasses will call this
self = super().__new__(cls)
try:
from vllm.distributed.parallel_state import get_dcp_group
from vllm.config import get_current_vllm_config_or_none
from vllm.distributed.parallel_state import get_dcp_world_size_and_rank
self.dcp_world_size = get_dcp_group().world_size
self.dcp_rank = get_dcp_group().rank_in_group
except AssertionError:
# DCP might not be initialized in testing
self.dcp_world_size = 1
self.dcp_rank = 0
# Replicated drafts run at DCP=1 inside a DCP target's process group.
config = get_current_vllm_config_or_none()
self.dcp_world_size, self.dcp_rank = get_dcp_world_size_and_rank(
config is None or config.parallel_config.decode_context_parallel_size > 1
)
try:
from vllm.distributed.parallel_state import get_pcp_group
+7 -10
View File
@@ -60,7 +60,10 @@ from vllm.config import (
get_layers_from_vllm_config,
)
from vllm.config.cache import CacheDType
from vllm.distributed.parallel_state import get_dcp_group
from vllm.distributed.parallel_state import (
get_dcp_group,
get_dcp_world_size_and_rank,
)
from vllm.logger import init_logger
from vllm.platforms.interface import DeviceCapability
from vllm.utils.math_utils import cdiv, round_up
@@ -726,15 +729,9 @@ class FlashAttentionMetadataBuilder(AttentionMetadataBuilder[FlashAttentionMetad
num_qo_heads=self.num_heads_q,
)
try:
from vllm.distributed.parallel_state import get_dcp_group
self.dcp_world_size = get_dcp_group().world_size
self.dcp_rank = get_dcp_group().rank_in_group
except AssertionError:
# DCP might not be initialized in testing
self.dcp_world_size = 1
self.dcp_rank = 0
self.dcp_world_size, self.dcp_rank = get_dcp_world_size_and_rank(
kv_cache_spec.dcp_sharded
)
# Fused draft decode reuses the captured metadata object across draft
# steps. For DCP, build-time host-side decisions such as
+29 -27
View File
@@ -30,7 +30,10 @@ from vllm.config import (
get_current_vllm_config_or_none,
)
from vllm.config.cache import CacheDType
from vllm.distributed.parallel_state import get_dcp_group
from vllm.distributed.parallel_state import (
get_dcp_group,
get_dcp_world_size_and_rank,
)
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.utils.quant_utils import (
QuantKey,
@@ -641,6 +644,7 @@ class FlashInferTrtllmAPIDecode:
@dataclass
class FlashInferMetadata:
kv_cache_layout: KVCacheLayout
num_actual_tokens: int
"""Total number of tokens in the batch (excluding padding)."""
@@ -696,6 +700,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
self.cache_config = vllm_config.cache_config
self.model_config = vllm_config.model_config
self.attention_config = vllm_config.attention_config
self._num_speculative_tokens = vllm_config.num_speculative_tokens
self._workspace_buffer = None
self._prefill_wrapper: (
BatchPrefillWithPagedKVCacheWrapper | BatchDCPPrefillWrapper | None
@@ -747,17 +752,12 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
self._decode_cudagraph_max_bs,
self.compilation_config.max_cudagraph_capture_size,
)
try:
self.dcp_world_size = get_dcp_group().world_size
self.dcp_rank = get_dcp_group().rank_in_group
self.dcp_kv_cache_interleave_size = (
vllm_config.parallel_config.cp_kv_cache_interleave_size
)
except AssertionError:
# DCP might not be initialized in testing
self.dcp_world_size = 1
self.dcp_rank = 0
self.dcp_kv_cache_interleave_size = 1
self.dcp_world_size, self.dcp_rank = get_dcp_world_size_and_rank(
kv_cache_spec.dcp_sharded
)
self.dcp_kv_cache_interleave_size = (
vllm_config.parallel_config.cp_kv_cache_interleave_size
)
self.use_dcp = self.dcp_world_size > 1
self.dcp_a2a = (
self.use_dcp and vllm_config.parallel_config.dcp_comm_backend == "a2a"
@@ -1424,6 +1424,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
# Leave prefill/decode/cascade_wrapper empty, to be populated
# case by case depending on the batch contents and backend selection.
attn_metadata = FlashInferMetadata(
kv_cache_layout=self.kv_cache_layout,
num_actual_tokens=num_actual_tokens,
slot_mapping=common_attn_metadata.slot_mapping,
q_data_type_prefill=self.q_data_type_prefill,
@@ -1446,8 +1447,15 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
# (block_tables, seq_lens) directly.
needs_seq_lens_cpu = self.use_dcp or use_cascade or not all_uses_trtllm
if needs_seq_lens_cpu:
with gpu_sync_allowed():
seq_lens_cpu = common_attn_metadata.seq_lens.cpu()
if (
self._num_speculative_tokens == 0
and common_attn_metadata.seq_lens_cpu_upper_bound is not None
):
# No speculative token accounting, so the upper bound is exact.
seq_lens_cpu = common_attn_metadata.seq_lens_cpu_upper_bound
else:
with gpu_sync_allowed():
seq_lens_cpu = common_attn_metadata.seq_lens.cpu()
else:
seq_lens_cpu = None
@@ -1904,8 +1912,6 @@ class FlashInferImpl(AttentionImpl):
num_heads, num_kv_heads, is_prefill=False
)
vllm_config = get_current_vllm_config_or_none()
# The layout is resolved after model construction, so read it lazily.
self.cache_config = vllm_config.cache_config if vllm_config else None
# Query pre-quantization needs a single dtype for the whole query tensor.
# SM90 XQA needs BF16/FP16-Q for decode and FP8 for prefill,
# so only enable this for SM100 trtllm-gen where both use FP8-Q.
@@ -1941,11 +1947,6 @@ class FlashInferImpl(AttentionImpl):
else:
self.dcp_combine = partial(cp_lse_ag_out_rs, is_lse_base_on_e=False)
@property
def kv_cache_layout(self) -> KVCacheLayout:
assert self.cache_config is not None
return self.cache_config.get_resolved_kv_cache_layout()
def fused_output_quant_supported(self, quant_key: QuantKey):
if quant_key == kNvfp4Dynamic and self.is_kvcache_nvfp4:
logger.warning_once(
@@ -2111,6 +2112,7 @@ class FlashInferImpl(AttentionImpl):
# performance to make sure it does not introduce any overhead.
num_actual_tokens = attn_metadata.num_actual_tokens
kv_cache_layout = attn_metadata.kv_cache_layout
# FlashInfer treats uint8 KV cache as NVFP4. vLLM stores FP8 KV cache
# as uint8 bytes, so pass FP8 caches with their logical dtype.
@@ -2134,7 +2136,7 @@ class FlashInferImpl(AttentionImpl):
if attn_metadata.use_cascade:
# Cascade attention (rare case).
assert attn_metadata.cascade_wrapper is not None
stride_order = self.kv_cache_layout.layer_view_order
stride_order = kv_cache_layout.layer_view_order
if self.is_kvcache_nvfp4:
kv_cache_views = tuple(
cache.permute(*stride_order)
@@ -2154,7 +2156,7 @@ class FlashInferImpl(AttentionImpl):
num_decode_tokens = attn_metadata.num_decode_tokens
num_prefill_tokens = attn_metadata.num_prefill_tokens
stride_order = self.kv_cache_layout.layer_view_order
stride_order = kv_cache_layout.layer_view_order
kv_cache_permute = kv_cache.permute(*stride_order) # HND and contiguous
# Fix degenerate strides on any size-1 dimension (e.g. num_kv_heads=1
# with TP=8). PyTorch permits non-canonical strides on size-1 dims;
@@ -2311,7 +2313,7 @@ class FlashInferImpl(AttentionImpl):
seq_lens_prefill = attn_metadata.prefill.seq_lens
# This path needs to be enabled with VLLM_KV_CACHE_LAYOUT = HND
assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
assert get_flashinfer_layout_string(kv_cache_layout) == "HND"
assert is_strictly_contiguous(prefill_query)
assert is_strictly_contiguous(workspace_buffer)
assert is_strictly_contiguous(block_tables_prefill)
@@ -2501,7 +2503,7 @@ class FlashInferImpl(AttentionImpl):
# trtllm-gen needs HND layout on SM100. XQA is selected
# separately on SM90 and does not use this SM100 layout gate.
if decode_with_trtllm_gen:
assert get_flashinfer_layout_string(self.kv_cache_layout) == "HND"
assert get_flashinfer_layout_string(kv_cache_layout) == "HND"
else:
assert decode_with_xqa
assert is_strictly_contiguous(decode_query)
@@ -2547,7 +2549,7 @@ class FlashInferImpl(AttentionImpl):
window_left=self.window_left,
out=output_padded[:decode_query_tokens],
sinks=self.sinks,
kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
kv_layout=get_flashinfer_layout_string(kv_cache_layout),
q_len_per_req=q_len_per_req,
mask=attn_metadata.decode.mask,
q_cu_seq_lens=attn_metadata.decode.q_cu_seq_lens,
@@ -2614,7 +2616,7 @@ class FlashInferImpl(AttentionImpl):
sinks=self.sinks,
o_sf_scale=self.o_sf_scale,
out=out,
kv_layout=get_flashinfer_layout_string(self.kv_cache_layout),
kv_layout=get_flashinfer_layout_string(kv_cache_layout),
backend=attn_metadata.decode.kernel.value,
q_len_per_req=q_len_per_req,
max_q_len=max_q_len,
+105 -19
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Backend for GatedDeltaNet attention."""
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import Literal
import torch
@@ -60,6 +60,7 @@ class GDNAttentionMetadata:
None # shape: [batch - num_spec_decodes,]
)
spec_sequence_masks: torch.Tensor | None = None # shape: [batch,]
spec_sequence_masks_cpu: torch.Tensor | None = None # shape: [batch,]
spec_token_indx: torch.Tensor | None = None
non_spec_token_indx: torch.Tensor | None = None
@@ -114,6 +115,18 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
self.use_full_cuda_graph: bool = (
self.compilation_config.cudagraph_mode.has_full_cudagraphs()
)
# update_block_table() keeps the source group's batch-level FULL graph
# buffers, so only MRV2, which also reuses metadata at capture, may use
# it.
self.supports_update_block_table = (
vllm_config.use_v2_model_runner
and device.type == "cuda"
# Not isinstance: KDA's RecoverSSM/checkpoint metadata is per group.
and type(self) is GDNAttentionMetadataBuilder
)
if self.supports_update_block_table:
# Opts into MRV2's CUDA-only aligned-index precompute.
self.mamba_aligned_state_indices: torch.Tensor | None = None
self.decode_cudagraph_max_bs: int = (
self.vllm_config.scheduler_config.max_num_seqs * (self.num_spec + 1)
@@ -220,12 +233,16 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
query_start_loc = m.query_start_loc
query_start_loc_cpu = m.query_start_loc_cpu
nums_dict, batch_ptr, token_chunk_offset_ptr = None, None, None
block_table_tensor = mamba_get_block_table_tensor(
m.block_table_tensor,
m.seq_lens,
self.kv_cache_spec,
self.vllm_config.cache_config.mamba_cache_mode,
)
aligned_state_indices = getattr(self, "mamba_aligned_state_indices", None)
if aligned_state_indices is not None:
block_table_tensor = aligned_state_indices[: m.num_reqs]
else:
block_table_tensor = mamba_get_block_table_tensor(
m.block_table_tensor,
m.seq_lens,
self.kv_cache_spec,
self.vllm_config.cache_config.mamba_cache_mode,
)
uniform_spec_sequence_length = None
spec_sequence_masks_cpu: torch.Tensor | None = None
@@ -460,12 +477,8 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
# metadata below is indexed by request.
batch_size = m.num_reqs
if (
self.use_full_cuda_graph
and num_prefills == 0
and num_decodes == 0
and num_spec_decodes <= self.decode_cudagraph_max_bs
and num_spec_decode_tokens <= self.decode_cudagraph_max_bs
if self._stage_spec_decode(
num_prefills, num_decodes, num_spec_decodes, num_spec_decode_tokens
):
assert spec_sequence_masks is not None
self.spec_state_indices_tensor[:num_spec_decodes].copy_(
@@ -506,12 +519,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
num_accepted_tokens = self.num_accepted_tokens[:batch_size]
num_accepted_tokens[num_spec_decodes:].fill_(1)
if (
self.use_full_cuda_graph
and num_prefills == 0
and num_spec_decodes == 0
and num_decodes <= self.decode_cudagraph_max_bs
):
if self._stage_decode(num_prefills, num_decodes, num_spec_decodes):
self.non_spec_state_indices_tensor[:num_decodes].copy_(
non_spec_state_indices_tensor, non_blocking=True
)
@@ -546,6 +554,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
spec_state_indices_tensor=spec_state_indices_tensor,
non_spec_state_indices_tensor=non_spec_state_indices_tensor,
spec_sequence_masks=spec_sequence_masks,
spec_sequence_masks_cpu=spec_sequence_masks_cpu,
spec_token_indx=spec_token_indx,
non_spec_token_indx=non_spec_token_indx,
num_accepted_tokens=num_accepted_tokens,
@@ -556,6 +565,83 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
)
return attn_metadata
def _stage_spec_decode(
self,
num_prefills: int,
num_decodes: int,
num_spec_decodes: int,
num_spec_decode_tokens: int,
) -> bool:
"""Whether spec-decode metadata goes into the FULL cudagraph buffers."""
return (
self.use_full_cuda_graph
and num_prefills == 0
and num_decodes == 0
and num_spec_decodes <= self.decode_cudagraph_max_bs
and num_spec_decode_tokens <= self.decode_cudagraph_max_bs
)
def _stage_decode(
self, num_prefills: int, num_decodes: int, num_spec_decodes: int
) -> bool:
"""Whether decode metadata goes into the FULL cudagraph buffers."""
return (
self.use_full_cuda_graph
and num_prefills == 0
and num_spec_decodes == 0
and num_decodes <= self.decode_cudagraph_max_bs
)
def update_block_table(
self,
metadata: GDNAttentionMetadata,
blk_table: torch.Tensor,
slot_mapping: torch.Tensor,
) -> GDNAttentionMetadata:
"""Re-gather this group's state indices. The other fields are
batch-level and stay shared with ``metadata``."""
m = metadata
if self.vllm_config.cache_config.mamba_cache_mode == "align":
assert self.mamba_aligned_state_indices is not None
blk_table = self.mamba_aligned_state_indices
masks = m.spec_sequence_masks_cpu
spec_indices = non_spec_indices = prefill_indices = None
if masks is None:
non_spec_indices = blk_table[:, 0]
if m.num_prefills > 0:
prefill_indices = non_spec_indices[m.num_decodes :]
else:
spec_indices = blk_table[masks, : self.num_spec + 1]
if m.num_prefills > 0:
non_spec_indices = prefill_indices = blk_table[~masks, 0]
if self._stage_spec_decode(
m.num_prefills, m.num_decodes, m.num_spec_decodes, m.num_spec_decode_tokens
):
assert m.spec_state_indices_tensor is not None
batch_size = m.spec_state_indices_tensor.shape[0]
self.spec_state_indices_tensor[: m.num_spec_decodes].copy_(
spec_indices, non_blocking=True
)
spec_indices = self.spec_state_indices_tensor[:batch_size]
spec_indices[m.num_spec_decodes :].fill_(NULL_BLOCK_ID)
if self._stage_decode(m.num_prefills, m.num_decodes, m.num_spec_decodes):
assert m.non_spec_state_indices_tensor is not None
batch_size = m.non_spec_state_indices_tensor.shape[0]
self.non_spec_state_indices_tensor[: m.num_decodes].copy_(
non_spec_indices, non_blocking=True
)
non_spec_indices = self.non_spec_state_indices_tensor[:batch_size]
non_spec_indices[m.num_decodes :].fill_(NULL_BLOCK_ID)
return replace(
m,
spec_state_indices_tensor=spec_indices,
non_spec_state_indices_tensor=non_spec_indices,
prefill_state_indices=prefill_indices,
)
def build_for_cudagraph_capture(
self, common_attn_metadata: CommonAttentionMetadata
):
@@ -17,14 +17,14 @@ encoded by the indexer's selection, so ``causal=False``.
CUDA-graph handling: ``plan()`` copies its inputs to host unconditionally,
so it must stay outside graph capture. Each metadata builder owns a wrapper,
reserved capture-stable device buffers, and the plan parameters. The wrapper
bakes the per-row ``kv_len`` into its int schedule
at plan() time — ``run()`` never reads the device-side buffer — so the
metadata builder replans every step (outside capture) with exact host-side
lengths derived from the batch's sequence lengths; a full-width schedule
would send the kernel past each row's valid count into the -1 tail of the
converted index buffer (illegal address). Per-step content (top-k slots)
is written into the reserved buffers by kernels inside the captured
forward, and captured runs read the refreshed plan buffers on replay.
bakes the per-row ``kv_len`` into its int schedule at plan() time — ``run()``
never reads the device-side buffer. The builder plans (outside capture) from
sync-free host upper bounds and clamps each scheduled work item's ``kv_end``
on device to the exact valid count, so the kernel never reads past a row's
valid prefix (the -1 tail of the converted index buffer) and async scheduling
needs no D2H sync. Per-step content (top-k slots) is written into the
reserved buffers by kernels inside the captured forward, and captured runs
read the refreshed plan buffers on replay.
KV cache format: plain contiguous E4M3 ``[num_blocks, block_size, 512]``
(uint8 storage) with a per-tensor ``k_scale``; BF16 caches also work. The
@@ -63,6 +63,26 @@ from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
_FP8_KV_DTYPES = ("fp8", "fp8_e4m3")
_WORKSPACE_BYTES = 128 * 1024 * 1024
# TODO: FlashInfer bakes per-row kv_len into the plan on the host, which
# forces a D2H sync under async scheduling. The plan-info layout constants
# below and the int-workspace clamp in _SM90State work around this by
# planning from sync-free upper bounds; delete them once FlashInfer accepts
# an upper-bound plan() that clamps kv_end internally, or exposes a
# GPU-side plan API (upstream ask:
# https://github.com/flashinfer-ai/flashinfer/issues/5559, see
# vllm-project/vllm#58684).
# FlashInfer MLAPlanInfo layout (scheduler.cuh) field indices.
_PLAN_INFO_LEN = 18
_PI_NUM_BLKS_Y = 1
_PI_Q_INDPTR = 2
_PI_KV_INDPTR = 3
_PI_KV_START = 13
_PI_KV_END = 14
_PI_WORK_INDPTR = 15
# Planned lengths exceed the host upper bound by up to this many tokens so a
# plan stays reusable across draft steps and consecutive decode steps; the
# device-side clamp restores the exact lengths.
_PLAN_SLACK = 32
@triton.jit
@@ -82,6 +102,40 @@ def _pack_topk_indices(
tl.store(indices + start + cols, tl.maximum(values, 0), mask=mask)
@triton.jit
def _clamp_work_kv_end(
int_ws,
saved_kv_end,
seq_lens,
query_start_loc,
req_id_per_token,
num_works_idx,
q_indptr_off,
kv_start_off,
kv_end_off,
TOPK: tl.constexpr,
KPOOL: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
# Clamp each planned work item to its row's exact valid count, derived
# from the device batch layout exactly as the convert kernel counts it.
works = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = works < tl.load(int_ws + num_works_idx)
row = tl.load(int_ws + q_indptr_off + works, mask=mask, other=0)
req = tl.load(req_id_per_token + row, mask=mask, other=0)
seq_len = tl.load(seq_lens + req, mask=mask, other=0)
query_end = tl.load(query_start_loc + req + 1, mask=mask, other=0)
ctx = seq_len - query_end + row + 1
valid = tl.where(ctx <= TOPK, ctx, TOPK + ctx % KPOOL)
start = tl.load(int_ws + kv_start_off + works, mask=mask, other=0)
end = tl.load(saved_kv_end + works, mask=mask, other=0)
tl.store(
int_ws + kv_end_off + works,
tl.maximum(tl.minimum(end, valid), start),
mask=mask,
)
class FlashInferMLASparseSM90Backend(AttentionBackend):
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
@@ -190,6 +244,8 @@ class _SM90State:
kv_lora_rank: int,
qk_rope_head_dim: int,
sm_scale: float,
index_topk: int,
index_kpool: int,
) -> None:
from flashinfer.mla import BatchMLAPagedAttentionWrapper
@@ -202,6 +258,10 @@ class _SM90State:
self.kv_lora_rank = kv_lora_rank
self.qk_rope_head_dim = qk_rope_head_dim
self.sm_scale = sm_scale
self.index_topk = index_topk
self.index_kpool = max(index_kpool, 1)
# Largest valid count the convert kernel can produce for any context.
self.max_valid = min(self.index_topk + self.index_kpool - 1, topk_width)
# User-reserved buffers: with use_cuda_graph=True plan() refreshes
# these in place, so run()'s captured kernels always read them.
self.kv_indices = torch.zeros(
@@ -226,24 +286,54 @@ class _SM90State:
self._lens_cpu = torch.full(
(self.max_tokens,), self.topk_width, dtype=torch.int32
)
# Planned per-work kv_end of the current plan, restored by each clamp;
# sized on first plan to the planner's work capacity.
self._saved_kv_end = torch.empty(0, dtype=torch.int32, device=device)
self._planned_num_tokens = -1
self._int_ws: torch.Tensor | None = None
self._plan_offsets: tuple[int, int, int, int] | None = None
def plan(self, num_tokens: int, kv_lens: torch.Tensor) -> None:
"""Replan with exact per-row KV lengths (CPU int32, ``[num_tokens]``).
def plan(
self,
num_tokens: int,
kv_lens: torch.Tensor,
cam: CommonAttentionMetadata | None,
req_id_per_token: torch.Tensor | None,
) -> None:
"""Plan per-row KV lengths (CPU int32, ``[num_tokens]``).
The wrapper bakes kv_len into its int schedule from host values;
run() never reads the device kv_len_arr buffer. Scheduling with the
full buffer width while kv_indices rows carry a -1 tail past each
row's valid count makes the kernel compute ``-1 * ckv_stride_page``
(illegal address), so the lengths must be exact at plan time and
replanned every step as contexts grow. Must run outside CUDA graph
capture: the in-place refreshed plan_info/indptr buffers are what
captured runs read.
The wrapper bakes kv_len into its int schedule from host values, so
rows past their valid count would send the kernel into the -1 tail of
the converted index buffer. With ``cam`` and ``req_id_per_token``
(device batch layout), ``kv_lens`` only needs to upper-bound the
valid counts: the plan is padded by ``_PLAN_SLACK`` and reused while
the bound still fits, and every call clamps each work item's kv_end
on device to the exact count, so no D2H sync is needed. Without them
the lengths must be exact. Must run outside CUDA graph capture: the
in-place refreshed plan_info/indptr buffers are what captured runs
read.
"""
if torch.cuda.is_current_stream_capturing():
raise RuntimeError(
"FlashInferMLASparseSM90 plan() called inside CUDA graph "
"capture; lengths must be planned host-side before capture."
)
kv_lens = kv_lens.to(torch.int32)
if cam is None or req_id_per_token is None:
self._plan(num_tokens, kv_lens)
self._planned_num_tokens = -1
return
planned = self._lens_cpu[:num_tokens]
if num_tokens != self._planned_num_tokens or not bool(
((planned >= kv_lens) & (planned <= kv_lens + _PLAN_SLACK)).all()
):
self._plan(
num_tokens, torch.clamp(kv_lens + _PLAN_SLACK, max=self.max_valid)
)
self._planned_num_tokens = num_tokens
self._clamp_kv_end(cam, req_id_per_token)
def _plan(self, num_tokens: int, kv_lens: torch.Tensor) -> None:
# CPU staging buffers are filled in place: plan() runs per step
# (once per draft/verify metadata build), so per-call allocations and
# device round trips are on the hot path. Passing CPU tensors lets
@@ -257,13 +347,16 @@ class _SM90State:
# matching the exact lengths, including zero-length padded rows.
torch.clamp(self._arange_cpu, max=num_tokens, out=self._qo_cpu)
self._lens_cpu.zero_()
self._lens_cpu[:num_tokens] = kv_lens.to(torch.int32)
self._lens_cpu[:num_tokens] = kv_lens
self._kv_cpu[0] = 0
torch.cumsum(self._lens_cpu, dim=0, out=self._kv_cpu[1:])
# Only the live prefix of kv_indices: the wrapper snapshots and
# copies whatever is passed.
num_indices = max(int(self._kv_cpu[-1]), 1)
self.wrapper.plan(
self._qo_cpu,
self._kv_cpu,
self.kv_indices,
self.kv_indices[:num_indices],
self._lens_cpu,
self.num_heads,
self.kv_lora_rank, # head_dim_ckv
@@ -274,6 +367,42 @@ class _SM90State:
q_data_type=torch.bfloat16,
kv_data_type=self.kv_dtype,
)
plan_info = [int(x) for x in self.wrapper._plan_info]
assert len(plan_info) == _PLAN_INFO_LEN, plan_info
# Per-work arrays are laid out back to back at the planner's capacity.
max_works = (plan_info[_PI_KV_INDPTR] - plan_info[_PI_Q_INDPTR]) // 4
if self._saved_kv_end.numel() != max_works:
self._saved_kv_end = torch.empty(
max_works, dtype=torch.int32, device=self.device
)
self._int_ws = self.wrapper._planned_backend._int_workspace_buffer.view(
torch.int32
)
self._plan_offsets = (
plan_info[_PI_WORK_INDPTR] // 4 + plan_info[_PI_NUM_BLKS_Y],
plan_info[_PI_Q_INDPTR] // 4,
plan_info[_PI_KV_START] // 4,
plan_info[_PI_KV_END] // 4,
)
kv_end_off = self._plan_offsets[3]
self._saved_kv_end.copy_(self._int_ws[kv_end_off : kv_end_off + max_works])
def _clamp_kv_end(
self, cam: CommonAttentionMetadata, req_id_per_token: torch.Tensor
) -> None:
assert self._int_ws is not None and self._plan_offsets is not None
block = 1024
_clamp_work_kv_end[(triton.cdiv(self._saved_kv_end.numel(), block),)](
self._int_ws,
self._saved_kv_end,
cam.seq_lens,
cam.query_start_loc,
req_id_per_token,
*self._plan_offsets,
TOPK=self.index_topk,
KPOOL=self.index_kpool,
BLOCK_SIZE=block,
)
def pack_indices(self, topk_slots: torch.Tensor) -> None:
num_tokens, width = topk_slots.shape
@@ -312,6 +441,8 @@ class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
)
topk_indices_buffer = impl.topk_indices_buffer
assert topk_indices_buffer is not None
hf_config = vllm_config.model_config.hf_text_config
assert hf_config.index_topk is not None
self.state = _SM90State(
device,
impl.num_heads,
@@ -321,20 +452,18 @@ class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
kv_lora_rank=impl.kv_lora_rank,
qk_rope_head_dim=impl.qk_rope_head_dim,
sm_scale=impl.scale,
index_topk=int(hf_config.index_topk),
index_kpool=int(getattr(hf_config, "index_kpool", 1) or 1),
)
spec_config = vllm_config.speculative_config
self._adaptive_verification = bool(
spec_config is not None and spec_config.enable_adaptive_verification
)
# seq_lens_cpu_upper_bound is optimistic on decode rows under async
# spec decode, so the fast sync-free path is only safe without it;
# under async scheduling the exact (device) positions are used at
# the cost of one D2H sync per metadata build.
self._async_scheduling = bool(vllm_config.scheduler_config.async_scheduling)
hf_config = vllm_config.model_config.hf_text_config
assert hf_config.index_topk is not None
self._index_topk = int(hf_config.index_topk)
self._index_kpool = int(getattr(hf_config, "index_kpool", 1) or 1)
def _kv_lens_host(self, cam: CommonAttentionMetadata) -> tuple[int, torch.Tensor]:
"""Exact per-row KV lengths, host-side (the flashinfer wrapper bakes
them into its schedule at plan time; there is no device-side path).
def _kv_lens_host(
self, cam: CommonAttentionMetadata
) -> tuple[int, torch.Tensor, bool]:
"""Host per-row KV lengths for the plan and whether they are exact.
A row for the j-th query token of request i attends
``seq_lens[i] - q_len[i] + j + 1`` tokens. The indexer's selection
@@ -343,53 +472,41 @@ class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
``index_topk`` pool-expanded tokens plus the trailing incomplete
pool (valid == ``index_topk + context % index_kpool``). Both match
the count of non -1 entries the convert kernel produces.
With ``seq_lens_cpu_upper_bound`` (optimistic under async spec
decode) returns sync-free upper bounds, which the plan clamps on
device. Otherwise returns exact lengths via a D2H copy.
"""
num_reqs = cam.num_reqs
qsl = cam.query_start_loc_cpu[: num_reqs + 1]
num_rows = int(qsl[-1])
if num_rows == 0:
return 0, torch.zeros(0, dtype=torch.int32)
# Row context == position + 1. Without async scheduling the
# maintained host upper bound is exact, giving a sync-free path;
# under async scheduling it is optimistic on decode rows, so fall
# back to the exact device positions (one D2H sync per build). The
# seq_lens derivation equals position + 1 because positions are
# contiguous per request.
return 0, torch.zeros(0, dtype=torch.int32), True
state = self.state
sl_host = cam.seq_lens_cpu_upper_bound
positions = cam.positions
if not self._async_scheduling and sl_host is not None:
seq_lens = sl_host[:num_reqs].to(torch.int32)
q_lens = qsl[1:] - qsl[:-1]
first_pos = seq_lens - q_lens
req_of_row = torch.repeat_interleave(
torch.arange(num_reqs, dtype=torch.int64), q_lens.to(torch.int64)
)
rows = torch.arange(num_rows, dtype=torch.int32)
ctx = (
first_pos.to(torch.int64)[req_of_row]
+ rows.to(torch.int64)
- qsl.to(torch.int64)[req_of_row]
+ 1
)
elif positions is not None and num_rows <= positions.shape[0]:
ctx = positions[:num_rows].cpu().to(torch.int64) + 1
if sl_host is None:
ctx = self._row_contexts(qsl, cam.seq_lens[:num_reqs].cpu())
topk, kpool = state.index_topk, state.index_kpool
lens = torch.where(ctx <= topk, ctx, topk + ctx % kpool)
return num_rows, lens.to(torch.int32), True
if self._adaptive_verification:
# The host query split may not match the device one, so bound
# every row by the longest request.
ctx = torch.full((num_rows,), int(sl_host[:num_reqs].max()))
else:
seq_lens = cam.seq_lens[:num_reqs].cpu().to(torch.int32)
q_lens = qsl[1:] - qsl[:-1]
first_pos = seq_lens - q_lens
req_of_row = torch.repeat_interleave(
torch.arange(num_reqs, dtype=torch.int64), q_lens.to(torch.int64)
)
rows = torch.arange(num_rows, dtype=torch.int32)
ctx = (
first_pos.to(torch.int64)[req_of_row]
+ rows.to(torch.int64)
- qsl.to(torch.int64)[req_of_row]
+ 1
)
topk = self._index_topk
lens = torch.where(ctx <= topk, ctx, topk + ctx % self._index_kpool)
return num_rows, lens.to(torch.int32)
ctx = self._row_contexts(qsl, sl_host[:num_reqs])
return num_rows, torch.clamp(ctx, max=state.max_valid), False
@staticmethod
def _row_contexts(qsl: torch.Tensor, seq_lens: torch.Tensor) -> torch.Tensor:
num_reqs = qsl.shape[0] - 1
q_lens = (qsl[1:] - qsl[:-1]).to(torch.int64)
first_ctx = seq_lens.to(torch.int64) - q_lens + 1
req_of_row = torch.repeat_interleave(
torch.arange(num_reqs, dtype=torch.int64), q_lens
)
rows = torch.arange(int(qsl[-1]), dtype=torch.int64)
return first_ctx[req_of_row] + rows - qsl.to(torch.int64)[req_of_row]
def build(
self,
@@ -399,9 +516,9 @@ class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
) -> FlashInferMLASparseSM90Metadata:
metadata = super().build(common_prefix_len, common_attn_metadata, fast_build)
assert isinstance(metadata, FlashInferMLASparseSM90Metadata)
# Replan every step outside any CUDA graph capture with this step's
# exact per-row lengths; captured runs read the refreshed buffers.
num_rows, kv_lens = self._kv_lens_host(common_attn_metadata)
# Plan outside any CUDA graph capture; captured runs read the
# refreshed buffers.
num_rows, kv_lens, exact = self._kv_lens_host(common_attn_metadata)
# MHA prefills are removed from q before forward_mqa. Plan only the
# decode prefix in that case, using the same routing decision as MLA.
if metadata.num_prefills > 0 and self._attention_layer._use_sparse_mha(
@@ -409,7 +526,12 @@ class FlashInferMLASparseSM90Builder(FlashInferMLASparseMetadataBuilder):
):
num_rows = metadata.num_decode_tokens
kv_lens = kv_lens[:num_rows]
self.state.plan(num_rows, kv_lens)
if exact:
self.state.plan(num_rows, kv_lens, None, None)
else:
self.state.plan(
num_rows, kv_lens, common_attn_metadata, metadata.req_id_per_token
)
metadata.state = self.state
return metadata
@@ -53,6 +53,10 @@ class MLAPrefillBackendEnum(Enum, metaclass=_MLAPrefillBackendEnumMeta):
"AiterFlashAttnPrefillBackend"
)
CPU = "vllm.v1.attention.backends.mla.prefill.cpu_sdpa.CPUSDPAMLAPrefillBackend"
ZEN_CPU = (
"vllm.v1.attention.backends.mla.prefill.zen_cpu_sdpa."
"ZenCPUSDPAMLAPrefillBackend"
)
# Placeholder for third-party/custom backends - must be registered before use
# set to None to avoid alias with other backend, whose value is an empty string
CUSTOM = None
@@ -110,8 +110,18 @@ def get_mla_prefill_backend(
from vllm.platforms import current_platform
if current_platform.is_cpu():
logger.info_once("Using CPU SDPA MLA prefill backend.")
return MLAPrefillBackendEnum.CPU.get_class()
# CPUs have no compute capability, so the capability-driven priority
# path below does not apply. Prefer an accelerator-specific CPU backend
# when its kernels are present, else the generic SDPA one.
for backend_enum in (MLAPrefillBackendEnum.ZEN_CPU, MLAPrefillBackendEnum.CPU):
try:
cpu_backend_cls = backend_enum.get_class()
except ImportError:
continue
if cpu_backend_cls.is_available():
logger.info_once("Using %s MLA prefill backend.", backend_enum.name)
return cpu_backend_cls
raise ValueError("No valid CPU MLA prefill backend found.")
device_capability = current_platform.get_device_capability()
if device_capability is None:
@@ -0,0 +1,106 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU MLA prefill backend using zentorch SDPA on AMD Zen CPUs.
Subclasses the generic CPU SDPA backend and replaces the per-request attention
with ``zentorch_sdpa``, which fuses the scale, causal mask, softmax and both
matmuls of the base implementation into a single call.
``zentorch_sdpa`` does not return a usable log-sum-exp, so requests that need
one (context chunks, prefix/suffix merge) are delegated to the base backend.
Availability is reported through :meth:`is_available`, so the prefill selector
gates this backend once at selection time rather than per attention call.
"""
import torch
from vllm.model_executor.kernels.linear.zentorch_utils import has_zentorch_op
from vllm.v1.attention.backends.mla.prefill.cpu_sdpa import CPUSDPAMLAPrefillBackend
class ZenCPUSDPAMLAPrefillBackend(CPUSDPAMLAPrefillBackend):
"""MLA prefill backend for AMD Zen CPUs backed by ``zentorch_sdpa``."""
@staticmethod
def get_name() -> str:
return "ZEN_CPU_SDPA_MLA"
@classmethod
def is_available(cls) -> bool:
return has_zentorch_op(["zentorch_sdpa"])
@staticmethod
def _sdpa_layout(
q_r: torch.Tensor,
k_r: torch.Tensor,
v_r: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
"""Convert one request's [S, NH, D] tensors to the [1, NH, S, D] layout.
MLA has ``v_head_dim < qk_head_dim``, which the fused kernel does not
accept, so V is padded up to the query head dim. The original V head
dim is returned so the caller can slice the padding off afterwards.
"""
h_q = q_r.shape[-1]
h_v = v_r.shape[-1]
pad = h_q - h_v
qs = q_r.transpose(0, 1).unsqueeze(0).contiguous()
ks = k_r.transpose(0, 1).unsqueeze(0).contiguous()
vs = v_r.transpose(0, 1).unsqueeze(0).contiguous()
if pad > 0:
vs = torch.nn.functional.pad(vs, (0, pad))
return qs, ks, vs, h_v
def _ragged_sdpa(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
q_cu_seq_lens: torch.Tensor,
kv_cu_seq_lens: torch.Tensor,
causal: bool,
return_softmax_lse: bool,
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
if return_softmax_lse:
# zentorch_sdpa's second return is not a usable LSE, so fall back
# to the base fp32 implementation whenever one is required.
return super()._ragged_sdpa(
q,
k,
v,
q_cu_seq_lens,
kv_cu_seq_lens,
causal,
return_softmax_lse,
)
num_reqs = q_cu_seq_lens.numel() - 1
assert num_reqs == kv_cu_seq_lens.numel() - 1
out_chunks: list[torch.Tensor] = []
for r in range(num_reqs):
q_start = int(q_cu_seq_lens[r])
q_end = int(q_cu_seq_lens[r + 1])
kv_start = int(kv_cu_seq_lens[r])
kv_end = int(kv_cu_seq_lens[r + 1])
qs, ks, vs, h_v = self._sdpa_layout(
q[q_start:q_end],
k[kv_start:kv_end],
v[kv_start:kv_end],
)
attn, _ = torch.ops.zentorch.zentorch_sdpa(
qs,
ks,
vs,
0.0,
causal,
attn_mask=None,
scale=self.scale,
)
out_chunks.append(attn[0].transpose(0, 1)[..., :h_v].to(v.dtype))
return torch.cat(out_chunks, dim=0)
+22 -2
View File
@@ -21,7 +21,12 @@ from vllm.config.cache import _layout_from_name
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.utils.math_utils import cdiv
from vllm.utils.torch_utils import PIN_MEMORY, async_tensor_h2d, np_to_pinned_tensor
from vllm.v1.kv_cache_interface import KVCacheLayout, KVCacheSpec, MambaSpec
from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheLayout,
KVCacheSpec,
MambaSpec,
)
if TYPE_CHECKING:
from vllm.v1.core.sched.output import SchedulerOutput
@@ -286,9 +291,10 @@ def resolve_kv_cache_layout(
# specs can re-interpret HNC with different sizes as long as the total number of
# bytes is the same. If not block-compact, each spec must agree on HNC to alias
# the same page (this aliasing is done by the Hybrid Memory Allocator, HMA).
kv_cache_specs = tuple(kv_cache_specs or ())
hnc_shapes = {
(spec.num_heads, spec.num_states, spec.page_size_bytes)
for spec in kv_cache_specs or ()
for spec in kv_cache_specs
}
if len(hnc_shapes) > 1:
candidates = [m for m in candidates if m.is_block_compact]
@@ -298,6 +304,20 @@ def resolve_kv_cache_layout(
f"none is in every supported set: {supported_layouts}."
)
dcp_sharding = {
spec.dcp_sharded for spec in kv_cache_specs if isinstance(spec, AttentionSpec)
}
page_sizes = {spec.page_size_bytes for spec in kv_cache_specs}
if len(dcp_sharding) > 1 and len(page_sizes) > 1:
# Sharded target and replicated draft caches need independent groups.
# Block-outer layouts can pack those groups without equalizing pages.
candidates = [layout for layout in candidates if layout.is_block_outermost]
if not candidates:
raise ValueError(
"DCP with a replicated draft and mixed KV page sizes requires "
f"a block-outer KV cache layout; supported sets: {supported_layouts}."
)
if (requested := envs.VLLM_KV_CACHE_LAYOUT) is not None:
layout = _layout_from_name(requested)
if layout not in candidates:
+13 -13
View File
@@ -11,7 +11,6 @@ from vllm.v1.core.kv_cache_metrics import KVCacheMetricsCollector
from vllm.v1.core.kv_cache_utils import (
BlockHash,
KVCacheBlock,
dcp_world_size_for_kv_cache_spec,
)
from vllm.v1.core.single_type_kv_cache_manager import (
CrossAttentionManager,
@@ -20,6 +19,7 @@ from vllm.v1.core.single_type_kv_cache_manager import (
get_manager_for_kv_cache_spec,
)
from vllm.v1.kv_cache_interface import (
AttentionSpec,
FullAttentionSpec,
KVCacheConfig,
KVCacheSpec,
@@ -140,9 +140,7 @@ class KVCacheCoordinator(ABC):
role=kv_cache_group.role,
enable_caching=enable_caching,
kv_cache_group_id=i,
dcp_world_size=dcp_world_size_for_kv_cache_spec(
kv_cache_group.kv_cache_spec, dcp_world_size
),
dcp_world_size=dcp_world_size,
pcp_world_size=pcp_world_size,
scheduler_block_size=self.scheduler_block_size,
needs_kv_cache_zeroing=self.kv_cache_config.needs_kv_cache_zeroing,
@@ -664,16 +662,18 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
f"hash_block_size. block_sizes={cacheable_block_sizes}, "
f"hash_block_size={hash_block_size}"
)
assert pcp_world_size == 1, "PCP not support hybrid attn now."
if dcp_world_size > 1:
# DCP shards full-attention KV across ranks and replicates Mamba
# state; other spec types (e.g. sliding window) have no DCP-aware
# handling yet, so reject them explicitly.
for g in kv_cache_config.kv_cache_groups:
assert isinstance(g.kv_cache_spec, (FullAttentionSpec, MambaSpec)), (
for g in kv_cache_config.kv_cache_groups:
spec = g.kv_cache_spec
replicated = not spec.dcp_sharded
if pcp_world_size > 1:
assert isinstance(spec, FullAttentionSpec) or (
isinstance(spec, AttentionSpec) and replicated
), "PCP only supports full attention and replicated draft groups."
if dcp_world_size > 1:
assert isinstance(spec, FullAttentionSpec) or replicated, (
"DCP with hybrid KV cache layouts only supports "
"full-attention and Mamba groups, got: "
f"{type(g.kv_cache_spec).__name__}."
"full-attention, Mamba, and replicated draft groups, got: "
f"{type(spec).__name__}."
)
# Fine-grained hash hits require Mamba "align" and compatible cache
# managers in every group. TP needs hashing finer than the Mamba block;
+19 -41
View File
@@ -682,12 +682,7 @@ def hash_block_tokens(
def resolve_dcp_kv_block_size(spec: KVCacheSpec, dcp_world_size: int) -> int:
"""Return the token span of a cache block under DCP."""
layer_specs = iter_layer_specs(spec)
if len(layer_specs) > 0 and all(
isinstance(layer_spec, AttentionSpec) for layer_spec in layer_specs
):
return spec.block_size * dcp_world_size
return spec.block_size
return spec.block_size * (dcp_world_size if spec.dcp_sharded else 1)
def resolve_dcp_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> KVCacheSpec:
@@ -707,28 +702,6 @@ def resolve_dcp_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> KVCache
return replace(spec, block_size=block_size)
def dcp_world_size_for_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> int:
"""Return the DCP size that owns this group's block geometry.
Full-attention KV (including MLA) is sharded across DCP ranks, so prefix
hashing and manager ``block_size`` use the process DCP size. Other specs
keep replicated per-rank state (Mamba, sliding window, chunked-local) and
must keep ``dcp_world_size=1`` even when the process runs with DCP > 1.
Draft MLA groups on the sharded DSpark path are ``FullAttentionSpec`` /
``MLAAttentionSpec`` and therefore keep the process DCP size. A replicated
draft group would need a different spec, not this helper.
"""
if dcp_world_size <= 1:
return 1
inner = spec
if isinstance(spec, UniformTypeKVCacheSpecs):
inner = next(iter(spec.kv_cache_specs.values()))
if isinstance(inner, FullAttentionSpec):
return dcp_world_size
return 1
def resolve_kv_cache_block_sizes(
kv_cache_config: KVCacheConfig,
vllm_config: VllmConfig,
@@ -752,6 +725,8 @@ def resolve_kv_cache_block_sizes(
groups = kv_cache_config.kv_cache_groups
if len(groups) <= 1:
if groups and not groups[0].kv_cache_spec.dcp_sharded:
dcp = 1
bs = cache_config.block_size * dcp
return bs, bs
@@ -1935,18 +1910,21 @@ def unify_hybrid_kv_cache_specs(kv_cache_spec: dict[str, KVCacheSpec]):
kv_cache_spec: The kv cache spec of each attention layer in the model
"""
if is_kv_cache_spec_uniform(
kv_cache_spec
) or UniformTypeKVCacheSpecs.is_uniform_type(kv_cache_spec):
return
logger.warning(
"Hybrid KV cache manager is disabled for this hybrid model, "
"This means we do not enable any optimizations for saving KV cache "
"memory (e.g., dropping the KV cache outside the sliding window). "
"The compute of layers like sliding window is still saved."
)
kv_cache_spec.update(_promote_local_kv_cache_specs(kv_cache_spec))
groups: defaultdict[bool, dict[str, KVCacheSpec]] = defaultdict(dict)
for name, spec in kv_cache_spec.items():
replicated = isinstance(spec, AttentionSpec) and not spec.dcp_sharded
groups[replicated][name] = spec
for specs in groups.values():
promoted_specs = _promote_local_kv_cache_specs(specs)
if promoted_specs == specs:
continue
logger.warning(
"Hybrid KV cache manager is disabled for this hybrid model, "
"This means we do not enable any optimizations for saving KV cache "
"memory (e.g., dropping the KV cache outside the sliding window). "
"The compute of layers like sliding window is still saved."
)
kv_cache_spec.update(promoted_specs)
def _approximate_gcd(values: Sequence[int], *, lower_bound: int | None = None) -> int:
@@ -2276,7 +2254,7 @@ def _ensure_min_page_size(
scaled: list[KVCacheGroupSpec] = []
for g in groups:
s = g.kv_cache_spec
kw: dict[str, int] = {"block_size": s.block_size * scale}
kw: dict[str, Any] = {"block_size": s.block_size * scale}
if isinstance(s, (AttentionSpec, MambaSpec)) and s.page_size_padded is not None:
kw["page_size_padded"] = s.page_size_padded * scale
scaled.append(KVCacheGroupSpec(g.layer_names, replace(s, **kw)))
+3 -9
View File
@@ -106,11 +106,9 @@ class SingleTypeKVCacheManager(ABC):
# managers have been validated by the coordinator.
self.cache_hit_alignment_tokens = scheduler_block_size
# The block size for this manager; used for actual block allocation.
self.block_size = kv_cache_spec.block_size
self.dcp_world_size = dcp_world_size
self.pcp_world_size = pcp_world_size
if dcp_world_size > 1:
self.block_size *= dcp_world_size
self.dcp_world_size = dcp_world_size if kv_cache_spec.dcp_sharded else 1
self.pcp_world_size = pcp_world_size if kv_cache_spec.dcp_sharded else 1
self.block_size = kv_cache_spec.block_size * self.dcp_world_size
self.kv_cache_spec = kv_cache_spec
self.block_pool = block_pool
self.enable_caching = enable_caching
@@ -1455,10 +1453,6 @@ class MambaManager(SingleTypeKVCacheManager):
self, kv_cache_spec: MambaSpec, block_pool: BlockPool, **kwargs
) -> None:
super().__init__(kv_cache_spec, block_pool, **kwargs)
# Mamba layers use TP instead of DCP, so each rank holds the full
# recurrent state. Undo the DCP/PCP block_size scaling that the base
# class applies for attention groups whose KV cache is partitioned.
self.block_size = kv_cache_spec.block_size
self.mamba_cache_mode = kv_cache_spec.mamba_cache_mode
self.num_speculative_blocks: int = kv_cache_spec.num_speculative_blocks
self.has_prefill_checkpoint_blocks = (
+2 -5
View File
@@ -219,10 +219,7 @@ class EngineCore:
logger.debug("Batch queue is enabled with size %d", self.batch_queue_size)
self.batch_queue = deque(maxlen=self.batch_queue_size)
self.is_ec_consumer = (
vllm_config.ec_transfer_config is None
or vllm_config.ec_transfer_config.is_ec_consumer
)
self.is_mm_encoder_only = vllm_config.is_mm_encoder_only
self.is_pooling_model = vllm_config.model_config.runner_type == "pooling"
self.request_block_hasher: Callable[[Request], list[BlockHash]] | None = None
@@ -702,7 +699,7 @@ class EngineCore:
exec_future = self.model_executor.execute_model(
scheduler_output, non_block=True
)
if self.is_ec_consumer:
if not self.is_mm_encoder_only:
model_executed = scheduler_output.total_num_scheduled_tokens > 0
if self.is_pooling_model or not model_executed:
+24 -5
View File
@@ -158,6 +158,8 @@ class KVCacheSpec:
# number of tokens in a block
block_size: int
dcp_sharded: bool = field(default=False, kw_only=True)
"""Whether DCP shards this cache's token positions across ranks."""
block_stride_alignment: int | None = field(default=None, kw_only=True)
"""Required byte alignment between physical blocks, including packed layers."""
@@ -481,6 +483,7 @@ class HiSparseResidentSpec(KVCacheSpec):
@dataclass(frozen=True, kw_only=True)
class AttentionSpec(KVCacheSpec):
dcp_sharded: bool = True
num_kv_heads: int
head_size: int
dtype: torch.dtype
@@ -536,7 +539,9 @@ class AttentionSpec(KVCacheSpec):
def max_num_blocks_per_req(self, vllm_config: VllmConfig, max_len: int) -> int:
parallel_config = vllm_config.parallel_config
kv_shard_count = parallel_config.decode_context_parallel_size
kv_shard_count = (
parallel_config.decode_context_parallel_size if self.dcp_sharded else 1
)
return cdiv(max_len, self.block_size * kv_shard_count)
@@ -568,7 +573,7 @@ class FullAttentionSpec(AttentionSpec):
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
max_model_len = vllm_config.model_config.max_model_len
dcp_world_size = vllm_config.parallel_config.decode_context_parallel_size
if dcp_world_size > 1:
if self.dcp_sharded and dcp_world_size > 1:
max_model_len = cdiv(max_model_len, dcp_world_size)
return cdiv(max_model_len, self.block_size) * self.page_size_bytes
@@ -612,6 +617,7 @@ class FullAttentionSpec(AttentionSpec):
head_size_v=specs[0].head_size_v,
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
dcp_sharded=specs[0].dcp_sharded,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -698,6 +704,7 @@ class MLAAttentionSpec(FullAttentionSpec):
head_size=specs[0].head_size,
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
dcp_sharded=specs[0].dcp_sharded,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -760,6 +767,7 @@ class RSWASpec(FullAttentionSpec):
head_size_v=base.head_size_v,
dtype=base.dtype,
kv_quant_mode=base.kv_quant_mode,
dcp_sharded=base.dcp_sharded,
page_size_padded=base.page_size_padded,
num_head_slots=base.num_head_slots,
state_content_bytes=base.state_content_bytes,
@@ -850,9 +858,10 @@ class SlidingWindowSpec(AttentionSpec):
return cdiv(num_tokens, self.block_size) + 1
def max_memory_usage_bytes(self, vllm_config: VllmConfig) -> int:
assert vllm_config.parallel_config.decode_context_parallel_size == 1, (
"DCP not support sliding window."
)
assert (
not self.dcp_sharded
or vllm_config.parallel_config.decode_context_parallel_size == 1
), "DCP not support sliding window."
max_blocks = self.max_admission_blocks_per_request(
max_in_flight_tokens=vllm_config.max_in_flight_tokens,
max_model_len=vllm_config.model_config.max_model_len,
@@ -950,6 +959,7 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
extra_retained_set = set(spec.extra_retained_tokens for spec in specs)
bounded_replay_set = set(spec.bounded_replay for spec in specs)
block_stride_alignment_set = {spec.block_stride_alignment for spec in specs}
assert len({spec.dcp_sharded for spec in specs}) == 1
assert (
len(cache_dtype_str_set) == 1
and len(tokens_per_state_set) == 1
@@ -969,6 +979,7 @@ class SlidingWindowMLASpec(SlidingWindowSpec):
num_kv_heads=specs[0].num_kv_heads,
head_size=specs[0].head_size,
dtype=specs[0].dtype,
dcp_sharded=specs[0].dcp_sharded,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -1185,6 +1196,7 @@ class SinkFullAttentionSpec(FullAttentionSpec):
block_stride_alignment=specs[0].block_stride_alignment,
dtype=specs[0].dtype,
kv_quant_mode=specs[0].kv_quant_mode,
dcp_sharded=specs[0].dcp_sharded,
page_size_padded=specs[0].page_size_padded,
num_head_slots=specs[0].num_head_slots,
state_content_bytes=specs[0].state_content_bytes,
@@ -1217,6 +1229,11 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
kv_cache_specs: dict[str, KVCacheSpec]
def __post_init__(self):
super().__post_init__()
if self.kv_cache_specs:
object.__setattr__(self, "dcp_sharded", self.first_spec.dcp_sharded)
@property
def prefix_cacheable(self) -> bool:
return all(spec.prefix_cacheable for spec in self.kv_cache_specs.values())
@@ -1270,6 +1287,8 @@ class UniformTypeKVCacheSpecs(KVCacheSpec):
if len(block_sizes) > 1:
# Different block sizes, not uniform.
return False
if len({spec.dcp_sharded for spec in kv_cache_specs.values()}) > 1:
return False
first_spec = next(iter(kv_cache_specs.values()))
return first_spec.is_uniform_with_collection(kv_cache_specs)
+84 -12
View File
@@ -4,7 +4,7 @@
import contextlib
from collections.abc import Iterable
from dataclasses import dataclass, field, replace
from dataclasses import dataclass, field, fields, replace
from enum import Enum, auto
from typing import TYPE_CHECKING, Any
@@ -27,13 +27,13 @@ from vllm.v1.core.kv_cache_coordinator import (
from vllm.v1.core.kv_cache_utils import (
BlockHashWithGroupId,
ExternalBlockHash,
dcp_world_size_for_kv_cache_spec,
generate_block_hash_extra_keys,
get_block_hash,
get_group_id,
make_block_hash_with_group_id,
maybe_convert_block_hash,
resolve_block_hashes,
resolve_dcp_kv_block_size,
)
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.kv_cache_interface import (
@@ -48,6 +48,11 @@ from vllm.v1.simple_kv_offload.metadata import (
SimpleCPUOffloadMetadata,
SimpleCPUOffloadWorkerMetadata,
)
from vllm.v1.simple_kv_offload.metrics import (
OUTCOME_TO_FIELD,
MetricName,
SimpleCPUOffloadStats,
)
if TYPE_CHECKING:
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
@@ -118,7 +123,8 @@ class BoundaryStoreStats:
symptom is a lower cache hit rate with nothing in the logs, so each decline
reason is counted and exposed through
``SimpleCPUOffloadConnector.get_boundary_store_stats()``. Reset by
``reset()``; not otherwise cleared.
``reset()``, which carries any not-yet-drained deltas; not otherwise
cleared.
"""
published: int = 0
@@ -143,6 +149,7 @@ class SimpleCPUOffloadScheduler:
hash_block_size: int,
lazy_offload: bool = False,
disk_capacity_bytes: int = 0,
use_page_cache: bool = False,
):
self.vllm_config = vllm_config
self.kv_cache_config = kv_cache_config
@@ -169,6 +176,13 @@ class SimpleCPUOffloadScheduler:
self.cpu_kv_cache_config.prefix_cacheable_group_ids
)
self.kv_event_medium = MEDIUM_STORAGE if disk_capacity_bytes > 0 else MEDIUM_CPU
# Must track kv_event_medium.
self._info_labelvalues: tuple[str, ...] = (
"disk" if disk_capacity_bytes > 0 else "cpu",
str(use_page_cache).lower(),
str(lazy_offload).lower(),
str(self.num_cpu_blocks),
)
# Find the full attention kv group for prefix cache matching.
self.fa_gidx = -1
for g_idx, g in enumerate(self.cpu_kv_cache_config.kv_cache_groups):
@@ -251,6 +265,9 @@ class SimpleCPUOffloadScheduler:
self._load_event_counter: int = 0
self._store_event_counter: int = 0
self.boundary_store_stats = BoundaryStoreStats()
# Interval stats state drained by get_stats()
self._boundary_stats_snapshot = BoundaryStoreStats()
self._interval_load_blocks_completed = 0
# For TP/PP: track partial store completions across steps.
# Events must be reported by all world_size workers before considered complete.
@@ -302,11 +319,7 @@ class SimpleCPUOffloadScheduler:
target = 0
for g in kv_cache_config.prefix_cacheable_groups:
spec = g.kv_cache_spec
# Only full attention is sharded across DCP ranks; replicated specs
# (mamba, sliding window, chunked-local) keep their own block size.
block_size = spec.block_size * dcp_world_size_for_kv_cache_spec(
spec, cp_world_size
)
block_size = resolve_dcp_kv_block_size(spec, cp_world_size)
if isinstance(spec, MambaSpec):
target += 2
elif isinstance(spec, SlidingWindowSpec):
@@ -955,6 +968,42 @@ class SimpleCPUOffloadScheduler:
def get_boundary_store_stats(self) -> BoundaryStoreStats:
return replace(self.boundary_store_stats)
def get_stats(self) -> SimpleCPUOffloadStats:
"""Drain per-step stats for the connector's stats hooks."""
stats = SimpleCPUOffloadStats()
current = self.boundary_store_stats
for outcome, field_name in OUTCOME_TO_FIELD.items():
delta = getattr(current, field_name) - getattr(
self._boundary_stats_snapshot, field_name
)
if delta > 0:
stats.increase_counter(MetricName.SAVE_OUTCOMES, delta, (outcome,))
self._boundary_stats_snapshot = replace(current)
if self._interval_load_blocks_completed:
stats.increase_counter(
MetricName.LOAD_BLOCKS,
self._interval_load_blocks_completed,
)
self._interval_load_blocks_completed = 0
stats.set_gauge(
MetricName.USED_BLOCKS,
self.num_cpu_blocks - self.cpu_block_pool.get_num_free_blocks(),
)
pending = sum(
len(t.cpu_block_ids)
for t in (
*self._store_event_to_blocks.values(),
*self._pending_finished_stores,
*self._abandoned_store_event_to_blocks.values(),
)
)
stats.set_gauge(MetricName.PENDING_STORE_BLOCKS, pending)
stats.set_gauge(MetricName.INFO, 1, self._info_labelvalues)
return stats
def update_connector_output(self, connector_output: KVConnectorOutput) -> None:
"""Handle async transfer completions from worker.
@@ -965,7 +1014,9 @@ class SimpleCPUOffloadScheduler:
"""
# --- Load completions ---
for req_id in list(connector_output.finished_recving or []):
self._cleanup_load_request(req_id)
completed_blocks = self._cleanup_load_request(req_id)
if completed_blocks:
self._interval_load_blocks_completed += completed_blocks
# --- Store completions ---
meta = connector_output.kv_connector_worker_meta
@@ -1270,18 +1321,22 @@ class SimpleCPUOffloadScheduler:
if blocks_to_free:
self.cpu_block_pool.free_blocks(blocks_to_free)
def _cleanup_load_request(self, req_id: str) -> None:
def _cleanup_load_request(self, req_id: str) -> int:
"""Release all load resources for a request.
Shared between request_finished() and update_connector_output() paths.
Removes the request from _reqs_to_load, cleans up event mappings,
and frees CPU/GPU touch refs.
Returns the number of blocks in the load if it had been issued to
the worker, else 0 (never-issued loads are not counted as completed
by the caller).
"""
state = self._reqs_to_load.pop(req_id, None)
if state is None:
state = self._abandoned_reqs_to_load.pop(req_id, None)
if state is None:
return
return 0
# Remove from load event mapping (only this req, not whole event)
if state.load_event is not None:
reqs = self._load_event_to_reqs.get(state.load_event)
@@ -1304,6 +1359,10 @@ class SimpleCPUOffloadScheduler:
for bid in state.transfer_meta.gpu_block_ids
)
if state.load_event is None:
return 0
return len(state.transfer_meta.gpu_block_ids)
def _cleanup_store_request(self, req_id: str) -> None:
"""Release store metadata for a request.
@@ -1363,7 +1422,20 @@ class SimpleCPUOffloadScheduler:
if event_idx in self._abandoned_store_event_to_blocks
}
self._cursor = None
self.boundary_store_stats = BoundaryStoreStats()
# Seed the fresh counters with outcomes since the last drain so a
# mid-interval reset() does not drop them from the next report.
undrained = BoundaryStoreStats(
**{
f.name: max(
0,
getattr(self.boundary_store_stats, f.name)
- getattr(self._boundary_stats_snapshot, f.name),
)
for f in fields(BoundaryStoreStats)
}
)
self.boundary_store_stats = undrained
self._boundary_stats_snapshot = BoundaryStoreStats()
# NOTE: _load_event_counter / _store_event_counter are not
# reset as they are monotonic and must stay ahead of the workers
# high-water marks to avoid event index collisions
+284
View File
@@ -0,0 +1,284 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Prometheus metrics for SimpleCPUOffloadConnector.
The stats payload uses the same self-describing wire format as the
offloading connector, so it survives IPC serialization without the
metric classes on the receiving side.
"""
from dataclasses import dataclass
from typing import Any
from vllm.config import VllmConfig
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
KVConnectorPromMetrics,
KVConnectorStats,
PromMetric,
PromMetricT,
)
class MetricName:
"""Metric names for SimpleCPUOffloadConnector."""
SAVE_OUTCOMES = "vllm:simple_kv_offload_save_outcomes_total"
LOAD_BLOCKS = "vllm:simple_kv_offload_load_blocks_total"
USED_BLOCKS = "vllm:simple_kv_offload_used_blocks"
PENDING_STORE_BLOCKS = "vllm:simple_kv_offload_pending_store_blocks"
INFO = "vllm:simple_kv_offload_info"
# outcome label value -> BoundaryStoreStats field name.
# ``published`` is the sum of all outcomes and is not labeled.
OUTCOME_TO_FIELD = {
"stored": "stored",
"dropped_cpu_full": "dropped_cpu_full",
"dropped_request_gone": "dropped_request_gone",
"dropped_null_block": "dropped_null_block",
"dropped_not_hashed": "dropped_not_hashed",
"skipped_already_cached": "skipped_already_cached",
"skipped_in_flight": "skipped_in_flight",
}
INFO_LABELS = ["backend", "page_cache", "lazy_offload", "capacity_blocks"]
class _MetricType:
"""Type tags embedded in the serialized stats payload."""
COUNTER = "counter"
GAUGE = "gauge"
class _StatsKey:
"""Top-level keys in the serialized stats dict."""
# Maps metric name -> _MetricType value
TYPES = "types"
# Maps metric name -> {label values tuple -> observed value}
DATA = "data"
@dataclass
class SimpleCPUOffloadStats(KVConnectorStats):
"""Stats payload for SimpleCPUOffloadConnector.
The ``data`` dict is structured as::
{
_StatsKey.TYPES: {name: _MetricType.*, ...},
_StatsKey.DATA: {name: {labelvalues: value, ...}, ...},
}
Counter values are summed when aggregating, gauge values keep the
latest snapshot, and unlabeled metrics use ``()`` as their
labelvalues tuple.
"""
def __post_init__(self):
if _StatsKey.DATA not in self.data:
self.reset()
def reset(self):
self.data: dict[str, Any] = {
_StatsKey.TYPES: {},
_StatsKey.DATA: {},
}
@property
def _types(self) -> dict[str, str]:
return self.data[_StatsKey.TYPES]
@property
def _values(self) -> dict[str, Any]:
return self.data[_StatsKey.DATA]
def aggregate(self, other: "KVConnectorStats") -> "KVConnectorStats":
if other.is_empty():
return self
assert isinstance(other, SimpleCPUOffloadStats)
for key, other_label_values in other._values.items():
type_str = other._types.get(key)
if type_str is None:
raise AssertionError(f"Unknown simple KV offload stats key: {key}")
self._types.setdefault(key, type_str)
current_label_values = self._values.setdefault(key, {})
for labelvalues, value in other_label_values.items():
if type_str == _MetricType.COUNTER:
assert isinstance(value, int | float)
current_label_values[labelvalues] = (
current_label_values.get(labelvalues, 0) + value
)
elif type_str == _MetricType.GAUGE:
assert isinstance(value, int | float)
current_label_values[labelvalues] = value
else:
raise AssertionError(
f"Unknown metric type '{type_str}' for key: {key}"
)
return self
def reduce(self) -> dict[str, int | float]:
"""Reduce the interval observations to a flat summary for logging."""
return_dict: dict[str, int | float] = {}
for key, label_value_map in self._values.items():
if key == MetricName.INFO:
# Constant config fingerprint; exclude from the log summary.
continue
type_str = self._types.get(key)
if type_str is None:
raise AssertionError(f"Unknown simple KV offload stats key: {key}")
for labelvalues, value in label_value_map.items():
key_with_labels = f"{key}:{labelvalues}" if labelvalues else key
if type_str in (_MetricType.COUNTER, _MetricType.GAUGE):
assert isinstance(value, int | float)
return_dict[key_with_labels] = value
else:
raise AssertionError(
f"Unknown metric type '{type_str}' for key: {key}"
)
return return_dict
def is_empty(self) -> bool:
return not self.data.get(_StatsKey.DATA)
def increase_counter(
self,
counter_name: str,
counter_increase_value: int | float = 1,
labelvalues: tuple[str, ...] = (),
) -> None:
"""Increase a counter on the stats payload."""
self._types.setdefault(counter_name, _MetricType.COUNTER)
counter_values = self._values.setdefault(counter_name, {})
counter_values[labelvalues] = (
counter_values.get(labelvalues, 0) + counter_increase_value
)
def set_gauge(
self,
gauge_name: str,
gauge_value: int | float,
labelvalues: tuple[str, ...] = (),
) -> None:
"""Set a gauge snapshot on the stats payload."""
self._types.setdefault(gauge_name, _MetricType.GAUGE)
gauge_values = self._values.setdefault(gauge_name, {})
gauge_values[labelvalues] = gauge_value
class SimpleCPUOffloadPromMetrics(KVConnectorPromMetrics):
"""Prometheus registration and recording for SimpleCPUOffloadConnector."""
def __init__(
self,
vllm_config: VllmConfig,
metric_types: dict[type[PromMetric], type[PromMetricT]],
labelnames: list[str],
per_engine_labelvalues: dict[int, list[object]],
):
super().__init__(vllm_config, metric_types, labelnames, per_engine_labelvalues)
# (engine_idx, metric_name, labelvalues) -> bound child metric
self._metrics: dict[tuple[int, str, tuple[str, ...]], PromMetricT] = {}
self._counter_save_outcomes = self._counter_cls(
name="vllm:simple_kv_offload_save_outcomes_total",
documentation=(
"Store admission decisions in SimpleCPUOffloadConnector, by "
"outcome. Outcomes classify eager-mode boundary hand-off "
"stores; lazy-mode stores are not classified."
),
labelnames=self._labelnames + ["outcome"],
)
self._counter_load_blocks = self._counter_cls(
name="vllm:simple_kv_offload_load_blocks_total",
documentation=(
"KV blocks restored to GPU from the offload pool, counted "
"when a load finishes. This is prefill work avoided "
"through offload cache hits."
),
labelnames=self._labelnames,
)
self._gauge_used_blocks = self._gauge_cls(
name="vllm:simple_kv_offload_used_blocks",
documentation=(
"Offload-pool blocks currently pinned by in-flight "
"transfers or cache hits (capacity minus free). Evictable "
"cached blocks are not counted; capacity_blocks is on "
"vllm:simple_kv_offload_info."
),
labelnames=self._labelnames,
multiprocess_mode="mostrecent",
)
self._gauge_pending_store_blocks = self._gauge_cls(
name="vllm:simple_kv_offload_pending_store_blocks",
documentation=(
"Offload blocks in pending stores: queued for dispatch, "
"issued to workers, or awaiting release after a cache "
"reset. A persistently growing value indicates a stuck "
"transfer."
),
labelnames=self._labelnames,
multiprocess_mode="mostrecent",
)
self._gauge_info = self._gauge_cls(
name="vllm:simple_kv_offload_info",
documentation=(
"SimpleCPUOffloadConnector deployment facts. Value is "
"always 1. backend is cpu or disk; page_cache and "
"lazy_offload are true/false; capacity_blocks is the "
"offload pool size."
),
labelnames=self._labelnames + INFO_LABELS,
multiprocess_mode="mostrecent",
)
self._defs: dict[str, PromMetricT] = {
MetricName.SAVE_OUTCOMES: self._counter_save_outcomes,
MetricName.LOAD_BLOCKS: self._counter_load_blocks,
MetricName.USED_BLOCKS: self._gauge_used_blocks,
MetricName.PENDING_STORE_BLOCKS: self._gauge_pending_store_blocks,
MetricName.INFO: self._gauge_info,
}
self._num_label_values: dict[str, int] = {
MetricName.SAVE_OUTCOMES: 1,
MetricName.LOAD_BLOCKS: 0,
MetricName.USED_BLOCKS: 0,
MetricName.PENDING_STORE_BLOCKS: 0,
MetricName.INFO: len(INFO_LABELS),
}
def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0):
"""Observe transfer statistics."""
metric_types = transfer_stats_data.get(_StatsKey.TYPES, {})
metric_data = transfer_stats_data.get(_StatsKey.DATA, {})
for key, label_value_map in metric_data.items():
prom_metric = self._defs.get(key)
if prom_metric is None:
raise AssertionError(f"Unknown simple KV offload stats key: {key}")
type_str = metric_types.get(key)
for labelvalues, value in label_value_map.items():
if len(labelvalues) != self._num_label_values[key]:
raise AssertionError(
f"Metric {key} expects "
f"{self._num_label_values[key]} labels, "
f"got {len(labelvalues)}"
)
child = self._metrics.get((engine_idx, key, labelvalues))
if child is None:
engine_labelvalues = self.per_engine_labelvalues[engine_idx]
child = prom_metric.labels(
*(engine_labelvalues + list(labelvalues))
)
self._metrics[(engine_idx, key, labelvalues)] = child
if type_str == _MetricType.COUNTER:
assert isinstance(value, int | float)
child.inc(value)
elif type_str == _MetricType.GAUGE:
assert isinstance(value, int | float)
child.set(value)
else:
raise AssertionError(
f"Unknown metric type '{type_str}' for key: {key}"
)
+8 -1
View File
@@ -81,13 +81,20 @@ class DraftModelProposer(SpecDecodeBaseProposer):
def _create_draft_vllm_config(self) -> VllmConfig:
base = super()._create_draft_vllm_config()
spec = self.speculative_config
target_parallel = base.parallel_config
return replace(
base,
quant_config=None,
parallel_config=replace(
spec.draft_parallel_config,
rank=self.vllm_config.parallel_config.rank,
rank=target_parallel.rank,
decode_context_parallel_size=(
target_parallel.decode_context_parallel_size
),
cp_kv_cache_interleave_size=target_parallel.cp_kv_cache_interleave_size,
dcp_comm_backend=target_parallel.dcp_comm_backend,
dcp_q_replicate=target_parallel.dcp_q_replicate,
),
model_config=spec.draft_model_config,
)
+2
View File
@@ -40,6 +40,8 @@ def check_attention_cp_compatibility(
layer_impl = getattr(layer, "impl", None)
if layer_impl is None:
continue
if not check_pcp and layer_impl.dcp_world_size == 1:
continue
if vllm_config.speculative_config is not None and interleave_size > 1:
assert layer_impl.supports_mtp_with_cp_non_trivial_interleave_size, (
"MTP with cp_kv_cache_interleave_size > 1 is not "
+17 -1
View File
@@ -29,6 +29,7 @@ from vllm.v1.kv_cache_interface import (
AttentionSpec,
KVCacheConfig,
KVCacheSpec,
MambaSpec,
UniformTypeKVCacheSpecs,
)
from vllm.v1.worker.gpu.model_states.interface import ModelSpecificAttnMetadata
@@ -462,6 +463,10 @@ def build_attn_metadata(
attn_metadata: dict[str, Any] = {}
token_to_req_indices: torch.Tensor | None = None
# Mamba groups with the same spec and builder differ only in their state
# indices, so later groups re-gather those from the first group's metadata.
# Also at capture, so FULL graphs share the batch-level buffers.
cached_metadata: dict[tuple[KVCacheSpec, type], 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]:
@@ -514,7 +519,16 @@ def build_attn_metadata(
for attn_group in attn_groups[i]:
attn_metadata_builder = attn_group.get_metadata_builder(ubatch_idx)
if for_cudagraph_capture:
reuse_key = None
if attn_metadata_builder.supports_update_block_table and isinstance(
attn_group.kv_cache_spec, MambaSpec
):
reuse_key = (attn_group.kv_cache_spec, type(attn_metadata_builder))
if reuse_key in cached_metadata:
metadata = attn_metadata_builder.update_block_table(
cached_metadata[reuse_key], block_table, slot_mapping
)
elif for_cudagraph_capture:
metadata = attn_metadata_builder.build_for_cudagraph_capture(
common_attn_metadata
)
@@ -532,6 +546,8 @@ def build_attn_metadata(
common_attn_metadata=common_attn_metadata,
**attn_metadata_extra_kwargs,
)
if reuse_key is not None and reuse_key not in cached_metadata:
cached_metadata[reuse_key] = metadata
for layer_name in attn_group.layer_names:
attn_metadata[layer_name] = metadata
token_to_req_indices = common_attn_metadata._token_to_req_indices_cache
+11
View File
@@ -27,6 +27,7 @@ class BlockTables:
cp_rank: int = 0,
cp_interleave: int = 1,
slot_mapping_enabled: list[bool] | None = None,
dcp_sharded: list[bool] | None = None,
):
self.block_sizes = block_sizes
self.kernel_block_sizes = kernel_block_sizes
@@ -44,6 +45,10 @@ class BlockTables:
slot_mapping_enabled = [True] * self.num_kv_cache_groups
assert len(slot_mapping_enabled) == self.num_kv_cache_groups
self._slot_mapping_enabled = slot_mapping_enabled
if dcp_sharded is None:
dcp_sharded = [True] * self.num_kv_cache_groups
assert len(dcp_sharded) == self.num_kv_cache_groups
self.dcp_sharded = torch.tensor(dcp_sharded, dtype=torch.bool, device=device)
self.blocks_per_kv_block = [
bs // kbs for bs, kbs in zip(block_sizes, kernel_block_sizes)
@@ -210,6 +215,7 @@ class BlockTables:
self.block_sizes_tensor,
self.kernel_block_sizes_tensor,
self.slot_mapping_enabled,
self.dcp_sharded,
slot_mappings,
slot_mappings.stride(0),
self.cp_rank,
@@ -283,6 +289,7 @@ def _compute_slot_mappings_kernel(
block_sizes, # [num_kv_cache_groups]
kernel_block_sizes, # [num_kv_cache_groups]
slot_mapping_enabled, # [num_kv_cache_groups]
dcp_sharded, # [num_kv_cache_groups]
slot_mappings_ptr, # [num_kv_cache_groups, max_num_tokens]
slot_mappings_stride,
cp_rank,
@@ -312,6 +319,8 @@ def _compute_slot_mappings_kernel(
kv_block_size = tl.load(block_sizes + group_id)
kernel_block_size = tl.load(kernel_block_sizes + group_id)
mapping_enabled = tl.load(slot_mapping_enabled + group_id)
if CP_SIZE != 1:
sharded = tl.load(dcp_sharded + group_id)
req_state_idx = tl.load(idx_mapping + batch_idx)
# idx_mapping == -1 marks a dummy (or CUDA-graph padding) request that owns
@@ -337,6 +346,8 @@ def _compute_slot_mappings_kernel(
remainder = virtual_block_offsets % CP_INTERLEAVE
local_offsets = rounds * CP_INTERLEAVE + remainder
local_positions = virtual_block_indices * kv_block_size + local_offsets
local_positions = tl.where(sharded, local_positions, positions)
is_local = ~sharded | is_local
block_indices = tl.where(
mapping_enabled, local_positions // kernel_block_size, 0
+14 -1
View File
@@ -21,6 +21,7 @@ import gc
import time
from contextlib import AbstractContextManager
from copy import deepcopy
from dataclasses import replace
from typing import Any, NamedTuple
import numpy as np
@@ -561,7 +562,16 @@ class GPUModelRunner(LoRAModelRunnerMixin):
return encoder_runner.get_encoder_timing_stats()
def get_kv_cache_spec(self):
return get_kv_cache_spec(self.vllm_config)
kv_cache_spec = get_kv_cache_spec(self.vllm_config)
# A draft running at DCP=1 under a DCP target keeps a replicated cache.
if (
isinstance(self.speculator, DraftModelSpeculator)
and self.speculator.dcp_size == 1
and self.dcp_size > 1
):
for name in self.speculator.draft_attn_layer_names & kv_cache_spec.keys():
kv_cache_spec[name] = replace(kv_cache_spec[name], dcp_sharded=False)
return kv_cache_spec
def initialize_kv_cache(
self,
@@ -587,6 +597,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
block_sizes = []
max_num_blocks_per_group = []
slot_mapping_enabled = []
dcp_sharded = []
for kv_cache_group in kv_cache_config.kv_cache_groups:
spec = kv_cache_group.kv_cache_spec
block_sizes.append(spec.block_size)
@@ -594,6 +605,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
spec.first_spec if isinstance(spec, UniformTypeKVCacheSpecs) else spec
)
slot_mapping_enabled.append(layer_spec.uses_slot_mapping)
dcp_sharded.append(spec.dcp_sharded)
# 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(
@@ -657,6 +669,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
device=self.device,
kernel_block_sizes=self.kernel_block_sizes,
slot_mapping_enabled=slot_mapping_enabled,
dcp_sharded=dcp_sharded,
cp_size=self.dcp_size,
cp_rank=self.dcp_rank,
cp_interleave=self.cp_interleave,
+4 -1
View File
@@ -145,7 +145,10 @@ class PCPManager:
if speculative_config is not None:
if speculative_config.use_dspark():
dcp_size = parallel_config.decode_context_parallel_size
if dcp_size not in (1, pcp_size):
if (
dcp_size not in (1, pcp_size)
and speculative_config.draft_model_config.use_mla
):
raise NotImplementedError(
"MRV2 PCP DSpark requires DCP=1 or DCP=PCP; got "
f"DCP={dcp_size}, PCP={pcp_size}."
@@ -37,12 +37,18 @@ class DFlashSpeculator(DraftModelSpeculator):
def __init__(self, vllm_config: VllmConfig, device: torch.device):
parallel_config = vllm_config.parallel_config
if parallel_config.prefill_context_parallel_size > 1:
vllm_config = copy.copy(vllm_config)
vllm_config.parallel_config = replace(
parallel_config,
prefill_context_parallel_size=1,
)
speculative_config = vllm_config.speculative_config
assert speculative_config is not None
vllm_config = copy.copy(vllm_config)
vllm_config.parallel_config = replace(
parallel_config,
prefill_context_parallel_size=1,
decode_context_parallel_size=(
parallel_config.decode_context_parallel_size
if speculative_config.draft_model_config.use_mla
else 1
),
)
super().__init__(vllm_config, device)
self.hidden_states = torch.zeros(
@@ -427,7 +433,7 @@ class DFlashSpeculator(DraftModelSpeculator):
self.block_tables.input_block_tables[gid],
self.block_tables.kernel_block_sizes[gid],
self.block_tables.cp_rank,
self.block_tables.cp_size,
self.dcp_size,
self.block_tables.cp_interleave,
self.parallel_drafting_token_id,
self.num_query_per_req,
+3 -2
View File
@@ -138,6 +138,7 @@ class DraftModelSpeculator(BaseSpeculator):
# DP configuration
self.dp_size = vllm_config.parallel_config.data_parallel_size
self.dp_rank = vllm_config.parallel_config.data_parallel_rank
self.dcp_size = vllm_config.parallel_config.decode_context_parallel_size
self.eplb_state: EplbState | None = None
@@ -332,14 +333,14 @@ class DraftModelSpeculator(BaseSpeculator):
out=draft_seq_lens_cpu_upper_bound[:num_reqs],
)
draft_seq_lens_cpu_upper_bound[:num_reqs].clamp_(max=self.max_model_len)
if dcp_local_seq_lens is None and self.block_tables.cp_size > 1:
if dcp_local_seq_lens is None and self.dcp_size > 1:
# Draft steps advance and rewind their own global sequence lengths,
# so the target model's DCP-local lengths may already be stale.
dcp_local_seq_lens = prepare_dcp_local_seq_lens(
self.input_buffers.dcp_local_seq_lens,
self.input_buffers.seq_lens,
num_reqs,
self.block_tables.cp_size,
self.dcp_size,
self.block_tables.cp_rank,
self.block_tables.cp_interleave,
)
+1
View File
@@ -817,6 +817,7 @@ class InputBatch:
self.allowed_token_ids_mask_cpu_tensor[empty_index] = (
self.allowed_token_ids_mask_cpu_tensor[last_req_index]
)
self.allowed_token_ids_mask_cpu_tensor[last_req_index].fill_(False)
bad_words_token_ids = self.bad_words_token_ids.pop(last_req_index, None)
if bad_words_token_ids is not None:
+12 -3
View File
@@ -801,11 +801,20 @@ class Worker(WorkerBase):
# related to kv cache connector (e.g. kv cache sharing layers).
ensure_kv_transfer_initialized(self.vllm_config, kv_cache_config)
# If the connector provides a custom memory pool (e.g. Mooncake
# NVLink/BAREX), use it for KV cache allocation; otherwise fall
# back to the standard CuMem pool.
mem_pool_context = (
get_kv_transfer_group().get_mem_pool_context()
if has_kv_transfer_group()
else None
)
if mem_pool_context is None:
mem_pool_context = self._maybe_get_memory_pool_context(tag="kv_cache")
self.model_runner.initialize_kv_cache(
kv_cache_config,
kv_cache_allocation_context=self._maybe_get_memory_pool_context(
tag="kv_cache"
),
kv_cache_allocation_context=mem_pool_context,
)
# Build KV-zero metadata outside the CuMem pool so the bookkeeping