Merge branch 'main' into patches

This commit is contained in:
2026-10-18 16:04:36 +07:00
299 changed files with 51483 additions and 2195 deletions
+12 -111
View File
@@ -9,7 +9,7 @@ from dataclasses import replace
from functools import partial, reduce
from typing import Any
from vllm.config import VllmConfig
from vllm.config import SpeculativeConfig, VllmConfig
from vllm.logger import init_logger
from vllm.utils.math_utils import cdiv, round_up
from vllm.utils.mem_utils import format_gib
@@ -1038,120 +1038,20 @@ def _get_packed_kv_cache_groups(
assert group_spec is not None
groups.append(KVCacheGroupSpec(group_layer_names, group_spec))
_annotate_eagle_groups(
vllm_config,
kv_cache_spec,
groups,
use_trailing_layer_fallback=_uses_trailing_mtp_layers(vllm_config),
)
_warn_if_unannotated_eagle_mamba(vllm_config, groups)
return groups
def _uses_trailing_mtp_layers(vllm_config: VllmConfig) -> bool:
"""Whether the drafter's KV layers can be located positionally.
MTP drafters register their KV layers after the target layers, without a
distinguishing spec marker. DeepseekV4/V4.1 do this with ``dspark`` too.
The annotator separately checks that the groups partition the layers exactly.
"""
spec_config = vllm_config.speculative_config
if spec_config is None or not spec_config.use_eagle():
return False
if spec_config.method == "mtp":
return True
model_config = vllm_config.model_config
return model_config is not None and model_config.hf_config.model_type in (
"deepseek_v4",
"deepseek_v41",
)
def _groups_partition_layers_exactly(
kv_cache_spec: dict[str, KVCacheSpec],
kv_cache_groups: list[KVCacheGroupSpec],
) -> bool:
"""Whether the groups cover every layer of ``kv_cache_spec`` exactly once.
The trailing-layer draft fallback is only meaningful when the last
registered layer is guaranteed to appear in exactly one group.
"""
names = [name for group in kv_cache_groups for name in group.layer_names]
return len(names) == len(kv_cache_spec) and set(names) == set(kv_cache_spec)
def _annotate_eagle_groups(
vllm_config: VllmConfig,
kv_cache_spec: dict[str, KVCacheSpec],
kv_cache_groups: list[KVCacheGroupSpec],
use_trailing_layer_fallback: bool = False,
) -> None:
"""Flag the KV cache groups that hold drafter attention layers.
Two detection rules, in order of preference:
1. Spec-driven. ``non_causal_multi_token_decode`` is declared on
MLAAttentionSpec and set by drafter attention layers that run a
non-causal multi-token decode (today only Kimi-K3 DSpark). It survives
MLAAttentionSpec.merge, so it still identifies a group after per-group
spec merging, wherever grouping happens to land. It is sufficient but
not necessary: a drafter whose spec is indistinguishable from the
target's cannot be found this way.
2. Positional fallback for MTP drafters (including DeepseekV4/V4.1 DSpark), whose
MTP block reuses the target's own decoder layer and so carries no spec
marker. Their draft attention layers always register after every
target layer, so flag whichever group holds the last registered layer.
This rule is only valid where the groups partition exactly the layers
of ``kv_cache_spec``, which is re-checked here before applying it.
When a drafter's trailing caches span several groups, this rule flags
only the group holding the very last layer and must be generalized.
FIXME(yifan): avoid/generalize this hacky check.
Args:
vllm_config: Config supplying the speculative method, if any.
kv_cache_spec: The kv cache spec of each attention layer, in layer
registration order. Only read by rule 2.
kv_cache_groups: Groups to annotate in place.
use_trailing_layer_fallback: Enable rule 2. Callers gate this on
``_uses_trailing_mtp_layers``.
"""
spec_config = vllm_config.speculative_config
if spec_config is None or not spec_config.use_eagle_block_drop():
return
for group in kv_cache_groups:
if any(
getattr(spec, "non_causal_multi_token_decode", False)
for spec in iter_layer_specs(group.kv_cache_spec)
):
group.is_eagle_group = True
if not use_trailing_layer_fallback:
return
if not _groups_partition_layers_exactly(kv_cache_spec, kv_cache_groups):
return
last_layer = next(reversed(kv_cache_spec))
for group in kv_cache_groups:
if last_layer in group.layer_names:
group.is_eagle_group = True
break
def _warn_if_unannotated_eagle_mamba(
vllm_config: VllmConfig,
spec_config: SpeculativeConfig,
kv_cache_groups: list[KVCacheGroupSpec],
) -> None:
"""Warn when no KV cache group could be identified as the draft model's.
Args:
vllm_config: Config supplying the speculative method, if any.
spec_config: Config supplying the speculative method.
kv_cache_groups: Groups as they will be handed to consumers.
"""
spec_config = vllm_config.speculative_config
if spec_config is None or not spec_config.use_eagle():
return
if any(group.is_eagle_group for group in kv_cache_groups):
return
mamba_groups = [
@@ -1297,13 +1197,6 @@ def get_kv_cache_groups(
aligned = replace(spec, block_size=new_bs, page_size_padded=common_page)
groups.append(KVCacheGroupSpec([name], aligned))
_annotate_eagle_groups(
vllm_config,
kv_cache_spec,
groups,
use_trailing_layer_fallback=_uses_trailing_mtp_layers(vllm_config),
)
_warn_if_unannotated_eagle_mamba(vllm_config, groups)
return groups
@@ -1556,7 +1449,7 @@ def _project_kv_cache_groups_to_worker(
KVCacheGroupSpec(
worker_layer_names,
group_spec,
is_eagle_group=group.is_eagle_group and bool(worker_layer_names),
is_eagle_group=group.is_eagle_group,
host_resident=group.host_resident,
enable_kv_transfer=group.enable_kv_transfer,
role=group.role,
@@ -1636,6 +1529,14 @@ def get_kv_cache_configs(
global_kv_cache_groups = get_kv_cache_groups_from_builder(
builder, vllm_config, merged_kv_cache_specs
)
spec_config = vllm_config.speculative_config
if spec_config is not None and spec_config.use_eagle_block_drop():
draft_layer_names = {
name for name, spec in merged_kv_cache_specs.items() if spec.is_draft
}
for group in global_kv_cache_groups:
group.is_eagle_group = not draft_layer_names.isdisjoint(group.layer_names)
_warn_if_unannotated_eagle_mamba(spec_config, global_kv_cache_groups)
# If original_max_model_len was -1, automatically
# determine the maximum model length that fits in available GPU memory.
+14 -9
View File
@@ -1732,14 +1732,14 @@ class Scheduler(SchedulerInterface):
Discards the last sampled output token from the prior input chunk.
"""
# Current streaming input behaviour: Keep only computed output tokens
# (discard final sampled output token).
num_computed_tokens = session.num_computed_tokens
# Keep all output tokens but the final sampled one.
keep_end = session.num_tokens - 1
assert keep_end >= session.num_computed_tokens
kept_output_tokens = session._all_token_ids[
session.num_prompt_tokens : num_computed_tokens
session.num_prompt_tokens : keep_end
]
del session._all_token_ids[num_computed_tokens:]
del session.block_hashes[num_computed_tokens // self.hash_block_size :]
del session._all_token_ids[keep_end:]
del session.block_hashes[keep_end // self.hash_block_size :]
session._output_token_ids.clear()
assert session.prompt_token_ids is not None
# Extend prompt with kept output tokens.
@@ -2155,6 +2155,8 @@ class Scheduler(SchedulerInterface):
# to avoid expensive operations inside the loop.
stopped_running_reqs: set[Request] = set()
stopped_preempted_reqs: set[Request] = set()
# Stopped resumable requests to re-enqueue, in output order.
continuing_reqs: list[Request] = []
for req_id, num_tokens_scheduled in num_scheduled_tokens.items():
assert num_tokens_scheduled > 0
request = self.requests.get(req_id)
@@ -2320,6 +2322,8 @@ class Scheduler(SchedulerInterface):
kv_transfer_params["remote_prefill_cached_tokens"] = (
prefill_stats.num_cached_tokens
)
else:
continuing_reqs.append(request)
if status_before_stop == RequestStatus.RUNNING:
stopped_running_reqs.add(request)
@@ -2371,14 +2375,16 @@ class Scheduler(SchedulerInterface):
assert not prompt_logprobs_tensors
assert prompt_token_id_logprobs is None
# Remove the stopped requests from the running and waiting queues.
# Remove stopped requests from their queues, then enqueue the ones
# that continue, so each ends up in exactly one queue.
if stopped_running_reqs:
self.running = remove_all(self.running, stopped_running_reqs)
if stopped_preempted_reqs:
# This is a rare case and unlikely to impact performance.
self.waiting.remove_requests(stopped_preempted_reqs)
self.kv_holding_waiting.remove_requests(stopped_preempted_reqs)
self.deferred_waiting.difference_update(stopped_preempted_reqs)
for request in continuing_reqs:
self._enqueue_waiting_request(request)
error_req_ids = set(self.grammar_compile_error_reqs)
self.grammar_compile_error_reqs.clear()
@@ -2568,7 +2574,6 @@ class Scheduler(SchedulerInterface):
request.status = RequestStatus.WAITING_FOR_STREAMING_REQ
self.num_waiting_for_streaming_input += 1
self._enqueue_waiting_request(request)
return False
def _update_request_with_output(
+8
View File
@@ -599,6 +599,7 @@ class AsyncLLM(EngineClient):
session_id: str | None = None,
kv_hints: KvHintsEnvelope | None = None,
) -> RequestOutputCollector:
self._validate_resumable_request()
self._validate_streaming_input_sampling_params(sampling_params)
inputs = dict(
@@ -693,6 +694,13 @@ class AsyncLLM(EngineClient):
queue._input_stream_task = asyncio.create_task(handle_inputs())
return queue
def _validate_resumable_request(self) -> None:
if self.vllm_config.is_mm_encoder_only or self.model_config.is_diffusion:
raise VLLMValidationError(
"Resumable requests are not supported for encoder-only or "
"diffusion models."
)
@staticmethod
def _validate_streaming_input_sampling_params(
params: SamplingParams | PoolingParams,
+11 -1
View File
@@ -175,6 +175,10 @@ class KVCacheSpec:
``MultipleOf(n)``: whole kernel blocks, when blocks are split into kernel
blocks of up to ``n`` tokens."""
is_draft: bool = field(default=False, kw_only=True, compare=False)
"""Whether a draft model owns this layer; excluded from equality so it never
affects grouping."""
def __post_init__(self):
alignment = self.block_stride_alignment
if isinstance(alignment, int) and alignment <= 0:
@@ -660,6 +664,8 @@ class FullAttentionSpec(AttentionSpec):
)
for spec in specs:
for f in fields(AttentionSpec):
if not f.compare:
continue
assert getattr(spec, f.name) == getattr(merged_spec, f.name), (
"All attention layers in the same KV cache group must have "
"the same attention spec."
@@ -747,6 +753,8 @@ class MLAAttentionSpec(FullAttentionSpec):
)
for spec in specs:
for f in fields(AttentionSpec):
if not f.compare:
continue
assert getattr(spec, f.name) == getattr(merged_spec, f.name), (
"All attention layers in the same KV cache group must have "
"the same attention spec."
@@ -1208,6 +1216,8 @@ class SinkFullAttentionSpec(FullAttentionSpec):
)
for spec in specs:
for f in fields(AttentionSpec):
if not f.compare:
continue
assert getattr(spec, f.name) == getattr(merged_spec, f.name), (
"All attention layers in the same KV cache group must have "
"the same attention spec."
@@ -1445,7 +1455,7 @@ class KVCacheGroupSpec:
layer_names: list[str]
# The KV cache spec of this manager layer
kv_cache_spec: KVCacheSpec
# Whether this group contains EAGLE/MTP draft attention layers.
# Whether this group holds draft layers and takes the EAGLE last-block drop.
is_eagle_group: bool = False
# Host groups use the dedicated HiSparse pool; others share the device pool.
host_resident: bool = False
+4 -1
View File
@@ -1330,10 +1330,13 @@ class SpecDecodeBaseProposer:
self.vllm_config,
AttentionLayerBase, # type: ignore[type-abstract]
)
draft_attn_layer_names = set(all_attn_layers) - target_attn_layer_names
for name in draft_attn_layer_names:
all_attn_layers[name].is_draft_layer = True
# Filter to only layers that have KV cache specs.
self._draft_attn_layer_names = {
name
for name in (set(all_attn_layers.keys()) - target_attn_layer_names)
for name in draft_attn_layer_names
if all_attn_layers[name].get_kv_cache_spec(self.vllm_config) is not None
}
+3 -1
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Mapping, Sequence
from contextlib import AbstractContextManager, nullcontext
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, Any, cast
import numpy as np
@@ -148,6 +148,8 @@ def get_kv_cache_spec(vllm_config: VllmConfig) -> dict[str, KVCacheSpec]:
if spec := attn_module.get_kv_cache_spec(vllm_config):
if isinstance(spec, AttentionSpec):
spec = customize_attention_spec(attn_module.get_attn_backend(), spec)
if attn_module.is_draft_layer:
spec = replace(spec, is_draft=True)
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)
+13 -6
View File
@@ -74,6 +74,7 @@ class BlockTables:
self.input_block_tables: list[torch.Tensor] = [
torch.zeros_like(b.gpu) for b in self.block_tables
]
self._num_dirty_rows = 0
self.slot_mappings = torch.zeros(
self.num_kv_cache_groups,
@@ -151,15 +152,18 @@ class BlockTables:
) -> tuple[torch.Tensor, ...]:
if self.num_kv_cache_groups == 0:
return ()
num_reqs = idx_mapping.shape[0]
num_rows = num_reqs_padded
if out is None:
out = tuple(self.input_block_tables)
out_ptrs = self.input_block_table_ptrs
num_rows = max(num_rows, self._num_dirty_rows)
self._num_dirty_rows = num_reqs
else:
assert out_ptrs is not None
assert len(out) == self.num_kv_cache_groups
num_reqs = idx_mapping.shape[0]
# Launch kernel with num_reqs_padded to fuse zeroing of padded rows.
_gather_block_tables_kernel[(self.num_kv_cache_groups, num_reqs_padded)](
# Also clear rows left by a larger batch in the shared buffer.
_gather_block_tables_kernel[(self.num_kv_cache_groups, num_rows)](
idx_mapping,
self.block_table_ptrs,
out_ptrs,
@@ -180,9 +184,12 @@ class BlockTables:
# Zero the rows so dummy runs write mamba state to the reserved null
# block rather than through the previous real step's (stale) block
# ids, which may point at blocks since freed and reallocated.
return tuple(
block_table[:num_reqs].zero_() for block_table in self.input_block_tables
)
num_rows = max(num_reqs, self._num_dirty_rows)
for block_table in self.input_block_tables:
block_table[:num_rows].zero_()
# Profiling may populate the returned rows with valid block IDs.
self._num_dirty_rows = num_reqs
return tuple(block_table[:num_reqs] for block_table in self.input_block_tables)
def compute_slot_mappings(
self,
+19 -4
View File
@@ -41,9 +41,14 @@ class KVConnector:
def finish_forward(self) -> None:
pass
def post_forward(self, finished_req_ids: set[str]) -> KVConnectorOutput | None:
def post_forward(
self, finished_req_ids: set[str], defer_finalize: bool = False
) -> KVConnectorOutput | None:
return None
def finalize_step(self) -> None:
pass
def no_forward(self, scheduler_output: "SchedulerOutput") -> ModelRunnerOutput:
return EMPTY_MODEL_RUNNER_OUTPUT
@@ -128,7 +133,9 @@ class ActiveKVConnector(KVConnector):
def reset_capture_state(self) -> None:
self.kv_connector.reset_capture_state()
def post_forward(self, finished_req_ids: set[str]) -> KVConnectorOutput | None:
def post_forward(
self, finished_req_ids: set[str], defer_finalize: bool = False
) -> KVConnectorOutput | None:
if self._disabled:
return None
@@ -136,7 +143,8 @@ class ActiveKVConnector(KVConnector):
self._start_load_kv()
output = KVConnectorOutput()
self.kv_connector.wait_for_save()
if not defer_finalize:
self.kv_connector.wait_for_save()
transfer_results = self.kv_connector.get_transfer_results(finished_req_ids)
output.finished_sending = transfer_results.finished_sending or None
output.finished_recving = transfer_results.finished_recving or None
@@ -147,9 +155,16 @@ class ActiveKVConnector(KVConnector):
output.kv_connector_worker_meta = (
self.kv_connector.build_connector_worker_meta()
)
self.kv_connector.clear_connector_metadata()
if not defer_finalize:
self.kv_connector.clear_connector_metadata()
return output
def finalize_step(self) -> None:
if self._disabled:
return
self.kv_connector.wait_for_save()
self.kv_connector.clear_connector_metadata()
def no_forward(self, scheduler_output: "SchedulerOutput") -> ModelRunnerOutput:
if self._disabled:
return EMPTY_MODEL_RUNNER_OUTPUT
+8 -3
View File
@@ -2207,6 +2207,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
pending_aux_output=pending_aux_output,
)
# Collect KV transfer results now; finalize saves after the drafter runs.
defer_kv_finalize = self.speculator is not None
model_runner_output.kv_connector_output = self.kv_connector.post_forward(
finished_req_ids, defer_finalize=defer_kv_finalize
)
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None
# The encoder runner exists only on the first PP rank, so later ranks
# have no cached embeddings to gather.
@@ -2288,9 +2294,8 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.req_states.draft_tokens, input_batch
)
# Post-step KV connector related operations.
kv_connector_output = self.kv_connector.post_forward(finished_req_ids)
model_runner_output.kv_connector_output = kv_connector_output
if defer_kv_finalize:
self.kv_connector.finalize_step()
model_runner_output.ec_connector_output = ec_connector_output
return async_output
+2 -1
View File
@@ -238,7 +238,8 @@ 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:
# All PP ranks must run the same forwards to match sends and receives.
if model_runner.speculative_config is not None:
# Greedy batches skip logits processing, so rejection kernels
# also see model-dtype logits instead of FP32.
_warmup_kernels(
+2
View File
@@ -7140,6 +7140,8 @@ class GPUModelRunner(
spec = customize_attention_spec(
attn_module.get_attn_backend(), spec
)
if attn_module.is_draft_layer:
spec = replace(spec, is_draft=True)
kv_cache_spec[layer_name] = spec
return kv_cache_spec
+3 -3
View File
@@ -61,9 +61,9 @@ def _torch_cuda_wrapper():
torch.cuda.stream = partial(torch.xpu.stream)
torch.cuda.set_stream = partial(torch.xpu.set_stream)
# torch.xpu.Event does not accept the ``blocking`` kwarg that
# torch.cuda.Event supports, so drop it here.
def _xpu_event(*args, blocking=None, **kwargs):
# torch.xpu.Event does not accept the ``blocking`` or ``external`` kwargs
# that torch.cuda.Event supports, so drop them here.
def _xpu_event(*args, blocking=None, external=None, **kwargs):
return torch.xpu.Event(*args, **kwargs)
torch.cuda.Event = _xpu_event