[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests

- Drop dead model modules, keeping files live imports require
- Remove anthropic, cohere, codegen entrypoints and batch STT modes
- Delete unused attention backends, MoE experts, and NPU/XPU util leaves
- Strip dead third_party trees and ROCm leaves with no CUDA path
- Remove mooncake EC connectors: dependency missing since branch base
- Re-audit verified by full import sweep and Qwen3.5 smoke test

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-19 00:20:48 +07:00
co-authored by Hinata
parent 6a95f62e2f
commit 81074e94a3
940 changed files with 11 additions and 380533 deletions
@@ -1,156 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
import pytest
from tests.evals.gsm8k.gsm8k_eval import evaluate_gsm8k_offline
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ...utils import compute_acceptance_len, compute_acceptance_rate
REGRESSION_TOLERANCE = 0.95
@dataclass(frozen=True)
class DSparkCorrectnessConfig:
model: str
draft_model: str
reference_accuracy: float
reference_acceptance_rate: float
reference_acceptance_len: float
num_speculative_tokens: int = 7
max_model_len: int = 4096
max_num_seqs: int | None = None
num_questions: int = 1319
max_tokens: int = 256
use_chat_completions: bool = False
chat_template_kwargs: dict[str, object] | None = None
attention_backend: str | None = None
gpu_memory_utilization: float = 0.92
enforce_eager: bool = False
disable_flashinfer_sampler: bool = False
language_model_only: bool = False
# References from 12 full GSM8K runs at temperature 1.0: accuracy 0.782-0.814,
# acceptance rate 0.418-0.434, acceptance length 3.928-4.037.
QWEN3_DSPARK_DEEPSPEC = DSparkCorrectnessConfig(
model="Qwen/Qwen3-4B-FP8",
draft_model="deepseek-ai/dspark_qwen3_4b_block7",
reference_accuracy=0.801,
reference_acceptance_rate=0.428,
reference_acceptance_len=3.994,
attention_backend="FLASH_ATTN",
)
# References from five 200-question runs at temperature 1.0: accuracy
# 0.900-0.955, acceptance rate 0.578-0.595, acceptance length 5.044-5.167.
GEMMA4_DSPARK_DEEPSPEC = DSparkCorrectnessConfig(
model="RedHatAI/gemma-4-12B-it-NVFP4",
draft_model="deepseek-ai/dspark_gemma4_12b_block7",
reference_accuracy=0.92,
reference_acceptance_rate=0.58,
reference_acceptance_len=5.0,
max_num_seqs=32,
num_questions=200,
use_chat_completions=True,
gpu_memory_utilization=0.85,
enforce_eager=True,
disable_flashinfer_sampler=True,
language_model_only=True,
)
# Reference from 200 GSM8K questions at temperature 1.0.
QWEN3_6_DSPARK_SPECULATORS = DSparkCorrectnessConfig(
model="RedHatAI/Qwen3.6-35B-A3B-NVFP4",
draft_model="RedHatAI/Qwen3.6-35B-A3B-speculator.dspark",
reference_accuracy=0.85,
reference_acceptance_rate=0.41,
reference_acceptance_len=4.25,
num_speculative_tokens=8,
max_num_seqs=32,
num_questions=200,
use_chat_completions=True,
chat_template_kwargs={"enable_thinking": False},
gpu_memory_utilization=0.85,
language_model_only=True,
)
@pytest.mark.parametrize(
"config",
[
pytest.param(QWEN3_DSPARK_DEEPSPEC, id="qwen3-deepspec"),
pytest.param(GEMMA4_DSPARK_DEEPSPEC, id="gemma4-deepspec"),
pytest.param(QWEN3_6_DSPARK_SPECULATORS, id="qwen3.6-speculators"),
],
)
def test_dspark_correctness_and_acceptance_rate(
monkeypatch: pytest.MonkeyPatch,
config: DSparkCorrectnessConfig,
vllm_runner,
):
"""Guard GSM8K accuracy and acceptance metrics for DSpark models."""
if config.disable_flashinfer_sampler:
monkeypatch.setenv("VLLM_USE_FLASHINFER_SAMPLER", "0")
speculative_config = {
"method": "dspark",
"model": config.draft_model,
"num_speculative_tokens": config.num_speculative_tokens,
"draft_sample_method": "probabilistic",
}
if config.attention_backend is not None and current_platform.is_cuda():
speculative_config["attention_backend"] = config.attention_backend
runner_config = {
"block_size": None,
"trust_remote_code": True,
"speculative_config": speculative_config,
"max_model_len": config.max_model_len,
"gpu_memory_utilization": config.gpu_memory_utilization,
"enforce_eager": config.enforce_eager,
"enable_chunked_prefill": None,
"enable_prefix_caching": False,
"disable_log_stats": False,
"compilation_config": CompilationConfig(),
}
if config.max_num_seqs is not None:
runner_config["max_num_seqs"] = config.max_num_seqs
if config.language_model_only:
runner_config["language_model_only"] = True
with vllm_runner(config.model, **runner_config) as spec_runner:
spec_llm = spec_runner.llm
results = evaluate_gsm8k_offline(
spec_llm,
num_questions=config.num_questions,
max_tokens=config.max_tokens,
temperature=1.0,
use_chat_completions=config.use_chat_completions,
chat_template_kwargs=config.chat_template_kwargs,
)
accuracy = results["accuracy"]
metrics = spec_llm.get_metrics()
acceptance_rate = compute_acceptance_rate(metrics)
acceptance_len = compute_acceptance_len(metrics)
context = f"DSpark target={config.model}, draft={config.draft_model}"
metrics_summary = (
f"gsm8k_accuracy={accuracy:.3f}, "
f"acceptance_rate={acceptance_rate:.3f}, "
f"acceptance_len={acceptance_len:.3f}"
)
print(f"{context}: {metrics_summary}")
assert accuracy >= config.reference_accuracy * REGRESSION_TOLERANCE, (
f"{context}: {metrics_summary}"
)
assert (
acceptance_rate >= config.reference_acceptance_rate * REGRESSION_TOLERANCE
), f"{context}: {metrics_summary}"
assert (
acceptance_len >= config.reference_acceptance_len * REGRESSION_TOLERANCE
), f"{context}: {metrics_summary}"
@@ -1,56 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig
from ...utils import compute_acceptance_len, get_test_prompts
@single_gpu_only
def test_synthetic_acceptance_rate(vllm_runner):
"""Verify that synthetic rejection sampling produces an acceptance
length close to the requested mean acceptance length."""
num_spec_tokens = 3
expected_acceptance_len = 1.875
tolerance = 0.15
with vllm_runner(
"meta-llama/Llama-3.2-1B-Instruct",
block_size=None,
trust_remote_code=True,
speculative_config={
"method": "eagle3",
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
"num_speculative_tokens": num_spec_tokens,
"max_model_len": 2048,
"rejection_sample_method": "synthetic",
"synthetic_acceptance_length": expected_acceptance_len,
},
max_model_len=2048,
enforce_eager=True,
enable_chunked_prefill=None,
disable_log_stats=False,
compilation_config=CompilationConfig(),
) as spec_runner:
spec_llm = spec_runner.llm
test_prompts = get_test_prompts(mm_enabled=False, num_prompts=50)
spec_llm.chat(
test_prompts,
SamplingParams(temperature=0, max_tokens=64, ignore_eos=True),
)
metrics = spec_llm.get_metrics()
acceptance_len = compute_acceptance_len(metrics)
print(
f"Synthetic acceptance length: {acceptance_len:.3f}"
f" (expected={expected_acceptance_len:.3f},"
f" tolerance=±{tolerance})"
)
assert abs(acceptance_len - expected_acceptance_len) <= tolerance, (
f"Synthetic acceptance length {acceptance_len:.3f} is not within"
f" ±{tolerance} of expected {expected_acceptance_len:.3f}"
)
@@ -1,102 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from vllm import SamplingParams
from vllm.config import CompilationConfig
from ..utils import compute_acceptance_len
def load_and_process_dataset(data_name: str):
from datasets import load_dataset
if data_name == "gsm8k":
dataset = load_dataset("openai/gsm8k", "main", split="test")
prompt_fmt = (
"{question}\nPlease reason step by step,"
" and put your final answer within \\boxed{{}}."
)
dataset = dataset.map(lambda x: {"turns": [prompt_fmt.format(**x)]})
elif data_name == "mt-bench":
dataset = load_dataset("HuggingFaceH4/mt_bench_prompts", split="train")
dataset = dataset.map(lambda x: {"turns": x["prompt"]})
elif data_name == "humaneval":
dataset = load_dataset("openai/openai_humaneval", split="test")
prompt_fmt = (
"Write a solution to the following problem and make sure"
" that it passes the tests:\n```python\n{prompt}\n```"
)
dataset = dataset.map(lambda x: {"turns": [prompt_fmt.format(**x)]})
return dataset
def run_acceptance_length_eval(
monkeypatch: pytest.MonkeyPatch,
vllm_runner,
spec_config: dict[str, Any],
expected_acceptance_lengths: dict[str, float],
chat_template_kwargs: dict[str, Any],
use_mrv2: bool,
):
"""E2E acceptance-rate validation for speculative decoding.
Drives one or more datasets (keyed in ``expected_acceptance_lengths``)
through the spec decode engine and asserts the mean acceptance length
stays within tolerance of the reference figure for each dataset.
"""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1" if use_mrv2 else "0")
runner_config = spec_config.copy()
model = runner_config.pop("model")
runner_config.setdefault("block_size", None)
runner_config.setdefault("enable_chunked_prefill", None)
runner_config.setdefault("compilation_config", CompilationConfig())
with vllm_runner(model, **runner_config) as spec_runner:
spec_llm = spec_runner.llm
# MT-Bench has 80 prompts and HumanEval has 164; truncate GSM8K.
max_prompts_per_dataset = 200
tokenizer = spec_llm.get_tokenizer()
for dataset_name, expected_len in expected_acceptance_lengths.items():
dataset = load_and_process_dataset(dataset_name)
prev_metrics = None
acceptance_lengths = []
for i in range(min(max_prompts_per_dataset, len(dataset))):
user_content = dataset[i]["turns"][0]
prompt_text = tokenizer.apply_chat_template(
[{"role": "user", "content": user_content}],
tokenize=False,
add_generation_prompt=True,
**chat_template_kwargs,
)
# Greedy (temp=0) so acceptance length is deterministic and comparable
# across runs.
spec_llm.generate(
[prompt_text],
SamplingParams(temperature=0, max_tokens=2048),
use_tqdm=False,
)
current_metrics = spec_llm.get_metrics()
acceptance_len = compute_acceptance_len(current_metrics, prev_metrics)
prev_metrics = current_metrics
acceptance_lengths.append(acceptance_len)
mean_acceptance_length = sum(acceptance_lengths) / len(acceptance_lengths)
# Fairly tight tolerance of 95% against the reference figures,
# watching for regressions. Can be relaxed if test is flaky but be sure to
# check for genuine issues such as #40727.
expected_len = expected_len * 0.95
print(
f"acceptance_len for {dataset_name}: {mean_acceptance_length:.2f}"
f" (expected at least {expected_len:.2f})"
)
assert mean_acceptance_length >= expected_len, (
f"acceptance_len for {dataset_name} is below expected threshold: "
f"{mean_acceptance_length:.2f} < {expected_len:.2f}"
)
@@ -1,96 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for sync-free speculative decoding with async scheduling."""
import pytest
# Test configurations: (model, spec_model, method, num_spec_tokens, backend_env)
SPEC_DECODE_CONFIGS = [
pytest.param(
"meta-llama/Llama-3.2-1B-Instruct",
"nm-testing/Llama3_2_1B_speculator.eagle3",
"eagle3",
2,
id="eagle3-llama",
),
pytest.param(
"eagle618/deepseek-v3-random",
"eagle618/eagle-deepseek-v3-random",
"eagle",
2,
id="eagle-mla-deepseek",
),
pytest.param(
"Qwen/Qwen3.5-0.8B-Base",
"Qwen/Qwen3.5-0.8B-Base",
"mtp",
1,
id="mtp-qwen3_5-hybrid",
),
]
@pytest.mark.parametrize(
"model,spec_model,method,num_spec_tokens",
SPEC_DECODE_CONFIGS,
)
def test_no_sync_with_spec_decode(
model: str,
spec_model: str,
method: str,
num_spec_tokens: int,
monkeypatch,
vllm_runner,
):
"""Test generation while the worker rejects unintended GPU-CPU syncs."""
monkeypatch.setenv("VLLM_GPU_SYNC_CHECK", "error")
from vllm import SamplingParams
from vllm.config import CompilationConfig
# Qwen3.5 is a VLM; without this, profile_run runs the ViT warmup
# and peaks well above the 18GB MIG slice used by one of the CI lanes.
# This test only exercises text generation, so the vision tower is
# never needed.
extra_kwargs: dict = {}
if "Qwen3.5" in model:
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
with vllm_runner(
model,
block_size=None,
trust_remote_code=False,
max_model_len=256,
speculative_config={
"method": method,
"num_speculative_tokens": num_spec_tokens,
"model": spec_model,
},
enforce_eager=True,
async_scheduling=True,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as runner:
llm = runner.llm
# Assert async scheduling is actually active before running inference.
assert llm.llm_engine.vllm_config.scheduler_config.async_scheduling, (
f"Expected async_scheduling=True for spec decode, got False. "
f"method={method}, target={model}, draft={spec_model}"
)
outputs = llm.generate(
["Hello, my name is"],
SamplingParams(temperature=0, max_tokens=10),
)
assert len(outputs) == 1, (
f"{method} target={model}: expected one request output, got {len(outputs)}"
)
assert outputs[0].outputs, (
f"{method} target={model}: request output has no completion candidates"
)
assert outputs[0].outputs[0].text, (
f"{method} target={model}: generated completion text is empty"
)
@@ -1,423 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
import pytest
from tests.utils import multi_gpu_only, single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig, VllmConfig, replace
from vllm.config.kernel import MoEBackend
from vllm.engine.arg_utils import EngineArgs
from vllm.platforms import current_platform
from vllm.v1.spec_decode.draft_model import DraftModelProposer
from ..utils import (
Messages,
compute_acceptance_len,
compute_acceptance_rate,
evaluate_llm_for_gsm8k,
get_instruct_coder_messages,
get_test_prompts,
greedy_sampling,
stochastic_sampling,
)
@dataclass
class ArgsTest:
target_model: str
draft_model: str
sampling_config: SamplingParams
num_speculative_tokens: int
expected_acceptance_rate: float
expected_acceptance_len: float
expected_gsm8k_accuracy: float = 0.0 # skip by default
# Defaults
enforce_eager: bool = True
parallel_drafting: bool = False
target_tensor_parallel_size: int = 1
draft_tensor_parallel_size: int = 1
max_model_len: int = 2048
gpu_memory_utilization: float = 0.5
dataset: str = "test_prompts"
# Doubling 100 to 200 reduces sampling standard error by about 29%.
num_prompts: int = 200
def get_messages(dataset: str, n: int) -> list[Messages]:
if dataset == "test_prompts":
return get_test_prompts(mm_enabled=False, num_prompts=n)
if dataset == "likaixin/InstructCoder":
return get_instruct_coder_messages(n=n)
raise NotImplementedError(f"Dataset '{dataset}' not implemented")
def some_high_acceptance_metrics() -> dict:
return {
"sampling_config": greedy_sampling(),
"num_speculative_tokens": 3,
"expected_acceptance_len": 3.4, # ref: 3.75
"expected_acceptance_rate": 0.8, # ref: 0.9
}
cases = [
# Same model for draft and target, greedy sampling.
ArgsTest(
target_model="Qwen/Qwen3-0.6B",
draft_model="Qwen/Qwen3-0.6B",
sampling_config=greedy_sampling(),
num_speculative_tokens=3, # K
expected_acceptance_len=0.98 * (3 + 1), # epsilon discount of K + 1
expected_acceptance_rate=0.98, # slight epsilon
expected_gsm8k_accuracy=0.25, # ref: 35-40%
),
# Smaller draft model, stochastic sampling.
ArgsTest(
target_model="Qwen/Qwen3-1.7B",
draft_model="Qwen/Qwen3-0.6B",
sampling_config=stochastic_sampling(),
num_speculative_tokens=3,
expected_acceptance_len=3.4, # ref: 3.7
expected_acceptance_rate=0.80, # ref: 0.90
expected_gsm8k_accuracy=0.5, # ref: 60%. Note gsm8k always runs greedy sampling
),
]
@pytest.mark.parametrize("args", cases)
@pytest.mark.parametrize("enforce_eager", [True, False])
@single_gpu_only
def test_draft_model_correctness(args: ArgsTest, enforce_eager: bool, vllm_runner):
args.enforce_eager = enforce_eager
assert_draft_model_correctness(args, vllm_runner)
@single_gpu_only
def test_draft_model_realistic_example(vllm_runner):
args = ArgsTest(
target_model="Qwen/Qwen3-1.7B",
draft_model="Qwen/Qwen3-0.6B",
dataset="likaixin/InstructCoder",
num_speculative_tokens=3,
sampling_config=greedy_sampling(),
enforce_eager=False,
expected_acceptance_len=2.6, # ref: 2.86
expected_acceptance_rate=0.5, # ref: 0.62
)
assert_draft_model_correctness(args, vllm_runner)
@single_gpu_only
def test_draft_model_parallel_drafting(vllm_runner):
args = ArgsTest(
target_model="Qwen/Qwen3-1.7B",
draft_model="amd/PARD-Qwen3-0.6B",
dataset="likaixin/InstructCoder",
num_speculative_tokens=3,
sampling_config=greedy_sampling(),
parallel_drafting=True,
enforce_eager=False,
expected_acceptance_len=2.3, # ref: 2.52
expected_acceptance_rate=0.4, # ref: 0.51
)
assert_draft_model_correctness(args, vllm_runner)
@pytest.mark.parametrize(
"models",
[
# target_model, draft_model
("Qwen/Qwen3-1.7B-FP8", "Qwen/Qwen3-0.6B"), # target quantized
("Qwen/Qwen3-1.7B", "Qwen/Qwen3-0.6B-FP8"), # draft quantized
],
ids=["target_quantized", "draft_quantized"],
)
@pytest.mark.parametrize("enforce_eager", [True, False])
@single_gpu_only
def test_draft_model_quantization(
models: tuple[str, str], enforce_eager: bool, vllm_runner
):
tgt_model, draft_model = models
sd_case = ArgsTest(
target_model=tgt_model,
draft_model=draft_model,
**some_high_acceptance_metrics(),
enforce_eager=enforce_eager,
)
assert_draft_model_correctness(sd_case, vllm_runner)
@single_gpu_only
def test_draft_model_transformers_backend(vllm_runner):
"""Ensure that Attention prefixes don't collide between the target and
draft models when both models use the Transformers modelling backend."""
sd_case = ArgsTest(
target_model="allenai/OLMo-2-0425-1B-Instruct",
draft_model="allenai/OLMo-2-0425-1B-Instruct",
sampling_config=greedy_sampling(),
num_speculative_tokens=3,
expected_acceptance_len=0.98 * (3 + 1), # epsilon discount of K + 1
expected_acceptance_rate=0.98, # slight epsilon
)
assert_draft_model_correctness(sd_case, vllm_runner)
@multi_gpu_only(num_gpus=2)
def test_draft_model_tensor_parallelism(vllm_runner):
"""Ensure spec decode works when running with TP > 1."""
sd_case = ArgsTest(
target_model="Qwen/Qwen3-1.7B",
target_tensor_parallel_size=2,
draft_model="Qwen/Qwen3-0.6B",
draft_tensor_parallel_size=2,
**some_high_acceptance_metrics(),
enforce_eager=False,
expected_gsm8k_accuracy=0.5,
)
assert_draft_model_correctness(sd_case, vllm_runner)
@multi_gpu_only(num_gpus=2)
def test_draft_model_engine_args_tensor_parallelism():
"""Ensure the vllm_config for the draft model is created correctly,
and independently of the target model (quantization, TP, etc.)"""
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B-FP8", # <<< tgt quantized
tensor_parallel_size=2,
speculative_config={
"model": "Qwen/Qwen3-0.6B", # <<< draft not quantized
"method": "draft_model",
"num_speculative_tokens": 3,
"draft_tensor_parallel_size": 1, # <<< valid arg name
},
)
target_config: VllmConfig = engine_args.create_engine_config()
assert target_config.parallel_config.tensor_parallel_size == 2
assert target_config.quant_config.get_name() == "fp8"
speculative_config = target_config.speculative_config
draft_config: VllmConfig = replace(
target_config,
quant_config=None,
parallel_config=replace(
speculative_config.draft_parallel_config,
rank=target_config.parallel_config.rank,
),
model_config=speculative_config.draft_model_config,
)
assert draft_config.parallel_config.tensor_parallel_size == 1
assert draft_config.quant_config is None
@pytest.mark.cpu_test
@pytest.mark.parametrize("dcp_size", [1, 2])
def test_draft_model_inherits_target_dcp_config(monkeypatch, dcp_size):
monkeypatch.setattr(current_platform, "device_count", lambda: 16)
target_config = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=16,
decode_context_parallel_size=dcp_size,
cp_kv_cache_interleave_size=16,
dcp_comm_backend="ag_rs",
distributed_executor_backend="mp",
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
},
).create_engine_config()
proposer = object.__new__(DraftModelProposer)
proposer.vllm_config = target_config
proposer.speculative_config = target_config.speculative_config
draft_config = proposer._create_draft_vllm_config()
draft_parallel = draft_config.parallel_config
assert draft_parallel.decode_context_parallel_size == dcp_size
assert draft_parallel.cp_kv_cache_interleave_size == 16
assert draft_parallel.dcp_comm_backend == "ag_rs"
assert (
draft_parallel.dcp_q_replicate == target_config.parallel_config.dcp_q_replicate
)
assert draft_parallel is not target_config.parallel_config
assert target_config.parallel_config.decode_context_parallel_size == dcp_size
def _apply_draft_moe_backend(vllm_config: VllmConfig) -> VllmConfig:
"""Replicate SpecDecodeBaseProposer._create_draft_vllm_config logic
so we can test it without instantiating a full proposer."""
spec_cfg = vllm_config.speculative_config
if spec_cfg.moe_backend is not None:
return replace(
vllm_config,
kernel_config=replace(
vllm_config.kernel_config,
moe_backend=spec_cfg.moe_backend,
),
)
return vllm_config
def _platform_moe_backend(monkeypatch: pytest.MonkeyPatch) -> MoEBackend:
if current_platform.is_rocm():
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
monkeypatch.setenv("VLLM_ROCM_USE_AITER_MOE", "1")
return "aiter"
if current_platform.is_cuda():
return "flashinfer_trtllm"
return "auto"
def test_draft_model_moe_backend_override(monkeypatch: pytest.MonkeyPatch):
"""When moe_backend is set in speculative_config, the draft VllmConfig
should use it while the target keeps its own setting."""
target_moe_backend = _platform_moe_backend(monkeypatch)
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
moe_backend=target_moe_backend,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
"moe_backend": "triton",
},
)
tgt_config: VllmConfig = engine_args.create_engine_config()
assert tgt_config.kernel_config.moe_backend == target_moe_backend
assert tgt_config.speculative_config.moe_backend == "triton"
draft_config = _apply_draft_moe_backend(tgt_config)
assert draft_config.kernel_config.moe_backend == "triton"
# Target config must be unaffected.
assert tgt_config.kernel_config.moe_backend == target_moe_backend
def test_draft_model_moe_backend_inherits_target(monkeypatch: pytest.MonkeyPatch):
"""When moe_backend is not set in speculative_config, the draft should
inherit the target's moe_backend."""
target_moe_backend = _platform_moe_backend(monkeypatch)
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
moe_backend=target_moe_backend,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
},
)
tgt_config: VllmConfig = engine_args.create_engine_config()
assert tgt_config.kernel_config.moe_backend == target_moe_backend
assert tgt_config.speculative_config.moe_backend is None
draft_config = _apply_draft_moe_backend(tgt_config)
assert draft_config.kernel_config.moe_backend == target_moe_backend
assert draft_config is tgt_config
def test_draft_model_moe_backend_default_auto():
"""When neither target nor draft set moe_backend explicitly, both should
default to 'auto'."""
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
},
)
tgt_config: VllmConfig = engine_args.create_engine_config()
assert tgt_config.kernel_config.moe_backend == "auto"
assert tgt_config.speculative_config.moe_backend is None
draft_config = _apply_draft_moe_backend(tgt_config)
assert draft_config.kernel_config.moe_backend == "auto"
assert draft_config is tgt_config
def test_draft_model_engine_args_rejects_invalid_tp_argname():
"""The user should pass "draft_tensor_parallel_size" rather than
"tensor_parallel_size". We enforce this with validation."""
engine_args = EngineArgs(
model="Qwen/Qwen3-1.7B",
tensor_parallel_size=1,
speculative_config={
"model": "Qwen/Qwen3-0.6B",
"method": "draft_model",
"num_speculative_tokens": 3,
"tensor_parallel_size": 1, # <<< invalid arg name
},
)
with pytest.raises(ValueError, match="draft_tensor_parallel_size"):
engine_args.create_engine_config()
def assert_draft_model_correctness(args: ArgsTest, vllm_runner):
"""Compare the outputs using and not using speculative decoding.
In the greedy decoding case, the outputs must match EXACTLY."""
test_prompts: list[Messages] = get_messages(
dataset=args.dataset, n=args.num_prompts
)
with vllm_runner(
args.target_model,
block_size=None,
trust_remote_code=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
speculative_config={
"model": args.draft_model,
"method": "draft_model",
"num_speculative_tokens": args.num_speculative_tokens,
"max_model_len": args.max_model_len,
"enforce_eager": args.enforce_eager,
"draft_tensor_parallel_size": args.draft_tensor_parallel_size,
"parallel_drafting": args.parallel_drafting,
},
max_num_seqs=100, # limit cudagraph capture runtime
max_model_len=args.max_model_len,
gpu_memory_utilization=args.gpu_memory_utilization,
tensor_parallel_size=args.target_tensor_parallel_size,
enforce_eager=args.enforce_eager,
disable_log_stats=False, # enables get_metrics()
) as spec_runner:
spec_llm = spec_runner.llm
# we don't check the outputs, only check the metrics
spec_llm.chat(test_prompts, args.sampling_config)
metrics = spec_llm.get_metrics()
acceptance_rate: float = compute_acceptance_rate(metrics)
acceptance_len: float = compute_acceptance_len(metrics)
# Need to evaluate after getting metrics to avoid polluting the AR
evaluate_llm_for_gsm8k(
spec_llm, expected_accuracy_threshold=args.expected_gsm8k_accuracy
)
print(
f"spec-decode: target={args.target_model}, draft={args.draft_model}, "
f"temperature={args.sampling_config.temperature:.2f}, "
f"acceptance_rate={acceptance_rate:.2f}, "
f"acceptance_len={acceptance_len:.2f}, "
)
context = (
f"draft_model target={args.target_model}, draft={args.draft_model}, "
f"eager={args.enforce_eager}, "
f"acceptance_rate={acceptance_rate:.3f}, "
f"acceptance_len={acceptance_len:.3f}"
)
assert acceptance_rate >= args.expected_acceptance_rate, (
f"{context}; expected acceptance_rate >= "
f"{args.expected_acceptance_rate:.3f}"
)
assert acceptance_len >= args.expected_acceptance_len, (
f"{context}; expected acceptance_len >= {args.expected_acceptance_len:.3f}"
)
# draft_model supports async scheduling; assert it is active by default.
has_async = spec_llm.llm_engine.vllm_config.scheduler_config.async_scheduling
assert has_async, "Expected async_scheduling=True for draft_model spec decode"
@@ -1,134 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""This script contains:
1. test lora with speculative decoding for batch inference
"""
import pytest
import torch
import vllm.envs as envs
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.lora.request import LoRARequest
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
from ..utils import assert_request_outputs_match
LORA_TEST_PROMPT_MAP: dict[str, str] = {}
LORA_TEST_PROMPT_MAP["premjatin/qwen-linear-algebra-coder"] = """
### INSTRUCTION:
You are an AI assistant that generates Python code to solve linear
algebra problems.
### PROBLEM:
Find the eigenvalues and eigenvectors of the following 3x3 matrix:
[[3, 2, 0],
[2, 3, 0],
[0, 0, 2]]
### OUTPUT FORMAT (STRICT):
Numbers should be represented as integers only.
### PYTHON SOLUTION:
"""
SEED = 42
@pytest.mark.parametrize(
"model_setup",
[
(
"eagle3",
"Qwen/Qwen3-1.7B",
"AngelSlim/Qwen3-1.7B_eagle3",
"premjatin/qwen-linear-algebra-coder",
1,
)
],
)
@pytest.mark.skipif(
not current_platform.is_cuda_alike(), reason="Requires CUDA or ROCm"
)
def test_batch_inference_correctness(
monkeypatch: pytest.MonkeyPatch,
model_setup: tuple[str, str, str, str, int],
vllm_runner,
):
"""Compare the outputs of a LLM with only Lora and a LLM with both SD and Lora.
Should be the same and no failure when doing batch inference.
model_setup: (method, model_name, spec_model_name, lora_path, tp_size)
"""
with monkeypatch.context() as m:
m.setenv("VLLM_BATCH_INVARIANT", "1")
m.setattr(envs, "VLLM_BATCH_INVARIANT", True)
set_random_seed(SEED)
m.setattr(torch.backends.cudnn, "benchmark", False)
m.setattr(torch.backends.cudnn, "deterministic", True)
method, model_name, spec_model_name, lora_path, tp_size = model_setup
prompts = [LORA_TEST_PROMPT_MAP[lora_path]] * 100
lora_request = LoRARequest("adapter", 1, lora_path)
sampling_params = SamplingParams(
temperature=0.0, top_p=1.0, top_k=-1, seed=SEED, max_tokens=128
)
# without speculative decoding
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
max_model_len=2048,
max_num_seqs=4,
enable_lora=True,
max_loras=1,
max_cpu_loras=1,
max_lora_rank=16,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as ref_runner:
ref_outputs = ref_runner.llm.generate(
prompts, sampling_params, lora_request=lora_request
)
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
speculative_config={
"method": method,
"model": spec_model_name,
"num_speculative_tokens": 3,
"max_model_len": 2048,
},
max_model_len=2048,
max_num_seqs=4,
enable_lora=True,
max_loras=1,
max_cpu_loras=1,
max_lora_rank=16,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as spec_runner:
lora_spec_outputs = spec_runner.llm.generate(
prompts, sampling_params, lora_request=lora_request
)
# Under greedy verification, the spec-decode output should equal the
# non-spec output (modulo FP noise from the target's verify-path matmul
# running at seqlen num_speculative_tokens+1 vs 1). 90% leaves slack.
assert_request_outputs_match(
ref_outputs,
lora_spec_outputs,
required_matches=int(0.90 * len(ref_outputs)) + 1,
context=(
f"LoRA + {method}: target={model_name}, draft={spec_model_name}, "
f"adapter={lora_path}"
),
)
@@ -1,59 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from tests.utils import multi_gpu_test
from tests.v1.e2e.spec_decode.utils import compute_acceptance_len
from vllm import LLM, SamplingParams
from vllm.distributed import cleanup_dist_env_and_memory
MODEL = "meta-llama/Llama-3.2-1B-Instruct"
DRAFT = "nm-testing/Llama3_2_1B_speculator.eagle3"
PROMPTS = [
"The capital of France is",
"2 + 2 equals",
"In one word, the color of the sky is",
"Q: If a train travels 60 miles in 1.5 hours, what is its average speed?\nA:",
]
ACCEPTANCE_TOLERANCE = 0.95
def _run(pp_size: int) -> float:
llm = LLM(
model=MODEL,
tensor_parallel_size=1,
pipeline_parallel_size=pp_size,
max_model_len=512,
gpu_memory_utilization=0.45,
disable_log_stats=False,
compilation_config={"cudagraph_mode": "FULL_AND_PIECEWISE"},
speculative_config={
"method": "eagle3",
"model": DRAFT,
"num_speculative_tokens": 3,
},
)
try:
llm.generate(
PROMPTS,
SamplingParams(temperature=0.0, max_tokens=32, ignore_eos=True),
)
acceptance = compute_acceptance_len(llm.get_metrics())
assert acceptance > 1
return acceptance
finally:
del llm
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
@multi_gpu_test(num_gpus=4)
def test_eagle3_pipeline_parallel_acceptance():
baseline = _run(1)
for pp_size in (2, 4):
parallel = _run(pp_size)
assert parallel >= baseline * ACCEPTANCE_TOLERANCE, (
f"PP={pp_size} acceptance regressed: {parallel:.3f} < "
f"{baseline:.3f} * {ACCEPTANCE_TOLERANCE}"
)
@@ -1,172 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import (
get_attn_backend_list_based_on_platform,
single_gpu_only,
)
from vllm import SamplingParams
from vllm.platforms import current_platform
from .utils import _run_eagle_correctness
@single_gpu_only
@pytest.mark.skipif(
current_platform.is_device_capability_family(100),
reason="DeepSeek head_dim=192 not supported on SM100/SM110 (Blackwell)",
)
@pytest.mark.parametrize(
[
"model_setup",
"mm_enabled",
"enable_chunked_prefill",
"model_impl",
"expected_accuracy_threshold",
],
[
(
(
"eagle",
"eagle618/deepseek-v3-random",
"eagle618/eagle-deepseek-v3-random",
1,
),
False,
False,
"auto",
0.0,
),
],
ids=["deepseek_eagle"],
)
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
def test_eagle_correctness_light(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, str, int],
mm_enabled: bool,
expected_accuracy_threshold: float,
enable_chunked_prefill: bool,
model_impl: str,
attn_backend: str,
vllm_runner,
):
_run_eagle_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
enable_chunked_prefill,
model_impl,
attn_backend,
vllm_runner,
)
@single_gpu_only
@pytest.mark.parametrize(
[
"model_setup",
"mm_enabled",
"enable_chunked_prefill",
"model_impl",
"expected_accuracy_threshold",
],
[
(
("eagle3", "Qwen/Qwen3-8B", "AngelSlim/Qwen3-8B_eagle3", 1),
False,
False,
"auto",
0.8,
),
pytest.param(
("eagle3", "Qwen/Qwen3-8B", "AngelSlim/Qwen3-8B_eagle3", 1),
False,
False,
"transformers",
0.8,
# TODO(hmellor): figure out why memory usage is so high
marks=pytest.mark.skipif(
not current_platform.is_rocm(),
reason="Feature is experimental and uses too much memory in CUDA CI",
),
),
(
(
"eagle3",
"Qwen/Qwen3-VL-8B-Instruct",
"taobao-mnn/Qwen3-VL-8B-Instruct-Eagle3",
1,
),
False,
False,
"auto",
0.8,
),
pytest.param(
(
"eagle3",
"Qwen/Qwen2.5-VL-7B-Instruct",
"Rayzl/qwen2.5-vl-7b-eagle3-sgl",
1,
),
False,
False,
"auto",
0.7,
# TODO: Re-measure the reference threshold when re-enabling this case.
# Text-only mode starts but loses target correctness with ROCm/TRITON;
# full multimodal profiling currently fails during engine startup.
marks=pytest.mark.skip(
reason="Qwen2.5-VL Eagle3 is not yet reliable in this test setup"
),
),
(
(
"eagle3",
"meta-llama/Llama-3.1-8B-Instruct",
"yuhuili/EAGLE3-LLaMA3.1-Instruct-8B",
1,
),
False,
False,
"auto",
0.7,
),
],
ids=[
"qwen3_eagle3",
"qwen3_eagle3-transformers",
"qwen3_vl_eagle3",
"qwen2_5_vl_eagle3",
"llama3_eagle3",
],
)
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
def test_eagle_correctness_medium(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, str, int],
mm_enabled: bool,
expected_accuracy_threshold: float,
enable_chunked_prefill: bool,
model_impl: str,
attn_backend: str,
vllm_runner,
):
_run_eagle_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
enable_chunked_prefill,
model_impl,
attn_backend,
vllm_runner,
)
-135
View File
@@ -1,135 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ..utils import (
_skip_if_insufficient_gpus_for_tp,
assert_request_outputs_match,
evaluate_llm_for_gsm8k,
get_test_prompts,
)
def _run_eagle_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, str, int],
mm_enabled: bool,
expected_accuracy_threshold: float,
enable_chunked_prefill: bool,
model_impl: str,
attn_backend: str,
vllm_runner,
):
"""Compare the outputs of an original LLM and a speculative LLM
which should be the same when using eagle speculative decoding.
"""
method, model_name, spec_model_name, tp_size = model_setup
_skip_if_insufficient_gpus_for_tp(tp_size)
test_prompts = get_test_prompts(mm_enabled)
extra_kwargs: dict[str, Any] = {}
if not mm_enabled and "Qwen3-VL" in model_name:
# These cases only exercise text generation. Avoid profiling an unused
# vision tower, which adds substantial memory to both reference runs.
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
if "Llama-4-Scout" in model_name and attn_backend == "FLASH_ATTN":
if current_platform.is_rocm():
print(
"FLASH_ATTN for spec_decode not supported on "
"ROCm currently. Changing to FLEX_ATTENTION backend."
)
attention_config = {"backend": "FLEX_ATTENTION"}
else:
attention_config = None
else:
attention_config = {"backend": attn_backend}
if attn_backend == "TRITON_ATTN" and not current_platform.is_rocm():
pytest.skip(
"TRITON_ATTN does not support "
"multi-token eagle spec decode on current platform"
)
with monkeypatch.context() as m:
m.setenv("VLLM_MLA_DISABLE", "1")
if attn_backend == "ROCM_AITER_FA" and current_platform.is_rocm():
if "deepseek" in model_name.lower():
m.setenv("VLLM_ROCM_USE_AITER", "1")
m.delenv("VLLM_MLA_DISABLE", raising=False)
attention_config = {"backend": "ROCM_AITER_MLA"}
else:
m.setenv("VLLM_ROCM_USE_AITER", "1")
max_model_len = 2048
max_num_batched_tokens = 128 if enable_chunked_prefill else max_model_len
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=False,
max_model_len=max_model_len,
tensor_parallel_size=tp_size,
attention_config=attention_config,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as ref_runner:
evaluate_llm_for_gsm8k(
ref_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
speculative_config={
"method": method,
"model": spec_model_name,
"num_speculative_tokens": 3,
"max_model_len": max_model_len,
},
max_model_len=max_model_len,
max_num_batched_tokens=max_num_batched_tokens,
enable_chunked_prefill=enable_chunked_prefill,
model_impl=model_impl,
attention_config=attention_config,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as spec_runner:
# EAGLE/EAGLE3 supports async scheduling by default.
has_async = (
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
)
assert has_async, (
f"Expected async scheduling for {method}: target={model_name}, "
f"draft={spec_model_name}, backend={attn_backend}; got {has_async}"
)
evaluate_llm_for_gsm8k(
spec_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
assert_request_outputs_match(
ref_outputs,
spec_outputs,
required_matches=int(0.6 * len(ref_outputs)) + 1,
context=(
f"{method} target={model_name}, draft={spec_model_name}, "
f"backend={attn_backend}"
),
)
@@ -1,110 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ..utils import (
_skip_if_insufficient_gpus_for_tp,
assert_request_outputs_match,
evaluate_llm_for_gsm8k,
get_test_prompts,
)
def check_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
"""Compare the outputs of a original LLM and a speculative LLM
which should be the same when using MTP speculative decoding. Due to some variance
in the engine, it is possible for some outputs to differ, so we expect that at least
6/10 output tokens match exactly, and that the GSM8k accuracy is above a precomputed
reference threshold for each model.
"""
method, model_name, tp_size, draft_model = model_setup
_skip_if_insufficient_gpus_for_tp(tp_size)
# Generate test prompts inside the function instead of using fixture
test_prompts = get_test_prompts(mm_enabled)
with monkeypatch.context() as m:
m.setenv("VLLM_MLA_DISABLE", "1")
attn_backend = "TRITON_ATTN" if current_platform.is_rocm() else "auto"
# Skip multimodal profiling for models that don't need it in this test.
extra_kwargs: dict[str, Any] = {}
if "Qwen3.5" in model_name:
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "video": 0}
elif "gemma-4" in model_name:
extra_kwargs["limit_mm_per_prompt"] = {"image": 0, "audio": 0}
with vllm_runner(
model_name,
block_size=None,
max_model_len=2048,
tensor_parallel_size=tp_size,
trust_remote_code=True,
attention_backend=attn_backend,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as ref_runner:
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
evaluate_llm_for_gsm8k(
ref_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
speculative_config: dict[str, Any] = {
"method": method,
"num_speculative_tokens": 1,
"max_model_len": 2048,
}
if draft_model is not None:
speculative_config["model"] = draft_model
speculative_config["num_speculative_tokens"] = 2
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=True,
tensor_parallel_size=tp_size,
speculative_config=speculative_config,
max_model_len=2048,
attention_backend=attn_backend,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**extra_kwargs,
) as spec_runner:
# MTP supports async scheduling by default.
has_async = (
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
)
assert has_async, (
f"Expected async scheduling for {method}: target={model_name}, "
f"draft={draft_model}; got {has_async}"
)
evaluate_llm_for_gsm8k(
spec_runner.llm,
expected_accuracy_threshold=expected_accuracy_threshold,
)
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
# Heuristic: expect at least 80% of the prompts to match exactly
# Upon failure, inspect the outputs to check for inaccuracy.
assert_request_outputs_match(
ref_outputs,
spec_outputs,
required_matches=int(0.8 * len(ref_outputs)) + 1,
context=f"{method} target={model_name}, draft={draft_model}",
)
@@ -1,44 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.platforms import current_platform
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
pytest.param(
("mtp", "ZixiQi/DeepSeek-V3-4layers-MTP-FP8", 1, None),
False,
0.0,
marks=pytest.mark.skipif(
current_platform.is_device_capability_family(100),
reason="DeepSeek MTP: TRTLLM MoE top_k check fails on Blackwell",
),
), # dummy model
],
ids=["deepseek"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@@ -1,39 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
(
("mtp", "google/gemma-4-E4B-it", 1, "google/gemma-4-E4B-it-assistant"),
False,
0.50,
), # gemma4 MTP with assistant model, ref: ~62%
],
ids=["gemma4-e4b"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@@ -1,36 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
# Reference accuracy: 65%-70%.
(("mtp", "XiaomiMiMo/MiMo-7B-Base", 1, None), False, 0.5),
],
ids=["mimo"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@@ -1,149 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.platforms import current_platform
from ...utils import (
assert_request_outputs_match,
compute_acceptance_len,
get_test_prompts,
)
from .._correctness import check_mtp_correctness
@pytest.mark.parametrize(
["model_setup", "mm_enabled", "expected_accuracy_threshold"],
[
(
("mtp", "Qwen/Qwen3.5-0.8B-Base", 1, None),
False,
0.20,
), # hybrid + MTP, ref: ~34%-35%
],
ids=["qwen3_5-hybrid"],
)
@single_gpu_only
def test_mtp_correctness(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_setup: tuple[str, str, int, str | None],
mm_enabled: bool,
expected_accuracy_threshold: float,
vllm_runner,
):
check_mtp_correctness(
monkeypatch,
sampling_config,
model_setup,
mm_enabled,
expected_accuracy_threshold,
vllm_runner,
)
@single_gpu_only
def test_mtp_draft_lm_head_quantization(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
vllm_runner,
):
"""A quantized draft copy of the shared lm_head only changes drafting:
greedy outputs match stock MTP and acceptance stays within 10%."""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
prompts = get_test_prompts(mm_enabled=False)
results = {}
# NVFP4 needs a CUDA W4A16 kernel.
quants = (None, "fp8", "nvfp4") if current_platform.is_cuda() else (None, "fp8")
for quant in quants:
with vllm_runner(
"Qwen/Qwen3.5-0.8B-Base",
block_size=None,
enable_chunked_prefill=None,
max_model_len=2048,
limit_mm_per_prompt={"image": 0, "video": 0},
speculative_config={
"method": "mtp",
"num_speculative_tokens": 3,
"draft_lm_head_quantization": quant,
},
disable_log_stats=False,
) as runner:
outputs = runner.llm.chat(prompts, sampling_config)
results[quant] = (outputs, compute_acceptance_len(runner.llm.get_metrics()))
ref_outputs, ref_al = results.pop(None)
for quant, (outputs, al) in results.items():
assert_request_outputs_match(
ref_outputs,
outputs,
# Not bit-exact: a different acceptance length changes the target's
# verify batch shapes, which can flip a near-tied greedy token.
required_matches=int(0.8 * len(ref_outputs)) + 1,
context=f"draft_lm_head_quantization={quant}",
)
assert al >= 0.9 * ref_al, (
f"{quant}: acceptance length {al:.3f} vs {ref_al:.3f}"
)
@single_gpu_only
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="nvfp4 needs a CUDA W4A16 kernel"
)
def test_mtp_draft_lm_head_quantization_survives_sleep_and_reload(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
vllm_runner,
):
"""The quantized draft head is derived from the target head: it must come
back intact after a level 1 sleep and be re-derived after a target weight
reload, so outputs and acceptance match the run before."""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
prompts = get_test_prompts(mm_enabled=False)
with vllm_runner(
"Qwen/Qwen3.5-0.8B-Base",
block_size=None,
enable_chunked_prefill=None,
max_model_len=2048,
limit_mm_per_prompt={"image": 0, "video": 0},
speculative_config={
"method": "mtp",
"num_speculative_tokens": 3,
"draft_lm_head_quantization": "nvfp4",
},
enable_sleep_mode=True,
disable_log_stats=False,
) as runner:
llm = runner.llm
def run():
before = llm.get_metrics()
outputs = llm.chat(prompts, sampling_config)
return outputs, compute_acceptance_len(llm.get_metrics(), before)
ref_outputs, ref_al = run()
llm.sleep(level=1)
llm.wake_up()
outputs, al = run()
assert_request_outputs_match(
ref_outputs,
outputs,
required_matches=int(0.8 * len(ref_outputs)) + 1,
context="after level 1 sleep",
)
assert al == pytest.approx(ref_al, rel=0.03)
llm.collective_rpc("reload_weights")
outputs, al = run()
assert_request_outputs_match(
ref_outputs,
outputs,
required_matches=int(0.8 * len(ref_outputs)) + 1,
context="after weight reload",
)
assert al == pytest.approx(ref_al, rel=0.03)
@@ -1,115 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig, CUDAGraphMode
from vllm.platforms import current_platform
from ...utils import get_spec_decode_metric_value
PLACEHOLDER_REGRESSION_MODEL = "Qwen/Qwen3.5-0.8B-Base"
PLACEHOLDER_REGRESSION_PROMPT = "The capital of France is"
PLACEHOLDER_REGRESSION_MAX_TOKENS = 16
PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID = 42
PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS = 3
@pytest.mark.parametrize(
"cudagraph_mode",
[CUDAGraphMode.PIECEWISE, CUDAGraphMode.FULL_AND_PIECEWISE],
ids=["piecewise", "full-and-piecewise"],
)
@single_gpu_only
def test_mtp_rejected_placeholders_match_greedy_token_ids(
cudagraph_mode: CUDAGraphMode,
vllm_runner,
):
"""Rejected MTP padding must not alter the non-speculative token stream."""
common_kwargs: dict[str, Any] = {
"block_size": None,
"max_model_len": 256,
"max_num_seqs": 1,
"trust_remote_code": True,
"enable_chunked_prefill": None,
"limit_mm_per_prompt": {"image": 0, "video": 0},
"attention_backend": ("TRITON_ATTN" if current_platform.is_rocm() else "auto"),
}
sampling_params = SamplingParams(
temperature=0.0,
max_tokens=PLACEHOLDER_REGRESSION_MAX_TOKENS,
ignore_eos=True,
allowed_token_ids=[PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID],
logprobs=1,
)
def generate_token_ids(runner) -> tuple[int, ...]:
outputs = runner.llm.generate([PLACEHOLDER_REGRESSION_PROMPT], sampling_params)
assert outputs and outputs[0].outputs, "Expected one completion"
token_ids = tuple(outputs[0].outputs[0].token_ids)
assert len(token_ids) == PLACEHOLDER_REGRESSION_MAX_TOKENS
return token_ids
def compilation_config() -> CompilationConfig:
return CompilationConfig(
cudagraph_mode=cudagraph_mode,
cudagraph_capture_sizes=[1, PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS + 1],
)
with vllm_runner(
PLACEHOLDER_REGRESSION_MODEL,
compilation_config=compilation_config(),
**common_kwargs,
) as ref_runner:
ref_mode = (
ref_runner.llm.llm_engine.vllm_config.compilation_config.cudagraph_mode
)
assert ref_mode == cudagraph_mode
ref_token_ids = generate_token_ids(ref_runner)
expected_token_ids = (PLACEHOLDER_REGRESSION_ALLOWED_TOKEN_ID,) * (
PLACEHOLDER_REGRESSION_MAX_TOKENS
)
assert ref_token_ids == expected_token_ids
with vllm_runner(
PLACEHOLDER_REGRESSION_MODEL,
speculative_config={
"method": "mtp",
"num_speculative_tokens": PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS,
"max_model_len": 256,
"rejection_sample_method": "synthetic",
"synthetic_acceptance_rates": [0.0]
* PLACEHOLDER_REGRESSION_NUM_SPEC_TOKENS,
},
disable_log_stats=False,
compilation_config=compilation_config(),
**common_kwargs,
) as spec_runner:
spec_mode = (
spec_runner.llm.llm_engine.vllm_config.compilation_config.cudagraph_mode
)
assert spec_mode == cudagraph_mode
spec_token_ids = generate_token_ids(spec_runner)
metrics = spec_runner.llm.get_metrics()
num_drafts = get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_drafts"
)
num_draft_tokens = get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_draft_tokens"
)
num_accepted_tokens = get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_accepted_tokens"
)
assert num_drafts > 0, "MTP drafter did not run"
assert num_draft_tokens > 0, "MTP drafter did not produce draft tokens"
assert num_accepted_tokens == 0, "Synthetic sampler accepted a draft token"
assert spec_token_ids == ref_token_ids, (
f"MTP changed greedy token ids under {cudagraph_mode.name}:\n"
f" reference={ref_token_ids}\n"
f" speculative={spec_token_ids}"
)
@@ -1,173 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig
from vllm.platforms import current_platform
from ..utils import (
evaluate_llm_for_gsm8k,
get_spec_decode_metric_value,
get_test_prompts,
)
@pytest.fixture
def disable_vllm_compile_cache_on_rocm(request: pytest.FixtureRequest) -> None:
if current_platform.is_rocm():
request.getfixturevalue("disable_vllm_compile_cache")
@pytest.mark.parametrize(
"speculative_config",
[
{
"method": "ngram",
"prompt_lookup_max": 5,
"prompt_lookup_min": 3,
"num_speculative_tokens": 3,
},
{
"method": "suffix",
"suffix_decoding_max_spec_factor": 2.0,
},
],
)
@pytest.mark.usefixtures("disable_vllm_compile_cache_on_rocm")
@single_gpu_only
def test_ngram_and_suffix_correctness(
speculative_config: dict,
model_name: str,
vllm_runner,
):
with vllm_runner(
model_name,
block_size=None,
# Keep LLM defaults; VllmRunner only provides lifecycle cleanup here.
trust_remote_code=False,
enable_chunked_prefill=None,
speculative_config=speculative_config,
max_model_len=4096,
# Preserve LLM's default compilation/cudagraph configuration. Without
# this, VllmRunner injects its reduced test-only capture sizes.
compilation_config=CompilationConfig(),
) as runner:
evaluate_llm_for_gsm8k(runner.llm)
@pytest.mark.parametrize("async_scheduling", [True], ids=["async"])
@single_gpu_only
def test_ngram_gpu_default_with_async_scheduling(
async_scheduling: bool,
vllm_runner,
):
"""Test ngram_gpu speculative decoding (k=3) correctness with and without
async scheduling, validated via GSM8K accuracy.
Uses Qwen/Qwen3-8B (ref GSM8K accuracy: 87%-92%).
"""
qwen3_model = "Qwen/Qwen3-8B"
with vllm_runner(
qwen3_model,
block_size=None,
trust_remote_code=False,
speculative_config={
"method": "ngram_gpu",
"prompt_lookup_max": 3,
"prompt_lookup_min": 2,
"num_speculative_tokens": 2,
},
max_model_len=4096,
async_scheduling=async_scheduling,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as spec_runner:
# Assert the resolved async_scheduling config matches what was requested.
assert (
spec_runner.llm.llm_engine.vllm_config.scheduler_config.async_scheduling
== async_scheduling
)
evaluate_llm_for_gsm8k(spec_runner.llm, expected_accuracy_threshold=0.8)
@single_gpu_only
def test_suffix_decoding_acceptance(
sampling_config: SamplingParams,
model_name: str,
vllm_runner,
):
"""Check that suffix decoding caching takes effect and improves acceptance
lengths and acceptance rates over multiple runs of the same prompts.
"""
test_prompts = get_test_prompts(mm_enabled=False)
with vllm_runner(
model_name,
block_size=None,
trust_remote_code=False,
speculative_config={
"method": "suffix",
"suffix_decoding_max_spec_factor": 2.0,
"suffix_decoding_max_cached_requests": 1000,
},
max_model_len=1024,
disable_log_stats=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
) as spec_runner:
# Run several times and check that the accepted tokens increase.
num_draft = []
num_accept = []
for _ in range(10): # Run multiple times to warm up the cache.
spec_runner.llm.chat(test_prompts, sampling_config)
# Collect draft and acceptance stats.
metrics = spec_runner.llm.get_metrics()
num_draft.append(
get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_draft_tokens"
)
)
num_accept.append(
get_spec_decode_metric_value(
metrics, "vllm:spec_decode_num_accepted_tokens"
)
)
# Calculate the acceptance rates for the first and last runs.
first_accept_tokens = num_accept[0]
first_draft_tokens = num_draft[0]
assert first_draft_tokens > 0, (
"Suffix decoder produced no draft tokens on the first run: "
f"accepted={first_accept_tokens}, drafted={first_draft_tokens}"
)
first_accept_rate = first_accept_tokens / first_draft_tokens
# Take the diff since the stats are cumulative.
last_accept_tokens = num_accept[-1] - num_accept[-2]
last_draft_tokens = num_draft[-1] - num_draft[-2]
assert last_draft_tokens > 0, (
"Suffix decoder produced no draft tokens on the last run: "
f"accepted_delta={last_accept_tokens}, drafted_delta={last_draft_tokens}; "
f"cumulative_drafted={num_draft[-2:]}"
)
last_accept_rate = last_accept_tokens / last_draft_tokens
summary = (
f"first accepted/drafted={first_accept_tokens}/{first_draft_tokens} "
f"(rate={first_accept_rate:.3f}); last delta accepted/drafted="
f"{last_accept_tokens}/{last_draft_tokens} (rate={last_accept_rate:.3f})"
)
# Expect the acceptance length to improve.
assert first_accept_tokens < last_accept_tokens, (
f"Expected accepted tokens to increase after cache warmup; {summary}"
)
# Expect the acceptance rate to improve.
assert first_accept_rate < last_accept_rate, (
f"Expected acceptance rate to increase after cache warmup; {summary}"
)
# Heuristic: expect at least 80.0% acceptance rate at the end.
assert last_accept_rate > 0.80, f"Expected final acceptance rate > 0.80; {summary}"
@@ -1,106 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from tests.utils import single_gpu_only
from vllm import SamplingParams
from vllm.config import CompilationConfig
from ..utils import (
assert_request_outputs_match,
evaluate_llm_for_gsm8k,
get_test_prompts,
)
@pytest.mark.parametrize(
["model_path", "expected_accuracy_threshold"],
[
# Measured reference: 75%-80%.
("RedHatAI/Llama-3.1-8B-Instruct-speculator.eagle3", 0.72),
# Measured reference: 87%-92%.
("RedHatAI/Qwen3-8B-speculator.eagle3", 0.84),
],
ids=["llama3_eagle3_speculator", "qwen3_eagle3_speculator"],
)
@single_gpu_only
def test_speculators_model_integration(
monkeypatch: pytest.MonkeyPatch,
sampling_config: SamplingParams,
model_path: str,
expected_accuracy_threshold: float,
vllm_runner,
):
"""Test that speculators models work with the simplified integration.
This verifies the `vllm serve <speculator-model>` use case where
speculative config is automatically detected from the model config
without requiring explicit --speculative-config argument.
Tests:
1. Speculator model is correctly detected
2. Verifier model is extracted from speculator config
3. Speculative decoding is automatically enabled
4. Text generation works correctly
5. GSM8k accuracy of the model passes a sanity check when speculative decoding on
6. Output matches reference (non-speculative) generation
"""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
# Generate test prompts
test_prompts = get_test_prompts(mm_enabled=False)
# First run: Direct speculator model (simplified integration)
with vllm_runner(
model_path,
block_size=None,
trust_remote_code=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
max_model_len=4096,
gpu_memory_utilization=0.92,
) as spec_runner:
evaluate_llm_for_gsm8k(
spec_runner.llm, expected_accuracy_threshold=expected_accuracy_threshold
)
spec_outputs = spec_runner.llm.chat(test_prompts, sampling_config)
# Verify speculative config was auto-detected
assert spec_runner.llm.llm_engine.vllm_config.speculative_config is not None, (
f"Speculative config should be auto-detected for {model_path}"
)
spec_config = spec_runner.llm.llm_engine.vllm_config.speculative_config
assert spec_config.num_speculative_tokens > 0, (
f"Expected positive speculative tokens, "
f"got {spec_config.num_speculative_tokens}"
)
# Verify draft model is set to the speculator model
assert spec_config.model == model_path, (
f"Draft model should be {model_path}, got {spec_config.model}"
)
# Extract verifier model for reference run
verifier_model = spec_runner.llm.llm_engine.vllm_config.model_config.model
# Second run: Reference without speculative decoding
with vllm_runner(
verifier_model,
block_size=None,
trust_remote_code=False,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
max_model_len=4096,
gpu_memory_utilization=0.92,
) as ref_runner:
ref_outputs = ref_runner.llm.chat(test_prompts, sampling_config)
# Heuristic: expect at least 66% of prompts to match exactly
assert_request_outputs_match(
ref_outputs,
spec_outputs,
required_matches=int(0.66 * len(ref_outputs)),
context=f"speculator={model_path}, verifier={verifier_model}",
)
@@ -1,268 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
from contextlib import AsyncExitStack
from dataclasses import dataclass, replace
from typing import Any
import pytest
import torch
from tests.utils import multi_gpu_marks
from vllm import LLM, SamplingParams
from vllm.config import CompilationConfig
from vllm.distributed import cleanup_dist_env_and_memory
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.platforms import current_platform
from vllm.sampling_params import RequestOutputKind
from vllm.v1.engine.async_llm import AsyncLLM
from vllm.v1.metrics.reader import Metric
DEEPSEEK_MTP_MAIN_RANDOM = "luccafong/deepseek_mtp_main_random"
DEEPSEEK_MTP_DRAFT_RANDOM = "luccafong/deepseek_mtp_draft_random"
PROMPT = "The capital of France is"
MAX_TOKENS = 8
MAX_MODEL_LEN = 2048
GPU_MEM_UTIL = 0.85
# Spec / no-spec greedy output should match, but exact match is not guaranteed
# across parallelism layouts (reduction order can flip near-tie argmaxes), so
# gate on a similarity ratio like the spec-decode E2E tests.
MIN_MATCH_RATIO = 0.8
def _token_match_ratio(a: tuple[int, ...], b: tuple[int, ...]) -> float:
n = min(len(a), len(b))
return sum(x == y for x, y in zip(a, b)) / n if n else 0.0
@dataclass(frozen=True)
class InlineConfig:
id: str
tp_size: int = 1
pp_size: int = 1
enable_expert_parallel: bool = False
enable_eplb: bool = False
skip_reason: str | None = None
INLINE_CONFIGS = [
InlineConfig(id="tp2", tp_size=2),
InlineConfig(id="ep2", tp_size=2, enable_expert_parallel=True),
InlineConfig(
id="ep2_eplb",
tp_size=2,
enable_expert_parallel=True,
enable_eplb=True,
),
InlineConfig(id="pp2", pp_size=2),
]
def _inline_kwargs(config: InlineConfig, *, with_spec: bool) -> dict[str, Any]:
kwargs: dict[str, Any] = {
"model": DEEPSEEK_MTP_MAIN_RANDOM,
"tensor_parallel_size": config.tp_size,
"pipeline_parallel_size": config.pp_size,
"enable_expert_parallel": config.enable_expert_parallel,
"max_model_len": MAX_MODEL_LEN,
"gpu_memory_utilization": GPU_MEM_UTIL,
"enforce_eager": True,
"trust_remote_code": True,
"disable_log_stats": False,
# MLA + batch invariance currently disables prefix caching at runtime
# (see vllm/v1/attention/backends/mla/common.py); set explicitly so the
# configuration is unambiguous.
"enable_prefix_caching": False,
}
if config.enable_eplb:
kwargs["enable_eplb"] = True
# Rearrangement first fires after step_interval // 4 forward steps
# (the step counter starts at 3/4 of step_interval, see
# vllm/distributed/eplb/eplb_state.py). Keep these small so the EPLB
# routine actually runs within the short MAX_TOKENS generation instead
# of never triggering.
kwargs["eplb_config"] = {
"num_redundant_experts": config.tp_size,
"window_size": 2,
"step_interval": 4,
"log_balancedness": False,
}
if with_spec:
kwargs["speculative_config"] = {
"method": "mtp",
"model": DEEPSEEK_MTP_DRAFT_RANDOM,
"num_speculative_tokens": 1,
}
return kwargs
def _generate_token_ids_inline(llm: LLM) -> tuple[int, ...]:
outputs = llm.generate(
[PROMPT],
SamplingParams(temperature=0.0, max_tokens=MAX_TOKENS, ignore_eos=True),
)
assert outputs and outputs[0].outputs, "expected one completion"
token_ids = tuple(outputs[0].outputs[0].token_ids)
assert len(token_ids) == MAX_TOKENS, (
f"expected {MAX_TOKENS} generated tokens, got {len(token_ids)}: {token_ids}"
)
return token_ids
def _spec_decode_num_drafts(metrics: list[Metric]) -> int:
name2metric = {m.name: m for m in metrics}
counter = name2metric.get("vllm:spec_decode_num_drafts")
assert counter is not None, (
"spec_decode_num_drafts metric missing; check disable_log_stats=False"
)
return int(counter.value)
def _enable_batch_invariance(monkeypatch: pytest.MonkeyPatch) -> None:
# This test exercises DeepSeek MLA prefill. ROCm's upstream FlashAttention
# varlen API lacks the num_splits argument used by batch invariance, so
# explicitly override any ambient setting on that path.
if current_platform.is_cuda():
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "1")
else:
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "0")
@pytest.mark.parametrize(
"config",
[
pytest.param(c, id=c.id, marks=multi_gpu_marks(num_gpus=2))
for c in INLINE_CONFIGS
],
)
def test_deepseek_mtp_load_inline(
monkeypatch: pytest.MonkeyPatch,
config: InlineConfig,
vllm_runner,
):
"""MTP loads and drafts under TP/EP/EPLB; spec output matches no-spec greedy."""
if config.skip_reason is not None:
pytest.skip(config.skip_reason)
# Reduces run-to-run nondeterminism so spec / no-spec stay close;
# see tests/v1/distributed/test_eagle_dp.py for the same pattern.
_enable_batch_invariance(monkeypatch)
spec_kwargs = _inline_kwargs(config, with_spec=True)
spec_model = spec_kwargs.pop("model")
with vllm_runner(
spec_model,
block_size=None,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**spec_kwargs,
) as spec_runner:
spec_tokens = _generate_token_ids_inline(spec_runner.llm)
n_drafts = _spec_decode_num_drafts(spec_runner.llm.get_metrics())
no_spec_kwargs = _inline_kwargs(config, with_spec=False)
no_spec_model = no_spec_kwargs.pop("model")
with vllm_runner(
no_spec_model,
block_size=None,
enable_chunked_prefill=None,
compilation_config=CompilationConfig(),
**no_spec_kwargs,
) as no_spec_runner:
no_spec_tokens = _generate_token_ids_inline(no_spec_runner.llm)
# Non-vacuity: a silently-broken MTP drafter that falls back to
# verifier-only decoding would still produce matching output below.
assert n_drafts > 0, (
f"MTP drafter never fired under {config.id}: vllm:spec_decode_num_drafts == 0"
)
match_ratio = _token_match_ratio(spec_tokens, no_spec_tokens)
print(f"\n{config.id}: spec/no-spec match_ratio={match_ratio:.3f}")
assert match_ratio >= MIN_MATCH_RATIO, (
f"Spec / no-spec output divergence under {config.id}: "
f"match_ratio={match_ratio:.2f} < {MIN_MATCH_RATIO}.\n"
f" spec_tokens = {spec_tokens}\n"
f" no_spec_tokens= {no_spec_tokens}"
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
"dp_size",
[
pytest.param(2, marks=pytest.mark.distributed(num_gpus=2), id="dp2"),
pytest.param(1, id="dp1"),
],
)
async def test_deepseek_mtp_load_dp(monkeypatch: pytest.MonkeyPatch, dp_size: int):
"""MTP loads under DP (on and off) via AsyncLLM; spec matches no-spec greedy."""
if torch.accelerator.device_count() < dp_size:
pytest.skip(f"dp{dp_size} requires at least {dp_size} GPUs")
_enable_batch_invariance(monkeypatch)
base_args = AsyncEngineArgs(
model=DEEPSEEK_MTP_MAIN_RANDOM,
tensor_parallel_size=1,
data_parallel_size=dp_size,
data_parallel_backend="mp",
max_model_len=MAX_MODEL_LEN,
gpu_memory_utilization=GPU_MEM_UTIL,
enforce_eager=True,
trust_remote_code=True,
enable_prefix_caching=False,
)
spec_args = replace(
base_args,
speculative_config={
"method": "mtp",
"model": DEEPSEEK_MTP_DRAFT_RANDOM,
"num_speculative_tokens": 1,
},
)
sampling_params = SamplingParams(
max_tokens=MAX_TOKENS,
ignore_eos=True,
output_kind=RequestOutputKind.FINAL_ONLY,
temperature=0.0,
)
async def _generate(args: AsyncEngineArgs, request_id: str) -> tuple[int, ...]:
try:
async with AsyncExitStack() as stack:
engine = AsyncLLM.from_engine_args(args)
stack.callback(engine.shutdown)
async for out in engine.generate(
request_id=request_id,
prompt=PROMPT,
sampling_params=sampling_params,
):
token_ids = tuple(out.outputs[0].token_ids)
assert len(token_ids) == MAX_TOKENS, (
f"{request_id}: expected {MAX_TOKENS} generated tokens, "
f"got {len(token_ids)}: {token_ids}"
)
return token_ids
raise AssertionError("AsyncLLM produced no output")
finally:
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
spec_tokens = await asyncio.wait_for(
_generate(spec_args, f"deepseek-mtp-dp{dp_size}-spec"), timeout=600
)
no_spec_tokens = await asyncio.wait_for(
_generate(base_args, f"deepseek-mtp-dp{dp_size}-no-spec"), timeout=600
)
match_ratio = _token_match_ratio(spec_tokens, no_spec_tokens)
print(f"\ndp{dp_size}: spec/no-spec match_ratio={match_ratio:.3f}")
assert match_ratio >= MIN_MATCH_RATIO, (
f"Spec / no-spec output divergence under dp{dp_size}: "
f"match_ratio={match_ratio:.2f} < {MIN_MATCH_RATIO}.\n"
f" spec_tokens = {spec_tokens}\n"
f" no_spec_tokens= {no_spec_tokens}"
)
@@ -1,103 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Batch-sharded sampling must be a drop-in for replicated sampling under
speculative decoding.
The non-spec arm of this claim lives in tests/v1/e2e/general/
test_sharded_sampling.py. Spec decode is the harder case: draft tokens give
each request a different number of logits rows, so the shard plan's
per-request arithmetic and the rejection sampler are both exercised.
"""
import pytest
import torch
from tests.utils import wait_for_memory_to_settle
from vllm import LLM, SamplingParams
from vllm.distributed import cleanup_dist_env_and_memory
from .utils import _skip_if_insufficient_gpus_for_tp, get_test_prompts, greedy_sampling
# Even with in-process scheduling, near-tie tokens still flip on up to 3 of 20
# prompts in CI, greedy and seeded. A sharding bug diverges wholesale instead.
MAX_DIVERGENT_PROMPTS = 3
def _is_sharded_sampling_active(worker) -> bool:
return worker.model_runner.batch_sharder is not None
def test_mtp_sharded_sampling_equivalence(monkeypatch: pytest.MonkeyPatch):
"""Batch-sharded sampling must match replicated sampling under MTP spec
decoding, up to measured near-tie noise."""
tp_size = 2
_skip_if_insufficient_gpus_for_tp(tp_size)
model_name = "Qwen/Qwen3.5-0.8B-Base"
test_prompts = get_test_prompts(mm_enabled=False, num_prompts=20)
with monkeypatch.context() as m:
# Batch-sharded sampling only exists in the V2 model runner.
m.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
# Required for the collective_rpc mode check below.
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
# Queue every request before the first step, so both boots schedule
# the same batches -- see tests/v1/e2e/general/test_sharded_sampling.py.
m.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
def run(disable_sharding: bool):
llm = LLM(
model=model_name,
tensor_parallel_size=tp_size,
enable_batch_sharded_sampling=not disable_sharding,
speculative_config={
"method": "mtp",
"num_speculative_tokens": 1,
"max_model_len": 2048,
},
max_model_len=2048,
limit_mm_per_prompt={"image": 0, "video": 0},
# More requests than ranks, so round-robin slot ownership
# splits the batch across both ranks.
max_num_seqs=len(test_prompts),
# Timing-based kernel selection is the dominant source of
# cross-boot numeric noise; disable for a tight comparison.
kernel_config={"enable_flashinfer_autotune": False},
)
try:
# Guard against a vacuous comparison: verify every worker is
# in the intended sampling mode.
modes = llm.llm_engine.collective_rpc(_is_sharded_sampling_active)
assert all(mode == (not disable_sharding) for mode in modes)
greedy = llm.chat(test_prompts, greedy_sampling())
seeded = llm.chat(
test_prompts,
SamplingParams(temperature=1.0, seed=33, max_tokens=10),
)
return greedy, seeded
finally:
del llm
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
wait_for_memory_to_settle()
ref_greedy, ref_seeded = run(disable_sharding=True)
shard_greedy, shard_seeded = run(disable_sharding=False)
# A sharding bug shows up as wholesale divergence, not isolated flips.
for name, ref_outputs, shard_outputs in (
("greedy", ref_greedy, shard_greedy),
("seeded", ref_seeded, shard_seeded),
):
divergent = []
for i, (ref, out) in enumerate(zip(ref_outputs, shard_outputs)):
if list(ref.outputs[0].token_ids) != list(out.outputs[0].token_ids):
divergent.append(i)
print(
f"{name} prompt {i} diverged:\n"
f" replicated: {ref.outputs[0].text!r}\n"
f" sharded: {out.outputs[0].text!r}"
)
assert len(divergent) <= MAX_DIVERGENT_PROMPTS, (
f"{name}: {len(divergent)}/{len(ref_outputs)} prompts diverged "
f"at {divergent}, beyond near-tie noise"
)