[Mini-vLLM] SM86-only cut: models, backends, Rust, tests
- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries - Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels - Remove inc/quark quant loaders; keep compressed-tensors and Marlin - Drop the Rust frontend, pooling entrypoints, and idle test suites - Rebuild kernels for sm_80;sm_86 and strip the extensions - Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,329 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""EAGLE3 Acceptance Length Regression Tests.
|
||||
|
||||
These tests verify that acceptance lengths for EAGLE3 speculative decoding
|
||||
do not regress across vLLM commits. Each test runs inference on the MT-Bench
|
||||
dataset and asserts that the mean acceptance length is within tolerance of
|
||||
the expected baseline.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.conftest import VllmRunner
|
||||
from tests.utils import large_gpu_mark
|
||||
from vllm import SamplingParams
|
||||
from vllm.benchmarks.datasets import get_samples
|
||||
from vllm.inputs import TokensPrompt
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.attention.selector import AttentionSelectorConfig
|
||||
from vllm.v1.metrics.reader import Counter, Vector
|
||||
|
||||
|
||||
@dataclass
|
||||
class Eagle3ModelConfig:
|
||||
verifier: str
|
||||
drafter: str
|
||||
expected_acceptance_length: float
|
||||
expected_acceptance_lengths_per_pos: list[float] = field(default_factory=list)
|
||||
id: str = ""
|
||||
# Backends that are incompatible with this model (will be skipped)
|
||||
excluded_backends: set[AttentionBackendEnum] = field(default_factory=set)
|
||||
# Pytest marks for this configuration
|
||||
marks: list = field(default_factory=list)
|
||||
# Custom relative tolerance (defaults to DEFAULT_RTOL if None)
|
||||
rtol: float | None = None
|
||||
# ROCm-specific test configuration
|
||||
rocm_expected_acceptance_lengths_per_pos: list[float] = field(default_factory=list)
|
||||
|
||||
|
||||
# Model configurations for EAGLE3 acceptance length tests.
|
||||
# Expected acceptance lengths are determined by running baseline benchmarks
|
||||
# using examples/features/speculative_decoding/spec_decode_offline.py
|
||||
# with the MT-Bench dataset.
|
||||
EAGLE3_MODEL_CONFIGS = [
|
||||
Eagle3ModelConfig(
|
||||
verifier="meta-llama/Llama-3.1-8B-Instruct",
|
||||
drafter="RedHatAI/Llama-3.1-8B-Instruct-speculator.eagle3",
|
||||
expected_acceptance_length=2.60,
|
||||
expected_acceptance_lengths_per_pos=[0.7296, 0.5208, 0.3545],
|
||||
id="llama3-8b-eagle3",
|
||||
),
|
||||
Eagle3ModelConfig(
|
||||
verifier="Qwen/Qwen3-8B",
|
||||
drafter="RedHatAI/Qwen3-8B-speculator.eagle3",
|
||||
expected_acceptance_length=2.26,
|
||||
expected_acceptance_lengths_per_pos=[0.6541, 0.3993, 0.2020],
|
||||
id="qwen3-8b-eagle3",
|
||||
),
|
||||
Eagle3ModelConfig(
|
||||
verifier="openai/gpt-oss-20b",
|
||||
drafter="RedHatAI/gpt-oss-20b-speculator.eagle3",
|
||||
expected_acceptance_length=2.56,
|
||||
expected_acceptance_lengths_per_pos=[0.7165, 0.5120, 0.3337],
|
||||
id="gpt-oss-20b-eagle3",
|
||||
# FLASHINFER incompatible: gpt-oss-20b uses sink attention which
|
||||
# FLASHINFER does not support ("sink setting not supported")
|
||||
excluded_backends={AttentionBackendEnum.FLASHINFER},
|
||||
rocm_expected_acceptance_lengths_per_pos=[0.7040, 0.4820, 0.3350],
|
||||
),
|
||||
Eagle3ModelConfig(
|
||||
verifier="Qwen/Qwen3-VL-30B-A3B-Instruct-FP8",
|
||||
drafter="nm-testing/Speculator-Qwen3-30B-MOE-VL-Eagle3",
|
||||
expected_acceptance_length=1.35,
|
||||
expected_acceptance_lengths_per_pos=[0.2900, 0.0620, 0.0115],
|
||||
id="qwen3-30b-moe-vl-eagle3",
|
||||
marks=[
|
||||
pytest.mark.slow_test,
|
||||
],
|
||||
rtol=0.15, # Higher tolerance due to small absolute values at position 2
|
||||
),
|
||||
]
|
||||
|
||||
# Default test parameters
|
||||
DEFAULT_NUM_SPEC_TOKENS = 3
|
||||
DEFAULT_NUM_PROMPTS = 80
|
||||
DEFAULT_OUTPUT_LEN = 256
|
||||
DEFAULT_MAX_MODEL_LEN = 16384
|
||||
DEFAULT_RTOL = 0.05
|
||||
|
||||
# TP sizes to test
|
||||
TP_SIZES = [1, 2, 4]
|
||||
|
||||
|
||||
# Backends excluded from testing due to significantly different behavior
|
||||
EXCLUDED_BACKENDS = {AttentionBackendEnum.FLEX_ATTENTION}
|
||||
|
||||
|
||||
def get_available_attention_backends() -> list[str]:
|
||||
if current_platform.is_rocm():
|
||||
return ["auto"]
|
||||
|
||||
# Check if get_valid_backends is actually defined in the platform class
|
||||
# (not just returning None from __getattr__)
|
||||
get_valid_backends = getattr(current_platform.__class__, "get_valid_backends", None)
|
||||
if get_valid_backends is None:
|
||||
return ["FLASH_ATTN"]
|
||||
|
||||
device_capability = current_platform.get_device_capability()
|
||||
if device_capability is None:
|
||||
return ["FLASH_ATTN"]
|
||||
|
||||
attn_selector_config = AttentionSelectorConfig(
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
kv_cache_dtype=None,
|
||||
block_size=None,
|
||||
use_mla=False,
|
||||
has_sink=False,
|
||||
use_sparse=False,
|
||||
use_mm_prefix=False,
|
||||
)
|
||||
|
||||
valid_backends, _ = current_platform.get_valid_backends(
|
||||
device_capability=device_capability,
|
||||
attn_selector_config=attn_selector_config,
|
||||
)
|
||||
|
||||
return [
|
||||
candidate.backend.name
|
||||
for candidate in valid_backends
|
||||
if candidate.backend not in EXCLUDED_BACKENDS
|
||||
]
|
||||
|
||||
|
||||
def get_attention_backend_params() -> list[str]:
|
||||
return get_available_attention_backends()
|
||||
|
||||
|
||||
def get_tp_size_params() -> list[pytest.param]:
|
||||
num_gpus = torch.accelerator.device_count() if torch.cuda.is_available() else 1
|
||||
return [pytest.param(tp, id=f"tp{tp}") for tp in TP_SIZES if tp <= num_gpus]
|
||||
|
||||
|
||||
def get_mt_bench_prompts(
|
||||
tokenizer, num_prompts: int = DEFAULT_NUM_PROMPTS
|
||||
) -> list[list[int]]:
|
||||
args = SimpleNamespace(
|
||||
dataset_name="hf",
|
||||
dataset_path="philschmid/mt-bench",
|
||||
num_prompts=num_prompts,
|
||||
seed=42,
|
||||
no_oversample=False,
|
||||
endpoint_type="openai-chat",
|
||||
input_len=None,
|
||||
output_len=DEFAULT_OUTPUT_LEN,
|
||||
sharegpt_output_len=DEFAULT_OUTPUT_LEN,
|
||||
hf_name=None,
|
||||
hf_split="train",
|
||||
hf_subset=None,
|
||||
hf_output_len=DEFAULT_OUTPUT_LEN,
|
||||
no_stream=True,
|
||||
disable_shuffle=False,
|
||||
skip_chat_template=False,
|
||||
trust_remote_code=False,
|
||||
enable_multimodal_chat=False,
|
||||
request_id_prefix="",
|
||||
)
|
||||
samples = get_samples(args, tokenizer)
|
||||
prompt_ids = [
|
||||
tokenizer.encode(sample.prompt, add_special_tokens=False) for sample in samples
|
||||
]
|
||||
return prompt_ids
|
||||
|
||||
|
||||
def extract_acceptance_metrics(metrics, num_spec_tokens: int) -> dict:
|
||||
num_drafts = 0
|
||||
num_accepted_tokens = 0
|
||||
acceptance_counts = [0] * num_spec_tokens
|
||||
|
||||
for metric in metrics:
|
||||
if metric.name == "vllm:spec_decode_num_drafts":
|
||||
assert isinstance(metric, Counter)
|
||||
num_drafts += metric.value
|
||||
elif metric.name == "vllm:spec_decode_num_accepted_tokens":
|
||||
assert isinstance(metric, Counter)
|
||||
num_accepted_tokens += metric.value
|
||||
elif metric.name == "vllm:spec_decode_num_accepted_tokens_per_pos":
|
||||
assert isinstance(metric, Vector)
|
||||
for pos in range(min(len(metric.values), num_spec_tokens)):
|
||||
acceptance_counts[pos] += metric.values[pos]
|
||||
|
||||
# Calculate mean acceptance length
|
||||
# Formula: 1 + (accepted_tokens / num_drafts)
|
||||
acceptance_length = 1 + (num_accepted_tokens / num_drafts) if num_drafts > 0 else 1
|
||||
|
||||
# Calculate per-position acceptance lengths (contribution to total)
|
||||
# Each position contributes: accepted_at_pos / num_drafts
|
||||
acceptance_lengths_per_pos = [
|
||||
count / num_drafts if num_drafts > 0 else 0.0 for count in acceptance_counts
|
||||
]
|
||||
|
||||
return {
|
||||
"acceptance_length": acceptance_length,
|
||||
"acceptance_lengths_per_pos": acceptance_lengths_per_pos,
|
||||
"num_drafts": num_drafts,
|
||||
"num_accepted_tokens": num_accepted_tokens,
|
||||
}
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=40)
|
||||
@pytest.mark.skipif(
|
||||
not current_platform.is_cuda_alike(),
|
||||
reason="This test is only supported on CUDA-alike platforms.",
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"model_config",
|
||||
[
|
||||
pytest.param(config, id=config.id, marks=config.marks)
|
||||
for config in EAGLE3_MODEL_CONFIGS
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("num_spec_tokens", [DEFAULT_NUM_SPEC_TOKENS])
|
||||
@pytest.mark.parametrize("tp_size", get_tp_size_params())
|
||||
@pytest.mark.parametrize("attention_backend", get_attention_backend_params())
|
||||
def test_eagle3_acceptance_length(
|
||||
model_config: Eagle3ModelConfig,
|
||||
num_spec_tokens: int,
|
||||
tp_size: int,
|
||||
attention_backend: str,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
# Skip if this backend is incompatible with the model
|
||||
attention_config = None
|
||||
if attention_backend != "auto":
|
||||
backend_enum = AttentionBackendEnum[attention_backend]
|
||||
if backend_enum in model_config.excluded_backends:
|
||||
pytest.skip(f"{attention_backend} is incompatible with {model_config.id}")
|
||||
attention_config = {"backend": attention_backend}
|
||||
|
||||
with monkeypatch.context() as m:
|
||||
m.setenv("VLLM_ALLOW_INSECURE_SERIALIZATION", "1")
|
||||
|
||||
with VllmRunner(
|
||||
model_name=model_config.verifier,
|
||||
speculative_config={
|
||||
"method": "eagle3",
|
||||
"model": model_config.drafter,
|
||||
"num_speculative_tokens": num_spec_tokens,
|
||||
},
|
||||
attention_config=attention_config,
|
||||
tensor_parallel_size=tp_size,
|
||||
gpu_memory_utilization=0.7,
|
||||
disable_log_stats=False,
|
||||
max_model_len=DEFAULT_MAX_MODEL_LEN,
|
||||
# Qwen/Qwen3-30B-A3B-FP8 with TP=4 needs EP
|
||||
# https://github.com/vllm-project/vllm/issues/25292
|
||||
enable_expert_parallel=(
|
||||
tp_size == 4 and "Qwen3-VL" in model_config.verifier
|
||||
),
|
||||
) as vllm_runner:
|
||||
tokenizer = vllm_runner.llm.get_tokenizer()
|
||||
prompt_ids = get_mt_bench_prompts(tokenizer, DEFAULT_NUM_PROMPTS)
|
||||
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0,
|
||||
max_tokens=DEFAULT_OUTPUT_LEN,
|
||||
)
|
||||
vllm_runner.llm.generate(
|
||||
[TokensPrompt(prompt_token_ids=ids) for ids in prompt_ids],
|
||||
sampling_params=sampling_params,
|
||||
)
|
||||
|
||||
metrics = vllm_runner.llm.get_metrics()
|
||||
results = extract_acceptance_metrics(metrics, num_spec_tokens)
|
||||
|
||||
actual_acceptance_length = results["acceptance_length"]
|
||||
expected = model_config.expected_acceptance_length
|
||||
actual_per_pos = results["acceptance_lengths_per_pos"]
|
||||
expected_per_pos = model_config.expected_acceptance_lengths_per_pos
|
||||
if (
|
||||
current_platform.is_rocm()
|
||||
and model_config.rocm_expected_acceptance_lengths_per_pos
|
||||
):
|
||||
expected_per_pos = model_config.rocm_expected_acceptance_lengths_per_pos
|
||||
|
||||
rel_error = abs(actual_acceptance_length - expected) / expected
|
||||
|
||||
# Overall acceptance length always uses DEFAULT_RTOL
|
||||
assert rel_error <= DEFAULT_RTOL, (
|
||||
f"Acceptance length regression detected for {model_config.id}!\n"
|
||||
f" Expected: {expected:.3f}\n"
|
||||
f" Actual: {actual_acceptance_length:.3f}\n"
|
||||
f" Relative error: {rel_error:.2%} (tolerance: {DEFAULT_RTOL:.2%})\n"
|
||||
f" Drafts: {results['num_drafts']}, "
|
||||
f"Accepted tokens: {results['num_accepted_tokens']}"
|
||||
)
|
||||
|
||||
if expected_per_pos and len(expected_per_pos) == len(actual_per_pos):
|
||||
# Per-position checks use model-specific rtol if provided
|
||||
rtol = (
|
||||
model_config.rtol if model_config.rtol is not None else DEFAULT_RTOL
|
||||
)
|
||||
for pos, (actual, exp) in enumerate(
|
||||
zip(actual_per_pos, expected_per_pos)
|
||||
):
|
||||
if exp > 0:
|
||||
min_expected = exp * (1 - rtol)
|
||||
assert actual >= min_expected, (
|
||||
f"Per-position acceptance length regression at pos {pos} "
|
||||
f"for {model_config.id}!\n"
|
||||
f" Expected: {exp:.3f}\n"
|
||||
f" Actual: {actual:.3f}\n"
|
||||
f" Minimum: {min_expected:.3f}\n"
|
||||
f" Tolerance: rtol={rtol:.2%}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"\n{model_config.id} [tp={tp_size}, backend={attention_backend}]: "
|
||||
f"acceptance_length={actual_acceptance_length:.3f}"
|
||||
f" (expected={expected:.3f}, rel_error={rel_error:.2%})"
|
||||
)
|
||||
print(f" Per-position: {[f'{v:.3f}' for v in actual_per_pos]}")
|
||||
if expected_per_pos:
|
||||
print(f" Expected: {[f'{v:.3f}' for v in expected_per_pos]}")
|
||||
@@ -1,461 +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.model_executor.models.qwen3_dflash import (
|
||||
_add_global_draft_layer_exclusions,
|
||||
)
|
||||
from vllm.model_executor.models.qwen3_dflash2 import _grouped_conv, _score_edges
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash2.speculator import DFlash2Speculator
|
||||
|
||||
|
||||
@pytest.mark.parametrize("block_size", [5, 8])
|
||||
def test_grouped_conv_matches_reference(block_size: int):
|
||||
torch.manual_seed(0)
|
||||
batch, taps, num_groups, group_size = 3, 3, 4, 2
|
||||
hidden = torch.randn(batch * block_size, num_groups * group_size)
|
||||
delta = torch.randn(batch * block_size, taps, num_groups)
|
||||
base = torch.randn(taps, num_groups * group_size)
|
||||
|
||||
actual = _grouped_conv(
|
||||
hidden, delta, base, block_size, num_groups, group_size, taps
|
||||
)
|
||||
hidden_blocks = hidden.view(batch, block_size, num_groups, group_size)
|
||||
expected = torch.zeros_like(hidden_blocks)
|
||||
base = base.view(taps, num_groups, group_size)
|
||||
delta = delta.view(batch, block_size, taps, num_groups)
|
||||
for position in range(block_size):
|
||||
for tap in range(min(taps, position + 1)):
|
||||
expected[:, position] += (
|
||||
base[tap] + delta[:, position, tap, :, None]
|
||||
) * hidden_blocks[:, position - tap]
|
||||
|
||||
torch.testing.assert_close(actual, expected.flatten(0, 1).flatten(-2))
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_cuda(), reason="This test requires CUDA")
|
||||
@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16])
|
||||
@pytest.mark.parametrize(
|
||||
"batch,num_groups,group_size,block_size,taps",
|
||||
[
|
||||
(7, 13, 11, 5, 1),
|
||||
(7, 13, 11, 5, 3),
|
||||
(7, 13, 11, 8, 2),
|
||||
(16, 64, 16, 8, 2),
|
||||
(16, 160, 16, 8, 2),
|
||||
],
|
||||
)
|
||||
def test_grouped_conv_triton_matches_reference(
|
||||
dtype: torch.dtype,
|
||||
batch: int,
|
||||
num_groups: int,
|
||||
group_size: int,
|
||||
block_size: int,
|
||||
taps: int,
|
||||
):
|
||||
torch.manual_seed(0)
|
||||
rows = batch * block_size
|
||||
hidden = torch.randn(rows, num_groups * group_size, device="cuda", dtype=dtype)
|
||||
base = torch.randn(taps, num_groups * group_size, device="cuda", dtype=dtype)
|
||||
projected = torch.randn(rows, 2, taps, num_groups, device="cuda", dtype=dtype)
|
||||
delta = projected[:, 1]
|
||||
|
||||
actual = _grouped_conv(
|
||||
hidden, delta, base, block_size, num_groups, group_size, taps
|
||||
)
|
||||
|
||||
hidden_blocks = hidden.float().view(batch, block_size, num_groups, group_size)
|
||||
expected = torch.zeros_like(hidden_blocks)
|
||||
base_blocks = base.float().view(taps, num_groups, group_size)
|
||||
delta_blocks = delta.float().view(batch, block_size, taps, num_groups)
|
||||
for position in range(block_size):
|
||||
for tap in range(min(taps, position + 1)):
|
||||
expected[:, position] += (
|
||||
base_blocks[tap] + delta_blocks[:, position, tap, :, None]
|
||||
) * hidden_blocks[:, position - tap]
|
||||
|
||||
torch.testing.assert_close(
|
||||
actual,
|
||||
expected.flatten(0, 1).flatten(-2).to(dtype),
|
||||
rtol=1e-2 if dtype is torch.bfloat16 else 1e-5,
|
||||
atol=1e-2 if dtype is torch.bfloat16 else 1e-5,
|
||||
)
|
||||
|
||||
|
||||
def test_draft_quant_exclusions_include_global_layer_indices():
|
||||
quant_config = SimpleNamespace(
|
||||
exclude_modules=[
|
||||
"layers.0.mlp_conv*",
|
||||
"*layers.4.self_attn.q_proj",
|
||||
"layers.88.already_global",
|
||||
"lilicorr.layers.0.mlp.0",
|
||||
]
|
||||
)
|
||||
|
||||
_add_global_draft_layer_exclusions(quant_config, 88, 5)
|
||||
|
||||
assert "layers.88.mlp_conv*" in quant_config.exclude_modules
|
||||
assert "*layers.92.self_attn.q_proj" in quant_config.exclude_modules
|
||||
assert quant_config.exclude_modules.count("layers.88.already_global") == 1
|
||||
assert "lilicorr.layers.88.mlp.0" not in quant_config.exclude_modules
|
||||
|
||||
|
||||
def test_selector_edges_match_sequential_reference():
|
||||
torch.manual_seed(1)
|
||||
batch, steps, top_k, rank = 2, 4, 3, 5
|
||||
vocab = 17
|
||||
predecessors = torch.randn(vocab, rank)
|
||||
successors = torch.randn(vocab, rank)
|
||||
candidate_ids = torch.randint(vocab, (batch, steps, top_k))
|
||||
unary = torch.randn(batch, steps, top_k)
|
||||
hidden = torch.randn(batch, steps, rank)
|
||||
anchors = torch.randint(vocab, (batch,))
|
||||
|
||||
actual = _score_edges(
|
||||
predecessors,
|
||||
successors,
|
||||
candidate_ids,
|
||||
unary,
|
||||
hidden,
|
||||
anchors,
|
||||
top_k,
|
||||
)
|
||||
expected = torch.empty_like(actual)
|
||||
for step in range(steps):
|
||||
pred = (
|
||||
anchors[:, None].expand(-1, top_k)
|
||||
if step == 0
|
||||
else candidate_ids[:, step - 1]
|
||||
)
|
||||
expected[:, step] = unary[:, step, None] + torch.einsum(
|
||||
"bpr,bcr->bpc",
|
||||
predecessors[pred] * hidden[:, step, None],
|
||||
successors[candidate_ids[:, step]],
|
||||
)
|
||||
|
||||
torch.testing.assert_close(actual, expected)
|
||||
|
||||
|
||||
def _stub_base(monkeypatch, draft_logits):
|
||||
"""A DFlashSpeculator.__init__ that allocates only what the base class would.
|
||||
|
||||
The real base class fills draft_logits from draft_logits_spec, so callers
|
||||
pass a tensor already in that state.
|
||||
"""
|
||||
|
||||
def init_base(self, _vllm_config, device):
|
||||
self.draft_model_config = SimpleNamespace(
|
||||
hf_config=SimpleNamespace(dflash_config={"selector_top_k": 3})
|
||||
)
|
||||
self.max_num_reqs = 2
|
||||
self.num_query_per_req = 5
|
||||
self.num_speculative_steps = 4
|
||||
self.vocab_size = 17
|
||||
self.draft_tokens = torch.empty((2, 4), dtype=torch.int64, device=device)
|
||||
self.draft_logits = draft_logits
|
||||
|
||||
monkeypatch.setattr(DFlashSpeculator, "__init__", init_base)
|
||||
|
||||
|
||||
def test_selector_leaves_greedy_drafting_without_proposal_logits(monkeypatch):
|
||||
"""Greedy is the default, and it caches no proposal distribution.
|
||||
|
||||
The base class allocates draft_logits only for "probabilistic"; verification
|
||||
reads `draft_logits is None` to decide whether a distribution is on offer, so
|
||||
allocating one here would claim a proposal the walk never sampled from.
|
||||
"""
|
||||
_stub_base(monkeypatch, None)
|
||||
speculator = DFlash2Speculator(None, torch.device("cpu"))
|
||||
|
||||
assert speculator.draft_logits is None
|
||||
|
||||
|
||||
def test_selector_asks_for_fp32_proposal_logits():
|
||||
"""The spec the base class allocates from: fp32, filled -inf.
|
||||
|
||||
Not the head dtype -- rounding selector scores to bf16 moves the argmax of a
|
||||
candidate row often enough that the walk and the rejection sampler checking it
|
||||
would no longer read the same distribution.
|
||||
"""
|
||||
dtype, fill = DFlash2Speculator.draft_logits_spec(None, None)
|
||||
|
||||
assert dtype is torch.float32
|
||||
assert fill == float("-inf")
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
@pytest.mark.parametrize("variant", ["dflash2", "lilicorr", "lilicorr_plain"])
|
||||
def test_candidate_model_decoder_layer_cls(monkeypatch, variant):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorr
|
||||
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3DecoderLayer
|
||||
from vllm.model_executor.models.qwen3_dflash2 import (
|
||||
DFlash2Qwen3DecoderLayer,
|
||||
DFlash2Qwen3Model,
|
||||
)
|
||||
|
||||
# 1. Mock get_current_vllm_config and TP groups
|
||||
mock_current_vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(
|
||||
block_size=16,
|
||||
user_specified_block_size=False,
|
||||
kv_cache_dtype_skip_layers=[],
|
||||
cache_dtype="auto",
|
||||
sliding_window=None,
|
||||
enable_prefix_caching=False,
|
||||
),
|
||||
kv_transfer_config=None,
|
||||
speculative_config=None,
|
||||
attention_config=SimpleNamespace(
|
||||
use_non_causal=False,
|
||||
backend=None,
|
||||
backend_per_kind={},
|
||||
),
|
||||
parallel_config=SimpleNamespace(
|
||||
prefill_context_parallel_size=1,
|
||||
decode_context_parallel_size=1,
|
||||
),
|
||||
compilation_config=SimpleNamespace(
|
||||
compile_custom_ops=False,
|
||||
custom_ops="all",
|
||||
enabled_custom_ops=set(),
|
||||
static_forward_context={},
|
||||
mode=0, # CompilationMode.NONE is 0
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
dtype=torch.float32,
|
||||
is_mm_prefix_lm=False,
|
||||
rswa_window=None,
|
||||
),
|
||||
kernel_config=SimpleNamespace(
|
||||
linear_backend="auto",
|
||||
),
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
monkeypatch.setattr(
|
||||
current_platform,
|
||||
"get_attn_backend_cls",
|
||||
lambda *args, **kwargs: (
|
||||
"vllm.v1.attention.backends.cpu_attn.CPUAttentionBackend"
|
||||
),
|
||||
)
|
||||
|
||||
class MockGroup:
|
||||
rank_in_group = 0
|
||||
world_size = 1
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm.distributed.parallel_state._TP",
|
||||
MockGroup(),
|
||||
)
|
||||
|
||||
# 2. Mock vllm_config
|
||||
hf_config = SimpleNamespace(
|
||||
vocab_size=1000,
|
||||
hidden_size=256,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=8,
|
||||
num_key_value_heads=2,
|
||||
max_position_embeddings=2048,
|
||||
rms_norm_eps=1e-6,
|
||||
rope_parameters={},
|
||||
intermediate_size=512,
|
||||
hidden_act="silu",
|
||||
dflash_config={
|
||||
"selector_rank": 4,
|
||||
"selector_top_k": 3,
|
||||
"conv_kernel_size": 0 if variant == "lilicorr_plain" else 3,
|
||||
"conv_group_size": 0 if variant == "lilicorr_plain" else 2,
|
||||
"block_size": 5,
|
||||
"lilicorr_candidate_topk": 4,
|
||||
"lilicorr_hidden_size": 8,
|
||||
"lilicorr_num_layers": 2,
|
||||
"lilicorr_num_heads": 2,
|
||||
"lilicorr_mlp_ratio": 2.0,
|
||||
"lilicorr_factor_dim": 4,
|
||||
"lilicorr_vector_eps": 1e-6,
|
||||
"lilicorr_logit_scale": 3.0,
|
||||
"use_aux_hidden_state": False,
|
||||
},
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(
|
||||
hf_config=hf_config,
|
||||
quantization=None,
|
||||
),
|
||||
num_speculative_tokens=4,
|
||||
enable_adaptive_verification=False,
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
dtype=torch.float32,
|
||||
is_mm_prefix_lm=False,
|
||||
),
|
||||
load_config=SimpleNamespace(
|
||||
quantization=None,
|
||||
quantization_param_path=None,
|
||||
),
|
||||
)
|
||||
mock_current_vllm_config.speculative_config = vllm_config.speculative_config
|
||||
vllm_config.compilation_config = mock_current_vllm_config.compilation_config
|
||||
|
||||
# 3. Instantiate the model under meta device to avoid parameter allocation issues
|
||||
with set_current_vllm_config(mock_current_vllm_config), torch.device("meta"):
|
||||
model_cls = DFlash2Qwen3Model if variant == "dflash2" else LiLiCorr
|
||||
model = model_cls(vllm_config=vllm_config)
|
||||
|
||||
# 4. Assert that the layers are DFlash2Qwen3DecoderLayer (the subclass)
|
||||
assert len(model.layers) == 2
|
||||
expected = (
|
||||
DFlashQwen3DecoderLayer
|
||||
if variant == "lilicorr_plain"
|
||||
else DFlash2Qwen3DecoderLayer
|
||||
)
|
||||
assert type(model.layers[0]) is expected
|
||||
|
||||
|
||||
def test_conv_projections_use_draft_quant_config(monkeypatch):
|
||||
from torch import nn
|
||||
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.model_executor.layers.quantization import modelopt
|
||||
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3DecoderLayer
|
||||
from vllm.model_executor.models.qwen3_dflash2 import DFlash2Qwen3DecoderLayer
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
monkeypatch.setattr(
|
||||
parallel_state, "_TP", SimpleNamespace(rank_in_group=0, world_size=1)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
DFlashQwen3DecoderLayer,
|
||||
"__init__",
|
||||
lambda self, *a, **kw: nn.Module.__init__(self),
|
||||
)
|
||||
# Exercise the real quantized parameter allocation without selecting a GPU kernel.
|
||||
monkeypatch.setattr(
|
||||
modelopt,
|
||||
"select_linear_kernel",
|
||||
lambda *a, **kw: SimpleNamespace(input_quant_key=lambda: None),
|
||||
)
|
||||
quant_config = modelopt.ModelOptNvFp4Config(
|
||||
quant_method="W4A16_NVFP4", is_checkpoint_nvfp4_serialized=True
|
||||
)
|
||||
layer = DFlash2Qwen3DecoderLayer(
|
||||
SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(num_speculative_tokens=7),
|
||||
model_config=SimpleNamespace(dtype=torch.bfloat16),
|
||||
),
|
||||
config=SimpleNamespace(
|
||||
hidden_size=16,
|
||||
dflash_config={"conv_kernel_size": 2, "conv_group_size": 2},
|
||||
),
|
||||
layer_idx=0,
|
||||
prefix="model.layers.0",
|
||||
quant_config=quant_config,
|
||||
)
|
||||
for name in ("attention_conv", "mlp_conv"):
|
||||
module = getattr(layer, name)
|
||||
projection = module.kernel_projection
|
||||
assert projection.weight.dtype == torch.uint8
|
||||
assert projection.weight.shape == (32, 8)
|
||||
weight = torch.ones_like(projection.weight)
|
||||
AutoWeightsLoader(module).load_weights([("kernel_projection.weight", weight)])
|
||||
torch.testing.assert_close(projection.weight, weight)
|
||||
assert module.base_kernel.dtype == torch.bfloat16
|
||||
|
||||
|
||||
def test_context_kv_uses_quantized_projection_fallback(monkeypatch):
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.models import qwen3_dflash
|
||||
|
||||
class Projection(nn.Module):
|
||||
def __init__(self, packed_weight):
|
||||
super().__init__()
|
||||
self.register_buffer("packed_weight", packed_weight)
|
||||
self.quant_method = object()
|
||||
self.calls = 0
|
||||
|
||||
def forward(self, hidden_states):
|
||||
self.calls += 1
|
||||
return torch.nn.functional.linear(hidden_states, self.packed_weight), None
|
||||
|
||||
monkeypatch.setattr(
|
||||
qwen3_dflash.ops,
|
||||
"rms_norm",
|
||||
lambda output, hidden_states, weight, eps: output.copy_(hidden_states),
|
||||
)
|
||||
context_states = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
|
||||
projections = [
|
||||
Projection(
|
||||
torch.tensor(
|
||||
[
|
||||
[0.0, 0.0],
|
||||
[0.0, 0.0],
|
||||
[1.0, 0.0],
|
||||
[0.0, 1.0],
|
||||
[1.0, 1.0],
|
||||
[1.0, -1.0],
|
||||
]
|
||||
)
|
||||
),
|
||||
Projection(
|
||||
torch.tensor(
|
||||
[
|
||||
[0.0, 0.0],
|
||||
[0.0, 0.0],
|
||||
[2.0, 0.0],
|
||||
[0.0, 2.0],
|
||||
[-1.0, 0.0],
|
||||
[0.0, -1.0],
|
||||
]
|
||||
)
|
||||
),
|
||||
]
|
||||
model = SimpleNamespace(
|
||||
hidden_norm=SimpleNamespace(weight=nn.Parameter(torch.ones(2))),
|
||||
_rms_norm_eps=1e-6,
|
||||
)
|
||||
layers_attn = [
|
||||
SimpleNamespace(
|
||||
qkv_proj=projection,
|
||||
q_size=2,
|
||||
k_norm=SimpleNamespace(weight=nn.Parameter(torch.ones(2))),
|
||||
)
|
||||
for projection in projections
|
||||
]
|
||||
qwen3_dflash.DFlashQwen3Model._build_context_kv_buffers(
|
||||
model,
|
||||
layers_attn,
|
||||
has_bias=False,
|
||||
)
|
||||
assert model._fused_kv_weight is None
|
||||
assert all(not hasattr(projection, "weight") for projection in projections)
|
||||
|
||||
actual_k, actual_v = qwen3_dflash.DFlashQwen3Model._project_context_kv(
|
||||
model,
|
||||
context_states,
|
||||
num_ctx=2,
|
||||
num_layers=2,
|
||||
num_kv_heads=1,
|
||||
head_dim=2,
|
||||
)
|
||||
|
||||
expected_k = torch.tensor(
|
||||
[[[1.0, 2.0], [3.0, 4.0]], [[2.0, 4.0], [6.0, 8.0]]]
|
||||
).unsqueeze(2)
|
||||
expected_v = torch.tensor(
|
||||
[[[3.0, -1.0], [7.0, -1.0]], [[-1.0, -2.0], [-3.0, -4.0]]]
|
||||
).unsqueeze(2)
|
||||
torch.testing.assert_close(actual_k, expected_k)
|
||||
torch.testing.assert_close(actual_v, expected_v)
|
||||
assert [projection.calls for projection in projections] == [1, 1]
|
||||
@@ -1,127 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Config-only DFlash behavior.
|
||||
|
||||
``dflash_has_any_non_causal`` decides pre-build whether the draft needs a
|
||||
non-causal-capable backend, so its branch table (explicit override, SWA-derived
|
||||
per-layer causality, and the no-``layer_types`` fallback) is worth pinning.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm.model_executor.models.qwen3_dflash import (
|
||||
_dflash_layer_causal,
|
||||
_get_dflash_fc_input_size,
|
||||
dflash_has_any_non_causal,
|
||||
)
|
||||
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
|
||||
get_eagle3_aux_layers_from_config,
|
||||
)
|
||||
|
||||
|
||||
def _config(num_hidden_layers, layer_types=None, causal_override=None, is_causal=None):
|
||||
dflash_config = None if causal_override is None else {"causal": causal_override}
|
||||
return SimpleNamespace(
|
||||
num_hidden_layers=num_hidden_layers,
|
||||
layer_types=layer_types,
|
||||
dflash_config=dflash_config,
|
||||
is_causal=is_causal,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"config,expected",
|
||||
[
|
||||
# Override forces causality on every layer, ignoring layer_types.
|
||||
(_config(2, layer_types=["full_attention"] * 2, causal_override=True), False),
|
||||
# Override forces non-causal on every layer.
|
||||
(
|
||||
_config(2, layer_types=["sliding_attention"] * 2, causal_override=False),
|
||||
True,
|
||||
),
|
||||
# DFlash2 stores the explicit attention semantics at the top level.
|
||||
(
|
||||
_config(
|
||||
2,
|
||||
layer_types=["sliding_attention"] * 2,
|
||||
is_causal=False,
|
||||
),
|
||||
True,
|
||||
),
|
||||
(
|
||||
_config(2, layer_types=["full_attention"] * 2, is_causal=True),
|
||||
False,
|
||||
),
|
||||
# SWA-derived: full-attention layers are non-causal.
|
||||
(_config(2, layer_types=["sliding_attention", "full_attention"]), True),
|
||||
# SWA-derived: all-sliding is fully causal.
|
||||
(_config(2, layer_types=["sliding_attention", "sliding_attention"]), False),
|
||||
# No layer_types -> non-causal fallback.
|
||||
(_config(2, layer_types=None), True),
|
||||
(_config(2, layer_types=[]), True),
|
||||
],
|
||||
)
|
||||
def test_dflash_has_any_non_causal(config, expected):
|
||||
assert dflash_has_any_non_causal(config) is expected
|
||||
|
||||
|
||||
def test_dflash_layer_causal_is_per_layer():
|
||||
config = _config(2, layer_types=["sliding_attention", "full_attention"])
|
||||
assert _dflash_layer_causal(config, 0) is True
|
||||
assert _dflash_layer_causal(config, 1) is False
|
||||
|
||||
|
||||
def test_dflash_layer_causal_honors_top_level_override():
|
||||
config = _config(
|
||||
2,
|
||||
layer_types=["sliding_attention", "full_attention"],
|
||||
is_causal=False,
|
||||
)
|
||||
assert _dflash_layer_causal(config, 0) is False
|
||||
assert _dflash_layer_causal(config, 1) is False
|
||||
|
||||
|
||||
def _vllm_config(**draft_config):
|
||||
config = SimpleNamespace(**draft_config)
|
||||
return SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(hf_config=config)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_dflash_fc_uses_aux_layer_count():
|
||||
vllm_config = _vllm_config(
|
||||
num_hidden_layers=5,
|
||||
hidden_size=4096,
|
||||
target_hidden_size=None,
|
||||
target_layer_ids=[1, 17, 32],
|
||||
)
|
||||
|
||||
assert _get_dflash_fc_input_size(vllm_config) == 3 * 4096
|
||||
|
||||
|
||||
def test_dflash_target_layers_map_to_post_layer_boundaries():
|
||||
vllm_config = _vllm_config(
|
||||
dflash_config={"target_layer_ids": [0, 16, 31]},
|
||||
)
|
||||
|
||||
assert get_eagle3_aux_layers_from_config(vllm_config.speculative_config) == (
|
||||
1,
|
||||
17,
|
||||
32,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("config_name", ["dflash_config", "eagle_config"])
|
||||
def test_eagle_aux_layers_preserves_legacy_layer_ids(config_name):
|
||||
layer_ids = [1, 17, 32]
|
||||
vllm_config = _vllm_config(
|
||||
**{config_name: {"layer_ids": layer_ids}},
|
||||
)
|
||||
|
||||
assert get_eagle3_aux_layers_from_config(vllm_config.speculative_config) == tuple(
|
||||
layer_ids
|
||||
)
|
||||
@@ -1,283 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
ModelOptLinearMethod,
|
||||
resolve,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import (
|
||||
dequantize_to_dtype,
|
||||
nvfp4_gathered_bias,
|
||||
)
|
||||
from vllm.model_executor.models.qwen3_dspark import DSparkMarkovHead
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
|
||||
from vllm.v1.worker.gpu.spec_decode.dspark.speculator import DSparkSpeculator
|
||||
|
||||
|
||||
def _markov_head(weight: torch.Tensor) -> DSparkMarkovHead:
|
||||
head = DSparkMarkovHead.__new__(DSparkMarkovHead)
|
||||
nn.Module.__init__(head)
|
||||
head.markov_w2 = nn.Linear(
|
||||
weight.shape[1], weight.shape[0], bias=False, dtype=weight.dtype
|
||||
)
|
||||
head.markov_w2.weight.data.copy_(weight)
|
||||
head.markov_w2._retain_weight_for_gather = False
|
||||
head.markov_w2.is_w4a16_nvfp4 = False
|
||||
return head
|
||||
|
||||
|
||||
def test_gathered_markov_bias_overwrites_dense_logits():
|
||||
weight = torch.arange(21, dtype=torch.float32).view(7, 3) / 10
|
||||
markov_embed = torch.tensor([[0.5, -1.0, 0.25], [1.0, 0.5, -0.5]])
|
||||
logits = torch.tensor(
|
||||
[
|
||||
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7],
|
||||
[0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1],
|
||||
]
|
||||
)
|
||||
values, index = logits.topk(3, dim=-1)
|
||||
values = torch.stack((values, torch.zeros_like(values)), dim=1)[:, 0]
|
||||
expected = values + torch.bmm(weight[index], markov_embed.unsqueeze(-1)).squeeze(-1)
|
||||
logits.fill_(float("-inf"))
|
||||
|
||||
result = _markov_head(weight).apply_bias_gathered(
|
||||
markov_embed, logits, values, index
|
||||
)
|
||||
|
||||
assert result is logits
|
||||
torch.testing.assert_close(result.gather(1, index), expected)
|
||||
selected = torch.zeros_like(result, dtype=torch.bool).scatter_(1, index, True)
|
||||
assert torch.isneginf(result.masked_select(~selected)).all()
|
||||
|
||||
|
||||
def test_gathered_markov_bias_matches_dense_at_full_vocab():
|
||||
weight = torch.arange(15, dtype=torch.float32).view(5, 3) / 10
|
||||
markov_embed = torch.tensor([[0.5, -1.0, 0.25]])
|
||||
logits = torch.tensor([[0.1, 0.4, -0.2, 0.3, 0.0]])
|
||||
original = logits.clone()
|
||||
values, index = logits.topk(logits.shape[-1], dim=-1)
|
||||
scale = 0.5
|
||||
logits.fill_(float("-inf"))
|
||||
|
||||
result = _markov_head(weight).apply_bias_gathered(
|
||||
markov_embed, logits, values, index, scale
|
||||
)
|
||||
|
||||
expected = original + markov_embed @ weight.T * scale
|
||||
torch.testing.assert_close(result, expected)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("use_fp64", [False, True])
|
||||
def test_dspark_revisited_position_uses_step_seed(use_fp64):
|
||||
"""A cached draft at a revisited position must use its current step."""
|
||||
device = torch.device("cuda")
|
||||
batch = 4096
|
||||
spec = DSparkSpeculator.__new__(DSparkSpeculator)
|
||||
spec.acceptance_estimator = None
|
||||
spec._d2t_scatter_index = None
|
||||
spec.draft_watermarker = None
|
||||
spec.use_fp64_gumbel = use_fp64
|
||||
spec.temperature = torch.ones(batch, device=device)
|
||||
spec.seeds = torch.arange(batch, dtype=torch.int64, device=device)
|
||||
spec._step_cols = torch.arange(2, dtype=torch.int32, device=device)
|
||||
spec.draft_logits = torch.empty(batch, 2, 2, device=device)
|
||||
logits = torch.tensor([0.7, 0.3], device=device).log().expand(batch, -1)
|
||||
mapping = torch.arange(batch, device=device)
|
||||
positions = torch.full((batch,), 22, dtype=torch.int64, device=device)
|
||||
|
||||
first = spec._sample_logits(logits, mapping, positions, 1)
|
||||
repeated = spec._sample_logits(logits, mapping, positions, 1)
|
||||
next_round = spec._sample_logits(logits, mapping, positions, 0)
|
||||
torch.testing.assert_close(first, repeated)
|
||||
expected = gumbel_sample(
|
||||
logits,
|
||||
mapping,
|
||||
spec.temperature,
|
||||
spec.seeds,
|
||||
positions - 1,
|
||||
apply_temperature=True,
|
||||
is_drafting=True,
|
||||
logits_cache=spec.draft_logits,
|
||||
logits_cache_col=spec._step_cols[0],
|
||||
use_fp64=use_fp64,
|
||||
)
|
||||
torch.testing.assert_close(next_round, expected)
|
||||
mismatch_rate = (first != next_round).float().mean().item()
|
||||
assert 0.35 < mismatch_rate < 0.5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cuda_alike_platform", [False, True])
|
||||
def test_gathered_markov_bias_dequantizes_selected_w4a16_rows(
|
||||
monkeypatch, cuda_alike_platform
|
||||
):
|
||||
packed_weight = torch.tensor(
|
||||
[[0x00] * 8, [0x22] * 8, [0xAA] * 8, [0x31] * 8], dtype=torch.uint8
|
||||
)
|
||||
weight_scale = torch.ones((4, 1), dtype=torch.float8_e4m3fn)
|
||||
|
||||
layer = nn.Module()
|
||||
layer.weight = nn.Parameter(packed_weight, requires_grad=False)
|
||||
layer.weight_scale = nn.Parameter(weight_scale, requires_grad=False)
|
||||
layer.weight_scale_2 = nn.Parameter(torch.ones(1), requires_grad=False)
|
||||
layer._retain_weight_for_gather = True
|
||||
|
||||
spec, ctx, fmt = resolve("W4A16_NVFP4", type("Config", (), {"group_size": 16}), "")
|
||||
method = ModelOptLinearMethod(spec, ctx, fmt)
|
||||
|
||||
class RepackingKernel:
|
||||
@staticmethod
|
||||
def process_weights_after_loading(layer):
|
||||
layer.weight = nn.Parameter(
|
||||
torch.zeros((1, 1), dtype=torch.int32), requires_grad=False
|
||||
)
|
||||
layer.weight_scale = nn.Parameter(
|
||||
torch.zeros((1, 1), dtype=torch.float32), requires_grad=False
|
||||
)
|
||||
layer.weight_global_scale = nn.Parameter(
|
||||
torch.zeros(1, dtype=torch.float32), requires_grad=False
|
||||
)
|
||||
|
||||
method.kernel = RepackingKernel()
|
||||
method.process_weights_after_loading(layer)
|
||||
assert layer.is_w4a16_nvfp4
|
||||
|
||||
head = DSparkMarkovHead.__new__(DSparkMarkovHead)
|
||||
nn.Module.__init__(head)
|
||||
head.markov_w2 = layer
|
||||
markov_embed = torch.tensor([[1.0] * 16, [0.5, -0.5] * 8], dtype=torch.float32)
|
||||
index = torch.tensor([[1, 3], [2, 0]])
|
||||
values = torch.tensor([[0.25, -0.5], [1.0, 2.0]])
|
||||
original_values = values.clone()
|
||||
logits = torch.full((2, 4), float("-inf"))
|
||||
|
||||
# CPU tensors must use the fallback even on CUDA/ROCm hosts.
|
||||
monkeypatch.setattr(current_platform, "is_cuda_alike", lambda: cuda_alike_platform)
|
||||
result = head.apply_bias_gathered(markov_embed, logits, values, index)
|
||||
|
||||
dense_weight = torch.tensor([[0.0] * 16, [1.0] * 16, [-1.0] * 16, [0.5, 1.5] * 8])
|
||||
expected = original_values + torch.bmm(
|
||||
dense_weight[index], markov_embed.unsqueeze(-1)
|
||||
).squeeze(-1)
|
||||
torch.testing.assert_close(result.gather(1, index), expected)
|
||||
torch.testing.assert_close(values, original_values)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_nvfp4_gathered_bias_rejects_non_16_group_size():
|
||||
device = torch.device("cuda")
|
||||
rank = 32
|
||||
vocab_size = 2
|
||||
|
||||
with pytest.raises(ValueError, match="group size of 16"):
|
||||
nvfp4_gathered_bias(
|
||||
torch.zeros((1, rank), dtype=torch.bfloat16, device=device),
|
||||
torch.zeros((vocab_size, rank // 2), dtype=torch.uint8, device=device),
|
||||
torch.ones(
|
||||
(vocab_size, rank // 32), dtype=torch.float8_e4m3fn, device=device
|
||||
),
|
||||
torch.ones(1, dtype=torch.float32, device=device),
|
||||
torch.zeros((1, 1), dtype=torch.bfloat16, device=device),
|
||||
torch.zeros((1, 1), dtype=torch.int64, device=device),
|
||||
torch.full(
|
||||
(1, vocab_size), float("-inf"), dtype=torch.bfloat16, device=device
|
||||
),
|
||||
1.0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("batch_size", [1, 2, 4, 8])
|
||||
def test_nvfp4_gathered_markov_bias_kernel_matches_reference(batch_size: int):
|
||||
torch.manual_seed(0)
|
||||
device = torch.device("cuda")
|
||||
topk = 256
|
||||
rank = 512
|
||||
vocab_size = 512
|
||||
alpha = 0.75
|
||||
|
||||
packed_weight = torch.randint(
|
||||
0, 256, (vocab_size, rank // 2), dtype=torch.uint8, device=device
|
||||
)
|
||||
weight_scale = torch.full(
|
||||
(vocab_size, rank // 16),
|
||||
0.5,
|
||||
dtype=torch.float8_e4m3fn,
|
||||
device=device,
|
||||
)
|
||||
global_scale = torch.tensor([0.25], dtype=torch.float32, device=device)
|
||||
|
||||
markov_storage = torch.randn(
|
||||
batch_size, 2, rank, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
values_storage = torch.randn(
|
||||
batch_size, 2, topk, dtype=torch.bfloat16, device=device
|
||||
)
|
||||
index_storage = torch.empty(batch_size, 2, topk, dtype=torch.int64, device=device)
|
||||
for batch_idx in range(batch_size):
|
||||
index_storage[batch_idx, 0] = (
|
||||
torch.arange(topk, device=device) + batch_idx
|
||||
) % vocab_size
|
||||
logits_storage = torch.full(
|
||||
(batch_size, 2, vocab_size),
|
||||
float("-inf"),
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
)
|
||||
|
||||
markov_embed = markov_storage[:, 0]
|
||||
values = values_storage[:, 0]
|
||||
index = index_storage[:, 0]
|
||||
logits = logits_storage[:, 0]
|
||||
|
||||
layer = nn.Module()
|
||||
layer.register_buffer("_nvfp4_weight_for_gather", packed_weight)
|
||||
layer.register_buffer("_nvfp4_weight_scale_for_gather", weight_scale)
|
||||
layer.register_buffer("_nvfp4_weight_global_scale_for_gather", global_scale)
|
||||
layer._nvfp4_group_size_for_gather = 16
|
||||
layer._retain_weight_for_gather = True
|
||||
layer.is_w4a16_nvfp4 = True
|
||||
head = DSparkMarkovHead.__new__(DSparkMarkovHead)
|
||||
nn.Module.__init__(head)
|
||||
head.markov_w2 = layer
|
||||
|
||||
flat_index = index.reshape(-1)
|
||||
selected_weight = dequantize_to_dtype(
|
||||
packed_weight.index_select(0, flat_index),
|
||||
weight_scale.index_select(0, flat_index),
|
||||
global_scale,
|
||||
dtype=torch.bfloat16,
|
||||
block_size=16,
|
||||
swizzle=False,
|
||||
).view(batch_size, topk, rank)
|
||||
expected = (
|
||||
values
|
||||
+ torch.bmm(selected_weight, markov_embed.unsqueeze(-1)).squeeze(-1) * alpha
|
||||
)
|
||||
|
||||
result = head.apply_bias_gathered(markov_embed, logits, values, index, alpha)
|
||||
|
||||
torch.testing.assert_close(
|
||||
result.gather(1, index), expected, rtol=1e-2, atol=6.25e-2
|
||||
)
|
||||
selected = torch.zeros_like(result, dtype=torch.bool).scatter_(1, index, True)
|
||||
assert torch.isneginf(result.masked_select(~selected)).all()
|
||||
|
||||
if batch_size == 1:
|
||||
logits.fill_(float("-inf"))
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
captured = head.apply_bias_gathered(
|
||||
markov_embed, logits, values, index, alpha
|
||||
)
|
||||
logits.fill_(float("-inf"))
|
||||
graph.replay()
|
||||
assert captured is logits
|
||||
torch.testing.assert_close(
|
||||
logits.gather(1, index), expected, rtol=1e-2, atol=6.25e-2
|
||||
)
|
||||
@@ -1,164 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""``get_top_tokens`` on the DeepSeek V4 MTP drafter.
|
||||
|
||||
The speculator opts into ``use_local_argmax_reduction`` by probing the draft
|
||||
model for ``get_top_tokens``, and expects it to select the same greedy draft
|
||||
token the full-vocab argmax would. V4 reaches its LM head through hc_head and
|
||||
the shared head's RMSNorm, so both methods have to share that transform.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.mhc import HCHeadOp
|
||||
from vllm.model_executor.models.deepseek_mtp import SharedHead
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip(
|
||||
"get_top_tokens is implemented on the ROCm DeepSeek V4 MTP drafter only.",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from vllm.models.deepseek_v4.amd.mtp import ( # noqa: E402
|
||||
DeepSeekV4MTP,
|
||||
DeepSeekV4MultiTokenPredictor,
|
||||
)
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
START_LAYER_IDX = 61
|
||||
HIDDEN_SIZE = 4096
|
||||
HC_MULT = 4
|
||||
RMS_NORM_EPS = 1e-6
|
||||
HC_EPS = 1e-6
|
||||
_EMBEDDING = "vllm.model_executor.layers.vocab_parallel_embedding"
|
||||
|
||||
|
||||
def _make_predictor(vocab_size: int) -> DeepSeekV4MultiTokenPredictor:
|
||||
config = PreTrainedConfig()
|
||||
config.hidden_size = HIDDEN_SIZE
|
||||
config.vocab_size = vocab_size
|
||||
config.rms_norm_eps = RMS_NORM_EPS
|
||||
|
||||
# A single vocab shard, so the reduction returns the local argmax without
|
||||
# touching the process group.
|
||||
with (
|
||||
mock.patch(f"{_EMBEDDING}.get_tensor_model_parallel_rank", return_value=0),
|
||||
mock.patch(
|
||||
f"{_EMBEDDING}.get_tensor_model_parallel_world_size", return_value=1
|
||||
),
|
||||
):
|
||||
shared_head = SharedHead(config=config, prefix="shared_head")
|
||||
|
||||
assert shared_head.head is not None
|
||||
generator = torch.Generator().manual_seed(7)
|
||||
with torch.no_grad():
|
||||
shared_head.head.weight.normal_(0.0, 0.02, generator=generator)
|
||||
# The default norm weight is all ones, and the argmax is invariant to
|
||||
# the norm's per-row rescale, so a uniform gain would hide a skipped
|
||||
# shared_head. Vary it so the comparison below can see one.
|
||||
shared_head.norm.weight.normal_(1.0, 0.5, generator=generator)
|
||||
shared_head = shared_head.to(device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
|
||||
hc_head_fn = torch.randn(
|
||||
HC_MULT, HC_MULT * HIDDEN_SIZE, dtype=torch.float32, generator=generator
|
||||
)
|
||||
# Non-trivial gate scale and bias: hc_head mixes the hc_mult streams with
|
||||
# these, and defaults of 0 would make a skipped hc_head harder to see.
|
||||
hc_head_scale = torch.randn(1, dtype=torch.float32, generator=generator) * 0.1
|
||||
hc_head_base = torch.randn(HC_MULT, dtype=torch.float32, generator=generator) * 0.1
|
||||
|
||||
mtp_layer = SimpleNamespace(
|
||||
config=config,
|
||||
hc_mult=HC_MULT,
|
||||
hc_eps=HC_EPS,
|
||||
rms_norm_eps=RMS_NORM_EPS,
|
||||
hc_head_op=HCHeadOp(),
|
||||
hc_head_fn=(hc_head_fn * 1e-4).to(DEVICE_TYPE),
|
||||
hc_head_scale=hc_head_scale.to(DEVICE_TYPE),
|
||||
hc_head_base=hc_head_base.to(DEVICE_TYPE),
|
||||
shared_head=shared_head,
|
||||
)
|
||||
|
||||
# Only the attributes the two methods read; a real predictor would also
|
||||
# build the MLA/MoE draft block, which is irrelevant here.
|
||||
predictor = object.__new__(DeepSeekV4MultiTokenPredictor)
|
||||
torch.nn.Module.__init__(predictor)
|
||||
predictor.layers = {str(START_LAYER_IDX): mtp_layer}
|
||||
predictor.mtp_start_layer_idx = START_LAYER_IDX
|
||||
predictor.num_mtp_layers = 1
|
||||
predictor.logits_processor = LogitsProcessor(vocab_size)
|
||||
return predictor
|
||||
|
||||
|
||||
def _hidden_states(num_tokens: int, seed: int) -> torch.Tensor:
|
||||
"""The flat pre-hc_head residual the MTP layer returns."""
|
||||
generator = torch.Generator().manual_seed(seed)
|
||||
hidden_states = torch.randn(
|
||||
num_tokens, HC_MULT * HIDDEN_SIZE, dtype=torch.float32, generator=generator
|
||||
)
|
||||
return hidden_states.to(device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
|
||||
|
||||
def _assert_selects_max_logit(top: torch.Tensor, logits: torch.Tensor) -> None:
|
||||
"""The selected token must carry the row's maximum logit.
|
||||
|
||||
hc_head emits bf16, so rows can tie for the maximum and then no single
|
||||
index is the right answer; compare the values the two paths select.
|
||||
"""
|
||||
assert top.shape == (logits.shape[0],)
|
||||
selected = logits.gather(1, top.unsqueeze(1)).squeeze(1)
|
||||
assert torch.equal(selected, logits.max(dim=-1).values)
|
||||
|
||||
|
||||
def test_get_top_tokens_matches_full_argmax(default_vllm_config):
|
||||
"""Same draft token as the path taken when the reduction is off.
|
||||
|
||||
``get_top_tokens`` has to run the same pre-head transform as
|
||||
``compute_logits``: hc_head over the (T, hc_mult, D) residual, then the
|
||||
shared head's RMSNorm. Dropping either one returns a different draft token
|
||||
instead of failing, which is what this comparison catches.
|
||||
"""
|
||||
predictor = _make_predictor(vocab_size=512)
|
||||
|
||||
for num_tokens in (1, 16, 128):
|
||||
hidden_states = _hidden_states(num_tokens, seed=11)
|
||||
|
||||
logits = predictor.compute_logits(hidden_states)
|
||||
top = predictor.get_top_tokens(hidden_states)
|
||||
|
||||
assert top.dtype == torch.int64
|
||||
_assert_selects_max_logit(top, logits)
|
||||
|
||||
|
||||
def test_get_top_tokens_honors_padded_vocab(default_vllm_config):
|
||||
"""Padding entries above ``org_vocab_size`` must never win the argmax."""
|
||||
vocab_size = 500
|
||||
predictor = _make_predictor(vocab_size)
|
||||
head = predictor.layers[str(START_LAYER_IDX)].shared_head.head
|
||||
assert head.shard_indices.num_org_vocab_padding > 0
|
||||
|
||||
hidden_states = _hidden_states(32, seed=13)
|
||||
logits = predictor.compute_logits(hidden_states)
|
||||
top = predictor.get_top_tokens(hidden_states)
|
||||
|
||||
_assert_selects_max_logit(top, logits)
|
||||
assert (top < vocab_size).all()
|
||||
|
||||
|
||||
def test_wrapper_forwards_spec_step_idx():
|
||||
"""``DeepSeekV4MTP`` is what the speculator probes, so it needs the method."""
|
||||
assert hasattr(DeepSeekV4MTP, "get_top_tokens")
|
||||
|
||||
hidden_states = torch.empty(0)
|
||||
wrapper = object.__new__(DeepSeekV4MTP)
|
||||
wrapper.model = SimpleNamespace(get_top_tokens=lambda *args: args)
|
||||
|
||||
assert DeepSeekV4MTP.get_top_tokens(wrapper, hidden_states, 2) == (hidden_states, 2)
|
||||
assert DeepSeekV4MTP.get_top_tokens(wrapper, hidden_states) == (hidden_states, 0)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,881 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
from vllm.config import (
|
||||
CompilationConfig,
|
||||
CompilationMode,
|
||||
DeviceConfig,
|
||||
LoadConfig,
|
||||
VllmConfig,
|
||||
set_current_vllm_config,
|
||||
)
|
||||
from vllm.distributed import parallel_state
|
||||
from vllm.model_executor.layers import logits_processor
|
||||
from vllm.model_executor.layers.linear import LinearBase
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorrHead
|
||||
from vllm.transformers_utils.configs.eagle import EAGLEConfig
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash2.speculator import CandidateSampler
|
||||
from vllm.v1.worker.gpu.spec_decode.lilicorr.speculator import LiLiCorrSpeculator
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def head_tp_metadata(monkeypatch):
|
||||
# Single-rank unit tests only need TP metadata.
|
||||
monkeypatch.setattr(
|
||||
parallel_state, "_TP", SimpleNamespace(rank_in_group=0, world_size=1)
|
||||
)
|
||||
|
||||
|
||||
def _config(**overrides):
|
||||
config = dict(
|
||||
candidate_topk=4,
|
||||
hidden_size=8,
|
||||
num_layers=2,
|
||||
num_heads=2,
|
||||
mlp_ratio=2.0,
|
||||
factor_dim=4,
|
||||
vector_eps=1e-6,
|
||||
logit_scale=3.0,
|
||||
)
|
||||
config.update(overrides)
|
||||
return {f"lilicorr_{key}": value for key, value in config.items()}
|
||||
|
||||
|
||||
def _reference_scores(head, embeddings, log_probs, hidden, anchor, valid):
|
||||
"""Unfused exported head: MHA attention, concatenated factors, separate edges."""
|
||||
batch, slots, top_k = log_probs.shape
|
||||
rank = torch.arange(top_k, device=log_probs.device) / max(top_k - 1, 1)
|
||||
top1 = (torch.arange(top_k, device=log_probs.device) == 0).float()
|
||||
features = torch.stack(
|
||||
(
|
||||
log_probs,
|
||||
log_probs.exp(),
|
||||
log_probs - log_probs.amax(-1, keepdim=True),
|
||||
rank.expand_as(log_probs),
|
||||
top1.expand_as(log_probs),
|
||||
),
|
||||
-1,
|
||||
)
|
||||
x = head.token_proj(embeddings) + head.pass_hidden_proj(hidden).unsqueeze(-2)
|
||||
features = head.feature_norm(features.to(x.dtype))
|
||||
x = x + head.feature_mlp.down_proj(F.silu(head.feature_mlp.up_proj(features)[0]))[0]
|
||||
x = x + head.slot_embedding[:, 0, :slots] + head.rank_embedding[:, 0]
|
||||
x = x.flatten(1, 2)
|
||||
positions = torch.arange(slots, device=x.device).repeat_interleave(top_k)
|
||||
relative = positions[:, None] - positions[None, :]
|
||||
bias = head.relative_slot_bias[:, relative + head.block_size - 1]
|
||||
bias = bias + (relative == 0) * head.same_slot_bias[:, None, None]
|
||||
bias = bias.repeat(batch, 1, 1)
|
||||
for layer in head.layers:
|
||||
attention = nn.MultiheadAttention(
|
||||
head.hidden_size,
|
||||
head.num_heads,
|
||||
batch_first=True,
|
||||
dtype=x.dtype,
|
||||
device=x.device,
|
||||
)
|
||||
attention.load_state_dict(layer.attn.state_dict())
|
||||
normalized = layer.attn_norm(x)
|
||||
x = (
|
||||
x
|
||||
+ attention(
|
||||
normalized, normalized, normalized, attn_mask=bias, need_weights=False
|
||||
)[0]
|
||||
)
|
||||
x = x + layer.mlp.down_proj(F.silu(layer.mlp.up_proj(layer.mlp_norm(x))[0]))[0]
|
||||
x = head.output_norm(x).view(batch, slots, top_k, -1)
|
||||
a = head.anchor_norm(head.context_proj(anchor) * valid[:, None])
|
||||
expanded = a[:, None, None].expand_as(x)
|
||||
factors = F.silu(head.factor_input_proj(torch.cat((x, expanded, x * expanded), -1)))
|
||||
incoming = F.normalize(head.in_head(factors), dim=-1, eps=head.vector_eps)
|
||||
outgoing = F.normalize(head.out_head(factors), dim=-1, eps=head.vector_eps)
|
||||
a = F.normalize(head.anchor_out_head(a), dim=-1, eps=head.vector_eps)
|
||||
start = (a[:, None] * incoming[:, 0]).sum(-1)
|
||||
pairs = outgoing[:, :-1] @ incoming[:, 1:].transpose(-1, -2)
|
||||
return (
|
||||
head.logit_scale
|
||||
* torch.cat((start[:, None, None].expand(-1, 1, top_k, -1), pairs), 1).float()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA or ROCm")
|
||||
@pytest.mark.parametrize(
|
||||
"head_width,slots,dtype",
|
||||
[
|
||||
pytest.param(8, 3, torch.float32, id="projected-multi-slot"),
|
||||
pytest.param(16, 1, torch.float32, id="identity-shortened-single-slot"),
|
||||
pytest.param(8, 2, torch.bfloat16, id="bf16-shortened-multi-slot"),
|
||||
],
|
||||
)
|
||||
def test_lilicorr_matches_exported_head(head_width, slots, dtype):
|
||||
device = torch.device("cuda")
|
||||
torch.manual_seed(7)
|
||||
with (
|
||||
torch.device(device),
|
||||
set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cuda"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
),
|
||||
):
|
||||
head = LiLiCorrHead(
|
||||
model_hidden_size=16,
|
||||
block_size=4,
|
||||
rms_norm_eps=1e-6,
|
||||
config=_config(hidden_size=head_width),
|
||||
).to(dtype)
|
||||
# vLLM linear parameters are initialized by the checkpoint loader.
|
||||
with torch.no_grad(), torch.device(device):
|
||||
for module in head.modules():
|
||||
if isinstance(module, LinearBase):
|
||||
for parameter in module.parameters():
|
||||
parameter.weight_loader(
|
||||
parameter, torch.randn_like(parameter) * 0.1
|
||||
)
|
||||
for layer in head.layers:
|
||||
layer.attn.in_proj_weight.normal_(std=0.1)
|
||||
layer.attn.in_proj_bias.normal_(std=0.1)
|
||||
head.relative_slot_bias.normal_(std=0.1)
|
||||
head.same_slot_bias.normal_(std=0.1)
|
||||
head.slot_embedding.normal_(std=0.1)
|
||||
head.rank_embedding.normal_(std=0.1)
|
||||
head.materialize_inference_buffers(device, dtype)
|
||||
inputs = (
|
||||
torch.randn(2, slots, 4, 16, dtype=dtype),
|
||||
torch.randn(2, slots, 23).log_softmax(-1).topk(4).values,
|
||||
torch.randn(2, slots, 16, dtype=dtype),
|
||||
torch.randn(2, 16, dtype=dtype),
|
||||
torch.tensor([True, False]),
|
||||
)
|
||||
actual = head(*inputs)
|
||||
expected = _reference_scores(head, *inputs)
|
||||
tolerance = 0.04 if dtype == torch.bfloat16 else 2e-6
|
||||
torch.testing.assert_close(actual, expected, atol=tolerance, rtol=tolerance)
|
||||
|
||||
|
||||
def test_runtime_length_keeps_trained_checkpoint_geometry(monkeypatch):
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorr
|
||||
from vllm.model_executor.models.qwen3_dflash import DFlashQwen3Model
|
||||
|
||||
def init_backbone(self, **kwargs):
|
||||
nn.Module.__init__(self)
|
||||
self.quant_config = None
|
||||
|
||||
monkeypatch.setattr(DFlashQwen3Model, "__init__", init_backbone)
|
||||
spec = SimpleNamespace(
|
||||
num_speculative_tokens=1,
|
||||
draft_model_config=SimpleNamespace(
|
||||
hf_config=SimpleNamespace(
|
||||
hidden_size=16,
|
||||
rms_norm_eps=1e-6,
|
||||
dflash_config=_config() | {"block_size": 4},
|
||||
)
|
||||
),
|
||||
)
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
for slots in (1, 3):
|
||||
spec.num_speculative_tokens = slots
|
||||
head = LiLiCorr(
|
||||
vllm_config=SimpleNamespace(speculative_config=spec)
|
||||
).lilicorr
|
||||
assert head.slot_embedding.shape == (1, 1, 3, 1, 8)
|
||||
assert head.relative_slot_bias.shape == (2, 7)
|
||||
spec.draft_model_config.hf_config.dflash_config["lilicorr_enabled"] = False
|
||||
with pytest.raises(ValueError, match="lilicorr_enabled"):
|
||||
LiLiCorr(vllm_config=SimpleNamespace(speculative_config=spec))
|
||||
spec.draft_model_config.hf_config.dflash_config["lilicorr_enabled"] = True
|
||||
spec.num_speculative_tokens = 4
|
||||
with pytest.raises(ValueError, match="trained block_size"):
|
||||
LiLiCorr(vllm_config=SimpleNamespace(speculative_config=spec))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tp_size", [1, 2])
|
||||
def test_candidates_use_global_partition_and_exclude_padding(monkeypatch, tp_size):
|
||||
"""Candidate features must include mass outside top-k and on other TP ranks."""
|
||||
|
||||
class Gather:
|
||||
def __init__(self, calls):
|
||||
self.calls = calls
|
||||
self.index = 0
|
||||
|
||||
def __call__(self, value, dim=-1):
|
||||
expected_input, result = self.calls[self.index]
|
||||
assert dim == -1
|
||||
torch.testing.assert_close(value, expected_input)
|
||||
self.index += 1
|
||||
return result
|
||||
|
||||
shards = [
|
||||
torch.tensor([[1.0, 3.0, 2.0, 100.0], [4.0, 1.0, 2.0, 100.0]]),
|
||||
torch.tensor([[6.0, 5.0, 0.0, 100.0], [3.0, 6.0, 5.0, 100.0]]),
|
||||
][:tp_size]
|
||||
for rank in range(tp_size):
|
||||
fake = SimpleNamespace(
|
||||
scale=1.0,
|
||||
soft_cap=None,
|
||||
_apply_head=lambda *args, rank=rank: shards[rank].clone(),
|
||||
)
|
||||
lm_head = SimpleNamespace(
|
||||
tp_size=tp_size,
|
||||
shard_indices=SimpleNamespace(
|
||||
num_org_vocab_padding=1, org_vocab_start_index=rank * 3
|
||||
),
|
||||
)
|
||||
valid_shards = [shard[:, :3] for shard in shards]
|
||||
local_topk = [shard.topk(2) for shard in valid_shards]
|
||||
gather_calls = [
|
||||
(
|
||||
valid_shards[rank].logsumexp(-1, keepdim=True),
|
||||
torch.cat(
|
||||
[shard.logsumexp(-1, keepdim=True) for shard in valid_shards],
|
||||
-1,
|
||||
),
|
||||
),
|
||||
(
|
||||
local_topk[rank].values,
|
||||
torch.cat([topk.values for topk in local_topk], -1),
|
||||
),
|
||||
(
|
||||
local_topk[rank].indices + rank * 3,
|
||||
torch.cat(
|
||||
[
|
||||
topk.indices + shard_rank * 3
|
||||
for shard_rank, topk in enumerate(local_topk)
|
||||
],
|
||||
-1,
|
||||
),
|
||||
),
|
||||
]
|
||||
all_gather = Gather(gather_calls)
|
||||
|
||||
monkeypatch.setattr(
|
||||
logits_processor,
|
||||
"tensor_model_parallel_all_gather",
|
||||
all_gather,
|
||||
)
|
||||
monkeypatch.setattr(logits_processor, "_topk", lambda x, k: x.topk(k, dim=-1))
|
||||
ids, values = logits_processor.LogitsProcessor.get_top_k_tokens(
|
||||
fake,
|
||||
lm_head,
|
||||
torch.empty(2, 1),
|
||||
2,
|
||||
return_log_probs=True,
|
||||
)
|
||||
expected = torch.cat(valid_shards, -1).log_softmax(-1).topk(2)
|
||||
torch.testing.assert_close(ids, expected.indices)
|
||||
torch.testing.assert_close(values, expected.values)
|
||||
assert all_gather.index == (3 if tp_size > 1 else 0)
|
||||
|
||||
|
||||
def test_context_anchor_is_last_committed_normalized_feature():
|
||||
hidden = torch.arange(1, 25, dtype=torch.float32).view(6, 4)
|
||||
norm = nn.RMSNorm(4)
|
||||
spec = SimpleNamespace(
|
||||
hidden_states=hidden,
|
||||
model=SimpleNamespace(model=SimpleNamespace(hidden_norm=norm)),
|
||||
anchor_hidden=torch.full((4, 4), 123.0),
|
||||
anchor_valid=torch.ones(4, dtype=torch.bool),
|
||||
)
|
||||
LiLiCorrSpeculator.prepare_context_anchor(
|
||||
spec, 2, torch.tensor([0, 2, 6]), torch.tensor([0, 2])
|
||||
)
|
||||
torch.testing.assert_close(spec.anchor_hidden[:2], norm(hidden[[1, 3]]))
|
||||
assert spec.anchor_valid.tolist() == [True, True, False, False]
|
||||
assert not spec.anchor_hidden[2:].any()
|
||||
# A smaller reordered batch must not retain an old request's anchor.
|
||||
LiLiCorrSpeculator.prepare_context_anchor(
|
||||
spec, 1, torch.tensor([0, 3]), torch.tensor([1])
|
||||
)
|
||||
torch.testing.assert_close(spec.anchor_hidden[0], norm(hidden[1]))
|
||||
assert not spec.anchor_hidden[1:].any()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_captured_context_anchor_rereads_fixed_inputs():
|
||||
"""The anchor runs in the draft's FULL graph: each replay must re-read its
|
||||
fixed-address inputs and ignore a padded request's stale rejected count."""
|
||||
dev = torch.device("cuda")
|
||||
query_start_loc = torch.zeros(3, dtype=torch.int32, device=dev)
|
||||
num_rejected = torch.zeros(2, dtype=torch.int32, device=dev)
|
||||
spec = SimpleNamespace(
|
||||
hidden_states=torch.randn(8, 2, device=dev),
|
||||
model=SimpleNamespace(model=SimpleNamespace(hidden_norm=lambda x: 2 * x)),
|
||||
anchor_hidden=torch.zeros(2, 2, device=dev),
|
||||
anchor_valid=torch.zeros(2, dtype=torch.bool, device=dev),
|
||||
)
|
||||
args = (spec, 2, query_start_loc, num_rejected)
|
||||
LiLiCorrSpeculator.prepare_context_anchor(*args)
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
LiLiCorrSpeculator.prepare_context_anchor(*args)
|
||||
# One live request padded to two; the second case anchors on a prefill row
|
||||
# past the graph's context rows, stored eagerly before replay.
|
||||
for loc, rejected, row in (([0, 2, 2], [1, 5], 0), ([0, 7, 7], [0, 0], 6)):
|
||||
query_start_loc.copy_(torch.tensor(loc))
|
||||
num_rejected.copy_(torch.tensor(rejected))
|
||||
graph.replay()
|
||||
torch.testing.assert_close(spec.anchor_hidden[0], 2 * spec.hidden_states[row])
|
||||
assert spec.anchor_valid.tolist() == [True, False]
|
||||
assert not spec.anchor_hidden[1].any()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lilicorr", [False, True])
|
||||
def test_candidate_generation_routes_scores_and_adaptive_inputs(monkeypatch, lilicorr):
|
||||
"""Both heads share the walk, including a padded request and adaptive scores."""
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import DFlashSpeculator
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash2.speculator import DFlash2Speculator
|
||||
|
||||
key = "lilicorr_candidate_topk" if lilicorr else "selector_top_k"
|
||||
|
||||
def init_base(self, config, device):
|
||||
self.draft_model_config = SimpleNamespace(
|
||||
hf_config=SimpleNamespace(hidden_size=4, dflash_config={key: 4})
|
||||
)
|
||||
self.max_num_reqs = 3
|
||||
self.num_speculative_steps = 2
|
||||
self.num_query_per_req = 3
|
||||
self.dtype = torch.float32
|
||||
|
||||
monkeypatch.setattr(DFlashSpeculator, "__init__", init_base)
|
||||
cls = LiLiCorrSpeculator if lilicorr else DFlash2Speculator
|
||||
spec = cls(None, torch.device("cpu"))
|
||||
hidden = torch.arange(36).float().view(9, 4)
|
||||
spec._run_model = lambda *args: hidden
|
||||
spec.sample_indices = torch.tensor([1, 2, 4, 5, 7, 8])
|
||||
spec.sample_pos = torch.arange(6)
|
||||
spec.sample_idx_mapping = torch.tensor([1, 1, 0, 0, -1, -1])
|
||||
spec.sample_col = torch.tensor([0, 1, 0, 1, 0, 1])
|
||||
spec.temperature = torch.ones(3)
|
||||
spec.seeds = torch.arange(3)
|
||||
spec.draft_tokens = torch.empty(3, 2, dtype=torch.long)
|
||||
spec.draft_logits = None
|
||||
spec.use_fp64_gumbel = False
|
||||
spec.enable_adaptive_verification = True
|
||||
spec.input_buffers = SimpleNamespace(input_ids=torch.arange(9))
|
||||
candidates = torch.arange(24).view(6, 4)
|
||||
log_probs = candidates.float().log_softmax(-1)
|
||||
scores = torch.randn(3, 2, 4, 4)
|
||||
scoring_inputs: list[torch.Tensor] = []
|
||||
sampling_inputs: list[Any] = []
|
||||
adaptive_inputs: list[torch.Tensor] = []
|
||||
|
||||
def score(*args):
|
||||
scoring_inputs.extend(args)
|
||||
return scores
|
||||
|
||||
def sample(*args):
|
||||
sampling_inputs.extend(args)
|
||||
spec.candidate_sampler.scores.copy_(scores[:, :, 0])
|
||||
|
||||
spec.model = SimpleNamespace(
|
||||
compute_candidates=lambda h: (candidates, log_probs),
|
||||
model=SimpleNamespace(lilicorr=score, candidate_selector=score),
|
||||
)
|
||||
if lilicorr:
|
||||
assert isinstance(spec, LiLiCorrSpeculator)
|
||||
monkeypatch.setattr(
|
||||
spec,
|
||||
"target_embeddings",
|
||||
lambda ids: ids.float().unsqueeze(-1).expand(*ids.shape, 4),
|
||||
raising=False,
|
||||
)
|
||||
spec.anchor_hidden.copy_(torch.arange(12).view(3, 4))
|
||||
spec.anchor_valid[:2] = True
|
||||
monkeypatch.setattr(spec.candidate_sampler, "sample", sample)
|
||||
monkeypatch.setattr(
|
||||
spec, "_maybe_predict_acceptance", lambda *args: adaptive_inputs.extend(args)
|
||||
)
|
||||
spec._generate_draft(3, 9, None, None, None)
|
||||
|
||||
expected_ids = candidates.view(3, 2, 4)
|
||||
expected_first = (
|
||||
spec.target_embeddings(expected_ids)
|
||||
if isinstance(spec, LiLiCorrSpeculator)
|
||||
else expected_ids
|
||||
)
|
||||
torch.testing.assert_close(scoring_inputs[0], expected_first)
|
||||
torch.testing.assert_close(scoring_inputs[1], log_probs.view(3, 2, 4))
|
||||
torch.testing.assert_close(
|
||||
scoring_inputs[2], hidden[spec.sample_indices].view(3, 2, 4)
|
||||
)
|
||||
if lilicorr:
|
||||
assert isinstance(spec, LiLiCorrSpeculator)
|
||||
torch.testing.assert_close(scoring_inputs[3], spec.anchor_hidden)
|
||||
torch.testing.assert_close(scoring_inputs[4], spec.anchor_valid)
|
||||
else:
|
||||
torch.testing.assert_close(scoring_inputs[3], torch.tensor([0, 3, 6]))
|
||||
torch.testing.assert_close(sampling_inputs[0], expected_ids)
|
||||
assert sampling_inputs[1] is scores
|
||||
assert sampling_inputs[4] is spec.sample_idx_mapping
|
||||
torch.testing.assert_close(adaptive_inputs[0], scores[:, :, 0].flatten(0, 1))
|
||||
torch.testing.assert_close(adaptive_inputs[1], spec.sample_idx_mapping)
|
||||
torch.testing.assert_close(adaptive_inputs[2], spec.sample_col)
|
||||
|
||||
|
||||
def test_lilicorr_config_preserves_architecture():
|
||||
from transformers import Qwen3Config
|
||||
|
||||
config = Qwen3Config(architectures=["LiLiCorrDraftModel"])
|
||||
wrapped = EAGLEConfig(config, method="dflash")
|
||||
assert wrapped.architectures == ["LiLiCorrDraftModel"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("probabilistic", [False, True])
|
||||
def test_candidate_walk_preserves_conditional_scores_and_padding(probabilistic):
|
||||
"""Check the shared sampler's actual q, stale support, and graph padding."""
|
||||
device = torch.device("cuda")
|
||||
batch, steps, top_k, vocab = 3, 3, 4, 32
|
||||
sampler = CandidateSampler(batch, steps, top_k, device)
|
||||
candidates = (
|
||||
torch.arange(steps * top_k, device=device)
|
||||
.view(1, steps, top_k)
|
||||
.repeat(batch, 1, 1)
|
||||
)
|
||||
scores = torch.randn(batch, steps, top_k, top_k, device=device)
|
||||
tokens = torch.full((batch, steps), -1, dtype=torch.long, device=device)
|
||||
cache = (
|
||||
torch.full((batch, steps, vocab), -float("inf"), device=device)
|
||||
if probabilistic
|
||||
else None
|
||||
)
|
||||
positions = torch.arange(batch * steps * 2, device=device)[::2]
|
||||
mappings = torch.tensor(
|
||||
[2] * steps + [0] * steps + [-1] * steps, device=device
|
||||
).repeat_interleave(2)[::2]
|
||||
temperature = torch.tensor([0.0, 1.0, 0.8], device=device)
|
||||
seeds = torch.tensor([11, 22, 33], device=device)
|
||||
|
||||
def run():
|
||||
sampler.sample(
|
||||
candidates,
|
||||
scores,
|
||||
batch,
|
||||
positions,
|
||||
mappings,
|
||||
temperature,
|
||||
seeds,
|
||||
tokens,
|
||||
cache,
|
||||
False,
|
||||
)
|
||||
|
||||
run()
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
run()
|
||||
old_candidates = candidates.clone()
|
||||
candidates.add_(12)
|
||||
graph.replay()
|
||||
for row, state in ((0, 2), (1, 0)):
|
||||
previous = 0
|
||||
for step in range(steps):
|
||||
realized = scores[row, step, previous]
|
||||
torch.testing.assert_close(sampler.scores[row, step], realized)
|
||||
index = (candidates[row, step] == tokens[row, step]).nonzero().item()
|
||||
if not probabilistic or temperature[state] == 0:
|
||||
assert index == realized.argmax().item()
|
||||
if cache is not None:
|
||||
torch.testing.assert_close(
|
||||
cache[state, step, candidates[row, step]], realized
|
||||
)
|
||||
assert cache[state, step, old_candidates[row, step]].isneginf().all()
|
||||
previous = index
|
||||
assert (tokens[2] == -1).all()
|
||||
if cache is not None:
|
||||
assert cache[1].isneginf().all()
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
@pytest.mark.parametrize("use_fp64", [False, True])
|
||||
def test_candidate_walk_revisited_position_matches_step_seed(use_fp64):
|
||||
"""The candidate walk must use the same step key as ordinary draft sampling."""
|
||||
device = torch.device("cuda")
|
||||
batch, steps, top_k = 4096, 2, 2
|
||||
sampler = CandidateSampler(batch, steps, top_k, device)
|
||||
candidates = torch.arange(top_k, device=device).expand(batch, steps, top_k)
|
||||
logits = torch.tensor([0.7, 0.3], device=device).log()
|
||||
scores = logits.expand(batch, steps, top_k, top_k)
|
||||
mapping = torch.arange(batch, device=device)
|
||||
temperature = torch.ones(batch, device=device)
|
||||
seeds = mapping.to(torch.int64)
|
||||
positions = torch.arange(21, 21 + steps, device=device).repeat(batch)
|
||||
tokens = torch.empty(batch, steps, dtype=torch.int64, device=device)
|
||||
cache = torch.empty(batch, steps, top_k, device=device)
|
||||
first_round = None
|
||||
for start in (21, 22):
|
||||
positions.view(batch, steps).copy_(
|
||||
torch.arange(start, start + steps, device=device)
|
||||
)
|
||||
sampler.sample(
|
||||
candidates,
|
||||
scores,
|
||||
batch,
|
||||
positions,
|
||||
mapping.repeat_interleave(steps),
|
||||
temperature,
|
||||
seeds,
|
||||
tokens,
|
||||
cache,
|
||||
use_fp64,
|
||||
)
|
||||
for step in range(steps):
|
||||
expected = gumbel_sample(
|
||||
logits.expand(batch, -1),
|
||||
mapping,
|
||||
temperature,
|
||||
seeds,
|
||||
positions.view(batch, steps)[:, step] - 1,
|
||||
apply_temperature=True,
|
||||
is_drafting=True,
|
||||
logits_cache=cache,
|
||||
logits_cache_col=torch.tensor(step, device=device),
|
||||
use_fp64=use_fp64,
|
||||
)
|
||||
torch.testing.assert_close(tokens[:, step], expected)
|
||||
if first_round is None:
|
||||
first_round = tokens.clone()
|
||||
else:
|
||||
mismatch_rate = (first_round[:, 1] != tokens[:, 0]).float().mean().item()
|
||||
assert 0.35 < mismatch_rate < 0.5
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("convolution", "mismatch", "quantized"),
|
||||
[
|
||||
pytest.param(False, None, False, id="valid-plain"),
|
||||
pytest.param(True, None, False, id="valid-convolution"),
|
||||
pytest.param(False, "missing_head", False, id="missing-head"),
|
||||
pytest.param(False, "extra_head", False, id="extra-head"),
|
||||
pytest.param(True, "missing_conv", False, id="missing-convolution"),
|
||||
pytest.param(False, "extra_conv", False, id="unexpected-convolution"),
|
||||
pytest.param(False, None, True, id="optional-w4a16-input-scale"),
|
||||
pytest.param(False, "missing_weight", True, id="missing-quantized-weight"),
|
||||
pytest.param(False, "missing_bias", True, id="missing-quantized-bias"),
|
||||
pytest.param(False, "missing_weight_scale", True, id="missing-block-scale"),
|
||||
pytest.param(False, "missing_weight_scale_2", True, id="missing-global-scale"),
|
||||
],
|
||||
)
|
||||
def test_checkpoint_coverage_rejects_incomplete_or_wrong_heads(
|
||||
monkeypatch, convolution, mismatch, quantized
|
||||
):
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorr, LiLiCorrForCausalLM
|
||||
|
||||
wrapper = LiLiCorrForCausalLM.__new__(LiLiCorrForCausalLM) # type: ignore[type-abstract]
|
||||
nn.Module.__init__(wrapper)
|
||||
wrapper.model = LiLiCorr.__new__(LiLiCorr)
|
||||
nn.Module.__init__(wrapper.model)
|
||||
wrapper.has_own_lm_head = False
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
wrapper.model.lilicorr = LiLiCorrHead(
|
||||
model_hidden_size=16, block_size=4, rms_norm_eps=1e-6, config=_config()
|
||||
)
|
||||
layer = nn.Module()
|
||||
if convolution:
|
||||
layer.attention_conv = nn.Linear(2, 2, bias=False)
|
||||
wrapper.model.layers = nn.ModuleList([layer])
|
||||
if quantized:
|
||||
from vllm.config.quantization import QuantSpec
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
CkptCtx,
|
||||
ModelOptLinearMethod,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
kNvfp4Static,
|
||||
)
|
||||
|
||||
# Match the W4A16 NVFP4 checkpoint contract without GPU kernel setup.
|
||||
projection = wrapper.model.lilicorr.pass_hidden_proj
|
||||
projection.quant_method = ModelOptLinearMethod(
|
||||
QuantSpec(weight=kNvfp4Static, activation=None), CkptCtx(group_size=16)
|
||||
)
|
||||
projection.weight = nn.Parameter(
|
||||
torch.zeros(8, 8, dtype=torch.uint8), requires_grad=False
|
||||
)
|
||||
for name, value in (
|
||||
("weight_scale", torch.ones(8, 1).to(torch.float8_e4m3fn)),
|
||||
("weight_scale_2", torch.ones(1)),
|
||||
("input_scale", torch.full((1,), torch.nan)),
|
||||
):
|
||||
projection.register_parameter(
|
||||
name, nn.Parameter(value, requires_grad=False)
|
||||
)
|
||||
weights = dict(wrapper.model.state_dict())
|
||||
if quantized:
|
||||
del weights["lilicorr.pass_hidden_proj.input_scale"]
|
||||
if mismatch == "missing_head":
|
||||
del weights["lilicorr.slot_embedding"]
|
||||
elif mismatch in (
|
||||
"missing_weight",
|
||||
"missing_bias",
|
||||
"missing_weight_scale",
|
||||
"missing_weight_scale_2",
|
||||
):
|
||||
del weights[f"lilicorr.pass_hidden_proj.{mismatch.removeprefix('missing_')}"]
|
||||
elif mismatch == "extra_head":
|
||||
weights["lilicorr.untrained.weight"] = torch.zeros(1)
|
||||
elif mismatch == "missing_conv":
|
||||
del weights["layers.0.attention_conv.weight"]
|
||||
elif mismatch == "extra_conv":
|
||||
weights["layers.0.mlp_conv.untrained"] = torch.zeros(1)
|
||||
|
||||
# Keep production loading and mapping, bypass only backbone GPU KV setup.
|
||||
wrapper.model.use_aux_hidden_state = True
|
||||
wrapper.model.has_separate_mask_embedding = False
|
||||
monkeypatch.setattr(wrapper, "_read_mask_embedding", lambda: None)
|
||||
monkeypatch.setattr(
|
||||
wrapper.model, "_build_fused_kv_buffers", lambda: None, raising=False
|
||||
)
|
||||
supplied = [("model." + name, value) for name, value in weights.items()]
|
||||
if mismatch:
|
||||
message = (
|
||||
"no module or parameter"
|
||||
if mismatch.startswith("extra")
|
||||
else "coverage mismatch"
|
||||
)
|
||||
with pytest.raises(ValueError, match=message):
|
||||
wrapper.load_weights(supplied)
|
||||
else:
|
||||
wrapper.load_weights(supplied)
|
||||
assert wrapper.model.lilicorr._attn_bias is not None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owned_head_model(monkeypatch):
|
||||
from vllm.model_executor.layers.quantization import modelopt
|
||||
from vllm.model_executor.models import qwen3_dflash
|
||||
from vllm.model_executor.models.lilicorr import LiLiCorrForCausalLM
|
||||
|
||||
quant_config = modelopt.ModelOptNvFp4Config(
|
||||
quant_method="W4A16_NVFP4", is_checkpoint_nvfp4_serialized=True
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
modelopt,
|
||||
"select_linear_kernel",
|
||||
lambda *a, **kw: SimpleNamespace(input_quant_key=lambda: None),
|
||||
)
|
||||
monkeypatch.setattr(qwen3_dflash, "get_draft_quant_config", lambda _: quant_config)
|
||||
|
||||
class Backbone(nn.Module):
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__()
|
||||
self.quant_config = quant_config
|
||||
self.use_aux_hidden_state = True
|
||||
self.has_separate_mask_embedding = False
|
||||
self.lilicorr = LiLiCorrHead(
|
||||
model_hidden_size=16, block_size=4, rms_norm_eps=1e-6, config=_config()
|
||||
)
|
||||
|
||||
def _build_fused_kv_buffers(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(LiLiCorrForCausalLM, "model_cls", Backbone)
|
||||
monkeypatch.setattr(LiLiCorrForCausalLM, "_read_mask_embedding", lambda _: None)
|
||||
|
||||
def build(owned=True):
|
||||
config = SimpleNamespace(
|
||||
vocab_size=64,
|
||||
draft_vocab_size=64,
|
||||
hidden_size=16,
|
||||
has_own_lm_head=owned,
|
||||
num_hidden_layers=0,
|
||||
dflash_config={},
|
||||
)
|
||||
vllm_config = SimpleNamespace(
|
||||
speculative_config=SimpleNamespace(
|
||||
draft_model_config=SimpleNamespace(hf_config=config),
|
||||
draft_load_config=None,
|
||||
attention_backend=None,
|
||||
kv_cache_dtype=None,
|
||||
),
|
||||
model_config=SimpleNamespace(
|
||||
get_total_num_hidden_layers=lambda: 0,
|
||||
get_vocab_size=lambda: 64,
|
||||
),
|
||||
attention_config=SimpleNamespace(),
|
||||
cache_config=SimpleNamespace(),
|
||||
load_config=LoadConfig(),
|
||||
)
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
model = LiLiCorrForCausalLM(vllm_config=vllm_config)
|
||||
return model, vllm_config
|
||||
|
||||
return build
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", [None, "weight", "weight_scale", "weight_scale_2"])
|
||||
def test_owned_nvfp4_lm_head_loads_required_checkpoint_tensors(
|
||||
owned_head_model, missing
|
||||
):
|
||||
model, _ = owned_head_model()
|
||||
assert model.lm_head.weight.dtype == torch.uint8
|
||||
assert model.lm_head.weight.shape == (64, 8)
|
||||
weights = {
|
||||
name: torch.ones_like(value) for name, value in model.state_dict().items()
|
||||
}
|
||||
del weights["lm_head.input_scale"] # Deprecated and unused for W4A16.
|
||||
if missing:
|
||||
del weights[f"lm_head.{missing}"]
|
||||
with pytest.raises(ValueError, match=f"lm_head.{missing}"):
|
||||
model.load_weights(weights.items())
|
||||
else:
|
||||
model.load_weights(weights.items())
|
||||
assert model.has_own_lm_head
|
||||
for name in ("weight", "weight_scale", "weight_scale_2"):
|
||||
torch.testing.assert_close(
|
||||
getattr(model.lm_head, name), weights[f"lm_head.{name}"]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owned", [False, True])
|
||||
def test_selected_lm_head_survives_dflash_and_lilicorr_sharing(
|
||||
monkeypatch, owned_head_model, owned
|
||||
):
|
||||
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.v1.worker.gpu.spec_decode.dflash import utils as dflash_utils
|
||||
from vllm.v1.worker.gpu.spec_decode.eagle import utils as eagle_utils
|
||||
|
||||
model, config = owned_head_model(owned)
|
||||
own_head = model.lm_head
|
||||
target_head = owned_head_model(owned)[0].lm_head
|
||||
# Identical packed bytes do not imply identical quantized heads.
|
||||
with torch.no_grad():
|
||||
own_head.weight.fill_(1)
|
||||
target_head.weight.fill_(1)
|
||||
if owned:
|
||||
own_head.weight_scale_2.fill_(1)
|
||||
target_head.weight_scale_2.fill_(2)
|
||||
embedding = VocabParallelEmbedding(64, 16)
|
||||
target = SimpleNamespace(
|
||||
model=SimpleNamespace(embed_tokens=embedding), lm_head=target_head
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
eagle_utils, "get_pp_group", lambda: SimpleNamespace(world_size=1)
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dflash_utils, "replace", lambda obj, **kw: SimpleNamespace(**(vars(obj) | kw))
|
||||
)
|
||||
monkeypatch.setattr(dflash_utils, "get_pp_safe_draft_load_config", lambda c: c)
|
||||
monkeypatch.setattr(dflash_utils, "get_model", lambda **kw: model)
|
||||
if owned:
|
||||
|
||||
def no_weight_comparison(*args):
|
||||
raise AssertionError("Explicit ownership must bypass raw-weight comparison")
|
||||
|
||||
monkeypatch.setattr(dflash_utils, "_should_share", no_weight_comparison)
|
||||
spec = LiLiCorrSpeculator.__new__(LiLiCorrSpeculator)
|
||||
spec.vllm_config = config
|
||||
assert spec.load_draft_model(target, set()) is model
|
||||
assert model.lm_head is (own_head if owned else target_head)
|
||||
assert spec.target_embeddings is embedding
|
||||
if owned:
|
||||
target.lm_head = None
|
||||
assert spec.load_draft_model(target, set()).lm_head is own_head
|
||||
|
||||
|
||||
def test_quantized_head_calls_methods_without_reading_packed_weights(monkeypatch):
|
||||
from vllm.model_executor.layers import linear
|
||||
from vllm.model_executor.layers.linear import UnquantizedLinearMethod
|
||||
|
||||
calls = []
|
||||
configured = []
|
||||
quant_config = object()
|
||||
|
||||
class PackedMethod(UnquantizedLinearMethod):
|
||||
def apply(self, layer, x, bias=None):
|
||||
calls.append(layer.prefix)
|
||||
# Packed storage has a different name/dtype from the activations.
|
||||
assert x.dtype == torch.float32
|
||||
return F.linear(x, layer.packed_weight.float() * layer.weight_scale, bias)
|
||||
|
||||
def resolve(config, layer, prefix):
|
||||
assert config is quant_config
|
||||
configured.append(prefix)
|
||||
return PackedMethod()
|
||||
|
||||
monkeypatch.setattr(linear, "resolve_quant_method", resolve)
|
||||
with set_current_vllm_config(
|
||||
VllmConfig(
|
||||
device_config=DeviceConfig("cpu"),
|
||||
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
|
||||
)
|
||||
):
|
||||
head = LiLiCorrHead(
|
||||
model_hidden_size=16,
|
||||
block_size=4,
|
||||
rms_norm_eps=1e-6,
|
||||
config=_config(hidden_size=8),
|
||||
quant_config=quant_config,
|
||||
prefix="model.lilicorr",
|
||||
)
|
||||
with torch.no_grad():
|
||||
for module in head.modules():
|
||||
if isinstance(module, LinearBase):
|
||||
if module.quant_config is None:
|
||||
module.weight.normal_(std=0.1)
|
||||
module.bias.zero_()
|
||||
continue
|
||||
module.register_parameter(
|
||||
"packed_weight",
|
||||
nn.Parameter(
|
||||
torch.randint(-4, 5, module.weight.shape, dtype=torch.int8),
|
||||
requires_grad=False,
|
||||
),
|
||||
)
|
||||
module.register_parameter(
|
||||
"weight_scale",
|
||||
nn.Parameter(
|
||||
torch.tensor(0.05),
|
||||
requires_grad=False,
|
||||
),
|
||||
)
|
||||
del module.weight
|
||||
module.bias.zero_()
|
||||
for layer in head.layers:
|
||||
layer.attn.in_proj_weight.normal_(std=0.1)
|
||||
layer.attn.in_proj_bias.zero_()
|
||||
head.materialize_inference_buffers(torch.device("cpu"), torch.float32)
|
||||
result = head(
|
||||
torch.randn(2, 3, 4, 16),
|
||||
torch.randn(2, 3, 4).log_softmax(-1),
|
||||
torch.randn(2, 3, 16),
|
||||
torch.randn(2, 16),
|
||||
torch.tensor([True, False]),
|
||||
)
|
||||
assert result.shape == (2, 3, 4, 4)
|
||||
assert torch.isfinite(result).all()
|
||||
for name in ("factor_input_proj", "out_head", "in_head"):
|
||||
assert getattr(head, name).quant_config is None
|
||||
assert f"model.lilicorr.{name}" not in configured
|
||||
assert set(calls) == set(configured)
|
||||
assert len(configured) == len(set(configured))
|
||||
for name, module in head.named_modules():
|
||||
if isinstance(module, LinearBase):
|
||||
assert module.prefix == f"model.lilicorr.{name}"
|
||||
@@ -1,239 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from tests.v1.attention.utils import (
|
||||
BatchSpec,
|
||||
create_common_attn_metadata,
|
||||
create_standard_kv_cache_spec,
|
||||
try_get_attention_backend,
|
||||
)
|
||||
from vllm.config import (
|
||||
CacheConfig,
|
||||
DeviceConfig,
|
||||
ModelConfig,
|
||||
ParallelConfig,
|
||||
SchedulerConfig,
|
||||
SpeculativeConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.config.load import LoadConfig
|
||||
from vllm.model_executor.models.llama import LlamaForCausalLM
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
from vllm.v1.spec_decode.eagle import EagleProposer
|
||||
|
||||
mimo_7b_dir = "XiaomiMiMo/MiMo-7B-Base"
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
|
||||
def test_glm_mtp_defers_lm_head(default_vllm_config):
|
||||
from vllm.model_executor.models import deepseek_mtp
|
||||
from vllm.models.glm5next.common import mtp
|
||||
|
||||
config = mock.MagicMock(
|
||||
hidden_size=16,
|
||||
rms_norm_eps=1e-5,
|
||||
index_topk=8,
|
||||
index_kpool=4,
|
||||
)
|
||||
vllm_config = mock.MagicMock()
|
||||
vllm_config.speculative_config.draft_model_config.hf_text_config = config
|
||||
vllm_config.scheduler_config.max_num_batched_tokens = 4
|
||||
|
||||
with (
|
||||
mock.patch.object(mtp, "Glm5NextDecoderLayer", return_value=nn.Identity()),
|
||||
mock.patch.object(deepseek_mtp, "ParallelLMHead") as parallel_lm_head,
|
||||
mock.patch.object(mtp.current_platform, "device_type", "cpu"),
|
||||
):
|
||||
layer = mtp.Glm5NextMultiTokenPredictorLayer(vllm_config, "model.layers.1")
|
||||
|
||||
parallel_lm_head.assert_not_called()
|
||||
assert layer.shared_head.head is None
|
||||
|
||||
|
||||
def _create_mtp_proposer(num_speculative_tokens: int) -> EagleProposer:
|
||||
"""Create an MTP proposer with unified model configuration."""
|
||||
model_config = ModelConfig(
|
||||
model=mimo_7b_dir, runner="generate", max_model_len=100, trust_remote_code=True
|
||||
)
|
||||
|
||||
speculative_config = SpeculativeConfig(
|
||||
target_model_config=model_config,
|
||||
target_parallel_config=ParallelConfig(),
|
||||
model=mimo_7b_dir,
|
||||
method="mtp",
|
||||
num_speculative_tokens=num_speculative_tokens,
|
||||
)
|
||||
|
||||
vllm_config = VllmConfig(
|
||||
model_config=model_config,
|
||||
cache_config=CacheConfig(),
|
||||
speculative_config=speculative_config,
|
||||
device_config=DeviceConfig(device=DEVICE_TYPE),
|
||||
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,
|
||||
),
|
||||
)
|
||||
|
||||
return EagleProposer(vllm_config=vllm_config, device=DEVICE_TYPE)
|
||||
|
||||
|
||||
@mock.patch("vllm.v1.spec_decode.llm_base_proposer.get_pp_group")
|
||||
@mock.patch("vllm.v1.spec_decode.llm_base_proposer.get_layers_from_vllm_config")
|
||||
@mock.patch("vllm.v1.spec_decode.llm_base_proposer.get_model")
|
||||
def test_mtp_load_model_unified(mock_get_model, mock_get_layers, mock_get_pp_group):
|
||||
"""Test MTP-specific model loading with unified model approach."""
|
||||
# Setup mocks
|
||||
mock_model = mock.MagicMock()
|
||||
mock_model.model.embed_tokens.weight.shape = (131072, 4096)
|
||||
mock_get_model.return_value = mock_model
|
||||
# MTP does not have its own embed_tokens or lm_head
|
||||
# so it should share them with the target model
|
||||
mock_model.has_own_embed_tokens = False
|
||||
mock_model.has_own_lm_head = False
|
||||
|
||||
target_attn_layers = {"target_attn_1": mock.MagicMock()}
|
||||
all_attn_layers = {**target_attn_layers, "draft_attn_1": mock.MagicMock()}
|
||||
|
||||
mock_get_layers.side_effect = [target_attn_layers, all_attn_layers]
|
||||
|
||||
mock_pp_group = mock.MagicMock()
|
||||
mock_pp_group.world_size = 1
|
||||
mock_get_pp_group.return_value = mock_pp_group
|
||||
|
||||
# Create target model
|
||||
class _TargetModelStub(LlamaForCausalLM):
|
||||
model: mock.MagicMock
|
||||
lm_head: mock.MagicMock
|
||||
|
||||
target_model = mock.create_autospec(_TargetModelStub, instance=True)
|
||||
target_model.model = mock.MagicMock()
|
||||
target_model.model.embed_tokens.weight.shape = (131072, 4096)
|
||||
target_model.lm_head = mock.MagicMock()
|
||||
|
||||
# Create MTP proposer
|
||||
proposer = _create_mtp_proposer(num_speculative_tokens=4)
|
||||
proposer.load_model(target_model)
|
||||
|
||||
# Verify MTP-specific behavior:
|
||||
# Model is loaded
|
||||
mock_get_model.assert_called_once()
|
||||
# MTP shares lm_head with target model
|
||||
assert proposer.model.lm_head == target_model.lm_head
|
||||
# MTP shares embed_tokens with target model
|
||||
assert proposer.model.model.embed_tokens == target_model.model.embed_tokens
|
||||
assert proposer._draft_attn_layer_names == {"draft_attn_1"}
|
||||
assert all_attn_layers["draft_attn_1"].is_draft_layer is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_speculative_tokens", [1])
|
||||
def test_mtp_propose(num_speculative_tokens, monkeypatch):
|
||||
"""Test that MTP's forward method returns hidden states directly."""
|
||||
device = torch.device(DEVICE_TYPE)
|
||||
batch_size = 2
|
||||
seq_lens = [5, 3]
|
||||
total_tokens = sum(seq_lens)
|
||||
vocab_size = 100
|
||||
|
||||
proposer = _create_mtp_proposer(num_speculative_tokens)
|
||||
hidden_size = proposer.hidden_size
|
||||
|
||||
# Mock the MTP model to verify it returns hidden states directly
|
||||
model_mock = mock.MagicMock()
|
||||
|
||||
# MTP returns hidden states directly
|
||||
if num_speculative_tokens == 1:
|
||||
model_mock.return_value = torch.zeros(total_tokens, hidden_size, device=device)
|
||||
else:
|
||||
# Multiple forward passes for multi-token speculation
|
||||
forward_returns = []
|
||||
for i in range(num_speculative_tokens):
|
||||
if i == 0:
|
||||
h_states = torch.zeros(total_tokens, hidden_size, device=device)
|
||||
else:
|
||||
h_states = torch.zeros(batch_size, hidden_size, device=device)
|
||||
forward_returns.append(h_states)
|
||||
model_mock.side_effect = forward_returns
|
||||
|
||||
# Mock compute_logits
|
||||
def create_deterministic_logits(batch_size, vocab_size, token_offset):
|
||||
logits = torch.full((batch_size, vocab_size), -100.0, device=device)
|
||||
logits[:, token_offset] = 100.0
|
||||
return logits
|
||||
|
||||
if num_speculative_tokens == 1:
|
||||
model_mock.compute_logits.return_value = create_deterministic_logits(
|
||||
batch_size, vocab_size, 42
|
||||
)
|
||||
else:
|
||||
logits_returns = [
|
||||
create_deterministic_logits(batch_size, vocab_size, 42 + i)
|
||||
for i in range(num_speculative_tokens)
|
||||
]
|
||||
model_mock.compute_logits.side_effect = logits_returns
|
||||
|
||||
proposer.model = model_mock
|
||||
proposer._draft_attn_layer_names = {"layer.0"}
|
||||
|
||||
# Prepare inputs
|
||||
batch_spec = BatchSpec(seq_lens=seq_lens, query_lens=seq_lens)
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
batch_spec, block_size=16, device=device
|
||||
)
|
||||
|
||||
target_token_ids = torch.randint(0, vocab_size, (total_tokens,), device=device)
|
||||
target_positions = torch.cat(
|
||||
[
|
||||
torch.arange(seq_lens[0], device=device),
|
||||
torch.arange(seq_lens[1], device=device),
|
||||
]
|
||||
)
|
||||
target_hidden_states = torch.randn(total_tokens, hidden_size, device=device)
|
||||
next_token_ids = torch.randint(
|
||||
0, vocab_size, (batch_size,), dtype=torch.int32, device=device
|
||||
)
|
||||
sampling_metadata = mock.MagicMock()
|
||||
|
||||
# Setup attention metadata
|
||||
attn_metadata_builder_cls, _ = try_get_attention_backend(
|
||||
AttentionBackendEnum.FLASH_ATTN
|
||||
)
|
||||
|
||||
attn_metadata_builder = attn_metadata_builder_cls(
|
||||
kv_cache_spec=create_standard_kv_cache_spec(proposer.vllm_config),
|
||||
layer_names=list(proposer._draft_attn_layer_names),
|
||||
vllm_config=proposer.vllm_config,
|
||||
device=device,
|
||||
)
|
||||
|
||||
mock_attn_group = mock.MagicMock()
|
||||
mock_attn_group.get_metadata_builder.return_value = attn_metadata_builder
|
||||
mock_attn_group.layer_names = list(proposer._draft_attn_layer_names)
|
||||
mock_attn_group.kv_cache_spec = attn_metadata_builder.kv_cache_spec
|
||||
proposer.draft_attn_groups = [mock_attn_group]
|
||||
|
||||
# Run propose
|
||||
result = proposer.propose(
|
||||
num_speculative_tokens=num_speculative_tokens,
|
||||
target_token_ids=target_token_ids,
|
||||
target_positions=target_positions,
|
||||
target_hidden_states=target_hidden_states,
|
||||
next_token_ids=next_token_ids,
|
||||
token_indices_to_sample=None,
|
||||
common_attn_metadata=common_attn_metadata,
|
||||
sampling_metadata=sampling_metadata,
|
||||
)
|
||||
|
||||
# Verify the model was called correctly
|
||||
assert model_mock.called
|
||||
# Verify output shape
|
||||
assert result.shape == (batch_size, num_speculative_tokens)
|
||||
Reference in New Issue
Block a user