Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-15 21:16:39 +07:00
1693 changed files with 99919 additions and 32440 deletions
+32 -12
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Mapping, Sequence
from collections.abc import Iterable, Mapping, Sequence
from contextlib import AbstractContextManager, nullcontext
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, cast
@@ -14,9 +14,11 @@ from vllm.config import (
get_layers_from_vllm_config,
)
from vllm.config.compilation import CUDAGraphMode
from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.multimodal.inputs import MultiModalFeatureSpec
from vllm.platforms import current_platform
from vllm.v1.attention.backend import (
AttentionCGSupport,
CommonAttentionMetadata,
@@ -40,9 +42,13 @@ from vllm.v1.worker.utils import (
add_kv_sharing_layers_to_kv_cache_groups,
allocate_kv_cache,
bind_kv_cache_to_layers,
customize_attention_spec,
map_kv_caches_to_kernel_blocks,
prepare_kernel_block_sizes,
)
logger = init_logger(__name__)
if TYPE_CHECKING:
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.cudagraph_utils import (
@@ -141,7 +147,7 @@ def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]:
# Skip modules that don't need KV cache (eg encoder-only attention)
if spec := attn_module.get_kv_cache_spec(vllm_config):
if isinstance(spec, AttentionSpec):
spec = attn_module.get_attn_backend().customize_spec(spec)
spec = customize_attention_spec(attn_module.get_attn_backend(), spec)
kv_cache_spec[layer_name] = spec
if vllm_config.attention_config.hisparse_config is not None:
kv_cache_spec = resolve_hisparse_specs(vllm_config, kv_cache_spec, attn_layers)
@@ -261,10 +267,24 @@ def init_attn_backend(
# by all backends within that group.
kernel_block_sizes = prepare_kernel_block_sizes(kv_cache_config, attn_groups)
if current_platform.is_xpu():
for kv_cache_group_id, selected_kernel_block_size in enumerate(
kernel_block_sizes
):
if selected_kernel_block_size % 64 != 0:
for attn_group in attn_groups[kv_cache_group_id]:
logger.warning_once(
"On XPU platform, current selected kernel block size is "
"not fully optimized: kernel_block_size=%s, backend=%s, "
"kv_cache_spec=%s",
selected_kernel_block_size,
attn_group.backend,
repr(attn_group.kv_cache_spec),
)
# Phase 3: create metadata builders and determine cudagraph support.
attn_backend_workspace: torch.Tensor | None = None
for kv_cache_group_id, groups in enumerate(attn_groups):
kernel_block_size = None
kernel_block_size: int | None = None
if kv_cache_group_id < len(kernel_block_sizes):
kernel_block_size = kernel_block_sizes[kv_cache_group_id]
for group in groups:
@@ -382,6 +402,7 @@ def init_kv_cache(
kv_cache_allocation_context: AbstractContextManager | None = None,
*,
block_tables: "BlockTables | None" = None,
attn_groups: Iterable[AttentionGroup] = (),
) -> dict[str, Any]:
allocation_context = kv_cache_allocation_context or nullcontext()
with allocation_context:
@@ -409,9 +430,10 @@ def init_kv_cache(
num_attn_module = (
2 if vllm_config.model_config.hf_config.model_type == "longcat_flash" else 1
)
bindable_caches = {
name: cache for name, cache in kv_caches.items() if name in forward_context
}
bindable_caches = map_kv_caches_to_kernel_blocks(
{name: cache for name, cache in kv_caches.items() if name in forward_context},
attn_groups,
)
bind_kv_cache_to_layers(
bindable_caches,
forward_context,
@@ -536,8 +558,8 @@ def build_attn_metadata(
cached_metadata[reuse_key], block_table, slot_mapping
)
elif for_cudagraph_capture:
metadata = attn_metadata_builder.build_for_cudagraph_capture(
common_attn_metadata
metadata = attn_group.build_metadata_for_cudagraph_capture(
common_attn_metadata, ubatch_idx
)
else:
attn_metadata_extra_kwargs = (
@@ -548,10 +570,8 @@ def build_attn_metadata(
if model_specific_attn_metadata is not None
else {}
)
metadata = attn_metadata_builder.build(
common_prefix_len=0,
common_attn_metadata=common_attn_metadata,
**attn_metadata_extra_kwargs,
metadata = attn_group.build_metadata(
common_attn_metadata, ubatch_idx, **attn_metadata_extra_kwargs
)
if reuse_key is not None and reuse_key not in cached_metadata:
cached_metadata[reuse_key] = metadata
+4 -22
View File
@@ -25,7 +25,6 @@ class BlockTables:
max_num_batched_tokens: int,
max_num_blocks_per_group: list[int],
device: torch.device,
kernel_block_sizes: list[int],
cp_size: int = 1,
cp_rank: int = 0,
cp_interleave: int = 1,
@@ -33,7 +32,6 @@ class BlockTables:
dcp_sharded: list[bool] | None = None,
):
self.block_sizes = block_sizes
self.kernel_block_sizes = kernel_block_sizes
self.max_num_reqs = max_num_reqs
self.max_num_batched_tokens = max_num_batched_tokens
self.device = device
@@ -53,14 +51,9 @@ class BlockTables:
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)
]
# num_kv_cache_groups x [max_num_reqs, max_num_blocks]
self.block_tables: list[StagedWriteTensor] = []
for i in range(self.num_kv_cache_groups):
max_num_blocks = max_num_blocks_per_group[i] * self.blocks_per_kv_block[i]
for max_num_blocks in max_num_blocks_per_group:
block_table = StagedWriteTensor(
(self.max_num_reqs, max_num_blocks), dtype=torch.int32, device=device
)
@@ -109,9 +102,6 @@ class BlockTables:
self.block_sizes_tensor = torch.tensor(
self.block_sizes, dtype=torch.int32, device=self.device
)
self.kernel_block_sizes_tensor = torch.tensor(
self.kernel_block_sizes, dtype=torch.int32, device=self.device
)
self.slot_mapping_enabled = torch.tensor(
self._slot_mapping_enabled, dtype=torch.bool, device=self.device
)
@@ -126,9 +116,6 @@ class BlockTables:
for i in range(self.num_kv_cache_groups):
start = self.num_blocks.np[i, req_index] if not overwrite else 0
block_ids = new_block_ids[i]
bpk = self.blocks_per_kv_block[i]
if bpk > 1:
block_ids = [b * bpk + k for b in block_ids for k in range(bpk)]
if self.redirect_writes_to_null_block:
block_ids = [0] * len(block_ids)
end = start + len(block_ids)
@@ -218,7 +205,6 @@ class BlockTables:
self.block_table_ptrs,
self.block_table_strides,
self.block_sizes_tensor,
self.kernel_block_sizes_tensor,
self.slot_mapping_enabled,
self.dcp_sharded,
slot_mappings,
@@ -292,7 +278,6 @@ def _compute_slot_mappings_kernel(
block_table_ptrs, # [num_kv_cache_groups]
block_table_strides, # [num_kv_cache_groups]
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]
@@ -322,7 +307,6 @@ def _compute_slot_mappings_kernel(
block_table_ptr = _load_ptr(block_table_ptrs + group_id, tl.int32)
block_table_stride = tl.load(block_table_strides + group_id)
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)
@@ -354,16 +338,14 @@ def _compute_slot_mappings_kernel(
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
)
block_offsets = local_positions % kernel_block_size
block_indices = tl.where(mapping_enabled, local_positions // kv_block_size, 0)
block_offsets = local_positions % kv_block_size
block_numbers = tl.load(
block_table_ptr + req_state_idx * block_table_stride + block_indices,
mask=is_local & is_real_req,
other=0,
)
slot_ids = block_numbers * kernel_block_size + block_offsets
slot_ids = block_numbers * kv_block_size + block_offsets
if CP_SIZE != 1:
slot_ids = tl.where(is_local, slot_ids, PAD_ID)
+1 -1
View File
@@ -310,7 +310,7 @@ def _apply_write_kernel(
MULTI_GROUP: tl.constexpr,
):
pid = tl.program_id(0)
row_idx = tl.load(write_indices_ptr + pid)
row_idx = tl.load(write_indices_ptr + pid).to(tl.int64)
start_idx = tl.load(write_starts_ptr + pid)
cu_start = tl.load(write_cu_lens_ptr + pid - 1) if pid > 0 else 0
+52 -7
View File
@@ -3,7 +3,7 @@
import gc
import itertools
from collections import defaultdict
from collections.abc import Callable, Iterable
from collections.abc import Callable, Iterable, Sequence
from contextlib import ExitStack
from dataclasses import dataclass, replace
from itertools import groupby, product
@@ -44,7 +44,11 @@ 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
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.cp_utils import prepare_dcp_local_seq_lens
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.input_batch import (
InputBatch,
InputBuffers,
set_dummy_context,
)
from vllm.v1.worker.gpu.model_states.interface import ModelState
from vllm.v1.worker.ubatch_utils import check_ubatch_thresholds, get_num_ubatches
from vllm.v1.worker.utils import AttentionGroup, clear_layer_kv_caches
@@ -694,9 +698,18 @@ class ModelCudaGraphManager(CudaGraphManager):
if desc.num_ubatches > 1:
# Prepare and park threads before capture; finish runs inside it.
assert self.ubatch_runner is not None
input_batch = InputBatch.make_dummy(num_reqs, num_tokens, input_buffers)
input_block_tables = block_tables.get_dummy_block_tables(num_reqs)
set_dcp_capture_context(
input_batch,
model_state,
block_tables,
input_block_tables,
kv_cache_config,
)
ubatch_state = self.ubatch_runner.prepare(
InputBatch.make_dummy(num_reqs, num_tokens, input_buffers),
block_tables.get_dummy_block_tables(num_reqs),
input_batch,
input_block_tables,
block_tables.get_dummy_slot_mappings(num_tokens),
cg_mode=CUDAGraphMode.FULL,
for_capture=True,
@@ -730,6 +743,9 @@ class ModelCudaGraphManager(CudaGraphManager):
# Capture with dummy rows marked as padding.
input_buffers.is_padding.fill_(True)
is_padding = input_buffers.is_padding[:num_tokens]
if pcp_manager is not None:
is_padding = pcp_manager.moe_is_padding(is_padding)
def forward_fn(cg_mode: CUDAGraphMode) -> None:
batch_descriptor = None
@@ -747,7 +763,7 @@ class ModelCudaGraphManager(CudaGraphManager):
num_tokens_across_dp=num_tokens_across_dp,
slot_mapping=slot_mappings,
batch_descriptor=batch_descriptor,
is_padding=input_buffers.is_padding[:num_tokens],
is_padding=is_padding,
):
if cg_mode == CUDAGraphMode.PIECEWISE:
# PIECEWISE graph (compiled PW or breakable, chosen inside
@@ -783,6 +799,27 @@ class ModelCudaGraphManager(CudaGraphManager):
return hidden_states, [x[: desc.num_tokens] for x in self.aux_hidden_states]
def set_dcp_capture_context(
input_batch: InputBatch,
model_state: ModelState,
block_tables: BlockTables,
input_block_tables: Sequence[torch.Tensor],
kv_cache_config: KVCacheConfig,
) -> None:
# Capture FULL graphs with KV context so a host-side skip of DCP context
# attention is not baked into the graph.
if block_tables.cp_size == 1:
return
set_dummy_context(
input_batch,
block_tables,
block_tables.cp_size * block_tables.cp_interleave,
kv_cache_config.num_blocks,
model_state.max_model_len,
input_block_tables=input_block_tables,
)
def prepare_inputs_to_capture(
num_reqs: int,
num_tokens: int,
@@ -803,7 +840,7 @@ def prepare_inputs_to_capture(
num_reqs, num_tokens, input_buffers, max_query_len=max_query_len
)
if pcp_manager is not None:
input_batch = pcp_manager.prepare_inputs_to_capture(input_batch)
input_batch = pcp_manager.prepare_inputs_for_capture_or_profile(input_batch)
block_table_provider = pcp_manager or block_tables
input_block_tables = block_table_provider.get_dummy_block_tables(num_reqs)
@@ -813,6 +850,14 @@ def prepare_inputs_to_capture(
)
if block_tables.cp_size > 1:
if full_cudagraph:
set_dcp_capture_context(
input_batch,
model_state,
block_tables,
input_block_tables,
kv_cache_config,
)
input_batch.dcp_local_seq_lens = prepare_dcp_local_seq_lens(
input_buffers.dcp_local_seq_lens,
input_batch.seq_lens,
@@ -989,7 +1034,7 @@ def _extrapolate_full_graph_memory(mem_samples: list[int], total_graphs: int) ->
def _init_minimal_kv_cache_for_profiling(runner: "GPUModelRunner") -> None:
"""Allocate the smallest KV cache that still lets every graph be captured."""
from vllm.v1.core.kv_cache_utils import (
from vllm.v1.core.kv_cache_planning import (
get_kv_cache_config_from_groups,
get_kv_cache_groups,
)
+19 -19
View File
@@ -152,7 +152,7 @@ def sync_cudagraph_and_dp_padding(
num_reqs=num_reqs,
)
synced_cg_mode = CUDAGraphMode(int(cg_mode_across_dp.min().item()))
synced_cg_mode = CUDAGraphMode(int(cg_mode_across_dp.min()))
# If any rank wants to run eager, all ranks run eager
if synced_cg_mode == CUDAGraphMode.NONE:
@@ -175,13 +175,13 @@ def sync_cudagraph_and_dp_padding(
"cudagraph_manager should only be None during profile run, "
"where synced_cg_mode must be NONE across all DP ranks"
)
synced_num_tokens = int(num_tokens_across_dp.max().item())
synced_num_tokens = int(num_tokens_across_dp.max())
# Varlen decode graphs are selected by the query-length bound, so ranks must agree
# on it or they pad to different token counts below.
synced_max_query_len: int | None = None
if bool(torch.all(max_query_lens_across_dp != -1).item()):
synced_max_query_len = int(max_query_lens_across_dp.max().item())
if bool(torch.all(max_query_lens_across_dp != -1)):
synced_max_query_len = int(max_query_lens_across_dp.max())
# Dispatch for the final synced values, use num_reqs instead of synced_num_reqs
# so we don't perform request padding for PIECEWISE graphs.
@@ -223,12 +223,12 @@ def dispatch_cg_and_sync_dp(
parallel_config: ParallelConfig | None = None,
allow_ubatching: bool = False,
uniform_decode: bool = False,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
) -> tuple[BatchExecutionDescriptor, DPSyncState | None]:
"""Pick a cudagraph descriptor for this batch, agreeing it across DP ranks.
Runs a collective when dp_size > 1 so every rank dispatches to the same
shape. Pass `dp_sync` from a dispatch already made over this same batch (a
shape. Pass `dp_sync_state` from a dispatch already made over this same batch (a
drafter's prefill runs the target's batch shape) to reuse that agreement
instead, with no collective.
@@ -238,7 +238,7 @@ def dispatch_cg_and_sync_dp(
num_reqs: Requests in this rank's batch.
num_tokens: Tokens in this rank's batch, already padded by the caller.
uniform_token_count: Per-request token count if this rank's batch is a
uniform decode, else None. `dp_sync.uniform_token_count` takes its
uniform decode, else None. `dp_sync_state.uniform_token_count` takes its
place when a sync is reused, since that one is agreed across ranks.
dp_size: Data-parallel world size. 1 skips all cross-rank work.
dp_rank: This rank's index in the DP group.
@@ -254,7 +254,7 @@ def dispatch_cg_and_sync_dp(
microbatches. Agreed across ranks before it takes effect.
uniform_decode: Whether this rank's batch is a uniform decode, used
to pick the microbatching split.
dp_sync: Agreement from a prior dispatch over this same batch, to reuse.
dp_sync_state: Agreement from a prior dispatch over this same batch, to reuse.
Must come from a batch with this same padded `num_tokens` and the
same `uniform_token_count`; `num_reqs` may differ, as neither
depends on it. Passing a sync from a different batch is a caller
@@ -265,7 +265,7 @@ def dispatch_cg_and_sync_dp(
dispatch to reuse. It is None when `dp_size` is 1 or no rank has work.
"""
reuse_eager = dp_sync is not None and dp_sync.eager
reuse_eager = dp_sync_state is not None and dp_sync_state.eager
if need_eager or reuse_eager:
batch_desc = BatchExecutionDescriptor(
@@ -282,7 +282,7 @@ def dispatch_cg_and_sync_dp(
batch_desc = cudagraph_manager.dispatch(
num_reqs,
num_tokens,
dp_sync.uniform_token_count if dp_sync is not None else uniform_token_count,
dp_sync_state.uniform_token_count if dp_sync_state else uniform_token_count,
num_active_loras=num_active_loras,
max_query_len=max_query_len,
)
@@ -290,24 +290,24 @@ def dispatch_cg_and_sync_dp(
if dp_size == 1:
return batch_desc, None
if dp_sync is not None:
assert dp_sync.num_tokens_across_dp[dp_rank] == num_tokens, (
if dp_sync_state is not None:
assert dp_sync_state.num_tokens_across_dp[dp_rank] == num_tokens, (
"reusing a DP sync taken over a different batch"
)
assert (
dp_sync.uniform_token_count is None
or uniform_token_count == dp_sync.uniform_token_count
dp_sync_state.uniform_token_count is None
or uniform_token_count == dp_sync_state.uniform_token_count
), "reusing a DP sync taken over a different batch"
if not dp_sync.eager and batch_desc.num_tokens != num_tokens:
if not dp_sync_state.eager and batch_desc.num_tokens != num_tokens:
# Capture sizes can differ between managers, so this one may
# pad further. Every rank pads alike, so report what will run.
dp_sync = replace(
dp_sync,
dp_sync_state = replace(
dp_sync_state,
num_tokens_across_dp=torch.full_like(
dp_sync.num_tokens_across_dp, batch_desc.num_tokens
dp_sync_state.num_tokens_across_dp, batch_desc.num_tokens
),
)
return batch_desc, dp_sync
return batch_desc, dp_sync_state
return sync_cudagraph_and_dp_padding(
cudagraph_manager,
+56 -5
View File
@@ -13,8 +13,10 @@ from vllm.config import ModelConfig
from vllm.distributed.eplb.eplb_state import EplbState
from vllm.logger import init_logger
from vllm.model_executor.models.interfaces import (
MixtureOfExperts,
get_mixture_of_experts_model,
)
from vllm.models.deepseek_v4.common.eplb_util import dspark_draft_supports_eplb
if TYPE_CHECKING:
from vllm.v1.worker.gpu.model_runner import GPUModelRunner
@@ -22,16 +24,37 @@ if TYPE_CHECKING:
logger = init_logger(__name__)
def eplb_draft_model_name(model_config: ModelConfig) -> str:
"""Return the EPLB step-log display name for a draft model."""
return f"{model_config.model} (draft)"
def draft_model_supports_eplb(
speculative_config: Any | None,
draft_moe_model: MixtureOfExperts | None,
) -> bool:
"""Return whether a draft MoE model should register with EPLB."""
if draft_moe_model is None:
return False
if speculative_config is None or speculative_config.draft_model_config is None:
return False
if getattr(speculative_config, "method", None) == "dspark":
return dspark_draft_supports_eplb(speculative_config.draft_model_config)
return True
def step_eplb_after(*, is_dummy: bool = False) -> Callable:
"""Step EPLB after a model runner method completes successfully."""
def decorator(fn: Callable) -> Callable:
@wraps(fn)
def wrapper(self: Any, *args, **kwargs) -> Any:
result = fn(self, *args, **kwargs)
if kwargs.get("skip_eplb", False):
return result
# The router kernel records load before step() is reached.
with self.eplb.suppress():
return fn(self, *args, **kwargs)
result = fn(self, *args, **kwargs)
is_profile = kwargs.get("is_profile", False) if is_dummy else False
self.eplb.step(is_dummy=is_dummy, is_profile=is_profile)
return result
@@ -70,6 +93,24 @@ class EPLBController:
self.suppressed = False
self._has_registered_models = False
@contextmanager
def suppress(self) -> Iterator[None]:
"""Keep warmup forwards from stepping EPLB or recording expert load."""
should_record = (
self.state.should_record_tensor if self.state is not None else None
)
was_suppressed = self.suppressed
was_recording = should_record.clone() if should_record is not None else None
self.suppressed = True
if should_record is not None:
should_record.fill_(False)
try:
yield
finally:
if should_record is not None and was_recording is not None:
should_record.copy_(was_recording)
self.suppressed = was_suppressed
def prepare_load(self) -> None:
self.state = None
self._has_registered_models = False
@@ -93,16 +134,26 @@ class EPLBController:
draft_model = speculator.model
draft_moe_model = get_mixture_of_experts_model(draft_model)
if draft_moe_model is None:
if not draft_model_supports_eplb(speculative_config, draft_moe_model):
return False
assert draft_moe_model is not None
assert not self.parallel_config.enable_elastic_ep, (
"Elastic EP is not supported with draft model."
)
assert speculative_config is not None
assert speculative_config.draft_model_config is not None
draft_model_config = speculative_config.draft_model_config
assert draft_model_config is not None
logger.info_once(
"EPLB is enabled for MoE part of drafter model %s.",
draft_model_config.model,
)
assert self.state is not None
self.state.add_model(draft_moe_model, speculative_config.draft_model_config)
self.state.add_model(
draft_moe_model,
draft_model_config,
model_name=eplb_draft_model_name(draft_model_config),
)
speculator.set_eplb_state(self.state)
self._has_registered_models = True
return True
+15 -11
View File
@@ -137,7 +137,7 @@ class InputBatch:
req_ids = [f"req_{i}_{random_uuid()}" for i in range(num_reqs)]
idx_mapping_np = np.arange(num_reqs, dtype=np.intp)
idx_mapping = torch.arange(num_reqs, dtype=torch.int32, device=device)
idx_mapping = torch.arange(num_reqs, dtype=torch.int64, device=device)
expanded_idx_mapping = idx_mapping
expanded_local_pos = torch.zeros(num_reqs, dtype=torch.int32, device=device)
@@ -228,7 +228,8 @@ def set_dummy_context(
max_model_len: int,
input_block_tables: Sequence[torch.Tensor] | None = None,
) -> None:
"""Give each dummy request context_len of context, used when profiling step cost."""
"""Give each dummy request context_len of context, for profiling step cost
and for DCP FULL cudagraph capture."""
if input_block_tables is None:
input_block_tables = block_tables.input_block_tables
if not input_block_tables:
@@ -252,17 +253,18 @@ def set_dummy_context(
input_batch.positions.copy_(torch.from_numpy(local_pos + context_len))
seq_len = context_len + query_len
for block_table, block_size, bpk in zip(
input_block_tables,
block_tables.kernel_block_sizes,
block_tables.blocks_per_kv_block,
):
for block_table, block_size in zip(input_block_tables, block_tables.block_sizes):
num_blocks = min(cdiv(seq_len, block_size), block_table.shape[1])
# Spans are disjoint until the pool runs out, then they wrap and share
# blocks: profiling only needs the reads to be realistic, not distinct.
block_ids = torch.arange(
num_reqs * num_blocks, dtype=block_table.dtype, device=block_table.device
) % (num_kv_blocks * bpk)
block_ids = (
torch.arange(
num_reqs * num_blocks,
dtype=block_table.dtype,
device=block_table.device,
)
% num_kv_blocks
)
block_table[:num_reqs, :num_blocks] = block_ids.view(num_reqs, num_blocks)
@@ -714,7 +716,9 @@ def expand_idx_mapping(
) -> tuple[torch.Tensor, torch.Tensor]:
num_reqs = idx_mapping.shape[0]
expanded_idx_mapping = idx_mapping.new_empty(total_num_logits)
expanded_local_pos = idx_mapping.new_empty(total_num_logits)
expanded_local_pos = torch.empty(
total_num_logits, dtype=torch.int32, device=idx_mapping.device
)
_expand_idx_mapping_kernel[(num_reqs,)](
idx_mapping,
expanded_idx_mapping,
+36 -3
View File
@@ -24,12 +24,18 @@ from vllm.v1.outputs import (
if TYPE_CHECKING:
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.worker.gpu.input_batch import InputBatch
class KVConnector:
"""KVConnector interface used by GPUModelRunner."""
def pre_forward(self, scheduler_output: "SchedulerOutput", **kwargs: Any) -> None:
def pre_forward(
self,
scheduler_output: "SchedulerOutput",
input_batch: "InputBatch | None" = None,
attn_metadata: dict[str, Any] | None = None,
) -> None:
pass
def finish_forward(self) -> None:
@@ -61,7 +67,12 @@ class ActiveKVConnector(KVConnector):
self._pending_load_kwargs: dict[str, Any] | None = None
self._disabled = False
def pre_forward(self, scheduler_output: "SchedulerOutput", **kwargs: Any) -> None:
def pre_forward(
self,
scheduler_output: "SchedulerOutput",
input_batch: "InputBatch | None" = None,
attn_metadata: dict[str, Any] | None = None,
) -> None:
if self._disabled:
return
@@ -69,7 +80,9 @@ 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
self._pending_load_kwargs = self._build_load_kwargs(
scheduler_output, input_batch, attn_metadata
)
if scheduler_output.has_sync_kv_loads:
# Sync loads need to run before this step's forward.
@@ -77,6 +90,26 @@ class ActiveKVConnector(KVConnector):
# Otherwise start the async load after forward to keep submission
# off the critical path.
@staticmethod
def _build_load_kwargs(
scheduler_output: "SchedulerOutput",
input_batch: "InputBatch | None",
attn_metadata: dict[str, Any] | None,
) -> dict[str, Any]:
"""Keyword args for the connector's start_load_kv()."""
if input_batch is None:
# No forward this step.
return {}
load_kwargs: dict[str, Any] = dict(
scheduler_output=scheduler_output,
request_state_indices=input_batch.idx_mapping,
request_ids=input_batch.req_ids,
num_tokens=input_batch.num_tokens,
)
if attn_metadata is not None:
load_kwargs["attn_metadata"] = attn_metadata
return load_kwargs
def _start_load_kv(self) -> None:
load_kwargs = self._pending_load_kwargs
assert load_kwargs is not None
+87 -91
View File
@@ -19,6 +19,7 @@ instead of embedding feature-specific logic directly.
import functools
import gc
import time
from collections.abc import Iterable
from contextlib import AbstractContextManager
from copy import deepcopy
from dataclasses import replace
@@ -46,6 +47,7 @@ from vllm.model_executor.layers.mamba.ops.ssu_dispatch import (
initialize_mamba_ssu_backend,
)
from vllm.model_executor.model_loader import get_model_loader
from vllm.model_executor.model_loader.reload.inplace import reload_weights
from vllm.model_executor.models.interfaces import requires_raw_input_tokens
from vllm.model_executor.offloader import (
create_offloader,
@@ -154,6 +156,7 @@ from vllm.v1.worker.gpu.spec_decode.adaptive_verification import (
resolve_adaptive_cudagraph_mode,
)
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
requires_aux_hidden_states,
set_eagle3_aux_hidden_state_layers,
verify_supports_aux_hidden_states_over_pp,
)
@@ -162,7 +165,10 @@ from vllm.v1.worker.gpu.spec_decode.rejection_sampler import (
get_max_chunk_logits,
)
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.utils import DraftTokensHandler
from vllm.v1.worker.gpu.spec_decode.utils import (
DraftTokensHandler,
get_drafter_hidden_states,
)
from vllm.v1.worker.gpu.states import RequestState
from vllm.v1.worker.gpu.structured_outputs import (
StructuredOutputsWorker,
@@ -292,19 +298,20 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.vllm_config, self.device, self.req_states
)
if self.speculative_config.method in (
"eagle3",
"dflash",
"dspark",
"extract_hidden_states",
):
# Drafting may require auxiliary hidden states from target model outputs
self.use_aux_hidden_state_outputs = True
self.use_aux_hidden_state_outputs = requires_aux_hidden_states(
self.speculative_config
)
# Draft tokens propagation - for spec-dec + struct outputs.
self.draft_tokens_handler = DraftTokensHandler(self.device)
self.pcp_manager: pcp.PCPManager | None = None
# Built before memory profiling; block tables are attached at KV init.
self.pcp_manager = pcp.maybe_build_pcp_manager(
self.vllm_config,
self.device,
self.supports_mm_inputs,
cls=self.pcp_manager_cls,
)
# Pooling models.
self.is_pooling_model = self.model_config.runner_type == "pooling"
@@ -370,9 +377,15 @@ class GPUModelRunner(LoRAModelRunnerMixin):
tasks.extend(PoolingRunner.get_supported_tasks(self.model))
return tuple(tasks)
def load_model(self, load_dummy_weights: bool = False, *args, **kwargs) -> None:
def load_model(
self,
load_dummy_weights: bool = False,
*args,
model: nn.Module | None = None,
**kwargs,
) -> None:
time_before_load = time.perf_counter()
if load_dummy_weights:
if model is None and load_dummy_weights:
self.load_config.load_format = "dummy"
self.eplb.prepare_load()
eplb_models_added = False
@@ -382,7 +395,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# Capture warmup providers selected while constructing the model.
with self.jit_warmup_registry.activate():
self.model = model_loader.load_model(
self.model = model or model_loader.load_model(
vllm_config=self.vllm_config,
model_config=self.vllm_config.model_config,
)
@@ -447,9 +460,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.vllm_config, self.req_states, self.is_pooling_model, config_processors
)
if self.is_last_pp_rank and not self.is_pooling_model:
# V2 bypasses TopKTopPSampler, which registers native warmups.
# ROCm only: on CUDA these warmups add ~2 min to every engine start.
if current_platform.is_rocm():
# Speculative verification uses native top-k/top-p masking even
# when target-only sampling can use FlashInfer's fused sampler.
if current_platform.is_rocm() or (
current_platform.is_cuda() and self.speculative_config is not None
):
from vllm.v1.sample.ops.topk_topp_sampler import (
register_top_k_top_p_warmups,
)
@@ -554,22 +569,21 @@ class GPUModelRunner(LoRAModelRunnerMixin):
return None
return speculator.model
def reload_weights(self, *args, **kwargs) -> None:
# TODO(Wentao): Use full version instead of import when fully migrated to v2
from vllm.v1.worker.gpu_model_runner import GPUModelRunner as GPUModelRunnerV1
GPUModelRunnerV1.reload_weights(self, *args, **kwargs) # type: ignore[arg-type]
def update_config(self, *args, **kwargs) -> None:
# TODO(Wentao): Use full version instead of import when fully migrated to v2
from vllm.v1.worker.gpu_model_runner import GPUModelRunner as GPUModelRunnerV1
GPUModelRunnerV1.update_config(self, *args, **kwargs) # type: ignore[arg-type]
# v2 reads config via self.vllm_config (e.g. in load_model), so keep it
# in sync with the attributes the v1 helper just replaced.
self.vllm_config.model_config = self.model_config
self.vllm_config.load_config = self.load_config
def reload_weights(
self,
weights_iterator: Iterable[tuple[str, torch.Tensor]] | None = None,
weights_path: str | None = None,
is_checkpoint_format: bool = True,
) -> None:
"""Reload weights in place."""
vllm_config = self.vllm_config
model = self.get_model()
reload_weights(
vllm_config, model, weights_iterator, weights_path, is_checkpoint_format
)
self.reset_lora_state()
self.reset_encoder_cache()
self.reset_mm_cache()
@functools.cached_property
def main_stream(self) -> torch.cuda.Stream:
@@ -578,9 +592,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
def get_encoder_timing_stats(self) -> dict[str, dict[str, float | int]]:
encoder_runner = getattr(self.model_state, "encoder_runner", None)
if encoder_runner is None:
return {}
return encoder_runner.get_encoder_timing_stats()
return encoder_runner.get_encoder_timing_stats() if encoder_runner else {}
def get_kv_cache_spec(self):
kv_cache_spec = get_kv_cache_spec(self.vllm_config)
@@ -688,20 +700,14 @@ class GPUModelRunner(LoRAModelRunnerMixin):
max_num_batched_tokens=self.max_num_tokens,
max_num_blocks_per_group=max_num_blocks_per_group,
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,
)
self.pcp_manager = pcp.maybe_build_pcp_manager(
self.vllm_config,
self.device,
self.supports_mm_inputs,
self.block_tables,
cls=self.pcp_manager_cls,
)
if self.pcp_manager is not None:
self.pcp_manager.set_block_tables(self.block_tables)
self.ubatch_runner = maybe_build_ubatch_runner(
self.vllm_config,
self.device,
@@ -773,6 +779,13 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.vllm_config,
kv_cache_allocation_context=kv_cache_allocation_context,
block_tables=self.block_tables,
# Draft groups build their own metadata, so they map the views too.
attn_groups=(
g
for groups in self.attn_groups
+ getattr(self.speculator, "attn_groups", [])
for g in groups
),
)
self.kv_caches = [
cache for cache in kv_caches_dict.values() if cache.device == self.device
@@ -843,6 +856,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
- num_reqs * self.speculator.num_extra_query_per_req,
)
assert num_tokens <= self.max_num_tokens, (
f"Dummy run with {num_tokens} tokens exceeds max_num_batched_tokens "
f"({self.max_num_tokens})"
)
# Distribute the remainder evenly so no dummy request exceeds
# ceil(num_tokens / num_reqs) <= max_model_len tokens.
@@ -899,7 +917,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
slot_mappings_by_layer = self.execute_model_state.slot_mappings_by_layer
hidden_states = self.execute_model_state.hidden_states
aux_hidden_states = self.execute_model_state.aux_hidden_states
dp_sync = self.execute_model_state.dp_sync
dp_sync_state = self.execute_model_state.dp_sync_state
self.execute_model_state = None
self.step_timing.forward_end()
@@ -915,7 +933,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
mm_inputs = [], all_false
spec_hidden_states = self._get_drafter_hidden_states(hidden_states)
spec_hidden_states = get_drafter_hidden_states(self.model, hidden_states)
if isinstance(self.sampler, GPUWatermarkSampler):
self.speculator.prepare_watermarking(
self.sampler, input_batch.idx_mapping
@@ -937,7 +955,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
next_prefill_tokens=self.req_states.next_prefill_tokens,
temperature=self.sampler.sampling_states.temperature.gpu,
seeds=self.sampler.sampling_states.seeds.gpu,
dp_sync=dp_sync,
dp_sync_state=dp_sync_state,
dummy_run=True,
skip_attn_for_dummy_run=skip_attn,
mm_inputs=mm_inputs,
@@ -1018,7 +1036,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
@torch.inference_mode()
def profile_cudagraph_memory(self) -> int:
"""Estimate the GPU memory required to capture CUDA graphs."""
return _profile_cudagraph_memory(self)
# Runs before the KV cache exists, outside compile_or_warm_up_model.
with self.eplb.suppress():
return _profile_cudagraph_memory(self)
def needs_cudagraph_capture(self) -> bool:
"""Whether capture_model() has any CUDA graphs left to capture."""
@@ -1217,17 +1237,13 @@ 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 and req_id not in table_updates:
if req_new_block_ids is not None:
self.block_tables.append_block_ids(
req_index, req_new_block_ids, overwrite=False
)
@@ -1355,7 +1371,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
num_scheduled_tokens_np = batch_req_state.num_scheduled_tokens
idx_mapping_np = batch_req_state.idx_mapping_np
idx_mapping = async_tensor_h2d(
idx_mapping_np, device=self.device, dtype=torch.int32
idx_mapping_np, device=self.device, dtype=torch.int64
)
num_reqs = len(req_ids)
@@ -1765,7 +1781,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# cross-attention cache with dynamic encoder outputs.
skip_compiled = True
batch_desc, dp_sync = dispatch_cg_and_sync_dp(
batch_desc, dp_sync_state = dispatch_cg_and_sync_dp(
self.cudagraph_manager,
num_reqs,
num_toks,
@@ -1833,7 +1849,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# All-zero input_ids route every token to the same experts.
input_batch.input_ids.random_(0, self.vocab_size)
if self.pcp_manager is not None:
input_batch = self.pcp_manager.prepare_inputs_to_capture(input_batch)
input_batch = self.pcp_manager.prepare_inputs_for_capture_or_profile(
input_batch
)
if skip_attn_for_dummy_run:
assert batch_desc.cg_mode != CUDAGraphMode.FULL, (
"Attention metadata must be prepared for dummy runs when using "
@@ -1888,9 +1906,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
assert block_tables is not None
attn_groups = self.attn_groups
if dummy_run and is_profile:
if dummy_run and is_profile and not valid_dummy_state_slots:
# Mamba layers take a cheap warmup path with no metadata;
# attention metadata is still built so those kernels tune.
# valid_dummy_state_slots runs the real Mamba kernels on distinct
# state slots; the caller must restore that state afterwards.
attn_groups = [
[g for g in groups if not isinstance(g.kv_cache_spec, MambaSpec)]
for groups in attn_groups
@@ -1977,13 +1997,6 @@ 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.
@@ -1991,7 +2004,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# because they are already copied to the CUDA graph input buffers.
assert self.cudagraph_manager is not None
self.kv_connector.pre_forward(
**connector_kwargs, attn_metadata=attn_metadata
scheduler_output, input_batch, attn_metadata=attn_metadata
)
model_output = self.cudagraph_manager.run_fullgraph(batch_desc)
else:
@@ -2007,16 +2020,15 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.vllm_config,
num_tokens=input_batch.num_tokens_after_padding,
cudagraph_runtime_mode=batch_desc.cg_mode,
num_tokens_across_dp=(
dp_sync.num_tokens_across_dp if dp_sync is not None else None
),
num_tokens_across_dp=dp_sync_state
and dp_sync_state.num_tokens_across_dp,
batch_descriptor=batch_descriptor,
ubatch_slices=ubatch_slices,
slot_mapping=slot_mappings_by_layer,
skip_compiled=skip_compiled,
is_padding=input_batch.is_padding,
):
self.kv_connector.pre_forward(**connector_kwargs)
self.kv_connector.pre_forward(scheduler_output, input_batch)
if ubatch_state is not None:
assert self.ubatch_runner is not None
model_output = self.ubatch_runner.run(
@@ -2058,7 +2070,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
slot_mappings_by_layer=slot_mappings_by_layer,
hidden_states=hidden_states,
aux_hidden_states=aux_hidden_states,
dp_sync=dp_sync,
dp_sync_state=dp_sync_state,
finished_req_ids=finished_req_ids,
ec_connector_output=ec_connector_output,
cudagraph_stats=cudagraph_stats,
@@ -2074,24 +2086,6 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
return None
def _get_drafter_hidden_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
"""Hidden states fed to the drafter.
Targets such as DeepSeek V4 expose the pre-hc_head residual through
get_mtp_target_hidden_states(). The buffer is sized at
max_num_batched_tokens and only allocated for drafters that consume
target hidden states, so None means "use the regular hidden states".
"""
get_target_hidden_states = getattr(
self.model, "get_mtp_target_hidden_states", None
)
if get_target_hidden_states is None:
return hidden_states
target_hidden_states = get_target_hidden_states()
if target_hidden_states is None:
return hidden_states
return target_hidden_states[: hidden_states.shape[0]]
@torch.inference_mode()
@step_eplb_after()
def sample_tokens(
@@ -2106,7 +2100,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
slot_mappings_by_layer = self.execute_model_state.slot_mappings_by_layer
hidden_states = self.execute_model_state.hidden_states
aux_hidden_states = self.execute_model_state.aux_hidden_states
dp_sync = self.execute_model_state.dp_sync
dp_sync_state = self.execute_model_state.dp_sync_state
finished_req_ids = self.execute_model_state.finished_req_ids
ec_connector_output = self.execute_model_state.ec_connector_output
cudagraph_stats = self.execute_model_state.cudagraph_stats
@@ -2237,7 +2231,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.speculator.observe_verification(
input_batch.idx_mapping, num_sampled, num_rejected
)
spec_hidden_states = self._get_drafter_hidden_states(draft_hidden_states)
spec_hidden_states = get_drafter_hidden_states(
self.model, draft_hidden_states
)
if isinstance(self.sampler, GPUWatermarkSampler):
self.speculator.prepare_watermarking(
self.sampler, input_batch.idx_mapping
@@ -2256,7 +2252,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.sampler.sampling_states.temperature.gpu,
self.sampler.sampling_states.seeds.gpu,
num_speculative_tokens=num_spec_tokens,
dp_sync=dp_sync,
dp_sync_state=dp_sync_state,
mm_inputs=mm_inputs,
)
if num_spec_tokens < self.num_speculative_steps:
@@ -2413,7 +2409,7 @@ class ExecuteModelState(NamedTuple):
slot_mappings_by_layer: dict[str, torch.Tensor] | None
hidden_states: torch.Tensor | None
aux_hidden_states: list[torch.Tensor] | None
dp_sync: DPSyncState | None
dp_sync_state: DPSyncState | None
finished_req_ids: set[str]
ec_connector_output: ECConnectorOutput | None
cudagraph_stats: CUDAGraphStat | None
@@ -135,7 +135,7 @@ class EncoderDecoderModelState(ModelState):
if for_capture:
max_seq_len = self.max_model_len
else:
max_seq_len = int(seq_lens_cpu_upper_bound[:num_reqs].max().item())
max_seq_len = int(seq_lens_cpu_upper_bound[:num_reqs].max())
attn_metadata = build_attn_metadata(
attn_groups=attn_groups,
num_reqs=num_reqs,
@@ -105,12 +105,15 @@ class EncoderOnlyModelState(DefaultModelState):
if pooling_params is None or pooling_params.extra_kwargs is None:
return
token_type_start = pooling_params.extra_kwargs.get("compressed_token_type_ids")
if token_type_start is not None:
token_type_range = pooling_params.extra_kwargs.get("compressed_token_type_ids")
if token_type_range is not None:
assert new_req_data.prompt_token_ids is not None
token_type_start, token_type_end = token_type_range
positions = torch.arange(
len(new_req_data.prompt_token_ids), dtype=torch.int32
)
self.token_type_ids[new_req_data.req_id] = (
torch.arange(len(new_req_data.prompt_token_ids), dtype=torch.int32)
>= token_type_start
(positions >= token_type_start) & (positions < token_type_end)
).to(torch.int32)
def remove_request(self, req_id: str) -> None:
@@ -288,7 +288,14 @@ class MambaHybridModelState(DefaultModelState):
# Test request state, not num_scheduled_tokens == draft_count+1:
# adaptive rewrites num_scheduled_tokens to an even split, so that
# equality rarely holds and would demote every verify row to decode.
is_decode = ~is_prefilling_np & (input_batch.num_scheduled_tokens > 0)
is_decode = (
~is_prefilling_np
& (input_batch.num_scheduled_tokens > 0)
& (
input_batch.num_scheduled_tokens
<= self.vllm_config.num_speculative_tokens + 1
)
)
num_decode_draft_tokens_np[: input_batch.num_reqs] = np.where(
is_decode, num_draft_tokens_per_req, -1
)
+50 -11
View File
@@ -56,6 +56,7 @@ class PCPManager:
dcp_world_size: int = 1,
dcp_rank: int = 0,
cp_interleave: int = 1,
moe_gathers_tokens: bool = False,
) -> None:
self.pcp_world_size = pcp_world_size
self.pcp_rank = pcp_rank
@@ -69,11 +70,16 @@ class PCPManager:
self._local_batch: InputBatch | None = None
self._local_gather_idx: torch.Tensor | None = None
self.draft_prefill_batch: InputBatch | None = None
self._block_tables = block_tables
self._hidden_restore_idx: torch.Tensor | None = None
self._padded_gather_idx: torch.Tensor | None = None
self._gathered_kv_write_mask: torch.Tensor | None = None
self._pad_slot_id = torch.tensor(PAD_SLOT_ID, dtype=torch.int64, device=device)
# Padding mask over the PCP-gathered rows the MoE routes (rank-major).
self._moe_is_padding = (
torch.ones(max_num_tokens * pcp_world_size, dtype=torch.bool, device=device)
if moe_gathers_tokens and max_num_tokens is not None
else None
)
max_num_local_reqs = 2 * max_num_reqs if max_num_reqs is not None else None
self._input_buffers = (
@@ -81,6 +87,18 @@ class PCPManager:
if max_num_local_reqs is not None and max_num_tokens is not None
else None
)
self._max_num_local_reqs = max_num_local_reqs
self._max_num_tokens = max_num_tokens
self.set_block_tables(block_tables)
def set_block_tables(self, block_tables: BlockTables | None) -> None:
"""Attach the KV block tables, which only exist after KV cache init."""
self._block_tables = block_tables
if block_tables is not None:
self.cp_interleave = block_tables.cp_interleave
max_num_local_reqs = self._max_num_local_reqs
max_num_tokens = self._max_num_tokens
device, pcp_world_size = self.device, self.pcp_world_size
self._local_block_tables: tuple[torch.Tensor, ...] | None
self._local_block_table_ptrs: torch.Tensor | None
if block_tables is not None and max_num_local_reqs is not None:
@@ -593,6 +611,12 @@ class PCPManager:
input_buffers.positions[:num_local_tokens_padded].masked_fill_(
is_padding, 0
)
if self._moe_is_padding is not None:
rows = np.arange(num_local_tokens_padded)
gathered = rows >= np.array(per_rank_num_tokens)[:, None]
is_padding = async_tensor_h2d(
gathered.ravel(), out=self._moe_is_padding[: gathered.size]
)
total_num_logits = num_local_reqs if num_local_tokens > 0 else 0
if total_num_logits > 0:
@@ -653,9 +677,7 @@ class PCPManager:
idx_mapping=local_to_global_req_idx,
idx_mapping_np=local_to_global_req_idx_np,
expanded_idx_mapping=local_to_global_req_idx,
expanded_local_pos=torch.zeros(
num_local_reqs, dtype=torch.int32, device=self.device
),
expanded_local_pos=input_batch.expanded_local_pos.new_zeros(num_local_reqs),
num_scheduled_tokens=local_num_scheduled_tokens,
num_tokens=num_local_tokens,
num_tokens_after_padding=num_local_tokens_padded,
@@ -685,7 +707,9 @@ class PCPManager:
)
return self._local_batch
def prepare_inputs_to_capture(self, input_batch: InputBatch) -> InputBatch:
def prepare_inputs_for_capture_or_profile(
self, input_batch: InputBatch
) -> InputBatch:
"""Stage a capture or dummy batch in persistent PCP input buffers."""
input_buffers = self.input_buffers
num_reqs = input_batch.num_reqs_after_padding
@@ -694,8 +718,8 @@ class PCPManager:
input_batch,
input_ids=input_buffers.input_ids[:num_tokens].copy_(input_batch.input_ids),
positions=input_buffers.positions[:num_tokens].copy_(input_batch.positions),
is_padding=input_buffers.is_padding[:num_tokens].copy_(
input_batch.is_padding
is_padding=self.moe_is_padding(
input_buffers.is_padding[:num_tokens].copy_(input_batch.is_padding)
),
query_start_loc=input_buffers.query_start_loc[: num_reqs + 1].copy_(
input_batch.query_start_loc
@@ -704,6 +728,15 @@ class PCPManager:
)
return input_batch
def moe_is_padding(self, is_padding: torch.Tensor) -> torch.Tensor:
"""Expand a capture/dummy padding mask, identical on every PCP rank, to
the rows the MoE routes."""
if self._moe_is_padding is None:
return is_padding
out = self._moe_is_padding[: self.pcp_world_size * is_padding.shape[0]]
out.view(self.pcp_world_size, -1).copy_(is_padding)
return out
def get_dummy_block_tables(self, num_reqs: int) -> tuple[torch.Tensor, ...]:
assert self._local_block_tables is not None
return tuple(
@@ -779,9 +812,13 @@ class PCPManager:
return gathered[self._hidden_restore_idx]
def get_draft_input_buffers(
self, input_buffers: InputBuffers
) -> InputBatch | InputBuffers:
return self.draft_prefill_batch or input_buffers
self, input_buffers: InputBuffers, num_tokens: int
) -> tuple[InputBatch | InputBuffers, torch.Tensor]:
"""Return draft inputs and their MoE routing padding mask."""
batch = self.draft_prefill_batch
if batch is not None:
return batch, batch.is_padding
return input_buffers, self.moe_is_padding(input_buffers.is_padding[:num_tokens])
def prepare_draft_prefill(
self, input_batch: InputBatch, input_ids: torch.Tensor
@@ -833,7 +870,7 @@ def maybe_build_pcp_manager(
vllm_config: VllmConfig,
device: torch.device,
supports_mm_inputs: bool,
block_tables: BlockTables,
block_tables: BlockTables | None = None,
cls: type[PCPManager] = PCPManager,
) -> PCPManager | None:
parallel_config = vllm_config.parallel_config
@@ -858,4 +895,6 @@ def maybe_build_pcp_manager(
dcp_world_size=dcp_size,
dcp_rank=dcp_rank,
cp_interleave=parallel_config.cp_kv_cache_interleave_size,
# Without EP all2all kernels, MoERunner all-gathers PCP tokens to route.
moe_gathers_tokens=not parallel_config.enable_expert_parallel,
)
+7 -13
View File
@@ -214,21 +214,15 @@ class BatchSharder:
local_logits_indices = torch.empty(
num_local_logits, dtype=torch.int64, device=self.device
)
local_idx_mapping = torch.empty(
num_local_reqs, dtype=torch.int32, device=self.device
local_idx_mapping = input_batch.idx_mapping.new_empty(num_local_reqs)
local_cu_num_logits = input_batch.cu_num_logits.new_empty(num_local_reqs + 1)
local_expanded_idx_mapping = input_batch.expanded_idx_mapping.new_empty(
num_local_logits
)
local_cu_num_logits = torch.empty(
num_local_reqs + 1, dtype=torch.int32, device=self.device
)
local_expanded_idx_mapping = torch.empty(
num_local_logits, dtype=torch.int32, device=self.device
)
local_expanded_local_pos = torch.empty(
num_local_logits, dtype=torch.int32, device=self.device
)
local_seq_lens = torch.empty(
num_local_reqs, dtype=torch.int32, device=self.device
local_expanded_local_pos = input_batch.expanded_local_pos.new_empty(
num_local_logits
)
local_seq_lens = input_batch.seq_lens.new_empty(num_local_reqs)
if num_reqs > 0:
_build_shard_plan_kernel[(num_reqs,)](
input_batch.idx_mapping,
+1 -1
View File
@@ -62,7 +62,7 @@ class PenaltiesState(LogitsProcessor):
def apply_staged_writes(self) -> None:
if self._new_penalties_reqs:
idx_mapping = async_tensor_h2d(
self._new_penalties_reqs, dtype=torch.int32, device=self.device
self._new_penalties_reqs, dtype=torch.int64, device=self.device
)
prefill_lens = self.req_states.prefill_len.np[self._new_penalties_reqs]
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable, Mapping
from typing import Any
import torch
@@ -84,11 +85,11 @@ class DFlashCudaGraphManager(CudaGraphManager):
kv_cache_config: KVCacheConfig,
max_model_len: int,
causal: bool | Mapping[int, bool],
precompute_context_kv: Callable[[int], None],
prepare_forward: Callable[[int, dict[str, Any] | None], None],
progress_bar_desc: str = "Capturing CUDA graphs",
) -> None:
"""``precompute_context_kv(num_reqs)`` is captured ahead of the query
forward."""
"""``prepare_forward(num_reqs, attn_metadata)`` is captured ahead of the
query forward."""
def create_forward_fn(
desc: BatchExecutionDescriptor,
@@ -115,7 +116,7 @@ class DFlashCudaGraphManager(CudaGraphManager):
attn_metadata, slot_mappings = attn_state
def forward(cg_mode: CUDAGraphMode) -> None:
precompute_context_kv(num_reqs)
prepare_forward(num_reqs, attn_metadata)
forward_fn(
num_reqs,
num_tokens,
@@ -25,6 +25,9 @@ from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.model_states.interface import ModelState
from vllm.v1.worker.gpu.spec_decode.dflash.cudagraph import DFlashCudaGraphManager
from vllm.v1.worker.gpu.spec_decode.dflash.utils import load_dflash_model
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
get_eagle3_aux_layers_from_config,
)
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.utils import get_parallel_drafting_token_id
from vllm.v1.worker.utils import AttentionGroup
@@ -90,6 +93,20 @@ class DFlashSpeculator(DraftModelSpeculator):
self.max_num_tokens, dtype=torch.int64, device=device
)
# Fixed-address inputs of the FULL graph's context step: the target's aux
# hidden states and, for an anchor that reads them, the rejected counts.
self._aux_staging: torch.Tensor | None = None
self._num_rejected: torch.Tensor | None = None
aux_layers = get_eagle3_aux_layers_from_config(speculative_config)
cudagraph_mode = vllm_config.compilation_config.cudagraph_mode
if aux_layers and cudagraph_mode.decode_mode() == CUDAGraphMode.FULL:
self._aux_staging = torch.zeros(
self._num_graph_context_tokens(self.max_num_reqs),
len(aux_layers) * vllm_config.model_config.get_hidden_size(),
dtype=self.dtype,
device=device,
)
# Per-mask-token sampling buffers. Flattened from (num_reqs, num_spec_tokens).
max_num_sampled_tokens = self.max_num_reqs * self.num_speculative_steps
self.sample_indices = torch.zeros(
@@ -102,7 +119,7 @@ class DFlashSpeculator(DraftModelSpeculator):
# full buffer before a real batch has populated it, so zero would make
# every padding row scatter into request slot 0.
self.sample_idx_mapping = torch.full(
(max_num_sampled_tokens,), -1, dtype=torch.int32, device=device
(max_num_sampled_tokens,), -1, dtype=torch.int64, device=device
)
# [0, 1, ..., N-1, 0, 1, ..., N-1, ...] -> the per-token column index into
# draft_logits[req, step, :].
@@ -166,12 +183,59 @@ class DFlashSpeculator(DraftModelSpeculator):
self.kv_cache_config,
self.max_model_len,
causal=self._group_causal,
precompute_context_kv=lambda num_reqs: self._precompute_context_kv(
0, self._num_graph_context_tokens(num_reqs)
),
prepare_forward=self._prepare_graph_forward,
progress_bar_desc=f"Capturing {self._speculator_name.lower()} CUDA graphs",
)
def _prepare_graph_forward(
self, num_reqs: int, attn_metadata: dict[str, Any] | None
) -> None:
"""The FULL graph's context step: combine the staged target hidden
states, publish the context anchor and store the context K/V."""
num_context = self._num_graph_context_tokens(num_reqs)
if self._aux_staging is not None:
self.hidden_states[:num_context].copy_(
self.model.combine_hidden_states(self._aux_staging[:num_context])
)
self.prepare_context_anchor(
num_reqs, self.target_input_buffers.query_start_loc, self._num_rejected
)
self._precompute_context_kv(0, num_context)
# Recorded in the FULL graph so replays skip the eager metadata build.
if attn_metadata is not None and self.supports_decode_metadata_update:
self._update_draft_decode_metadata(attn_metadata, num_reqs)
def _prepare_graph_replay(
self,
input_batch: InputBatch,
num_graph_reqs: int,
last_hidden_states: torch.Tensor,
aux_hidden_states: list[torch.Tensor] | None,
num_rejected: torch.Tensor,
dummy_run: bool,
) -> None:
"""Eager work before a FULL replay: stage the inputs _prepare_graph_forward
reads and store the context rows past the graph's num_context rows."""
num_reqs = input_batch.num_reqs
num_target_tokens = input_batch.num_tokens
num_context = self._num_graph_context_tokens(num_graph_reqs)
self._store_hidden_states(
num_target_tokens, last_hidden_states, aux_hidden_states, num_context
)
if self._num_rejected is not None:
self._num_rejected[:num_reqs].copy_(num_rejected[:num_reqs])
if dummy_run:
# Dummy block tables are placeholders: write no context K/V.
self._context_slot_mappings[:, :num_context].fill_(PAD_SLOT_ID)
elif num_target_tokens <= num_context:
# Rows past the batch keep stale positions but write no K/V.
self._context_slot_mappings[:, num_target_tokens:num_context].fill_(
PAD_SLOT_ID
)
else:
# Prefill context beyond the graph's rows is stored before replay.
self._precompute_context_kv(num_context, num_target_tokens)
def load_draft_model(
self,
target_model: nn.Module,
@@ -265,6 +329,7 @@ class DFlashSpeculator(DraftModelSpeculator):
num_tokens_across_dp=num_tokens_across_dp,
slot_mapping=slot_mappings,
batch_descriptor=batch_descriptor,
is_padding=self.input_buffers.is_padding[:num_tokens],
):
last_hidden_states = self.model(
input_ids=self.input_buffers.input_ids[:num_tokens],
@@ -328,10 +393,42 @@ class DFlashSpeculator(DraftModelSpeculator):
context_slots,
)
def prepare_context_anchor(
self, input_batch: InputBatch, num_rejected: torch.Tensor
def _store_hidden_states(
self,
num_tokens: int,
last_hidden_states: torch.Tensor,
aux_hidden_states: list[torch.Tensor] | None,
num_graph_tokens: int = 0,
) -> None:
"""Publish context features required by a draft's candidate head."""
# A FULL graph combines its first num_graph_tokens rows from the staged
# aux hidden states; the remaining rows are combined here.
start = 0
if num_graph_tokens and self._aux_staging is not None:
assert aux_hidden_states
start = min(num_tokens, num_graph_tokens)
torch.cat(
[h[:start] for h in aux_hidden_states],
dim=-1,
out=self._aux_staging[:start],
)
if start == num_tokens:
return
if aux_hidden_states:
hidden_states = self.model.combine_hidden_states(
torch.cat([h[start:num_tokens] for h in aux_hidden_states], dim=-1)
)
else:
hidden_states = last_hidden_states[start:num_tokens]
self.hidden_states[start:num_tokens].copy_(hidden_states)
def prepare_context_anchor(
self,
num_reqs: int,
query_start_loc: torch.Tensor,
num_rejected: torch.Tensor | None,
) -> None:
"""Publish context features required by a draft's candidate head. Runs
inside the FULL graph, so it must not sync with the host."""
@torch.inference_mode()
def propose(
@@ -355,7 +452,7 @@ class DFlashSpeculator(DraftModelSpeculator):
temperature: torch.Tensor,
# [max_num_reqs]
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
@@ -374,19 +471,16 @@ class DFlashSpeculator(DraftModelSpeculator):
# number of rejected tokens, we maintain the size of input_ids and
# hidden_states the same as the target model's. This means, we pad each
# request's query length to include any rejected positions.
if aux_hidden_states:
hidden_states = self.model.combine_hidden_states(
torch.cat(aux_hidden_states, dim=-1)
)
else:
hidden_states = last_hidden_states
self.hidden_states[:num_target_tokens].copy_(hidden_states[:num_target_tokens])
self.prepare_context_anchor(input_batch, num_rejected)
if dummy_run and skip_attn_for_dummy_run:
# Memory profiling path: block_tables / kv_cache_config are not initialized.
# Since DFlash needs to build its own attention metadata, we must skip the
# preparation in this path and run a minimal forward pass.
self._store_hidden_states(
num_target_tokens, last_hidden_states, aux_hidden_states
)
self.prepare_context_anchor(
num_reqs, input_batch.query_start_loc, num_rejected
)
self.model.precompute_and_store_context_kv(
self.hidden_states[:num_target_tokens],
self.context_positions[:num_target_tokens],
@@ -432,7 +526,7 @@ class DFlashSpeculator(DraftModelSpeculator):
temperature,
seeds,
self.block_tables.input_block_tables[gid],
self.block_tables.kernel_block_sizes[gid],
self.block_tables.block_sizes[gid],
self.block_tables.cp_rank,
self.dcp_size,
self.block_tables.cp_interleave,
@@ -446,8 +540,10 @@ class DFlashSpeculator(DraftModelSpeculator):
)
batch_sync, num_batch_tokens = (
self._build_uniform_batch_dp_sync(dp_sync, num_reqs, self.num_query_per_req)
if dp_sync is not None
self._build_uniform_batch_dp_sync(
dp_sync_state, num_reqs, self.num_query_per_req
)
if dp_sync_state is not None
else (None, num_query_tokens)
)
# Every DFlash step has exactly num_query_per_req tokens, so we can use FULL CGs
@@ -459,7 +555,7 @@ class DFlashSpeculator(DraftModelSpeculator):
dp_size=self.dp_size,
dp_rank=self.dp_rank,
need_eager=is_profile,
dp_sync=batch_sync,
dp_sync_state=batch_sync,
)
num_tokens_padded = batch_desc.num_tokens
num_tokens_across_dp = (
@@ -467,46 +563,50 @@ class DFlashSpeculator(DraftModelSpeculator):
)
if batch_desc.cg_mode == CUDAGraphMode.FULL:
# The graph stores the first num_context context rows.
assert batch_desc.num_reqs is not None
num_context = self._num_graph_context_tokens(batch_desc.num_reqs)
if dummy_run:
# Dummy block tables are placeholders: write no context K/V.
self._context_slot_mappings[:, :num_context].fill_(PAD_SLOT_ID)
elif num_target_tokens <= num_context:
# Rows past the batch keep stale positions but write no K/V.
self._context_slot_mappings[:, num_target_tokens:num_context].fill_(
PAD_SLOT_ID
)
else:
# Prefill context beyond the graph's rows is stored before replay.
self._precompute_context_kv(num_context, num_target_tokens)
self._prepare_graph_replay(
input_batch,
batch_desc.num_reqs,
last_hidden_states,
aux_hidden_states,
num_rejected,
dummy_run,
)
else:
self._store_hidden_states(
num_target_tokens, last_hidden_states, aux_hidden_states
)
self.prepare_context_anchor(
num_reqs, input_batch.query_start_loc, num_rejected
)
self._precompute_context_kv(0, num_target_tokens, dummy_run)
# Rebuild the draft attention metadata even when replaying the FULL
# graph so that any attention metadata builder state is updated.
draft_attn_metadata = self._build_uniform_attn_metadata(
num_reqs=num_reqs,
batch_desc=batch_desc,
num_query_per_req=self.num_query_per_req,
seq_lens_cpu_upper_bound=input_batch.seq_lens_cpu_upper_bound,
step=self.num_query_per_req,
causal=self._group_causal,
)
draft_slot_mappings_by_layer = build_slot_mappings_by_layer(
self.block_tables.slot_mappings[:, :num_tokens_padded],
self.kv_cache_config,
)
is_full_cudagraph = batch_desc.cg_mode == CUDAGraphMode.FULL
# During FULL cudagraph with a model that supports decode metadata updates,
# the metadata update is captured in the graph, and we can skip the full
# build below.
if not (is_full_cudagraph and self.supports_decode_metadata_update):
draft_attn_metadata = self._build_uniform_attn_metadata(
num_reqs=num_reqs,
batch_desc=batch_desc,
num_query_per_req=self.num_query_per_req,
seq_lens_cpu_upper_bound=input_batch.seq_lens_cpu_upper_bound,
step=self.num_query_per_req,
causal=self._group_causal,
)
# DFlash processes all speculative tokens in one forward pass,
# so the real token count is num_query_tokens.
self._prepare_eplb_forward(num_query_tokens)
if batch_desc.cg_mode == CUDAGraphMode.FULL:
if is_full_cudagraph:
assert self.query_cudagraph_manager is not None
self.query_cudagraph_manager.run_fullgraph(batch_desc)
else:
draft_slot_mappings_by_layer = build_slot_mappings_by_layer(
self.block_tables.slot_mappings[:, :num_tokens_padded],
self.kv_cache_config,
)
self._generate_draft(
num_reqs,
num_tokens_padded,
@@ -524,6 +624,7 @@ def _prepare_dflash_inputs_kernel(
# Outputs
out_input_ids_ptr,
out_query_positions_ptr,
out_is_padding_ptr,
out_query_start_loc_ptr,
out_seq_lens_ptr,
out_query_slot_mapping_ptr,
@@ -654,6 +755,7 @@ def _prepare_dflash_inputs_kernel(
)
tl.store(out_input_ids_ptr + query_idx, input_id, mask=is_query)
tl.store(out_is_padding_ptr + query_idx, False, mask=is_query)
clamped_query_pos = tl.minimum(query_pos, max_model_len - 1)
tl.store(out_query_positions_ptr + query_idx, clamped_query_pos, mask=is_query)
tl.store(out_query_slot_mapping_ptr + query_idx, q_slot, mask=is_query)
@@ -716,6 +818,9 @@ def _prepare_dflash_inputs_kernel(
for i in range(q_pad_start, max_num_tokens, BLOCK_SIZE):
block = i + tl.arange(0, BLOCK_SIZE)
mask = block < max_num_tokens
tl.store(out_input_ids_ptr + block, 0, mask=mask)
tl.store(out_query_positions_ptr + block, 0, mask=mask)
tl.store(out_is_padding_ptr + block, True, mask=mask)
tl.store(out_query_slot_mapping_ptr + block, PAD_SLOT_ID, mask=mask)
@@ -767,6 +872,7 @@ def prepare_dflash_inputs(
_prepare_dflash_inputs_kernel[(num_reqs, num_blocks)](
input_buffers.input_ids,
input_buffers.positions,
input_buffers.is_padding,
input_buffers.query_start_loc,
input_buffers.seq_lens,
query_slot_mapping,
+18 -3
View File
@@ -6,6 +6,7 @@ import torch.nn as nn
from vllm.config import ModelConfig, ParallelConfig, VllmConfig, replace
from vllm.logger import init_logger
from vllm.model_executor.model_loader.utils import get_draft_load_config
from vllm.models.deepseek_v4.common.eplb_util import dspark_draft_supports_eplb
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.worker.gpu.spec_decode.utils import get_pp_safe_draft_load_config
@@ -35,11 +36,24 @@ def _resolve_dspark_attention_backend(
def _get_dspark_parallel_config(
parallel_config: ParallelConfig,
tensor_parallel_size: int,
draft_model_config: ModelConfig,
) -> ParallelConfig:
if parallel_config.enable_eplb:
enable_draft_eplb = parallel_config.enable_eplb and dspark_draft_supports_eplb(
draft_model_config
)
if parallel_config.enable_eplb and not enable_draft_eplb:
logger.warning_once(
"EPLB is disabled for the DSpark draft model. EPLB remains enabled "
"for the target model."
"EPLB is disabled for the DSpark draft model (%s). EPLB remains "
"enabled for the target model.",
draft_model_config.hf_config.model_type,
)
if enable_draft_eplb:
return replace(
parallel_config,
pipeline_parallel_size=1,
tensor_parallel_size=tensor_parallel_size,
enable_elastic_ep=False,
)
return replace(
@@ -81,6 +95,7 @@ def load_dspark_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Mo
parallel_config=_get_dspark_parallel_config(
vllm_config.parallel_config,
speculative_config.draft_parallel_config.tensor_parallel_size,
draft_model_config,
),
attention_config=replace(
vllm_config.attention_config,
@@ -12,6 +12,16 @@ from vllm.model_executor.models.interfaces import SupportsEagle3, supports_eagle
logger = init_logger(__name__)
def requires_aux_hidden_states(spec_config: SpeculativeConfig) -> bool:
if spec_config.method == "eagle3":
eagle_config = (
getattr(spec_config.draft_model_config.hf_config, "eagle_config", None)
or {}
)
return eagle_config.get("use_aux_hidden_state", True)
return spec_config.method in ("dflash", "dspark", "extract_hidden_states")
def set_eagle3_aux_hidden_state_layers(
model: nn.Module,
spec_config: SpeculativeConfig,
@@ -98,7 +98,7 @@ class ExtractHiddenStatesSpeculator(DraftModelSpeculator):
next_prefill_tokens: torch.Tensor,
temperature: torch.Tensor,
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
@@ -145,9 +145,7 @@ class ExtractHiddenStatesSpeculator(DraftModelSpeculator):
draft_attn_metadata,
self.vllm_config,
num_tokens=num_tokens,
num_tokens_across_dp=(
dp_sync.num_tokens_across_dp if dp_sync is not None else None
),
num_tokens_across_dp=dp_sync_state and dp_sync_state.num_tokens_across_dp,
cudagraph_runtime_mode=CUDAGraphMode.NONE,
slot_mapping=draft_slot_mappings,
is_padding=input_batch.is_padding[:num_tokens],
@@ -6,7 +6,6 @@ from torch import nn
from vllm.config import VllmConfig
from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.spec_decode.dflash2.speculator import DFlash2Speculator
from vllm.v1.worker.gpu.spec_decode.eagle.utils import get_target_lm_head
@@ -24,6 +23,9 @@ class LiLiCorrSpeculator(DFlash2Speculator):
self.anchor_valid = torch.zeros(
self.max_num_reqs, dtype=torch.bool, device=device
)
self._num_rejected = torch.zeros(
self.max_num_reqs, dtype=torch.int32, device=device
)
def load_draft_model(
self, target_model: nn.Module, target_attn_layer_names: set[str]
@@ -67,11 +69,14 @@ class LiLiCorrSpeculator(DFlash2Speculator):
return model
def prepare_context_anchor(
self, input_batch: InputBatch, num_rejected: torch.Tensor
self,
num_reqs: int,
query_start_loc: torch.Tensor,
num_rejected: torch.Tensor | None,
) -> None:
num_reqs = input_batch.num_reqs
starts = input_batch.query_start_loc[:num_reqs]
ends = input_batch.query_start_loc[1 : num_reqs + 1] - num_rejected[:num_reqs]
assert num_rejected is not None
starts = query_start_loc[:num_reqs]
ends = query_start_loc[1 : num_reqs + 1] - num_rejected[:num_reqs]
valid = ends > starts
indices = (ends - 1).clamp_min(0).long()
self.anchor_hidden.zero_()
@@ -150,7 +150,7 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
temperature: torch.Tensor,
# [max_num_reqs]
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
@@ -201,7 +201,7 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
dp_size=self.dp_size,
dp_rank=self.dp_rank,
need_eager=is_profile,
dp_sync=dp_sync,
dp_sync_state=dp_sync_state,
)
num_tokens_across_dp = (
batch_sync.num_tokens_across_dp if batch_sync is not None else None
@@ -226,7 +226,7 @@ class NgramGPUSpeculator(BaseSpeculator):
next_prefill_tokens: torch.Tensor,
temperature: torch.Tensor,
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
@@ -425,6 +425,9 @@ def _compute_local_residual_mass_kernel(
PADDED_VOCAB_NUM_BLOCKS: tl.constexpr,
):
logit_idx = tl.program_id(0).to(tl.int64)
# Adaptive verification can end before num_speculative_steps.
if logit_idx + 1 >= tl.num_programs(0):
return
draft_step_idx = tl.load(expanded_local_pos_ptr + logit_idx)
if draft_step_idx == 0 or draft_step_idx >= num_speculative_steps:
# The acceptance threshold, h, looks one position ahead and sums
+27 -6
View File
@@ -92,7 +92,7 @@ class BaseSpeculator(ABC):
temperature: torch.Tensor,
# [max_num_reqs]
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
@@ -152,7 +152,7 @@ class DraftModelSpeculator(BaseSpeculator):
device=device,
)
self.idx_mapping = torch.zeros(
self.max_num_reqs, dtype=torch.int32, device=device
self.max_num_reqs, dtype=torch.int64, device=device
)
self.temperature = torch.zeros(
self.max_num_reqs, dtype=torch.float32, device=device
@@ -207,6 +207,9 @@ class DraftModelSpeculator(BaseSpeculator):
self.supports_mm_inputs = False
self.pcp_manager: PCPManager | None = None
# Whether every draft attention builder can refresh its decode metadata
# in place, so the refresh can be recorded in the draft CUDA graph.
self.supports_decode_metadata_update = False
@abstractmethod
def load_draft_model(
@@ -299,6 +302,24 @@ class DraftModelSpeculator(BaseSpeculator):
# builders and buffers.
self.target_input_buffers = target_input_buffers
self.target_attn_groups = target_attn_groups
self._configure_decode_metadata_update()
def _configure_decode_metadata_update(self) -> None:
unsupported_backends = sorted(
{
attn_group.backend.get_name()
for attn_groups in self.attn_groups
for attn_group in attn_groups
if not attn_group.supports_draft_decode_metadata_update
}
)
self.supports_decode_metadata_update = not unsupported_backends
if unsupported_backends:
logger.info_once(
"Attention backend(s) %s cannot update draft decode metadata in "
"place; falling back to rebuilding attention metadata eagerly.",
", ".join(unsupported_backends),
)
def _build_attn_metadata(
self,
@@ -525,18 +546,18 @@ class DraftModelSpeculator(BaseSpeculator):
def _build_uniform_batch_dp_sync(
self,
target_dp_sync: DPSyncState,
target_dp_sync_state: DPSyncState,
num_reqs: int,
num_query_per_req: int = 1,
) -> tuple[DPSyncState, int]:
num_batch_tokens = target_dp_sync.num_reqs * num_query_per_req
num_batch_tokens = target_dp_sync_state.num_reqs * num_query_per_req
assert num_reqs * num_query_per_req <= num_batch_tokens, (
"reusing a DP sync that does not cover this batch's requests"
)
return replace(
target_dp_sync,
target_dp_sync_state,
num_tokens_across_dp=torch.full_like(
target_dp_sync.num_tokens_across_dp, num_batch_tokens
target_dp_sync_state.num_tokens_across_dp, num_batch_tokens
),
uniform_token_count=num_query_per_req,
eager=False,
@@ -70,6 +70,12 @@ class StandaloneARSpeculator(DraftModelSpeculator):
def capture(self) -> None:
pass # CUDA graph not yet supported for standalone AR speculator.
@property
def attn_vllm_config(self) -> VllmConfig:
if self.speculative_config.kv_cache_dtype is not None:
return self._draft_vllm_config
return self.vllm_config
def set_attn(
self,
model_state: ModelState,
@@ -99,15 +105,21 @@ class StandaloneARSpeculator(DraftModelSpeculator):
) -> nn.Module:
spec = self.speculative_config
assert spec is not None
cache_config = self.vllm_config.cache_config
if spec.kv_cache_dtype is not None:
cache_config = replace(cache_config, cache_dtype=spec.kv_cache_dtype)
draft_vllm_config = replace(
self.vllm_config,
model_config=self.draft_model_config,
quant_config=None,
cache_config=cache_config,
parallel_config=replace(
spec.draft_parallel_config,
rank=self.vllm_config.parallel_config.rank,
),
)
self._draft_vllm_config = draft_vllm_config
with set_model_tag("draft_model"):
return get_model(
vllm_config=draft_vllm_config,
@@ -350,7 +362,7 @@ class StandaloneARSpeculator(DraftModelSpeculator):
next_prefill_tokens: torch.Tensor,
temperature: torch.Tensor,
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
@@ -362,7 +374,7 @@ class StandaloneARSpeculator(DraftModelSpeculator):
num_reqs = input_batch.num_reqs
skip_attn = dummy_run and skip_attn_for_dummy_run
num_tokens_across_dp = (
dp_sync.num_tokens_across_dp if dp_sync is not None else None
dp_sync_state.num_tokens_across_dp if dp_sync_state is not None else None
)
# Copy per-request temperature/seeds/idx_mapping into pre-allocated
@@ -402,7 +414,7 @@ def _prepare_prefill_inputs_kernel(
target_input_ids_ptr, # [src_tokens] int32
target_positions_ptr, # [src_tokens] int64
last_sampled_ptr, # [max_num_reqs] int32
idx_mapping_ptr, # [num_reqs] int32
idx_mapping_ptr, # [num_reqs] int64
out_input_ids_ptr, # [src_tokens + num_reqs] int32
out_positions_ptr, # [src_tokens + num_reqs] int64
last_token_indices_ptr, # [max_num_reqs] int64
@@ -10,18 +10,15 @@ from vllm.config.compilation import CUDAGraphMode
from vllm.forward_context import BatchDescriptor, set_forward_context
from vllm.logger import init_logger
from vllm.triton_utils import tl, triton
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
from vllm.v1.worker.gpu.dp_utils import DPSyncState, dispatch_cg_and_sync_dp
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.model_states.interface import ModelState
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.cudagraph_utils import (
SpeculatorCudaGraphManager,
)
from vllm.v1.worker.utils import AttentionGroup, get_uniform_decode_token_count
from vllm.v1.worker.utils import get_uniform_decode_token_count
logger = init_logger(__name__)
@@ -51,7 +48,6 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
self.prefill_cudagraph_manager: SpeculatorCudaGraphManager | None = None
self.decode_cudagraph_manager: SpeculatorCudaGraphManager | None = None
self.use_fused_multi_step_decode = False
def load_model(self, target_model: nn.Module) -> None:
super().load_model(target_model)
@@ -83,44 +79,12 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
"""
return True
def set_attn(
self,
model_state: ModelState,
kv_cache_config: KVCacheConfig,
block_tables: BlockTables,
target_input_buffers: InputBuffers,
target_attn_groups: list[list[AttentionGroup]],
) -> None:
super().set_attn(
model_state,
kv_cache_config,
block_tables,
target_input_buffers,
target_attn_groups,
)
self._configure_fused_multi_step_decode()
def _configure_fused_multi_step_decode(self) -> None:
def _configure_decode_metadata_update(self) -> None:
# With one speculative step there are no draft decode steps to update.
if self.num_speculative_steps == 1:
self.use_fused_multi_step_decode = False
self.supports_decode_metadata_update = False
return
unsupported_backends = sorted(
{
attn_group.backend.get_name()
for attn_groups in self.attn_groups
for attn_group in attn_groups
if not attn_group.supports_draft_decode_metadata_update
}
)
self.use_fused_multi_step_decode = not unsupported_backends
if unsupported_backends:
logger.info_once(
"Fused multi-step draft decode is not supported by attention "
"backend(s) %s; falling back to rebuilding attention metadata "
"between draft steps.",
", ".join(unsupported_backends),
)
super()._configure_decode_metadata_update()
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
# Initialize cudagraph manager for draft prefill (draft position 0).
@@ -181,7 +145,7 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
assert self.decode_cudagraph_manager is not None
decode_fn = (
self._generate_fused_drafts
if self.use_fused_multi_step_decode
if self.supports_decode_metadata_update
else self._generate_draft
)
self.decode_cudagraph_manager.capture(
@@ -192,7 +156,7 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
self.attn_groups,
self.kv_cache_config,
progress_bar_desc="Capturing decode CUDA graphs",
specialize_spec_tokens=self.use_fused_multi_step_decode
specialize_spec_tokens=self.supports_decode_metadata_update
and self.speculative_config.uses_dynamic_speculative_decoding(),
)
self.on_multi_step_decode_end(self.max_num_reqs)
@@ -219,7 +183,7 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
temperature: torch.Tensor,
# [max_num_reqs]
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
@@ -299,7 +263,7 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
dp_size=self.dp_size,
dp_rank=self.dp_rank,
need_eager=is_profile,
dp_sync=dp_sync,
dp_sync_state=dp_sync_state,
)
num_tokens_across_dp = (
prefill_batch_sync.num_tokens_across_dp
@@ -352,8 +316,10 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
)
decode_batch_sync, num_batch_tokens = (
self._build_uniform_batch_dp_sync(dp_sync, num_reqs, num_query_per_req=1)
if dp_sync is not None
self._build_uniform_batch_dp_sync(
dp_sync_state, num_reqs, num_query_per_req=1
)
if dp_sync_state is not None
else (None, num_reqs)
)
# Each request produces exactly 1 token per draft generation step,
@@ -366,7 +332,7 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
dp_size=self.dp_size,
dp_rank=self.dp_rank,
need_eager=is_profile,
dp_sync=decode_batch_sync,
dp_sync_state=decode_batch_sync,
)
if self.decode_cudagraph_manager is not None:
decode_batch_desc = self.decode_cudagraph_manager.specialize_spec_tokens(
@@ -382,7 +348,7 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
# Generate the remaining num_speculative_steps - 1 draft tokens.
decode_fn = (
self._fused_multi_step_decode
if self.use_fused_multi_step_decode
if self.supports_decode_metadata_update
else self._multi_step_decode
)
decode_fn(
@@ -410,8 +376,9 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
input_buffers: InputBatch | InputBuffers = self.input_buffers
is_padding = None
if self.pcp_manager is not None:
input_buffers = self.pcp_manager.get_draft_input_buffers(self.input_buffers)
is_padding = input_buffers.is_padding[:num_tokens]
input_buffers, is_padding = self.pcp_manager.get_draft_input_buffers(
self.input_buffers, num_tokens
)
batch_descriptor = BatchDescriptor(num_tokens=num_tokens)
with set_forward_context(
attn_metadata,
@@ -577,6 +544,11 @@ class TargetDependentARSpeculator(DraftModelSpeculator):
idx_mapping = self.idx_mapping[:num_reqs]
if batch_desc.cg_mode == CUDAGraphMode.FULL:
for groups in self.attn_groups:
for group in groups:
group.map_to_kernel_block_table(
self.block_tables.input_block_tables[group.kv_cache_group_id]
)
assert self.decode_cudagraph_manager is not None
self.decode_cudagraph_manager.run_fullgraph(batch_desc)
return
+19
View File
@@ -13,6 +13,25 @@ from vllm.v1.worker.gpu.input_batch import InputBatch
logger = init_logger(__name__)
def get_drafter_hidden_states(
model: torch.nn.Module, hidden_states: torch.Tensor
) -> torch.Tensor:
"""Hidden states fed to the drafter.
Targets such as DeepSeek V4 expose the pre-hc_head residual through
get_mtp_target_hidden_states(). The buffer is sized at
max_num_batched_tokens and only allocated for drafters that consume
target hidden states, so None means "use the regular hidden states".
"""
get_target_hidden_states = getattr(model, "get_mtp_target_hidden_states", None)
if get_target_hidden_states is None:
return hidden_states
target_hidden_states = get_target_hidden_states()
if target_hidden_states is None:
return hidden_states
return target_hidden_states[: hidden_states.shape[0]]
def get_pp_safe_draft_load_config(load_config: LoadConfig) -> LoadConfig:
"""Avoid collectives that include PP ranks without a draft model."""
if get_pp_group().world_size > 1 and load_config.load_format == "fastsafetensors":
+2 -1
View File
@@ -114,7 +114,8 @@ class RequestState:
self.num_computed_tokens_np[req_idx] = num_computed_tokens
self.num_computed_tokens.stage_write_elem(req_idx, num_computed_tokens)
self.draft_tokens[req_idx].zero_()
if self.num_speculative_steps > 0:
self.draft_tokens[req_idx].zero_()
def apply_staged_writes(self) -> None:
self.prompt_len.copy_to_uva()
+12 -7
View File
@@ -106,7 +106,6 @@ def run_mixed_prefill_decode_warmup(
prefill_token_ids = list(range(prefill_len))
kv_cache_groups = model_runner.kv_cache_config.kv_cache_groups
num_kv_cache_groups = len(kv_cache_groups)
block_count = _warmup_block_counter(model_runner)
kv_cache_specs = [g.kv_cache_spec for g in kv_cache_groups]
decode_prefill_block_counts = [
@@ -166,7 +165,6 @@ def run_mixed_prefill_decode_warmup(
decode_req_id: decode_prompt_len,
}
decode_prefill_output.total_num_scheduled_tokens = decode_prompt_len
decode_prefill_output.num_common_prefix_blocks = [0] * num_kv_cache_groups
decode_new_blocks = tuple(_alloc_blocks(n) for n in decode_block_deltas)
cached_decode_req = CachedRequestData.make_empty()
@@ -198,7 +196,6 @@ def run_mixed_prefill_decode_warmup(
prefill_req_id: prefill_len,
}
mixed_output.total_num_scheduled_tokens = num_tokens
mixed_output.num_common_prefix_blocks = [0] * num_kv_cache_groups
cleanup_output = SchedulerOutput.make_empty()
cleanup_output.finished_req_ids = {decode_req_id, prefill_req_id}
@@ -241,6 +238,12 @@ def warmup_kernels(
rejection_sampler.enable_adaptive_verification = False
try:
_warmup_kernels(model_runner, worker_execute_model, worker_sample_tokens)
if rejection_sampler is not None:
# Greedy batches skip logits processing, so rejection kernels
# also see model-dtype logits instead of FP32.
_warmup_kernels(
model_runner, worker_execute_model, worker_sample_tokens, greedy=True
)
finally:
model_runner.adaptive_verification = adaptive_verification
if adaptive_sampling:
@@ -252,6 +255,7 @@ def _warmup_kernels(
model_runner: GPUModelRunner,
worker_execute_model: Callable[[SchedulerOutput], Any],
worker_sample_tokens: Callable[[GrammarOutput | None], Any],
greedy: bool = False,
) -> None:
if model_runner.vllm_config.is_mm_encoder_only:
return
@@ -272,7 +276,6 @@ def _warmup_kernels(
decode_len = prompt_len + num_decode_steps * decode_query_len
kv_cache_groups = model_runner.kv_cache_config.kv_cache_groups
num_kv_cache_groups = len(kv_cache_groups)
# Encoder-decoder models: give each warmup request a dummy encoder input so
# cross-attention warms up over a realistic, non-empty key sequence.
@@ -325,7 +328,11 @@ def _warmup_kernels(
pooling_params = PoolingParams(task=pooling_task)
pooling_params.verify(model_runner.model_config)
else:
sampling_params = SamplingParams.for_sampler_warmup()
sampling_params = (
SamplingParams(temperature=0)
if greedy
else SamplingParams.for_sampler_warmup()
)
pooling_params = None
# Assign distinct block IDs per request per group. 0 null block, start from 1.
@@ -361,7 +368,6 @@ def _warmup_kernels(
prefill_output.scheduled_new_reqs = new_reqs
prefill_output.num_scheduled_tokens = {rid: prompt_len for rid in req_ids}
prefill_output.total_num_scheduled_tokens = prompt_len * num_reqs
prefill_output.num_common_prefix_blocks = [0] * num_kv_cache_groups
# Disable KV connector for warmup run.
model_runner.kv_connector.set_disabled(True)
@@ -424,7 +430,6 @@ def _warmup_kernels(
decode_output.total_num_scheduled_tokens = sum(
step_num_scheduled_tokens.values()
)
decode_output.num_common_prefix_blocks = [0] * num_kv_cache_groups
worker_execute_model(decode_output)
worker_sample_tokens(None)