class TargetDependentARSpeculator(AutoRegressiveSpeculator):
"""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)
self.hidden_states = torch.zeros(
self.max_num_tokens, self.hidden_size, dtype=self.dtype, device=device
)
self.sample_src_positions = torch.zeros(
self.max_num_reqs, dtype=torch.int64, device=device
)
self.inputs_embeds: torch.Tensor | None = None
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
self.prefill_cudagraph_manager = SpeculatorCudaGraphManager(
self.vllm_config,
self.device,
cudagraph_mode,
self.vllm_config.get_decode_cudagraph_query_lens(
self.num_speculative_steps + 1
),
# Draft prefill shares the target's padded attention metadata.
varlen_decode=self.enable_adaptive_verification,
)
super().init_cudagraph_manager(cudagraph_mode)
def load_model(self, target_model: nn.Module) -> None:
super().load_model(target_model)
if not self.supports_mm_inputs:
return
self.inputs_embeds = torch.zeros(
self.max_num_tokens, self.hidden_size, dtype=self.dtype, device=self.device
)
def _prefill_capture_inputs(
self,
) -> tuple[InputBuffers, list[list[AttentionGroup]]]:
attn_groups = (
self.target_attn_groups
if self.can_reuse_target_attn_metadata
else self.attn_groups
)
return self.target_input_buffers, attn_groups
def _prepare_decode_inputs(
self,
input_batch: InputBatch,
num_rejected: torch.Tensor,
num_reqs: int,
skip_attn: bool,
batch_desc: Any,
) -> None:
_prepare_decode_inputs_kernel[(num_reqs + 1,)](
self.draft_tokens[:num_reqs, 0],
self.draft_tokens.stride(0),
input_batch.seq_lens,
num_rejected,
self.input_buffers.input_ids,
self.input_buffers.positions,
self.sample_src_positions,
self.input_buffers.query_start_loc,
self.input_buffers.seq_lens,
self.max_model_len,
self.max_num_reqs,
BLOCK_SIZE=1024,
ADVANCE_DRAFT_POSITIONS=self.advance_draft_positions,
)
def supports_batch_sharded_draft_logits(self) -> bool:
# Every draft logits write goes through sample_draft.
return True
@torch.inference_mode()
def propose(
self,
input_batch: InputBatch,
attn_metadata: dict[str, Any],
slot_mappings: dict[str, torch.Tensor],
# [num_tokens, hidden_size]
last_hidden_states: torch.Tensor,
# num_layers x [num_tokens, hidden_size]
aux_hidden_states: list[torch.Tensor] | None,
# [num_reqs]
num_sampled: torch.Tensor,
# [num_reqs]
num_rejected: torch.Tensor,
# [max_num_reqs]
last_sampled: torch.Tensor,
# [max_num_reqs]
next_prefill_tokens: torch.Tensor,
# [max_num_reqs]
temperature: torch.Tensor,
# [max_num_reqs]
seeds: torch.Tensor,
dp_sync_state: DPSyncState | None = None,
dummy_run: bool = False,
skip_attn_for_dummy_run: bool = False,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
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
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 + num_speculative_tokens, self.max_model_len
)
# NOTE(woosuk): To avoid CPU-GPU synchronization without CPU knowing the
# number of rejected tokens, we maintain the size of input_ids and
# hidden_states the same as the target model's. This means, we pad each
# request's query length to include any rejected positions. By doing so,
# we can also reuse the attention metadata (e.g., query_start_loc,
# seq_lens) of the target model.
if aux_hidden_states:
assert self.method == "eagle3"
hidden_states = self.model.combine_hidden_states(
torch.cat(aux_hidden_states, dim=-1)
)
else:
hidden_states = last_hidden_states
self._copy_request_inputs(
num_reqs,
input_batch.idx_mapping,
temperature,
seeds,
dummy_run=dummy_run,
)
# Get the input ids and last token indices for the speculator.
prepare_prefill_inputs(
self.last_token_indices,
self.current_draft_step,
self.input_buffers,
input_batch,
num_sampled,
num_rejected,
last_sampled,
next_prefill_tokens,
self.max_num_reqs,
)
if self.pcp_manager is not None:
self.pcp_manager.prepare_draft_prefill(
input_batch, self.input_buffers.input_ids[:num_tokens_padded]
)
prefill = self.pcp_manager.draft_prefill_batch
if prefill is not None:
num_tokens = prefill.num_tokens
num_tokens_padded = prefill.num_tokens_after_padding
self.hidden_states[:num_tokens_padded].copy_(hidden_states)
# When all requests are decoding (no true prefills), each has
# num_speculative_steps + 1 tokens, enabling FULL graph replay.
uniform_token_count = get_uniform_decode_token_count(
num_reqs,
# Use the actual number of tokens without padding added by
# the target model during FULL cudagraph.
num_tokens,
max_query_len,
input_batch.decode_graph_eligible,
)
prefill_batch_desc, prefill_batch_sync = dispatch_cg_and_sync_dp(
self.prefill_cudagraph_manager,
num_reqs,
num_tokens_padded,
uniform_token_count,
dp_size=self.dp_size,
dp_rank=self.dp_rank,
max_query_len=(
int(max_query_len) if input_batch.decode_graph_eligible else None
),
need_eager=is_profile,
dp_sync_state=dp_sync_state,
parallel_config=self.vllm_config.parallel_config,
)
num_tokens_across_dp = (
prefill_batch_sync.num_tokens_across_dp
if prefill_batch_sync is not None
else None
)
self._prepare_eplb_forward(num_tokens)
if not skip_attn_for_dummy_run:
attn_metadata, slot_mappings = self._build_drafter_attn_metadata(
input_batch,
attn_metadata,
slot_mappings,
prefill_batch_desc.cg_mode,
for_capture=dummy_run
and prefill_batch_desc.cg_mode == CUDAGraphMode.FULL,
)
self.on_prefill_begin(num_reqs)
if prefill_batch_desc.cg_mode == CUDAGraphMode.FULL:
# Replay the full graph for draft prefill.
assert self.prefill_cudagraph_manager is not None
self.prefill_cudagraph_manager.run_fullgraph(prefill_batch_desc)
else:
# The target model's attention metadata and slot mappings
# can directly be used for draft prefill, because of the
# identical batch shape and KV cache layout.
self._prefill(
num_reqs,
prefill_batch_desc.num_tokens,
attn_metadata,
slot_mappings,
num_tokens_across_dp=num_tokens_across_dp,
cudagraph_runtime_mode=prefill_batch_desc.cg_mode,
mm_inputs=mm_inputs,
skip_sample=num_speculative_tokens == 0,
)
self.on_prefill_end(num_reqs)
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(
input_batch.idx_mapping, num_reqs_padded=num_reqs
)
self._run_multi_step_decode(
input_batch,
num_rejected,
num_reqs,
dummy_run and skip_attn_for_dummy_run,
dp_sync_state,
input_batch.seq_lens_cpu_upper_bound,
is_profile,
num_speculative_tokens,
)
return self.draft_tokens[:num_reqs]
@torch.inference_mode()
def _run_model(
self,
num_tokens: int,
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,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
input_buffers: InputBatch | InputBuffers = self.input_buffers
is_padding = None
if self.pcp_manager is not None:
input_buffers, is_padding = self.pcp_manager.get_draft_input_buffers(
self.input_buffers, num_tokens
)
batch_descriptor = BatchDescriptor(num_tokens=num_tokens)
with set_forward_context(
attn_metadata,
self.vllm_config,
num_tokens=num_tokens,
cudagraph_runtime_mode=cudagraph_runtime_mode,
num_tokens_across_dp=num_tokens_across_dp,
slot_mapping=slot_mappings,
batch_descriptor=batch_descriptor,
is_padding=is_padding,
):
inputs_embeds = None
if self.supports_mm_inputs:
assert self.inputs_embeds is not None
# Merge multimodal embeddings with input ids.
mm_embeds, is_mm_embed = mm_inputs or (None, None)
num_input_tokens = (
is_mm_embed.shape[0] if is_mm_embed is not None else num_tokens
)
self.inputs_embeds[:num_input_tokens] = self.model.embed_input_ids(
input_buffers.input_ids[:num_input_tokens],
multimodal_embeddings=mm_embeds,
is_multimodal=is_mm_embed,
)
inputs_embeds = self.inputs_embeds[:num_tokens]
model_inputs = dict(
input_ids=input_buffers.input_ids[:num_tokens],
positions=input_buffers.positions[:num_tokens],
hidden_states=self.hidden_states[:num_tokens],
inputs_embeds=inputs_embeds,
)
if cudagraph_runtime_mode == CUDAGraphMode.PIECEWISE:
# Draft prefill with PIECEWISE cudagraph (compiled PW or breakable),
# chosen inside run_pw_graph.
assert self.prefill_cudagraph_manager is not None
ret_hidden_states = self.prefill_cudagraph_manager.run_pw_graph(
self.model, model_inputs
)
else:
# Eager (NONE): call the raw model directly.
ret_hidden_states = self.model(**model_inputs)
# Some MTP models declare a single-tensor contract but return
# (logits_hidden, feedback_hidden) for final-norm correctness.
if isinstance(ret_hidden_states, tuple):
last_hidden_states, hidden_states = ret_hidden_states
else:
last_hidden_states = ret_hidden_states
hidden_states = ret_hidden_states
return last_hidden_states, hidden_states
def _prefill(
self,
num_reqs: int,
num_tokens: int,
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,
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
skip_sample: bool = False,
) -> None:
last_token_indices = self.last_token_indices[:num_reqs]
positions = self.input_buffers.positions[last_token_indices]
# The output hidden state at position P (= positions) and the token id
# at P+1 are used to draft the token at P+2. Sampling keys a draw by the
# position before the sampled token, so the net adjustment is +1.
sample_src_positions = positions + 1
idx_mapping = self.idx_mapping[:num_reqs]
last_hidden_states, hidden_states = self._run_model(
num_tokens,
attn_metadata,
slot_mappings,
num_tokens_across_dp=num_tokens_across_dp,
cudagraph_runtime_mode=cudagraph_runtime_mode,
mm_inputs=mm_inputs,
)
if self.pcp_manager is not None:
last_hidden_states, hidden_states = self.pcp_manager.restore_draft_prefill(
last_hidden_states, hidden_states
)
if skip_sample:
# No drafts are needed; this pass only keeps the drafter KV in sync.
return
sample_hidden_states = last_hidden_states[last_token_indices]
self.draft_tokens[:num_reqs, 0] = self.sample_draft(
sample_hidden_states,
sample_src_positions,
idx_mapping,
self.temperature,
self.seeds,
self.current_draft_step,
self.draft_logits,
)
if last_hidden_states is hidden_states:
self.hidden_states[:num_reqs] = sample_hidden_states
else:
self.hidden_states[:num_reqs] = hidden_states[last_token_indices]
self.input_buffers.positions[:num_reqs] = positions
self.sample_src_positions[:num_reqs] = sample_src_positions
def _decode(
self,
num_reqs: int,
num_tokens_padded: int,
attn_metadata: dict[str, Any] | None,
slot_mappings: dict[str, torch.Tensor] | None,
num_tokens_across_dp: torch.Tensor | None,
cudagraph_runtime_mode: CUDAGraphMode,
num_speculative_steps: int,
) -> None:
self._prepare_eplb_forward(num_reqs)
idx_mapping = self.idx_mapping[:num_reqs]
# Run the draft model forward pass.
last_hidden_states, hidden_states = self._run_model(
num_tokens_padded,
attn_metadata,
slot_mappings,
num_tokens_across_dp,
cudagraph_runtime_mode,
)
# Sample the draft tokens.
sample_hidden_states = last_hidden_states[:num_reqs]
sample_src_positions = self.sample_src_positions[:num_reqs]
draft_tokens = self.sample_draft(
sample_hidden_states,
sample_src_positions,
idx_mapping,
self.temperature,
self.seeds,
self.current_draft_step,
self.draft_logits,
)
# Update the inputs for the next step.
update_draft_inputs(
draft_tokens,
self.current_draft_step,
hidden_states,
self.draft_tokens,
self.hidden_states,
self.input_buffers,
self.sample_src_positions,
num_reqs,
self.max_model_len_gpu,
num_speculative_steps,
advance_draft_positions=self.advance_draft_positions,
)