[Feat][Spec Decode] DFlash (#36847)
Signed-off-by: Benjamin Chislett <bchislett@nvidia.com>
This commit is contained in:
@@ -0,0 +1,282 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from typing_extensions import override
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.forward_context import set_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.triton_utils import triton
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.spec_decode.eagle import SpecDecodeBaseProposer
|
||||
from vllm.v1.spec_decode.utils import copy_and_expand_dflash_inputs_kernel
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class DFlashProposer(SpecDecodeBaseProposer):
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
runner=None,
|
||||
):
|
||||
assert vllm_config.speculative_config is not None
|
||||
assert vllm_config.speculative_config.method == "dflash"
|
||||
super().__init__(
|
||||
vllm_config=vllm_config,
|
||||
device=device,
|
||||
pass_hidden_states_to_model=True,
|
||||
runner=runner,
|
||||
)
|
||||
|
||||
# Only next_token_ids and mask tokens are query tokens, all other context is K/V
|
||||
self.max_query_tokens = self.max_batch_size * (1 + self.num_speculative_tokens)
|
||||
# Positions covers both context states + query states
|
||||
self.max_positions = self.max_num_tokens + self.max_query_tokens
|
||||
|
||||
# Separate context buffers to keep query buffer addresses stable for CUDA graphs
|
||||
self._context_slot_mapping_buffer = torch.zeros(
|
||||
self.max_num_tokens,
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
self._slot_mapping_buffer = torch.zeros(
|
||||
self.max_query_tokens,
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
self._context_positions_buffer = torch.zeros(
|
||||
self.max_num_tokens,
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
self.positions = torch.zeros(
|
||||
self.max_query_tokens,
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
|
||||
self.arange = torch.arange(
|
||||
self.max_positions + 1, device=device, dtype=torch.int32
|
||||
)
|
||||
|
||||
# For DFlash we use the input embeddings to embed the mask token
|
||||
self.parallel_drafting_hidden_state_tensor = None
|
||||
|
||||
@override
|
||||
def _raise_if_multimodal(self):
|
||||
# Override to allow multimodal inputs since DFlash supports Qwen3.5 models
|
||||
# Support for multimodal inputs has not been tested.
|
||||
pass
|
||||
|
||||
@override
|
||||
def set_inputs_first_pass(
|
||||
self,
|
||||
target_token_ids: torch.Tensor,
|
||||
next_token_ids: torch.Tensor,
|
||||
target_positions: torch.Tensor,
|
||||
target_hidden_states: torch.Tensor,
|
||||
token_indices_to_sample: torch.Tensor | None,
|
||||
cad: CommonAttentionMetadata,
|
||||
num_rejected_tokens_gpu: torch.Tensor | None,
|
||||
) -> tuple[int, torch.Tensor, CommonAttentionMetadata]:
|
||||
# DFlash cross-attention: context K/V from target hidden states,
|
||||
# Q from query embeddings (bonus + mask tokens).
|
||||
batch_size = cad.batch_size()
|
||||
num_context = target_token_ids.shape[0]
|
||||
num_query_per_req = 1 + self.num_speculative_tokens
|
||||
num_query_total = batch_size * num_query_per_req
|
||||
|
||||
# Store for build_model_inputs_first_pass to use
|
||||
self._dflash_num_context = num_context
|
||||
|
||||
# We don't need to copy into a buffer here since the context preprocessing
|
||||
# does not run in a CUDA graph
|
||||
self._dflash_hidden_states = target_hidden_states
|
||||
|
||||
token_indices_to_sample = torch.empty(
|
||||
batch_size * self.num_speculative_tokens,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
# Launch fused triton kernel for input_ids, positions, slot_mapping,
|
||||
# and token_indices_to_sample
|
||||
max_ctx_per_req = cad.max_query_len
|
||||
max_tokens_per_req = max_ctx_per_req + num_query_per_req
|
||||
BLOCK_SIZE = min(256, triton.next_power_of_2(max_tokens_per_req))
|
||||
num_blocks = triton.cdiv(max_tokens_per_req, BLOCK_SIZE)
|
||||
grid = (batch_size, num_blocks)
|
||||
|
||||
has_num_rejected = num_rejected_tokens_gpu is not None
|
||||
copy_and_expand_dflash_inputs_kernel[grid](
|
||||
# Inputs
|
||||
next_token_ids_ptr=next_token_ids,
|
||||
target_positions_ptr=target_positions,
|
||||
# Outputs
|
||||
out_input_ids_ptr=self.input_ids,
|
||||
out_context_positions_ptr=self._context_positions_buffer,
|
||||
out_query_positions_ptr=self.positions,
|
||||
out_context_slot_mapping_ptr=self._context_slot_mapping_buffer,
|
||||
out_query_slot_mapping_ptr=self._slot_mapping_buffer,
|
||||
out_token_indices_ptr=token_indices_to_sample,
|
||||
# Block table
|
||||
block_table_ptr=cad.block_table_tensor,
|
||||
block_table_stride=cad.block_table_tensor.stride(0),
|
||||
# Metadata
|
||||
query_start_loc_ptr=cad.query_start_loc,
|
||||
num_rejected_tokens_ptr=(
|
||||
num_rejected_tokens_gpu if has_num_rejected else 0
|
||||
),
|
||||
# Scalars
|
||||
parallel_drafting_token_id=self.parallel_drafting_token_id,
|
||||
block_size=self.block_size,
|
||||
num_query_per_req=num_query_per_req,
|
||||
num_speculative_tokens=self.num_speculative_tokens,
|
||||
total_input_tokens=num_context,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
HAS_NUM_REJECTED=has_num_rejected,
|
||||
)
|
||||
|
||||
query_slot_mapping = self._slot_mapping_buffer[:num_query_total]
|
||||
new_query_start_loc = self.arange[: batch_size + 1] * num_query_per_req
|
||||
|
||||
# In padded mode, cad.seq_lens includes rejected tokens. Subtract
|
||||
# them so attention only sees the valid prefix of context states.
|
||||
effective_seq_lens = cad.seq_lens
|
||||
if has_num_rejected:
|
||||
effective_seq_lens = effective_seq_lens - num_rejected_tokens_gpu
|
||||
|
||||
new_cad = CommonAttentionMetadata(
|
||||
query_start_loc=new_query_start_loc,
|
||||
seq_lens=effective_seq_lens + num_query_per_req,
|
||||
query_start_loc_cpu=(
|
||||
torch.from_numpy(self.token_arange_np[: batch_size + 1]).clone()
|
||||
* num_query_per_req
|
||||
),
|
||||
_seq_lens_cpu=None,
|
||||
_num_computed_tokens_cpu=None,
|
||||
num_reqs=cad.num_reqs,
|
||||
num_actual_tokens=num_query_total,
|
||||
max_query_len=num_query_per_req,
|
||||
max_seq_len=cad.max_seq_len + num_query_per_req,
|
||||
block_table_tensor=cad.block_table_tensor,
|
||||
slot_mapping=query_slot_mapping,
|
||||
causal=False, # Non-causal attention is required for DFlash
|
||||
)
|
||||
|
||||
return num_query_total, token_indices_to_sample, new_cad
|
||||
|
||||
@override
|
||||
@torch.inference_mode()
|
||||
def dummy_run(
|
||||
self,
|
||||
num_tokens: int,
|
||||
use_cudagraphs: bool = True,
|
||||
is_graph_capturing: bool = False,
|
||||
slot_mappings: dict[str, torch.Tensor] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Key differences to default dummy_run:
|
||||
- Only one forward pass due to parallel drafting
|
||||
- DFlash uses context states as unpadded metadata, so hidden_states will
|
||||
use the unpadded num_tokens instead of num_input_tokens
|
||||
- max_query_tokens is quite small, DFlash only sees spec tokens as queries
|
||||
- Multimodal inputs are not currently supported
|
||||
"""
|
||||
num_query_tokens = min(num_tokens, self.max_query_tokens)
|
||||
cudagraph_runtime_mode, num_input_tokens, num_tokens_across_dp = (
|
||||
self._determine_batch_execution_and_padding(
|
||||
num_query_tokens, use_cudagraphs=use_cudagraphs
|
||||
)
|
||||
)
|
||||
|
||||
# Slot mapping sized to num_input_tokens (query only), matching
|
||||
# the K/V tensor size from the model forward. Context KVs are
|
||||
# pre-inserted separately and don't flow through the model.
|
||||
if (
|
||||
self._draft_attn_layer_names
|
||||
and slot_mappings is not None
|
||||
and next(iter(self._draft_attn_layer_names)) in slot_mappings
|
||||
):
|
||||
slot_mapping_dict = self._get_slot_mapping(num_input_tokens)
|
||||
else:
|
||||
slot_mapping_dict = slot_mappings or {}
|
||||
|
||||
# Context and query positions use separate buffers; no copy needed.
|
||||
context_positions = self._context_positions_buffer[:num_tokens]
|
||||
# Context states will be passed directly to the precomputation without
|
||||
# going through the buffer, since no CUDA graph is used for the precomputation.
|
||||
# For the dummy run, we use the dummy buffer.
|
||||
context_states = self.hidden_states[:num_tokens]
|
||||
|
||||
# Run the KV projection (GEMM + norms + RoPE) for memory profiling,
|
||||
self.model.precompute_and_store_context_kv(context_states, context_positions)
|
||||
with set_forward_context(
|
||||
None,
|
||||
self.vllm_config,
|
||||
num_tokens=num_input_tokens,
|
||||
num_tokens_across_dp=num_tokens_across_dp,
|
||||
cudagraph_runtime_mode=cudagraph_runtime_mode,
|
||||
slot_mapping=slot_mapping_dict,
|
||||
):
|
||||
self.model(
|
||||
input_ids=self.input_ids[:num_input_tokens],
|
||||
positions=self._get_positions(num_input_tokens),
|
||||
inputs_embeds=None,
|
||||
)
|
||||
|
||||
@override
|
||||
def build_model_inputs_first_pass(
|
||||
self,
|
||||
num_tokens: int,
|
||||
num_input_tokens: int,
|
||||
mm_embed_inputs: tuple[list[torch.Tensor], torch.Tensor] | None,
|
||||
) -> tuple[dict[str, Any], int]:
|
||||
# Context and query positions/slots were written to separate
|
||||
# buffers by the kernel — no copy needed.
|
||||
num_context = self._dflash_num_context
|
||||
|
||||
# Pre-insert context KVs directly into cache
|
||||
self.model.precompute_and_store_context_kv(
|
||||
self._dflash_hidden_states, # Shape is already [num_context, hidden_size]
|
||||
self._context_positions_buffer[:num_context],
|
||||
self._context_slot_mapping_buffer[:num_context],
|
||||
)
|
||||
return (
|
||||
dict(
|
||||
input_ids=self.input_ids[:num_input_tokens],
|
||||
positions=self._get_positions(num_input_tokens),
|
||||
inputs_embeds=None,
|
||||
),
|
||||
num_input_tokens,
|
||||
)
|
||||
|
||||
@override
|
||||
def build_per_layer_attn_metadata(
|
||||
self, cad: CommonAttentionMetadata, draft_index: int = 0
|
||||
) -> dict[str, object]:
|
||||
per_layer_attention_metadata = super().build_per_layer_attn_metadata(
|
||||
cad, draft_index
|
||||
)
|
||||
for layer_name, attn_metadata in per_layer_attention_metadata.items():
|
||||
assert getattr(attn_metadata, "causal", None) is False, (
|
||||
f"Attention metadata for layer {layer_name} does not have"
|
||||
" non-causal support, which is required for DFlash."
|
||||
" Consider using a different attention backend, such as FlashAttention."
|
||||
)
|
||||
return per_layer_attention_metadata
|
||||
|
||||
@override
|
||||
def _get_eagle3_use_aux_hidden_state_from_config(self):
|
||||
use_aux_hidden_state = True
|
||||
dflash_config = getattr(
|
||||
self.draft_model_config.hf_config, "dflash_config", None
|
||||
)
|
||||
if dflash_config is not None:
|
||||
use_aux_hidden_state = dflash_config.get("use_aux_hidden_state", True)
|
||||
return use_aux_hidden_state
|
||||
+119
-72
@@ -2,7 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import ast
|
||||
from importlib.util import find_spec
|
||||
from typing import cast
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -23,6 +23,7 @@ from vllm.model_executor.models import supports_multimodal
|
||||
from vllm.model_executor.models.deepseek_eagle3 import Eagle3DeepseekV2ForCausalLM
|
||||
from vllm.model_executor.models.interfaces import SupportsMultiModal
|
||||
from vllm.model_executor.models.llama_eagle3 import Eagle3LlamaForCausalLM
|
||||
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3ForCausalLM
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import triton
|
||||
@@ -83,13 +84,15 @@ class SpecDecodeBaseProposer:
|
||||
self.hidden_size = self.draft_model_config.get_hidden_size()
|
||||
self.inputs_embeds_size = self.draft_model_config.get_inputs_embeds_size()
|
||||
|
||||
# Unifying eagle, draft model, and parallel drafting support
|
||||
# Unifying eagle, draft model, and parallel drafting support.
|
||||
# DFlash always uses parallel drafting (all tokens in one pass),
|
||||
# but has an additional slot for the next_token_id (does not shift like EAGLE)
|
||||
self.parallel_drafting: bool = self.speculative_config.parallel_drafting
|
||||
self.extra_slots_per_request = (
|
||||
1 if not self.parallel_drafting else self.num_speculative_tokens
|
||||
)
|
||||
self.net_num_new_slots_per_request = self.extra_slots_per_request - (
|
||||
1 if self.pass_hidden_states_to_model else 0
|
||||
1 if (self.pass_hidden_states_to_model and self.method != "dflash") else 0
|
||||
)
|
||||
self.needs_extra_input_slots = self.net_num_new_slots_per_request > 0
|
||||
|
||||
@@ -101,10 +104,14 @@ class SpecDecodeBaseProposer:
|
||||
self.speculative_config.use_local_argmax_reduction
|
||||
)
|
||||
|
||||
max_batch_size = vllm_config.scheduler_config.max_num_seqs
|
||||
self.max_batch_size = vllm_config.scheduler_config.max_num_seqs
|
||||
self.max_num_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self.token_arange_np = np.arange(self.max_num_tokens)
|
||||
|
||||
# Can be specialized by methods like DFlash to reduce the limit
|
||||
self.max_query_tokens = self.max_num_tokens
|
||||
self.max_positions = self.max_num_tokens
|
||||
|
||||
# Multi-modal data support
|
||||
self.mm_registry = MULTIMODAL_REGISTRY
|
||||
self.supports_mm_inputs = self.mm_registry.supports_multimodal_inputs(
|
||||
@@ -146,18 +153,20 @@ class SpecDecodeBaseProposer:
|
||||
# 1D-RoPE.
|
||||
# See page 5 of https://arxiv.org/abs/2409.12191
|
||||
self.mrope_positions = torch.zeros(
|
||||
(3, self.max_num_tokens + 1), dtype=torch.int64, device=device
|
||||
(3, self.max_positions + 1), dtype=torch.int64, device=device
|
||||
)
|
||||
elif self.uses_xdrope_dim > 0 and self.draft_uses_xdrope_dim > 0:
|
||||
self.xdrope_positions = torch.zeros(
|
||||
(self.uses_xdrope_dim, self.max_num_tokens + 1),
|
||||
(self.uses_xdrope_dim, self.max_positions + 1),
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
else:
|
||||
# RoPE need (max_num_tokens,)
|
||||
self.positions = torch.zeros(
|
||||
self.max_num_tokens, dtype=torch.int64, device=device
|
||||
self.max_positions,
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
self.hidden_states = torch.zeros(
|
||||
(self.max_num_tokens, self.hidden_size), dtype=self.dtype, device=device
|
||||
@@ -168,7 +177,7 @@ class SpecDecodeBaseProposer:
|
||||
|
||||
# We need +1 here because the arange is used to set query_start_loc,
|
||||
# which has one more element than batch_size.
|
||||
max_num_slots_for_arange = max(max_batch_size + 1, self.max_num_tokens)
|
||||
max_num_slots_for_arange = max(self.max_batch_size + 1, self.max_num_tokens)
|
||||
self.arange = torch.arange(
|
||||
max_num_slots_for_arange, device=device, dtype=torch.int32
|
||||
)
|
||||
@@ -200,7 +209,7 @@ class SpecDecodeBaseProposer:
|
||||
)
|
||||
|
||||
self.backup_next_token_ids = CpuGpuBuffer(
|
||||
max_batch_size,
|
||||
self.max_batch_size,
|
||||
dtype=torch.int32,
|
||||
pin_memory=is_pin_memory_available(),
|
||||
device=device,
|
||||
@@ -208,7 +217,9 @@ class SpecDecodeBaseProposer:
|
||||
)
|
||||
|
||||
self._slot_mapping_buffer = torch.zeros(
|
||||
self.max_num_tokens, dtype=torch.int64, device=device
|
||||
self.max_positions,
|
||||
dtype=torch.int64,
|
||||
device=device,
|
||||
)
|
||||
|
||||
# Determine allowed attention backends once during initialization.
|
||||
@@ -275,7 +286,7 @@ class SpecDecodeBaseProposer:
|
||||
# Precompute draft position offsets in flattened tree.
|
||||
self.tree_draft_pos_offsets = torch.arange(
|
||||
1, len(self.tree_choices) + 1, device=device, dtype=torch.int32
|
||||
).repeat(max_batch_size, 1)
|
||||
).repeat(self.max_batch_size, 1)
|
||||
|
||||
def _raise_if_padded_drafter_batch_disabled(self):
|
||||
if self.speculative_config.disable_padded_drafter_batch:
|
||||
@@ -305,14 +316,19 @@ class SpecDecodeBaseProposer:
|
||||
# for those masked slots.
|
||||
|
||||
model_hf_config = self.draft_model_config.hf_config
|
||||
if hasattr(model_hf_config, "pard_token"):
|
||||
# DFlash stores mask_token_id in dflash_config
|
||||
dflash_config = getattr(model_hf_config, "dflash_config", None)
|
||||
if dflash_config and "mask_token_id" in dflash_config:
|
||||
self.parallel_drafting_token_id = dflash_config["mask_token_id"]
|
||||
elif hasattr(model_hf_config, "pard_token"):
|
||||
self.parallel_drafting_token_id = model_hf_config.pard_token
|
||||
elif hasattr(model_hf_config, "ptd_token_id"):
|
||||
self.parallel_drafting_token_id = model_hf_config.ptd_token_id
|
||||
else:
|
||||
raise ValueError(
|
||||
"For parallel drafting, the draft model config must have "
|
||||
"`pard_token` or `ptd_token_id` specified in its config.json."
|
||||
"`pard_token`, `ptd_token_id`, or "
|
||||
"`dflash_config.mask_token_id` specified in its config.json."
|
||||
)
|
||||
|
||||
if self.pass_hidden_states_to_model:
|
||||
@@ -402,9 +418,14 @@ class SpecDecodeBaseProposer:
|
||||
) -> torch.Tensor:
|
||||
batch_size = common_attn_metadata.batch_size()
|
||||
|
||||
if self.method == "eagle3":
|
||||
if self.method in ("eagle3", "dflash"):
|
||||
assert isinstance(
|
||||
self.model, (Eagle3LlamaForCausalLM, Eagle3DeepseekV2ForCausalLM)
|
||||
self.model,
|
||||
(
|
||||
Eagle3LlamaForCausalLM,
|
||||
Eagle3DeepseekV2ForCausalLM,
|
||||
DFlashQwen3ForCausalLM,
|
||||
),
|
||||
)
|
||||
target_hidden_states = self.model.combine_hidden_states(
|
||||
target_hidden_states
|
||||
@@ -423,40 +444,17 @@ class SpecDecodeBaseProposer:
|
||||
)
|
||||
)
|
||||
|
||||
per_layer_attn_metadata: dict[str, object] = {}
|
||||
for attn_group in self.draft_attn_groups:
|
||||
attn_metadata = attn_group.get_metadata_builder().build_for_drafting(
|
||||
common_attn_metadata=common_attn_metadata, draft_index=0
|
||||
)
|
||||
for layer_name in attn_group.layer_names:
|
||||
per_layer_attn_metadata[layer_name] = attn_metadata
|
||||
per_layer_attn_metadata = self.build_per_layer_attn_metadata(
|
||||
common_attn_metadata
|
||||
)
|
||||
|
||||
cudagraph_runtime_mode, num_input_tokens, num_tokens_across_dp = (
|
||||
self._determine_batch_execution_and_padding(num_tokens)
|
||||
)
|
||||
|
||||
if self.supports_mm_inputs:
|
||||
mm_embeds, is_mm_embed = mm_embed_inputs or (None, None)
|
||||
|
||||
self.inputs_embeds[:num_tokens] = self.model.embed_input_ids(
|
||||
self.input_ids[:num_tokens],
|
||||
multimodal_embeddings=mm_embeds,
|
||||
is_multimodal=is_mm_embed,
|
||||
)
|
||||
|
||||
input_ids = None
|
||||
inputs_embeds = self.inputs_embeds[:num_input_tokens]
|
||||
else:
|
||||
input_ids = self.input_ids[:num_input_tokens]
|
||||
inputs_embeds = None
|
||||
|
||||
model_kwargs = {
|
||||
"input_ids": input_ids,
|
||||
"positions": self._get_positions(num_input_tokens),
|
||||
"inputs_embeds": inputs_embeds,
|
||||
}
|
||||
if self.pass_hidden_states_to_model:
|
||||
model_kwargs["hidden_states"] = self.hidden_states[:num_input_tokens]
|
||||
model_kwargs, slot_mapping_size = self.build_model_inputs_first_pass(
|
||||
num_tokens, num_input_tokens, mm_embed_inputs
|
||||
)
|
||||
|
||||
with set_forward_context(
|
||||
per_layer_attn_metadata,
|
||||
@@ -465,7 +463,7 @@ class SpecDecodeBaseProposer:
|
||||
num_tokens_across_dp=num_tokens_across_dp,
|
||||
cudagraph_runtime_mode=cudagraph_runtime_mode,
|
||||
slot_mapping=self._get_slot_mapping(
|
||||
num_input_tokens, common_attn_metadata.slot_mapping
|
||||
slot_mapping_size, common_attn_metadata.slot_mapping
|
||||
),
|
||||
):
|
||||
ret_hidden_states = self.model(**model_kwargs)
|
||||
@@ -488,7 +486,10 @@ class SpecDecodeBaseProposer:
|
||||
positions = self.positions[token_indices_to_sample]
|
||||
hidden_states = hidden_states[token_indices_to_sample]
|
||||
|
||||
if isinstance(attn_metadata, TreeAttentionMetadata):
|
||||
if any(
|
||||
isinstance(attn_metadata, TreeAttentionMetadata)
|
||||
for attn_metadata in per_layer_attn_metadata.values()
|
||||
):
|
||||
# Draft using tree attention - requires full logits for top-k
|
||||
logits = self.model.compute_logits(sample_hidden_states)
|
||||
draft_token_ids_list = self.propose_tree(
|
||||
@@ -504,15 +505,16 @@ class SpecDecodeBaseProposer:
|
||||
|
||||
draft_token_ids = self._greedy_sample(sample_hidden_states)
|
||||
|
||||
if self.allowed_attn_types is not None and not isinstance(
|
||||
attn_metadata, self.allowed_attn_types
|
||||
):
|
||||
raise ValueError(
|
||||
f"Unsupported attention metadata type for speculative "
|
||||
"decoding with num_speculative_tokens > 1: "
|
||||
f"{type(attn_metadata)}. Supported types are: "
|
||||
f"{self.allowed_attn_types}"
|
||||
)
|
||||
for attn_metadata in per_layer_attn_metadata.values():
|
||||
if self.allowed_attn_types is not None and not isinstance(
|
||||
attn_metadata, self.allowed_attn_types
|
||||
):
|
||||
raise ValueError(
|
||||
f"Unsupported attention metadata type for speculative "
|
||||
"decoding with num_speculative_tokens > 1: "
|
||||
f"{type(attn_metadata)}. Supported types are: "
|
||||
f"{self.allowed_attn_types}"
|
||||
)
|
||||
|
||||
# Generate the remaining draft tokens.
|
||||
draft_token_ids_list = [draft_token_ids]
|
||||
@@ -593,13 +595,9 @@ class SpecDecodeBaseProposer:
|
||||
common_attn_metadata._num_computed_tokens_cpu += 1
|
||||
|
||||
# Rebuild attention metadata
|
||||
for attn_group in self.draft_attn_groups:
|
||||
attn_metadata = attn_group.get_metadata_builder().build_for_drafting(
|
||||
common_attn_metadata=common_attn_metadata,
|
||||
draft_index=token_index + 1,
|
||||
)
|
||||
for layer_name in attn_group.layer_names:
|
||||
per_layer_attn_metadata[layer_name] = attn_metadata
|
||||
per_layer_attn_metadata = self.build_per_layer_attn_metadata(
|
||||
common_attn_metadata, draft_index=token_index + 1
|
||||
)
|
||||
|
||||
# copy inputs to buffer for cudagraph
|
||||
self.input_ids[:batch_size] = input_ids
|
||||
@@ -780,8 +778,51 @@ class SpecDecodeBaseProposer:
|
||||
|
||||
return total_num_output_tokens, token_indices_to_sample, new_cad
|
||||
|
||||
def build_model_inputs_first_pass(
|
||||
self,
|
||||
num_tokens: int,
|
||||
num_input_tokens: int,
|
||||
mm_embed_inputs: tuple[list[torch.Tensor], torch.Tensor] | None,
|
||||
) -> tuple[dict[str, Any], int]:
|
||||
if self.supports_mm_inputs:
|
||||
mm_embeds, is_mm_embed = mm_embed_inputs or (None, None)
|
||||
|
||||
self.inputs_embeds[:num_tokens] = self.model.embed_input_ids(
|
||||
self.input_ids[:num_tokens],
|
||||
multimodal_embeddings=mm_embeds,
|
||||
is_multimodal=is_mm_embed,
|
||||
)
|
||||
|
||||
input_ids = None
|
||||
inputs_embeds = self.inputs_embeds[:num_input_tokens]
|
||||
else:
|
||||
input_ids = self.input_ids[:num_input_tokens]
|
||||
inputs_embeds = None
|
||||
|
||||
model_kwargs = {
|
||||
"input_ids": input_ids,
|
||||
"positions": self._get_positions(num_input_tokens),
|
||||
"inputs_embeds": inputs_embeds,
|
||||
}
|
||||
if self.pass_hidden_states_to_model:
|
||||
model_kwargs["hidden_states"] = self.hidden_states[:num_input_tokens]
|
||||
|
||||
return model_kwargs, num_input_tokens
|
||||
|
||||
def build_per_layer_attn_metadata(
|
||||
self, common_attn_metadata: CommonAttentionMetadata, draft_index: int = 0
|
||||
) -> dict[str, object]:
|
||||
per_layer_attn_metadata: dict[str, object] = {}
|
||||
for attn_group in self.draft_attn_groups:
|
||||
attn_metadata = attn_group.get_metadata_builder().build_for_drafting(
|
||||
common_attn_metadata=common_attn_metadata, draft_index=draft_index
|
||||
)
|
||||
for layer_name in attn_group.layer_names:
|
||||
per_layer_attn_metadata[layer_name] = attn_metadata
|
||||
return per_layer_attn_metadata
|
||||
|
||||
def model_returns_tuple(self) -> bool:
|
||||
return self.method not in ("mtp", "draft_model")
|
||||
return self.method not in ("mtp", "draft_model", "dflash")
|
||||
|
||||
def prepare_next_token_ids_cpu(
|
||||
self,
|
||||
@@ -1310,15 +1351,20 @@ class SpecDecodeBaseProposer:
|
||||
self._maybe_share_embeddings(target_language_model)
|
||||
self._maybe_share_lm_head(target_language_model)
|
||||
|
||||
if self.parallel_drafting and self.pass_hidden_states_to_model:
|
||||
assert self.parallel_drafting_hidden_state_tensor is not None
|
||||
self.parallel_drafting_hidden_state_tensor.copy_(
|
||||
self.model.combine_hidden_states(
|
||||
self.model.mask_hidden.view(3 * self.hidden_size)
|
||||
if (
|
||||
self.parallel_drafting
|
||||
and self.pass_hidden_states_to_model
|
||||
and self.parallel_drafting_hidden_state_tensor is not None
|
||||
):
|
||||
flat_mask = self.model.mask_hidden.view(-1)
|
||||
if self.eagle3_use_aux_hidden_state:
|
||||
# EAGLE3: mask_hidden stores all aux hidden states,
|
||||
# project through combine_hidden_states
|
||||
self.parallel_drafting_hidden_state_tensor.copy_(
|
||||
self.model.combine_hidden_states(flat_mask)
|
||||
)
|
||||
if self.eagle3_use_aux_hidden_state
|
||||
else self.model.mask_hidden.view(self.hidden_size)
|
||||
)
|
||||
else:
|
||||
self.parallel_drafting_hidden_state_tensor.copy_(flat_mask)
|
||||
|
||||
def _maybe_share_embeddings(self, target_language_model: nn.Module) -> None:
|
||||
"""
|
||||
@@ -1493,8 +1539,9 @@ class SpecDecodeBaseProposer:
|
||||
) -> None:
|
||||
# FIXME: when using tree-based specdec, adjust number of forward-passes
|
||||
# according to the depth of the tree.
|
||||
only_one_forward_pass = is_graph_capturing or self.parallel_drafting
|
||||
for fwd_idx in range(
|
||||
self.num_speculative_tokens if not is_graph_capturing else 1
|
||||
1 if only_one_forward_pass else self.num_speculative_tokens
|
||||
):
|
||||
if fwd_idx <= 1:
|
||||
cudagraph_runtime_mode, num_input_tokens, num_tokens_across_dp = (
|
||||
|
||||
@@ -441,6 +441,114 @@ def copy_and_expand_eagle_inputs_kernel(
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def copy_and_expand_dflash_inputs_kernel(
|
||||
# Inputs
|
||||
next_token_ids_ptr, # [num_reqs]
|
||||
target_positions_ptr, # [num_context]
|
||||
# Outputs
|
||||
out_input_ids_ptr, # [num_query_total] (output)
|
||||
out_context_positions_ptr, # [num_context] (output)
|
||||
out_query_positions_ptr, # [num_query_total] (output)
|
||||
out_context_slot_mapping_ptr, # [num_context] (output)
|
||||
out_query_slot_mapping_ptr, # [num_query_total] (output)
|
||||
out_token_indices_ptr, # [num_reqs * num_speculative_tokens] (output)
|
||||
# Block table
|
||||
block_table_ptr, # [max_reqs, max_blocks]
|
||||
block_table_stride, # stride of block_table dim 0 (in elements)
|
||||
# Metadata
|
||||
query_start_loc_ptr, # [num_reqs + 1]
|
||||
num_rejected_tokens_ptr, # [num_reqs] or null (0) when not padded
|
||||
# Scalars
|
||||
parallel_drafting_token_id, # tl.int32
|
||||
block_size, # tl.int32
|
||||
num_query_per_req, # tl.int32
|
||||
num_speculative_tokens, # tl.int32
|
||||
total_input_tokens, # tl.int32
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
HAS_NUM_REJECTED: tl.constexpr = False,
|
||||
):
|
||||
"""
|
||||
Fused kernel for DFlash first-pass input setup.
|
||||
|
||||
Per request, this kernel:
|
||||
1. Copies context positions from target_positions to
|
||||
out_context_positions.
|
||||
2. Computes query positions (last_target_pos + 1 + offset) and writes
|
||||
them to out_query_positions.
|
||||
3. Writes input_ids for query tokens: [next_token, mask, mask, ...].
|
||||
4. Computes slot_mapping for context and query positions into separate
|
||||
buffers via block_table lookup.
|
||||
5. Writes token_indices_to_sample for the mask (speculative) tokens.
|
||||
"""
|
||||
req_idx = tl.program_id(axis=0)
|
||||
block_idx = tl.program_id(axis=1)
|
||||
|
||||
# Load context token range for this request
|
||||
ctx_start = tl.load(query_start_loc_ptr + req_idx)
|
||||
ctx_end = tl.load(query_start_loc_ptr + req_idx + 1)
|
||||
num_ctx = ctx_end - ctx_start
|
||||
total_tokens = num_ctx + num_query_per_req
|
||||
|
||||
j = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
in_bounds = j < total_tokens
|
||||
is_ctx = j < num_ctx
|
||||
is_query = (~is_ctx) & in_bounds
|
||||
query_off = j - num_ctx # offset within query portion (0-indexed)
|
||||
|
||||
# --- Positions ---
|
||||
# Context: load from target_positions
|
||||
ctx_pos_idx = tl.minimum(ctx_start + j, total_input_tokens - 1)
|
||||
ctx_pos = tl.load(target_positions_ptr + ctx_pos_idx, mask=is_ctx, other=0)
|
||||
|
||||
# Query: last_valid_pos + 1 + query_off
|
||||
# In padded mode, ctx_end includes rejected tokens; use valid_ctx_end
|
||||
# to find the last accepted context position.
|
||||
if HAS_NUM_REJECTED:
|
||||
num_rejected = tl.load(num_rejected_tokens_ptr + req_idx)
|
||||
valid_ctx_end = ctx_end - num_rejected
|
||||
else:
|
||||
valid_ctx_end = ctx_end
|
||||
last_pos = tl.load(target_positions_ptr + valid_ctx_end - 1)
|
||||
query_pos = last_pos + 1 + query_off
|
||||
|
||||
positions = tl.where(is_ctx, ctx_pos, query_pos)
|
||||
|
||||
# Context and query positions go to separate buffers.
|
||||
ctx_pos_out = ctx_start + j
|
||||
tl.store(out_context_positions_ptr + ctx_pos_out, ctx_pos, mask=is_ctx)
|
||||
query_out = req_idx * num_query_per_req + query_off
|
||||
tl.store(out_query_positions_ptr + query_out, query_pos, mask=is_query)
|
||||
|
||||
# --- Slot mapping (block_table lookup for all positions) ---
|
||||
block_num = positions // block_size
|
||||
# # Clamp block_number to avoid OOB when position is at max
|
||||
block_num = tl.minimum(block_num, block_table_stride - 1)
|
||||
block_id = tl.load(
|
||||
block_table_ptr + req_idx * block_table_stride + block_num,
|
||||
mask=in_bounds,
|
||||
other=0,
|
||||
).to(tl.int64)
|
||||
slot = block_id * block_size + (positions % block_size)
|
||||
tl.store(out_context_slot_mapping_ptr + ctx_pos_out, slot, mask=is_ctx)
|
||||
tl.store(out_query_slot_mapping_ptr + query_out, slot, mask=is_query)
|
||||
|
||||
# --- Input IDs (query tokens only) ---
|
||||
bonus_token = tl.load(next_token_ids_ptr + req_idx)
|
||||
is_bonus = is_query & (query_off == 0)
|
||||
input_id = tl.where(is_bonus, bonus_token, parallel_drafting_token_id)
|
||||
tl.store(out_input_ids_ptr + query_out, input_id, mask=is_query)
|
||||
|
||||
# --- Token indices to sample (mask tokens, skip the bonus token) ---
|
||||
is_sample = is_query & (query_off > 0)
|
||||
sample_out_idx = req_idx * num_speculative_tokens + (query_off - 1)
|
||||
tl.store(
|
||||
out_token_indices_ptr + sample_out_idx,
|
||||
query_out,
|
||||
mask=is_sample,
|
||||
)
|
||||
|
||||
|
||||
@torch.compile(dynamic=True, backend=current_platform.simple_compile_backend)
|
||||
def update_num_computed_tokens_for_batch_change(
|
||||
num_computed_tokens: torch.Tensor,
|
||||
|
||||
Reference in New Issue
Block a user