Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 17:41:13 +00:00
1122 changed files with 60114 additions and 20956 deletions
+3 -1
View File
@@ -268,7 +268,9 @@ class CPUWorker(Worker):
self.model_runner.warming_up_model()
# Reset the seed to ensure that the random state is not affected by
# the model initialization and profiling.
set_random_seed(self.model_config.seed)
set_random_seed(
self.model_config.seed, self.parallel_config.data_parallel_index
)
return CompilationTimes(
language_model=self.compilation_config.compilation_time,
encoder=self.compilation_config.encoder_compilation_time,
+33 -18
View File
@@ -23,6 +23,7 @@ from vllm.model_executor.models.interfaces import (
from vllm.model_executor.models.utils import scatter_output_slices
from vllm.model_executor.models.vision import get_load_balance_assignment
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.utils.math_utils import round_up_to
from vllm.utils.torch_utils import current_stream
from vllm.v1.worker.encoder_cudagraph_defs import (
ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG,
@@ -347,17 +348,17 @@ class EncoderCudaGraphManager:
def _find_smallest_fitting_budget_given_tokens(
self, total_tokens: int, budgets: list[int] | None = None
) -> int | None:
"""Find smallest budget >= total_tokens.
Returns:
Token budget if found, None if no fitting budget.
"""
"""Find smallest budget >= total_tokens, or None if none fits."""
budgets = budgets if budgets is not None else self.token_budgets
for budget in budgets:
if budget >= total_tokens:
return budget
return None
return round_up_to(budgets, total_tokens)
def _path_fitting_budget(self, path: str, tokens: int) -> int | None:
"""Smallest captured budget on a path; 0 when idle, None if oversized."""
if tokens == 0:
return 0
return self._find_smallest_fitting_budget_given_tokens(
tokens, self.path_token_budgets[path]
)
def _get_item_specs(self, mm_kwargs: dict[str, Any]) -> list[EncoderItemSpec]:
"""Get item specs from the model."""
@@ -479,24 +480,38 @@ class EncoderCudaGraphManager:
if not current_batch:
return
path_budgets = {
path: (
0
if current_tokens[path] == 0
else self._find_smallest_fitting_budget_given_tokens(
current_tokens[path], self.path_token_budgets[path]
)
)
path: self._path_fitting_budget(path, current_tokens[path])
for path in paths
}
batches.append((list(current_batch), path_budgets))
def should_defer_item(item_tokens: dict[str, int]) -> bool:
"""Whether closing the batch strictly reduces summed budgets."""
for path in paths:
item = item_tokens[path]
if item == 0:
continue
cur = current_tokens[path]
b_cur = self._path_fitting_budget(path, cur)
b_alone = self._path_fitting_budget(path, item)
b_merged = self._path_fitting_budget(path, cur + item)
# Only called when the item fits; lookups land on a budget.
assert (
b_cur is not None and b_alone is not None and b_merged is not None
)
# Only defer items that alone outweigh the whole current
# batch; splitting smaller ones fragments flood packing.
if b_cur + b_alone < b_merged and b_alone >= b_cur:
return True
return False
for orig_idx in sorted_indices:
item_tokens = {path: per_item_path_tokens[path][orig_idx] for path in paths}
fits = len(current_batch) < self.max_batch_size and all(
current_tokens[path] + item_tokens[path] <= max_path_budgets[path]
for path in paths
)
if current_batch and not fits:
if current_batch and (not fits or should_defer_item(item_tokens)):
append_current_batch()
current_batch = []
current_tokens = dict.fromkeys(paths, 0)
+1 -1
View File
@@ -262,7 +262,7 @@ class AsyncPoolingOutput(AsyncModelRunnerOutput):
def async_copy_to_np(x: torch.Tensor) -> np.ndarray:
return x.to("cpu", non_blocking=True).numpy()
return x.to("cpu", non_blocking=True, copy=True).numpy()
@contextlib.contextmanager
+9
View File
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, cast
import numpy as np
import torch
import vllm.envs as envs
from vllm.config import (
VllmConfig,
get_layers_from_vllm_config,
@@ -224,6 +225,14 @@ def init_attn_backend(
for layer_name in layer_names:
attn_backend = attn_layers[layer_name].get_attn_backend()
if (
envs.VLLM_BATCH_INVARIANT
and not attn_backend.supports_batch_invariance()
):
raise RuntimeError(
"VLLM batch_invariant mode is not supported for "
f"{attn_backend.get_name()}."
)
if layer_name in fast_prefill_eligible_layers:
attn_backend = create_fast_prefill_custom_backend(
"FastPrefill", attn_backend
+2 -2
View File
@@ -54,8 +54,8 @@ class NonUvaBuffer:
def uva(self, n: int | None = None) -> torch.Tensor:
if n is None:
return self._uva.copy_(self.cpu)
return self._uva[:n].copy_(self.cpu[:n])
return self._uva.copy_(self.cpu, non_blocking=True)
return self._uva[:n].copy_(self.cpu[:n], non_blocking=True)
class UvaBufferPool:
+1
View File
@@ -272,6 +272,7 @@ class CudaGraphManager:
if (
speculative_config
and speculative_config.uses_dynamic_speculative_decoding()
and self.decode_query_len > self.vllm_config.num_speculative_tokens
):
# decode_query_len = num_speculative_steps + num_new_sampled_tokens
# _per_step. Recover num_new_sampled_tokens_per_step
+5 -2
View File
@@ -150,9 +150,12 @@ class EncoderRunner:
def execute_mm_encoder(
self, mm_kwargs: list[tuple[str, MultiModalKwargsItem]]
) -> list[torch.Tensor]:
# Stable-sort items by modality so each modality is encoded in as few
# batches as possible. The returned outputs are restored to input order.
order = sorted(range(len(mm_kwargs)), key=lambda i: mm_kwargs[i][0])
encoder_outputs: list[torch.Tensor] = []
for modality, num_items, mm_kwargs_batch in group_and_batch_mm_kwargs(
mm_kwargs, device=self.device, pin_memory=PIN_MEMORY
[mm_kwargs[i] for i in order], device=self.device, pin_memory=PIN_MEMORY
):
cg_manager = self.cudagraph_manager
cudagraph_output = (
@@ -169,7 +172,7 @@ class EncoderRunner:
)
sanity_check_mm_encoder_outputs(batch_outputs, expected_num_items=num_items)
encoder_outputs.extend(batch_outputs)
return encoder_outputs
return [encoder_outputs[i] for i in np.argsort(order)]
@contextmanager
def timed_encoder_operation(self, request_ids: Collection[str]):
+19 -16
View File
@@ -6,6 +6,7 @@ import numpy as np
from vllm.lora.layers import LoRAMapping, LoRAMappingType
from vllm.lora.worker_manager import WorkerLoRAManager
from vllm.multimodal.inputs import MultiModalFeatureSpec
from vllm.v1.worker.gpu.lora_utils import LoraState
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
@@ -31,7 +32,7 @@ def set_active_mm_loras(
encoder_token_counts: list[int] = []
connector_token_counts: list[int] = []
# iterate through images
mm_items: list[tuple[int, MultiModalFeatureSpec]] = []
for req_id, encoder_input_ids in scheduled_encoder_inputs.items():
req_idx = req_id_to_index.get(req_id)
if req_idx is None:
@@ -39,27 +40,29 @@ def set_active_mm_loras(
lora_id = int(lora_state.lora_ids[req_idx])
mm_features = encoder_cache.mm_features[req_id]
# iterate through visual tokens
for mm_input_id in encoder_input_ids:
pos_info = mm_features[mm_input_id].mm_position
tower_tokens, connector_tokens = model.get_mm_lora_token_counts(
modality=mm_features[mm_input_id].modality,
mm_kwargs=mm_features[mm_input_id].data,
num_mm_embeds=pos_info.get_num_embeds(),
)
prompt_lora_mapping.append(lora_id)
token_lora_mapping.extend([lora_id] * tower_tokens)
encoder_token_counts.append(tower_tokens)
connector_token_counts.append(connector_tokens)
mm_items.extend((lora_id, mm_features[i]) for i in encoder_input_ids)
if lora_id > 0:
lora_request = lora_state.lora_requests.get(req_id)
if lora_request is not None:
lora_requests.add(lora_request)
# Runs items sorted by modality.
mm_items.sort(key=lambda x: x[1].modality)
for lora_id, mm_feature in mm_items:
pos_info = mm_feature.mm_position
tower_tokens, connector_tokens = model.get_mm_lora_token_counts(
modality=mm_feature.modality,
mm_kwargs=mm_feature.data,
num_mm_embeds=pos_info.get_num_embeds(),
)
prompt_lora_mapping.append(lora_id)
token_lora_mapping.extend([lora_id] * tower_tokens)
encoder_token_counts.append(tower_tokens)
connector_token_counts.append(connector_tokens)
if not prompt_lora_mapping:
return
+57 -35
View File
@@ -265,13 +265,32 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.encoder_cache = EncoderCache()
self.ec_connector = get_ec_connector(vllm_config, self.encoder_cache)
self.num_speculative_steps = vllm_config.num_speculative_tokens
num_prefill_lookahead = max(1, vllm_config.num_prefill_lookahead_tokens)
use_dense_all_token_ids = (
self.speculative_config is not None and self.speculative_config.use_ngram()
)
# General request states.
self.req_states = RequestState(
max_num_reqs=self.max_num_reqs,
max_model_len=self.max_model_len,
max_num_batched_tokens=self.max_num_tokens,
num_speculative_steps=self.num_speculative_steps,
vocab_size=self.vocab_size,
device=self.device,
num_prefill_lookahead=num_prefill_lookahead,
use_dense_all_token_ids=use_dense_all_token_ids,
)
# Speculative decoding.
self.speculator = None
self.use_aux_hidden_state_outputs = False
self.num_speculative_steps = vllm_config.num_speculative_tokens
if self.speculative_config is not None:
if self.is_last_pp_rank:
self.speculator = init_speculator(self.vllm_config, self.device)
self.speculator = init_speculator(
self.vllm_config, self.device, self.req_states
)
if self.speculative_config.method in (
"eagle3",
@@ -291,20 +310,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.is_pooling_model = self.model_config.runner_type == "pooling"
self.pooling_runner: PoolingRunner | None = None
num_prefill_lookahead = max(1, vllm_config.num_prefill_lookahead_tokens)
self.step_timing = StepTimingCollector()
# General request states.
self.req_states = RequestState(
max_num_reqs=self.max_num_reqs,
max_model_len=self.max_model_len,
max_num_batched_tokens=self.max_num_tokens,
num_speculative_steps=self.num_speculative_steps,
vocab_size=self.vocab_size,
device=self.device,
num_prefill_lookahead=num_prefill_lookahead,
)
self.adaptive_verification: AdaptiveVerificationManager | None = None
self.input_buffers = InputBuffers(
max_num_reqs=self.max_num_reqs,
@@ -482,7 +488,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
custom = self.model_state.custom_sampler(self.sampler)
if custom:
self.vllm_config._check_watermarking_unsupported(custom_sampler=True)
self.vllm_config._check_supports_watermarking(custom_sampler=True)
self.sampler, self.rejection_sampler = custom
elif self.speculative_config is not None:
self.rejection_sampler = RejectionSampler(
@@ -724,7 +730,6 @@ class GPUModelRunner(LoRAModelRunnerMixin):
attn_cg_support.min_cg_attn_backend,
self.decode_query_len,
use_v2_model_runner=True,
tensor_parallel_size=self.parallel_config.tensor_parallel_size,
kv_cache_config=self.kv_cache_config,
max_num_reqs=self.max_num_reqs,
is_profiling=is_profiling,
@@ -772,6 +777,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.kv_caches = [
cache for cache in kv_caches_dict.values() if cache.device == self.device
]
self.model_state.initialize_kv_cache(self.kv_cache_config, self.block_tables)
if is_profiling:
self.kv_connector = NO_OP_KV_CONNECTOR
else:
@@ -813,7 +819,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
"skip_attn must only be True for initial memory profiling."
)
# Create a dummy scheduler output. Plain draft-model speculation adds
# Create a dummy scheduler output. Standalone AR speculation adds
# one correction slot per request during prefill. The scheduler
# accounts for these slots, while dummy runs bypass the scheduler.
# Adjust the dummy token count only when the expanded draft batch
@@ -909,14 +915,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
mm_inputs = [], all_false
# Let the target override the hidden state fed to the drafter
# (e.g. DeepSeek V4 MTP needs the pre-hc_head residual). The
# target returns a persistent buffer sized at max_num_batched_tokens;
# slice to the active token count that propose() expects.
spec_hidden_states = hidden_states
if hasattr(self.model, "get_mtp_target_hidden_states"):
pre_hc_hidden_states = self.model.get_mtp_target_hidden_states()
spec_hidden_states = pre_hc_hidden_states[: hidden_states.shape[0]] # type: ignore[union-attr]
spec_hidden_states = self._get_drafter_hidden_states(hidden_states)
if isinstance(self.sampler, GPUWatermarkSampler):
self.speculator.prepare_watermarking(
self.sampler, input_batch.idx_mapping
@@ -1077,6 +1076,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.lora_config, self
),
)
self.model_state.capture_inner_cudagraphs(
input_buffers,
self.block_tables,
self.attn_groups,
self.kv_cache_config,
)
if self.speculator is not None:
with use_workspace_lane(self._draft_workspace_lane):
self.speculator.capture()
@@ -2057,6 +2062,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
finished_req_ids=finished_req_ids,
ec_connector_output=ec_connector_output,
cudagraph_stats=cudagraph_stats,
num_spec_tokens_to_schedule=scheduler_output.num_spec_tokens_to_schedule,
)
if not self.is_last_pp_rank:
@@ -2068,6 +2074,24 @@ 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(
@@ -2086,6 +2110,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
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
num_spec_tokens = self.execute_model_state.num_spec_tokens_to_schedule
self.execute_model_state = None
if not self.is_last_pp_rank:
@@ -2212,14 +2237,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.speculator.observe_verification(
input_batch.idx_mapping, num_sampled, num_rejected
)
# Let the target override the hidden state fed to the drafter
# (e.g. DeepSeek V4 MTP needs the pre-hc_head residual). The
# target returns a persistent buffer sized at max_num_batched_tokens;
# slice to the active token count that propose() expects.
spec_hidden_states = draft_hidden_states
if hasattr(self.model, "get_mtp_target_hidden_states"):
pre_hc_hidden_states = self.model.get_mtp_target_hidden_states()
spec_hidden_states = pre_hc_hidden_states[: draft_hidden_states.size(0)]
spec_hidden_states = self._get_drafter_hidden_states(draft_hidden_states)
if isinstance(self.sampler, GPUWatermarkSampler):
self.speculator.prepare_watermarking(
self.sampler, input_batch.idx_mapping
@@ -2237,9 +2255,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.req_states.next_prefill_tokens,
self.sampler.sampling_states.temperature.gpu,
self.sampler.sampling_states.seeds.gpu,
num_speculative_tokens=num_spec_tokens,
dp_sync=dp_sync,
mm_inputs=mm_inputs,
)
if num_spec_tokens < self.num_speculative_steps:
draft_tokens[:, num_spec_tokens:] = -1
self.req_states.draft_tokens[input_batch.idx_mapping] = draft_tokens
if self.adaptive_verification is not None:
self.adaptive_verification.record_confidences(
@@ -2251,7 +2272,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# not have a speculator (i.e. self.speculator is None)
self.draft_tokens_handler.set_draft_tokens(
input_batch,
self.req_states.draft_tokens[input_batch.idx_mapping],
self.req_states.draft_tokens[input_batch.idx_mapping, :num_spec_tokens],
)
if self.pp_handler is not None:
self.pp_handler.broadcast_drafts(
@@ -2396,6 +2417,7 @@ class ExecuteModelState(NamedTuple):
finished_req_ids: set[str]
ec_connector_output: ECConnectorOutput | None
cudagraph_stats: CUDAGraphStat | None
num_spec_tokens_to_schedule: int
class BatchReqState(NamedTuple):
+18 -1
View File
@@ -17,7 +17,8 @@ from vllm.v1.attention.backend import AttentionCGSupport
from vllm.v1.core.sched.output import NewRequestData
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.encoder_cudagraph import EncoderCudaGraphManager
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
from vllm.v1.worker.gpu.mm.encoder_runner import EncoderRunner
from vllm.v1.worker.gpu.states import RequestState
@@ -126,6 +127,22 @@ class ModelState(ABC):
def apply_staged_writes(self) -> None:
return None
def initialize_kv_cache(
self, kv_cache_config: KVCacheConfig, block_tables: BlockTables
) -> None:
"""Hook run after the KV cache tensors are allocated and bound."""
return None
def capture_inner_cudagraphs(
self,
input_buffers: InputBuffers,
block_tables: BlockTables,
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
) -> None:
"""Capture the CUDA graphs this state runs inside the model's forward."""
return None
def get_additional_cg_support(self) -> tuple[AttentionCGSupport, str | None]:
"""Cudagraph support of attention groups this ModelState builds outside
``init_attn_backend`` (e.g. encoder-only layers).
+53 -52
View File
@@ -21,6 +21,7 @@ from vllm.v1.core.sched.output import NewRequestData
from vllm.v1.kv_cache_interface import KVCacheConfig, MambaSpec
from vllm.v1.utils import CpuGpuBuffer
from vllm.v1.worker.gpu.attn_utils import build_attn_metadata
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
@@ -114,8 +115,13 @@ class MambaHybridModelState(DefaultModelState):
self.num_accepted_tokens_gpu[req_index].fill_(1)
if self._align_mode:
# Seed the running state block from the resumed/prefilled position.
# The column is in mamba blocks. cache_config.block_size is the
# min over prefix-cacheable groups, so a drafter group with its own
# smaller block (e.g. DFlash) pulls it below mamba_block_size.
mamba_block_size = self.cache_config.mamba_block_size
assert mamba_block_size is not None
self._mamba_state_idx_gpu[req_index].fill_(
(new_req_data.num_computed_tokens - 1) // self.cache_config.block_size
(new_req_data.num_computed_tokens - 1) // mamba_block_size
)
def _get_mamba_group_info(
@@ -134,47 +140,42 @@ class MambaHybridModelState(DefaultModelState):
self._mamba_spec = mamba_spec
return self._mamba_group_ids, self._mamba_spec
def _ensure_align_ctx(
self,
kv_cache_config: KVCacheConfig,
mamba_group_ids: list[int],
block_tables: tuple[torch.Tensor, ...],
) -> MambaSpecDecodeGPUContext:
def initialize_kv_cache(
self, kv_cache_config: KVCacheConfig, block_tables: BlockTables
) -> None:
if not self._align_mode:
return
mamba_group_ids, _ = self._get_mamba_group_info(kv_cache_config)
if self._mamba_state_copy_funcs is None:
mamba_groups = get_mamba_groups(kv_cache_config)
mamba_types = {spec.mamba_type for spec in mamba_groups}
copy_funcs = self.model.get_mamba_state_copy_funcs(mamba_types)
validate_mamba_state_copy_funcs(mamba_groups, copy_funcs)
self._mamba_state_copy_funcs = copy_funcs
copy_funcs = self._mamba_state_copy_funcs
if self._mamba_ctx is None:
# Both SD and DS conv layouts support a >0 spec-decode shift: the
# fused pre-copy kernel (``_copy_mamba_state_block``) applies the
# ``token_bias = num_accepted - 1`` window shift per conv layout
# (SD: contiguous slice; DS: per-dim-row strided slice), matching
# the V1 ``get_conv_copy_spec`` semantics.
self._mamba_ctx = MambaSpecDecodeGPUContext.create(
max_num_reqs=self.max_num_reqs,
kv_cache_config=kv_cache_config,
copy_funcs=copy_funcs,
device=self.device,
make_buffer=lambda n, dtype: CpuGpuBuffer(
n, dtype=dtype, device=self.device
),
)
ctx = self._mamba_ctx
if not ctx.is_initialized:
forward_context = self.vllm_config.compilation_config.static_forward_context
# block_tables are batch-order slices of the persistent
# input_block_tables (stable data_ptr), so the metadata is captured
# once here and reused across steps.
ctx.initialize_from_forward_context(
kv_cache_config,
forward_context,
copy_funcs,
[block_tables[gid] for gid in mamba_group_ids],
)
return ctx
# Both SD and DS conv layouts support a >0 spec-decode shift: the
# fused pre-copy kernel (``_copy_mamba_state_block``) applies the
# ``token_bias = num_accepted - 1`` window shift per conv layout
# (SD: contiguous slice; DS: per-dim-row strided slice), matching
# the V1 ``get_conv_copy_spec`` semantics.
self._mamba_ctx = MambaSpecDecodeGPUContext.create(
max_num_reqs=self.max_num_reqs,
kv_cache_config=kv_cache_config,
copy_funcs=self._mamba_state_copy_funcs,
device=self.device,
make_buffer=lambda n, dtype: CpuGpuBuffer(
n, dtype=dtype, device=self.device
),
)
# Under PP a step's postprocess runs after later steps re-gathered the
# batch-ordered input tables, so state copies read the per-request-slot
# tables. Aligned state indices are for the current batch only.
self._mamba_ctx.initialize_from_forward_context(
kv_cache_config,
self.vllm_config.compilation_config.static_forward_context,
self._mamba_state_copy_funcs,
[block_tables.block_tables[gid].gpu for gid in mamba_group_ids],
[block_tables.input_block_tables[gid] for gid in mamba_group_ids],
)
def preprocess_state(
self,
@@ -194,8 +195,9 @@ class MambaHybridModelState(DefaultModelState):
num_reqs = input_batch.num_reqs
if num_reqs == 0:
return
mamba_group_ids, mamba_spec = self._get_mamba_group_info(kv_cache_config)
ctx = self._ensure_align_ctx(kv_cache_config, mamba_group_ids, block_tables)
_, mamba_spec = self._get_mamba_group_info(kv_cache_config)
ctx = self._mamba_ctx
assert ctx is not None
# The state-advance + pre-copy kernels run every step; they fast-exit per
# request when src_col < 0 or src_col == dst_col, so no copy happens on
@@ -277,18 +279,19 @@ class MambaHybridModelState(DefaultModelState):
]
# GDN uses >= 0 to select spec-decode rows, so non-decode rows
# need the -1 sentinel rather than a raw zero draft count.
# need the -1 sentinel. Decode rows without drafts stay spec rows:
# only that path applies the previous step's accepted offset.
num_decode_draft_tokens_np = np.full(num_reqs, -1, dtype=np.int32)
num_draft_tokens_per_req = input_batch.num_draft_tokens_per_req
if num_draft_tokens_per_req is not None:
# 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)
spec_decode_mask = (num_draft_tokens_per_req > 0) & is_decode
num_decode_draft_tokens_np[: input_batch.num_reqs] = np.where(
spec_decode_mask, num_draft_tokens_per_req, -1
)
if num_draft_tokens_per_req is None:
num_draft_tokens_per_req = np.zeros(input_batch.num_reqs, np.int32)
# 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)
num_decode_draft_tokens_np[: input_batch.num_reqs] = np.where(
is_decode, num_draft_tokens_per_req, -1
)
num_decode_draft_tokens_cpu = torch.from_numpy(num_decode_draft_tokens_np)
if self._align_mode:
@@ -300,10 +303,8 @@ class MambaHybridModelState(DefaultModelState):
if hasattr(builder, "mamba_aligned_state_indices"):
aligned_index_builders.append((group_idx, builder))
if aligned_index_builders:
ctx = self._ensure_align_ctx(
kv_cache_config, mamba_group_ids, block_tables
)
all_group_indices = ctx.compute_aligned_state_indices(
assert self._mamba_ctx is not None
all_group_indices = self._mamba_ctx.compute_aligned_state_indices(
input_batch.seq_lens, num_reqs
)
for group_idx, builder in aligned_index_builders:
+20 -4
View File
@@ -1,11 +1,21 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import TYPE_CHECKING
import torch
from vllm.config import VllmConfig
if TYPE_CHECKING:
from vllm.v1.worker.gpu.states import RequestState
def init_speculator(vllm_config: VllmConfig, device: torch.device):
def init_speculator(
vllm_config: VllmConfig,
device: torch.device,
req_states: "RequestState",
):
"""Build the speculator for this config."""
speculative_config = vllm_config.speculative_config
assert speculative_config is not None
if speculative_config.method == "extract_hidden_states":
@@ -61,10 +71,16 @@ def init_speculator(vllm_config: VllmConfig, device: torch.device):
return EagleSpeculator(vllm_config, device)
elif speculative_config.uses_draft_model():
from vllm.v1.worker.gpu.spec_decode.draft_model.speculator import (
PlainDraftModelSpeculator,
from vllm.v1.worker.gpu.spec_decode.standalone_ar.speculator import (
StandaloneARSpeculator,
)
return PlainDraftModelSpeculator(vllm_config, device)
return StandaloneARSpeculator(vllm_config, device)
elif speculative_config.use_ngram():
from vllm.v1.worker.gpu.spec_decode.ngram.speculator import (
NgramGPUSpeculator,
)
return NgramGPUSpeculator(vllm_config, device, req_states)
else:
raise NotImplementedError(f"{speculative_config.method} is not supported yet.")
@@ -360,6 +360,7 @@ class DFlashSpeculator(DraftModelSpeculator):
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
is_profile: bool = False,
num_speculative_tokens: int | None = None,
) -> torch.Tensor:
num_reqs = input_batch.num_reqs
num_target_tokens = input_batch.num_tokens
@@ -3,13 +3,13 @@
import torch.nn as nn
from vllm.v1.worker.gpu.spec_decode.autoregressive.speculator import (
AutoRegressiveSpeculator,
)
from vllm.v1.worker.gpu.spec_decode.eagle.utils import load_eagle_model
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
TargetDependentARSpeculator,
)
class EagleSpeculator(AutoRegressiveSpeculator):
class EagleSpeculator(TargetDependentARSpeculator):
def load_draft_model(
self,
target_model: nn.Module,
@@ -103,6 +103,7 @@ class ExtractHiddenStatesSpeculator(DraftModelSpeculator):
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
is_profile: bool = False,
num_speculative_tokens: int | None = None,
) -> torch.Tensor:
del (
last_hidden_states,
@@ -17,8 +17,8 @@ from vllm.distributed.parallel_state import get_pp_group
from vllm.logger import init_logger
from vllm.model_executor.model_loader import get_model
from vllm.model_executor.model_loader.utils import get_draft_load_config
from vllm.v1.worker.gpu.spec_decode.autoregressive.speculator import (
AutoRegressiveSpeculator,
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
TargetDependentARSpeculator,
)
logger = init_logger(__name__)
@@ -45,7 +45,7 @@ def _copy_target_kv_scales(attn: nn.Module, target_attn: nn.Module) -> None:
getattr(attn, scale_name).copy_(getattr(target_attn, scale_name))
class Gemma4Speculator(AutoRegressiveSpeculator):
class Gemma4Speculator(TargetDependentARSpeculator):
@property
def advance_draft_positions(self) -> bool:
# Gemma4 MTP is Q-only and reads K/V from the target's existing cache.
@@ -3,13 +3,13 @@
import torch.nn as nn
from vllm.v1.worker.gpu.spec_decode.autoregressive.speculator import (
AutoRegressiveSpeculator,
)
from vllm.v1.worker.gpu.spec_decode.eagle.utils import load_eagle_model
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
TargetDependentARSpeculator,
)
class MTPSpeculator(AutoRegressiveSpeculator):
class MTPSpeculator(TargetDependentARSpeculator):
share_mtp_topk_indices: bool = False
def load_draft_model(
@@ -14,11 +14,11 @@ from vllm.v1.attention.backends.utils import PAD_SLOT_ID
from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer
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.spec_decode.autoregressive.cudagraph_utils import (
SpeculatorCudaGraphManager,
)
from vllm.v1.worker.gpu.spec_decode.eagle.utils import load_eagle_model
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 get_uniform_decode_token_count
logger = init_logger(__name__)
@@ -155,6 +155,7 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
is_profile: bool = False,
num_speculative_tokens: int | None = None,
) -> torch.Tensor:
num_reqs = input_batch.num_reqs
seq_lens_cpu_upper_bound = input_batch.seq_lens_cpu_upper_bound
@@ -0,0 +1,279 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import torch
from vllm.config import VllmConfig
from vllm.triton_utils import HAS_TRITON, tl, triton
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.spec_decode.speculator import BaseSpeculator
if TYPE_CHECKING:
from vllm.config.compilation import CUDAGraphMode
from vllm.v1.worker.gpu.dp_utils import DPSyncState
from vllm.v1.worker.gpu.states import RequestState
@triton.jit
def _ngram_scan_kernel(
token_ids_ptr, # *int32 [max_num_reqs, token_ids_stride]
token_ids_stride,
idx_mapping_ptr, # *int64 [B] batch_idx -> req_state_idx
total_len_ptr, # *int32 [max_num_reqs]
num_sampled_ptr, # *int32 [B]
scratch_ptr, # *int64 [B, scratch_stride] (output)
scratch_stride,
L, # int64 scalar (= max_model_len)
MIN_N: tl.constexpr,
MAX_N: tl.constexpr,
MAX_N_PO2: tl.constexpr,
BLOCK_L: tl.constexpr,
):
b = tl.program_id(0).to(tl.int64)
blk = tl.program_id(1).to(tl.int64)
Lp1 = tl.cast(L, tl.int64) + 1
req_state_idx = tl.load(idx_mapping_ptr + b).to(tl.int64)
seq_len = tl.load(total_len_ptr + req_state_idx).to(tl.int64)
num_sampled = tl.load(num_sampled_ptr + b)
eligible_row = (num_sampled > 0) & (seq_len >= MIN_N)
scratch_off = b * scratch_stride + blk
# Ineligible rows, and blocks fully past the last candidate match
# position, write 0 and exit.
if not (eligible_row & (blk * BLOCK_L <= seq_len - MIN_N - 1)):
tl.store(scratch_ptr + scratch_off, tl.zeros((), tl.int64))
return
row_off = req_state_idx * token_ids_stride
# Load the length-MAX_N suffix once into registers.
suf_iota = tl.arange(0, MAX_N_PO2).to(tl.int64)
suf_pos = seq_len - MAX_N + suf_iota
suf_in_range = (suf_iota < MAX_N) & (suf_pos >= 0) & (suf_pos < seq_len)
suffix = tl.load(
token_ids_ptr + row_off + suf_pos,
mask=suf_in_range,
other=-1,
).to(tl.int32)
pos_iota = tl.arange(0, BLOCK_L).to(tl.int64)
pos = blk * BLOCK_L + pos_iota # ascending
best_score = tl.zeros([BLOCK_L], dtype=tl.int64)
for n_iter in tl.static_range(MIN_N, MAX_N + 1):
max_pos_n = seq_len - n_iter - 1
match = (pos >= 0) & (pos <= max_pos_n)
for j in tl.static_range(0, n_iter):
tok = tl.load(
token_ids_ptr + row_off + (pos + j),
mask=match,
other=0,
).to(tl.int32)
suf_idx = (MAX_N - n_iter) + j
suf_val = tl.sum(tl.where(suf_iota == suf_idx, suffix, 0))
match = match & (tok == suf_val)
# Pack (n, pos) so a single max yields longest-n, rightmost-pos.
cand = n_iter * Lp1 + pos + 1
best_score = tl.where(match, cand, best_score)
block_best = tl.max(best_score, axis=0)
tl.store(scratch_ptr + scratch_off, block_best)
@triton.jit
def _ngram_finalize_kernel(
token_ids_ptr, # *int32 [max_num_reqs, token_ids_stride]
token_ids_stride,
idx_mapping_ptr, # *int64 [B]
total_len_ptr, # *int32 [max_num_reqs]
num_sampled_ptr, # *int32 [B]
last_sampled_ptr, # *int64 [max_num_reqs]
scratch_ptr, # *int64 [B, scratch_stride]
scratch_stride,
drafts_ptr, # *int64 [B, K] (output)
L,
N_BLOCKS,
K: tl.constexpr,
K_PO2: tl.constexpr,
N_BLOCKS_PO2: tl.constexpr,
):
b = tl.program_id(0).to(tl.int64)
Lp1 = tl.cast(L, tl.int64) + 1
NB = tl.cast(N_BLOCKS, tl.int64)
req_state_idx = tl.load(idx_mapping_ptr + b).to(tl.int64)
nb_iota = tl.arange(0, N_BLOCKS_PO2).to(tl.int64)
nb_in_range = nb_iota < NB
block_scores = tl.load(
scratch_ptr + b * scratch_stride + nb_iota,
mask=nb_in_range,
other=0,
)
score = tl.max(block_scores, axis=0)
seq_len = tl.load(total_len_ptr + req_state_idx).to(tl.int64)
num_sampled = tl.load(num_sampled_ptr + b)
last_tok = tl.load(last_sampled_ptr + req_state_idx)
has_match = score > 0
s1 = score - 1
best_n = tl.where(has_match, s1 // Lp1, tl.zeros_like(s1))
best_pos = tl.where(has_match, s1 - best_n * Lp1, tl.zeros_like(s1))
draft_start = tl.where(has_match, best_pos + best_n, tl.zeros_like(s1))
tokens_avail = tl.maximum(seq_len - draft_start, 0)
write_ok = (num_sampled > 0) & has_match
row_off = req_state_idx * token_ids_stride
k_iota = tl.arange(0, K_PO2).to(tl.int64)
k_in_range = k_iota < K
gather_idx = tl.minimum(draft_start + k_iota, tl.cast(L, tl.int64) - 1)
slot_valid = (k_iota < tokens_avail) & write_ok & k_in_range
gathered = tl.load(
token_ids_ptr + row_off + gather_idx,
mask=slot_valid,
other=0,
).to(tl.int64)
# Invalid slots fall back to the last sampled token; they are verified as
# ordinary (rejectable) drafts, so the fill value only affects efficiency.
out = tl.where(slot_valid, gathered, last_tok)
tl.store(drafts_ptr + b * K + k_iota, out, mask=k_in_range)
class NgramGPUSpeculator(BaseSpeculator):
"""V2-compatible GPU n-gram speculator."""
supports_mm_inputs = False
draft_logits = None
def __init__(
self,
vllm_config: VllmConfig,
device: torch.device,
req_states: RequestState,
):
if not HAS_TRITON:
raise RuntimeError("ngram_gpu speculative decoding requires Triton.")
spec = vllm_config.speculative_config
assert spec is not None
assert spec.prompt_lookup_min is not None, (
"prompt_lookup_min must be configured for ngram_gpu"
)
assert spec.prompt_lookup_max is not None, (
"prompt_lookup_max must be configured for ngram_gpu"
)
assert 1 <= spec.prompt_lookup_min <= spec.prompt_lookup_max
self.vllm_config = vllm_config
self.device = device
self.req_states = req_states
self.speculative_config = spec
self.num_speculative_steps: int = spec.num_speculative_tokens
self.min_n: int = spec.prompt_lookup_min
self.max_n: int = spec.prompt_lookup_max
self.max_num_reqs: int = vllm_config.scheduler_config.max_num_seqs
self.max_model_len: int = vllm_config.model_config.max_model_len
L = self.max_model_len
if L >= 1024:
self.block_l = 256
elif L >= 256:
self.block_l = 128
elif L >= 64:
self.block_l = 64
else:
self.block_l = max(16, triton.next_power_of_2(max(L, 1)))
self.n_blocks = triton.cdiv(L, self.block_l)
self.scratch = torch.zeros(
(self.max_num_reqs, self.n_blocks), dtype=torch.int64, device=device
)
# Batch-ordered draft output, scattered into RequestState.draft_tokens
# by the model runner (same contract as the model-based speculators).
self.drafts = torch.zeros(
(self.max_num_reqs, self.num_speculative_steps),
dtype=torch.int64,
device=device,
)
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
del cudagraph_mode
def capture(self) -> None:
return None
@torch.inference_mode()
def propose(
self,
input_batch: InputBatch,
attn_metadata: Any,
slot_mappings: Any,
last_hidden_states: torch.Tensor,
aux_hidden_states: list[torch.Tensor] | None,
num_sampled: torch.Tensor,
num_rejected: torch.Tensor,
last_sampled: torch.Tensor,
next_prefill_tokens: torch.Tensor,
temperature: torch.Tensor,
seeds: torch.Tensor,
dp_sync: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
is_profile: bool = False,
num_speculative_tokens: int | None = None,
) -> torch.Tensor:
num_reqs = input_batch.num_reqs
if dummy_run:
return self.drafts[:num_reqs]
req_states = self.req_states
token_ids = req_states.all_token_ids.gpu
idx_mapping = input_batch.idx_mapping
_ngram_scan_kernel[(num_reqs, self.n_blocks)](
token_ids,
token_ids.stride(0),
idx_mapping,
req_states.total_len.gpu,
num_sampled,
self.scratch,
self.scratch.stride(0),
self.max_model_len,
self.min_n,
self.max_n,
max(1, triton.next_power_of_2(self.max_n)),
self.block_l,
num_warps=4,
num_stages=2,
)
_ngram_finalize_kernel[(num_reqs,)](
token_ids,
token_ids.stride(0),
idx_mapping,
req_states.total_len.gpu,
num_sampled,
last_sampled.view(-1),
self.scratch,
self.scratch.stride(0),
self.drafts,
self.max_model_len,
self.n_blocks,
self.num_speculative_steps,
max(1, triton.next_power_of_2(self.num_speculative_steps)),
max(1, triton.next_power_of_2(self.n_blocks)),
num_warps=2,
num_stages=1,
)
return self.drafts[:num_reqs]
@@ -97,6 +97,7 @@ class BaseSpeculator(ABC):
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
is_profile: bool = False,
num_speculative_tokens: int | None = None,
) -> torch.Tensor:
pass
@@ -561,3 +562,19 @@ class DraftModelSpeculator(BaseSpeculator):
causal=causal,
dcp_local_seq_lens=dcp_local_seq_lens,
)
def _update_draft_decode_metadata(
self, attn_metadata: dict[str, Any], num_reqs: int
) -> None:
if self.block_tables.cp_size > 1:
prepare_dcp_local_seq_lens(
self.input_buffers.dcp_local_seq_lens,
self.input_buffers.seq_lens,
num_reqs,
self.block_tables.cp_size,
self.block_tables.cp_rank,
self.block_tables.cp_interleave,
)
for groups in self.attn_groups:
for group in groups:
group.update_draft_decode_metadata(attn_metadata)
@@ -26,22 +26,22 @@ from vllm.v1.worker.utils import AttentionGroup
logger = init_logger(__name__)
class PlainDraftModelSpeculator(DraftModelSpeculator):
"""Speculative decoding using a separate smaller draft LM.
class StandaloneARSpeculator(DraftModelSpeculator):
"""Standalone autoregressive (AR) drafting with a separate smaller LM.
Unlike Eagle, the draft model runs fully independently of the target model.
Step 0 builds an expanded buffer (accepted + correction token + rejected
slots) via a Triton kernel; steps 1..k-1 are single-token decode steps.
"""
# Plain draft model needs one extra slot per request for correction.
# Standalone AR drafting needs one extra slot per request for correction.
num_extra_query_per_req = 1
def __init__(self, vllm_config: VllmConfig, device: torch.device):
super().__init__(vllm_config, device)
# draft_max_seq_len is read by the parent's attention metadata builder.
# Plain draft model doesn't do per-batch adjustment; cap at max.
# Standalone AR drafting doesn't do per-batch adjustment; cap at max.
self.draft_max_seq_len = self.max_model_len
self.last_token_indices = torch.zeros(
@@ -65,10 +65,10 @@ class PlainDraftModelSpeculator(DraftModelSpeculator):
self.supports_mm_inputs = False
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
pass # CUDA graph not yet supported for plain draft model speculator.
pass # CUDA graph not yet supported for standalone AR speculator.
def capture(self) -> None:
pass # CUDA graph not yet supported for plain draft model speculator.
pass # CUDA graph not yet supported for standalone AR speculator.
def set_attn(
self,
@@ -355,6 +355,7 @@ class PlainDraftModelSpeculator(DraftModelSpeculator):
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
is_profile: bool = False,
num_speculative_tokens: int | None = None,
) -> torch.Tensor:
assert self.model is not None
@@ -414,7 +415,7 @@ def _prepare_prefill_inputs_kernel(
max_model_len,
BLOCK_SIZE: tl.constexpr,
):
"""Per-request step-0 input preparation for the plain draft-model speculator.
"""Per-request step-0 input preparation for the standalone AR speculator.
Output layout for request i (out_start = query_start_loc[i] + i):
[out_start, out_start + num_valid) accepted tokens
@@ -1,11 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
from dataclasses import dataclass, replace
import torch
from vllm.config.compilation import CUDAGraphMode
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.spec_decode.dynamic.utils import build_dynamic_sd_schedule_lookup
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.cudagraph_utils import (
BatchExecutionDescriptor,
@@ -17,6 +19,11 @@ from vllm.v1.worker.gpu.model_states.interface import ModelState
from vllm.v1.worker.utils import AttentionGroup
@dataclass(frozen=True)
class SpeculatorBatchDescriptor(BatchExecutionDescriptor):
num_speculative_tokens: int = 0
class SpeculatorCudaGraphManager(CudaGraphManager):
"""CudaGraphManager for draft prefill and decode.
@@ -27,6 +34,18 @@ class SpeculatorCudaGraphManager(CudaGraphManager):
earlier capture would execute kernels with stale buffer contents.
"""
def specialize_spec_tokens(
self, desc: BatchExecutionDescriptor, num_speculative_tokens: int
) -> BatchExecutionDescriptor:
if desc.cg_mode != CUDAGraphMode.FULL or desc in self.graphs:
return desc
desc = SpeculatorBatchDescriptor(
**vars(desc), num_speculative_tokens=num_speculative_tokens
)
return (
desc if desc in self.graphs else replace(desc, cg_mode=CUDAGraphMode.NONE)
)
def capture(
self,
forward_fn: Callable,
@@ -36,7 +55,25 @@ class SpeculatorCudaGraphManager(CudaGraphManager):
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
progress_bar_desc: str = "Capturing CUDA graphs",
specialize_spec_tokens: bool = False,
) -> None:
if specialize_spec_tokens:
speculative_config = self.vllm_config.speculative_config
assert speculative_config is not None
dense_schedule = build_dynamic_sd_schedule_lookup(
speculative_config.num_speculative_tokens_per_batch_size,
vllm_max_batch_size=self.max_num_reqs,
vllm_num_speculative_tokens=self.vllm_config.num_speculative_tokens,
)
self._capture_descs = {
mode: [
SpeculatorBatchDescriptor(**vars(desc), num_speculative_tokens=k)
for desc in descs
for k in sorted(set(dense_schedule) - {0, 1}, reverse=True)
]
for mode, descs in self._capture_descs.items()
}
def create_forward_fn(
desc: BatchExecutionDescriptor,
warmup: bool,
@@ -60,6 +97,13 @@ class SpeculatorCudaGraphManager(CudaGraphManager):
max_query_len=desc.max_query_len or desc.uniform_token_count,
)
forward_kwargs = {}
if self.decode_query_len == 1:
forward_kwargs["num_speculative_steps"] = (
desc.num_speculative_tokens
if isinstance(desc, SpeculatorBatchDescriptor)
else self.vllm_config.num_speculative_tokens
)
return lambda cg_mode: forward_fn(
num_reqs,
num_tokens,
@@ -67,6 +111,7 @@ class SpeculatorCudaGraphManager(CudaGraphManager):
slot_mappings,
num_tokens_across_dp,
cg_mode,
**forward_kwargs,
)
super().capture(create_forward_fn, progress_bar_desc)
@@ -17,16 +17,22 @@ 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.autoregressive.cudagraph_utils import (
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.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.utils import AttentionGroup, get_uniform_decode_token_count
logger = init_logger(__name__)
class AutoRegressiveSpeculator(DraftModelSpeculator):
class TargetDependentARSpeculator(DraftModelSpeculator):
"""Autoregressive (AR) drafting that depends on target model state.
Base for Eagle, MTP, and Gemma4 drafters, which consume the target's
hidden states (and, for Gemma4, its KV cache) at each draft step.
"""
def __init__(self, vllm_config: VllmConfig, device: torch.device):
super().__init__(vllm_config, device)
@@ -99,10 +105,6 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
self.use_fused_multi_step_decode = False
return
if not self.advance_draft_positions:
self.use_fused_multi_step_decode = True
return
unsupported_backends = sorted(
{
attn_group.backend.get_name()
@@ -190,6 +192,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
self.attn_groups,
self.kv_cache_config,
progress_bar_desc="Capturing decode CUDA graphs",
specialize_spec_tokens=self.use_fused_multi_step_decode
and self.speculative_config.uses_dynamic_speculative_decoding(),
)
self.on_multi_step_decode_end(self.max_num_reqs)
@@ -220,14 +224,17 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
is_profile: bool = False,
num_speculative_tokens: int | None = None,
) -> torch.Tensor:
num_reqs = input_batch.num_reqs
if num_speculative_tokens is None:
num_speculative_tokens = self.num_speculative_steps
num_tokens = input_batch.num_tokens
num_tokens_padded = input_batch.num_tokens_after_padding
num_reqs = input_batch.num_reqs
max_query_len = input_batch.num_scheduled_tokens.max()
max_seq_len = input_batch.seq_lens_cpu_upper_bound[:num_reqs].max().item()
self.draft_max_seq_len = min(
max_seq_len + self.num_speculative_steps, self.max_model_len
max_seq_len + num_speculative_tokens, self.max_model_len
)
# NOTE(woosuk): To avoid CPU-GPU synchronization without CPU knowing the
@@ -322,9 +329,10 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
)
self.on_prefill_end(num_reqs)
if self.num_speculative_steps == 1:
# Early exit.
return self.draft_tokens[:num_reqs, :1]
if num_speculative_tokens <= 1:
if num_speculative_tokens == 0:
self.draft_tokens[:num_reqs].fill_(-1)
return self.draft_tokens[:num_reqs]
if self.pcp_manager is not None and not dummy_run:
self.block_tables.gather_block_tables(
@@ -360,6 +368,10 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
need_eager=is_profile,
dp_sync=decode_batch_sync,
)
if self.decode_cudagraph_manager is not None:
decode_batch_desc = self.decode_cudagraph_manager.specialize_spec_tokens(
decode_batch_desc, num_speculative_tokens
)
num_tokens_across_dp = (
decode_batch_sync.num_tokens_across_dp
if decode_batch_sync is not None
@@ -379,6 +391,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
decode_batch_desc,
num_tokens_across_dp,
input_batch.seq_lens_cpu_upper_bound,
num_speculative_tokens,
)
self.on_multi_step_decode_end(num_reqs)
@@ -505,6 +518,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
batch_desc: BatchExecutionDescriptor,
num_tokens_across_dp: torch.Tensor | None,
seq_lens_cpu_upper_bound: torch.Tensor,
num_speculative_steps: int,
) -> None:
positions = self.input_buffers.positions[:num_reqs]
query_start_loc = self.input_buffers.query_start_loc[: num_reqs + 1]
@@ -512,7 +526,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
attn_metadata = None
slot_mappings_by_layer = None
for step in range(1, self.num_speculative_steps):
for step in range(1, num_speculative_steps):
# Rebuild every step when positions advance, or just once
# on the first step when positions are constant (Gemma4 MTP).
if not skip_attn and (self.advance_draft_positions or step == 1):
@@ -546,6 +560,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
slot_mappings_by_layer,
num_tokens_across_dp=num_tokens_across_dp,
cudagraph_runtime_mode=batch_desc.cg_mode,
num_speculative_steps=num_speculative_steps,
)
def _fused_multi_step_decode(
@@ -555,11 +570,17 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
batch_desc: BatchExecutionDescriptor,
num_tokens_across_dp: torch.Tensor | None,
seq_lens_cpu_upper_bound: torch.Tensor,
num_speculative_steps: int,
) -> None:
positions = self.input_buffers.positions[:num_reqs]
query_start_loc = self.input_buffers.query_start_loc[: num_reqs + 1]
idx_mapping = self.idx_mapping[:num_reqs]
if batch_desc.cg_mode == CUDAGraphMode.FULL:
assert self.decode_cudagraph_manager is not None
self.decode_cudagraph_manager.run_fullgraph(batch_desc)
return
attn_metadata = None
slot_mappings_by_layer = None
if not skip_attn:
@@ -569,10 +590,9 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
positions,
batch_desc.num_tokens,
)
if batch_desc.cg_mode != CUDAGraphMode.FULL:
slot_mappings_by_layer = build_slot_mappings_by_layer(
slot_mappings, self.kv_cache_config
)
slot_mappings_by_layer = build_slot_mappings_by_layer(
slot_mappings, self.kv_cache_config
)
attn_metadata = self._build_uniform_attn_metadata(
num_reqs=num_reqs,
batch_desc=batch_desc,
@@ -581,11 +601,6 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
step=1,
)
if batch_desc.cg_mode == CUDAGraphMode.FULL:
assert self.decode_cudagraph_manager is not None
self.decode_cudagraph_manager.run_fullgraph(batch_desc)
return
self._generate_fused_drafts(
num_reqs,
batch_desc.num_tokens,
@@ -593,6 +608,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
slot_mappings_by_layer,
num_tokens_across_dp,
batch_desc.cg_mode,
num_speculative_steps,
)
def _generate_fused_drafts(
@@ -602,18 +618,25 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
attn_metadata: dict[str, Any] | None,
slot_mappings: dict[str, torch.Tensor] | None,
num_tokens_across_dp: torch.Tensor | None,
cudagraph_runtime_mode: CUDAGraphMode = CUDAGraphMode.NONE,
cudagraph_runtime_mode: CUDAGraphMode,
num_speculative_steps: int,
) -> None:
idx_mapping = self.idx_mapping[:num_reqs]
positions = self.input_buffers.positions[:num_reqs]
query_start_loc = self.input_buffers.query_start_loc[: num_reqs + 1]
attn_groups = (
[group for groups in self.attn_groups for group in groups]
if attn_metadata is not None
else []
)
for step in range(1, self.num_speculative_steps):
for step in range(1, num_speculative_steps):
if attn_metadata is not None and (
self.advance_draft_positions or step == 1
):
self.block_tables.compute_slot_mappings(
idx_mapping,
query_start_loc,
positions,
num_tokens_padded,
)
self._update_draft_decode_metadata(attn_metadata, num_reqs)
self.current_draft_step.fill_(step)
self._generate_draft(
num_reqs,
@@ -622,20 +645,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
slot_mappings,
num_tokens_across_dp,
cudagraph_runtime_mode,
num_speculative_steps,
)
if (
step < self.num_speculative_steps - 1
and attn_metadata is not None
and self.advance_draft_positions
):
self.block_tables.compute_slot_mappings(
idx_mapping,
query_start_loc,
positions,
num_tokens_padded,
)
for attn_group in attn_groups:
attn_group.update_draft_decode_metadata(attn_metadata)
def _generate_draft(
self,
@@ -644,7 +655,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
attn_metadata: dict[str, Any] | None,
slot_mappings: dict[str, torch.Tensor] | None,
num_tokens_across_dp: torch.Tensor | None,
cudagraph_runtime_mode: CUDAGraphMode = CUDAGraphMode.NONE,
cudagraph_runtime_mode: CUDAGraphMode,
num_speculative_steps: int,
) -> None:
self._prepare_eplb_forward(num_reqs)
@@ -682,7 +694,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
self.sample_src_positions,
num_reqs,
self.max_model_len,
self.num_speculative_steps,
num_speculative_steps,
advance_draft_positions=self.advance_draft_positions,
)
+5 -2
View File
@@ -16,6 +16,7 @@ class RequestState:
vocab_size: int,
device: torch.device,
num_prefill_lookahead: int = 1,
use_dense_all_token_ids: bool = False,
):
self.max_num_reqs = max_num_reqs
self.max_model_len = max_model_len
@@ -30,12 +31,14 @@ class RequestState:
# NOTE(woosuk): This tensor can be extremely large (e.g., several GBs)
# depending on the configured max_num_reqs and max_model_len.
# To save GPU memory, we use UVA instead of GPU for this tensor.
# To save GPU memory, we use UVA instead of GPU by default, but
# ngram_gpu benefits from dense device residency because it scans
# active rows repeatedly during proposal.
self.all_token_ids = StagedWriteTensor(
(self.max_num_reqs, self.max_model_len),
dtype=torch.int32,
device=device,
uva_instead_of_gpu=True,
uva_instead_of_gpu=not use_dense_all_token_ids,
)
# NOTE(woosuk): Distinguish clearly between prompt_len and prefill_len:
# - prompt_len: Number of tokens in the user-provided prompt.
+11 -1
View File
@@ -139,9 +139,16 @@ def run_mixed_prefill_decode_warmup(
next_block_id += num_blocks
return block_ids
sampling_params = SamplingParams(max_tokens=2, temperature=0.0)
sampling_params = SamplingParams(
max_tokens=2,
temperature=0.0,
watermarking=False,
)
decode_prefill_output = SchedulerOutput.make_empty()
decode_prefill_output.num_spec_tokens_to_schedule = (
model_runner.num_speculative_steps
)
decode_prefill_output.scheduled_new_reqs = [
NewRequestData(
req_id=decode_req_id,
@@ -171,6 +178,7 @@ def run_mixed_prefill_decode_warmup(
]
mixed_output = SchedulerOutput.make_empty()
mixed_output.num_spec_tokens_to_schedule = model_runner.num_speculative_steps
mixed_output.scheduled_cached_reqs = cached_decode_req
mixed_output.scheduled_new_reqs = [
NewRequestData(
@@ -349,6 +357,7 @@ def _warmup_kernels(
]
prefill_output = SchedulerOutput.make_empty()
prefill_output.num_spec_tokens_to_schedule = num_spec_steps
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
@@ -408,6 +417,7 @@ def _warmup_kernels(
step_spec_tokens[req_ids[i]] = [0] * num_spec_steps
decode_output = SchedulerOutput.make_empty()
decode_output.num_spec_tokens_to_schedule = num_spec_steps
decode_output.scheduled_cached_reqs = cached_req_data
decode_output.num_scheduled_tokens = step_num_scheduled_tokens
decode_output.scheduled_spec_decode_tokens = step_spec_tokens
+36 -56
View File
@@ -116,7 +116,7 @@ from vllm.tracing import instrument
from vllm.utils import length_from_prompt_token_ids_or_embeds
from vllm.utils.gc_utils import freeze_gc_for_cudagraph_capture
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.utils.math_utils import cdiv, round_up
from vllm.utils.math_utils import cdiv
from vllm.utils.mem_utils import DeviceMemoryProfiler, format_gib
from vllm.utils.nvtx_pytorch_hooks import PytHooks
from vllm.utils.platform_utils import num_compute_units
@@ -222,7 +222,6 @@ from vllm.v1.worker.ubatch_utils import (
)
from vllm.v1.worker.utils import (
EncoderTimingStats,
is_residual_scattered_for_sp,
raise_if_nan_logits,
)
from vllm.v1.worker.workspace import lock_workspace
@@ -840,6 +839,12 @@ class GPUModelRunner(
self.num_accepted_tokens = self._make_buffer(
self.max_num_reqs, dtype=torch.int32
)
# The count includes the bonus token, so one is the minimum, and the
# recurrent kernels pick their state slot as `accepted - 1`. Dummy runs
# skip `_prepare_inputs`, so the zeros from the allocation would reach
# those kernels as index -1 and fault on the out-of-bounds read.
self.num_accepted_tokens.np.fill(1)
self.num_accepted_tokens.copy_to_gpu()
# Only relevant for models using M-RoPE (e.g, Qwen2-VL)
if self.uses_mrope:
@@ -2199,7 +2204,7 @@ class GPUModelRunner(
)
self.mrope_positions.gpu[:, :total_num_scheduled_tokens] += drift
use_spec_decode = len(scheduler_output.scheduled_spec_decode_tokens) > 0
use_spec_decode = self.speculative_config is not None
if not use_spec_decode:
# NOTE(woosuk): Due to chunked prefills, the batch may contain
# partial requests. While we should not sample any token
@@ -2226,6 +2231,18 @@ class GPUModelRunner(
num_draft_tokens[req_idx] = draft_len
if num_scheduled_tokens[req_idx] == draft_len + 1:
num_decode_draft_tokens[req_idx] = draft_len
# Some recurrent backends may read the previous step's state at an
# offset that only the speculative path applies. So a decode step
# that got no drafts must still count as a speculative row with
# zero drafts, not as a plain decode. Prompt chunks are left out:
# their tokens are prompt tokens and carry no such offset.
zero_draft_decode_mask = (
self.input_batch.num_computed_tokens_cpu[:num_reqs]
>= self.input_batch.num_prompt_tokens[:num_reqs]
) & (num_scheduled_tokens[:num_reqs] == 1)
num_decode_draft_tokens[
(num_decode_draft_tokens < 0) & zero_draft_decode_mask
] = 0
spec_decode_metadata = self._calc_spec_decode_metadata(
num_draft_tokens, cu_num_tokens
)
@@ -2912,7 +2929,14 @@ class GPUModelRunner(
mm_kwargs.append((mm_feature.modality, mm_feature.data))
mm_lora_refs.append((req_id, mm_feature.mm_position))
return mm_hashes, mm_kwargs, mm_lora_refs
# Stable-sort by modality so each modality is encoded in as few batches
# as possible. Encoder outputs are cached by mm_hash, so order is free.
order = sorted(range(len(mm_kwargs)), key=lambda i: mm_kwargs[i][0])
return (
[mm_hashes[i] for i in order],
[mm_kwargs[i] for i in order],
[mm_lora_refs[i] for i in order],
)
def _cache_encoder_output(
self,
@@ -2973,13 +2997,6 @@ class GPUModelRunner(
and scheduler_output.scheduled_encoder_inputs
)
# Batch mm inputs as much as we can: if a request in the batch has
# multiple modalities or a different modality than the previous one,
# we process it separately to preserve item order.
# FIXME(ywang96): This is a hacky way to deal with multiple modalities
# in the same batch while still being able to benefit from batching
# multimodal inputs. The proper solution should be reordering the
# encoder outputs.
model = cast(SupportsMultiModal, self.model)
if self.lora_config and self.lora_manager.supports_tower_connector_lora():
@@ -3022,10 +3039,8 @@ class GPUModelRunner(
)
self.lora_manager.set_active_adapters(lora_requests, tower_mapping)
# Only set connector mapping if the model actually has a connector.
# Some multimodal models inherit a stub `get_num_mm_connector_tokens`
# from `SupportsMultiModal`, which returns None and should not be
# treated as a signal that connector LoRA is supported.
# Only set connector mapping if the model actually has a connector
# and reports connector token counts.
mm_mapping = (
self.model.get_mm_mapping() # type: ignore[attr-defined]
if hasattr(self.model, "get_mm_mapping")
@@ -3324,20 +3339,9 @@ class GPUModelRunner(
) -> IntermediateTensors:
assert self.intermediate_tensors is not None
tp = self.vllm_config.parallel_config.tensor_parallel_size
is_rs = is_residual_scattered_for_sp(self.vllm_config, num_tokens)
# When sequence parallelism is enabled, the "residual" tensor is
# sharded across TP ranks. All-gather it here because downstream
# QKV + Attention needs the full residual before the SP split point.
if sync_self:
assert intermediate_tensors is not None
for k, v in intermediate_tensors.items():
is_scattered = k == "residual" and is_rs
if is_scattered:
local_len = num_tokens // tp
v = get_tp_group().all_gather(v[:local_len], dim=0)
self.intermediate_tensors[k][:num_tokens].copy_(
v[:num_tokens], non_blocking=True
)
@@ -3432,14 +3436,6 @@ class GPUModelRunner(
async_output_copy_stream=self._get_or_create_async_output_copy_stream(),
)
def _pad_for_sequence_parallelism(self, num_scheduled_tokens: int) -> int:
# Pad tokens to multiple of tensor_parallel_size when
# enabled collective fusion for SP
tp_size = self.vllm_config.parallel_config.tensor_parallel_size
if self.compilation_config.pass_config.enable_sp and tp_size > 1:
return round_up(num_scheduled_tokens, tp_size)
return num_scheduled_tokens
def _prepare_padding_mask(
self, num_tokens_unpadded: int, num_tokens_padded: int
) -> torch.Tensor:
@@ -3928,8 +3924,6 @@ class GPUModelRunner(
)
has_lora = num_active_loras > 0 if force_has_lora is None else force_has_lora
num_tokens_padded = self._pad_for_sequence_parallelism(num_tokens)
def dispatch_cudagraph(num_tokens, disable_full=False, valid_modes=None):
return self.cudagraph_dispatcher.dispatch(
num_tokens=num_tokens,
@@ -3941,18 +3935,9 @@ class GPUModelRunner(
)
cudagraph_mode, batch_descriptor = dispatch_cudagraph(
num_tokens_padded, disable_full=use_cascade_attn or has_encoder_output
num_tokens, disable_full=use_cascade_attn or has_encoder_output
)
num_tokens_padded = batch_descriptor.num_tokens
if self.compilation_config.pass_config.enable_sp:
assert (
batch_descriptor.num_tokens
% self.vllm_config.parallel_config.tensor_parallel_size
== 0
), (
"Sequence parallelism requires num_tokens to be "
"a multiple of tensor parallel size"
)
# Extra coordination when running data-parallel since we need to coordinate
# across ranks
@@ -4314,7 +4299,7 @@ class GPUModelRunner(
self.mamba_state_idx,
)
use_spec_decode = len(scheduler_output.scheduled_spec_decode_tokens) > 0
use_spec_decode = self.speculative_config is not None
ubatch_slices_attn = ubatch_slices_padded if pad_attn else ubatch_slices
slot_mappings_by_group, slot_mappings = self._get_slot_mappings(
@@ -4437,15 +4422,9 @@ class GPUModelRunner(
sample_hidden_states = hidden_states[logits_indices]
if not get_pp_group().is_last_rank:
all_gather_tensors = {
"residual": not is_residual_scattered_for_sp(
self.vllm_config, num_tokens_padded
)
}
get_pp_group().send_tensor_dict(
hidden_states.tensors,
all_gather_group=get_tp_group(),
all_gather_tensors=all_gather_tensors,
)
logits = None
else:
@@ -5518,9 +5497,11 @@ class GPUModelRunner(
)
if weights_path is not None:
# The revision belongs to the model we are reloading away from,
# so it must not be carried over to the new path.
# The revision and any object-storage `model_weights` source
# belong to the model we are reloading away from, so they must
# not be carried over to the new path.
self.model_config.model = weights_path
self.model_config.model_weights = ""
self.model_config.revision = None
weights_iterator = model_loader.get_all_weights(self.model_config, model)
weights_iterator = cast(
@@ -7117,7 +7098,6 @@ class GPUModelRunner(
min_cg_attn_backend,
self.uniform_decode_query_len,
use_v2_model_runner=False,
tensor_parallel_size=self.parallel_config.tensor_parallel_size,
kv_cache_config=self.kv_cache_config,
max_num_reqs=self.max_num_reqs,
is_profiling=is_profiling,
+26 -46
View File
@@ -12,13 +12,13 @@ from fnmatch import filter as fnmatch_filter
from types import NoneType
from typing import TYPE_CHECKING, Any, cast
import numpy as np
import torch
import torch.nn as nn
import vllm.envs as envs
from vllm.config import CUDAGraphMode, VllmConfig, set_current_vllm_config
from vllm.config.compilation import CompilationMode
from vllm.config.profiler import validate_profile_prefix
from vllm.device_allocator import get_mem_allocator_instance
from vllm.distributed import (
ensure_model_parallel_initialized,
@@ -97,7 +97,6 @@ from vllm.v1.worker.startup_plan import (
maybe_apply_startup_plan,
maybe_save_startup_plan,
)
from vllm.v1.worker.utils import is_residual_scattered_for_sp
from vllm.v1.worker.worker_base import CompilationTimes, WorkerBase
from vllm.v1.worker.workspace import init_workspace_manager
@@ -822,10 +821,15 @@ class Worker(WorkerBase):
# so that it's available to the warmup stage.
self.cache_config.num_gpu_blocks = kv_cache_config.num_blocks
# Adopt the engine core's layout; workers spawned after resolution
# (e.g. elastic EP scale-up) only see it through the config.
# Adopt the engine core's layout and prefix-cache granularity; workers
# spawned after resolution (e.g. elastic EP scale-up) only see them
# through the config.
if kv_cache_config.kv_cache_layout is not None:
record_kv_cache_layout(self.cache_config, kv_cache_config.kv_cache_layout)
self.cache_config.hash_block_size = kv_cache_config.hash_block_size
self.cache_config.cache_hit_alignment_tokens = (
kv_cache_config.cache_hit_alignment_tokens
)
# Init kv cache connector here, because it requires
# `kv_cache_config`.
@@ -1020,7 +1024,9 @@ class Worker(WorkerBase):
# Reset the seed to ensure that the random state is not affected by
# the model initialization and profiling.
set_random_seed(self.model_config.seed)
set_random_seed(
self.model_config.seed, self.parallel_config.data_parallel_index
)
# Eagerly trigger inductor's once-per-process lazy inits during
# warmup (rather than on a later compile cache-miss at runtime).
@@ -1270,45 +1276,10 @@ class Worker(WorkerBase):
intermediate_tensors = None
forward_pass = scheduler_output.total_num_scheduled_tokens > 0
num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens
all_gather_tensors = {}
compilation_config = self.vllm_config.compilation_config
parallel_config = self.vllm_config.parallel_config
if (
parallel_config.pipeline_parallel_size > 1
and compilation_config.pass_config.enable_sp
and forward_pass
):
# currently only supported by V1 GPUModelRunner
assert not self.use_v2_model_runner
num_scheduled_tokens_np = np.array(
list(scheduler_output.num_scheduled_tokens.values()),
dtype=np.int32,
)
# TODO(lucas): This is pretty gross; ideally we should only ever call
# `_determine_batch_execution_and_padding` once (will get called again
# in `execute_model`) but this requires a larger refactor of PP.
_, batch_desc, _, _, _ = (
self.model_runner._determine_batch_execution_and_padding(
num_tokens=num_scheduled_tokens,
num_reqs=len(num_scheduled_tokens_np),
num_scheduled_tokens_np=num_scheduled_tokens_np,
max_num_scheduled_tokens=num_scheduled_tokens_np.max(),
use_cascade_attn=False, # TODO(lucas): Handle cascade attention
)
)
all_gather_tensors = {
"residual": not is_residual_scattered_for_sp(
self.vllm_config, batch_desc.num_tokens
)
}
if forward_pass and not get_pp_group().is_first_rank:
tensor_dict, comm_handles, comm_postprocess = (
get_pp_group().irecv_tensor_dict(
all_gather_group=get_tp_group(),
all_gather_tensors=all_gather_tensors,
)
)
assert tensor_dict is not None
@@ -1346,7 +1317,6 @@ class Worker(WorkerBase):
handles = get_pp_group().isend_tensor_dict(
output.tensors,
all_gather_group=get_tp_group(),
all_gather_tensors=all_gather_tensors,
)
self._pp_send_work = handles[1:]
@@ -1357,7 +1327,14 @@ class Worker(WorkerBase):
def take_draft_token_ids(self) -> DraftTokenIds | None:
return self.model_runner.take_draft_token_ids()
def profile(self, is_start: bool = True, profile_prefix: str | None = None):
def profile(
self,
is_start: bool = True,
profile_prefix: str | None = None,
*,
delay_iterations: int | None = None,
max_iterations: int | None = None,
):
# Check if profiling is enabled
if self.profiler_config is None or self.profiler_config.profiler is None:
raise RuntimeError(
@@ -1368,6 +1345,8 @@ class Worker(WorkerBase):
)
if is_start:
validate_profile_prefix(profile_prefix)
# Generate the trace name by combining prefix with comprehensive rank suffix
from vllm.distributed.utils import get_worker_rank_suffix
@@ -1379,9 +1358,6 @@ class Worker(WorkerBase):
else:
trace_name = rank_suffix
if self.profiler_config.profiler == "proton" and self.profiler is not None:
self.profiler.set_output_name(trace_name)
# Create the profiler wrapper only on the first start call
if self.profiler is None:
self.profiler = create_worker_profiler(
@@ -1390,7 +1366,11 @@ class Worker(WorkerBase):
local_rank=self.local_rank,
)
self.profiler.start()
self.profiler.set_output_name(trace_name)
self.profiler.start(
delay_iterations=delay_iterations,
max_iterations=max_iterations,
)
else:
if self.profiler is None:
logger.warning("Profiler was not started, nothing to stop.")
+28 -14
View File
@@ -392,8 +392,8 @@ def postprocess_mamba_fused_kernel(
# Output: num_accepted_tokens update (for src==dst case)
num_accepted_tokens_out_ptr,
# Optional: batch_idx -> req_idx mapping (V2 model runner / PP). The
# per-request decision arrays are in req-state-slot order; the block table
# is in batch order, so HAS_IDX_MAPPING splits the two indexings.
# per-request decision arrays and the block tables are both in
# req-state-slot order.
idx_mapping_ptr,
# Runtime parameter (varies per batch - NOT constexpr to avoid recompilation)
num_reqs,
@@ -476,10 +476,9 @@ def postprocess_mamba_fused_kernel(
if src_block_idx == dest_block_idx and accept_token_bias == 0:
return
bt_row_idx = batch_idx if HAS_IDX_MAPPING else req_idx
_copy_mamba_state_block(
state_idx,
bt_row_idx,
req_idx,
src_block_idx,
dest_block_idx,
accept_token_bias,
@@ -610,7 +609,7 @@ def precopy_mamba_align_fused_kernel(
token_bias = tl.load(token_bias_ptr + req_idx)
_copy_mamba_state_block(
state_idx,
batch_idx,
req_idx,
src_col,
dst_col,
token_bias,
@@ -806,8 +805,10 @@ class MambaSpecDecodeGPUContext:
# Per-group block-table base addresses: int64[num_groups]. Populated in
# initialize_from_forward_context from the persistent per-group block
# table tensors (whose data_ptr is stable across steps).
# table tensors (whose data_ptr is stable across steps). Rows are request
# state slots for the state copies and batch rows for the aligned indices.
block_table_ptrs: torch.Tensor
aligned_index_block_table_ptrs: torch.Tensor
block_table_stride_req: int = 0
# persistent output for the once-per-step, all-group aligned-index launch.
@@ -900,6 +901,9 @@ class MambaSpecDecodeGPUContext:
block_table_ptrs=torch.zeros(
len(mamba_group_ids), dtype=torch.int64, device=device
),
aligned_index_block_table_ptrs=torch.zeros(
len(mamba_group_ids), dtype=torch.int64, device=device
),
aligned_state_indices=torch.empty(
(
len(mamba_group_ids),
@@ -924,6 +928,7 @@ class MambaSpecDecodeGPUContext:
forward_context: dict[str, Any],
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
block_tables: list[torch.Tensor],
aligned_index_block_tables: list[torch.Tensor] | None = None,
) -> None:
"""Extract and cache memory layout metadata from Mamba state tensors.
@@ -955,8 +960,12 @@ class MambaSpecDecodeGPUContext:
mamba_state_copy_funcs: Mapping from MambaAttentionBackendEnum to
copy functions.
block_tables: per-mamba-group persistent block-table tensors, in
the same order as `mamba_group_ids`. Their `data_ptr()` /
`stride(0)` are captured once for the kernel to index into.
the same order as `mamba_group_ids`, with one row per request
state slot. Their `data_ptr()` / `stride(0)` are captured once
for the state-copy kernels to index into.
aligned_index_block_tables: per-mamba-group persistent tables
read by `compute_aligned_state_indices`, with one row per
batch row. Defaults to `block_tables`.
"""
if self.is_initialized:
@@ -968,6 +977,7 @@ class MambaSpecDecodeGPUContext:
forward_context,
mamba_state_copy_funcs,
block_tables,
aligned_index_block_tables or block_tables,
)
def _populate_metadata(
@@ -976,6 +986,7 @@ class MambaSpecDecodeGPUContext:
forward_context: dict[str, Any],
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
block_tables: list[torch.Tensor],
aligned_index_block_tables: list[torch.Tensor],
) -> None:
idx = 0
for group_local_idx, mamba_group_id in enumerate(self.mamba_group_ids):
@@ -1076,16 +1087,19 @@ class MambaSpecDecodeGPUContext:
# `block_tables[i]` is the persistent 2D int32 block-table tensor for
# `mamba_group_ids[i]`; `data_ptr()` / `stride(0)` are stable for the
# engine's lifetime, so we capture them once here.
assert len(block_tables) == self.num_groups, (
f"expected {self.num_groups} block tables, got {len(block_tables)}"
)
strides = {bt.stride(0) for bt in block_tables}
assert len(block_tables) == len(aligned_index_block_tables) == self.num_groups
strides = {bt.stride(0) for bt in (*block_tables, *aligned_index_block_tables)}
assert len(strides) == 1, (
f"all mamba block tables must share stride(0), got {strides}"
)
self.block_table_stride_req = int(next(iter(strides)))
for i, bt in enumerate(block_tables):
for i, (bt, aligned_bt) in enumerate(
zip(block_tables, aligned_index_block_tables)
):
self.block_table_ptrs[i] = _reinterpret_u64_as_i64(bt.data_ptr())
self.aligned_index_block_table_ptrs[i] = _reinterpret_u64_as_i64(
aligned_bt.data_ptr()
)
self.is_initialized = True
@@ -1107,7 +1121,7 @@ class MambaSpecDecodeGPUContext:
block_rows = 32
grid = (triton.cdiv(num_reqs, block_rows),)
get_aligned_state_indices_multi_group_kernel[grid](
self.block_table_ptrs,
self.aligned_index_block_table_ptrs,
seq_lens,
self.aligned_state_indices,
self.block_table_stride_req,
+44 -54
View File
@@ -10,7 +10,7 @@ from typing import Any
import numpy as np
import torch
from vllm.config import CacheConfig, VllmConfig
from vllm.config import CacheConfig
from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.mamba.mamba_mixer2 import share_replayssm_ring_trackers
@@ -327,6 +327,30 @@ class AttentionGroup:
self.get_metadata_builder().update_draft_decode_metadata(metadata)
def _block_size_is_supported(
backends: list[type[AttentionBackend]], block_size: int
) -> bool:
"""Check if the block size is supported by all backends.
An exact ``int`` declaration must match exactly; a ``MultipleOf``
declaration accepts any multiple of its base.
"""
for backend in backends:
is_supported = False
for supported_size in backend.get_supported_kernel_block_sizes():
if isinstance(supported_size, int):
if block_size == supported_size:
is_supported = True
elif isinstance(supported_size, MultipleOf):
if block_size % supported_size.base == 0:
is_supported = True
else:
raise ValueError(f"Unknown supported size: {supported_size}")
if not is_supported:
return False
return True
def select_common_block_size(
kv_manager_block_size: int,
backends: list[type[AttentionBackend]],
@@ -348,27 +372,7 @@ def select_common_block_size(
ValueError: If no valid block size found.
"""
def block_size_is_supported(
backends: list[type[AttentionBackend]], block_size: int
) -> bool:
"""Check if the block size is supported by all backends."""
for backend in backends:
is_supported = False
for supported_size in backend.get_supported_kernel_block_sizes():
if isinstance(supported_size, int):
if block_size == supported_size:
is_supported = True
elif isinstance(supported_size, MultipleOf):
if block_size % supported_size.base == 0:
is_supported = True
else:
raise ValueError(f"Unknown supported size: {supported_size}")
if not is_supported:
return False
return True
if block_size_is_supported(backends, kv_manager_block_size):
if _block_size_is_supported(backends, kv_manager_block_size):
return kv_manager_block_size
# MultipleOf constraints also accept the manager size if they accept a divisor.
@@ -381,7 +385,7 @@ def select_common_block_size(
}
for size in sorted(candidates, reverse=True):
if block_size_is_supported(backends, size):
if _block_size_is_supported(backends, size):
return size
raise ValueError(
f"No common block size for {kv_manager_block_size} ("
@@ -493,9 +497,24 @@ def prepare_kernel_block_sizes(
# This is an attention backend that supports virtual block splitting.
kv_manager_block_size = kv_cache_group.kv_cache_spec.block_size
group_backends = [g.backend for g in attn_groups[kv_cache_gid]]
selected_kernel_size = select_common_block_size(
kv_manager_block_size, group_backends
storage_block_size = (
kv_cache_spec.storage_block_size
if isinstance(kv_cache_spec, MLAAttentionSpec)
else None
)
if storage_block_size is not None and _block_size_is_supported(
group_backends, storage_block_size
):
# Storage-block specs (e.g. the GLM-5.3-Flash kpool indexer
# cache) address the cache in pool pages, and every other
# consumer (cache views, metadata builders, hisparse) already
# uses storage_block_size as the kernel block. Fall back to the
# backend vote when the group's backends do not accept it.
selected_kernel_size = storage_block_size
else:
selected_kernel_size = select_common_block_size(
kv_manager_block_size, group_backends
)
kernel_block_sizes.append(selected_kernel_size)
elif isinstance(kv_cache_spec, MambaSpec):
# This is likely Mamba or other non-attention cache, no splitting.
@@ -794,35 +813,6 @@ def get_uniform_decode_token_count(
return None
def is_residual_scattered_for_sp(
vllm_config: VllmConfig, num_input_tokens: int
) -> bool:
"""Check if the residual tensor is scattered for sequence parallelism.
The residual tensor is scattered across tensor parallel ranks when sequence
parallelism and tensor parallelism is enabled. SP is only supported in
full-graph compilation mode.
"""
if not vllm_config.compilation_config.pass_config.enable_sp:
return False
tp = vllm_config.parallel_config.tensor_parallel_size
if tp == 1:
return False
assert (
vllm_config.compilation_config.use_inductor_graph_partition
or not vllm_config.compilation_config.splitting_ops
), "Sequence parallelism requires full-graph compilation"
# When sequence parallelism is enabled, we always pad num_input_tokens
# to be a multiple of tensor_parallel_size (tp) earlier.
assert num_input_tokens % tp == 0
return True
@dataclass
class EncoderTimingStats:
"""Per-request timing statistics for encoder forward pass."""
+3 -7
View File
@@ -139,7 +139,8 @@ class WorkspaceManager:
AssertionError.
Keys must identify the resource type and configuration. Callers must not
resize or replace tensor storage held by a cached resource. Uses of the
resize or replace tensor storage held by a cached resource once the
manager is locked. Uses of the
same resource must not overlap; include the CUDA stream in the key when
streams can execute concurrently.
@@ -229,12 +230,7 @@ class WorkspaceManager:
# Walk up the stack skipping WorkspaceManager frames
curr_frame = curr_frame.f_back
while curr_frame is not None:
# TODO: This only catches instance methods (self), missing
# classmethods and staticmethods. Once Python 3.11+ is the
# minimum supported version, use co_qualname instead:
# qualname = curr_frame.f_code.co_qualname
# if qualname.startswith("WorkspaceManager."):
if isinstance(curr_frame.f_locals.get("self"), WorkspaceManager):
if curr_frame.f_code.co_qualname.startswith("WorkspaceManager."):
curr_frame = curr_frame.f_back
continue
filename = os.path.basename(curr_frame.f_code.co_filename)