[Spec Decode] DSpark confidence-scheduled verification (#47808)

Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com>
Signed-off-by: Lucas Wilkinson <LucasWilkinson@users.noreply.github.com>
Signed-off-by: Benjamin Chislett <chislett.ben@gmail.com>
Signed-off-by: Lucas Wilkinson <wilkinson.lucas@gmail.com>
Signed-off-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Benjamin Chislett <chislett.ben@gmail.com>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: OpenAI Codex <noreply@openai.com>
This commit is contained in:
Lucas Wilkinson
2026-08-12 12:27:48 -07:00
committed by GitHub
co-authored by OpenAI Codex Claude Opus 5 Benjamin Chislett mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> Nick Hill OpenAI Codex
parent fe889ac925
commit 7f7a32cfec
40 changed files with 1643 additions and 111 deletions
+94
View File
@@ -1,6 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import contextlib
from collections.abc import Iterator
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
import numpy as np
import torch
@@ -17,6 +20,97 @@ from vllm.v1.outputs import (
from vllm.v1.worker.gpu.sample.output import SamplerOutput
from vllm.v1.worker.utils import raise_if_nan_logits
if TYPE_CHECKING:
from vllm.v1.worker.gpu.input_batch import InputBatch
@dataclass(frozen=True)
class StepTimingSample:
forward_ms: float
drafter_ms: float
num_target_tokens: int
num_reqs: int
full_cudagraph: bool
def _timing_event() -> torch.cuda.Event:
return torch.cuda.Event(enable_timing=True)
@dataclass
class StepTimingEvents:
forward_start: torch.cuda.Event = field(default_factory=_timing_event)
forward_end: torch.cuda.Event = field(default_factory=_timing_event)
drafter_start: torch.cuda.Event = field(default_factory=_timing_event)
drafter_end: torch.cuda.Event = field(default_factory=_timing_event)
class StepTimingCollector:
"""Times the steps run inside ``collect``; record calls no-op outside it.
Every step gets its own events, so the steps queue back-to-back and the
block resolves them all behind one sync on the way out.
"""
def __init__(self):
self._collecting = False
self._step: StepTimingEvents | None = None
self._batch = (False, 0, 0)
self._timed: list[tuple[StepTimingEvents, tuple[bool, int, int]]] = []
@contextlib.contextmanager
def collect(self) -> Iterator[list[StepTimingSample]]:
"""Time every step run in this block.
The yielded list holds one sample per timed step once the block exits;
it stays empty inside the block, where the timings are still on device.
"""
samples: list[StepTimingSample] = []
self._collecting = True
try:
yield samples
finally:
self._collecting = False
timed, self._timed, self._step = self._timed, [], None
if not timed:
return
# Same stream, issue order: once the last step is done, so are the rest.
timed[-1][0].drafter_end.synchronize()
samples.extend(
StepTimingSample(
events.forward_start.elapsed_time(events.forward_end),
events.drafter_start.elapsed_time(events.drafter_end),
num_target_tokens,
num_reqs,
full_cudagraph,
)
for events, (full_cudagraph, num_target_tokens, num_reqs) in timed
)
def record_batch(self, input_batch: "InputBatch", full_cudagraph: bool) -> None:
"""Costs from different execution modes must not share a cost curve."""
self._batch = (full_cudagraph, input_batch.num_tokens, input_batch.num_reqs)
def forward_start(self) -> None:
if self._collecting:
self._step = StepTimingEvents()
self._step.forward_start.record()
def forward_end(self) -> None:
if self._step is not None:
self._step.forward_end.record()
def drafter_start(self) -> None:
if self._step is not None:
self._step.drafter_start.record()
def drafter_end(self) -> None:
"""Ends the step: only steps that reach here have a draft cost."""
if self._step is not None:
self._step.drafter_end.record()
self._timed.append((self._step, self._batch))
self._step = None
class AsyncOutput(AsyncModelRunnerOutput):
def __init__(
+16
View File
@@ -180,6 +180,22 @@ def init_attn_backend(
return attn_groups, attn_cg_support_info, kernel_block_sizes
def get_query_lens_mismatch_unsupported_backend(
attn_groups: list[list[AttentionGroup]],
) -> str | None:
"""Name the first backend needing the CPU query lengths to be exact, if any.
The attention selector already excludes these when adaptive verification is
enabled, but models that hard-wire their backend never consult it. See
AttentionBackend.supports_device_cpu_query_lens_mismatch().
"""
for groups in attn_groups:
for group in groups:
if not group.backend.supports_device_cpu_query_lens_mismatch():
return group.backend.__name__
return None
def _allocate_kv_cache(
kv_cache_config: KVCacheConfig, shared_layers: dict[str, str], device: torch.device
):
+43 -2
View File
@@ -54,6 +54,9 @@ class BatchExecutionDescriptor:
num_tokens: int
num_reqs: int | None # None means no request padding is needed (PIECEWISE graphs)
uniform_token_count: int | None = None
# Upper bound on per-request query length. Varlen decode graphs leave
# uniform_token_count unset, so this is what keeps a prefill batch out of one.
max_query_len: int | None = None
num_active_loras: int = 0
@@ -75,14 +78,21 @@ def _is_compatible(
num_tokens: int,
uniform_token_count: int | None,
num_active_loras: int,
max_query_len: int | None,
) -> bool:
# desc.uniform_token_count=None (PIECEWISE) can handle any uniform_token_count
# desc.num_reqs=None means no request padding needed (PIECEWISE)
# desc.max_query_len=None means the graph does not constrain query length; a
# caller that does not track max_query_len must not match one that does
return (
(
desc.uniform_token_count is None
or desc.uniform_token_count == uniform_token_count
)
and (
desc.max_query_len is None
or (max_query_len is not None and desc.max_query_len >= max_query_len)
)
and (desc.num_reqs is None or desc.num_reqs >= num_reqs)
and desc.num_tokens >= num_tokens
and desc.num_active_loras == num_active_loras
@@ -97,6 +107,7 @@ class CudaGraphManager:
cudagraph_mode: CUDAGraphMode,
decode_query_len: int,
lora_capture_cases: list[int] | None = None,
varlen_decode: bool = False,
):
self.vllm_config = vllm_config
self.device = device
@@ -105,6 +116,7 @@ class CudaGraphManager:
assert self.compilation_config is not None
self.cudagraph_mode = cudagraph_mode
self.decode_query_len = decode_query_len
self.varlen_decode = varlen_decode
self.dp_size = vllm_config.parallel_config.data_parallel_size
self.tp_size = vllm_config.parallel_config.tensor_parallel_size
@@ -204,12 +216,27 @@ class CudaGraphManager:
else:
decode_query_lens = [self.decode_query_len]
capture_varlen_decode = (
separate_decode_routine and bool(decode_mode) and self.varlen_decode
)
for num_tokens, num_active_loras in product(
capture_sizes, self.lora_capture_cases
):
# Varlen decode graphs take any mix of 1..decode_query_len tokens per
# request, worst case 1 token per request (or max_num_reqs)
if capture_varlen_decode and num_tokens <= max_decode_tokens:
desc = BatchExecutionDescriptor(
cg_mode=decode_mode,
num_tokens=num_tokens,
num_reqs=min(num_tokens, self.max_num_reqs),
max_query_len=self.decode_query_len,
num_active_loras=num_active_loras,
)
descs_by_mode[decode_mode].append(desc)
descs_by_token_lora[(num_tokens, num_active_loras)].append(desc)
# Capture uniform decode specfifc graphs if required
# (i.e. separate decode routine)
if separate_decode_routine and decode_mode:
elif separate_decode_routine and decode_mode and not self.varlen_decode:
for decode_query_len in decode_query_lens:
rounded_num_tokens = round_up(num_tokens, decode_query_len)
rounded_num_reqs = rounded_num_tokens // decode_query_len
@@ -346,12 +373,19 @@ class CudaGraphManager:
compilation_counter.num_cudagraph_captured += 1
self._graphs_captured = True
def captured_token_counts(self) -> list[int]:
"""Sorted token counts with a captured graph, ignoring LoRA variants."""
return sorted(
{desc.num_tokens for desc in self.graphs if desc.num_active_loras == 0}
)
def dispatch(
self,
num_reqs: int,
num_tokens: int,
uniform_token_count: int | None,
num_active_loras: int,
max_query_len: int | None = None,
) -> BatchExecutionDescriptor:
"""Find matching cudagraph descriptor from priority-ordered candidates."""
@@ -365,6 +399,7 @@ class CudaGraphManager:
num_tokens,
uniform_token_count,
effective_loras,
max_query_len,
):
return desc
return BatchExecutionDescriptor(
@@ -413,6 +448,7 @@ class ModelCudaGraphManager(CudaGraphManager):
cudagraph_mode: CUDAGraphMode,
decode_query_len: int,
lora_capture_cases: list[int] | None = None,
varlen_decode: bool = False,
):
super().__init__(
vllm_config,
@@ -420,6 +456,7 @@ class ModelCudaGraphManager(CudaGraphManager):
cudagraph_mode,
decode_query_len,
lora_capture_cases=lora_capture_cases,
varlen_decode=varlen_decode,
)
self.hidden_states: torch.Tensor | None = None
self.aux_hidden_states: list[torch.Tensor] = []
@@ -483,6 +520,7 @@ class ModelCudaGraphManager(CudaGraphManager):
attn_groups,
kv_cache_config,
full_cudagraph=desc.cg_mode == CUDAGraphMode.FULL,
max_query_len=desc.max_query_len,
)
# Capture with dummy rows marked as padding.
@@ -574,8 +612,11 @@ def prepare_inputs_to_capture(
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
full_cudagraph: bool,
max_query_len: int | None = None,
) -> AttentionState:
input_batch = InputBatch.make_dummy(num_reqs, num_tokens, input_buffers)
input_batch = InputBatch.make_dummy(
num_reqs, num_tokens, input_buffers, max_query_len=max_query_len
)
input_block_tables = block_tables.get_dummy_block_tables(num_reqs)
slot_mappings = block_tables.get_dummy_slot_mappings(num_tokens)
slot_mappings_by_layer = build_slot_mappings_by_layer(
+14 -1
View File
@@ -21,6 +21,7 @@ def sync_cudagraph_and_dp_padding(
uniform_token_count: int | None,
dp_size: int,
dp_rank: int,
max_query_len: int | None = None,
num_active_loras: int = 0,
) -> tuple[BatchExecutionDescriptor, torch.Tensor | None]:
"""
@@ -30,15 +31,17 @@ def sync_cudagraph_and_dp_padding(
"""
assert dp_size > 1, "DP size must be greater than 1"
group = get_dp_group().cpu_group
tensor = torch.zeros(3, dp_size, dtype=torch.int32, device="cpu")
tensor = torch.zeros(4, dp_size, dtype=torch.int32, device="cpu")
tensor[0][dp_rank] = num_tokens
tensor[1][dp_rank] = desired_batch_desc.cg_mode.value
tensor[2][dp_rank] = uniform_token_count or 0 # (0 means None)
tensor[3][dp_rank] = max_query_len or -1 # (-1 means None)
dist.all_reduce(tensor, group=group)
num_tokens_across_dp = tensor[0]
cg_mode_across_dp = tensor[1]
uniform_token_counts_across_dp = tensor[2]
max_query_lens_across_dp = tensor[3]
if torch.all(num_tokens_across_dp == 0).item():
synced_desc = BatchExecutionDescriptor(
@@ -69,6 +72,12 @@ def sync_cudagraph_and_dp_padding(
):
synced_uniform_token_count = None
# Varlen decode graphs are selected by the query-length bound, so ranks must agree
# on it or they pad to different token counts below.
synced_max_query_len: int | None = None
if bool(torch.all(max_query_lens_across_dp != -1).item()):
synced_max_query_len = int(max_query_lens_across_dp.max().item())
# Dispatch for the final synced values, use num_reqs instead of synced_num_reqs
# so we don't perform request padding for PIECEWISE graphs.
# num_active_loras is per-rank and doesn't need cross-rank agreement.
@@ -77,6 +86,7 @@ def sync_cudagraph_and_dp_padding(
synced_num_tokens,
synced_uniform_token_count,
num_active_loras=num_active_loras,
max_query_len=synced_max_query_len,
)
# Update num_tokens_across_dp to reflect padded size.
@@ -92,6 +102,7 @@ def dispatch_cg_and_sync_dp(
uniform_token_count: int | None,
dp_size: int,
dp_rank: int,
max_query_len: int | None = None,
need_eager: bool = False,
num_active_loras: int = 0,
) -> tuple[BatchExecutionDescriptor, torch.Tensor | None]:
@@ -112,6 +123,7 @@ def dispatch_cg_and_sync_dp(
num_tokens,
uniform_token_count,
num_active_loras=num_active_loras,
max_query_len=max_query_len,
)
if dp_size == 1:
@@ -125,5 +137,6 @@ def dispatch_cg_and_sync_dp(
uniform_token_count,
dp_size,
dp_rank,
max_query_len=max_query_len,
num_active_loras=num_active_loras,
)
+68 -5
View File
@@ -1,12 +1,17 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from typing import TYPE_CHECKING
import numpy as np
import torch
from vllm.triton_utils import tl, triton
from vllm.utils import random_uuid
from vllm.utils.math_utils import cdiv
if TYPE_CHECKING:
from vllm.v1.worker.gpu.block_table import BlockTables
class InputBuffers:
@@ -49,9 +54,10 @@ class InputBatch:
expanded_local_pos: torch.Tensor
# [num_reqs]
# batch_idx -> num_scheduled_tokens
# batch_idx -> num_scheduled_tokens, (upper bound when using adaptive verification)
num_scheduled_tokens: np.ndarray
# sum(num_scheduled_tokens)
# number of tokens in the batch,
# may be < sum(num_scheduled_tokens) when using adaptive verification
num_tokens: int
num_tokens_after_padding: int
# Sum of draft tokens scheduled across requests.
@@ -101,9 +107,18 @@ class InputBatch:
# [num_reqs] per-request prompt length, only populated for R-SWA.
prompt_lens: torch.Tensor | None
# Longest query the batch may contain. Set when a cudagraph descriptor promises
# a query length this batch's own split does not reach, so attention metadata
# stays valid for every replay the graph serves.
max_query_len: int | None = None
@classmethod
def make_dummy(
cls, num_reqs: int, num_tokens: int, input_buffers: InputBuffers
cls,
num_reqs: int,
num_tokens: int,
input_buffers: InputBuffers,
max_query_len: int | None = None,
) -> "InputBatch":
assert 0 < num_reqs <= num_tokens
device = input_buffers.device
@@ -115,9 +130,12 @@ class InputBatch:
expanded_local_pos = torch.zeros(num_reqs, dtype=torch.int32, device=device)
# Distribute the remainder evenly so that no dummy request exceeds
# ceil(num_tokens / num_reqs) <= max_model_len tokens.
# ceil(num_tokens / num_reqs) <= max_model_len tokens. Varlen graphs
# accept any split with non-empty slots, so this shape works for them
# too; attention metadata is built from the promised max_query_len.
base_tokens = num_tokens // num_reqs
num_extra = num_tokens % num_reqs
assert max_query_len is None or base_tokens + (num_extra > 0) <= max_query_len
num_scheduled_tokens = np.full(num_reqs, base_tokens, dtype=np.int32)
if num_extra > 0:
num_scheduled_tokens[-num_extra:] += 1
@@ -150,7 +168,8 @@ class InputBatch:
logits_indices = query_start_loc[1:] - 1
cu_num_logits = torch.arange(num_reqs + 1, device=device, dtype=torch.int32)
cu_num_logits_np = np.arange(num_reqs + 1, dtype=np.int32)
# Dummy: seq_len == query_len (fresh-prefill shape).
# Copy so set_dummy_context can add context in place without touching
# num_scheduled_tokens.
seq_lens_cpu_upper_bound = torch.from_numpy(num_scheduled_tokens.copy())
return cls(
req_ids=req_ids,
@@ -184,9 +203,53 @@ class InputBatch:
cu_num_logits_np=cu_num_logits_np,
has_structured_output_reqs=False,
prompt_lens=None,
max_query_len=max_query_len,
)
def set_dummy_context(
input_batch: InputBatch,
block_tables: "BlockTables",
context_len: int,
num_kv_blocks: int,
max_model_len: int,
) -> None:
"""Give each dummy request context_len of context, used when profiling step cost."""
if not block_tables.input_block_tables:
# Attention-free models have no KV context to fabricate.
return
num_reqs = input_batch.num_reqs
query_len = input_batch.max_query_len or int(input_batch.num_scheduled_tokens.max())
context_len = max(min(context_len, max_model_len - query_len), 0)
if not context_len:
return
# Decode-like shape: each request continues after context_len
# already-computed tokens.
input_batch.seq_lens += context_len
input_batch.seq_lens_cpu_upper_bound += context_len
input_batch.num_computed_tokens_np.fill(context_len)
input_batch.num_computed_prefill_tokens_np.fill(context_len)
local_pos = np.arange(input_batch.num_tokens, dtype=np.int64) - np.repeat(
input_batch.query_start_loc_np[:-1], input_batch.num_scheduled_tokens
)
input_batch.positions.copy_(torch.from_numpy(local_pos + context_len))
seq_len = context_len + query_len
for block_table, block_size, bpk in zip(
block_tables.input_block_tables,
block_tables.kernel_block_sizes,
block_tables.blocks_per_kv_block,
):
num_blocks = min(cdiv(seq_len, block_size), block_table.shape[1])
# Spans are disjoint until the pool runs out, then they wrap and share
# blocks: profiling only needs the reads to be realistic, not distinct.
block_ids = torch.arange(
num_reqs * num_blocks, dtype=block_table.dtype, device=block_table.device
) % (num_kv_blocks * bpk)
block_table[:num_reqs, :num_blocks] = block_ids.view(num_reqs, num_blocks)
@triton.jit
def _prepare_prefill_inputs_kernel(
input_ids_ptr,
+134 -16
View File
@@ -72,7 +72,11 @@ from vllm.v1.outputs import (
from vllm.v1.worker.block_table import get_block_table_width
from vllm.v1.worker.cp_utils import check_attention_cp_compatibility
from vllm.v1.worker.gpu import pcp_manager as pcp
from vllm.v1.worker.gpu.async_utils import AsyncOutput, AsyncPoolingOutput
from vllm.v1.worker.gpu.async_utils import (
AsyncOutput,
AsyncPoolingOutput,
StepTimingCollector,
)
from vllm.v1.worker.gpu.attn_utils import (
build_slot_mappings_by_layer,
get_kv_cache_spec,
@@ -101,6 +105,7 @@ from vllm.v1.worker.gpu.input_batch import (
post_update_num_computed_tokens,
prepare_pos_seq_lens,
prepare_prefill_inputs,
set_dummy_context,
)
from vllm.v1.worker.gpu.kv_connector import (
NO_OP_KV_CONNECTOR,
@@ -123,10 +128,17 @@ from vllm.v1.worker.gpu.sample.prompt_logprob import PromptLogprobsWorker
from vllm.v1.worker.gpu.sample.sampler import Sampler
from vllm.v1.worker.gpu.shutdown import free_before_shutdown
from vllm.v1.worker.gpu.spec_decode import init_speculator
from vllm.v1.worker.gpu.spec_decode.adaptive_verification import (
AdaptiveVerificationManager,
maybe_create_adaptive_verification_manager,
)
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
set_eagle3_aux_hidden_state_layers,
)
from vllm.v1.worker.gpu.spec_decode.rejection_sampler import RejectionSampler
from vllm.v1.worker.gpu.spec_decode.rejection_sampler import (
RejectionSampler,
get_max_chunk_logits,
)
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.utils import DraftTokensHandler
from vllm.v1.worker.gpu.states import RequestState
@@ -252,6 +264,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
and self.speculative_config.use_multi_module_mtp()
else 1
)
self.step_timing = StepTimingCollector()
# General request states.
self.req_states = RequestState(
max_num_reqs=self.max_num_reqs,
@@ -262,6 +277,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
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,
max_num_tokens=self.max_num_tokens,
@@ -401,6 +417,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
max_num_logits=self.max_num_reqs * self.decode_query_len,
vocab_size=self.vocab_size,
device=self.device,
mask_stride=self.decode_query_len,
)
if self.is_pooling_model and self.is_last_pp_rank:
@@ -510,6 +527,20 @@ class GPUModelRunner(LoRAModelRunnerMixin):
attn_cg_support = attn_cg_support.narrow(
*self.model_state.get_additional_cg_support()
)
# The speculator clears the flag at load time when the checkpoint has
# no confidence head, so it holds the effective value.
self.adaptive_verification = maybe_create_adaptive_verification_manager(
enable_adaptive_verification=getattr(
self.speculator, "enable_adaptive_verification", False
),
attn_groups=self.attn_groups,
attn_cg_support=attn_cg_support,
req_states=self.req_states,
query_start_loc=self.input_buffers.query_start_loc,
num_bonus_tokens=self.model_state.num_new_sampled_tokens_per_step,
max_total_logits=get_max_chunk_logits(self.vocab_size),
)
self.block_tables = BlockTables(
block_sizes=block_sizes,
max_num_reqs=self.max_num_reqs,
@@ -532,6 +563,8 @@ class GPUModelRunner(LoRAModelRunnerMixin):
initialize_mamba_ssu_backend(
self.vllm_config.mamba_config, self.kv_cache_config
)
if self.adaptive_verification is not None:
self.compilation_config.cudagraph_mode = CUDAGraphMode.FULL_AND_PIECEWISE
cudagraph_mode = self.compilation_config.resolve_cudagraph_mode_and_sizes(
attn_cg_support.min_cg_support,
attn_cg_support.min_cg_attn_backend,
@@ -547,6 +580,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
cudagraph_mode,
decode_query_len=self.decode_query_len,
lora_capture_cases=self.lora_capture_cases,
varlen_decode=self.adaptive_verification is not None,
)
check_attention_cp_compatibility(self.vllm_config)
if isinstance(self.speculator, DraftModelSpeculator):
@@ -594,6 +628,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
*args,
skip_attn: bool = False,
uniform_decode: bool = False,
context_len: int = 0,
skip_eplb: bool = False,
is_profile: bool = False,
**kwargs,
@@ -655,6 +690,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
dummy_run=True,
skip_attn_for_dummy_run=skip_attn,
is_profile=is_profile,
context_len=context_len,
)
self.kv_connector.set_disabled(False)
@@ -670,9 +706,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
aux_hidden_states = self.execute_model_state.aux_hidden_states
self.execute_model_state = None
self.step_timing.forward_end()
# dummy run the eagle speculator's propose to ensure DP/EP sync.
if self.speculator is not None:
assert self.sampler is not None
self.step_timing.drafter_start()
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None
if self.speculator.supports_mm_inputs:
mm_inputs = (
@@ -713,6 +752,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
mm_inputs=mm_inputs,
is_profile=is_profile,
)
self.step_timing.drafter_end()
assert hidden_states is not None # Last PP rank always has hidden_states
sample_hidden_states = hidden_states[input_batch.logits_indices]
@@ -830,6 +870,13 @@ class GPUModelRunner(LoRAModelRunnerMixin):
)
if self.speculator is not None:
self.speculator.capture()
if self.adaptive_verification is not None:
with self.step_timing.collect() as timings:
for batch in self.adaptive_verification.batches_to_profile(
self.cudagraph_manager.captured_token_counts()
):
self._dummy_run(**batch)
self.adaptive_verification.set_initial_cost_curves(timings)
end_time = time.perf_counter()
end_free_gpu_memory = torch.accelerator.get_memory_info()[0]
@@ -906,6 +953,8 @@ class GPUModelRunner(LoRAModelRunnerMixin):
max_tokens=sampling_params.max_tokens if sampling_params else 1, # type: ignore[arg-type]
)
req_index = self.req_states.req_id_to_index[req_id]
if self.adaptive_verification is not None:
self.adaptive_verification.add_request(req_index)
if self.pooling_runner is not None:
assert new_req_data.pooling_params is not None
@@ -994,8 +1043,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
num_reqs, num_toks, max_query_len, has_prefill=False
)
draft_tokens = scheduler_output.scheduled_spec_decode_tokens
# batch_idx -> req_id
req_ids = sort_batch_req_ids(num_tokens_per_req, self.decode_query_len)
req_ids = sort_batch_req_ids(
num_tokens_per_req, draft_tokens, self.decode_query_len
)
numtoks_iter = map(num_tokens_per_req.__getitem__, req_ids)
num_scheduled_tokens = np.fromiter(numtoks_iter, dtype=np.int32, count=num_reqs)
@@ -1007,9 +1060,15 @@ class GPUModelRunner(LoRAModelRunnerMixin):
]
is_prefilling_np = num_computed_prefill_tokens_np < prefill_len_np
if self.adaptive_verification is not None and draft_tokens:
num_toks = self.adaptive_verification.get_num_tokens(
num_tokens_per_req, draft_tokens
)
batch_state = BatchReqState(
req_ids=req_ids,
num_scheduled_tokens=num_scheduled_tokens,
num_tokens=num_toks,
idx_mapping_np=idx_mapping_np,
prefill_len_np=prefill_len_np,
num_computed_prefill_tokens_np=num_computed_prefill_tokens_np,
@@ -1026,7 +1085,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
batch_req_state: "BatchReqState",
batch_desc: BatchExecutionDescriptor,
) -> InputBatch:
num_tokens = scheduler_output.total_num_scheduled_tokens
num_tokens = batch_req_state.num_tokens
num_tokens_after_padding = batch_desc.num_tokens
assert num_tokens > 0
if envs.VLLM_MOE_SKIP_PADDING:
@@ -1072,9 +1131,20 @@ class GPUModelRunner(LoRAModelRunnerMixin):
np.cumsum(num_logits, out=cu_num_logits_np[1:])
cu_num_logits = async_copy_to_gpu(cu_num_logits_np, device=self.device)
max_expand_len = self.decode_query_len
expanded_idx_mapping, expanded_local_pos = expand_idx_mapping(
idx_mapping, total_num_logits, cu_num_logits, max_expand_len
adaptive_verification = (
self.adaptive_verification if num_draft_tokens_per_req is not None else None
)
num_scheduled_tokens_upper_bound = num_scheduled_tokens_np
if adaptive_verification is not None:
# num_scheduled_tokens represents the draft budget evenly distributed across
# all verification requests, `reallocate_drafts` will unevenly assign the
# draft budget to requests on the GPU side only.
num_scheduled_tokens_np, cu_num_logits_np = (
adaptive_verification.compact_batch(
num_draft_tokens_per_req,
num_scheduled_tokens_np,
cu_num_logits_np,
)
)
# Get query_start_loc.
@@ -1086,9 +1156,19 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# Pad for full CUDA graph mode.
# Some attention backends like FA3 require query_start_loc to be non-decreasing.
query_start_loc_np[num_reqs + 1 :] = num_tokens
async_copy_to_gpu(query_start_loc_np, out=self.input_buffers.query_start_loc)
query_start_loc = self.input_buffers.query_start_loc
async_copy_to_gpu(query_start_loc_np, out=query_start_loc)
if adaptive_verification is not None:
cu_num_logits, query_start_loc, total_num_draft_tokens = (
adaptive_verification.reallocate_drafts(req_ids, idx_mapping)
)
total_num_logits = num_reqs * num_bonus_tokens + total_num_draft_tokens
if draft_tokens:
expanded_idx_mapping, expanded_local_pos = expand_idx_mapping(
idx_mapping, total_num_logits, cu_num_logits, self.decode_query_len
)
query_start_loc_np = query_start_loc_np[: num_reqs_padded + 1]
query_start_loc = self.input_buffers.query_start_loc[: num_reqs_padded + 1]
query_start_loc = query_start_loc[: num_reqs_padded + 1]
# Get prefill tokens if any.
if batch_req_state.has_prefill:
@@ -1145,7 +1225,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
seq_lens_cpu_upper_bound_np = np.zeros(num_reqs_padded, dtype=np.int32)
np.add(
num_computed_tokens_np,
num_scheduled_tokens_np,
num_scheduled_tokens_upper_bound,
out=seq_lens_cpu_upper_bound_np[:num_reqs],
)
seq_lens_cpu_upper_bound = torch.from_numpy(seq_lens_cpu_upper_bound_np)
@@ -1168,7 +1248,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
idx_mapping_np=idx_mapping_np,
expanded_idx_mapping=expanded_idx_mapping,
expanded_local_pos=expanded_local_pos,
num_scheduled_tokens=num_scheduled_tokens_np,
num_scheduled_tokens=num_scheduled_tokens_upper_bound,
num_tokens=num_tokens,
num_tokens_after_padding=num_tokens_after_padding,
num_draft_tokens=total_num_draft_tokens,
@@ -1192,6 +1272,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
cu_num_logits_np=cu_num_logits_np,
has_structured_output_reqs=scheduler_output.has_structured_output_requests,
prompt_lens=prompt_lens,
max_query_len=(
int(num_scheduled_tokens_upper_bound.max())
if adaptive_verification is not None
else None
),
)
return pcp.maybe_partition_pcp_batch(self.pcp_manager, input_batch)
@@ -1298,6 +1383,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
is_profile: bool = False,
context_len: int = 0,
) -> ModelRunnerOutput | IntermediateTensors | None:
if not dummy_run:
# Update the request states.
@@ -1315,9 +1401,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# Get batch descriptor and sync across DP ranks.
num_reqs = len(scheduler_output.num_scheduled_tokens)
num_toks = scheduler_output.total_num_scheduled_tokens
max_query_len = max(scheduler_output.num_scheduled_tokens.values())
batch_req_state, uniform_tok_count = self.gather_batch_req_state(
scheduler_output, dummy_run
)
if batch_req_state is not None:
num_toks = batch_req_state.num_tokens
num_active_loras = 0
if self.lora_config:
@@ -1340,6 +1429,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
uniform_tok_count,
self.dp_size,
self.dp_rank,
max_query_len=max_query_len,
need_eager=is_profile or skip_compiled,
num_active_loras=num_active_loras,
)
@@ -1378,13 +1468,23 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self._set_active_loras(*lora_inputs)
else:
# No actual tokens to run. A dummy run for DP or memory profiling.
dummy_num_reqs = batch_desc.num_reqs or num_reqs
input_batch = InputBatch.make_dummy(
batch_desc.num_reqs or num_reqs,
dummy_num_reqs,
batch_desc.num_tokens,
self.input_buffers,
max_query_len=batch_desc.max_query_len,
)
if not skip_attn_for_dummy_run:
block_tables, slot_mappings = self.prepare_dummy_attn(input_batch)
if context_len:
set_dummy_context(
input_batch,
self.block_tables,
context_len,
self.kv_cache_config.num_blocks,
self.max_model_len,
)
else:
assert batch_desc.cg_mode != CUDAGraphMode.FULL, (
"Attention metadata must be prepared for dummy runs when using "
@@ -1488,6 +1588,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
# Update the EPLB meta.
self.eplb.prepare_forward(self.model_config, input_batch.num_tokens)
self.step_timing.record_batch(
input_batch, batch_desc.cg_mode == CUDAGraphMode.FULL
)
self.step_timing.forward_start()
# Run model.
if batch_desc.cg_mode == CUDAGraphMode.FULL:
# Use explicit cudagraph replay for FULL mode.
@@ -1698,6 +1803,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
mm_inputs=mm_inputs,
)
self.req_states.draft_tokens[input_batch.idx_mapping] = draft_tokens
if self.adaptive_verification is not None:
self.adaptive_verification.record_confidences(
self.speculator.draft_token_confidence_probs, input_batch
)
if self.num_speculative_steps > 0:
# Spec-decode and diffusion LLMs both use draft tokens but the latter does
@@ -1839,6 +1948,9 @@ class BatchReqState(NamedTuple):
req_ids: list[str]
num_scheduled_tokens: np.ndarray # [num_reqs]
# May be less than scheduler_output.total_num_scheduled_tokens:
# adaptive verification trims the draft budget before running.
num_tokens: int
idx_mapping_np: np.ndarray # [num_reqs]
prefill_len_np: np.ndarray # [num_reqs]
num_computed_prefill_tokens_np: np.ndarray # [num_reqs]
@@ -1847,9 +1959,15 @@ class BatchReqState(NamedTuple):
def sort_batch_req_ids(
num_tokens_per_req: dict[str, int], decode_query_len: int
num_tokens_per_req: dict[str, int],
draft_tokens: dict[str, list[int]],
decode_query_len: int,
) -> list[str]:
# Order decode -> short_extend -> prefill; split_decodes_and_prefills
# relies on uniform decodes (query_len == decode_query_len) leading.
key = lambda r: ((num := num_tokens_per_req[r]) != decode_query_len, num)
# Order verification/decode -> short_extend -> prefill;
# split_decodes_and_prefills relies on decode-like requests leading.
key = lambda r: (
not draft_tokens.get(r),
(num := num_tokens_per_req[r]) != decode_query_len,
num,
)
return sorted(num_tokens_per_req, key=key)
+3 -1
View File
@@ -144,7 +144,9 @@ class DefaultModelState(ModelState):
input_batch.query_start_loc_np[: num_reqs + 1]
)
query_start_loc_gpu = input_batch.query_start_loc[: num_reqs + 1]
max_query_len = input_batch.num_scheduled_tokens.max().item()
max_query_len = input_batch.max_query_len
if max_query_len is None:
max_query_len = input_batch.num_scheduled_tokens.max().item()
seq_lens_cpu_upper_bound = input_batch.seq_lens_cpu_upper_bound
if for_capture:
# Capture with worst-case max_seq_len so the graph is valid at any replay.
@@ -0,0 +1,477 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Adaptive verification for DSpark speculative decoding."""
from collections import defaultdict
from collections.abc import Iterable, Iterator
from typing import TYPE_CHECKING
import numpy as np
import torch
import vllm.envs as envs
from vllm.distributed.parallel_state import get_tp_group
from vllm.logger import init_logger
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.v1.attention.backend import AttentionCGSupport
from vllm.v1.utils import CpuGpuBuffer
from vllm.v1.worker.gpu.async_utils import StepTimingSample, stream
from vllm.v1.worker.gpu.attn_utils import (
get_query_lens_mismatch_unsupported_backend,
)
from vllm.v1.worker.gpu.buffer_utils import async_copy_to_gpu
logger = init_logger(__name__)
_PROFILE_REPLAYS = 5
if TYPE_CHECKING:
from vllm.v1.worker.gpu.attn_utils import AttentionCGSupportInfo
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.states import RequestState
from vllm.v1.worker.utils import AttentionGroup
def _assign_draft_token_budget(
confidence_probs: torch.Tensor,
idx_mapping: torch.Tensor,
capacities: torch.Tensor,
draft_budget: int,
num_steps: int,
) -> None:
"""Admit the globally best `draft_budget` draft slots, in place.
Every (request, step) slot is scored by its survival probability, the running
product of that request's per-position confidences, and the highest scores win.
Survival only decreases along a request, so a global top-k always admits
continuously along steps with a request.
`capacities` enters holding each request's scheduled draft count (which bounds its
eligible slots) and leaves holding the admitted count. The caller only calls this
when `draft_budget < capacities.sum()`, so every winner is a real draft slot.
"""
survival = confidence_probs[idx_mapping].cumprod(dim=1)
steps = torch.arange(num_steps, device=survival.device)
# Out-of-range slots score -inf so they never outrank a real draft.
out_of_range = steps[None, :] >= capacities[:, None]
survival = survival.masked_fill(out_of_range, -float("inf"))
flat = survival.flatten()
winners = flat.topk(draft_budget).indices
admitted = torch.zeros_like(flat, dtype=torch.bool).index_fill_(0, winners, True)
torch.sum(admitted.view_as(survival), dim=1, dtype=capacities.dtype, out=capacities)
_assign_draft_token_budget_compiled = torch.compile(
_assign_draft_token_budget, dynamic=True
)
def build_cost_tables_from_curves(
draft_curve: list[tuple[int, float]],
verify_curve: list[tuple[int, float]],
max_num_reqs: int,
max_batch_tokens: int,
cudagraph_limit: int = 0,
) -> tuple[np.ndarray, np.ndarray]:
"""Build cost tables: graph-padded below the capture limit, smooth above.
Args:
cudagraph_limit: Largest cudagraph-captured size. At or below it,
execution pads up to the next captured size, so cost is a step
function. Above it there is no padding, so cost is continuous.
"""
def build_table(limit: int, curve: list[tuple[int, float]]) -> np.ndarray:
xs, ys = np.asarray(curve, dtype=np.float64).T
ys = np.maximum.accumulate(ys)
values = np.arange(limit + 1)
# Execution pads to the next captured size, so cost is a step
# function of the padded size: smooth interpolation would invent
# marginal per-token costs that don't exist within a pad bucket.
idx = np.searchsorted(xs, values, side="left")
result = ys[np.minimum(idx, len(xs) - 1)]
# Past the capture limit nothing pads, so cost really is continuous in
# size; snapping to the next profiled point overestimates badly when
# the profiled points are far apart. Interpolate only between points
# that are themselves past the limit: crossing the limit loses
# cudagraphs entirely, which is a genuine discontinuity, so the first
# point above it must not be blended with the last one below.
if cudagraph_limit:
smooth = values > cudagraph_limit
above = xs > cudagraph_limit
if smooth.any() and above.any():
result[smooth] = np.interp(values[smooth], xs[above], ys[above])
if len(xs) > 1:
after = values > xs[-1]
slope = (ys[-1] - ys[-2]) / (xs[-1] - xs[-2])
result[after] = ys[-1] + slope * (values[after] - xs[-1])
return result
draft_table = np.maximum(build_table(max_num_reqs, draft_curve), 0.0)
verify_table = np.maximum(build_table(max_batch_tokens, verify_curve), 1e-6)
return draft_table, verify_table
class AdaptiveVerificationManager:
def __init__(
self,
req_states: "RequestState",
query_start_loc: torch.Tensor,
num_bonus_tokens: int,
max_total_logits: int,
):
self.req_states = req_states
self.num_speculative_steps = req_states.num_speculative_steps
device = req_states.device
self._copy_stream = torch.cuda.Stream(device)
self.num_bonus_tokens = num_bonus_tokens
# Rejection sampling verifies logits in one contiguous chunk; the
# chunked path indexes by scheduled (untrimmed) offsets and cannot
# address the compacted layout, so the budget must fit one chunk.
self._max_total_logits = max_total_logits
self.query_start_loc = query_start_loc
self.cost_tables: tuple[np.ndarray, np.ndarray] | None = None
# Largest cudagraph-captured token count; above it nothing pads.
self._cudagraph_limit = 0
self._batch_budget: tuple[dict[str, int], dict[str, int], int] | None = None
max_num_reqs = req_states.max_num_reqs
# Current per-slot confidences
self._confidence_probs = torch.empty(
(max_num_reqs, self.num_speculative_steps),
dtype=torch.float32,
device=device,
)
self._batch_draft_capacity = torch.empty(
max_num_reqs, dtype=torch.int32, device=device
)
self._num_non_draft_tokens = torch.empty_like(query_start_loc[:-1])
self._cu_num_logits = torch.empty_like(query_start_loc)
# Two D2H slots preserve stale inputs for budget selection.
self._stale_confidences = [
CpuGpuBuffer(
max_num_reqs,
self.num_speculative_steps,
dtype=torch.float32,
device=device,
)
for _ in range(2)
]
self._copy_events = [torch.cuda.Event(blocking=True) for _ in range(2)]
self._pending_resets: list[int] = []
self._stale_idx = 0
for slot in self._stale_confidences:
slot.np.fill(1.0)
def add_request(self, req_idx: int) -> None:
self._stale_confidences[self._stale_idx].np[req_idx].fill(1.0)
self._pending_resets.append(req_idx)
self._confidence_probs[req_idx].fill_(1.0)
def batches_to_profile(self, capture_sizes: list[int]) -> Iterator[dict[str, int]]:
"""Dummy-run kwargs whose step timings seed the cost tables.
Run these inside StepTimingCollector.collect(), then hand the block's
timings to set_initial_cost_curves."""
max_num_tokens = self.req_states.max_num_batched_tokens
size = self._cudagraph_limit = capture_sizes[-1] if capture_sizes else 0
# Also profile beyond the capture limit: real steps run there
# (piecewise/eager) and linear extrapolation badly underestimates
# them. These runs double as JIT warmup for the piecewise shapes.
tail_sizes: set[int] = set()
if size:
tail_sizes.add(min(size + size // 2, max_num_tokens))
while size < max_num_tokens:
size = min(size * 2, max_num_tokens)
tail_sizes.add(size)
tail_sizes -= set(capture_sizes)
for num_tokens in capture_sizes + sorted(tail_sizes):
for _ in range(_PROFILE_REPLAYS):
yield {
"num_tokens": num_tokens,
"context_len": envs.VLLM_ADAPTIVE_VERIFICATION_PROFILE_CONTEXT_LEN,
}
def set_initial_cost_curves(self, samples: list[StepTimingSample]) -> None:
def median_curve(
points: Iterable[tuple[int, float]],
) -> list[tuple[int, float]]:
grouped: defaultdict[int, list[float]] = defaultdict(list)
for key, value in points:
grouped[key].append(value)
return [(k, float(np.median(v))) for k, v in sorted(grouped.items())]
# Draft curve: eager-target steps inflate drafter timings (the CPU is
# still launching kernels, opening gaps between the drafter's events),
# and request counts — unlike token counts — collide across execution
# modes, so only graph-replay samples may price the draft curve.
draft_curve = median_curve(
(s.num_reqs, s.drafter_ms) for s in samples if s.full_cudagraph
)
verify_curve = median_curve(
(s.num_target_tokens, s.forward_ms) for s in samples
)
self.set_cost_curves(draft_curve, verify_curve)
def set_cost_curves(
self,
draft_curve: list[tuple[int, float]],
verify_curve: list[tuple[int, float]],
) -> None:
draft_curve, verify_curve = get_tp_group().broadcast_object(
(draft_curve, verify_curve), src=0
)
if not draft_curve or not verify_curve:
raise RuntimeError(
"Adaptive verification could not profile step costs. Pass "
"`enable_adaptive_verification=false` in the speculative config to "
"verify a fixed number of drafts instead."
)
self.cost_tables = build_cost_tables_from_curves(
draft_curve,
verify_curve,
self.req_states.max_num_reqs,
self.req_states.max_num_batched_tokens,
self._cudagraph_limit,
)
logger.debug("DSpark cost tables: %s", self.cost_tables)
def record_confidences(
self,
confidence_probs: torch.Tensor,
input_batch: "InputBatch",
) -> None:
"""Publish this step's raw confidences for the ranking kernel and start
copying them to the CPU, where a later step's budget reads them."""
num_reqs = input_batch.num_reqs
ready_idx = self._stale_idx ^ 1
with gpu_sync_allowed():
self._copy_events[ready_idx].synchronize()
if self._pending_resets:
self._stale_confidences[ready_idx].np[self._pending_resets] = 1.0
self._pending_resets.clear()
# Last step's copy has landed: budgets read it, this step overwrites the
# slot they were reading before.
self._stale_idx, write_idx = ready_idx, self._stale_idx
self._confidence_probs[input_batch.idx_mapping] = confidence_probs[:num_reqs]
write_slot = self._stale_confidences[write_idx]
write_slot.gpu.copy_(self._confidence_probs)
current_stream = torch.cuda.current_stream(self.req_states.device)
self._copy_stream.wait_stream(current_stream)
with stream(self._copy_stream, current_stream):
write_slot.copy_to_cpu()
self._copy_events[write_idx].record()
def get_num_tokens(
self,
num_tokens_per_req: dict[str, int],
draft_tokens: dict[str, list[int]],
) -> int:
"""Token count once the draft budget is trimmed to fit.
Stashes the chosen budget in ``_batch_budget`` for the compaction and
reallocation that follow in the same step.
"""
assert self.cost_tables is not None
req_ids = list(num_tokens_per_req)
num_reqs = len(req_ids)
scheduled_tokens = np.fromiter(
num_tokens_per_req.values(), dtype=np.int32, count=num_reqs
)
scheduled_drafts = np.fromiter(
(len(draft_tokens.get(req_id, ())) for req_id in req_ids),
dtype=np.int32,
count=num_reqs,
)
num_non_draft_tokens = scheduled_tokens - scheduled_drafts
slots = np.fromiter(
(self.req_states.req_id_to_index[req_id] for req_id in req_ids),
dtype=np.int32,
count=len(req_ids),
)
stale_confidences = self._stale_confidences[self._stale_idx].np[slots]
survival_probability = np.cumprod(stale_confidences.astype(np.float64), axis=1)
steps = np.arange(self.num_speculative_steps)
valid = steps[None, :] < scheduled_drafts[:, None]
scores = np.sort(survival_probability[valid])[::-1]
num_non_draft_tokens_total = int(num_non_draft_tokens.sum())
max_draft_budget = min(
int(scheduled_drafts.sum()),
max(0, self._max_total_logits - num_reqs * self.num_bonus_tokens),
)
scores = scores[:max_draft_budget]
draft_cost_ms, verify_cost_ms = self.cost_tables
num_sampling_requests = np.count_nonzero(
self.req_states.num_computed_tokens_np[slots] + num_non_draft_tokens
>= self.req_states.prefill_len.np[slots]
)
num_tokens_to_estimated_accepted_tokens = np.concatenate(
([num_sampling_requests], num_sampling_requests + np.cumsum(scores))
)
costs = (
draft_cost_ms[len(req_ids)]
+ verify_cost_ms[
num_non_draft_tokens_total : num_non_draft_tokens_total
+ max_draft_budget
+ 1
]
)
num_drafts_per_req = {
req_id: int(num_drafts)
for req_id, num_drafts in zip(req_ids, scheduled_drafts, strict=True)
}
num_non_draft_tokens_per_req = {
req_id: int(num_tokens)
for req_id, num_tokens in zip(req_ids, num_non_draft_tokens, strict=True)
}
draft_budget = int(np.argmax(num_tokens_to_estimated_accepted_tokens / costs))
self._batch_budget = (
num_drafts_per_req,
num_non_draft_tokens_per_req,
draft_budget,
)
return sum(num_non_draft_tokens_per_req.values()) + draft_budget
def compact_batch(
self,
num_draft_tokens_per_req: np.ndarray,
num_scheduled_tokens: np.ndarray,
cu_num_logits_np: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Compact the CPU batch to the chosen draft budget.
Returns the compacted per-request token counts and the CPU cu_num_logits_np.
If the draft budget is 0, we can know cu_num_logits_np exactly, otherwise
its unchanged/an-upper-bound.
"""
batch_budget = self._batch_budget
assert batch_budget is not None
_, _, draft_budget = batch_budget
num_drafts = int(num_draft_tokens_per_req.sum())
if draft_budget == num_drafts:
return num_scheduled_tokens, cu_num_logits_np
num_non_draft_tokens = num_scheduled_tokens - num_draft_tokens_per_req
if draft_budget == 0:
# The draft budget is 0, so we can know cu_num_logits_np exactly. This helps
# when we would exceed the sampler logit chunk size.
num_reqs = num_scheduled_tokens.shape[0]
cu_num_logits_np = (
np.arange(num_reqs + 1, dtype=cu_num_logits_np.dtype)
* self.num_bonus_tokens
)
return num_non_draft_tokens, cu_num_logits_np
is_verification_request = num_draft_tokens_per_req > 0
num_verification_reqs = int(is_verification_request.sum())
# sort_batch_req_ids keeps verification requests at the front.
assert np.all(is_verification_request[:num_verification_reqs])
# for the CPU side buffer we distribute draft tokens evenly
draft_lens_cpu = np.zeros_like(num_non_draft_tokens)
draft_lens_cpu[:num_verification_reqs] = draft_budget // num_verification_reqs
draft_lens_cpu[: draft_budget % num_verification_reqs] += 1
return num_non_draft_tokens + draft_lens_cpu, cu_num_logits_np
def reallocate_drafts(
self, req_ids: list[str], idx_mapping: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, int]:
batch_budget, self._batch_budget = self._batch_budget, None
assert batch_budget is not None
num_drafts_per_req, num_non_draft_tokens_per_req, draft_budget = batch_budget
num_reqs = idx_mapping.shape[0]
scheduled_drafts = np.fromiter(
(num_drafts_per_req[req_id] for req_id in req_ids),
dtype=np.int32,
count=num_reqs,
)
num_non_draft_tokens = np.fromiter(
(num_non_draft_tokens_per_req[req_id] for req_id in req_ids),
dtype=np.int32,
count=num_reqs,
)
num_tokens = int(num_non_draft_tokens.sum()) + draft_budget
# Rank draft slots by survival probability and admit the best prefix.
# capacities enters holding each request's valid draft count (the kernel
# uses it to bound eligible slots) and leaves holding the admitted count.
capacities = self._batch_draft_capacity[:num_reqs]
if draft_budget == 0:
capacities.zero_()
else:
async_copy_to_gpu(scheduled_drafts, out=capacities)
if draft_budget < int(scheduled_drafts.sum()):
_assign_draft_token_budget_compiled(
self._confidence_probs,
idx_mapping,
capacities,
draft_budget,
self.num_speculative_steps,
)
num_non_draft_tokens_gpu = self._num_non_draft_tokens[:num_reqs]
async_copy_to_gpu(
num_non_draft_tokens,
out=num_non_draft_tokens_gpu,
)
self._cu_num_logits[:1].zero_()
torch.cumsum(
capacities + self.num_bonus_tokens,
dim=0,
out=self._cu_num_logits[1 : num_reqs + 1],
)
self.query_start_loc[:1].zero_()
torch.cumsum(
capacities + num_non_draft_tokens_gpu,
dim=0,
out=self.query_start_loc[1 : num_reqs + 1],
)
self.query_start_loc[num_reqs + 1 :].fill_(num_tokens)
return (
self._cu_num_logits[: num_reqs + 1],
self.query_start_loc,
draft_budget,
)
def maybe_create_adaptive_verification_manager(
*,
enable_adaptive_verification: bool,
attn_groups: list[list["AttentionGroup"]],
attn_cg_support: "AttentionCGSupportInfo",
req_states: "RequestState",
query_start_loc: torch.Tensor,
num_bonus_tokens: int,
max_total_logits: int,
) -> AdaptiveVerificationManager | None:
if not enable_adaptive_verification:
return None
# The selector rejects unsupported backends, but models that
# hard-wire theirs (e.g. DeepSeek-V4) never go through it.
backend = get_query_lens_mismatch_unsupported_backend(attn_groups)
if backend is not None:
raise ValueError(
"Adaptive verification trims verification requests on device, which"
f" the {backend} attention backend does not support. Pass "
"enable_adaptive_verification=false in the speculative config, or "
"use a backend that does."
)
if attn_cg_support.min_cg_support != AttentionCGSupport.ALWAYS:
raise ValueError(
"Adaptive verification captures varlen decode cudagraphs, so every"
" attention builder must report AttentionCGSupport.ALWAYS, but "
f"{attn_cg_support.min_cg_attn_backend} reports "
f"{attn_cg_support.min_cg_support}. Pass "
"enable_adaptive_verification=false in the speculative config, or "
"use a backend that does."
)
return AdaptiveVerificationManager(
req_states,
query_start_loc,
num_bonus_tokens,
max_total_logits=max_total_logits,
)
@@ -135,11 +135,10 @@ class DFlashSpeculator(DraftModelSpeculator):
def capture(self) -> None:
logger.info("Capturing model for %s speculator...", self._speculator_name)
# Reset sampling indices to zero to prevent stale values from prior
# dummy runs from being baked into the captured graph.
# Padded sample rows must not scatter into a live request during capture.
self.sample_indices.zero_()
self.sample_pos.zero_()
self.sample_idx_mapping.zero_()
self.sample_idx_mapping.fill_(-1)
assert self.query_cudagraph_manager is not None
self.query_cudagraph_manager.capture(
self._generate_draft,
@@ -589,7 +588,10 @@ def _prepare_dflash_inputs_kernel(
# seq_lens is the absolute sequence length the draft attention
# reads up to (context + query), not just the count of accepted
# tokens this step.
tl.store(out_seq_lens_ptr + req_idx, last_valid_pos + 1 + num_query_per_req)
tl.store(
out_seq_lens_ptr + req_idx,
tl.minimum(last_valid_pos + 1 + num_query_per_req, max_model_len),
)
# Copy sampling state.
tl.store(
out_temperature_ptr + req_state_idx,
@@ -29,10 +29,13 @@ import torch
from vllm.config import VllmConfig
from vllm.config.compilation import CUDAGraphMode
from vllm.logger import init_logger
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
from vllm.v1.worker.gpu.spec_decode.dspark.utils import load_dspark_model
logger = init_logger(__name__)
class DSparkSpeculator(DFlashSpeculator):
_speculator_name = "DSpark"
@@ -76,6 +79,13 @@ class DSparkSpeculator(DFlashSpeculator):
self.draft_model_config.hf_config, "dspark_draft_topk", None
)
self.draft_token_confidence_probs = torch.empty_like(
self.draft_tokens, dtype=torch.float32
)
self.enable_adaptive_verification = (
self.speculative_config.enable_adaptive_verification
)
def load_draft_model(
self,
target_model: torch.nn.Module,
@@ -98,6 +108,13 @@ class DSparkSpeculator(DFlashSpeculator):
dtype=self.draft_logits.dtype,
device=self.device,
)
if self.enable_adaptive_verification and model.model.confidence_head is None:
raise ValueError(
"Adaptive verification needs a DSpark checkpoint with a confidence "
"head, and this one has none. Pass "
"enable_adaptive_verification=false in the speculative config to verify"
" a fixed number of drafts instead."
)
return model
def _sample_logits(
@@ -149,6 +166,7 @@ class DSparkSpeculator(DFlashSpeculator):
idx_map = self.sample_idx_mapping[:num_sample].view(num_reqs, n_spec)
sample_pos = self.sample_pos[:num_sample].view(num_reqs, n_spec)
confidence_markov_embeds = []
# Anchor (bonus) token per request = the input id at query offset 0,
# read via the precomputed persistent index (fixed buffer for capture).
@@ -157,6 +175,8 @@ class DSparkSpeculator(DFlashSpeculator):
for i in range(n_spec):
# Sequential stage: Markov bias from the previously sampled token.
markov_embed = self.model.markov_embed(prev)
if self.enable_adaptive_verification:
confidence_markov_embeds.append(markov_embed)
bias = self.model.markov_bias(markov_embed)
logits_i = base_logits[:, i] + bias
draft_sampled_i = self._sample_logits(
@@ -165,6 +185,15 @@ class DSparkSpeculator(DFlashSpeculator):
self.draft_tokens[:num_reqs, i] = draft_sampled_i
prev = draft_sampled_i
if self.enable_adaptive_verification:
confidence = self.model.compute_confidence(
sample_hidden,
torch.stack(confidence_markov_embeds, dim=1).flatten(0, 1),
)
self.draft_token_confidence_probs[:num_reqs] = confidence.view(
num_reqs, n_spec
)
def _sample_sequential_topk(self, num_reqs: int, head_hidden: torch.Tensor) -> None:
"""Apply the sequential Markov head only to top-k base-logit candidates.
@@ -186,10 +215,13 @@ class DSparkSpeculator(DFlashSpeculator):
base_logits.fill_(float("-inf"))
idx_map = self.sample_idx_mapping[:num_sample].view(num_reqs, n_spec)
sample_pos = self.sample_pos[:num_sample].view(num_reqs, n_spec)
confidence_markov_embeds = []
prev = self.input_buffers.input_ids[self._anchor_idx[:num_reqs]]
for i in range(n_spec):
markov_embed = self.model.markov_embed(prev)
if self.enable_adaptive_verification:
confidence_markov_embeds.append(markov_embed)
logits_i = self.model.apply_markov_bias_gathered(
markov_embed,
base_logits[:, i],
@@ -202,6 +234,15 @@ class DSparkSpeculator(DFlashSpeculator):
self.draft_tokens[:num_reqs, i] = draft_sampled_i
prev = draft_sampled_i
if self.enable_adaptive_verification:
confidence = self.model.compute_confidence(
sample_hidden,
torch.stack(confidence_markov_embeds, dim=1).flatten(0, 1),
)
self.draft_token_confidence_probs[:num_reqs] = confidence.view(
num_reqs, n_spec
)
def _generate_draft(
self,
num_reqs: int,
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterator
from collections.abc import Iterable, Iterator
import numpy as np
import torch
@@ -32,6 +32,11 @@ MAX_CHUNK_BYTES = 2**30 # 1GB
_FP32_BYTES = 4
def get_max_chunk_logits(vocab_size: int) -> int:
"""Largest number of logits rows one verification chunk may hold."""
return max(1, MAX_CHUNK_BYTES // (vocab_size * _FP32_BYTES))
def _iter_request_chunks(
cu_num_logits: np.ndarray, max_chunk_logits: int
) -> Iterator[tuple[int, int]]:
@@ -177,11 +182,22 @@ class RejectionSampler:
) -> tuple[torch.Tensor, torch.Tensor, LogprobsTensors | None]:
cu_num_logits_np = input_batch.cu_num_logits_np
use_processed_logits = self.sampler.logprobs_mode in PROCESSED_LOGPROBS_MODES
num_reqs = input_batch.num_reqs
if logits.shape[0] <= max_chunk_logits:
# One chunk covers the batch. Adaptive verification compacts the logits
# without updating cu_num_logits_np (it keeps the pre-compacted layout),
# so the stale sums must not pick chunk boundaries; its budget cap
# guarantees the compacted batch always lands here.
request_chunks: Iterable[tuple[int, int]] = ((0, num_reqs),)
else:
request_chunks = _iter_request_chunks(cu_num_logits_np, max_chunk_logits)
sampled_chunks: list[torch.Tensor] = []
num_sampled_chunks: list[torch.Tensor] = []
logprobs_chunks: list[LogprobsTensors] = []
for start, end in _iter_request_chunks(cu_num_logits_np, max_chunk_logits):
for start, end in request_chunks:
lo = int(cu_num_logits_np[start])
hi = int(cu_num_logits_np[end])
chunk_cu_num_logits_np = cu_num_logits_np[start : end + 1] - lo
@@ -246,14 +262,14 @@ class RejectionSampler:
max_num_logprobs = self.sampler.sampling_states.max_num_logprobs(
input_batch.idx_mapping_np
)
max_chunk_logits = max(1, MAX_CHUNK_BYTES // (logits.shape[1] * _FP32_BYTES))
chunk_logit_limit = get_max_chunk_logits(logits.shape[1])
sampled, num_sampled, logprobs_tensors = self._verify_in_chunks(
logits,
input_batch,
draft_logits,
draft_sampled,
pos,
max_chunk_logits,
chunk_logit_limit,
max_num_logprobs,
)
+27 -4
View File
@@ -10,7 +10,13 @@ from vllm.v1.worker.gpu.input_batch import InputBatch
class StructuredOutputsWorker:
def __init__(self, max_num_logits: int, vocab_size: int, device: torch.device):
def __init__(
self,
max_num_logits: int,
vocab_size: int,
device: torch.device,
mask_stride: int,
):
self.logits_indices = torch.zeros(
max_num_logits, dtype=torch.int32, device=device
)
@@ -19,6 +25,7 @@ class StructuredOutputsWorker:
)
self.device = device
self.copy_stream = torch.cuda.Stream()
self.mask_stride = mask_stride
def apply_grammar_bitmask(
self,
@@ -45,7 +52,13 @@ class StructuredOutputsWorker:
req_idx = req_id_to_idx[grammar_req_id]
logits_start_idx = cu_num_logits[req_idx]
logits_end_idx = cu_num_logits[req_idx + 1]
mapping.extend(range(logits_start_idx, logits_end_idx))
# Key by (request, position) rather than absolute logit index:
# adaptive verification finalizes per-request logit offsets on
# device, so the kernel resolves them from the GPU cu_num_logits.
mapping.extend(
req_idx * self.mask_stride + position
for position in range(logits_end_idx - logits_start_idx)
)
# Asynchronously copy the mapping to GPU.
with torch.cuda.stream(self.copy_stream):
@@ -69,9 +82,11 @@ class StructuredOutputsWorker:
logits,
logits.stride(0),
logits_indices,
input_batch.cu_num_logits,
bitmask,
bitmask.stride(0),
vocab_size,
MASK_STRIDE=self.mask_stride,
BLOCK_SIZE=BLOCK_SIZE,
)
@@ -87,13 +102,21 @@ def _apply_grammar_bitmask_kernel(
logits_ptr,
logits_stride,
logits_indices_ptr,
cu_num_logits_ptr,
bitmask_ptr,
bitmask_stride,
vocab_size,
MASK_STRIDE: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
bitmask_idx = tl.program_id(0)
logits_idx = tl.load(logits_indices_ptr + bitmask_idx)
mapping_idx = tl.load(logits_indices_ptr + bitmask_idx)
req_idx = mapping_idx // MASK_STRIDE
position_idx = mapping_idx % MASK_STRIDE
logits_idx = tl.load(cu_num_logits_ptr + req_idx)
num_req_logits = tl.load(cu_num_logits_ptr + req_idx + 1) - logits_idx
logits_idx += position_idx
position_is_active = position_idx < num_req_logits
# Load the bitmask.
block_id = tl.program_id(1)
@@ -111,5 +134,5 @@ def _apply_grammar_bitmask_kernel(
tl.store(
logits_ptr + logits_idx * logits_stride + block_offset,
-float("inf"),
mask=bitmask & (block_offset < vocab_size),
mask=position_is_active & bitmask & (block_offset < vocab_size),
)