[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,178 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for the fused EAGLE slot mapping kernel."""
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.spec_decode.utils import (
PADDING_SLOT_ID,
eagle_step_update_slot_mapping_and_metadata,
)
DEVICE_TYPE = current_platform.device_type
# Skip if no CUDA - Triton kernel requires GPU
pytest.importorskip("triton")
if not current_platform.is_cuda_alike() and not current_platform.is_xpu():
pytest.skip("CUDA/XPU required for EAGLE kernel tests", allow_module_level=True)
def _reference_eagle_step_slot_mapping(
positions_1d: torch.Tensor,
block_table_tensor: torch.Tensor,
seq_lens: torch.Tensor,
block_size: int,
max_model_len: int,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Python reference for eagle_step_update_slot_mapping_and_metadata."""
new_positions = positions_1d + 1
exceeds_max = new_positions >= max_model_len
clamped_positions = torch.where(
exceeds_max, torch.zeros_like(positions_1d), new_positions
)
block_numbers = (clamped_positions // block_size).clamp(
max=block_table_tensor.shape[1] - 1
)
block_ids = block_table_tensor[
torch.arange(positions_1d.shape[0], device=positions_1d.device),
block_numbers.long(),
].long()
slot_mapping = block_ids * block_size + (clamped_positions % block_size)
slot_mapping = torch.where(
exceeds_max, torch.full_like(slot_mapping, PADDING_SLOT_ID), slot_mapping
)
new_seq_lens = torch.where(exceeds_max, torch.ones_like(seq_lens), seq_lens + 1)
new_seq_lens = new_seq_lens.clamp(max=max_model_len)
return clamped_positions, slot_mapping, new_seq_lens
def test_eagle_step_slot_mapping_kernel():
"""Test fused kernel matches Python reference for slot mapping and metadata."""
device = torch.device(DEVICE_TYPE)
batch_size = 32
block_size = 16
max_model_len = 4096
n_blocks_per_req = (max_model_len + block_size - 1) // block_size
positions_1d = torch.randint(
0, max_model_len - 10, (batch_size,), dtype=torch.int64, device=device
)
block_table_tensor = torch.randint(
0, 1000, (batch_size, n_blocks_per_req), dtype=torch.int32, device=device
)
seq_lens = torch.randint(1, 100, (batch_size,), dtype=torch.int32, device=device)
ref_clamped, ref_slot, ref_seq_lens = _reference_eagle_step_slot_mapping(
positions_1d.clone(),
block_table_tensor,
seq_lens.clone(),
block_size,
max_model_len,
)
out_clamped = torch.zeros(batch_size, dtype=torch.int64, device=device)
out_slot = torch.zeros(batch_size, dtype=torch.int64, device=device)
seq_lens_copy = seq_lens.clone()
eagle_step_update_slot_mapping_and_metadata(
positions_1d=positions_1d,
block_table_tensor=block_table_tensor,
seq_lens=seq_lens_copy,
block_size=block_size,
max_model_len=max_model_len,
out_clamped_positions=out_clamped,
out_slot_mapping=out_slot,
)
assert torch.equal(out_clamped, ref_clamped), (
f"clamped: {out_clamped} vs {ref_clamped}"
)
assert torch.equal(out_slot, ref_slot), f"slot: {out_slot} vs {ref_slot}"
assert torch.equal(seq_lens_copy, ref_seq_lens), (
f"seq_lens: {seq_lens_copy} vs {ref_seq_lens}"
)
def test_eagle_step_slot_mapping_kernel_exceeds_max():
"""Test fused kernel when position exceeds max_model_len."""
device = torch.device(DEVICE_TYPE)
batch_size = 4
block_size = 16
max_model_len = 100
n_blocks_per_req = (max_model_len + block_size - 1) // block_size
positions_1d = torch.tensor([50, 98, 99, 100], dtype=torch.int64, device=device)
block_table_tensor = torch.randint(
0, 100, (batch_size, n_blocks_per_req), dtype=torch.int32, device=device
)
seq_lens = torch.tensor([51, 99, 100, 101], dtype=torch.int32, device=device)
out_clamped = torch.zeros(batch_size, dtype=torch.int64, device=device)
out_slot = torch.zeros(batch_size, dtype=torch.int64, device=device)
eagle_step_update_slot_mapping_and_metadata(
positions_1d=positions_1d,
block_table_tensor=block_table_tensor,
seq_lens=seq_lens,
block_size=block_size,
max_model_len=max_model_len,
out_clamped_positions=out_clamped,
out_slot_mapping=out_slot,
)
assert out_clamped[0].item() == 51
assert out_clamped[1].item() == 99
assert out_clamped[2].item() == 0
assert out_clamped[3].item() == 0
assert out_slot[2].item() == PADDING_SLOT_ID
assert out_slot[3].item() == PADDING_SLOT_ID
assert seq_lens[2].item() == 1
assert seq_lens[3].item() == 1
def test_eagle_step_slot_mapping_kernel_cudagraph_padding():
"""Test that padding threads write PADDING_SLOT_ID when
input_batch_size > batch_size (cudagraph padding)."""
device = torch.device(DEVICE_TYPE)
batch_size = 4
input_batch_size = 8
block_size = 16
max_model_len = 4096
n_blocks_per_req = (max_model_len + block_size - 1) // block_size
positions_1d = torch.tensor([10, 20, 30, 40], dtype=torch.int64, device=device)
block_table_tensor = torch.randint(
0, 100, (batch_size, n_blocks_per_req), dtype=torch.int32, device=device
)
seq_lens = torch.tensor([11, 21, 31, 41], dtype=torch.int32, device=device)
ref_clamped, ref_slot, ref_seq_lens = _reference_eagle_step_slot_mapping(
positions_1d.clone(),
block_table_tensor,
seq_lens.clone(),
block_size,
max_model_len,
)
out_clamped = torch.zeros(batch_size, dtype=torch.int64, device=device)
out_slot = torch.full((input_batch_size,), -999, dtype=torch.int64, device=device)
seq_lens_copy = seq_lens.clone()
eagle_step_update_slot_mapping_and_metadata(
positions_1d=positions_1d,
block_table_tensor=block_table_tensor,
seq_lens=seq_lens_copy,
block_size=block_size,
max_model_len=max_model_len,
out_clamped_positions=out_clamped,
out_slot_mapping=out_slot,
input_batch_size=input_batch_size,
)
# Real slots should match the reference
assert torch.equal(out_clamped, ref_clamped)
assert torch.equal(out_slot[:batch_size], ref_slot)
assert torch.equal(seq_lens_copy, ref_seq_lens)
# Padding slots should be PADDING_SLOT_ID
for i in range(batch_size, input_batch_size):
assert out_slot[i].item() == PADDING_SLOT_ID
@@ -1,488 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
from unittest import mock
import numpy as np
import pytest
import torch
from transformers import CLIPVisionConfig, LlamaConfig, LlavaConfig, PreTrainedConfig
from tests.v1.attention.utils import (
BatchSpec,
create_common_attn_metadata,
)
from vllm.config import (
AttentionConfig,
CacheConfig,
DeviceConfig,
ModelConfig,
ParallelConfig,
SchedulerConfig,
SpeculativeConfig,
VllmConfig,
)
from vllm.config.load import LoadConfig
from vllm.platforms import current_platform
from vllm.transformers_utils.config import get_hf_text_config
from vllm.transformers_utils.configs.extract_hidden_states import (
ExtractHiddenStatesConfig,
)
from vllm.v1.spec_decode.extract_hidden_states import ExtractHiddenStatesProposer
from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch
model_dir = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
DEVICE_TYPE = current_platform.device_type
def _create_proposer(
num_speculative_tokens: int = 1,
layer_ids: list[int] | None = None,
) -> ExtractHiddenStatesProposer:
"""Create an ExtractHiddenStatesProposer for testing."""
if layer_ids is None:
layer_ids = [1, 2, 3, 4]
model_config = ModelConfig(model=model_dir, runner="generate", max_model_len=100)
speculative_config = SpeculativeConfig(
target_model_config=model_config,
target_parallel_config=ParallelConfig(),
method="extract_hidden_states",
num_speculative_tokens=num_speculative_tokens,
draft_model_config={
"hf_config": {
"eagle_aux_hidden_state_layer_ids": layer_ids,
}
},
)
device = DEVICE_TYPE
vllm_config = VllmConfig(
model_config=model_config,
cache_config=CacheConfig(),
speculative_config=speculative_config,
device_config=DeviceConfig(device=device),
parallel_config=ParallelConfig(),
load_config=LoadConfig(),
scheduler_config=SchedulerConfig(
max_model_len=model_config.max_model_len,
is_encoder_decoder=model_config.is_encoder_decoder,
),
attention_config=AttentionConfig(),
)
return ExtractHiddenStatesProposer(vllm_config=vllm_config, device=device)
def test_proposer_initialization():
"""Test that the proposer initializes correctly with the right parameters."""
layer_ids = [1, 2, 3, 4]
proposer = _create_proposer(num_speculative_tokens=1, layer_ids=layer_ids)
assert proposer.num_hidden_states == len(layer_ids)
assert proposer.vllm_config.speculative_config is not None
assert proposer.vllm_config.speculative_config.num_speculative_tokens == 1
# Verify the hidden states buffer is correctly shaped
expected_shape = (
proposer.max_num_tokens,
len(layer_ids),
proposer.hidden_size,
)
assert proposer.hidden_states.shape == expected_shape
def test_proposer_initialization_missing_layer_ids():
"""Test that initialization fails when layer_ids are not provided."""
model_config = ModelConfig(model=model_dir, runner="generate", max_model_len=100)
speculative_config = SpeculativeConfig(
target_model_config=model_config,
target_parallel_config=ParallelConfig(),
method="extract_hidden_states",
num_speculative_tokens=1,
draft_model_config={
"hf_config": {} # Missing eagle_aux_hidden_state_layer_ids
},
)
device = DEVICE_TYPE
vllm_config = VllmConfig(
model_config=model_config,
cache_config=CacheConfig(),
speculative_config=speculative_config,
device_config=DeviceConfig(device=device),
parallel_config=ParallelConfig(),
load_config=LoadConfig(),
scheduler_config=SchedulerConfig(
max_model_len=model_config.max_model_len,
is_encoder_decoder=model_config.is_encoder_decoder,
),
attention_config=AttentionConfig(),
)
with pytest.raises(
ValueError, match="eagle_aux_hidden_state_layer_ids must be set"
):
ExtractHiddenStatesProposer(vllm_config=vllm_config, device=device)
def test_prepare_next_token_ids_padded():
"""Test for prepare_next_token_ids_padded with extract_hidden_states.
Since num_speculative_tokens == 1, sampled_token_ids has shape (batch_size, 1).
For each request we either use the sampled token (if valid and not discarded)
or a backup token from the request state.
"""
device = torch.device(DEVICE_TYPE)
num_requests = 4
req_ids = [f"req_{i + 1}" for i in range(num_requests)]
mock_input_batch = mock.MagicMock(spec=InputBatch)
mock_input_batch.req_ids = req_ids
mock_input_batch.num_reqs = num_requests
mock_input_batch.vocab_size = 100
mock_input_batch.num_tokens_no_spec = np.array([5] * num_requests)
mock_requests: dict[str, CachedRequestState] = {}
for req_id in req_ids:
mock_request = mock.MagicMock(spec=CachedRequestState)
# Each request will have a backup next token id of 10, 20, 30, 40
mock_request.get_token_id.return_value = int(req_id.split("_")[1]) * 10
mock_requests[req_id] = mock_request
# explicitly discard the last request
discarded_req_mask = torch.tensor(
[False, False, False, True], dtype=torch.bool, device=device
)
# With num_speculative_tokens=1, sampled_token_ids has shape [batch_size, 1]
sampled_token_ids = torch.tensor(
[
[1], # valid, use 1
[4], # valid, use 4
[-1], # invalid, use backup token "30"
[2], # explicitly discarded, use backup token "40"
],
dtype=torch.int32,
device=device,
)
expected_next_token_ids_cpu = [1, 4, 30, 40]
expected_next_token_ids_tensor = torch.tensor(
expected_next_token_ids_cpu, dtype=torch.int32, device=device
)
proposer = _create_proposer(num_speculative_tokens=1)
# valid_sampled_tokens_count tracks if token is valid (not -1 and in vocab range)
# It doesn't depend on whether the request is discarded
expected_valid_sampled_tokens_count = torch.tensor(
[1, 1, 0, 1], dtype=torch.int32, device=device
)
next_token_ids, valid_sampled_tokens_count = proposer.prepare_next_token_ids_padded(
sampled_token_ids,
mock_requests,
mock_input_batch,
discarded_req_mask,
)
assert torch.equal(next_token_ids, expected_next_token_ids_tensor)
assert torch.equal(valid_sampled_tokens_count, expected_valid_sampled_tokens_count)
def test_propose():
"""Test the propose() method of ExtractHiddenStatesProposer.
This should:
1. Accept target hidden states and sampled token IDs
2. Return the sampled tokens as "draft" tokens (shape [batch_size, 1])
3. Cache the hidden states in the model's KV cache
"""
device = torch.device(DEVICE_TYPE)
# Setup test parameters
batch_size = 2
num_tokens = 5
num_hidden_layers = 4
proposer = _create_proposer(
num_speculative_tokens=1, layer_ids=list(range(num_hidden_layers))
)
hidden_size = proposer.hidden_size
# Create mock model
model_mock = mock.MagicMock()
proposer.model = model_mock
# Mock attention layer names
proposer.attn_layer_names = ["cache_only_layers.28"]
# Mock attention metadata builder
mock_attn_metadata = mock.MagicMock()
mock_attn_metadata_builder = mock.MagicMock()
mock_attn_metadata_builder.build_for_drafting.return_value = mock_attn_metadata
proposer.attn_metadata_builder = mock_attn_metadata_builder
# Create input tensors
batch_spec = BatchSpec(
seq_lens=[3, 2],
query_lens=[3, 2],
)
common_attn_metadata = create_common_attn_metadata(
batch_spec,
block_size=16,
device=device,
)
# Create target hidden states: list of tensors, one per layer
# Each tensor has shape [num_tokens, hidden_size]
target_hidden_states = [
torch.randn(num_tokens, hidden_size, dtype=proposer.dtype, device=device)
for _ in range(num_hidden_layers)
]
# Sampled token IDs from target model
sampled_token_ids = torch.tensor(
[42, 60], dtype=torch.int32, device=device
).unsqueeze(-1)
# Call propose
draft_tokens = proposer.propose(
num_speculative_tokens=1,
sampled_token_ids=sampled_token_ids,
target_hidden_states=target_hidden_states,
common_attn_metadata=common_attn_metadata,
slot_mappings=None,
)
# Verify draft tokens match sampled tokens
# Shape should be [batch_size, 1] for num_speculative_tokens=1
assert draft_tokens.shape == (batch_size, 1)
assert torch.equal(draft_tokens, sampled_token_ids)
# Verify the model was called
model_mock.assert_called_once()
# Verify hidden states were copied to the buffer The stacked hidden states
# should have shape [num_tokens, num_hidden_layers, hidden_size]
expected_stacked = torch.stack(target_hidden_states, dim=1)
assert torch.allclose(
proposer.hidden_states[:num_tokens], expected_stacked, atol=1e-6
)
@pytest.mark.parametrize("num_hidden_layers", [1, 4, 8])
def test_propose_different_layer_counts(num_hidden_layers):
"""Test that propose works correctly with different numbers of hidden layers."""
device = torch.device(DEVICE_TYPE)
batch_size = 2
num_tokens = 5
proposer = _create_proposer(
num_speculative_tokens=1, layer_ids=list(range(num_hidden_layers))
)
hidden_size = proposer.hidden_size
# Setup mocks
model_mock = mock.MagicMock()
proposer.model = model_mock
proposer.attn_layer_names = ["cache_only_layers.28"]
mock_attn_metadata_builder = mock.MagicMock()
mock_attn_metadata_builder.build_for_drafting.return_value = mock.MagicMock()
proposer.attn_metadata_builder = mock_attn_metadata_builder
batch_spec = BatchSpec(
seq_lens=[3, 2],
query_lens=[3, 2],
)
common_attn_metadata = create_common_attn_metadata(
batch_spec,
block_size=16,
device=device,
)
# Create target hidden states
target_hidden_states = [
torch.randn(num_tokens, hidden_size, dtype=proposer.dtype, device=device)
for _ in range(num_hidden_layers)
]
sampled_token_ids = torch.tensor(
[42, 60], dtype=torch.int32, device=device
).unsqueeze(-1)
draft_tokens = proposer.propose(
num_speculative_tokens=1,
sampled_token_ids=sampled_token_ids,
target_hidden_states=target_hidden_states,
common_attn_metadata=common_attn_metadata,
slot_mappings=None,
)
assert draft_tokens.shape == (batch_size, 1)
assert torch.equal(draft_tokens, sampled_token_ids)
# ---------------------------------------------------------------------------
# VLM / composite config tests for ExtractHiddenStatesConfig
# ---------------------------------------------------------------------------
class _DummyVLMConfig(PreTrainedConfig):
"""Minimal composite config that mimics VLMs like Kimi-K2.5 or LLaVA.
The text model's parameters (hidden_size, num_attention_heads, …) live
exclusively under ``text_config``; the top-level config has none of them.
"""
model_type = "test_vlm"
def __init__(self, text_config: PreTrainedConfig, **kwargs):
self.text_config = text_config
super().__init__(architectures=["LlamaForCausalLM"], **kwargs)
def get_text_config(self, decoder: bool = False) -> PreTrainedConfig:
del decoder
return self.text_config
def test_extract_hidden_states_text_only_config_regression():
"""Text-only models (no nested text_config) must keep working."""
model_config = ModelConfig(model=model_dir, runner="generate", max_model_len=100)
speculative_config = SpeculativeConfig(
target_model_config=model_config,
target_parallel_config=ParallelConfig(),
method="extract_hidden_states",
num_speculative_tokens=1,
draft_model_config={
"hf_config": {
"eagle_aux_hidden_state_layer_ids": [1, 2, 3, 4],
}
},
)
assert speculative_config.draft_model_config is not None
# For text-only models, hf_text_config should be the config itself.
assert speculative_config.draft_model_config.hf_text_config is (
speculative_config.draft_model_config.hf_config
)
assert (
speculative_config.draft_model_config.hf_text_config.num_attention_heads
== model_config.hf_text_config.num_attention_heads
)
def test_extract_hidden_states_config_preserves_vlm_text_config():
"""A real VLM config (LLaVA) with nested text_config must be preserved."""
text_config = LlamaConfig(
vocab_size=32000,
hidden_size=128,
intermediate_size=256,
num_hidden_layers=2,
num_attention_heads=8,
)
vlm_config = LlavaConfig(
vision_config=CLIPVisionConfig(),
text_config=text_config,
)
# Precondition: to_dict() flattens the nested config to a plain dict.
assert isinstance(vlm_config.to_dict()["text_config"], dict)
extract_config = ExtractHiddenStatesConfig(
vlm_config,
eagle_aux_hidden_state_layer_ids=[1, 2],
)
# The fix: text_config is still a PreTrainedConfig, not a dict.
assert isinstance(extract_config.text_config, LlamaConfig)
extracted = get_hf_text_config(extract_config)
assert extracted is extract_config.text_config
assert extracted.num_attention_heads == text_config.num_attention_heads
assert extracted.hidden_size == text_config.hidden_size
# Serialization must still round-trip correctly.
serialized = extract_config.to_dict()
assert isinstance(serialized["text_config"], dict)
assert serialized["text_config"]["num_attention_heads"] == (
text_config.num_attention_heads
)
json_str = json.loads(extract_config.to_json_string())
assert json_str["text_config"]["num_attention_heads"] == (
text_config.num_attention_heads
)
def test_extract_hidden_states_speculative_config_vlm():
"""SpeculativeConfig with a VLM target must build without errors."""
nested_text_config = LlamaConfig(
vocab_size=32000,
hidden_size=128,
intermediate_size=256,
num_hidden_layers=2,
num_attention_heads=8,
)
target_model_config = ModelConfig(
model=model_dir,
runner="generate",
max_model_len=100,
)
# Replace the real text-only config with our composite VLM config.
target_model_config.hf_config = _DummyVLMConfig(
text_config=nested_text_config,
)
target_model_config.hf_text_config = nested_text_config
speculative_config = SpeculativeConfig(
target_model_config=target_model_config,
target_parallel_config=ParallelConfig(),
method="extract_hidden_states",
num_speculative_tokens=1,
draft_model_config={
"hf_config": {
"eagle_aux_hidden_state_layer_ids": [1, 2],
}
},
)
assert speculative_config.draft_model_config is not None
assert isinstance(
speculative_config.draft_model_config.hf_config.text_config,
LlamaConfig,
)
assert speculative_config.draft_model_config.hf_text_config is (
speculative_config.draft_model_config.hf_config.text_config
)
assert (
speculative_config.draft_model_config.hf_text_config.num_attention_heads
== nested_text_config.num_attention_heads
)
def test_extract_hidden_states_config_invalid_text_config():
"""A nested text_config missing required attrs must still be rejected."""
broken_text_config = PreTrainedConfig(hidden_size=128)
vlm_config = _DummyVLMConfig(text_config=broken_text_config)
extract_config = ExtractHiddenStatesConfig(
vlm_config,
eagle_aux_hidden_state_layer_ids=[1],
)
# The object is preserved (not flattened), …
assert extract_config.text_config is broken_text_config
# … but validation still rejects the missing attribute.
with pytest.raises(ValueError, match="num_attention_heads"):
get_hf_text_config(extract_config)
@@ -1,92 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.sample.logits_processor import LogitsProcessors
from vllm.v1.sample.metadata import SamplingMetadata
from vllm.v1.spec_decode.llm_base_proposer import (
SpecDecodeBaseProposer,
compute_probs_and_sample_next_token,
)
DEVICE_TYPE = current_platform.device_type
def _seed_default_generator(seed: int) -> None:
set_random_seed(seed)
def _make_sampling_metadata(batch_size: int) -> SamplingMetadata:
return SamplingMetadata(
temperature=torch.ones(batch_size, dtype=torch.float32, device=DEVICE_TYPE),
all_greedy=False,
all_random=True,
top_p=None,
top_k=None,
generators={},
max_num_logprobs=None,
no_penalties=True,
prompt_token_ids=None,
frequency_penalties=torch.empty(0, device=DEVICE_TYPE),
presence_penalties=torch.empty(0, device=DEVICE_TYPE),
repetition_penalties=torch.empty(0, device=DEVICE_TYPE),
output_token_ids=[[] for _ in range(batch_size)],
spec_token_ids=[[] for _ in range(batch_size)],
allowed_token_ids_mask=None,
bad_words_token_ids={},
logitsprocs=LogitsProcessors(),
)
def test_compute_probs_and_sample_next_token_uses_fp64_exponential_race():
batch_size = 4
vocab_size = 32
generator = torch.Generator(device=DEVICE_TYPE).manual_seed(11)
logits = torch.randn(
batch_size,
vocab_size,
dtype=torch.float32,
device=DEVICE_TYPE,
generator=generator,
)
metadata = _make_sampling_metadata(batch_size)
_seed_default_generator(12345)
probs = logits.softmax(dim=-1, dtype=torch.float32)
q = torch.empty(probs.shape, dtype=torch.float64, device=probs.device)
q.exponential_()
expected_ids = q.reciprocal_().mul_(probs).argmax(dim=-1).view(-1)
_seed_default_generator(12345)
actual_ids, actual_probs = compute_probs_and_sample_next_token(
logits.clone(),
metadata,
use_fp64_gumbel=True,
)
assert torch.equal(actual_ids, expected_ids)
assert torch.allclose(actual_probs, probs)
@pytest.mark.parametrize(
("architecture", "expected"),
[
("DeepSeekMTPModel", True),
("KimiK3MTPModel", True),
("MiniMaxM3ForCausalLM", False),
],
)
def test_mtp_model_returns_tuple(architecture: str, expected: bool):
proposer = object.__new__(SpecDecodeBaseProposer)
proposer.method = "mtp"
proposer.draft_model_config = SimpleNamespace(
hf_config=SimpleNamespace(architectures=[architecture])
)
assert proposer.model_returns_tuple() is expected
-143
View File
@@ -1,143 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Test whether spec decoding handles the max model length properly."""
import pytest
from tests.utils import get_attn_backend_list_based_on_platform
from vllm import SamplingParams
from vllm.config import ModelConfig, ParallelConfig, SpeculativeConfig
from vllm.platforms import current_platform
from vllm.sampling_params import StructuredOutputsParams
_PROMPTS = [
"1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1",
"Repeat the following sentence 10 times: Consistency is key to mastering any skill.", # noqa: E501
"Who won the Turing Award in 2018, and for what contribution? Describe in detail.", # noqa: E501
]
@pytest.mark.parametrize("num_speculative_tokens", [1, 3, 10])
def test_ngram_max_len(num_speculative_tokens: int, vllm_runner):
with vllm_runner(
"facebook/opt-125m",
trust_remote_code=False,
max_model_len=100,
enable_chunked_prefill=None,
enforce_eager=True, # For faster initialization.
speculative_config={
"method": "ngram",
"prompt_lookup_max": 5,
"prompt_lookup_min": 3,
"num_speculative_tokens": num_speculative_tokens,
},
) as runner:
sampling_params = SamplingParams(max_tokens=100, ignore_eos=True)
runner.llm.generate(_PROMPTS, sampling_params)
@pytest.mark.parametrize("num_speculative_tokens", [1, 3, 10])
@pytest.mark.parametrize("method", ["ngram", "ngram_gpu"])
def test_ngram_gpu_max_len(
method: str,
num_speculative_tokens: int,
vllm_runner,
monkeypatch: pytest.MonkeyPatch,
):
"""V2 n-gram decoding stops at max_model_len."""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
with vllm_runner(
"facebook/opt-125m",
trust_remote_code=False,
max_model_len=100,
enable_chunked_prefill=None,
enforce_eager=True, # For faster initialization.
speculative_config={
"method": method,
"prompt_lookup_max": 5,
"prompt_lookup_min": 3,
"num_speculative_tokens": num_speculative_tokens,
},
) as runner:
assert runner.llm.llm_engine.vllm_config.use_v2_model_runner
sampling_params = SamplingParams(max_tokens=100, ignore_eos=True)
outputs = runner.llm.generate(_PROMPTS, sampling_params)
for output in outputs:
assert output.prompt_token_ids is not None
assert (
len(output.prompt_token_ids) + len(output.outputs[0].token_ids) == 100
)
@pytest.mark.parametrize("num_speculative_tokens", [1, 3, 10])
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
def test_eagle_max_len(
monkeypatch: pytest.MonkeyPatch,
num_speculative_tokens: int,
attn_backend: str,
vllm_runner,
):
if attn_backend == "ROCM_AITER_FA" and current_platform.is_rocm():
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
with vllm_runner(
"meta-llama/Meta-Llama-3-8B-Instruct",
trust_remote_code=False,
enable_chunked_prefill=None,
enforce_eager=True, # For faster initialization.
speculative_config={
"method": "eagle",
"model": "yuhuili/EAGLE-LLaMA3-Instruct-8B",
"num_speculative_tokens": num_speculative_tokens,
"max_model_len": 80,
},
max_model_len=200,
attention_config={"backend": attn_backend},
) as runner:
sampling_params = SamplingParams(max_tokens=200, ignore_eos=True)
outputs = runner.llm.generate(_PROMPTS, sampling_params)
for o in outputs:
assert o.outputs[0].finish_reason == "length", (
"This test is only meaningful if the output is truncated "
"due to max length"
)
sampling_params = SamplingParams(
max_tokens=200,
structured_outputs=StructuredOutputsParams(
regex="^" + "a b c d e " * 15 + "$"
),
)
output = runner.llm.generate(_PROMPTS, sampling_params)
for o in output:
assert o.prompt_token_ids is not None
assert (
len(o.prompt_token_ids)
< 80
< len(o.prompt_token_ids) + len(o.outputs[0].token_ids)
<= 200
), (
"This test is only meaningful if the output "
"is longer than the eagle max length"
)
assert o.outputs[0].text == "a b c d e " * 15
@pytest.mark.parametrize("spec_max_model_len", [80, 150])
def test_mtp_speculative_config_max_model_len(spec_max_model_len: int):
"""Regression test for #41456: max_model_len in speculative config
should be respected for the draft model."""
model_config = ModelConfig(
model="XiaomiMiMo/MiMo-7B-Base",
runner="generate",
max_model_len=200,
trust_remote_code=True,
)
spec_config = SpeculativeConfig(
target_model_config=model_config,
target_parallel_config=ParallelConfig(),
method="mtp",
num_speculative_tokens=1,
max_model_len=spec_max_model_len,
)
assert spec_config.draft_model_config.max_model_len == spec_max_model_len
@@ -1,238 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import dataclasses
import pytest
import torch
from tests.evals.gsm8k.gsm8k_eval import evaluate_gsm8k_offline
from tests.utils import large_gpu_mark
from vllm import LLM
from vllm.config import SpeculativeConfig
from vllm.distributed import cleanup_dist_env_and_memory
@dataclasses.dataclass
class SpeculatorTestConfig:
model_path: str
method: str
display_name: str
expected_gsm8k_accuracy: float
accuracy_rtol: float
expected_acceptance_len: float
acceptance_len_rtol: float
expected_per_pos_acceptance_rates: tuple[float, ...]
per_pos_rtol: float
quantization: str | None = None
parallel_drafting: bool | None = None
DFLASH_CONFIG = SpeculatorTestConfig(
model_path="nm-testing/dflash-qwen3-8b-speculators",
method="dflash",
display_name="DFlash",
expected_gsm8k_accuracy=0.885,
accuracy_rtol=0.03,
expected_acceptance_len=3.45,
acceptance_len_rtol=0.15,
expected_per_pos_acceptance_rates=(0.795, 0.611, 0.429, 0.282),
per_pos_rtol=0.15,
quantization="fp8_per_tensor",
)
PEAGLE_CONFIG = SpeculatorTestConfig(
model_path="nm-testing/qwen3-8b-peagle-speculators",
method="eagle3",
display_name="PEagle",
expected_gsm8k_accuracy=0.88,
accuracy_rtol=0.05,
expected_acceptance_len=2.27,
acceptance_len_rtol=0.20,
expected_per_pos_acceptance_rates=(0.66, 0.36, 0.18, 0.09),
per_pos_rtol=0.20,
parallel_drafting=True,
)
QWEN3_EAGLE3_CONFIG = SpeculatorTestConfig(
model_path=(
"inference-optimization/"
"Qwen3-8B-from-Qwen3-8B_regen-speculators.eagle3-qwen3arch-ckpt1"
),
method="eagle3",
display_name="Qwen3 Eagle3",
expected_gsm8k_accuracy=0.88,
accuracy_rtol=0.05,
expected_acceptance_len=2.67,
acceptance_len_rtol=0.10,
expected_per_pos_acceptance_rates=(0.76, 0.55, 0.36),
per_pos_rtol=0.10,
)
QWEN3_PEAGLE_CONFIG = SpeculatorTestConfig(
model_path="inference-optimization/Qwen3-8B-speculators.peagle-qwen3arch-ckpt4",
method="eagle3",
display_name="Qwen3 PEagle",
expected_gsm8k_accuracy=0.88,
accuracy_rtol=0.05,
expected_acceptance_len=3.42,
acceptance_len_rtol=0.15,
expected_per_pos_acceptance_rates=(0.78, 0.59, 0.43, 0.29, 0.18, 0.10, 0.05),
per_pos_rtol=0.10,
parallel_drafting=True,
)
SPECULATOR_CONFIGS = [
pytest.param(DFLASH_CONFIG, id="dflash"),
pytest.param(PEAGLE_CONFIG, id="peagle"),
pytest.param(QWEN3_EAGLE3_CONFIG, id="qwen3arch_eagle3"),
pytest.param(QWEN3_PEAGLE_CONFIG, id="qwen3arch_peagle"),
]
def compute_spec_decode_stats(metrics) -> dict:
"""Extract all spec-decode metrics and compute derived stats."""
name2metric = {m.name: m for m in metrics}
n_drafts = name2metric["vllm:spec_decode_num_drafts"].value
n_draft_tokens = name2metric["vllm:spec_decode_num_draft_tokens"].value
n_accepted = name2metric["vllm:spec_decode_num_accepted_tokens"].value
per_pos_vec = name2metric["vllm:spec_decode_num_accepted_tokens_per_pos"].values
acceptance_len = 1 + (n_accepted / n_drafts) if n_drafts > 0 else 1.0
draft_tokens_per_step = (n_draft_tokens / n_drafts) if n_drafts > 0 else 0
overall_acceptance_rate = (n_accepted / n_draft_tokens) if n_draft_tokens > 0 else 0
per_pos_rates = [v / n_drafts for v in per_pos_vec] if n_drafts > 0 else []
return {
"num_drafts": n_drafts,
"num_draft_tokens": n_draft_tokens,
"num_accepted_tokens": n_accepted,
"acceptance_len": acceptance_len,
"draft_tokens_per_step": draft_tokens_per_step,
"overall_acceptance_rate": overall_acceptance_rate,
"per_pos_accepted": list(per_pos_vec),
"per_pos_acceptance_rates": per_pos_rates,
}
def print_spec_decode_stats(stats: dict) -> None:
"""Print all spec-decode metrics and derived values."""
print("\n===== Spec Decode Metrics =====")
print(f" num_drafts: {stats['num_drafts']}")
print(f" num_draft_tokens: {stats['num_draft_tokens']}")
print(f" num_accepted_tokens: {stats['num_accepted_tokens']}")
print(f" draft_tokens_per_step: {stats['draft_tokens_per_step']:.2f}")
print(f" overall_acceptance_rate: {stats['overall_acceptance_rate']:.4f}")
print(f" acceptance_len (1+acc/drafts): {stats['acceptance_len']:.4f}")
print(" per-position accepted tokens:", stats["per_pos_accepted"])
print(" per-position acceptance rates:")
for i, rate in enumerate(stats["per_pos_acceptance_rates"]):
print(f" pos {i}: {rate:.4f}")
print("===============================\n")
@pytest.mark.parametrize("config", SPECULATOR_CONFIGS)
def test_speculators_model(vllm_runner, example_prompts, monkeypatch, config):
"""Test speculators model properly initializes speculative decoding.
Verifies:
1. Speculative config is automatically initialized from speculators config
2. Method is detected correctly
3. parallel_drafting is set correctly (if applicable)
4. The draft model path is correctly set
5. Speculative tokens count is valid
6. Text generation works with speculative decoding enabled
"""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
runner_kwargs = dict(dtype=torch.bfloat16, enforce_eager=True)
if config.quantization:
runner_kwargs["quantization"] = config.quantization
with vllm_runner(config.model_path, **runner_kwargs) as vllm_model:
vllm_config = vllm_model.llm.llm_engine.vllm_config
assert isinstance(vllm_config.speculative_config, SpeculativeConfig), (
"Speculative config should be initialized for speculators model"
)
spec_config = vllm_config.speculative_config
assert spec_config.method == config.method, (
f"Expected method='{config.method}', got '{spec_config.method}'"
)
if config.parallel_drafting is not None:
assert spec_config.parallel_drafting is config.parallel_drafting, (
f"Expected parallel_drafting={config.parallel_drafting} "
f"for {config.display_name} model"
)
assert spec_config.num_speculative_tokens > 0, (
f"Expected positive speculative tokens, "
f"got {spec_config.num_speculative_tokens}"
)
assert spec_config.model == config.model_path, (
f"Draft model should be {config.model_path}, got {spec_config.model}"
)
vllm_outputs = vllm_model.generate_greedy(example_prompts, max_tokens=20)
assert vllm_outputs, (
f"No outputs generated for speculators model {config.model_path}"
)
@pytest.mark.slow_test
@large_gpu_mark(min_gb=40)
@pytest.mark.parametrize("config", SPECULATOR_CONFIGS)
def test_speculators_correctness(monkeypatch, config):
"""E2E correctness test via the speculators auto-detect path.
Evaluates GSM8k accuracy to ensure the speculators-format model produces
correct outputs, and checks that acceptance length does not collapse under
batched inference (lm-eval style).
"""
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
spec_llm = LLM(
model=config.model_path,
trust_remote_code=True,
max_model_len=4096,
max_num_seqs=128,
gpu_memory_utilization=0.85,
enforce_eager=False,
disable_log_stats=False,
)
results = evaluate_gsm8k_offline(spec_llm)
accuracy = results["accuracy"]
print(f"GSM8K Accuracy: {accuracy:.4f}")
accuracy_threshold = config.expected_gsm8k_accuracy * (1 - config.accuracy_rtol)
assert accuracy >= accuracy_threshold, (
f"Expected GSM8K accuracy >= {accuracy_threshold:.3f}, got {accuracy:.3f}"
)
current_metrics = spec_llm.get_metrics()
stats = compute_spec_decode_stats(current_metrics)
print_spec_decode_stats(stats)
acceptance_len = stats["acceptance_len"]
al_threshold = config.expected_acceptance_len * (1 - config.acceptance_len_rtol)
assert acceptance_len >= al_threshold, (
f"{config.display_name} speculators acceptance length too low: "
f"{acceptance_len:.2f} < {al_threshold:.2f}"
)
per_pos_rates = stats["per_pos_acceptance_rates"]
for i, expected_rate in enumerate(config.expected_per_pos_acceptance_rates):
assert i < len(per_pos_rates), (
f"Missing per-position acceptance rate for position {i}"
)
threshold = expected_rate * (1 - config.per_pos_rtol)
assert per_pos_rates[i] >= threshold, (
f"Per-position acceptance rate at pos {i} too low: "
f"{per_pos_rates[i]:.4f} < {threshold:.4f} "
f"(expected ~{expected_rate:.4f})"
)
del spec_llm
torch.accelerator.empty_cache()
cleanup_dist_env_and_memory()
@@ -1,69 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm.config import SpeculativeConfig
from vllm.model_executor.models.interfaces import supports_eagle3
from vllm.platforms import current_platform
@pytest.mark.parametrize(
"model_path",
[
pytest.param(
"nm-testing/SpeculatorLlama3-1-8B-Eagle3-converted-0717-quantized",
id="llama3-eagle3-speculator",
),
pytest.param(
"nm-testing/Speculator-Qwen3-8B-Eagle3-converted-071-quantized",
id="qwen3-eagle3-speculator",
),
pytest.param(
"nm-testing/Speculator-Qwen3-8B-Eagle3-converted-071-quantized-w4a16",
id="qwen3-eagle3-speculator-w4a16-verifier",
marks=pytest.mark.skipif(
current_platform.is_rocm(),
reason="The tests are skipped on rocm platform.",
),
),
],
)
def test_eagle3_speculators_model(
vllm_runner, example_prompts, model_path, monkeypatch
):
"""Test Eagle3 speculators models properly initialize speculative decoding.
This test verifies:
1. Eagle3 support is detected for the model
2. Speculative config is automatically initialized from embedded config
3. The draft model path is correctly set to the speculators model
4. Speculative tokens count is valid
5. Text generation works with speculative decoding enabled
"""
# Set environment variable for V1 engine serialization
monkeypatch.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
with vllm_runner(model_path, dtype=torch.bfloat16) as vllm_model:
# Verify Eagle3 support is detected
eagle3_supported = vllm_model.apply_model(supports_eagle3)
assert eagle3_supported, f"Eagle3 should be supported for {model_path}"
vllm_config = vllm_model.llm.llm_engine.vllm_config
assert isinstance(vllm_config.speculative_config, SpeculativeConfig), (
"Speculative config should be initialized for speculators model"
)
spec_config = vllm_config.speculative_config
assert spec_config.num_speculative_tokens > 0, (
f"Expected positive speculative tokens, "
f"got {spec_config.num_speculative_tokens}"
)
assert spec_config.model == model_path, (
f"Draft model should be {model_path}, got {spec_config.model}"
)
vllm_outputs = vllm_model.generate_greedy(example_prompts, max_tokens=20)
assert vllm_outputs, f"No outputs generated for speculators model {model_path}"