[Core] Backport MRV2 DFlash base (#252)

Backport the isolated MRV2 DFlash base while retaining existing Eagle, MTP, and DDTree paths.

Audit:
- restored auxiliary projection dtype compatibility
- added missing SPDX header
- 10 focused DFlash tests passed
- changed-file pre-commit and diff checks passed
- exact merge tree verified against main ca2caa7d
- prior V100 batched RMSNorm evidence remains valid

Signed-off-by: yangzhuxinyzx <153831768+yangzhuxinyzx@users.noreply.github.com>
This commit is contained in:
yangzhuxinyzx authored and GitHub committed 2026-08-24 19:34:38 +08:00
1 parent ca2caa7d23
commit 933371faa7
24 files changed
+2217 -372

No files matched your search

+22 -5
View File
@@ -26,20 +26,25 @@ __global__ void rms_norm_kernel(
const int64_t input_stride_d4, // input.stride(-4)
const int64_t input_shape_d2, // input.size(-2)
const int64_t input_shape_d3, // input.size(-3)
const scalar_t* __restrict__ weight, // [hidden_size]
const scalar_t* __restrict__ weight, // [hidden_size] or
// [num_groups, hidden_size]
const int64_t weight_stride, // 0 or weight.stride(0)
const float epsilon, const int num_tokens, const int hidden_size) {
__shared__ float s_variance;
float variance = 0.0f;
const scalar_t* input_row;
const scalar_t* weight_row;
if constexpr (NUM_DIMS == 2) {
// 2D for layernorm normal case [batch_size, hidden]
input_row = input + blockIdx.x * input_stride_d2;
weight_row = weight + blockIdx.x * weight_stride;
} else if constexpr (NUM_DIMS == 3) {
// 3D for q/k norm [batch_size, num_heads, head_size]
int batch_idx = blockIdx.x / input_shape_d2;
int head_idx = blockIdx.x % input_shape_d2;
input_row =
input + batch_idx * input_stride_d3 + head_idx * input_stride_d2;
weight_row = weight + batch_idx * weight_stride;
} else if constexpr (NUM_DIMS == 4) {
// 4D for transformers model_impl qk norm [batch, seq, head, head_dim]
int batch_idx = blockIdx.x / (input_shape_d3 * input_shape_d2);
@@ -48,6 +53,7 @@ __global__ void rms_norm_kernel(
int head_idx = remaining % input_shape_d2;
input_row = input + batch_idx * input_stride_d4 +
seq_idx * input_stride_d3 + head_idx * input_stride_d2;
weight_row = weight + batch_idx * weight_stride;
}
auto vec_op = [&variance](const vec_n_t<scalar_t, VEC_SIZE>& vec) {
@@ -75,7 +81,7 @@ __global__ void rms_norm_kernel(
scalar_t* out_row = out + blockIdx.x * hidden_size;
auto* v_in = reinterpret_cast<const vec_n_t<scalar_t, VEC_SIZE>*>(input_row);
auto* v_w = reinterpret_cast<const vec_n_t<scalar_t, VEC_SIZE>*>(weight);
auto* v_w = reinterpret_cast<const vec_n_t<scalar_t, VEC_SIZE>*>(weight_row);
auto* v_out = reinterpret_cast<vec_n_t<scalar_t, VEC_SIZE>*>(out_row);
for (int i = threadIdx.x; i < hidden_size / VEC_SIZE; i += blockDim.x) {
vec_n_t<scalar_t, VEC_SIZE> dst;
@@ -291,7 +297,8 @@ __global__ void __launch_bounds__(kSm70GemmaLongPrefillThreads, 2)
void rms_norm(torch::stable::Tensor& out, // [..., hidden_size]
torch::stable::Tensor& input, // [..., hidden_size]
torch::stable::Tensor& weight, // [hidden_size]
torch::stable::Tensor& weight, // [hidden_size] or
// [num_groups, hidden_size]
double epsilon) {
STD_TORCH_CHECK(out.is_contiguous());
if (input.stride(-1) != 1) {
@@ -299,6 +306,16 @@ void rms_norm(torch::stable::Tensor& out, // [..., hidden_size]
}
STD_TORCH_CHECK(input.stride(-1) == 1);
STD_TORCH_CHECK(weight.is_contiguous());
int64_t weight_stride = 0;
if (weight.dim() == 1) {
STD_TORCH_CHECK(weight.size(0) == input.size(-1));
} else if (weight.dim() == 2) {
STD_TORCH_CHECK(weight.size(0) == input.size(0));
STD_TORCH_CHECK(weight.size(-1) == input.size(-1));
weight_stride = weight.stride(0);
} else {
STD_TORCH_CHECK(false, "rms_norm weight must be 1D or 2D");
}
int hidden_size = input.size(-1);
@@ -330,8 +347,8 @@ void rms_norm(torch::stable::Tensor& out, // [..., hidden_size]
out.mutable_data_ptr<scalar_t>(),
input.const_data_ptr<scalar_t>(), input_stride_d2,
input_stride_d3, input_stride_d4, input_shape_d2,
input_shape_d3, weight.const_data_ptr<scalar_t>(), epsilon,
num_tokens, hidden_size);
input_shape_d3, weight.const_data_ptr<scalar_t>(),
weight_stride, epsilon, num_tokens, hidden_size);
});
});
});
@@ -24,6 +24,27 @@ Goal:
sampling, and normal MoE architecture wherever possible.
- Do not carry unsafe quality-regressing routes into the main path.
## Active MRV2 DFlash2 campaign, 2026-08-20
- Integration base: `onecat/main@7aede2cf010d92815c9d7bff25867b4fa009b6cb`.
- Review chain starts at Draft PR #252 on
`codex/v100-dflash-mrv2-base-20260820-041115`.
- Frozen sources: vLLM MRV2 DFlash base `9842d7014502`, vLLM DFlash2 PR
`66e5414c6d75`, SGLang `c14312a66420`, and sglang-V100 `5526ef1c6a82`.
- Route contract: `method=dflash` is MRV2-only; the experimental V1 flat path
is removed. `method=dflash_ddtree` retains the existing V1 DDTree scheduler,
payload, verifier, and diagnostics through a narrow model compatibility
adapter. Existing Eagle and MTP implementations are not replaced.
- Selector top-K is checkpoint-owned and fixed at 16 for Qwen3.8 DFlash2;
official bring-up uses seven draft tokens (block size eight). Target sampling
top-k 20 is a separate sampling parameter.
- PR1 evidence so far: focused routing/config/DDTree tests pass, and the V1
DFlash input-preparation test passes on V100 after supplying the KV-group
initialization contract used in production. Two unrelated DDTree metadata
assertions fail identically on the frozen base and are recorded as pre-existing.
- No speed or acceptance claim is made until DFlash2 eager correctness, graph
equivalence, and same-stack dense-selector baselines pass.
Main implementation priority:
1. Add a decoupled SM70 TurboMind backend for AWQ and FP8 base GEMM.
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for the batched-weight RMS norm kernel.
The outermost input dimension selects the corresponding weight row. DFlash
uses this for its fused per-layer K normalization.
"""
import pytest
import torch
from vllm import _custom_ops as ops
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
pytestmark = pytest.mark.skipif(
not current_platform.is_cuda_alike(),
reason="rms_norm requires a CUDA/ROCm device",
)
@pytest.mark.parametrize(
"shape",
[
(28, 17, 128),
(1, 5, 2, 128),
(28, 13, 8, 128),
(6, 3, 4, 769),
],
)
@pytest.mark.parametrize("dtype", [torch.half, torch.bfloat16, torch.float])
@pytest.mark.parametrize("seed", [42])
@torch.inference_mode()
def test_rms_norm_matches_loop(
shape: tuple[int, ...], dtype: torch.dtype, seed: int
) -> None:
set_random_seed(seed)
torch.set_default_device("cuda")
num_rows, hidden = shape[0], shape[-1]
eps = 1e-6
x = torch.randn(*shape, dtype=dtype) * 0.1
weight = torch.randn(num_rows, hidden, dtype=dtype) * 0.1 + 1.0
out_ref = torch.empty_like(x)
for i in range(x.shape[0]):
ops.rms_norm(out_ref[i], x[i], weight[i], eps)
out = torch.empty_like(x)
ops.rms_norm(out, x, weight, eps)
torch.testing.assert_close(out, out_ref, atol=0, rtol=0)
@torch.inference_mode()
def test_rms_norm_validates_shapes() -> None:
torch.set_default_device("cuda")
x = torch.randn(4, 8, 128, dtype=torch.float)
out = torch.empty_like(x)
with pytest.raises(RuntimeError):
ops.rms_norm(out, x, torch.randn(3, 128), 1e-6)
with pytest.raises(RuntimeError):
ops.rms_norm(out, x, torch.randn(4, 64), 1e-6)
@@ -0,0 +1,199 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
from types import SimpleNamespace
import pytest
import torch
from vllm.config.speculative import SpeculativeConfig
from vllm.config.vllm import VllmConfig
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3ForCausalLM
from vllm.v1.spec_decode.dflash import DFlashProposer
from vllm.v1.spec_decode.llm_base_proposer import SpecDecodeBaseProposer
from vllm.v1.worker.gpu.attn_utils import build_attn_metadata
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
get_eagle3_aux_layers_from_config,
)
from vllm.v1.worker.gpu.spec_decode.utils import get_parallel_drafting_token_id
def _config(method: str, num_speculative_tokens: int = 7) -> SpeculativeConfig:
config = object.__new__(SpeculativeConfig)
config.method = method
config.num_speculative_tokens = num_speculative_tokens
config.parallel_drafting = True
return config
def test_dflash_and_ddtree_routes_are_disjoint() -> None:
mrv2 = _config("dflash")
ddtree = _config("dflash_ddtree")
assert mrv2.use_dflash()
assert not mrv2.use_dflash_ddtree()
assert mrv2.use_dflash_family()
assert not ddtree.use_dflash()
assert ddtree.use_dflash_ddtree()
assert ddtree.use_dflash_family()
def test_mrv2_dflash_reserves_all_mask_slots() -> None:
assert _config("dflash").max_num_new_slots_for_drafting == 7
# The retained DDTree path keeps its existing flat-parallel slot contract.
assert _config("dflash_ddtree").max_num_new_slots_for_drafting == 6
def test_dflash_forces_v2_and_rejects_explicit_v1(monkeypatch) -> None:
fake = SimpleNamespace(
speculative_config=SimpleNamespace(use_dflash=lambda: True),
)
monkeypatch.setattr("vllm.config.vllm.envs.VLLM_USE_V2_MODEL_RUNNER", None)
assert VllmConfig.use_v2_model_runner.fget(fake)
monkeypatch.setattr("vllm.config.vllm.envs.VLLM_USE_V2_MODEL_RUNNER", False)
with pytest.raises(ValueError, match="implemented only by Model Runner V2"):
VllmConfig.use_v2_model_runner.fget(fake)
def test_dflash_target_layers_use_boundary_indices() -> None:
spec_config = SimpleNamespace(
draft_model_config=SimpleNamespace(
hf_config=SimpleNamespace(target_layer_ids=[5, 19, 33, 47, 61])
)
)
assert get_eagle3_aux_layers_from_config(spec_config) == (6, 20, 34, 48, 62)
def test_parallel_drafting_token_id_prefers_dflash_config() -> None:
config = SimpleNamespace(
dflash_config={"mask_token_id": 248070},
pard_token=1,
)
assert get_parallel_drafting_token_id(config) == 248070
def test_ddtree_topk_adapter_uses_official_logits_processor() -> None:
hidden_states = torch.randn(2, 4)
expected_ids = torch.tensor([[3, 2], [1, 0]])
expected_logprobs = torch.tensor([[-0.1, -0.2], [-0.3, -0.4]])
class Processor:
def get_topk_tokens_and_logprobs(self, head, states, top_k):
assert head == "head"
assert states is hidden_states
assert top_k == 2
return expected_ids, expected_logprobs
model = SimpleNamespace(
draft_id_to_target_id=None,
logits_processor=Processor(),
lm_head="head",
)
actual = DFlashQwen3ForCausalLM.get_topk_tokens_and_logprobs(
model, hidden_states, 2
)
assert actual is not None
assert actual[0] is expected_ids
assert actual[1] is expected_logprobs
def test_dflash_aux_projection_matches_fc_weight_dtype() -> None:
class FC:
input_size = 4
weight = torch.empty((4, 4), dtype=torch.float16)
def __call__(self, hidden_states: torch.Tensor) -> torch.Tensor:
assert hidden_states.dtype == self.weight.dtype
return hidden_states
model = SimpleNamespace(
model=SimpleNamespace(use_aux_hidden_state=True, fc=FC()),
)
hidden_states = torch.ones((2, 4), dtype=torch.float32)
output = DFlashQwen3ForCausalLM.combine_hidden_states(model, hidden_states)
assert output.dtype == torch.float16
def test_draft_kv_dtype_is_public_and_defaults_to_inherit() -> None:
assert SpeculativeConfig.kv_cache_dtype is None
def test_ddtree_draft_config_combines_sm70_kv_and_non_causal(monkeypatch) -> None:
@dataclass(frozen=True)
class CacheConfig:
cache_dtype: str
@dataclass(frozen=True)
class AttentionConfig:
use_non_causal: bool
@dataclass(frozen=True)
class DraftConfig:
cache_config: CacheConfig
attention_config: AttentionConfig
base = DraftConfig(
cache_config=CacheConfig(cache_dtype="fp8_e5m2"),
attention_config=AttentionConfig(use_non_causal=False),
)
proposer = object.__new__(DFlashProposer)
proposer.speculative_config = SimpleNamespace(kv_cache_dtype=None)
proposer.dflash_causal = False
monkeypatch.setattr(
SpecDecodeBaseProposer,
"_create_draft_vllm_config",
lambda _self: base,
)
monkeypatch.setattr(
"vllm.v1.spec_decode.dflash.current_platform",
SimpleNamespace(
is_cuda=lambda: True,
is_device_capability=lambda capability: capability == 70,
),
)
draft = DFlashProposer._create_draft_vllm_config(proposer)
assert draft.cache_config.cache_dtype == "auto"
assert draft.attention_config.use_non_causal is True
def test_draft_attention_metadata_resolves_causal_per_kv_group() -> None:
class Builder:
def build(self, common_prefix_len, common_attn_metadata, **_kwargs):
assert common_prefix_len == 0
return common_attn_metadata
class Group:
def __init__(self, layer_name: str):
self.layer_names = [layer_name]
self.builder = Builder()
def get_metadata_builder(self, _index: int):
return self.builder
attn_metadata = build_attn_metadata(
attn_groups=[[Group("layer.0")], [Group("layer.1")]],
num_reqs=1,
num_tokens=1,
query_start_loc_gpu=torch.tensor([0, 1], dtype=torch.int32),
query_start_loc_cpu=torch.tensor([0, 1], dtype=torch.int32),
max_query_len=1,
seq_lens=torch.tensor([1], dtype=torch.int32),
max_seq_len=1,
block_tables=[
torch.zeros((1, 1), dtype=torch.int32),
torch.zeros((1, 1), dtype=torch.int32),
],
slot_mappings=torch.zeros((2, 1), dtype=torch.int64),
kv_cache_config=SimpleNamespace(kv_cache_groups=[object(), object()]),
causal={0: False, 1: True},
)
assert attn_metadata["layer.0"].causal is False
assert attn_metadata["layer.1"].causal is True
+7 -4
View File
@@ -63,7 +63,7 @@ def _create_proposer(
elif method == "draft_model":
target_model_dir = model_dir
draft_model_dir = ar_draft_model_dir
elif method == "dflash":
elif method == "dflash_ddtree":
target_model_dir = dflash_target_dir
draft_model_dir = dflash_dir
else:
@@ -73,7 +73,7 @@ def _create_proposer(
model=target_model_dir,
runner="generate",
max_model_len=100,
trust_remote_code=(method == "dflash"),
trust_remote_code=(method == "dflash_ddtree"),
)
speculative_config = SpeculativeConfig(
@@ -105,7 +105,7 @@ def _create_proposer(
attention_config=AttentionConfig(backend=attention_backend),
)
if method == "dflash":
if method == "dflash_ddtree":
proposer = DFlashProposer(vllm_config=vllm_config, device=device)
elif "eagle" in method:
proposer = EagleProposer(vllm_config=vllm_config, device=device)
@@ -1132,7 +1132,10 @@ def test_set_inputs_first_pass_dflash():
device = torch.device(current_platform.device_type)
num_speculative_tokens = 3
proposer = _create_proposer("dflash", num_speculative_tokens)
proposer = _create_proposer("dflash_ddtree", num_speculative_tokens)
# Production initialization assigns the draft KV cache group before this
# method runs. This isolated input-preparation test supplies that contract.
proposer.kv_cache_gid = 0
mask_token_id = proposer.parallel_drafting_token_id
# Setup batch with 3 requests
+26 -8
View File
@@ -8,6 +8,7 @@ from pydantic import Field, SkipValidation, field_validator, model_validator
from typing_extensions import Self
from vllm.config import LoadConfig
from vllm.config.cache import CacheDType
from vllm.config.kernel import MoEBackend
from vllm.config.model import ModelConfig
from vllm.config.parallel import ParallelConfig
@@ -52,7 +53,8 @@ MTPModelTypes = Literal[
"gemma4_mtp",
]
NgramGPUTypes = Literal["ngram_gpu"]
DFlashModelTypes = Literal["dflash", "dflash_ddtree"]
DFlashModelTypes = Literal["dflash"]
DFlashDDTreeModelTypes = Literal["dflash_ddtree"]
DSparkModelTypes = Literal["dspark"]
DDTreeBuildMode = Literal["best_first", "root_leaf", "spine_leaf"]
EagleModelTypes = Literal[
@@ -61,6 +63,7 @@ EagleModelTypes = Literal[
"extract_hidden_states",
MTPModelTypes,
DFlashModelTypes,
DFlashDDTreeModelTypes,
DSparkModelTypes,
]
SpeculativeMethod = Literal[
@@ -119,6 +122,10 @@ class SpeculativeConfig:
"""Attention backend to use for the draft model. When `None`, the backend is
automatically selected. Useful when the drafter requires a different attention
backend (e.g. DFlash needs a non-causal-capable backend like FLASH_ATTN)."""
kv_cache_dtype: CacheDType | None = None
"""KV cache dtype for the draft model. When ``None``, the draft inherits
the target cache dtype, except for SM70 DFlash with a quantized target,
which is resolved to ``auto`` during draft model loading."""
max_model_len: int | None = Field(default=None, ge=1)
"""The maximum model length of the draft model. Used when testing the
ability to skip speculation for some sequences."""
@@ -307,7 +314,7 @@ class SpeculativeConfig:
"eagle3",
"extract_hidden_states",
)
or self.use_dflash()
or self.use_dflash_family()
or self.use_dspark()
)
factors.append(uses_aux_hidden_states)
@@ -748,7 +755,7 @@ class SpeculativeConfig:
# Automatically detect the method
if (
self.method in ("eagle", "eagle3")
or self.use_dflash()
or self.use_dflash_family()
or self.use_dspark()
):
pass
@@ -788,7 +795,7 @@ class SpeculativeConfig:
)
# Replace hf_config for EAGLE draft_model
if self.method in ("eagle", "eagle3") or self.use_dflash():
if self.method in ("eagle", "eagle3") or self.use_dflash_family():
from vllm.transformers_utils.configs.eagle import EAGLEConfig
from vllm.transformers_utils.configs.speculators import (
SpeculatorsConfig,
@@ -800,7 +807,9 @@ class SpeculativeConfig:
):
pass
else:
eagle_method = "dflash" if self.use_dflash() else self.method
eagle_method = (
"dflash" if self.use_dflash_family() else self.method
)
eagle_config = EAGLEConfig(
self.draft_model_config.hf_config,
method=eagle_method,
@@ -815,7 +824,7 @@ class SpeculativeConfig:
draft_hf_config.architectures = ["DSparkDraftModel"]
self.update_arch_()
if self.use_dflash() or self.use_dspark():
if self.use_dflash_family() or self.use_dspark():
self.parallel_drafting = True
if self.num_speculative_tokens is not None and hasattr(
@@ -1135,6 +1144,12 @@ class SpeculativeConfig:
Calculate the maximum number of new slots that might be added to the batch
when drafting.
"""
if self.use_dflash():
# MRV2 DFlash uses one bonus query followed by K mask queries. The
# scheduler already owns the target query slot, so K more slots
# must be available to the drafter.
return self.num_speculative_tokens
slots_per_req = 0 # for serial non-draft-model methods, no change needed
if self.parallel_drafting:
# For parallel drafting, we need one new slot per 'masked' token
@@ -1164,16 +1179,19 @@ class SpeculativeConfig:
def use_eagle(self) -> bool:
return (
self.method in ("eagle", "eagle3", "mtp")
or self.use_dflash()
or self.use_dflash_family()
or self.use_dspark()
)
def use_dflash(self) -> bool:
return self.method in get_args(DFlashModelTypes)
return self.method == "dflash"
def use_dflash_ddtree(self) -> bool:
return self.method == "dflash_ddtree"
def use_dflash_family(self) -> bool:
return self.use_dflash() or self.use_dflash_ddtree()
def use_dspark(self) -> bool:
return self.method == "dspark"
+29 -2
View File
@@ -523,9 +523,23 @@ class VllmConfig:
@property
def use_v2_model_runner(self) -> bool:
use_v2_model_runner = envs.VLLM_USE_V2_MODEL_RUNNER
is_mrv2_dflash = (
self.speculative_config is not None and self.speculative_config.use_dflash()
)
if use_v2_model_runner is not None:
if is_mrv2_dflash and not use_v2_model_runner:
raise ValueError(
"method='dflash' is implemented only by Model Runner V2. "
"Use method='dflash_ddtree' for the retained V1 DDTree route."
)
return use_v2_model_runner
# The old V1 flat-DFlash route is intentionally removed. Force every
# method='dflash' checkpoint through the MRV2 speculator and fail in
# _validate_v2_model_runner if another configured feature is unsupported.
if is_mrv2_dflash:
return True
if not self._is_default_v2_model_runner_model():
return False
@@ -2505,11 +2519,19 @@ class VllmConfig:
# TODO: ngram / ngram_gpu are not supported by the v2 model runner yet
if speculative_config.method in ("ngram", "ngram_gpu"):
unsupported.append("ngram/ngram_gpu speculative decoding")
elif speculative_config.method not in ("eagle", "eagle3", "mtp"):
elif speculative_config.method not in (
"eagle",
"eagle3",
"mtp",
"dflash",
):
unsupported.append(f"speculative method '{speculative_config.method}'")
# V2 EagleSpeculator does not support parallel_drafting (required by PEagle)
if speculative_config.parallel_drafting:
if (
speculative_config.parallel_drafting
and speculative_config.method != "dflash"
):
unsupported.append("parallel drafting for speculative decoding")
if (
@@ -2517,6 +2539,11 @@ class VllmConfig:
and self.parallel_config.pipeline_parallel_size > 1
):
unsupported.append("EAGLE3 with pipeline parallelism")
if (
speculative_config.method == "dflash"
and self.parallel_config.pipeline_parallel_size > 1
):
unsupported.append("DFlash with pipeline parallelism")
if self.parallel_config.enable_dbo:
unsupported.append("dual batch overlap")
+370 -325
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
import io
from collections.abc import Iterable
import torch
@@ -10,10 +10,12 @@ from torch import nn
from transformers import Qwen3Config
from vllm import _custom_ops as ops
from vllm import envs
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig, get_current_vllm_config
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.distributed import (
get_tensor_model_parallel_rank,
get_tensor_model_parallel_world_size,
)
from vllm.logger import init_logger
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.layernorm import RMSNorm
@@ -35,12 +37,17 @@ from vllm.model_executor.model_loader.weight_utils import (
)
from vllm.multimodal.inputs import NestedTensors
from vllm.transformers_utils.config import set_default_rope_theta
from vllm.transformers_utils.repo_utils import get_hf_file_bytes
from vllm.v1.attention.backend import AttentionType
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
get_eagle3_aux_layers_from_config,
)
from .qwen2 import Qwen2MLP as Qwen3MLP
from .qwen3 import Qwen3ForCausalLM
from .utils import (
AutoWeightsLoader,
WeightsMapper,
get_draft_quant_config,
maybe_prefix,
process_eagle_weight,
@@ -49,43 +56,118 @@ from .utils import (
logger = init_logger(__name__)
def _get_dflash_per_layer_sliding_window(
config: Qwen3Config,
layer_idx: int,
) -> int | None:
_SLIDING_ATTENTION = "sliding_attention"
def _dflash_layer_causal(config: Qwen3Config, layer_idx: int) -> bool:
"""``dflash_config.causal`` overrides all layers; else only SWA layers causal."""
override = (getattr(config, "dflash_config", None) or {}).get("causal")
if override is not None:
return override
layer_types = getattr(config, "layer_types", None)
if layer_types is None:
return None
layer_type = layer_types[layer_idx]
if layer_type == "sliding_attention":
return getattr(config, "sliding_window", None)
if layer_type == "full_attention":
return None
raise ValueError(f"Invalid DFlash layer_type {layer_type}")
return bool(layer_types) and layer_types[layer_idx] == _SLIDING_ATTENTION
def _debug_sync_context_kv_enabled() -> bool:
return envs.VLLM_DFLASH_SYNC_CONTEXT_KV
def dflash_has_any_non_causal(config: Qwen3Config) -> bool:
"""Whether the draft needs a non-causal-capable backend, resolved from config
(config mirror of the model's ``get_draft_attn_causal``, usable pre-build)."""
return not all(
_dflash_layer_causal(config, i) for i in range(config.num_hidden_layers)
)
def _skip_context_kv_precompute_enabled() -> bool:
return envs.VLLM_DFLASH_SKIP_CONTEXT_KV_PRECOMPUTE
def dflash_target_rope_is_neox_style(target_model: nn.Module) -> bool | None:
"""The target's RoPE layout, from its first attention layer.
A DFlash head must rotate Q/K the way the target it was distilled against
does, and a mismatch is silent — acceptance collapses but nothing errors and
the output stays correct. Draft checkpoints do not carry this, so take it
from the target. None if the target uses no RoPE.
"""
language_model = (
target_model.get_language_model()
if hasattr(target_model, "get_language_model")
else target_model
)
for module in language_model.modules():
style = getattr(module, "is_neox_style", None)
if isinstance(style, bool):
return style
return None
def _debug_context_kv_enabled() -> bool:
return envs.VLLM_DFLASH_DEBUG_CONTEXT_KV
def _get_dflash_fc_input_size(vllm_config: VllmConfig) -> int:
spec_config = vllm_config.speculative_config
config = spec_config.draft_model_config.hf_config
aux_layers = get_eagle3_aux_layers_from_config(spec_config)
num_features_to_use = len(aux_layers) if aux_layers else config.num_hidden_layers
target_hidden_size = (
getattr(config, "target_hidden_size", None) or config.hidden_size
)
return target_hidden_size * num_features_to_use
def _dump_draft_layer_hiddens_enabled() -> bool:
return envs.VLLM_DFLASH_DUMP_LAYER_HIDDENS
def _resolve_layer_attention(
config: Qwen3Config, layer_idx: int
) -> tuple[int | None, bool]:
"""Resolve ``(sliding_window, causal)`` for one DFlash draft layer.
+----------------------+-------------------------+--------------------------------+
| Config | ``layer_type`` | *``causal`` |
+======================+=========================+================================+
| ``layer_types`` | SWA if ``use_swa`` | True if ``layer_types[i]=SWA`` |
| | else ``layer_types[i]`` | else False |
+----------------------+-------------------------+--------------------------------+
| ``layer_types=None`` | SWA | False |
| + ``use_swa=True`` | | |
+----------------------+-------------------------+--------------------------------+
| ``layer_types=None`` | Full | False |
| + ``use_swa=False`` | | |
+----------------------+-------------------------+--------------------------------+
* If ``dflash_config.causal`` is set, its value overrides ``causal`` for all layers.
def _dump_draft_layer0_components_enabled() -> bool:
return envs.VLLM_DFLASH_DUMP_LAYER0_COMPONENTS
This is to support a varied ecosystem of checkpoints, including:
- XiaomiMiMo/MiMo-V2.5-Pro-FP4-DFlash (sets "use_swa", assumes non-causal)
- z-lab/gemma-4-31B-it-DFlash (has mixed layer types, assumes causal only for SWA)
- z-lab/Qwen3.5-9B-DFlash ("standard" DFlash, all full attn, assumes non-causal)
"""
dflash_config = getattr(config, "dflash_config", None) or {}
layer_types = getattr(config, "layer_types", None)
use_swa = dflash_config.get("use_swa", False)
any_sliding = False
if layer_types is not None:
num_sliding = sum(lt == _SLIDING_ATTENTION for lt in layer_types)
any_sliding = num_sliding > 0
# Mixed sliding/full attention needs multiple KV groups (V2 runner only).
if (
0 < num_sliding < len(layer_types)
and not get_current_vllm_config().use_v2_model_runner
):
raise NotImplementedError(
"DFlash drafters with mixed sliding/full attention require "
"the V2 model runner; relaunch with "
"VLLM_USE_V2_MODEL_RUNNER=1."
)
def _dump_draft_attn_components_enabled() -> bool:
return envs.VLLM_DFLASH_DUMP_ATTN_COMPONENTS
# ``use_swa`` forces SWA on every layer, even an all-full ``layer_types``.
if layer_types is None or (use_swa and not any_sliding):
is_sliding = use_swa
else:
is_sliding = layer_types[layer_idx] == _SLIDING_ATTENTION
sliding_window = None
if is_sliding:
sliding_window = dflash_config.get(
"swa_window_size", getattr(config, "sliding_window", None)
)
if sliding_window is None:
raise ValueError(
"DFlash sliding attention requires a window size configured in "
"dflash_config.swa_window_size or the top-level sliding_window."
)
return sliding_window, _dflash_layer_causal(config, layer_idx)
class DFlashQwen3Attention(nn.Module):
@@ -105,16 +187,18 @@ class DFlashQwen3Attention(nn.Module):
head_dim: int | None = None,
rms_norm_eps: float = 1e-06,
attention_bias: bool = False,
add_swa_attention_sink_bias: bool = False,
sliding_window: int | None = None,
causal: bool = False,
is_neox_style: bool = True,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
attn_type: str = AttentionType.DECODER,
per_layer_sliding_window: int | None = None,
) -> None:
super().__init__()
self.layer_name = prefix
self.hidden_size = hidden_size
self.per_layer_sliding_window = per_layer_sliding_window
tp_size = get_tensor_model_parallel_world_size()
self.total_num_heads = num_heads
assert self.total_num_heads % tp_size == 0
@@ -150,8 +234,17 @@ class DFlashQwen3Attention(nn.Module):
self.rotary_emb = get_rope(
self.head_dim,
max_position=max_position,
is_neox_style=is_neox_style,
rope_parameters=rope_parameters,
)
self.attention_sink_bias = (
torch.nn.Parameter(torch.empty(self.num_heads), requires_grad=False)
if add_swa_attention_sink_bias
else None
)
self.sliding_window = sliding_window
self.attn = Attention(
self.num_heads,
self.head_dim,
@@ -159,14 +252,17 @@ class DFlashQwen3Attention(nn.Module):
num_kv_heads=self.num_kv_heads,
cache_config=cache_config,
quant_config=quant_config,
per_layer_sliding_window=sliding_window,
prefix=f"{prefix}.attn",
attn_type=attn_type,
per_layer_sliding_window=per_layer_sliding_window,
sinks=self.attention_sink_bias,
)
# The in-tree FlashAttention-V100 backend uses this marker to select
# its DFlash-compatible non-causal paged-prefill fallback.
self.attn.is_dflash_draft_attn = True
self.causal = causal
self.q_norm = RMSNorm(self.head_dim, eps=rms_norm_eps)
self.k_norm = RMSNorm(self.head_dim, eps=rms_norm_eps)
self._attn_components_dumped = False
def forward(
self,
@@ -177,7 +273,7 @@ class DFlashQwen3Attention(nn.Module):
with the context K/V from the target model's hidden states. This forward op
computes attention for the query tokens only.
See also: precompute_and_store_context_kv"""
qkv = F.linear(hidden_states, self.qkv_proj.weight, self.qkv_proj.bias)
qkv, _ = self.qkv_proj(hidden_states)
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
# Per-head RMSNorm
@@ -193,27 +289,6 @@ class DFlashQwen3Attention(nn.Module):
attn_output = self.attn(q, k, v)
output, _ = self.o_proj(attn_output)
if (
_dump_draft_attn_components_enabled()
and not self._attn_components_dumped
and positions.shape[-1] == 17
and int(positions.max().item()) > 0
and ".layers.32.self_attn" in self.layer_name
):
dump_path = f"/tmp/dflash_draft_attn_components_pid{os.getpid()}.pt"
torch.save(
{
"positions": positions.detach().cpu(),
"q": q.detach().to(torch.float16).cpu(),
"k": k.detach().to(torch.float16).cpu(),
"v": v.detach().to(torch.float16).cpu(),
"attn_output": attn_output.detach().to(torch.float16).cpu(),
"o_proj_output": output.detach().to(torch.float16).cpu(),
},
dump_path,
)
self._attn_components_dumped = True
logger.warning("Saved DFlash draft attn components to %s", dump_path)
return output
@@ -223,19 +298,35 @@ class DFlashQwen3DecoderLayer(nn.Module):
vllm_config: VllmConfig,
*,
config: Qwen3Config,
layer_idx: int,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
layer_idx: int,
prefix: str = "",
) -> None:
super().__init__()
self.hidden_size = config.hidden_size
set_default_rope_theta(config, default_theta=1000000)
attn_type = AttentionType.DECODER
per_layer_sliding_window = _get_dflash_per_layer_sliding_window(
config, layer_idx
# DFlash drafts store the sink-bias flag inside dflash_config; fall back
# to the top-level attribute used by other (e.g. MiMo) configs.
dflash_config = getattr(config, "dflash_config", None) or {}
add_swa_attention_sink_bias = dflash_config.get(
"attention_sink_bias",
getattr(config, "add_swa_attention_sink_bias", False),
)
# Resolve this layer's attention mode (full vs sliding window, causal vs
# non-causal) from the draft config.
sliding_window, causal = _resolve_layer_attention(config, layer_idx)
# RoPE layout, copied off the target at load time by the draft loader
# (see `dflash_target_rope_is_neox_style`). Checkpoints do not carry it:
# a head distilled from an interleaved-RoPE target must rotate the way
# that target does, or every drafted Q/K is wrong and acceptance
# collapses with no error raised.
is_neox_style = getattr(config, "is_neox_style", True)
self.self_attn = DFlashQwen3Attention(
hidden_size=self.hidden_size,
num_heads=config.num_attention_heads,
@@ -243,13 +334,16 @@ class DFlashQwen3DecoderLayer(nn.Module):
num_kv_heads=config.num_key_value_heads,
rms_norm_eps=config.rms_norm_eps,
attention_bias=getattr(config, "attention_bias", False),
add_swa_attention_sink_bias=add_swa_attention_sink_bias,
sliding_window=sliding_window,
causal=causal,
is_neox_style=is_neox_style,
head_dim=getattr(config, "head_dim", None),
cache_config=cache_config,
quant_config=quant_config,
rope_parameters=config.rope_parameters,
prefix=f"{prefix}.self_attn",
attn_type=attn_type,
per_layer_sliding_window=per_layer_sliding_window,
)
self.mlp = Qwen3MLP(
hidden_size=self.hidden_size,
@@ -262,7 +356,6 @@ class DFlashQwen3DecoderLayer(nn.Module):
self.post_attention_layernorm = RMSNorm(
config.hidden_size, eps=config.rms_norm_eps
)
self._layer0_components_dumped = False
def forward(
self,
@@ -275,49 +368,30 @@ class DFlashQwen3DecoderLayer(nn.Module):
else:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
ln_out = hidden_states
hidden_states = self.self_attn(
positions=positions,
hidden_states=hidden_states,
)
attn_out = hidden_states
hidden_states, residual = self.post_attention_layernorm(hidden_states, residual)
post_attn_ln_out = hidden_states
hidden_states = self.mlp(hidden_states)
if (
_dump_draft_layer0_components_enabled()
and not self._layer0_components_dumped
and positions.shape[-1] == 17
and int(positions.max().item()) > 0
and ".layers.32.self_attn" in self.self_attn.layer_name
):
mlp_gate_up, _ = self.mlp.gate_up_proj(post_attn_ln_out)
mlp_act_out = self.mlp.act_fn(mlp_gate_up)
dump_path = f"/tmp/dflash_draft_layer0_components_pid{os.getpid()}.pt"
torch.save(
{
"positions": positions.detach().cpu(),
"input_layernorm_out": ln_out.detach().to(torch.float16).cpu(),
"self_attn_out": attn_out.detach().to(torch.float16).cpu(),
"post_attention_layernorm_out": post_attn_ln_out.detach()
.to(torch.float16)
.cpu(),
"mlp_gate_up": mlp_gate_up.detach().to(torch.float16).cpu(),
"mlp_act_out": mlp_act_out.detach().to(torch.float16).cpu(),
"mlp_out": hidden_states.detach().to(torch.float16).cpu(),
"residual": residual.detach().to(torch.float16).cpu(),
},
dump_path,
)
self._layer0_components_dumped = True
logger.warning("Saved DFlash draft layer0 components to %s", dump_path)
return hidden_states, residual
@support_torch_compile
class DFlashQwen3Model(nn.Module):
hf_to_vllm_mapper = WeightsMapper(
orig_to_new_substr={
"midlayer.": "layers.0.",
# Muse-Glimmer-30B-assistant names the aux-hidden-state encoder
# `encoder.fc` / `encoder.output_norm_enc`; this head calls them
# `fc` / `hidden_norm`. Same tensors and shapes, different names.
"encoder.output_norm_enc.": "hidden_norm.",
"encoder.fc.": "fc.",
},
)
def __init__(
self,
*,
@@ -346,31 +420,36 @@ class DFlashQwen3Model(nn.Module):
prefix=maybe_prefix(prefix, "embed_tokens"),
)
# Masked query slots are fed to the draft as `mask_token_id`. Most DFlash
# checkpoints will have the mask embedding in the vocabulary embedding table
# at that slot id. Some checkpoints (XiaomiMiMo/MiMo-V2.5-Pro-FP4-DFlash) ship
# with a separate mask embedding tensor to use instead. When present, we load it
# and substitute it for embed_tokens[mask_token_id] when computing embeddings.
self.mask_token_id = drafter_config.get("mask_token_id")
self.mask_embedding = nn.Parameter(
torch.zeros(self.config.hidden_size, dtype=vllm_config.model_config.dtype),
requires_grad=False,
)
self.has_separate_mask_embedding = False
self.layers = nn.ModuleList(
[
DFlashQwen3DecoderLayer(
current_vllm_config,
config=self.config,
layer_idx=layer_idx,
cache_config=current_vllm_config.cache_config,
quant_config=self.quant_config,
layer_idx=layer_idx,
prefix=maybe_prefix(prefix, f"layers.{layer_idx + start_layer_id}"),
)
for layer_idx in range(self.config.num_hidden_layers)
]
)
if self.use_aux_hidden_state:
num_features_to_use = self.config.num_hidden_layers
if "target_layer_ids" in drafter_config:
num_features_to_use = len(drafter_config["target_layer_ids"])
elif "layer_ids" in drafter_config:
num_features_to_use = len(drafter_config["layer_ids"])
if hasattr(self.config, "target_hidden_size"):
fc_input_size = self.config.target_hidden_size * num_features_to_use
else:
fc_input_size = self.config.hidden_size * num_features_to_use
self.fc = ReplicatedLinear(
input_size=fc_input_size,
input_size=_get_dflash_fc_input_size(
vllm_config,
),
output_size=self.config.hidden_size,
bias=False,
params_dtype=vllm_config.model_config.dtype,
@@ -386,11 +465,36 @@ class DFlashQwen3Model(nn.Module):
self.config.hidden_size,
eps=self.config.rms_norm_eps,
)
self._debug_context_kv_dumped = False
self._draft_layer_hiddens_dumped = False
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
embeds = self.embed_tokens(input_ids)
if self.has_separate_mask_embedding and self.mask_token_id is not None:
# Replace masked slots with the dedicated mask embedding.
is_mask = (input_ids == self.mask_token_id).unsqueeze(-1)
embeds = torch.where(is_mask, self.mask_embedding.to(embeds.dtype), embeds)
return embeds
def _build_context_kv_buffers(
self,
layers_attn: list[nn.Module],
has_bias: bool,
) -> None:
self._hidden_norm_weight = self.hidden_norm.weight.data
# KV projection weights: [num_layers * 2 * kv_size, hidden_size]
kv_weights = [a.qkv_proj.weight[a.q_size :] for a in layers_attn]
self._fused_kv_weight = torch.cat(kv_weights, dim=0)
if has_bias:
kv_biases = [a.qkv_proj.bias[a.q_size :] for a in layers_attn]
self._fused_kv_bias: torch.Tensor | None = torch.cat(kv_biases, dim=0)
else:
self._fused_kv_bias = None
# K-norm weights stacked into one contiguous [num_layers, head_dim]
# tensor so the per-layer K-norm runs as a single grouped kernel.
self._k_norm_weights = torch.stack(
[a.k_norm.weight.data for a in layers_attn], dim=0
).contiguous()
def _build_fused_kv_buffers(self) -> None:
"""Build fused weight buffers for precompute_and_store_context_kv.
@@ -404,19 +508,7 @@ class DFlashQwen3Model(nn.Module):
attn0 = layers_attn[0]
has_bias = attn0.qkv_proj.bias is not None
self._hidden_norm_weight = self.hidden_norm.weight.data
# KV projection weights: [num_layers * 2 * kv_size, hidden_size]
kv_weights = [a.qkv_proj.weight[a.q_size :] for a in layers_attn]
self._fused_kv_weight = torch.cat(kv_weights, dim=0)
if has_bias:
kv_biases = [a.qkv_proj.bias[a.q_size :] for a in layers_attn]
self._fused_kv_bias: torch.Tensor | None = torch.cat(kv_biases, dim=0)
else:
self._fused_kv_bias = None
# K-norm weights: list of [head_dim] tensors, one per layer.
self._k_norm_weights = [a.k_norm.weight.data for a in layers_attn]
self._build_context_kv_buffers(layers_attn, has_bias)
# RoPE parameters
self._rope_head_size = attn0.rotary_emb.head_size
@@ -447,41 +539,14 @@ class DFlashQwen3Model(nn.Module):
# References to inner Attention layers for direct cache writes
self._attn_layers = [layer.self_attn.attn for layer in self.layers]
def precompute_and_store_context_kv(
def _project_context_kv(
self,
context_states: torch.Tensor,
context_positions: torch.Tensor,
context_slot_mapping: torch.Tensor | dict[str, torch.Tensor] | None = None,
) -> None:
"""Precompute K/V for context states write them into each layer's KV cache.
Input context states are projected to K/V, normed, and have RoPE applied.
Since the context shape is different than the query shape, we can't rely on the
regular forward pass to apply torch.compile and CUDA graphs to this section.
As such, this function is optimized to minimize the number of torch ops present:
we use fused vLLM kernels for RMSNorm and RoPE, fuse the GEMM into one
large projection, and avoid cloning buffers (with .contiguous()) where possible.
When context_slot_mapping is None (e.g. during dummy_run) only
the computation runs, and no K/V is written to cache.
"""
if _skip_context_kv_precompute_enabled():
logger.warning("Skipping DFlash context KV precompute for debugging.")
return
if not hasattr(self, "_num_attn_layers"):
logger.warning_once(
"DFlash buffer initialization was skipped. If dummy weights are not "
"in use, this may indicate an error in weight loading."
)
self._build_fused_kv_buffers()
num_ctx = context_states.shape[0]
L = self._num_attn_layers
kv = self._kv_size
hd = self._head_dim
nkv = self._num_kv_heads
num_ctx: int,
num_layers: int,
num_kv_heads: int,
head_dim: int,
) -> tuple[torch.Tensor, torch.Tensor]:
# --- Fused KV projection (one GEMM for all layers) ---
normed_context_states = torch.empty_like(context_states)
ops.rms_norm(
@@ -497,20 +562,59 @@ class DFlashQwen3Model(nn.Module):
# layer-major layout. Result: [2, L, num_ctx, nkv, hd] contiguous.
# Indexing dim-0 gives contiguous [L, num_ctx, nkv, hd] for K and V.
all_kv = (
all_kv_flat.view(num_ctx, L, 2, nkv, hd).permute(2, 1, 0, 3, 4).contiguous()
all_kv_flat.view(num_ctx, num_layers, 2, num_kv_heads, head_dim)
.permute(2, 1, 0, 3, 4)
.contiguous()
)
all_k = all_kv[0] # [L, num_ctx, nkv, hd], contiguous
all_v = all_kv[1] # [L, num_ctx, nkv, hd], contiguous
return all_k, all_v
# --- Per-layer RMSNorm K (3D: [num_ctx, nkv, hd] per layer) ---
def _normalize_context_k(self, all_k: torch.Tensor) -> torch.Tensor:
# --- Grouped RMSNorm K across all layers ([L, num_ctx, nkv, hd]) ---
# The weight is selected per layer by the outermost (layer) index.
all_k_normed = torch.empty_like(all_k)
for i in range(L):
ops.rms_norm(
all_k_normed[i],
all_k[i],
self._k_norm_weights[i],
self._rms_norm_eps,
ops.rms_norm(
all_k_normed,
all_k,
self._k_norm_weights,
self._rms_norm_eps,
)
return all_k_normed
def precompute_and_store_context_kv(
self,
context_states: torch.Tensor,
context_positions: torch.Tensor,
context_slot_mapping: torch.Tensor | list[torch.Tensor | None] | None = None,
) -> None:
"""Precompute K/V for context states write them into each layer's KV cache.
Input context states are projected to K/V, normed, and have RoPE applied.
Since the context shape is different than the query shape, we can't rely on the
regular forward pass to apply torch.compile and CUDA graphs to this section.
As such, this function is optimized to minimize the number of torch ops present:
we use fused vLLM kernels for RMSNorm and RoPE, fuse the GEMM into one
large projection, and avoid cloning buffers (with .contiguous()) where possible.
When context_slot_mapping is None (e.g. during dummy_run) only
the computation runs, and no K/V is written to cache.
"""
if not hasattr(self, "_num_attn_layers"):
logger.warning_once(
"DFlash buffer initialization was skipped. If dummy weights are not "
"in use, this may indicate an error in weight loading."
)
self._build_fused_kv_buffers()
num_ctx = context_states.shape[0]
L = self._num_attn_layers
kv = self._kv_size
hd = self._head_dim
nkv = self._num_kv_heads
all_k, all_v = self._project_context_kv(context_states, num_ctx, L, nkv, hd)
all_k_normed = self._normalize_context_k(all_k)
# --- Fused RoPE across all layers ---
# View as [L * num_ctx, kv] so RoPE sees one big batch (no copy).
@@ -534,145 +638,22 @@ class DFlashQwen3Model(nn.Module):
# --- Per-layer cache insert ---
all_k_final = all_k_flat.view(L, num_ctx, nkv, hd)
debug_direct_refs: dict[
int, list[tuple[str, int, torch.Tensor, torch.Tensor]]
] = {}
if _debug_context_kv_enabled() and not self._debug_context_kv_dumped:
sample_tokens = min(8, num_ctx)
debug_ranges: list[tuple[str, int, int]] = [("head", 0, sample_tokens)]
if num_ctx > sample_tokens:
tail_start = max(0, num_ctx - sample_tokens)
if tail_start > 0:
debug_ranges.append(("tail", tail_start, num_ctx))
debug_cos_sin_cache = self._rope_cos_sin_cache
for layer_idx in sorted({0, L // 2, L - 1}):
attn_layer = self.layers[layer_idx].self_attn
layer_refs: list[tuple[str, int, torch.Tensor, torch.Tensor]] = []
for sample_name, sample_start, sample_end in debug_ranges:
sample_len = sample_end - sample_start
direct_kv = F.linear(
normed_context_states[sample_start:sample_end],
attn_layer.qkv_proj.weight[attn_layer.q_size :],
(
None
if attn_layer.qkv_proj.bias is None
else attn_layer.qkv_proj.bias[attn_layer.q_size :]
),
)
direct_k, direct_v = direct_kv.split([kv, kv], dim=-1)
direct_k = direct_k.view(sample_len, nkv, hd).contiguous()
direct_v = direct_v.view(sample_len, nkv, hd).contiguous()
direct_k_norm = torch.empty_like(direct_k)
ops.rms_norm(
direct_k_norm,
direct_k,
attn_layer.k_norm.weight.data,
self._rms_norm_eps,
)
direct_k_flat = direct_k_norm.view(sample_len, kv)
if debug_cos_sin_cache.dtype != direct_k_flat.dtype:
debug_cos_sin_cache = debug_cos_sin_cache.to(
dtype=direct_k_flat.dtype
)
ops.rotary_embedding(
context_positions[sample_start:sample_end],
direct_k_flat,
None,
self._rope_head_size,
debug_cos_sin_cache,
self._rope_is_neox,
)
direct_k = direct_k_flat.view(sample_len, nkv, hd)
layer_refs.append((sample_name, sample_start, direct_k, direct_v))
fused_k_diff = (
all_k_final[layer_idx, sample_start:sample_end] - direct_k
).abs()
fused_v_diff = (
all_v[layer_idx, sample_start:sample_end] - direct_v
).abs()
logger.warning(
"DFlash context KV fused-vs-direct layer=%d sample=%s "
"start=%d tokens=%d k_max=%.6f k_mean=%.6f "
"v_max=%.6f v_mean=%.6f",
layer_idx,
sample_name,
sample_start,
sample_len,
float(fused_k_diff.max().item()),
float(fused_k_diff.mean().item()),
float(fused_v_diff.max().item()),
float(fused_v_diff.mean().item()),
)
debug_direct_refs[layer_idx] = layer_refs
per_layer = isinstance(context_slot_mapping, (list, tuple))
for i in range(L):
slot_mapping = (
context_slot_mapping[i] if per_layer else context_slot_mapping
)
if slot_mapping is None:
continue # dummy run: skip cache ops
attn = self._attn_layers[i]
layer_context_slot_mapping = context_slot_mapping
if isinstance(context_slot_mapping, dict):
layer_context_slot_mapping = context_slot_mapping[attn.layer_name]
assert layer_context_slot_mapping is not None
kv_cache = attn.kv_cache
if isinstance(kv_cache, list):
kv_cache = kv_cache[0]
if _debug_sync_context_kv_enabled():
logger.warning(
"DFlash context KV update layer=%s kv_cache_shape=%s "
"slot_min=%s slot_max=%s num_ctx=%d",
attn.layer_name,
tuple(kv_cache.shape),
int(layer_context_slot_mapping.min().item()),
int(layer_context_slot_mapping.max().item()),
num_ctx,
)
attn.impl.do_kv_cache_update(
attn,
all_k_final[i],
all_v[i],
kv_cache,
layer_context_slot_mapping,
slot_mapping,
)
if (
i in debug_direct_refs
and _debug_context_kv_enabled()
and not self._debug_context_kv_dumped
):
block_size = kv_cache.shape[2]
for (
sample_name,
sample_start,
direct_k,
direct_v,
) in debug_direct_refs[i]:
sample_len = direct_k.shape[0]
sample_end = sample_start + sample_len
slots = layer_context_slot_mapping[sample_start:sample_end].to(
torch.long
)
block_idx = torch.div(slots, block_size, rounding_mode="floor")
block_off = torch.remainder(slots, block_size)
cache_k = kv_cache[block_idx, 0, block_off]
cache_v = kv_cache[block_idx, 1, block_off]
cache_k_diff = (cache_k - direct_k).abs()
cache_v_diff = (cache_v - direct_v).abs()
logger.warning(
"DFlash context KV cache-readback layer=%d sample=%s "
"start=%d tokens=%d k_max=%.6f k_mean=%.6f "
"v_max=%.6f v_mean=%.6f",
i,
sample_name,
sample_start,
sample_len,
float(cache_k_diff.max().item()),
float(cache_k_diff.mean().item()),
float(cache_v_diff.max().item()),
float(cache_v_diff.mean().item()),
)
if i == max(debug_direct_refs):
self._debug_context_kv_dumped = True
if _debug_sync_context_kv_enabled():
torch.accelerator.synchronize(all_k_final.device)
def forward(
self,
@@ -686,44 +667,34 @@ class DFlashQwen3Model(nn.Module):
hidden_states = input_embeds
residual = None
layer_hidden_states: list[torch.Tensor] | None = None
should_dump_layer_hiddens = (
_dump_draft_layer_hiddens_enabled()
and not self._draft_layer_hiddens_dumped
and positions.shape[-1] == 17
and int(positions.max().item()) > 0
)
if should_dump_layer_hiddens:
layer_hidden_states = []
for layer in self.layers:
hidden_states, residual = layer(
positions=positions,
hidden_states=hidden_states,
residual=residual,
)
if layer_hidden_states is not None:
layer_hidden_states.append(
hidden_states.detach().to(torch.float16).cpu()
)
hidden_states, _ = self.norm(hidden_states, residual)
if layer_hidden_states is not None:
dump_path = f"/tmp/dflash_draft_layers_pid{os.getpid()}.pt"
torch.save(
{
"positions": positions.detach().cpu(),
"input_embeds": input_embeds.detach().to(torch.float16).cpu(),
"layer_hidden_states": layer_hidden_states,
"final_hidden_states": hidden_states.detach()
.to(torch.float16)
.cpu(),
},
dump_path,
)
self._draft_layer_hiddens_dumped = True
logger.warning("Saved DFlash draft layer hiddens to %s", dump_path)
return hidden_states
def _preprocess(
self, weights: Iterable[tuple[str, torch.Tensor]]
) -> Iterable[tuple[str, torch.Tensor]]:
tp_size = get_tensor_model_parallel_world_size()
tp_rank = get_tensor_model_parallel_rank()
for name, loaded_weight in weights:
if "attention_sink_bias" in name:
# Sink bias is per-head; shard it across TP ranks like the
# attention heads themselves.
heads_per_rank = loaded_weight.shape[0] // tp_size
loaded_weight = loaded_weight.narrow(
0, tp_rank * heads_per_rank, heads_per_rank
)
yield name, loaded_weight
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
# onecat's current AutoWeightsLoader predates stacked mapper metadata,
# so preserve the upstream naming contract while passing shard ids
# directly to the existing linear weight loaders.
stacked_params_mapping = [
(".qkv_proj", ".q_proj", "q"),
(".qkv_proj", ".k_proj", "k"),
@@ -733,9 +704,11 @@ class DFlashQwen3Model(nn.Module):
]
params_dict = dict(self.named_parameters())
loaded_params: set[str] = set()
for name, loaded_weight in weights:
if "midlayer." in name:
name = name.replace("midlayer.", "layers.0.")
for name, loaded_weight in self._preprocess(weights):
mapped_name = self.hf_to_vllm_mapper._map_name(name)
if mapped_name is None:
continue
name = mapped_name
if self.quant_config is not None and (
scale_name := self.quant_config.get_cache_scale(name)
):
@@ -756,8 +729,7 @@ class DFlashQwen3Model(nn.Module):
continue
name = name.replace(weight_name, param_name)
param = params_dict[name]
weight_loader = param.weight_loader
weight_loader(param, loaded_weight, shard_id)
param.weight_loader(param, loaded_weight, shard_id)
break
else:
param = params_dict[name]
@@ -770,7 +742,8 @@ class DFlashQwen3Model(nn.Module):
class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
nn.Module.__init__(self)
self.config = vllm_config.speculative_config.draft_model_config.hf_config
self.draft_model_config = vllm_config.speculative_config.draft_model_config
self.config = self.draft_model_config.hf_config
if getattr(self.config, "draft_vocab_size", None) is None:
self.config.draft_vocab_size = getattr(self.config, "vocab_size", None)
target_layer_num = vllm_config.model_config.get_num_layers(
@@ -816,6 +789,14 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
) -> torch.Tensor:
return self.model(input_ids, positions, inputs_embeds)
def get_draft_kv_cache_layer_names(self) -> list[str]:
return [layer.self_attn.attn.layer_name for layer in self.model.layers]
def get_draft_attn_causal(self) -> list[bool]:
"""Per-layer attention causality, aligned with
get_draft_kv_cache_layer_names."""
return [layer.self_attn.causal for layer in self.model.layers]
def compute_logits(
self,
hidden_states: torch.Tensor,
@@ -838,6 +819,12 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
hidden_states: torch.Tensor,
top_k: int,
) -> tuple[torch.Tensor, torch.Tensor] | None:
"""Compatibility adapter for the retained V1 DDTree proposer.
MRV2 DFlash does not use this method. Keeping the adapter on the
official model avoids retaining the removed experimental flat-DFlash
implementation solely for DDTree payload construction.
"""
if self.draft_id_to_target_id is not None:
return None
return self.logits_processor.get_topk_tokens_and_logprobs(
@@ -850,7 +837,7 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
self,
context_states: torch.Tensor,
context_positions: torch.Tensor,
context_slot_mapping: torch.Tensor | dict[str, torch.Tensor] | None = None,
context_slot_mapping: torch.Tensor | list[torch.Tensor | None] | None = None,
) -> None:
"""Precompute projected + RoPE'd K/V and write to cache."""
self.model.precompute_and_store_context_kv(
@@ -866,9 +853,17 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
needs_squeeze = hidden_states.dim() == 1
if needs_squeeze:
hidden_states = hidden_states.unsqueeze(0)
# Keep the auxiliary hidden-state projection on the same dtype as the
# DFlash FC weights. AWQ target paths may surface fp32 hidden states
# even when the draft projection is initialized in fp16.
expected = self.model.fc.input_size
if hidden_states.shape[-1] != expected:
raise ValueError(
f"DFlash drafter expects {expected} concatenated aux hidden "
f"features but received {hidden_states.shape[-1]}. This usually "
"means the draft model's target_layer_ids reference layers that "
"do not exist in the target model (incompatible draft/target pair)."
)
# AWQ target paths can surface fp32 auxiliary states even when the
# draft projection is initialized in fp16. Match the FC weight dtype
# before dispatching the linear kernel.
fc_weight = getattr(self.model.fc, "weight", None)
if fc_weight is not None and hidden_states.dtype != fc_weight.dtype:
hidden_states = hidden_states.to(dtype=fc_weight.dtype)
@@ -883,7 +878,9 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
includes_embed_tokens = False
for name, loaded_weight in weights:
assert "mask_hidden" not in name, (
"DFlash should use mask_token_id to embed the padding hidden state"
"DFlash embeds masked slots via mask_token_id (optionally "
"overridden by a mask_embedding.pt file); it should not ship a "
"mask_hidden weight."
)
if "t2d" in name:
continue
@@ -897,6 +894,13 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
model_weights[name] = loaded_weight
process_eagle_weight(self, name)
# Route the separately-trained mask embedding (if shipped) through the
# standard weight loader alongside the rest of the draft weights.
mask_embedding = self._read_mask_embedding()
if mask_embedding is not None:
model_weights["model.mask_embedding"] = mask_embedding
self.model.has_separate_mask_embedding = True
skip_substrs = []
if not includes_draft_id_mapping:
skip_substrs.append("draft_id_to_target_id")
@@ -904,6 +908,8 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
skip_substrs.append("embed_tokens")
if not self.model.use_aux_hidden_state:
skip_substrs.append("fc.")
if not self.model.has_separate_mask_embedding:
skip_substrs.append("mask_embedding")
loader = AutoWeightsLoader(
self,
skip_prefixes=None,
@@ -911,3 +917,42 @@ class DFlashQwen3ForCausalLM(Qwen3ForCausalLM):
)
loader.load_weights(model_weights.items())
self.model._build_fused_kv_buffers()
def _read_mask_embedding(self) -> torch.Tensor | None:
"""Checks for an override mask embedding in `mask_embedding.pt` and returns it.
Some checkpoints ship a separately-trained mask embedding for the mask token,
which we use to overwrite the embedding for `mask_token_id`. This helper
checks for the file, loads the pytorch tensor, and returns the embedding to use.
Returns None if the override file is not present.
"""
mask_token_id = self.model.mask_token_id
if mask_token_id is None:
return None
MASK_EMBEDDING_FILENAME = "mask_embedding.pt"
data = get_hf_file_bytes(
MASK_EMBEDDING_FILENAME,
self.draft_model_config.model,
self.draft_model_config.revision,
)
if data is None:
return None
state = torch.load(io.BytesIO(data), weights_only=True)
if isinstance(state, dict):
if state.get("mask_token_id", mask_token_id) != mask_token_id:
raise ValueError(
f"{MASK_EMBEDDING_FILENAME} mask_token_id does not match "
f"dflash_config.mask_token_id ({mask_token_id}). "
f"Got {state.get('mask_token_id')}."
)
state = state["embedding"]
logger.info(
"Loaded DFlash mask embedding for mask_token_id %s from %s",
mask_token_id,
MASK_EMBEDDING_FILENAME,
)
return state.reshape(-1)
+1 -1
View File
@@ -255,7 +255,7 @@ class Scheduler(SchedulerInterface):
self.num_lookahead_tokens = self.num_spec_tokens
if speculative_config.uses_draft_model():
self.num_lookahead_tokens = self.num_spec_tokens
if speculative_config.use_dflash():
if speculative_config.use_dflash_family():
# DFlash requires an extra lookahead slot since it uses in-fill-style
# decoding instead of standard next-token sampling, so it has a query
# for the last sampled token plus queries for each draft token.
+27 -12
View File
@@ -55,6 +55,32 @@ def _ddtree_worker_profile_enabled() -> bool:
class DFlashProposer(SpecDecodeBaseProposer):
@override
def _create_draft_vllm_config(self) -> VllmConfig:
base = super()._create_draft_vllm_config()
if (
self.speculative_config.kv_cache_dtype is None
and str(base.cache_config.cache_dtype).startswith("fp8")
and current_platform.is_cuda()
and current_platform.is_device_capability(70)
):
logger.info_once(
"Using FP16 draft KV cache for SM70 DFlash DDTree while the "
"target uses %s.",
base.cache_config.cache_dtype,
)
base = replace(
base,
cache_config=replace(base.cache_config, cache_dtype="auto"),
)
return replace(
base,
attention_config=replace(
base.attention_config,
use_non_causal=not self.dflash_causal,
),
)
def __init__(
self,
vllm_config: VllmConfig,
@@ -63,7 +89,7 @@ class DFlashProposer(SpecDecodeBaseProposer):
):
assert vllm_config.speculative_config is not None
assert (
vllm_config.speculative_config.use_dflash()
vllm_config.speculative_config.use_dflash_ddtree()
or vllm_config.speculative_config.use_dspark()
)
super().__init__(
@@ -323,17 +349,6 @@ class DFlashProposer(SpecDecodeBaseProposer):
"dflash_expand_inputs",
)
@override
def _create_draft_vllm_config(self) -> VllmConfig:
base = super()._create_draft_vllm_config()
return replace(
base,
attention_config=replace(
base.attention_config,
use_non_causal=not self.dflash_causal,
),
)
@override
def _warn_if_multimodal(self):
# Override to allow multimodal inputs since DFlash supports Qwen3.5 models
+9
View File
@@ -2035,6 +2035,15 @@ class SpecDecodeBaseProposer:
),
)
if spec_cfg.kv_cache_dtype is not None:
base = replace(
base,
cache_config=replace(
base.cache_config,
cache_dtype=spec_cfg.kv_cache_dtype,
),
)
return base
def _get_model(self) -> nn.Module:
+4 -2
View File
@@ -1,6 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Iterable, Sequence
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from typing import Any, cast
@@ -389,6 +389,7 @@ def build_attn_metadata(
positions: torch.Tensor | None = None,
model_specific_attn_metadata: ModelSpecificAttnMetadata | None = None,
for_cudagraph_capture: bool = False,
causal: bool | Mapping[int, bool] = True,
) -> dict[str, Any]:
seq_lens = seq_lens[:num_reqs]
if dcp_local_seq_lens is not None:
@@ -401,6 +402,7 @@ def build_attn_metadata(
for i in range(num_kv_cache_groups):
block_table = block_tables[i]
slot_mapping = slot_mappings[i]
group_causal = causal if isinstance(causal, bool) else causal.get(i, True)
common_attn_metadata_extra_kwargs = (
model_specific_attn_metadata.get_extra_common_attn_kwargs(i, num_reqs)
@@ -418,7 +420,7 @@ def build_attn_metadata(
max_query_len=max_query_len,
block_table_tensor=block_table,
slot_mapping=slot_mapping,
causal=True,
causal=group_causal,
dcp_local_seq_lens=dcp_local_seq_lens,
positions=positions,
**common_attn_metadata_extra_kwargs,
+21
View File
@@ -59,3 +59,24 @@ def _dcp_local_seq_lens_kernel(
# For [num_reqs, max_num_reqs), pad with 0
local_seq_lens = tl.where(block < num_reqs, local_seq_lens, 0)
tl.store(out_ptr + block, local_seq_lens, mask=block < max_num_reqs)
@triton.jit
def cp_local_slot(
positions,
block_numbers,
block_size,
cp_rank,
CP_SIZE: tl.constexpr,
CP_INTERLEAVE: tl.constexpr,
PAD_ID: tl.constexpr,
):
"""Return rank-local KV slots, or PAD_ID for non-local positions."""
block_offsets = positions % (block_size * CP_SIZE)
if CP_SIZE == 1:
return block_numbers * block_size + block_offsets
is_local = block_offsets // CP_INTERLEAVE % CP_SIZE == cp_rank
rounds = block_offsets // (CP_INTERLEAVE * CP_SIZE)
remainder = block_offsets % CP_INTERLEAVE
local_offsets = rounds * CP_INTERLEAVE + remainder
return tl.where(is_local, block_numbers * block_size + local_offsets, PAD_ID)
+25 -8
View File
@@ -99,6 +99,7 @@ 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.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.utils import DraftTokensHandler
from vllm.v1.worker.gpu.states import RequestState
from vllm.v1.worker.gpu.structured_outputs import StructuredOutputsWorker
@@ -175,11 +176,14 @@ class GPUModelRunner(LoRAModelRunnerMixin):
if self.is_last_pp_rank:
self.speculator = init_speculator(self.vllm_config, self.device)
if self.speculative_config.method == "eagle3":
# EAGLE3 may require auxiliary hidden states from target model outputs.
if self.speculative_config.method in ("eagle3", "dflash"):
# EAGLE3 and DFlash may require auxiliary target hidden states.
self.use_aux_hidden_state_outputs = True
if self.use_pp:
raise ValueError("EAGLE3 with pipeline parallel is not supported.")
raise ValueError(
f"{self.speculative_config.method} with pipeline parallel "
"is not supported."
)
# Draft tokens propagation - for spec-dec + struct outputs.
self.draft_tokens_handler = DraftTokensHandler(self.device)
@@ -424,11 +428,21 @@ class GPUModelRunner(LoRAModelRunnerMixin):
cudagraph_mode,
decode_query_len=self.decode_query_len,
)
if self.speculator is not None:
self.speculator.init_cudagraph_manager(cudagraph_mode)
check_attention_cp_compatibility(self.vllm_config)
if self.speculator is not None:
if isinstance(self.speculator, DraftModelSpeculator):
self.speculator.set_attn(
self.model_state,
self.kv_cache_config,
self.block_tables,
self.input_buffers,
self.attn_groups,
)
# DFlash sizes its graph mode from the selected draft attention
# backend, which is available only after set_attn().
self.speculator.init_cudagraph_manager(cudagraph_mode)
elif self.speculator is not None:
# Preserve the existing Eagle initialization order.
self.speculator.init_cudagraph_manager(cudagraph_mode)
# HACK(woosuk)
self.speculator.set_attn(
self.model_state, self.kv_cache_config, self.block_tables
@@ -650,7 +664,10 @@ class GPUModelRunner(LoRAModelRunnerMixin):
use_aux_hidden_state_outputs=self.use_aux_hidden_state_outputs,
)
if self.speculator is not None:
self.speculator.capture(captured_attn_states)
if isinstance(self.speculator, DraftModelSpeculator):
self.speculator.capture()
else:
self.speculator.capture(captured_attn_states)
end_time = time.perf_counter()
end_free_gpu_memory = torch.cuda.mem_get_info()[0]
@@ -8,6 +8,18 @@ from vllm.config import VllmConfig
def init_speculator(vllm_config: VllmConfig, device: torch.device):
speculative_config = vllm_config.speculative_config
assert speculative_config is not None
if speculative_config.method == "dflash":
draft_config = speculative_config.draft_model_config
if draft_config is None:
raise ValueError("method='dflash' requires a draft model config")
if "DFlash2DraftModel" in (draft_config.architectures or []):
raise ValueError(
"DFlash2 requires the MRV2 DFlash2 speculator, which is not "
"available in this base backport stage."
)
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
return DFlashSpeculator(vllm_config, device)
if speculative_config.use_eagle():
from vllm.v1.worker.gpu.spec_decode.eagle.speculator import EagleSpeculator
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,125 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable, Mapping
import torch
from vllm.config.compilation import CUDAGraphMode
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.gpu.attn_utils import (
build_attn_metadata,
build_slot_mappings_by_layer,
)
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.cp_utils import prepare_dcp_local_seq_lens
from vllm.v1.worker.gpu.cudagraph_utils import (
BatchExecutionDescriptor,
CapturedAttentionState,
CudaGraphManager,
)
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.utils import AttentionGroup
def _prepare_dflash_inputs_to_capture(
num_reqs: int,
num_tokens: int,
input_buffers: InputBuffers,
block_tables: BlockTables,
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
max_model_len: int,
skip_attn: bool,
causal: bool | Mapping[int, bool],
) -> CapturedAttentionState:
input_batch = InputBatch.make_dummy(num_reqs, num_tokens, input_buffers)
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(
slot_mappings, kv_cache_config
)
attn_metadata = None
if not skip_attn:
query_start_loc_cpu = torch.from_numpy(input_batch.query_start_loc_np)
dcp_local_seq_lens = None
if block_tables.cp_size > 1:
prepare_dcp_local_seq_lens(
input_buffers.dcp_local_seq_lens,
input_buffers.seq_lens,
num_reqs,
block_tables.cp_size,
block_tables.cp_rank,
block_tables.cp_interleave,
)
dcp_local_seq_lens = input_buffers.dcp_local_seq_lens
attn_metadata = build_attn_metadata(
attn_groups=attn_groups,
num_reqs=num_reqs,
num_tokens=num_tokens,
query_start_loc_gpu=input_batch.query_start_loc,
query_start_loc_cpu=query_start_loc_cpu,
max_query_len=num_tokens // num_reqs,
seq_lens=input_batch.seq_lens,
dcp_local_seq_lens=dcp_local_seq_lens,
max_seq_len=max_model_len,
block_tables=input_block_tables,
slot_mappings=slot_mappings,
kv_cache_config=kv_cache_config,
for_cudagraph_capture=True,
causal=causal,
)
return CapturedAttentionState(attn_metadata, slot_mappings_by_layer)
class DFlashCudaGraphManager(CudaGraphManager):
"""DFlash CudaGraphManager for the parallel-drafting query forward,
building its own attention metadata from scratch."""
def capture(
self,
forward_fn: Callable,
input_buffers: InputBuffers,
block_tables: BlockTables,
attn_groups: list[list[AttentionGroup]],
kv_cache_config: KVCacheConfig,
max_model_len: int,
causal: bool | Mapping[int, bool],
progress_bar_desc: str = "Capturing CUDA graphs",
) -> None:
def create_forward_fn(
desc: BatchExecutionDescriptor,
) -> tuple[Callable[[CUDAGraphMode], None], CapturedAttentionState]:
num_tokens = desc.num_tokens
num_reqs = desc.num_reqs or min(num_tokens, self.max_num_reqs)
num_tokens_across_dp = (
torch.full((self.dp_size,), num_tokens, dtype=torch.int32, device="cpu")
if self.dp_size > 1
else None
)
attn_state = _prepare_dflash_inputs_to_capture(
num_reqs,
num_tokens,
input_buffers,
block_tables,
attn_groups,
kv_cache_config,
max_model_len,
skip_attn=(desc.cg_mode == CUDAGraphMode.PIECEWISE),
causal=causal,
)
attn_metadata, slot_mappings = attn_state
return (
lambda cg_mode: forward_fn(
num_reqs,
num_tokens,
attn_metadata,
slot_mappings,
num_tokens_across_dp,
cg_mode,
),
attn_state,
)
super().capture(create_forward_fn, progress_bar_desc)
@@ -0,0 +1,764 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Mapping
from typing import Any
import numpy as np
import torch
import torch.nn as nn
from vllm.config import VllmConfig, replace
from vllm.config.compilation import CUDAGraphMode
from vllm.forward_context import BatchDescriptor, set_forward_context
from vllm.logger import init_logger
from vllm.triton_utils import tl, triton
from vllm.v1.attention.backend import AttentionCGSupport
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.cp_utils import cp_local_slot, prepare_dcp_local_seq_lens
from vllm.v1.worker.gpu.dp_utils import dispatch_cg_and_sync_dp
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.model_states.interface import ModelState
from vllm.v1.worker.gpu.spec_decode.dflash.cudagraph import DFlashCudaGraphManager
from vllm.v1.worker.gpu.spec_decode.dflash.utils import load_dflash_model
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.utils import get_parallel_drafting_token_id
from vllm.v1.worker.utils import AttentionGroup
logger = init_logger(__name__)
class DFlashSpeculator(DraftModelSpeculator):
_speculator_name = "DFlash" # For logging, so we can share methods with subclasses
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
)
# Multimodal inputs not currently supported.
self.supports_mm_inputs = False
# Each request emits exactly (bonus + N mask) query tokens per step.
self.num_query_per_req = 1 + self.num_speculative_steps
self.parallel_drafting_token_id = get_parallel_drafting_token_id(
self.draft_model_config.hf_config
)
from vllm.model_executor.models.qwen3_dflash import dflash_has_any_non_causal
self.requires_non_causal = dflash_has_any_non_causal(
self.draft_model_config.hf_config
)
# Whether the anchor query position is itself a prediction. DFlash default uses
# the anchor as the bonus token (only mask tokens predict); DSpark samples from
# the anchor and the N-1 mask token positions. See _prepare_dflash_inputs_kernel
dflash_config = (
getattr(self.draft_model_config.hf_config, "dflash_config", None) or {}
)
if dflash_config.get("sample_from_anchor", False):
raise ValueError(
"sample_from_anchor=True is not supported for DFlash. "
"DFlash uses a fixed 1+N query layout where the anchor "
"is the bonus token."
)
self.sample_from_anchor = False
# Context positions for the K/V precompute. Populated by
# prepare_dflash_inputs, and processed by the model's
# precompute_and_store_context_kv method. NOT captured by CUDA graphs.
self.context_positions = torch.zeros(
self.max_num_tokens, dtype=torch.int64, device=device
)
# Per-mask-token sampling buffers. Flattened from (num_reqs, num_spec_tokens).
max_num_sampled_tokens = self.max_num_reqs * self.num_speculative_steps
self.sample_indices = torch.zeros(
max_num_sampled_tokens, dtype=torch.int64, device=device
)
self.sample_pos = torch.zeros(
max_num_sampled_tokens, dtype=torch.int64, device=device
)
# -1 marks an inert sampling row. CUDA graph capture can execute the
# full buffer before a real batch has populated it, so zero would make
# every padding row scatter into request slot 0.
self.sample_idx_mapping = torch.full(
(max_num_sampled_tokens,), -1, dtype=torch.int32, device=device
)
# [0, 1, ..., N-1, 0, 1, ..., N-1, ...] -> the per-token column index into
# draft_logits[req, step, :].
self.sample_col = torch.arange(
self.num_speculative_steps, dtype=torch.int32, device=device
).repeat(self.max_num_reqs)
self.query_cudagraph_manager: DFlashCudaGraphManager | None = None
self.draft_kv_cache_group_id: int = -1
@property
def attn_vllm_config(self) -> VllmConfig:
# The draft's attention differs from the target's in causality.
return replace(
self.vllm_config,
attention_config=replace(
self.vllm_config.attention_config,
use_non_causal=self.requires_non_causal,
),
)
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
wants_full = cudagraph_mode.decode_mode() == CUDAGraphMode.FULL
supports_full = (
self.attn_cg_support.min_cg_support.value
>= AttentionCGSupport.UNIFORM_BATCH.value
)
if wants_full and not supports_full:
logger.warning(
"%s draft attention (%s) does not support full CUDA graphs; "
"running the draft eagerly.",
self._speculator_name,
self.attn_cg_support.min_cg_attn_backend,
)
# PIECEWISE cudagraphs are not supported for dflash.
if wants_full and supports_full:
cudagraph_mode = CUDAGraphMode.FULL_DECODE_ONLY
else:
cudagraph_mode = CUDAGraphMode.NONE
self.query_cudagraph_manager = DFlashCudaGraphManager(
self.vllm_config,
self.device,
cudagraph_mode,
decode_query_len=self.num_query_per_req,
)
def capture(self) -> None:
logger.info("Capturing model for %s speculator...", self._speculator_name)
# Padded sample rows must not scatter into a live request during capture.
self.sample_indices.zero_()
self.sample_pos.zero_()
self.sample_idx_mapping.fill_(-1)
assert self.query_cudagraph_manager is not None
self.query_cudagraph_manager.capture(
self._generate_draft,
self.input_buffers,
self.block_tables,
self.attn_groups,
self.kv_cache_config,
self.max_model_len,
causal=self._group_causal,
progress_bar_desc=f"Capturing {self._speculator_name.lower()} CUDA graphs",
)
def load_draft_model(
self,
target_model: nn.Module,
target_attn_layer_names: set[str],
) -> nn.Module:
return load_dflash_model(target_model, self.vllm_config)
def set_attn(
self,
model_state: ModelState,
kv_cache_config: KVCacheConfig,
block_tables: BlockTables,
target_input_buffers: InputBuffers,
target_attn_groups: list[list[AttentionGroup]],
) -> None:
super().set_attn(
model_state,
kv_cache_config,
block_tables,
target_input_buffers,
target_attn_groups,
)
self.draft_kv_cache_group_ids = [
gid for gid, g in enumerate(self.attn_groups) if g
]
assert self.draft_kv_cache_group_ids, "No draft attention groups found."
self.draft_kv_cache_group_id = self.draft_kv_cache_group_ids[0]
# Per-group context slot buffers for the precompute (one row per group).
self._context_slot_mappings = torch.zeros(
len(self.draft_kv_cache_group_ids),
self.max_num_tokens,
dtype=torch.int64,
device=self.device,
)
# Map each draft decoder layer to the index (within draft_kv_cache_group_ids)
# of the kv-cache group its cache belongs to. Models that share a single group
# leave this as None and share one context slot mapping.
self._layer_group_idx: list[int] | None = None
# Per-KV-group causal, falling back to whether the drafter is all-causal.
self._group_causal: dict[int, bool] | bool = not self.requires_non_causal
if hasattr(self.model, "get_draft_kv_cache_layer_names"):
layer_names = self.model.get_draft_kv_cache_layer_names()
name_to_gid = {
ln: gid
for gid, group in enumerate(kv_cache_config.kv_cache_groups)
for ln in group.layer_names
}
gid_to_idx = {gid: i for i, gid in enumerate(self.draft_kv_cache_group_ids)}
self._layer_group_idx = [
gid_to_idx[name_to_gid[name]] for name in layer_names
]
if hasattr(self.model, "get_draft_attn_causal"):
self._group_causal = {
name_to_gid[name]: layer_causal
for name, layer_causal in zip(
layer_names, self.model.get_draft_attn_causal()
)
}
@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,
) -> torch.Tensor:
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,
):
last_hidden_states = self.model(
input_ids=self.input_buffers.input_ids[:num_tokens],
positions=self.input_buffers.positions[:num_tokens],
inputs_embeds=None,
)
return last_hidden_states
def _generate_draft(
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 = CUDAGraphMode.NONE,
) -> None:
last_hidden_states = self._run_model(
num_tokens_padded,
attn_metadata,
slot_mappings,
num_tokens_across_dp,
cudagraph_runtime_mode,
)
num_sample = num_reqs * self.num_speculative_steps
sample_hidden_states = last_hidden_states[self.sample_indices[:num_sample]]
# sample_pos is the predicted token's position Q; verification keys
# Gumbel by the predecessor (Q-1). sample_draft adds +1, so pass Q-2.
draft_tokens = self.sample_draft(
sample_hidden_states,
self.sample_pos[:num_sample] - 2,
self.sample_idx_mapping[:num_sample],
self.temperature,
self.seeds,
self.sample_col[:num_sample],
self.draft_logits,
)
self.draft_tokens[:num_reqs] = draft_tokens.view(
num_reqs, self.num_speculative_steps
)
def _build_draft_attn_metadata(
self,
num_reqs: int,
num_reqs_padded: int,
num_tokens_padded: int,
seq_lens_cpu_upper_bound: torch.Tensor,
step: int,
num_query_per_req: int | None = None,
causal: bool | Mapping[int, bool] = False,
query_start_loc_np: np.ndarray | None = None,
dcp_local_seq_lens: torch.Tensor | None = None,
) -> dict[str, Any] | None:
if not self.draft_attn_layer_names:
return None
assert num_query_per_req is None # Omitted for DFlash, read from self instead
if dcp_local_seq_lens is None and self.block_tables.cp_size > 1:
prepare_dcp_local_seq_lens(
self.input_buffers.dcp_local_seq_lens,
self.input_buffers.seq_lens,
num_reqs,
self.block_tables.cp_size,
self.block_tables.cp_rank,
self.block_tables.cp_interleave,
)
dcp_local_seq_lens = self.input_buffers.dcp_local_seq_lens
return super()._build_draft_attn_metadata(
num_reqs,
num_reqs_padded,
num_tokens_padded,
seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound,
step=step,
num_query_per_req=self.num_query_per_req,
causal=causal,
query_start_loc_np=query_start_loc_np,
dcp_local_seq_lens=dcp_local_seq_lens,
)
@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,
num_tokens_across_dp: torch.Tensor | 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,
) -> torch.Tensor:
num_reqs = input_batch.num_reqs
num_target_tokens = input_batch.num_tokens
num_query_tokens = num_reqs * self.num_query_per_req
max_seq_len = input_batch.seq_lens_cpu_upper_bound[:num_reqs].max().item()
self.draft_max_seq_len = min(
max_seq_len + self.num_query_per_req, self.max_model_len
)
# NOTE: 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.
if aux_hidden_states:
hidden_states = self.model.combine_hidden_states(
torch.cat(aux_hidden_states, dim=-1)
)
else:
hidden_states = last_hidden_states
self.hidden_states[:num_target_tokens].copy_(hidden_states[:num_target_tokens])
if dummy_run and skip_attn_for_dummy_run:
# Memory profiling path: block_tables / kv_cache_config are not initialized.
# Since DFlash needs to build its own attention metadata, we must skip the
# preparation in this path and run a minimal forward pass.
self.model.precompute_and_store_context_kv(
self.hidden_states[:num_target_tokens],
self.context_positions[:num_target_tokens],
)
self._generate_draft(
num_reqs,
num_query_tokens,
attn_metadata=None,
slot_mappings=None,
num_tokens_across_dp=num_tokens_across_dp,
cudagraph_runtime_mode=CUDAGraphMode.NONE,
)
return self.draft_tokens[:num_reqs]
# The query slot mapping is written into the shared BlockTables slot_mappings.
# That buffer's address is what the captured CUDA graph reads from at replay.
assert self.draft_kv_cache_group_id >= 0
# Support multiple draft KV cache groups by preparing inputs once for each
for i, gid in enumerate(self.draft_kv_cache_group_ids):
prepare_dflash_inputs(
self.input_buffers,
self.block_tables.slot_mappings[gid],
self.context_positions,
self._context_slot_mappings[i],
self.sample_indices,
self.sample_pos,
self.sample_idx_mapping,
self.temperature,
self.seeds,
input_batch,
num_sampled,
num_rejected,
last_sampled,
next_prefill_tokens,
temperature,
seeds,
self.block_tables.input_block_tables[gid],
self.block_tables.kernel_block_sizes[gid],
self.block_tables.cp_rank,
self.block_tables.cp_size,
self.block_tables.cp_interleave,
self.parallel_drafting_token_id,
self.num_query_per_req,
self.num_speculative_steps,
self.max_num_reqs,
self.max_num_tokens,
self.max_model_len,
self.sample_from_anchor,
)
# Pre-insert context K/V into the cache. Runs eagerly outside the captured graph
# because the context shape varies per step. During dummy runs the block tables
# are placeholders, so we skip the cache write to avoid clobbering real entries.
# Each layer uses the context slots of its own kv-cache group.
if dummy_run:
context_slots: torch.Tensor | list[torch.Tensor | None] | None = None
elif self._layer_group_idx is not None:
context_slots = [
self._context_slot_mappings[gidx][:num_target_tokens]
for gidx in self._layer_group_idx
]
else:
context_slots = self._context_slot_mappings[0][:num_target_tokens]
self.model.precompute_and_store_context_kv(
self.hidden_states[:num_target_tokens],
self.context_positions[:num_target_tokens],
context_slots,
)
# Every DFlash step has exactly num_query_per_req tokens, so we can use FULL CGs
batch_desc, num_tokens_across_dp = dispatch_cg_and_sync_dp(
self.query_cudagraph_manager,
num_reqs,
num_query_tokens,
uniform_token_count=self.num_query_per_req,
dp_size=self.dp_size,
dp_rank=self.dp_rank,
need_eager=is_profile,
)
num_reqs_padded = batch_desc.num_reqs or num_reqs
num_tokens_padded = batch_desc.num_tokens
# Rebuild the draft attention metadata even when replaying the FULL
# graph so that any attention metadata builder state is updated.
draft_attn_metadata = self._build_draft_attn_metadata(
num_reqs=num_reqs,
num_reqs_padded=num_reqs_padded,
num_tokens_padded=num_tokens_padded,
seq_lens_cpu_upper_bound=input_batch.seq_lens_cpu_upper_bound,
step=self.num_query_per_req,
causal=self._group_causal,
)
draft_slot_mappings_by_layer = build_slot_mappings_by_layer(
self.block_tables.slot_mappings[:, :num_tokens_padded],
self.kv_cache_config,
)
if batch_desc.cg_mode == CUDAGraphMode.FULL:
assert self.query_cudagraph_manager is not None
self.query_cudagraph_manager.run_fullgraph(batch_desc)
else:
self._generate_draft(
num_reqs,
num_tokens_padded,
draft_attn_metadata,
draft_slot_mappings_by_layer,
num_tokens_across_dp=num_tokens_across_dp,
cudagraph_runtime_mode=batch_desc.cg_mode,
)
return self.draft_tokens[:num_reqs]
@triton.jit
def _prepare_dflash_inputs_kernel(
# Outputs
out_input_ids_ptr,
out_query_positions_ptr,
out_query_start_loc_ptr,
out_seq_lens_ptr,
out_query_slot_mapping_ptr,
out_context_positions_ptr,
out_context_slot_mapping_ptr,
out_sample_indices_ptr,
out_sample_pos_ptr,
out_sample_idx_mapping_ptr,
out_temperature_ptr,
out_seeds_ptr,
# Inputs from target batch
target_positions_ptr,
target_query_start_loc_ptr,
idx_mapping_ptr,
last_sampled_ptr,
next_prefill_tokens_ptr,
num_sampled_ptr,
num_rejected_ptr,
# Sampling params
temperature_ptr,
seeds_ptr,
# Block table for slot mapping lookup.
block_table_ptr,
block_table_stride,
# Scalars
parallel_drafting_token_id,
block_size,
num_query_per_req,
num_speculative_steps,
max_num_reqs,
max_num_tokens,
max_model_len,
cp_rank,
SAMPLE_FROM_ANCHOR: tl.constexpr,
PAD_SLOT_ID: tl.constexpr,
CP_SIZE: tl.constexpr,
CP_INTERLEAVE: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
req_idx = tl.program_id(0)
block_idx = tl.program_id(1)
num_reqs = tl.num_programs(0)
req_state_idx = tl.load(idx_mapping_ptr + req_idx)
ctx_start = tl.load(target_query_start_loc_ptr + req_idx)
ctx_end = tl.load(target_query_start_loc_ptr + req_idx + 1)
num_ctx = ctx_end - ctx_start
num_rejected = tl.load(num_rejected_ptr + req_idx)
valid_ctx_end = ctx_end - num_rejected
num_valid_ctx = valid_ctx_end - ctx_start
num_sampled = tl.load(num_sampled_ptr + req_idx)
if num_sampled > 0:
bonus_token = tl.load(last_sampled_ptr + req_state_idx).to(tl.int32)
else:
# Chunked prefilling: splice in the next prefill token.
bonus_token = tl.load(next_prefill_tokens_ptr + req_state_idx).to(tl.int32)
last_valid_pos = tl.load(target_positions_ptr + valid_ctx_end - 1)
query_base = req_idx * num_query_per_req
j = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
is_ctx = j < num_ctx
is_valid_ctx = j < num_valid_ctx
is_query = (j >= num_valid_ctx) & (j < num_valid_ctx + num_query_per_req)
query_off = j - num_valid_ctx
# --- Context positions / slots ---
ctx_pos_idx = ctx_start + tl.where(is_ctx, j, 0)
ctx_pos = tl.load(target_positions_ptr + ctx_pos_idx, mask=is_valid_ctx, other=0)
ctx_block_num = ctx_pos // (block_size * CP_SIZE)
ctx_block_num = tl.minimum(ctx_block_num, block_table_stride - 1)
ctx_block_id = tl.load(
block_table_ptr + req_idx * block_table_stride + ctx_block_num,
mask=is_valid_ctx,
other=0,
).to(tl.int64)
# Block 0 is the null block. Old sliding-window context positions can map
# to it after eviction; rejected suffix rows are invalid context as well.
# Neither kind of row may write draft KV into physical block 0.
ctx_resident = is_valid_ctx & (ctx_block_id != 0)
local_ctx_slot = cp_local_slot(
ctx_pos, ctx_block_id, block_size, cp_rank, CP_SIZE, CP_INTERLEAVE, PAD_SLOT_ID
)
ctx_slot = tl.where(
ctx_resident,
local_ctx_slot,
PAD_SLOT_ID,
)
# Stored over the full [0, num_ctx) span while the loads above are masked to
# [0, num_valid_ctx): the rejected suffix rows in between get position 0 and
# PAD_SLOT_ID. That is intentional — those rows write no KV and their
# positions are never consumed, but the span must stay fully initialized so
# a replayed graph cannot observe a stale value from an earlier batch.
tl.store(out_context_positions_ptr + ctx_start + j, ctx_pos, mask=is_ctx)
tl.store(out_context_slot_mapping_ptr + ctx_start + j, ctx_slot, mask=is_ctx)
# --- Query positions / input_ids / slots ---
query_pos = last_valid_pos + 1 + query_off
query_idx = query_base + query_off
is_bonus = is_query & (query_off == 0)
input_id = tl.where(is_bonus, bonus_token, parallel_drafting_token_id)
q_block_num = query_pos // (block_size * CP_SIZE)
q_block_num = tl.minimum(q_block_num, block_table_stride - 1)
q_block_id = tl.load(
block_table_ptr + req_idx * block_table_stride + q_block_num,
mask=is_query,
other=0,
).to(tl.int64)
# A null block is never a writable cache slot. This can occur when a
# sliding-window block table contains evicted/global padding entries.
q_resident = is_query & (q_block_id != 0)
local_q_slot = cp_local_slot(
query_pos,
q_block_id,
block_size,
cp_rank,
CP_SIZE,
CP_INTERLEAVE,
PAD_SLOT_ID,
)
q_slot = tl.where(
q_resident,
local_q_slot,
PAD_SLOT_ID,
)
tl.store(out_input_ids_ptr + query_idx, input_id, mask=is_query)
clamped_query_pos = tl.minimum(query_pos, max_model_len - 1)
tl.store(out_query_positions_ptr + query_idx, clamped_query_pos, mask=is_query)
tl.store(out_query_slot_mapping_ptr + query_idx, q_slot, mask=is_query)
# --- Sample indices / positions / idx_mapping ---
# When SAMPLE_FROM_ANCHOR (DSpark), so we sample at EVERY query position
# and each position k predicts the NEXT token (sampled position = query_pos + 1).
# Otherwise (DFlash default) the anchor is the bonus token and only the mask tokens
# at offsets > 0 are sampled from, each AT its own position.
sample_off = 0 if SAMPLE_FROM_ANCHOR else 1
is_sample = is_query & (query_off >= sample_off)
sample_idx = req_idx * num_speculative_steps + (query_off - sample_off)
sample_pos = query_pos + 1 if SAMPLE_FROM_ANCHOR else query_pos
tl.store(out_sample_indices_ptr + sample_idx, query_idx, mask=is_sample)
tl.store(out_sample_pos_ptr + sample_idx, sample_pos, mask=is_sample)
tl.store(out_sample_idx_mapping_ptr + sample_idx, req_state_idx, mask=is_sample)
if block_idx == 0:
tl.store(out_query_start_loc_ptr + req_idx, query_base)
# 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,
tl.minimum(last_valid_pos + 1 + num_query_per_req, max_model_len),
)
# Copy sampling state.
tl.store(
out_temperature_ptr + req_state_idx,
tl.load(temperature_ptr + req_state_idx),
)
tl.store(out_seeds_ptr + req_state_idx, tl.load(seeds_ptr + req_state_idx))
if req_idx == num_reqs - 1:
# Pad per-request buffers to max_num_reqs for CUDA graph safety.
last_query_end = num_reqs * num_query_per_req
for i in range(num_reqs, max_num_reqs + 1, BLOCK_SIZE):
block = i + tl.arange(0, BLOCK_SIZE)
mask = block < max_num_reqs + 1
tl.store(out_query_start_loc_ptr + block, last_query_end, mask=mask)
for i in range(num_reqs, max_num_reqs, BLOCK_SIZE):
block = i + tl.arange(0, BLOCK_SIZE)
mask = block < max_num_reqs
tl.store(out_seq_lens_ptr + block, 0, mask=mask)
# Padded sample slots point at query index 0 (a valid row in
# last_hidden_states) so CG replay never reads OOB. Padded
# sample idx mappings point to -1, which is ignored during
# sampling to prevent writing stale values to draft logits.
pad_start = num_reqs * num_speculative_steps
pad_end = max_num_reqs * num_speculative_steps
for i in range(pad_start, pad_end, BLOCK_SIZE):
block = i + tl.arange(0, BLOCK_SIZE)
mask = block < pad_end
tl.store(out_sample_indices_ptr + block, 0, mask=mask)
tl.store(out_sample_pos_ptr + block, 0, mask=mask)
tl.store(out_sample_idx_mapping_ptr + block, -1, mask=mask)
# Pad query slot mappings past num_query_tokens with PAD so the
# captured CG sees PAD slots (no K/V write) for replay sizes
# larger than the current request count.
q_pad_start = num_reqs * num_query_per_req
for i in range(q_pad_start, max_num_tokens, BLOCK_SIZE):
block = i + tl.arange(0, BLOCK_SIZE)
mask = block < max_num_tokens
tl.store(out_query_slot_mapping_ptr + block, PAD_SLOT_ID, mask=mask)
def prepare_dflash_inputs(
input_buffers: InputBuffers,
query_slot_mapping: torch.Tensor,
context_positions: torch.Tensor,
context_slot_mapping: torch.Tensor,
sample_indices: torch.Tensor,
sample_pos: torch.Tensor,
sample_idx_mapping: torch.Tensor,
temperature: torch.Tensor,
seeds: torch.Tensor,
input_batch: InputBatch,
# [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]
input_temperature: torch.Tensor,
# [max_num_reqs]
input_seeds: torch.Tensor,
# [max_num_reqs, max_num_blocks]
block_table: torch.Tensor,
block_size: int,
cp_rank: int,
cp_size: int,
cp_interleave: int,
parallel_drafting_token_id: int,
num_query_per_req: int,
num_speculative_steps: int,
max_num_reqs: int,
max_num_tokens: int,
max_model_len: int,
sample_from_anchor: bool = False,
) -> None:
num_reqs = input_batch.num_reqs
assert num_reqs > 0
# Cover the longest possible per-request span (ctx + query). Use the max
# per-request query length, not the total token count across the batch.
max_target_query_len = int(input_batch.num_scheduled_tokens.max())
max_tokens_per_req = max_target_query_len + num_query_per_req
BLOCK_SIZE = min(256, triton.next_power_of_2(max(1, max_tokens_per_req)))
num_blocks = triton.cdiv(max_tokens_per_req, BLOCK_SIZE)
_prepare_dflash_inputs_kernel[(num_reqs, num_blocks)](
input_buffers.input_ids,
input_buffers.positions,
input_buffers.query_start_loc,
input_buffers.seq_lens,
query_slot_mapping,
context_positions,
context_slot_mapping,
sample_indices,
sample_pos,
sample_idx_mapping,
temperature,
seeds,
input_batch.positions,
input_batch.query_start_loc,
input_batch.idx_mapping,
last_sampled,
next_prefill_tokens,
num_sampled,
num_rejected,
input_temperature,
input_seeds,
block_table,
block_table.stride(0),
parallel_drafting_token_id,
block_size,
num_query_per_req,
num_speculative_steps,
max_num_reqs,
max_num_tokens,
max_model_len,
cp_rank,
SAMPLE_FROM_ANCHOR=sample_from_anchor,
PAD_SLOT_ID=PAD_SLOT_ID,
CP_SIZE=cp_size,
CP_INTERLEAVE=cp_interleave,
BLOCK_SIZE=BLOCK_SIZE,
)
@@ -0,0 +1,101 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch.nn as nn
from vllm.config import VllmConfig, replace
from vllm.distributed.parallel_state import get_pp_group
from vllm.logger import init_logger
from vllm.model_executor.model_loader import get_model
from vllm.platforms import current_platform
from vllm.v1.worker.gpu.spec_decode.eagle.utils import (
_should_share,
get_target_lm_head,
)
logger = init_logger(__name__)
def load_dflash_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Module:
from vllm.compilation.backends import set_model_tag
from vllm.model_executor.models.qwen3_dflash import (
dflash_has_any_non_causal,
dflash_target_rope_is_neox_style,
)
speculative_config = vllm_config.speculative_config
assert speculative_config is not None
draft_model_config = speculative_config.draft_model_config
draft_cache_dtype = speculative_config.kv_cache_dtype
if (
draft_cache_dtype is None
and str(vllm_config.cache_config.cache_dtype).startswith("fp8")
and current_platform.is_cuda()
and current_platform.is_device_capability(70)
):
draft_cache_dtype = "auto"
logger.info_once(
"Using FP16 draft KV cache for SM70 DFlash while the target uses %s.",
vllm_config.cache_config.cache_dtype,
)
# The drafter must rotate Q/K the way its target does. Take that from the
# built target before super() constructs the draft.
is_neox_style = dflash_target_rope_is_neox_style(target_model)
if is_neox_style is not None:
draft_model_config.hf_config.is_neox_style = is_neox_style
# Select an attention backend that supports the drafter's attention: mixing
# a non-causal layer onto a causal-only backend would fail.
draft_vllm_config = replace(
vllm_config,
attention_config=replace(
vllm_config.attention_config,
use_non_causal=dflash_has_any_non_causal(draft_model_config.hf_config),
backend=speculative_config.attention_backend,
),
cache_config=(
replace(
vllm_config.cache_config,
cache_dtype=draft_cache_dtype,
)
if draft_cache_dtype is not None
else vllm_config.cache_config
),
)
with set_model_tag("dflash_head"):
dflash_model = get_model(
vllm_config=draft_vllm_config, model_config=draft_model_config
)
target_language_model = (
target_model.get_language_model()
if hasattr(target_model, "get_language_model")
else target_model
)
# MuseGlimmerForCausalLM marks its inner MuseGlimmerModel as the language
# model, so get_language_model() already returns the inner module and has
# no .model of its own.
target_inner = getattr(target_language_model, "model", target_language_model)
draft_inner = dflash_model.model
# Skip embedding sharing under PP — each rank owns its own embedding.
if get_pp_group().world_size == 1:
target_embed = getattr(target_inner, "embed_tokens", None) or getattr(
target_inner, "embedding", None
)
draft_embed = getattr(draft_inner, "embed_tokens", None)
if target_embed is not None and _should_share(
dflash_model, "has_own_embed_tokens", draft_embed, target_embed
):
if draft_embed is not None:
del draft_inner.embed_tokens
draft_inner.embed_tokens = target_embed
target_lm_head = get_target_lm_head(target_model, target_language_model)
draft_lm_head = getattr(dflash_model, "lm_head", None)
if target_lm_head is not None and _should_share(
dflash_model, "has_own_lm_head", draft_lm_head, target_lm_head
):
if draft_lm_head is not None:
del dflash_model.lm_head
dflash_model.lm_head = target_lm_head
return dflash_model
@@ -38,9 +38,17 @@ def get_eagle3_aux_layers_from_config(
if not (spec_config and spec_config.draft_model_config):
return None
hf_config = spec_config.draft_model_config.hf_config
if not hasattr(hf_config, "eagle_aux_hidden_state_layer_ids"):
return None
layer_ids = hf_config.eagle_aux_hidden_state_layer_ids
layer_ids = getattr(hf_config, "eagle_aux_hidden_state_layer_ids", None)
if not layer_ids:
dflash_config = getattr(hf_config, "dflash_config", None)
if dflash_config and isinstance(dflash_config, dict):
# DFlash checkpoint indices identify decoder layers, while target
# hidden-state capture uses layer boundaries.
layer_ids = [i + 1 for i in (dflash_config.get("target_layer_ids") or [])]
if not layer_ids:
target_layer_ids = getattr(hf_config, "target_layer_ids", None)
if target_layer_ids:
layer_ids = [i + 1 for i in target_layer_ids]
if layer_ids and isinstance(layer_ids, (list, tuple)):
return tuple(layer_ids)
return None
@@ -24,6 +24,13 @@ def _should_share(eagle: nn.Module, flag: str, draft, target) -> bool:
return torch.equal(w, target.weight)
def get_target_lm_head(target_model: nn.Module, target_language_model: nn.Module):
"""Return the language-model head for plain and conditional targets."""
return getattr(target_language_model, "lm_head", None) or getattr(
target_model, "lm_head", None
)
def load_eagle_model(target_model: nn.Module, vllm_config: VllmConfig) -> nn.Module:
from vllm.compilation.backends import set_model_tag
@@ -0,0 +1,354 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from abc import ABC, abstractmethod
from collections.abc import Mapping
from typing import Any
import numpy as np
import torch
import torch.nn as nn
from vllm.config import VllmConfig, get_layers_from_vllm_config
from vllm.config.compilation import CUDAGraphMode
from vllm.logger import init_logger
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.model_executor.models import supports_multimodal
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.gpu.attn_utils import (
build_attn_metadata,
init_attn_backend,
)
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.model_states.interface import ModelState
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
from vllm.v1.worker.utils import AttentionGroup
logger = init_logger(__name__)
class BaseSpeculator(ABC):
@abstractmethod
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
pass
@abstractmethod
def capture(self) -> None:
pass
@abstractmethod
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,
# [num_prefill_lookahead, max_num_reqs]
next_prefill_tokens: torch.Tensor,
# [max_num_reqs]
temperature: torch.Tensor,
# [max_num_reqs]
seeds: torch.Tensor,
num_tokens_across_dp: torch.Tensor | 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,
) -> torch.Tensor:
pass
class DraftModelSpeculator(BaseSpeculator):
def __init__(self, vllm_config: VllmConfig, device: torch.device):
self.vllm_config = vllm_config
self.device = device
assert vllm_config.speculative_config is not None
self.speculative_config = vllm_config.speculative_config
self.method = self.speculative_config.method
self.num_speculative_steps = self.speculative_config.num_speculative_tokens
self.draft_model_config = self.speculative_config.draft_model_config
self.scheduler_config = vllm_config.scheduler_config
self.max_num_reqs = self.scheduler_config.max_num_seqs
self.max_num_tokens = self.scheduler_config.max_num_batched_tokens
self.max_model_len = vllm_config.model_config.max_model_len
self.draft_max_seq_len = self.max_model_len
# We need to get the hidden size from the draft model config because
# the draft model's hidden size can be different from the target model's
# hidden size (e.g., Llama 3.3 70B).
self.hidden_size = self.draft_model_config.get_hidden_size()
# Widen for HC-multiplexed residuals (e.g. DeepSeek V4 feeds the MTP
# draft the target's pre-hc_head (T, hc_mult * hidden_size) residual).
# Non-HC models default to hc_mult=1 and are unaffected.
hc_mult = getattr(self.draft_model_config.hf_config, "hc_mult", 1)
self.hidden_size = self.hidden_size * hc_mult
self.vocab_size = self.draft_model_config.get_vocab_size()
self.dtype = vllm_config.model_config.dtype
self.use_fp64_gumbel = vllm_config.model_config.use_fp64_gumbel
self.use_local_argmax_reduction = (
self.speculative_config.use_local_argmax_reduction
)
# DP configuration
self.dp_size = vllm_config.parallel_config.data_parallel_size
self.dp_rank = vllm_config.parallel_config.data_parallel_rank
self.input_buffers = InputBuffers(
max_num_reqs=self.max_num_reqs,
max_num_tokens=self.max_num_tokens,
device=device,
)
self.idx_mapping = torch.zeros(
self.max_num_reqs, dtype=torch.int32, device=device
)
self.temperature = torch.zeros(
self.max_num_reqs, dtype=torch.float32, device=device
)
self.seeds = torch.zeros(self.max_num_reqs, dtype=torch.int64, device=device)
self.draft_tokens = torch.zeros(
self.max_num_reqs,
self.num_speculative_steps,
dtype=torch.int64,
device=device,
)
self.arange = torch.arange(
self.max_num_reqs + 1, dtype=torch.int32, device="cpu"
)
self.draft_logits: torch.Tensor | None = None
if self.speculative_config.draft_sample_method == "probabilistic":
# Pre-temperature logits, cached from the previous decode step.
self.draft_logits = torch.zeros(
self.max_num_reqs,
self.num_speculative_steps,
self.vocab_size,
dtype=vllm_config.model_config.head_dtype,
device=device,
)
self.supports_mm_inputs = False
@abstractmethod
def load_draft_model(
self,
target_model: nn.Module,
target_attn_layer_names: set[str],
) -> nn.Module:
pass
def load_model(self, target_model: nn.Module) -> None:
target_attn_layer_names = set(
get_layers_from_vllm_config(
self.vllm_config,
AttentionLayerBase, # type: ignore[type-abstract]
).keys()
)
self.model = self.load_draft_model(target_model, target_attn_layer_names)
self._validate_local_argmax_reduction()
all_attn_layers = set[str](
get_layers_from_vllm_config(
self.vllm_config,
AttentionLayerBase, # type: ignore[type-abstract]
).keys()
)
self.draft_attn_layer_names = all_attn_layers - target_attn_layer_names
target_supports_mm = MULTIMODAL_REGISTRY.supports_multimodal_inputs(
self.vllm_config.model_config
)
draft_supports_mm = supports_multimodal(self.model)
self.supports_mm_inputs = target_supports_mm and draft_supports_mm
if target_supports_mm and not draft_supports_mm:
logger.warning_once(
"Draft model %s does not support external multimodal embeddings. "
"Embeddings from the target model will not be passed to the "
"drafter; using text-only draft inputs instead.",
type(self.model).__name__,
)
@property
def attn_vllm_config(self) -> VllmConfig:
"""Config for the draft's attention metadata builders. Overridden by
speculators whose attention mode differs from the target's."""
return self.vllm_config
def set_attn(
self,
model_state: ModelState,
kv_cache_config: KVCacheConfig,
block_tables: BlockTables,
target_input_buffers: InputBuffers,
target_attn_groups: list[list[AttentionGroup]],
) -> None:
self.model_state = model_state
self.kv_cache_config = kv_cache_config
self.attn_groups, self.attn_cg_support, _ = init_attn_backend(
kv_cache_config,
self.attn_vllm_config,
self.device,
active_layer_names=self.draft_attn_layer_names,
)
self.block_tables = block_tables
# The target model runner's buffers and attention groups. Draft
# prefill reuses the target model's attention metadata, so its
# cudagraph capture must build dummy metadata through the same
# builders and buffers.
self.target_input_buffers = target_input_buffers
self.target_attn_groups = target_attn_groups
def _build_draft_attn_metadata(
self,
num_reqs: int,
num_reqs_padded: int,
num_tokens_padded: int,
seq_lens_cpu_upper_bound: torch.Tensor,
step: int,
num_query_per_req: int = 1,
causal: bool | Mapping[int, bool] = True,
query_start_loc_np: np.ndarray | None = None,
dcp_local_seq_lens: torch.Tensor | None = None,
) -> dict[str, Any] | None:
if query_start_loc_np is not None:
# Non-uniform query layout (e.g. multi-module MTP's mixed
# prefill/decode queries); num_query_per_req is ignored.
query_start_loc_cpu = torch.empty(num_reqs_padded + 1, dtype=torch.int32)
query_start_loc_cpu[: num_reqs + 1] = torch.from_numpy(
query_start_loc_np[: num_reqs + 1]
)
query_start_loc_cpu[num_reqs:] = query_start_loc_cpu[num_reqs]
max_query_len = int(
(query_start_loc_cpu[1:] - query_start_loc_cpu[:-1]).max()
)
else:
# Uniform query: query_start_loc[i] = min(i, num_reqs) * num_query_per_req.
# Clamp keeps the series non-decreasing past num_reqs, which some
# attention backends require.
query_start_loc_cpu = (
torch.clamp(self.arange[: num_reqs_padded + 1], max=num_reqs)
* num_query_per_req
)
max_query_len = num_query_per_req
block_tables = [
x[:num_reqs_padded] for x in self.block_tables.input_block_tables
]
slot_mappings = self.block_tables.slot_mappings[:, :num_tokens_padded]
draft_seq_lens_cpu_upper_bound = torch.zeros(
num_reqs_padded, dtype=torch.int32, device="cpu"
)
torch.add(
seq_lens_cpu_upper_bound[:num_reqs],
step,
out=draft_seq_lens_cpu_upper_bound[:num_reqs],
)
draft_seq_lens_cpu_upper_bound[:num_reqs].clamp_(max=self.max_model_len)
attn_metadata = build_attn_metadata(
attn_groups=self.attn_groups,
num_reqs=num_reqs_padded,
num_tokens=num_tokens_padded,
query_start_loc_gpu=self.input_buffers.query_start_loc[
: num_reqs_padded + 1
],
query_start_loc_cpu=query_start_loc_cpu,
max_query_len=max_query_len,
seq_lens=self.input_buffers.seq_lens[:num_reqs_padded],
dcp_local_seq_lens=(
None
if dcp_local_seq_lens is None
else dcp_local_seq_lens[:num_reqs_padded]
),
max_seq_len=self.draft_max_seq_len,
block_tables=block_tables,
slot_mappings=slot_mappings,
kv_cache_config=self.kv_cache_config,
causal=causal,
seq_lens_cpu_upper_bound=draft_seq_lens_cpu_upper_bound,
)
return attn_metadata
def _validate_local_argmax_reduction(self) -> None:
if not self.use_local_argmax_reduction:
return
if self.speculative_config.draft_sample_method == "probabilistic":
raise ValueError(
"use_local_argmax_reduction is not compatible with "
"draft_sample_method='probabilistic'."
)
if not hasattr(self.model, "get_top_tokens"):
raise ValueError(
"use_local_argmax_reduction is enabled but draft model "
f"{self.model.__class__.__name__} does not implement "
"get_top_tokens()."
)
logger.info(
"Using local argmax reduction for draft token generation "
"(communication: O(2*tp_size) vs O(vocab_size))."
)
def _greedy_sample_draft(self, hidden_states: torch.Tensor) -> torch.Tensor:
if self.use_local_argmax_reduction:
return self.model.get_top_tokens(hidden_states)
logits = self.model.compute_logits(hidden_states)
return logits.argmax(dim=-1)
def sample_draft(
self,
hidden_states: torch.Tensor,
positions: torch.Tensor,
idx_mapping: torch.Tensor,
temperature: torch.Tensor,
seeds: torch.Tensor,
draft_step: torch.Tensor,
draft_logits: torch.Tensor | None,
) -> torch.Tensor:
if draft_logits is not None:
logits = self.model.compute_logits(hidden_states)
# NOTE(woosuk): We must add 1 to the positions to match the Gumbel noise
# used for draft and target sampling.
return gumbel_sample(
logits,
idx_mapping,
temperature,
seeds,
positions + 1,
apply_temperature=True,
output_processed_logits=draft_logits,
output_processed_logits_col=draft_step,
use_fp64=self.use_fp64_gumbel,
)
return self._greedy_sample_draft(hidden_states)
def _copy_request_inputs(
self,
num_reqs: int,
# [num_reqs]
idx_mapping: torch.Tensor,
# [max_num_reqs]
temperature: torch.Tensor,
# [max_num_reqs]
seeds: torch.Tensor,
) -> None:
# Copy temperature, seeds, and idx mapping to the pre-allocated buffers.
# NOTE(woosuk): For draft sampling, we only consider the temperature
# and ignore the other sampling parameters such as top_k and top_p,
# for simplicity and performance.
# While this may slightly degrade the acceptance rate, it does not
# affect the output distribution after rejection sampling.
self.temperature.copy_(temperature)
self.seeds.copy_(seeds)
self.idx_mapping[:num_reqs].copy_(idx_mapping)
# idx_mapping for CG padded requests points to -1, which is ignored
# during sampling to prevent writing stale values to draft logits.
self.idx_mapping[num_reqs:].fill_(-1)
+15
View File
@@ -45,3 +45,18 @@ class DraftTokensHandler:
# This case only happens when async scheduling is disabled.
draft_token_ids = [[-1] * self.num_draft_tokens for _ in self.req_ids]
return DraftTokenIds(self.req_ids, draft_token_ids)
def get_parallel_drafting_token_id(hf_config) -> int:
"""Resolve the mask token used by a parallel-drafting checkpoint."""
dflash_config = getattr(hf_config, "dflash_config", None) or {}
if "mask_token_id" in dflash_config:
return int(dflash_config["mask_token_id"])
if hasattr(hf_config, "pard_token"):
return int(hf_config.pard_token)
if hasattr(hf_config, "ptd_token_id"):
return int(hf_config.ptd_token_id)
raise ValueError(
"Model config must specify dflash_config.mask_token_id, pard_token, "
"or ptd_token_id for parallel drafting."
)
+2 -2
View File
@@ -1499,7 +1499,7 @@ class GPUModelRunner(
elif self.speculative_config.use_dspark():
self.drafter = DSparkProposer(self.vllm_config, self.device, self)
self.use_aux_hidden_state_outputs = True
elif self.speculative_config.use_dflash():
elif self.speculative_config.use_dflash_ddtree():
self.drafter = DFlashProposer(self.vllm_config, self.device, self)
self.use_aux_hidden_state_outputs = (
self.drafter.eagle3_use_aux_hidden_state
@@ -9495,7 +9495,7 @@ class GPUModelRunner(
elif (
spec_config.use_eagle()
or spec_config.use_dflash()
or spec_config.use_dflash_ddtree()
or spec_config.uses_draft_model()
):
assert isinstance(