[Spec Decode] Enable Gemma4 DSpark adaptive verification with FlashInfer (#57263)

Signed-off-by: zixi-qi <zixi@inferact.ai>
Co-authored-by: OpenAI Codex <noreply@openai.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
This commit is contained in:
qizixi
2026-09-26 17:01:17 +08:00
committed by GitHub
co-authored by OpenAI Codex Claude Opus 5.5 Nick Hill
parent 3b4566c5cf
commit a4eb3f25d6
24 changed files with 894 additions and 135 deletions
+2
View File
@@ -631,6 +631,8 @@ class SpeculativeConfig:
"dspark",
)
factors.append(uses_aux_hidden_states)
if self.method == "dspark":
factors.append(self.enable_adaptive_verification)
if self.draft_model_config is not None:
factors.append(self.draft_model_config.compute_hash())
+22 -3
View File
@@ -24,7 +24,11 @@ from vllm.transformers_utils.configs.gemma4 import gemma4_layer_config
from .gemma4_mtp import Gemma4MTPAttention, Gemma4MTPDecoderLayer
from .qwen3_dflash import DFlashQwen3Model, _dflash_layer_causal
from .qwen3_dspark import DSparkMarkovHead, Qwen3DSparkForCausalLM
from .qwen3_dspark import (
DSparkConfidenceHead,
DSparkMarkovHead,
Qwen3DSparkForCausalLM,
)
from .utils import extract_layer_index, maybe_prefix
@@ -187,6 +191,18 @@ class Gemma4DSparkModel(DFlashQwen3Model):
config.markov_rank,
prefix=maybe_prefix(prefix, "markov_head"),
)
self.confidence_head: DSparkConfidenceHead | None = None
if getattr(config, "enable_confidence_head", False):
with_markov = getattr(config, "confidence_head_with_markov", False)
input_dim = config.hidden_size
if with_markov:
input_dim += config.markov_rank
self.confidence_head = DSparkConfidenceHead(
input_dim,
prefix=maybe_prefix(prefix, "confidence_head"),
bias=True,
with_markov=with_markov,
)
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids) * self.normalizer
@@ -295,9 +311,8 @@ class Gemma4DSparkForCausalLM(Qwen3DSparkForCausalLM):
params = dict(self.named_parameters())
params.update(dict(self.named_buffers()))
loaded: set[str] = set()
includes_confidence_head = False
for name, w in weights:
if "confidence_head" in name:
continue
if "lm_head" not in name:
name = "model." + name
for pn, wn, shard in stacked:
@@ -310,5 +325,9 @@ class Gemma4DSparkForCausalLM(Qwen3DSparkForCausalLM):
p = params[name]
getattr(p, "weight_loader", default_weight_loader)(p, w)
loaded.add(name)
if "confidence_head" in name:
includes_confidence_head = True
if not includes_confidence_head:
self.model.confidence_head = None
self.model._build_fused_kv_buffers()
return loaded
+6 -5
View File
@@ -52,7 +52,11 @@ from vllm.models.minimax_m3.common.sparse_attention import (
_minimax_m3_aiter_sparse_pa_requested,
)
from vllm.platforms import current_platform
from vllm.v1.attention.backend import AttentionBackend, CommonAttentionMetadata
from vllm.v1.attention.backend import (
AttentionBackend,
CommonAttentionMetadata,
max_decode_query_len,
)
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
from vllm.v1.kv_cache_interface import AttentionSpec
@@ -97,10 +101,7 @@ def aiter_indexer_max_decode_query_len(vllm_config: VllmConfig) -> int:
since that is what the builder splits the batch on and therefore what the
decode kernel will actually be handed.
"""
spec = vllm_config.speculative_config
if spec is None or spec.num_speculative_tokens is None:
return 1
return 1 + (2 if spec.parallel_drafting else 1) * spec.num_speculative_tokens
return max_decode_query_len(vllm_config)
@cache
+14 -1
View File
@@ -387,7 +387,20 @@ class HFConfigParser(ConfigParserBase):
if extra_layer_types := _PATCH_HF_ALLOWED_LAYER_TYPES.get(model_type):
_patch_hf_transformers_allowed_layer_types(extra_layer_types)
if model_type in _SPECULATIVE_DECODING_CONFIGS:
rope_parameters = config_dict.get("rope_parameters") or {}
if model_type == "gemma4_text" and "full_attention" in rope_parameters:
from transformers import Gemma4TextConfig
# Published DSpark configs mix redundant scalar entries with per-layer
# RoPE dicts. Remove them before Transformers' constructor validates.
config_dict["rope_parameters"] = {
k: v
for k, v in rope_parameters.items()
if k not in ("rope_type", "rope_theta")
}
kwargs.setdefault("name_or_path", str(model))
config = Gemma4TextConfig.from_dict(config_dict, **kwargs)
elif model_type in _SPECULATIVE_DECODING_CONFIGS:
config_class = _CONFIG_REGISTRY[model_type]
config = config_class.from_pretrained(
model,
+45 -6
View File
@@ -573,6 +573,26 @@ class AttentionCGSupport(Enum):
"""NO cudagraph support"""
def max_decode_query_len(vllm_config: "VllmConfig") -> int:
"""Widest request a spec-as-decode builder treats as a decode.
On model runner V2 this is a verification request, 1 +
num_speculative_tokens: no V2 speculator builds a wider query. The reorder
threshold and the code that mirrors the builders' decode/prefill split all
read this, so they cannot drift apart.
"""
speculative_config = getattr(vllm_config, "speculative_config", None)
if speculative_config is None or speculative_config.num_speculative_tokens is None:
return 1
num_speculative_tokens = speculative_config.num_speculative_tokens
max_query_len = 1 + num_speculative_tokens
if speculative_config.parallel_drafting and not vllm_config.use_v2_model_runner:
# Model runner V1 only; remove with it. Its parallel drafter appends up
# to num_speculative_tokens mask slots to each verified request.
max_query_len += num_speculative_tokens
return max_query_len
class AttentionMetadataBuilder(ABC, Generic[M]):
# Does this backend/builder support CUDA Graphs for attention (default: no).
# Do not access directly. Call get_cudagraph_support() instead.
@@ -616,6 +636,30 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
"""Get the cudagraph support level of this builder class."""
return cls._cudagraph_support
@classmethod
def get_varlen_cudagraph_max_query_len(
cls: type["AttentionMetadataBuilder"],
vllm_config: "VllmConfig",
kv_cache_spec: "KVCacheSpec",
) -> int | None:
"""Get the largest per-request query length L of the variable-length
decode batches a FULL cudagraph of this builder class can replay.
The graph must replay any decode batch in which every real request has
between 1 and L query tokens and every padding request has 0. Lengths
come from the device query_start_loc; host metadata carries only the
token count and an upper bound on the per-request length. Batches with
a prefill never replay these graphs. Whether host metadata may
understate device query lengths at all is a separate backend question;
see supports_device_cpu_query_lens_mismatch().
Returns:
L, or None for builders reporting ALWAYS, which replay any batch,
and for builders that cannot replay variable-length batches.
"""
return None
def _init_reorder_batch_threshold(
self,
reorder_batch_threshold: int | None = 1,
@@ -632,14 +676,9 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
speculative_config is not None
and speculative_config.num_speculative_tokens is not None
):
max_num_queries_for_spec = (
1
+ (2 if speculative_config.parallel_drafting else 1)
* speculative_config.num_speculative_tokens
)
self.reorder_batch_threshold = max(
self.reorder_batch_threshold,
max_num_queries_for_spec,
max_decode_query_len(self.vllm_config),
)
if (
+56 -18
View File
@@ -67,6 +67,7 @@ from vllm.v1.attention.backend import (
AttentionType,
CommonAttentionMetadata,
MultipleOf,
max_decode_query_len,
)
from vllm.v1.attention.backends.utils import (
get_dcp_local_seq_lens,
@@ -856,15 +857,8 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
self.use_xqa = (
self.flashinfer_trtllm_api_decode_kernel == FlashInferDecodeKernel.XQA
)
# Adaptive verification trims drafts on device, so decode query lengths
# must come from the device qo_indptr; only trtllm-gen supports that
# (the selector already rejects the other configurations).
self.use_trtllm_gen_varlen_decode = (
speculative_config is not None
and speculative_config.enable_adaptive_verification
and self.flashinfer_trtllm_api_decode_kernel
== FlashInferDecodeKernel.TRTLLM_GEN
and not self.use_dcp
self.use_trtllm_gen_varlen_decode = self._uses_trtllm_gen_varlen_decode(
vllm_config, self.flashinfer_trtllm_api_decode_kernel, self.use_dcp
)
self._init_reorder_batch_threshold(
1,
@@ -1011,6 +1005,31 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
else:
return AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
@override # type: ignore[misc]
@classmethod
def get_varlen_cudagraph_max_query_len(
cls: type["FlashInferMetadataBuilder"],
vllm_config: VllmConfig,
kv_cache_spec: KVCacheSpec,
) -> int | None:
# The uniform gate already covers DCP, head geometry, the XQA head-dim
# limit and causality, and yields None for subclasses that force NEVER.
if (
cls.get_cudagraph_support(vllm_config, kv_cache_spec)
!= AttentionCGSupport.UNIFORM_BATCH
):
return None
# The kernel selector asserts off the trtllm-capable architectures, so
# call it only past the gate, as get_cudagraph_support does.
if not cls._uses_trtllm_gen_varlen_decode(
vllm_config,
cls._get_flashinfer_trtllm_api_decode_kernel(),
use_dcp=vllm_config.parallel_config.decode_context_parallel_size > 1,
):
return None
# Longer requests are split off as prefills.
return max_decode_query_len(vllm_config)
def _get_workspace_buffer(self):
if self._workspace_buffer is None:
buffer_size = envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE
@@ -1039,6 +1058,24 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
def set_workspace_buffer(self, workspace_buffer: torch.Tensor):
self._workspace_buffer = workspace_buffer
@staticmethod
def _uses_trtllm_gen_varlen_decode(
vllm_config: VllmConfig,
decode_kernel: FlashInferDecodeKernel | None,
use_dcp: bool,
) -> bool:
"""Whether decode reads per-request query lengths from the device
qo_indptr. Adaptive verification trims drafts on device, and only
trtllm-gen supports that (the selector already rejects the other
configurations)."""
speculative_config = vllm_config.speculative_config
return (
speculative_config is not None
and speculative_config.enable_adaptive_verification
and decode_kernel == FlashInferDecodeKernel.TRTLLM_GEN
and not use_dcp
)
@staticmethod
def _get_flashinfer_trtllm_api_decode_kernel() -> FlashInferDecodeKernel:
if current_platform.is_device_capability(
@@ -1302,7 +1339,9 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
split_decodes_and_prefills(
common_attn_metadata,
decode_threshold=self.reorder_batch_threshold,
require_uniform=not self.use_xqa,
require_uniform=not (
self.use_xqa or self.use_trtllm_gen_varlen_decode
),
)
)
else:
@@ -1704,15 +1743,14 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
bool(causal),
)
elif self.use_trtllm_gen_varlen_decode:
# CPU lens are only an upper bound, device qo_indptr is
# the truth.
decode_q_lens = (
qo_indptr_cpu[1 : num_decodes + 1] - qo_indptr_cpu[:num_decodes]
# CPU placeholders may underestimate query lengths;
# use a safe upper bound.
q_len_per_req = min(
common_attn_metadata.max_query_len, self.reorder_batch_threshold
)
max_q_upper = int(decode_q_lens.max())
if max_q_upper > 1:
q_len_per_req = max_q_upper
q_cu_seq_lens = qo_indptr[: num_decodes + 1]
# Always pass GPU offsets so a graph captured with uniform
# query lengths can replay batches with variable query lengths.
q_cu_seq_lens = qo_indptr[: num_decodes + 1]
attn_metadata.decode = FlashInferTrtllmAPIDecode(
kernel=self.flashinfer_trtllm_api_decode_kernel,
block_tables=block_table_tensor[:num_decodes],
+2 -10
View File
@@ -12,6 +12,7 @@ from vllm import _custom_ops as ops
from vllm.config import VllmConfig
from vllm.forward_context import in_piecewise_cudagraph
from vllm.utils.torch_utils import current_stream
from vllm.v1.attention.backend import max_decode_query_len
from vllm.v1.attention.backends.mla.sparse_utils import (
triton_convert_req_index_to_global_index,
)
@@ -496,17 +497,8 @@ class SparseMLAIndexGroupBuilder:
def get_sparse_mla_index_group_max_rows(vllm_config: VllmConfig) -> int:
max_query_len = 1
speculative_config = vllm_config.speculative_config
if (
speculative_config is not None
and speculative_config.num_speculative_tokens is not None
):
max_query_len += speculative_config.num_speculative_tokens * (
2 if speculative_config.parallel_drafting else 1
)
scheduler_config = vllm_config.scheduler_config
return min(
scheduler_config.max_num_batched_tokens,
scheduler_config.max_num_seqs * max_query_len,
scheduler_config.max_num_seqs * max_decode_query_len(vllm_config),
)
+4 -7
View File
@@ -26,6 +26,7 @@ from vllm.v1.attention.backend import (
AttentionMetadataBuilder,
CommonAttentionMetadata,
MultipleOf,
max_decode_query_len,
)
from vllm.v1.attention.backends.mla.compressor_utils import (
get_dspark_swa_index_width,
@@ -456,14 +457,10 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
self.num_speculative_tokens = (
spec_config.num_speculative_tokens if spec_config else 0
)
# Decode can have query_len up to
# 1 + (2 if parallel drafting else 1) * num_speculative_tokens.
# sparse_swa has no MQA-vs-dense-MHA routing, so multi-token queries take
# the prefill path and the decode/prefill split stays at that width.
spec_mult = (
2 if (spec_config is not None and spec_config.parallel_drafting) else 1
)
self.decode_threshold = 1 + spec_mult * self.num_speculative_tokens
# the prefill path and the decode/prefill split stays at the widest
# decode.
self.decode_threshold = max_decode_query_len(self.vllm_config)
self.reorder_batch_threshold = None
hf_config = self.vllm_config.model_config.hf_config
+4 -10
View File
@@ -27,6 +27,7 @@ from vllm.model_executor.warmup.jit_warmup_triton_helper import (
triton_scalar_specialization_rep,
)
from vllm.triton_utils import tl, triton
from vllm.v1.attention.backend import max_decode_query_len
from vllm.v1.attention.ops.cp_common import (
DirectCPWorkspace,
direct_cp_enabled,
@@ -1011,16 +1012,9 @@ def dcp_a2a_lse_reduce(
def get_dcp_workspace_max_num_tokens(vllm_config: VllmConfig) -> int:
scheduler_config = vllm_config.scheduler_config
speculative_config = vllm_config.speculative_config
speculative_tokens = vllm_config.num_speculative_tokens
tokens_per_seq = (
1
+ (
2
if speculative_config is not None and speculative_config.parallel_drafting
else 1
)
* speculative_tokens
# num_speculative_tokens also counts a diffusion canvas.
tokens_per_seq = max(
1 + vllm_config.num_speculative_tokens, max_decode_query_len(vllm_config)
)
return min(
scheduler_config.max_num_batched_tokens,
+3 -14
View File
@@ -21,6 +21,7 @@ from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.math_utils import round_up
from vllm.utils.torch_utils import current_stream
from vllm.v1.attention.backend import max_decode_query_len
from vllm.v1.kv_offload.cpu.shared_offload_region import SharedOffloadRegion
from vllm.v1.simple_kv_offload.cuda_mem_ops import pin_tensor
@@ -46,20 +47,8 @@ def is_hisparse_decode_batch(attn_metadata: Any | None) -> bool:
)
def _get_max_decode_query_len(vllm_config: VllmConfig) -> int:
speculative_config = getattr(vllm_config, "speculative_config", None)
if (
speculative_config is not None
and speculative_config.num_speculative_tokens is not None
):
return 1 + speculative_config.num_speculative_tokens * (
2 if speculative_config.parallel_drafting else 1
)
return 1
def _get_max_swap_rows(vllm_config: VllmConfig) -> int:
max_query_len = _get_max_decode_query_len(vllm_config)
max_query_len = max_decode_query_len(vllm_config)
scheduler_config = vllm_config.scheduler_config
return min(
scheduler_config.max_num_batched_tokens,
@@ -120,7 +109,7 @@ class ResolvedHiSparseConfig:
if config is None:
return None
max_query_len = _get_max_decode_query_len(vllm_config)
max_query_len = max_decode_query_len(vllm_config)
min_device_buffer_size = max_query_len * model_top_k
# Retain the worst-case union of every speculative step's top-k and
# leave one additional top-k of LRU slack.
+34
View File
@@ -328,6 +328,40 @@ def get_query_lens_mismatch_unsupported_backend(
return None
def get_varlen_cudagraph_unsupported_backend(
attn_groups: list[list[AttentionGroup]],
vllm_config: VllmConfig,
max_query_len: int,
checked_layer_names: set[str] | None = None,
) -> tuple[str, int | None] | None:
"""Name the first backend whose FULL cudagraphs cannot replay decode batches
of 1 to max_query_len tokens per request, with its bound, if any.
ALWAYS builders replay any batch; the others need a bound of at least
max_query_len. See AttentionMetadataBuilder.get_varlen_cudagraph_max_query_len().
"""
for groups in attn_groups:
for group in groups:
if checked_layer_names is not None and checked_layer_names.isdisjoint(
group.layer_names
):
continue
builder = group.get_metadata_builder(0)
spec = group.kv_cache_spec
support = builder.get_cudagraph_support(vllm_config, spec)
if support == AttentionCGSupport.ALWAYS:
continue
bound = (
# NEVER means never, whatever an inherited override says.
None
if support == AttentionCGSupport.NEVER
else builder.get_varlen_cudagraph_max_query_len(vllm_config, spec)
)
if bound is None or bound < max_query_len:
return group.backend.__name__, bound
return None
def init_kv_cache(
forward_context: dict[str, Any],
kv_cache_config: KVCacheConfig,
+2 -1
View File
@@ -69,7 +69,8 @@ class BatchExecutionDescriptor:
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.
# uniform_token_count unset, so this is what keeps a prefill batch out of one:
# the runner passes None for any batch with a prefill.
max_query_len: int | None = None
num_active_loras: int = 0
# Number of microbatches the batch is split into (DBO). 1 means no splitting.
+2 -1
View File
@@ -243,7 +243,8 @@ def dispatch_cg_and_sync_dp(
dp_size: Data-parallel world size. 1 skips all cross-rank work.
dp_rank: This rank's index in the DP group.
max_query_len: Upper bound on per-request query length, for selecting
varlen decode graphs. None means the graph must not constrain it.
varlen decode graphs. None, as for a batch with a prefill, keeps
the batch out of graphs that constrain it.
need_eager: Force `CUDAGraphMode.NONE` instead of dispatching.
num_active_loras: Active LoRA count for this rank. Does not need
cross-rank agreement; it never changes a bucket's token count.
+5 -2
View File
@@ -640,7 +640,6 @@ class GPUModelRunner(LoRAModelRunnerMixin):
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,
@@ -1646,12 +1645,16 @@ 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())
max_query_len: int | None = 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
if batch_req_state.has_prefill:
# Varlen decode graphs replay decodes only, and their bound
# alone would admit a short prefill.
max_query_len = None
if self.pcp_manager is not None:
num_toks = self.pcp_manager.get_num_tokens_for_dispatch(
batch_req_state.num_scheduled_tokens,
@@ -19,8 +19,8 @@ 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_attn_cg_support,
get_query_lens_mismatch_unsupported_backend,
get_varlen_cudagraph_unsupported_backend,
)
logger = init_logger(__name__)
@@ -28,7 +28,6 @@ _PROFILE_REPLAYS = 5
if TYPE_CHECKING:
from vllm.config import VllmConfig
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
@@ -452,7 +451,6 @@ 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,
@@ -477,25 +475,30 @@ def maybe_create_adaptive_verification_manager(
"use a backend that does."
)
target_attn_cg_support = attn_cg_support
if target_layer_names is not None:
target_attn_cg_support = get_attn_cg_support(
# The runner's decode_query_len, the width varlen decode graphs capture.
max_query_len = req_states.num_speculative_steps + num_bonus_tokens
unsupported: tuple[str | None, int | None] | None = (
get_varlen_cudagraph_unsupported_backend(
attn_groups,
vllm_config,
max_query_len,
checked_layer_names=target_layer_names,
)
if additional_attn_cg_support is not None:
target_attn_cg_support = target_attn_cg_support.narrow(
*additional_attn_cg_support
)
if target_attn_cg_support.min_cg_support != AttentionCGSupport.ALWAYS:
)
if unsupported is None and additional_attn_cg_support is not None:
# Groups built outside init_attn_backend report only their support
# level, and without a bound only ALWAYS replays varlen batches.
additional_support, additional_backend = additional_attn_cg_support
if additional_support != AttentionCGSupport.ALWAYS:
unsupported = additional_backend, None
if unsupported is not None:
backend, bound = unsupported
allowed = "none" if bound is None else f"at most {bound}"
raise ValueError(
"Adaptive verification captures varlen decode cudagraphs, so every"
" target attention builder must report AttentionCGSupport.ALWAYS, but "
f"{target_attn_cg_support.min_cg_attn_backend} reports "
f"{target_attn_cg_support.min_cg_support}. Pass "
"enable_adaptive_verification=false in the speculative config, or "
"use a backend that does."
"Adaptive verification replays decode cudagraphs whose per-request "
f"query lengths vary up to {max_query_len}, but {backend} allows "
f"{allowed}. Pass enable_adaptive_verification=false in the "
"speculative config, or use a backend that does."
)
return AdaptiveVerificationManager(