Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-23 00:40:48 +09:00
512 changed files with 29298 additions and 6783 deletions
+16 -8
View File
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Cold start and warm start tests for vLLM-compile.
Cold start runs in a forked child (must fork before CUDA init) which
Cold start runs in a separate child process which
populates on-disk caches and asserts cold-start counters. Warm start
then runs in the parent with clean in-memory state but populated caches.
"""
@@ -18,7 +18,7 @@ from vllm.compilation.counter import compilation_counter
from vllm.config import CompilationConfig, CompilationMode, CUDAGraphMode, PassConfig
from vllm.utils.torch_utils import is_torch_equal_or_newer
from ...utils import fork_new_process_for_each_test
from ...utils import create_new_process_for_each_test, requires_spawn_multiprocessing
MODEL = "microsoft/Phi-tiny-MoE-instruct"
@@ -54,17 +54,21 @@ def _cold_start(vllm_runner):
assert counters["aot_autograd"]["autograd_cache_hit"] == 0
@fork_new_process_for_each_test
@create_new_process_for_each_test()
@pytest.mark.parametrize("mega_aot_artifact", ["0", "1"])
def test_moe_startup(monkeypatch, vllm_runner, fresh_vllm_cache, mega_aot_artifact):
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
monkeypatch.setenv("VLLM_USE_MEGA_AOT_ARTIFACT", mega_aot_artifact)
monkeypatch.setenv("VLLM_DEEP_GEMM_WARMUP", "skip")
# Cold start in a forked child (must fork before CUDA init).
# ROCm and XPU cannot fork safely after device discovery.
# This model has 32 identical transformer layers which produce
# 33 subgraphs after splitting on attention — only 3 are unique.
ctx = mp.get_context("fork")
ctx = (
mp.get_context("spawn")
if requires_spawn_multiprocessing()
else mp.get_context("fork")
)
p = ctx.Process(target=_cold_start, args=(vllm_runner,))
p.start()
p.join()
@@ -223,13 +227,17 @@ def _cold_start_model(vllm_runner, spec: ModelStartupSpec):
@pytest.mark.parametrize("spec", MODEL_SPECS)
@fork_new_process_for_each_test
@create_new_process_for_each_test()
def test_model_startup(monkeypatch, vllm_runner, fresh_vllm_cache, spec):
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
monkeypatch.setenv("VLLM_DEEP_GEMM_WARMUP", "skip")
# Cold start in a forked child (must fork before CUDA init).
ctx = mp.get_context("fork")
# ROCm and XPU cannot fork safely after device discovery.
ctx = (
mp.get_context("spawn")
if requires_spawn_multiprocessing()
else mp.get_context("fork")
)
p = ctx.Process(target=_cold_start_model, args=(vllm_runner, spec))
p.start()
p.join()
+22
View File
@@ -0,0 +1,22 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.worker.workspace import init_workspace_manager, reset_workspace_manager
@pytest.fixture(autouse=True)
def _workspace_manager_for_compile_passes(cleanup_fixture):
if not current_platform.is_rocm():
yield
return
# Release workspace tensors before cleanup_fixture flushes the allocator.
reset_workspace_manager()
if torch.accelerator.is_available():
init_workspace_manager(torch.device(0))
yield
reset_workspace_manager()
+21 -5
View File
@@ -550,7 +550,9 @@ class TestGatedModel(torch.nn.Module):
"""Model that uses RMSNormGated + reshape + group FP8 quant + linear.
Mimics GatedDeltaNetAttention's output projection path where:
- RMSNormGated operates on per-head tensors (N*H, D)
- RMSNormGated operates on per-head tensors, either (N, H, D) as
QwenGatedDeltaNetAttention passes them or flattened to (N*H, D) as
OlmoHybridGatedDeltaNetAttention does
- Output is reshaped to (N, H*D) before group quantization + linear
"""
@@ -563,10 +565,12 @@ class TestGatedModel(torch.nn.Module):
group_shape: GroupShape,
dtype: torch.dtype,
use_aiter_quant: bool = True,
flatten_heads: bool = True,
):
super().__init__()
self.num_heads = num_heads
self.head_dim = head_dim
self.flatten_heads = flatten_heads
hidden_dim = num_heads * head_dim
self.norm = RMSNormGated(
@@ -599,8 +603,11 @@ class TestGatedModel(torch.nn.Module):
hidden_dim = num_heads * head_dim
x = torch.relu(x)
z = torch.relu(z)
x_heads = x.reshape(-1, num_heads, head_dim).reshape(-1, head_dim)
z_heads = z.reshape(-1, num_heads, head_dim).reshape(-1, head_dim)
x_heads = x.reshape(-1, num_heads, head_dim)
z_heads = z.reshape(-1, num_heads, head_dim)
if self.flatten_heads:
x_heads = x_heads.reshape(-1, head_dim)
z_heads = z_heads.reshape(-1, head_dim)
normed = self.norm(x_heads, z_heads)
merged = normed.reshape(-1, hidden_dim)
out = self.fp8_linear(merged)
@@ -638,6 +645,8 @@ class _MockGDNLayer:
@pytest.mark.parametrize("head_dim", [128])
@pytest.mark.parametrize("num_tokens", [8])
@pytest.mark.parametrize("eps", [1e-5, 1e-6])
@pytest.mark.parametrize("flatten_heads", [True, False])
@pytest.mark.parametrize("quant_fp8_op", ["-quant_fp8", "+quant_fp8"])
@pytest.mark.skipif(
(not current_platform.is_rocm() or not IS_AITER_FOUND),
reason="Only test on ROCm with aiter package installed",
@@ -648,6 +657,8 @@ def test_aiter_fusion_rmsnorm_gated_quant(
head_dim: int,
num_tokens: int,
eps: float,
flatten_heads: bool,
quant_fp8_op: str,
monkeypatch: pytest.MonkeyPatch,
):
group_shape = GroupShape(1, 128)
@@ -655,7 +666,7 @@ def test_aiter_fusion_rmsnorm_gated_quant(
model_config=ModelConfig(dtype=dtype),
compilation_config=CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
custom_ops=["-rms_norm", "-silu_and_mul", "-quant_fp8"],
custom_ops=["-rms_norm", "-silu_and_mul", quant_fp8_op],
pass_config=PassConfig(fuse_norm_quant=True, eliminate_noops=True),
),
)
@@ -688,6 +699,7 @@ def test_aiter_fusion_rmsnorm_gated_quant(
group_shape=group_shape,
dtype=dtype,
use_aiter_quant=True,
flatten_heads=flatten_heads,
)
noop_pass = NoOpEliminationPass(vllm_config)
@@ -708,7 +720,11 @@ def test_aiter_fusion_rmsnorm_gated_quant(
model_unfused = torch.compile(model, backend=backend2)
result_unfused = model_unfused(x, z)
torch.testing.assert_close(result_fused, result_unfused, atol=1e-2, rtol=1e-2)
# The opaque AITER quant op preserves a BF16 intermediate in the
# unfused path, while the fused kernel normalizes and quantizes
# directly. Allow for that extra rounding before the FP8 GEMM.
tol = 2e-2 if quant_fp8_op == "+quant_fp8" else 1e-2
torch.testing.assert_close(result_fused, result_unfused, atol=tol, rtol=tol)
assert fusion_pass.matched_count == 1
backend.check_after_ops(model.ops_in_model_after())
+159
View File
@@ -0,0 +1,159 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
from typing import Any
import pytest
from vllm.config import AuxOutputConfig, VllmConfig
from vllm.config.kv_transfer import KVRole, KVTransferConfig
from vllm.engine.arg_utils import EngineArgs
pytestmark = pytest.mark.cpu_test
def _config(
*,
use_v2: bool = True,
pp: int = 1,
dcp: int = 1,
pcp: int = 1,
connector: str | None = None,
kv_role: KVRole = "kv_both",
runner_type: str = "generate",
is_moe: bool = True,
sliding_window: int | None = None,
attention_chunk_size: int | None = None,
enable_prefix_caching: bool = True,
adaptive_verification: bool = False,
):
return SimpleNamespace(
model_config=SimpleNamespace(
runner_type=runner_type,
is_moe=is_moe,
get_sliding_window=lambda: sliding_window,
attention_chunk_size=attention_chunk_size,
),
use_v2_model_runner=use_v2,
parallel_config=SimpleNamespace(
pipeline_parallel_size=pp,
decode_context_parallel_size=dcp,
prefill_context_parallel_size=pcp,
),
aux_output_config=AuxOutputConfig(enable_return_routed_experts=True),
cache_config=SimpleNamespace(
enable_prefix_caching=enable_prefix_caching,
),
speculative_config=(
SimpleNamespace(enable_adaptive_verification=True)
if adaptive_verification
else None
),
kv_transfer_config=(
None
if connector is None
else KVTransferConfig(
kv_connector=connector,
kv_role=kv_role,
)
),
)
def test_aux_output_config_defaults():
config = AuxOutputConfig()
assert not config.enabled
assert not config.enable_return_routed_experts
assert config.max_bytes is None
def test_aux_output_capture_changes_compilation_hash():
disabled = AuxOutputConfig()
enabled = AuxOutputConfig(enable_return_routed_experts=True)
assert disabled.compute_hash() != enabled.compute_hash()
def test_legacy_routed_experts_flag_updates_aux_output_config():
args = EngineArgs(enable_return_routed_experts=True)
assert args.aux_output_config.enabled
assert args.aux_output_config.enable_return_routed_experts
@pytest.mark.parametrize(
("kwargs", "error"),
[
({"use_v2": False}, "requires Model Runner V2"),
({"runner_type": "pooling"}, "only supports generate runners"),
({"is_moe": False}, "only supports MoE models"),
({"enable_prefix_caching": False}, "requires prefix caching"),
(
{"adaptive_verification": True},
"adaptive speculative verification",
),
({"pp": 2}, "pipeline parallelism"),
({"dcp": 2}, "context parallelism"),
({"pcp": 2}, "context parallelism"),
],
)
def test_aux_output_connector_rejects_unsupported_configuration(kwargs, error):
with pytest.raises(ValueError, match=error):
VllmConfig._verify_aux_output_compatibility(_config(**kwargs))
@pytest.mark.parametrize(
("connector", "blocked"),
[
("NixlConnector", True),
("NixlPullConnector", True),
("NixlPushConnector", True),
("MoRIIOConnector", True),
("MooncakeConnector", True),
("MooncakeStoreConnector", False),
("OffloadingConnector", False),
("LMCacheConnectorV1", False),
("LMCacheMPConnector", False),
("SimpleCPUOffloadConnector", False),
],
)
@pytest.mark.parametrize("kv_role", ["kv_both", "kv_producer", "kv_consumer"])
@pytest.mark.parametrize("multi", [False, True])
def test_aux_output_connector_policy_is_independent_of_role(
connector, blocked, kv_role, multi
):
config = _config(connector=connector, kv_role=kv_role)
if multi:
config.kv_transfer_config = KVTransferConfig(
kv_connector="MultiConnector",
kv_role=kv_role,
kv_connector_extra_config={
"connectors": [
{"kv_connector": "OffloadingConnector", "kv_role": "kv_both"},
{"kv_connector": connector, "kv_role": kv_role},
]
},
)
if blocked:
with pytest.raises(ValueError, match=f"incompatible with {connector}"):
VllmConfig._verify_aux_output_compatibility(config)
else:
VllmConfig._verify_aux_output_compatibility(config)
@pytest.mark.parametrize(
"kwargs",
[{"sliding_window": 4096}, {"attention_chunk_size": 4096}],
)
def test_aux_output_config_defers_attention_layout_to_kv_config(kwargs):
VllmConfig._verify_aux_output_compatibility(_config(**kwargs))
def test_aux_output_guards_are_inactive_when_capture_is_disabled():
config: Any = VllmConfig.__new__(VllmConfig)
config.model_config = SimpleNamespace()
config.aux_output_config = AuxOutputConfig()
config._verify_aux_output_compatibility()
+46 -54
View File
@@ -1,12 +1,14 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import copy
from unittest.mock import MagicMock, patch
import pytest
import torch
from transformers import PretrainedConfig
from tests.models.utils import build_model_context
from vllm.config.ec_transfer import ECRole, ECTransferConfig
from vllm.config.model import ModelConfig
from vllm.config.multimodal import MultiModalConfig
@@ -17,6 +19,26 @@ from vllm.transformers_utils.model_arch_config_convertor import (
from vllm.v1.attention.backends.registry import AttentionBackendEnum
@pytest.mark.parametrize(
"model_id,limit_mm_per_prompt,expected",
[
("Qwen/Qwen2-0.5B-Instruct", {}, False),
("Qwen/Qwen2.5-VL-3B-Instruct", {}, True),
("Qwen/Qwen2.5-VL-3B-Instruct", {"image": 0, "video": 0}, False),
("Qwen/Qwen2.5-VL-3B-Instruct", {"image": 0}, True),
],
)
@pytest.mark.core_model
def test_supports_multimodal_inputs(model_id, limit_mm_per_prompt, expected):
"""Test supports_multimodal_inputs returns correct boolean for various
configs."""
ctx = build_model_context(
model_id,
limit_mm_per_prompt=limit_mm_per_prompt,
)
assert ctx.model_config.supports_multimodal_inputs is expected
def test_mm_encoder_attn_backend_str_conversion():
config = MultiModalConfig(mm_encoder_attn_backend="FLASH_ATTN") # type: ignore[arg-type]
assert config.mm_encoder_attn_backend == AttentionBackendEnum.FLASH_ATTN
@@ -84,59 +106,33 @@ def test_mm_encoder_attn_dtype_hash_updates(tmp_path):
assert fp8_hash != fp8_static_hash
_MULTIMODAL_MODEL = "llava-hf/llava-1.5-7b-hf"
_TEXT_ONLY_MODEL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
def _make_mm_prefix_model_config(
model: str = _MULTIMODAL_MODEL,
*,
language_model_only: bool = False,
) -> ModelConfig:
model_config = MagicMock(spec=ModelConfig)
model_config.multimodal_config = MultiModalConfig(
language_model_only=language_model_only
)
# Bind real helper methods onto the mock.
model_config._supports_multimodal_for_mm_prefix = (
ModelConfig._supports_multimodal_for_mm_prefix.__get__(
model_config, ModelConfig
)
)
return model_config
@pytest.mark.parametrize("supports_mm", [True, False])
def test_supports_multimodal_for_mm_prefix_uses_registry(supports_mm: bool):
model_config = _make_mm_prefix_model_config()
with patch(
"vllm.multimodal.MULTIMODAL_REGISTRY.supports_multimodal_inputs",
return_value=supports_mm,
) as mocked:
assert model_config._supports_multimodal_for_mm_prefix() is supports_mm
mocked.assert_called_once_with(model_config)
# Sticky cache — registry must not be consulted again.
with patch(
"vllm.multimodal.MULTIMODAL_REGISTRY.supports_multimodal_inputs",
side_effect=AssertionError("should use cache"),
):
assert model_config._supports_multimodal_for_mm_prefix() is supports_mm
return ModelConfig(model, language_model_only=language_model_only)
def test_supports_multimodal_for_mm_prefix_before_multimodal_config():
model_config = _make_mm_prefix_model_config()
model_config.multimodal_config = None
"""A text-only model never builds a multimodal config, so the early
return must neither clear mm_prefix nor write the sticky cache."""
model_config = _make_mm_prefix_model_config(_TEXT_ONLY_MODEL)
assert model_config.multimodal_config is None
assert model_config._supports_multimodal_for_mm_prefix() is True
assert not hasattr(model_config, "_supports_multimodal_inputs_cached")
assert not getattr(model_config, "_supports_multimodal_inputs_cache", None)
def test_language_model_only_disables_via_supports_multimodal_inputs():
"""language_model_only zeros all limits, so registry reports text-only."""
model_config = _make_mm_prefix_model_config(language_model_only=True)
with patch(
"vllm.multimodal.MULTIMODAL_REGISTRY.supports_multimodal_inputs",
return_value=False,
):
assert model_config._supports_multimodal_for_mm_prefix() is False
assert model_config._supports_multimodal_for_mm_prefix() is False
def test_convertor_clears_mm_prefix_when_multimodal_disabled():
@@ -159,23 +155,19 @@ def test_convertor_clears_mm_prefix_when_multimodal_disabled():
def test_sticky_cache_survives_text_subconfig_regeneration():
"""with_hf_config deepcopies the cached decision onto text submodules."""
model_config = _make_mm_prefix_model_config()
with patch(
"vllm.multimodal.MULTIMODAL_REGISTRY.supports_multimodal_inputs",
return_value=False,
):
assert model_config._supports_multimodal_for_mm_prefix() is False
assert model_config._supports_multimodal_for_mm_prefix() is True
# Simulate deepcopy onto a Gemma4ForCausalLM-like config that would
# otherwise fail registry lookup / return False incorrectly.
text_config = _make_mm_prefix_model_config()
text_config._supports_multimodal_inputs_cached = (
model_config._supports_multimodal_inputs_cached
)
with patch(
"vllm.multimodal.MULTIMODAL_REGISTRY.supports_multimodal_inputs",
side_effect=AssertionError("must not re-query registry"),
):
assert text_config._supports_multimodal_for_mm_prefix() is False
# `with_hf_config` deep-copies this config and swaps `hf_config` for a
# text-only submodule (e.g. Gemma4ForCausalLM).
text_config = copy.deepcopy(model_config)
text_config.hf_config = model_config.hf_text_config
assert text_config._supports_multimodal_for_mm_prefix() is True
# Without the copied cache the submodule architecture has no registered
# multimodal processor, so re-querying the registry wrongly settles on
# text-only and would clear mm_prefix.
del text_config._supports_multimodal_inputs_cache
assert text_config._supports_multimodal_for_mm_prefix() is False
@pytest.mark.parametrize(
+32 -5
View File
@@ -504,6 +504,36 @@ class HfRunner:
if model_cls is not None:
_fix_v4_tied_weights_keys(model_cls)
from transformers.integrations import is_deepspeed_zero3_enabled
# On ROCm, avoid a converted CPU copy when downcasting FP32 references.
# Same-dtype CPU loads can stay lazily mapped and use less host RAM.
# Leave customized, remote, and quantized loading unchanged.
if (
current_platform.is_rocm()
and self.device == "cuda"
and auto_cls is AutoModelForCausalLM
and revision is None
and model_kwargs.keys() == {"dtype"}
and self.config.dtype == torch.float32
and model_kwargs["dtype"] in (torch.float16, torch.bfloat16)
and not (trust_remote_code and hasattr(self.config, "auto_map"))
and getattr(self.config, "quantization_config", None) is None
and getattr(
self.config.get_text_config(decoder=True),
"quantization_config",
None,
)
is None
and not is_deepspeed_zero3_enabled()
):
model_kwargs = {
**model_kwargs,
"device_map": torch.device(
"cuda", torch.accelerator.current_device_index()
),
}
model = cast(
nn.Module,
auto_cls.from_pretrained(
@@ -901,13 +931,10 @@ class HfRunner:
# tests/basic_correctness/test_basic_correctness.py::test_models_distributed
# where vllm worker processes are still alive and holding GPU
# memory when hf_runner.__exit__ is called.
from tests.utils import (
get_physical_device_indices,
record_gpu_memory_usage_stats,
)
from tests.utils import record_gpu_memory_usage_stats
if (device_count := current_platform.device_count()) > 0:
devices = get_physical_device_indices(devices=list(range(device_count)))
devices = list(range(device_count))
mem_usage_stats = record_gpu_memory_usage_stats(devices=devices)
self.threshold_ratios = {
device: 0.05 + mem_used / mem_tot
File diff suppressed because it is too large Load Diff
+111
View File
@@ -11,6 +11,7 @@ import torch.distributed as dist
from vllm.distributed.communication_op import tensor_model_parallel_all_reduce # noqa
from vllm.distributed.device_communicators import custom_all_reduce as car
from vllm.distributed.parallel_state import get_tp_group, graph_capture
from vllm.platforms import current_platform
from ..utils import (
ensure_model_parallel_initialized,
@@ -24,6 +25,116 @@ for i, v in enumerate(test_sizes):
test_sizes[i] -= v % 8
@ray.remote(num_gpus=1, max_calls=1)
def _all_reduce_mhc(monkeypatch, tp_size, pp_size, rank, distributed_init_port):
from vllm.model_executor.kernels.mhc.tilelang import (
mhc_post_tilelang,
mhc_pre_delayed_tilelang,
)
with monkeypatch.context() as m:
m.delenv("CUDA_VISIBLE_DEVICES", raising=False)
device = torch.device(f"cuda:{rank}")
torch.accelerator.set_device_index(device)
init_test_distributed_environment(tp_size, pp_size, rank, distributed_init_port)
ensure_model_parallel_initialized(tp_size, pp_size)
comm = get_tp_group().device_communicator.ca_comm
assert comm is not None and comm.mnnvl_lamport_ag_multicast_ptr
fn = torch.zeros(24, 20480, device=device)
scale = torch.ones(3, device=device)
base = torch.zeros(24, device=device)
# Changing shapes and interleaving all-gather exercise the shared
# Lamport stages, including cleanup of a larger previous payload.
def run(n):
torch.manual_seed(42 + rank)
x = torch.randn(n, 5120, device=device, dtype=torch.bfloat16)
# Packed +0/-0 pairs collide with the Lamport sentinel.
x[:, :16] = 0
x[:, 9:16:2] = -0.0
torch.manual_seed(123)
residual = torch.randn(n, 4, 5120, device=device, dtype=torch.bfloat16)
post = torch.rand(n, 4, device=device)
comb = torch.randn(n, 4, 4, device=device) * 0.1
pre = torch.rand(n, 4, device=device)
weight = torch.randn(5120, device=device, dtype=torch.bfloat16)
output = torch.empty_like(residual)
normalized = torch.empty_like(x)
def fused():
torch.ops._C_custom_ar.all_reduce_mhc(
x,
residual,
post,
comb,
pre,
weight,
output,
normalized,
comm.mnnvl_lamport_ag_local_ptr,
comm.mnnvl_lamport_ag_multicast_ptr,
comm.mnnvl_lamport_epochs[0],
rank,
comm.mnnvl_buffer_size,
1e-6,
)
def check():
gathered = comm.custom_all_gather(x)
assert gathered is not None
peers = gathered.view(tp_size, n, 5120).float()
reduced = peers[0].clone()
for peer in peers[1:]:
reduced.add_(peer)
expected = mhc_post_tilelang(
reduced.bfloat16(), residual, post.unsqueeze(-1), comb
)
expected_norm = mhc_pre_delayed_tilelang(
expected,
fn,
scale,
base,
1e-6,
1e-6,
1e-6,
2.0,
20,
pre_mix=pre,
norm_weight=weight,
)[2]
torch.testing.assert_close(output, expected, rtol=0.008, atol=1e-6)
torch.testing.assert_close(
normalized, expected_norm, rtol=0.008, atol=0.008
)
fused()
check()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
for _ in range(6):
fused()
for _ in range(20):
graph.replay()
check()
x.mul_(0.5)
residual.mul_(2)
graph.replay()
check()
# Cover fixed Q6 and shrinking/growing adaptive verification batches.
for n in (1, 6, 12, 8, 16, 3, 5, 2, 4, 1):
run(n)
@pytest.mark.skipif(
not current_platform.is_device_capability_family(100), reason="Requires SM100"
)
def test_all_reduce_mhc_preserves_bf16_boundaries_and_graph_replay(monkeypatch):
if torch.accelerator.device_count() < 4:
pytest.skip("Requires four GPUs with NVLink multicast")
multi_process_parallel(monkeypatch, 4, 1, _all_reduce_mhc)
@pytest.mark.parametrize(
("dtype", "expected"),
[
@@ -512,6 +512,7 @@ def _check_dummy_hash_model_forward(
model = SimpleNamespace(
use_mega_moe=False,
use_sequence_parallel=False,
fuse_mhc_all_reduce=False,
engram_hash=state,
engram_swa_prefix="swa",
engram_dp_shared_memory=dp_shared_memory,
@@ -684,6 +685,13 @@ def test_engram_dp_shared_memory_runtime_requirements(
)
def test_engram_tables_too_large_for_shm_are_not_shared(monkeypatch):
"""A /dev/shm smaller than the tables must fall back instead of failing startup."""
monkeypatch.setattr(engram_ops, "get_engram_dp_size", lambda: 2)
layout = SimpleNamespace(num_embeddings=(1 << 50,), head_dim=DIM)
assert not engram_ops.can_share_engram_tables(layout)
@pytest.mark.parametrize(
"node_ids,dp_size,replica_size,expected",
[
+28 -2
View File
@@ -9,7 +9,13 @@ from typing import Annotated, Literal
import pytest
from pydantic import Field
from vllm.config import AttentionConfig, CompilationConfig, ModelConfig, config
from vllm.config import (
AttentionConfig,
CacheConfig,
CompilationConfig,
ModelConfig,
config,
)
from vllm.engine.arg_utils import (
EngineArgs,
_expand_json_human_readable_numbers,
@@ -86,6 +92,26 @@ def test_watermark_config_cli():
assert config.deduplicate_contexts_max_history == 32
@pytest.mark.parametrize(
"option",
["--gpu-memory-utilization", "--device-memory-utilization"],
)
def test_memory_utilization_cli_aliases(option):
parser = EngineArgs.add_cli_args(FlexibleArgumentParser())
args = EngineArgs.from_cli_args(parser.parse_args([option, "0.8"]))
assert args.gpu_memory_utilization == 0.8
def test_device_memory_utilization_property():
config = CacheConfig(gpu_memory_utilization=0.8)
assert config.device_memory_utilization == 0.8
config.device_memory_utilization = 0.7
assert config.gpu_memory_utilization == 0.7
@pytest.mark.parametrize(
"options",
[
@@ -114,7 +140,7 @@ def test_engram_config_cli(options):
"options,provided,dp_shared_memory",
[
([], False, False),
(["--engram-config", "{}"], True, False),
(["--engram-config", "{}"], True, None),
(
["--engram-config", '{"dp_shared_memory": true}'],
True,
@@ -60,7 +60,10 @@ class MockModelConfig:
encoder_config = None
generation_config: str = "auto"
media_io_kwargs: dict[str, dict[str, Any]] = field(default_factory=dict)
skip_tokenizer_init = False
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
vocab_size = 151936
def get_diff_sampling_param(self):
File diff suppressed because it is too large Load Diff
@@ -56,9 +56,10 @@ class MockModelConfig:
encoder_config = None
generation_config: str = "auto"
media_io_kwargs: dict[str, dict[str, Any]] = field(default_factory=dict)
skip_tokenizer_init = False
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
renderer_num_workers: int = 1
def get_diff_sampling_param(self):
@@ -556,6 +556,7 @@ class MockModelConfig:
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
renderer_num_workers: int = 1
enable_prompt_embeds: bool = False
@@ -61,9 +61,10 @@ class MockModelConfig:
encoder_config = None
generation_config: str = "auto"
media_io_kwargs: dict[str, dict[str, Any]] = field(default_factory=dict)
skip_tokenizer_init = False
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
renderer_num_workers: int = 1
def get_diff_sampling_param(self):
@@ -54,6 +54,7 @@ class MockModelConfig:
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
renderer_num_workers: int = 1
def get_diff_sampling_param(self):
@@ -86,9 +86,10 @@ class MockModelConfig:
generation_config: str = "auto"
override_generation_config: dict[str, Any] = field(default_factory=dict)
media_io_kwargs: dict[str, dict[str, Any]] = field(default_factory=dict)
skip_tokenizer_init = False
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
renderer_num_workers: int = 1
enable_prompt_embeds: bool = False
@@ -12,15 +12,13 @@ from ...utils import RemoteOpenAIServer
MODEL_NAME = "TitanML/tiny-mixtral"
# tiny-mixtral config: 8 local experts, top-2 routing, 2 hidden layers.
# The published config has sliding_window=4096, which produces
# SlidingWindowSpec kv-cache groups; RoutedExpertsManager requires a
# FullAttentionSpec group, so we override sliding_window=null below.
# Its published sliding window is incompatible with AuxOutput retention.
NUM_LOCAL_EXPERTS = 8
NUM_EXPERTS_PER_TOK = 2
NUM_HIDDEN_LAYERS = 2
def assert_valid_routed_experts(encoded: str | None) -> None:
def decode_routed_experts(encoded: str | None) -> np.ndarray:
assert encoded is not None
routed_experts = np.load(io.BytesIO(base64.b64decode(encoded)))
assert routed_experts.ndim == 3
@@ -30,6 +28,7 @@ def assert_valid_routed_experts(encoded: str | None) -> None:
assert topk == NUM_EXPERTS_PER_TOK
assert (routed_experts >= 0).all()
assert (routed_experts < NUM_LOCAL_EXPERTS).all()
return routed_experts
@pytest.fixture(scope="module")
@@ -44,7 +43,11 @@ def server():
"--hf-overrides",
'{"sliding_window": null}',
]
with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
with RemoteOpenAIServer(
MODEL_NAME,
args,
env_dict={"VLLM_USE_V2_MODEL_RUNNER": "1"},
) as remote_server:
yield remote_server
@@ -63,4 +66,8 @@ async def test_routed_experts(server):
choice = result.model_dump()["choices"][0]
assert choice["token_ids"] is not None
assert_valid_routed_experts(choice["routed_experts"])
assert result.usage is not None
routed_experts = decode_routed_experts(choice["routed_experts"])
assert len(routed_experts) == (
result.usage.prompt_tokens + len(choice["token_ids"]) - 1
)
@@ -3,20 +3,25 @@
"""Round trip parity CI: render -> generate -> derender -> render == render.
Pins the coupled parsing path (``/v1/chat/completions`` on a normal GPU
Pins the coupled parsing path (`/v1/chat/completions` on a normal GPU
server which parses generated tokens incrementally as they stream out)
against the disaggregated path (``OnlineDerenderer.derender_chat`` via
``/v1/chat/completions/derender`` which parses the same tokens all at once,
out of process). A standard ``vllm serve`` GPU server mounts both, so one
against the disaggregated path (`OnlineDerenderer.derender_chat` via
`/v1/chat/completions/derender` which parses the same tokens all at once,
out of process). A standard `vllm serve` GPU server mounts both, so one
real generation lets both parsers run on identical input.
Both paths consume the same generated token IDs (extracted from the coupled
response's ``token_ids`` via ``return_token_ids=True``), so generation
response's `token_ids` via `return_token_ids=True`), so generation
nondeterminism is irrelevant. The only variable under test is whether the
two parsing code paths agree. Parity is asserted unconditionally as only the
stronger per case assertions (e.g. "a tool call was produced") are gated
behind the marker actually having been emitted since a 1.5B model is not
guaranteed to emit ``<think>`` / ``<tool_call>``.
guaranteed to emit `<think>` / `<tool_call>`.
The streaming cases do the same for `stream=true`. Each coupled chunk's
`token_ids` becomes one `/inference/v1/generate` stream chunk, fed
through the chunked derender path with `stream_state` threaded across calls
the way a client would, so both parsers see the same chunk boundaries.
"""
import json
@@ -24,7 +29,12 @@ import json
import httpx
import pytest
import pytest_asyncio
import regex as re
from tests.entrypoints.scale_out.derender.utils import (
assemble_stream,
stream_chat_derender,
)
from tests.utils import RemoteOpenAIServer
MODEL = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B"
@@ -228,8 +238,8 @@ async def test_parity_logprobs(client):
"""token_id:N resolution parity vs. the coupled server's real strings.
A real disaggregated worker only has token IDs so it emits logprobs
with ``token_id:N`` placeholders (``return_tokens_as_token_ids=True``
reproduces that shape here). ``/derender`` must resolve those
with `token_id:N` placeholders (`return_tokens_as_token_ids=True`
reproduces that shape here). `/derender` must resolve those
placeholders to the same token strings/bytes the coupled server
resolves them to directly.
"""
@@ -267,3 +277,166 @@ async def test_parity_logprobs(client):
for d_entry, r_entry in zip(d_content, r_content):
assert d_entry["token"] == r_entry["token"]
assert d_entry["bytes"] == r_entry["bytes"]
# ---------------------------------------------------------------------------
# Streaming helpers
# ---------------------------------------------------------------------------
async def _coupled_stream(
client: httpx.AsyncClient, messages: list[dict], **extra
) -> tuple[list[dict], list[int]]:
"""Stream `/v1/chat/completions` and return the choices that carry
`token_ids` along with the prompt token IDs.
The leading role only chunk has no `token_ids` and no counterpart on
`/inference/v1/generate`, so it is dropped.
"""
choices: list[dict] = []
prompt_token_ids: list[int] | None = None
async with client.stream(
"POST",
"/v1/chat/completions",
json={
"model": MODEL,
"messages": messages,
"temperature": 0,
"max_tokens": 128,
"return_token_ids": True,
"stream": True,
**extra,
},
) as resp:
assert resp.status_code == 200, await resp.aread()
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
data = line[len("data: ") :]
if data == "[DONE]":
break
chunk = json.loads(data)
assert "error" not in chunk, chunk
if chunk.get("prompt_token_ids") is not None:
prompt_token_ids = chunk["prompt_token_ids"]
choices.extend(
ch for ch in chunk["choices"] if ch.get("token_ids") is not None
)
assert prompt_token_ids is not None
return choices, prompt_token_ids
def _tool_call_id_shape(tool_call_id: str | None) -> str | None:
"""Drop the random suffix so IDs compare by format, e.g. `chatcmpl-tool-`.
Deterministic IDs such as kimi_k2's `functions.<name>:<idx>` are kept
whole."""
if tool_call_id is None:
return None
return re.sub(r"[0-9a-f]{16}$", "", tool_call_id)
async def _run_stream_parity_case(
client: httpx.AsyncClient,
messages: list[dict],
finish_only_tail: bool = False,
**extra,
) -> tuple[dict, list[dict]]:
"""Stream the coupled request, replay its chunks through the streaming
derender endpoint and assert the assembled messages agree. Returns the
assembled coupled message and the coupled choices.
Derender gets the engine's finish reason, since `"tool_calls"` is a chat
level rewrite of `"stop"` that derender has to reapply itself. With
`finish_only_tail` it goes on a trailing chunk with no tokens.
"""
coupled_choices, prompt_token_ids = await _coupled_stream(client, messages, **extra)
finish_reason = coupled_choices[-1]["finish_reason"]
disagg = await stream_chat_derender(
client,
[tid for ch in coupled_choices for tid in ch["token_ids"]],
[len(ch["token_ids"]) for ch in coupled_choices]
+ ([0] if finish_only_tail else []),
{"model": MODEL, "messages": messages, **extra},
len(prompt_token_ids),
prompt_token_ids,
finish_reason="stop" if finish_reason == "tool_calls" else finish_reason,
)
coupled = assemble_stream(coupled_choices)
for message in (coupled, disagg):
for tc in message["tool_calls"]:
tc["id"] = _tool_call_id_shape(tc["id"])
assert disagg == coupled
return coupled, coupled_choices
# ---------------------------------------------------------------------------
# Streaming parity cases
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_stream_parity_plain(client):
"""Plain streamed detokenization parity."""
messages = [
{"role": "user", "content": "What is 2+2? Answer in one short sentence."}
]
await _run_stream_parity_case(client, messages)
@pytest.mark.asyncio
async def test_stream_parity_reasoning(client):
"""Streamed reasoning/content split parity."""
messages = [{"role": "user", "content": "What is 17 times 23? Think it through."}]
coupled, _ = await _run_stream_parity_case(
client, messages, include_reasoning=True, max_tokens=256
)
if not coupled["reasoning"]:
pytest.skip("Model did not emit a <think> block")
@pytest.mark.asyncio
async def test_stream_parity_tool_call(client):
"""Streamed tool call parity under `tool_choice="auto"`, where a tool
call also rewrites `finish_reason` to `"tool_calls"`."""
messages = [{"role": "user", "content": "What's the weather in Paris?"}]
coupled, _ = await _run_stream_parity_case(
client, messages, tools=TOOLS, tool_choice="auto", max_tokens=512
)
if not coupled["tool_calls"]:
pytest.skip("Model did not emit a tool call")
@pytest.mark.asyncio
@pytest.mark.parametrize(
"chunking", ["engine_steps", "multi_token", "finish_only_tail"]
)
async def test_stream_parity_reasoning_and_tool_call(client, chunking):
"""Streamed reasoning + forced tool call parity across chunk shapes.
`multi_token` batches tokens per chunk with `stream_interval` the way
speculative decoding does, so replay has to reuse the original chunk
boundaries. `finish_only_tail` sends the finish reason on a chunk with no
tokens, which must still flush buffered tool call arguments.
"""
messages = [{"role": "user", "content": "What's the weather in Paris?"}]
extra: dict = {
"tools": TOOLS,
"tool_choice": FORCE_WEATHER_TOOL,
"include_reasoning": True,
"max_tokens": 512,
}
if chunking == "multi_token":
extra["stream_interval"] = 4
coupled, coupled_choices = await _run_stream_parity_case(
client,
messages,
finish_only_tail=chunking == "finish_only_tail",
**extra,
)
if chunking == "multi_token":
assert any(len(ch["token_ids"]) > 1 for ch in coupled_choices)
if not (coupled["reasoning"] and coupled["tool_calls"]):
pytest.skip("Model did not emit both a <think> block and a tool call")
@@ -5,24 +5,24 @@
Tests are split into two layers:
1. Unit tests (no server): covers ``_detokenize_delta`` correctness
(chunked == one-shot) and ``derender_completion_stream`` /
``derender_chat_stream`` logic via a real tokenizer on a tiny model.
1. Unit tests (no server): covers `_detokenize_delta` correctness
(chunked == one-shot) and `derender_completion_stream` /
`derender_chat_stream` logic via a real tokenizer on a tiny model.
The parser path is covered both with a deterministic stub parser and
with the real ``HarmonyParser`` (skipped without ``openai_harmony``).
with the real `HarmonyParser` (skipped without `openai_harmony`).
2. Integration tests (require a running render server): covers the full
HTTP round-trip through the streaming endpoint. Marked with
``@pytest.mark.asyncio`` and gated by the ``server`` / ``client``
fixtures from the sibling ``test_derender.py``.
`@pytest.mark.asyncio` and gated by the `server` / `client`
fixtures from the sibling `test_derender.py`.
"""
import json
from collections.abc import Callable
import pytest
import pytest_asyncio
from tests.entrypoints.scale_out.derender.utils import stream_chat_derender
from vllm.entrypoints.generate.base.protocol import (
DeltaFunctionCall,
DeltaMessage,
@@ -356,7 +356,7 @@ class TestDetokenizeDelta:
"""prev_tokens must not grow with the number of chunks (bounded transport).
Guards that the carried decode window is a small constant
tail, so cumulative ``stream_state`` transport is O(n) and not O(n^2).
tail, so cumulative `stream_state` transport is O(n) and not O(n^2).
"""
token_ids = tokenizer.encode(
"a reasonably long ascii stream of tokens used to exercise the "
@@ -1616,86 +1616,6 @@ async def _render_parser_chat(client, messages: list[dict]) -> dict:
return resp.json()
async def _stream_chat_derender(
client,
output_ids: list[int],
chunk_sizes: list[int],
chat_request: dict,
prompt_tokens: int,
prompt_token_ids: list[int],
on_chunk: Callable[[list[dict]], None] | None = None,
) -> dict:
"""Feed `output_ids` through the streaming chat derender endpoint in
the given `chunk_sizes`, threading `stream_state` across calls and
return the assembled message.
If `on_chunk` is given, it is called after every chunk with a
snapshot (deep copy) of the `tool_calls` accumulator so far, letting
callers assert properties of the intermediate deltas (e.g. monotonic
argument growth) rather than only the final assembled result.
"""
state = None
content = ""
reasoning = ""
tool_calls: list[dict] = []
finish_reason = None
pos = 0
for i, size in enumerate(chunk_sizes):
tids = output_ids[pos : pos + size]
pos += size
is_last = i == len(chunk_sizes) - 1
resp = await client.post(
"/v1/chat/completions/derender",
json={
"stream": True,
"model": PARSER_MODEL,
"generate_chunk": {
"request_id": "stream-test",
"choices": [
{
"index": 0,
"token_ids": tids,
"finish_reason": "stop" if is_last else None,
}
],
},
"stream_state": state,
"prompt_tokens": prompt_tokens,
"prompt_token_ids": prompt_token_ids,
"chat_request": chat_request,
},
)
assert resp.status_code == 200, resp.text
data = resp.json()
state = data["stream_state"]
delta = data["chunk"]["choices"][0]["delta"]
content += delta.get("content") or ""
reasoning += delta.get("reasoning") or ""
for tc in delta.get("tool_calls") or []:
idx = tc["index"]
while len(tool_calls) <= idx:
tool_calls.append({"id": None, "name": None, "arguments": ""})
if tc.get("id"):
tool_calls[idx]["id"] = tc["id"]
fn = tc.get("function") or {}
if fn.get("name"):
tool_calls[idx]["name"] = fn["name"]
if fn.get("arguments"):
tool_calls[idx]["arguments"] += fn["arguments"]
if is_last:
finish_reason = data["chunk"]["choices"][0]["finish_reason"]
if on_chunk is not None:
on_chunk([dict(tc) for tc in tool_calls])
return {
"content": content or None,
"reasoning": reasoning or None,
"tool_calls": tool_calls,
"finish_reason": finish_reason,
}
@pytest.mark.asyncio
@pytest.mark.parametrize(
"chunking",
@@ -1755,7 +1675,7 @@ async def test_stream_parsed_matches_batch_reasoning(
"triples": [3] * (n // 3) + [n % 3],
}[chunking]
chunk_sizes = [c for c in chunk_sizes if c > 0]
streamed = await _stream_chat_derender(
streamed = await stream_chat_derender(
parser_client,
output_ids,
chunk_sizes,
@@ -1823,7 +1743,7 @@ async def test_stream_parsed_matches_batch_tool_call(parser_client, parser_token
if tool_calls and tool_calls[0]["arguments"]:
_snapshots.append(tool_calls[0]["arguments"])
streamed = await _stream_chat_derender(
streamed = await stream_chat_derender(
parser_client,
output_ids,
chunk_sizes,
@@ -1868,7 +1788,7 @@ async def test_stream_parsed_cjk_across_chunk_boundaries(
"messages": messages,
"include_reasoning": True,
}
streamed = await _stream_chat_derender(
streamed = await stream_chat_derender(
parser_client,
output_ids,
[1] * len(output_ids),
@@ -1896,7 +1816,7 @@ async def test_stream_parsed_include_reasoning_false(parser_client, parser_token
"messages": messages,
"include_reasoning": False,
}
streamed = await _stream_chat_derender(
streamed = await stream_chat_derender(
parser_client,
output_ids,
[1] * len(output_ids),
@@ -0,0 +1,103 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Helpers shared by the streaming chat derender tests."""
from collections.abc import Callable
import httpx
def assemble_stream(choices: list[dict]) -> dict:
"""Fold streamed chat choices into one message.
A tool call index must keep the first ID it was given. On the derender
side that is what pinning the IDs in `stream_state` guarantees.
"""
content = ""
reasoning = ""
tool_calls: list[dict] = []
finish_reason = None
for choice in choices:
delta = choice["delta"]
content += delta.get("content") or ""
reasoning += delta.get("reasoning") or ""
for tc in delta.get("tool_calls") or []:
idx = tc["index"]
while len(tool_calls) <= idx:
tool_calls.append({"id": None, "name": None, "arguments": ""})
if tc.get("id"):
assert tool_calls[idx]["id"] in (None, tc["id"]), (
f"tool call {idx} changed ID mid stream"
)
tool_calls[idx]["id"] = tc["id"]
fn = tc.get("function") or {}
if fn.get("name"):
tool_calls[idx]["name"] = fn["name"]
tool_calls[idx]["arguments"] += fn.get("arguments") or ""
finish_reason = choice.get("finish_reason") or finish_reason
return {
"content": content or None,
"reasoning": reasoning or None,
"tool_calls": tool_calls,
"finish_reason": finish_reason,
}
async def stream_chat_derender(
client: httpx.AsyncClient,
output_ids: list[int],
chunk_sizes: list[int],
chat_request: dict,
prompt_tokens: int,
prompt_token_ids: list[int],
finish_reason: str = "stop",
on_chunk: Callable[[list[dict]], None] | None = None,
) -> dict:
"""Feed `output_ids` through the streaming chat derender endpoint in
the given `chunk_sizes`, threading `stream_state` across calls and
return the assembled message.
`finish_reason` goes on the last chunk, so a trailing size of 0 sends it
on a chunk with no tokens.
If `on_chunk` is given, it is called after every chunk with the
`tool_calls` assembled so far, letting callers assert properties of the
intermediate deltas (e.g. monotonic argument growth) rather than only
the final assembled result.
"""
state = None
choices: list[dict] = []
pos = 0
for i, size in enumerate(chunk_sizes):
tids = output_ids[pos : pos + size]
pos += size
is_last = i == len(chunk_sizes) - 1
resp = await client.post(
"/v1/chat/completions/derender",
json={
"stream": True,
"model": chat_request["model"],
"generate_chunk": {
"request_id": "stream-test",
"choices": [
{
"index": 0,
"token_ids": tids,
"finish_reason": finish_reason if is_last else None,
}
],
},
"stream_state": state,
"prompt_tokens": prompt_tokens,
"prompt_token_ids": prompt_token_ids,
"chat_request": chat_request,
},
)
assert resp.status_code == 200, resp.text
data = resp.json()
state = data["stream_state"]
choices.extend(data["chunk"]["choices"])
if on_chunk is not None:
on_chunk(assemble_stream(choices)["tool_calls"])
return assemble_stream(choices)
@@ -61,9 +61,10 @@ class MockModelConfig:
encoder_config = None
generation_config: str = "auto"
media_io_kwargs: dict[str, dict[str, Any]] = field(default_factory=dict)
skip_tokenizer_init = False
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
renderer_num_workers: int = 1
def get_diff_sampling_param(self):
@@ -15,9 +15,7 @@ MODEL_NAME = "TitanML/tiny-mixtral"
GEN_ENDPOINT = "/inference/v1/generate"
# tiny-mixtral config: 8 local experts, top-2 routing, 2 hidden layers.
# The published config has sliding_window=4096, which produces
# SlidingWindowSpec kv-cache groups; RoutedExpertsManager requires a
# FullAttentionSpec group, so we override sliding_window=null below.
# Its published sliding window is incompatible with AuxOutput retention.
NUM_LOCAL_EXPERTS = 8
NUM_EXPERTS_PER_TOK = 2
NUM_HIDDEN_LAYERS = 2
@@ -36,7 +34,13 @@ def server():
'{"sliding_window": null}',
"--enable-scale-out",
]
with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
with RemoteOpenAIServer(
MODEL_NAME,
args,
env_dict={
"VLLM_USE_V2_MODEL_RUNNER": "1",
},
) as remote_server:
yield remote_server
@@ -56,9 +60,10 @@ async def client(server: RemoteOpenAIServer):
@pytest.mark.asyncio
async def test_generate_routed_experts(client):
"""Test that /inference/v1/generate returns routed_experts when enabled."""
prompt_token_ids = [1, 2, 3]
payload = {
"model": MODEL_NAME,
"token_ids": [1, 2, 3],
"token_ids": prompt_token_ids,
"sampling_params": {"max_tokens": 10, "temperature": 0.0},
"stream": False,
}
@@ -80,3 +85,4 @@ async def test_generate_routed_experts(client):
assert topk == NUM_EXPERTS_PER_TOK
assert (routed_experts >= 0).all()
assert (routed_experts < NUM_LOCAL_EXPERTS).all()
assert num_tokens == len(prompt_token_ids) + len(choice["token_ids"]) - 1
@@ -112,6 +112,29 @@ async def test_generate_endpoint(client):
assert data["choices"][0].get("sampling_mask") is None
@pytest.mark.asyncio
async def test_generate_rejects_min_tokens_above_filled_max_tokens(client):
"""Explicit null max_tokens must not skip the min_tokens bound."""
payload = {
"model": MODEL_NAME,
"token_ids": [1, 2, 3],
"sampling_params": {"max_tokens": None, "min_tokens": 2147483648},
"stream": False,
}
resp = await client.post(GEN_ENDPOINT, json=payload)
assert resp.status_code == 400
assert "min_tokens" in resp.json()["error"]["message"]
followup = {
"model": MODEL_NAME,
"token_ids": [1, 2, 3],
"sampling_params": {"max_tokens": 4},
"stream": False,
}
resp = await client.post(GEN_ENDPOINT, json=followup)
resp.raise_for_status()
@pytest.mark.asyncio
@pytest.mark.skipif(
envs.VLLM_USE_RUST_FRONTEND,
@@ -56,9 +56,10 @@ class MockModelConfig:
encoder_config = None
generation_config: str = "auto"
media_io_kwargs: dict[str, dict[str, Any]] = field(default_factory=dict)
skip_tokenizer_init = False
skip_tokenizer_init: bool = False
is_encoder_decoder: bool = False
is_multimodal_model: bool = False
supports_multimodal_inputs: bool = False
renderer_num_workers: int = 1
def get_diff_sampling_param(self):
@@ -9,3 +9,5 @@ server_args: >-
--moe-backend humming
--linear-backend humming
--dtype bfloat16
env:
VLLM_HUMMING_MOE_GEMM_TYPE: "grouped_contiguous"
@@ -0,0 +1,14 @@
model_name: "nm-testing/Qwen3-30B-A3B-FP8-block"
accuracy_threshold: 0.86
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 8192
--moe-backend humming
--linear-backend humming
--data-parallel-size 2
--enable-expert-parallel
--all2all-backend deepep_high_throughput
env:
VLLM_HUMMING_MOE_GEMM_TYPE: "grouped_contiguous"
@@ -0,0 +1,14 @@
model_name: "nm-testing/Qwen3-30B-A3B-FP8-block"
accuracy_threshold: 0.86
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 8192
--moe-backend humming
--linear-backend humming
--data-parallel-size 2
--enable-expert-parallel
--all2all-backend deepep_high_throughput
env:
VLLM_HUMMING_MOE_GEMM_TYPE: "indexed"
@@ -7,3 +7,5 @@ server_args: >-
--max-model-len 8192
--quantization humming
--linear-backend humming
env:
VLLM_HUMMING_MOE_GEMM_TYPE: "grouped_contiguous"
@@ -7,3 +7,5 @@ server_args: >-
--max-model-len 8192
--moe-backend humming
--linear-backend humming
env:
VLLM_HUMMING_MOE_GEMM_TYPE: "grouped_contiguous"
@@ -1,13 +0,0 @@
model_name: "Qwen/Qwen3-30B-A3B"
accuracy_threshold: 0.80
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 8192
--tensor-parallel-size 1
--quantization humming
--kernel-config.enable_flashinfer_autotune=False
env:
VLLM_HUMMING_ONLINE_QUANT_CONFIG: '{"dtype":"int5","hadamard_block_size":-1}'
VLLM_HUMMING_INPUT_QUANT_CONFIG: '{"dtype":"float8e4m3"}'
@@ -1,7 +1,8 @@
model_name: "Qwen/Qwen3-30B-A3B"
accuracy_threshold: 0.80
model_name: "Qwen/Qwen3.5-35B-A3B"
accuracy_threshold: 0.90
num_questions: 1319
num_fewshot: 5
gen_prefix: " <think>\n\n</think>\n"
server_args: >-
--enforce-eager
--max-model-len 8192
@@ -9,5 +10,5 @@ server_args: >-
--quantization humming
--kernel-config.enable_flashinfer_autotune=False
env:
VLLM_HUMMING_ONLINE_QUANT_CONFIG: '{"dtype":"int5","hadamard_block_size":-1}'
VLLM_HUMMING_ONLINE_QUANT_CONFIG: '{"dtype":"int6","hadamard_block_size":-1}'
VLLM_HUMMING_INPUT_QUANT_CONFIG: '{"dtype":"int8"}'
@@ -1,7 +1,8 @@
model_name: "Qwen/Qwen3-30B-A3B"
accuracy_threshold: 0.80
model_name: "Qwen/Qwen3.5-35B-A3B"
accuracy_threshold: 0.90
num_questions: 1319
num_fewshot: 5
gen_prefix: " <think>\n\n</think>\n"
server_args: >-
--enforce-eager
--max-model-len 8192
@@ -9,4 +10,4 @@ server_args: >-
--quantization humming
--kernel-config.enable_flashinfer_autotune=False
env:
VLLM_HUMMING_ONLINE_QUANT_CONFIG: '{"dtype":"int5","hadamard_block_size":-1}'
VLLM_HUMMING_ONLINE_QUANT_CONFIG: '{"dtype":"int6","hadamard_block_size":-1}'
@@ -0,0 +1,13 @@
model_name: "Qwen/Qwen3.5-9B"
accuracy_threshold: 0.88
num_questions: 1319
num_fewshot: 5
gen_prefix: " <think>\n\n</think>\n"
server_args: >-
--enforce-eager
--max-model-len 8192
--quantization humming
--kernel-config.enable_flashinfer_autotune=False
env:
VLLM_HUMMING_ONLINE_QUANT_CONFIG: '{"dtype":"int6","hadamard_block_size":-1}'
VLLM_HUMMING_INPUT_QUANT_CONFIG: '{"dtype":"int8"}'
@@ -0,0 +1,12 @@
model_name: "Qwen/Qwen3.5-9B"
accuracy_threshold: 0.88
num_questions: 1319
num_fewshot: 5
gen_prefix: " <think>\n\n</think>\n"
server_args: >-
--enforce-eager
--max-model-len 8192
--quantization humming
--kernel-config.enable_flashinfer_autotune=False
env:
VLLM_HUMMING_ONLINE_QUANT_CONFIG: '{"dtype":"int6","hadamard_block_size":-1}'
@@ -0,0 +1,3 @@
gpt-oss-20b-humming.yaml
Qwen3.5-35B-A3B-experts-int8-humming-act-int8.yaml
Qwen3.5-35B-A3B-int6wc-hadamard-humming-act-int8.yaml
@@ -0,0 +1,4 @@
Qwen3-30B-A3B-Instruct-2507-quantized.w8a8-humming-act-int8.yaml
Qwen3-30B-A3B-GPTQ-Int4-humming-act-int8.yaml
Qwen3-30B-A3B-AWQ-humming.yaml
Qwen3-4B-mixed-quant-RTN-humming.yaml
@@ -1,4 +1,5 @@
Qwen3.5-35B-A3B-experts-int8-humming.yaml
Qwen3.5-35B-A3B-int6wc-hadamard-humming.yaml
gpt-oss-20b-humming.yaml
Qwen3-30B-A3B-GPTQ-Int4-humming.yaml
Qwen3-30B-A3B-FP8-block-humming.yaml
@@ -3,4 +3,5 @@ Qwen3-30B-A3B-Instruct-2507-quantized.w8a8-humming-act-int8.yaml
Qwen3-30B-A3B-GPTQ-Int4-humming-act-int8.yaml
Qwen3-30B-A3B-AWQ-humming.yaml
Qwen3.5-35B-A3B-experts-int8-humming-act-int8.yaml
Qwen3.5-35B-A3B-int6wc-hadamard-humming-act-int8.yaml
Qwen3-4B-mixed-quant-RTN-humming.yaml
@@ -0,0 +1,2 @@
Qwen3-30B-A3B-FP8-block-humming-deepep-ht-grouped.yaml
Qwen3-30B-A3B-FP8-block-humming-deepep-ht-indexed.yaml
@@ -1,4 +1,5 @@
Qwen3.5-35B-A3B-experts-int8-humming.yaml
Qwen3.5-35B-A3B-int6wc-hadamard-humming.yaml
Qwen3-30B-A3B-Instruct-2507-quantized.w8a8-humming.yaml
Qwen3-30B-A3B-Fp8-v1-humming.yaml
Qwen3-30B-A3B-NVFP4-humming.yaml
@@ -1,3 +0,0 @@
Qwen3-30B-A3B-int5wc-hadamard-humming.yaml
Qwen3-30B-A3B-int5wc-hadamard-humming-act-fp8.yaml
Qwen3-30B-A3B-int5wc-hadamard-humming-act-int8.yaml
@@ -0,0 +1,9 @@
Qwen2-1.5B-Instruct-FP8W8-humming.yaml
Qwen2-1.5B-Instruct-FP8W8-humming-act-fp8.yaml
Qwen3-0.6B-MXFP8-humming.yaml
Qwen3-0.6B-MXFP8-humming-act-fp8.yaml
Qwen3-30B-A3B-AWQ-humming.yaml
Qwen3-30B-A3B-GPTQ-Int4-humming-act-fp8.yaml
gpt-oss-20b-humming.yaml
Qwen3.5-9B-int6wc-hadamard-humming.yaml
Qwen3.5-9B-int6wc-hadamard-humming-act-int8.yaml
@@ -0,0 +1 @@
DeepSeek-R1-DP.yaml
@@ -0,0 +1 @@
DeepSeek-R1-TP.yaml
@@ -0,0 +1 @@
DeepSeek-V3.2-DP.yaml
@@ -0,0 +1 @@
DeepSeek-V3.2-TP.yaml
@@ -0,0 +1,2 @@
Nemotron-3-Super-120B-A12B-BF16.yaml
Nemotron-3-Super-120B-A12B-FP8.yaml
@@ -1,6 +0,0 @@
DeepSeek-R1-TP.yaml
DeepSeek-R1-DP.yaml
DeepSeek-V3.2-TP.yaml
DeepSeek-V3.2-DP.yaml
Nemotron-3-Super-120B-A12B-BF16.yaml
Nemotron-3-Super-120B-A12B-FP8.yaml
@@ -0,0 +1,5 @@
model_name: "Qwen/Qwen3-30B-A3B"
accuracy_threshold: 0.88
num_questions: 1319
num_fewshot: 5
server_args: "--enforce-eager --max-model-len 8192 --tensor-parallel-size 2 --moe-backend=triton"
@@ -0,0 +1 @@
Qwen3-30B-A3B-BF16-triton-rocm.yaml
@@ -0,0 +1 @@
Qwen3-30B-A3B-Fp8-AutoFp8-triton.yaml
@@ -0,0 +1 @@
Qwen3-30B-A3B-Fp8-CT-Block-triton.yaml
@@ -0,0 +1 @@
Mixtral-8x7B-Fp8-AutoFp8-triton.yaml
@@ -0,0 +1,26 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
model_name: "Qwen/Qwen3.8-Flash-Next-FP8"
datasets:
gsm8k:
metric_threshold: 0.98
tolerance: 0.02
aime25:
metric_threshold: 0.90
tolerance: 0.05
eval_batch_size: 32
startup_max_wait_seconds: 1800
generation_config:
seed: 1236
do_sample: true
temperature: 0.7
top_p: 0.8
top_k: 20
repetition_penalty: 1.0
presence_penalty: 1.5
max_tokens: 32768
stream: true
extra_body:
chat_template_kwargs:
enable_thinking: true
server_args: "--tensor-parallel-size 4 --mamba-cache-mode align"
@@ -0,0 +1 @@
Qwen3.8-Flash-Next-FP8-rocm.yaml
@@ -130,69 +130,123 @@ def test_flashinfer_mla_decode(dtype: torch.dtype, bs: int, block_size: int):
torch.testing.assert_close(out_ans, out_ref, atol=1e-2, rtol=1e-2)
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float8_e4m3fn])
@pytest.mark.parametrize("mode", ["tp", "dcp", "hisparse"])
@requires_sm10x
def test_flashinfer_trtllm_sparse_mla_decode_without_rope():
"""The native sparse MLA path supports a zero-width rotary tail."""
def test_flashinfer_trtllm_sparse_mla_decode_without_rope(dtype, mode, monkeypatch):
"""TP skips preparation; empty DCP contributions and HiSparse outputs vanish."""
import vllm.v1.attention.backends.mla.flashinfer_mla_sparse as backend
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
torch.set_default_device("cuda")
torch.manual_seed(42)
batch_size = 2
block_size = 64
num_blocks = 4
sparse_topk = 128
valid_lens = torch.tensor([17, 73], dtype=torch.int32)
query = torch.randn(
batch_size,
1,
NUM_HEADS,
KV_LORA_RANK,
dtype=torch.bfloat16,
)
kv_cache = torch.randn(
num_blocks,
block_size,
KV_LORA_RANK,
dtype=torch.bfloat16,
)
batch_size, num_heads, block_size, num_blocks, sparse_topk = 3, 8, 64, 4, 2176
valid_lens = [1 if mode == "tp" else 0, 17, 73]
counts = torch.tensor(valid_lens, dtype=torch.int32)
query = torch.randn(batch_size, 1, num_heads, KV_LORA_RANK).to(dtype)
kv_cache = torch.randn(num_blocks, block_size, KV_LORA_RANK).to(dtype)
num_slots = num_blocks * block_size
slot_tables = torch.stack(
[torch.randperm(num_slots)[:sparse_topk] for _ in range(batch_size)]
).to(torch.int32)
for row, valid_len in zip(slot_tables, valid_lens.tolist()):
row[valid_len:] = -1
indices = torch.full((batch_size, sparse_topk), -1, dtype=torch.int32)
for token, length in enumerate(valid_lens):
indices[token, :length] = torch.randperm(num_slots)[:length].int()
empty = counts == 0
reference_indices = indices.clone()
reference_indices[:, 0].masked_fill_(empty, 0)
workspace = torch.empty(FLASHINFER_WORKSPACE_BUFFER_SIZE, dtype=torch.int8)
workspace_buffer = torch.empty(
FLASHINFER_WORKSPACE_BUFFER_SIZE,
dtype=torch.int8,
impl = object.__new__(backend.FlashInferMLASparseImpl)
impl.qk_nope_head_dim = QK_NOPE_HEAD_DIM
impl.kv_lora_rank = KV_LORA_RANK
impl.qk_rope_head_dim = 0
impl.index_group = (
object.__new__(HiSparseMLAIndexGroup) if mode == "hisparse" else None
)
out = trtllm_batch_decode_with_kv_cache_mla(
impl._workspace_buffer = workspace
impl.bmm1_scale = QK_NOPE_HEAD_DIM**-0.5
impl.bmm2_scale = 1.0
impl.is_nope_mla = True
impl.need_to_return_lse_for_decode = mode == "dcp"
if mode == "tp":
def unexpected_helper(*args, **kwargs):
pytest.fail("TP must not launch empty-query preparation")
monkeypatch.setattr(
backend, "prepare_sparse_mla_safe_lengths", unexpected_helper
)
out, lse = impl._run_mqa_kernel(query.squeeze(1), kv_cache, indices, counts)
reference = trtllm_batch_decode_with_kv_cache_mla(
query=query,
kv_cache=kv_cache.unsqueeze(1),
workspace_buffer=workspace_buffer,
workspace_buffer=workspace,
qk_nope_head_dim=QK_NOPE_HEAD_DIM,
kv_lora_rank=KV_LORA_RANK,
qk_rope_head_dim=0,
block_tables=slot_tables.unsqueeze(1),
seq_lens=valid_lens,
block_tables=reference_indices.unsqueeze(1),
seq_lens=counts,
max_seq_len=sparse_topk,
sparse_mla_top_k=sparse_topk,
sparse_mla_top_k_lens=valid_lens,
sparse_mla_top_k_lens=counts.clamp(min=1),
bmm1_scale=QK_NOPE_HEAD_DIM**-0.5,
bmm2_scale=1.0,
).squeeze(1)
return_lse=mode == "dcp",
)
if mode == "dcp":
reference, reference_lse = reference
reference_lse = reference_lse.reshape(batch_size, num_heads)
reference_lse.masked_fill_(empty[:, None], float("-inf"))
torch.testing.assert_close(lse, reference_lse, atol=0, rtol=0)
flat_cache = kv_cache.view(num_slots, KV_LORA_RANK).float()
refs = []
for batch_idx, valid_len in enumerate(valid_lens.tolist()):
selected_kv = flat_cache[slot_tables[batch_idx, :valid_len].long()]
scores = torch.einsum("hd,kd->hk", query[batch_idx, 0].float(), selected_kv)
probs = torch.softmax(scores * QK_NOPE_HEAD_DIM**-0.5, dim=-1)
refs.append(torch.einsum("hk,kd->hd", probs, selected_kv))
ref = torch.stack(refs).to(torch.bfloat16)
from vllm.v1.attention.ops.dcp import CPTritonContext, correct_attn_out
torch.testing.assert_close(out, ref, atol=2e-2, rtol=2e-2)
# The peer owns only our empty selections. Check our contribution after
# the production merge, without zeroing the local attention output.
peer_lse = torch.full_like(lse, float("-inf")).masked_fill(empty[:, None], 0)
out, _ = correct_attn_out(
out, torch.stack((lse, peer_lse)), cp_rank=0, ctx=CPTritonContext()
)
else:
assert lse is None
reference = reference.squeeze(1).masked_fill(empty[:, None, None], 0)
torch.testing.assert_close(out, reference, atol=0, rtol=0)
if dtype == torch.bfloat16:
flat_cache = kv_cache.view(num_slots, KV_LORA_RANK).float()
refs = []
for token, length in enumerate(valid_lens):
selected_kv = flat_cache[reference_indices[token, :length].long()]
scores = torch.einsum("hd,kd->hk", query[token, 0].float(), selected_kv)
probs = torch.softmax(scores * QK_NOPE_HEAD_DIM**-0.5, dim=-1)
refs.append(torch.einsum("hk,kd->hd", probs, selected_kv))
ref = torch.stack(refs).to(torch.bfloat16)
torch.testing.assert_close(out, ref, atol=2e-2, rtol=2e-2)
@requires_sm10x
def test_sparse_mla_safe_lengths():
from vllm.v1.attention.backends.mla.sparse_utils import (
prepare_sparse_mla_safe_lengths,
)
device = "cuda"
num_tokens = 259
# Include a partial tile and expose accidental writes into adjacent storage.
counts_storage = torch.full((num_tokens, 2), 17, dtype=torch.int32, device=device)
counts = counts_storage[:, 0]
counts[::3] = 0
original_counts = counts_storage.clone()
empty = counts == 0
indices_storage = torch.full(
(num_tokens, 256), 42, dtype=torch.int32, device=device
)
indices = indices_storage[:, ::2]
expected_indices = indices_storage.clone()
expected_indices[:, 0].masked_fill_(empty, 0)
safe = prepare_sparse_mla_safe_lengths(indices, counts)
torch.testing.assert_close(safe, counts.clamp(min=1), rtol=0, atol=0)
torch.testing.assert_close(indices_storage, expected_indices, rtol=0, atol=0)
torch.testing.assert_close(counts_storage, original_counts, rtol=0, atol=0)
@requires_sm90
+361 -10
View File
@@ -19,7 +19,10 @@ from vllm.models.minimax_m3.common.ops.sparse_attn import (
minimax_m3_sparse_attn,
minimax_m3_sparse_attn_decode,
)
from vllm.models.minimax_m3.common.sparse_attention import MiniMaxM3SparseTritonImpl
from vllm.models.minimax_m3.common.sparse_attention import (
MiniMaxM3SparseTritonImpl,
minimax_m3_rebase_slots_to_page16,
)
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.attention.backends.utils import record_kv_cache_layout
@@ -28,6 +31,7 @@ from vllm.v1.kv_cache_interface import (
KVCacheLayout,
MLAAttentionSpec,
compute_layer_kv_cache_shape_bytes,
get_kv_quant_mode,
)
if not (current_platform.is_cuda() or current_platform.is_rocm()):
@@ -1672,8 +1676,9 @@ def test_main_cache_layout_contract():
assert set(order) == set(range(len(order)))
def test_aiter_sparse_pa_layout_contract(monkeypatch):
"""The shuffle-only AITER path retains separately contiguous K/V storage."""
@pytest.mark.parametrize("layout", [KVCacheLayout.LHBNC, KVCacheLayout.LBHNC])
def test_aiter_sparse_pa_layout_contract(monkeypatch, layout):
"""Build the exact separate and packed page-16 views used by the model."""
import vllm.models.minimax_m3.common.sparse_attention as sparse_attn_mod
monkeypatch.setattr(sparse_attn_mod.rocm_aiter_ops, "is_enabled", lambda: True)
@@ -1685,21 +1690,43 @@ def test_aiter_sparse_pa_layout_contract(monkeypatch):
backend = sparse_attn_mod.MiniMaxM3SparseBackend
assert KVCacheLayout.LHBNC in backend.supported_kv_cache_layouts()
assert KVCacheLayout.LBHNC in backend.supported_kv_cache_layouts()
nb, h = 7, 1
nb, h = 3, 1
cache_dtype = current_platform.fp8_dtype()
spec = FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=h,
head_size=HEAD_DIM,
dtype=DTYPE,
dtype=cache_dtype,
kv_quant_mode=get_kv_quant_mode("fp8"),
num_head_slots=2,
state_content_bytes=h * HEAD_DIM * DTYPE.itemsize,
state_content_bytes=h * HEAD_DIM * cache_dtype.itemsize,
)
raw = torch.zeros(nb * spec.page_size_bytes, dtype=torch.int8)
view = dense_kv_cache_views(raw, spec, nb, 1, KVCacheLayout.LHBNC)[0]
key_cache, value_cache = view.unbind(1)
assert key_cache.is_contiguous()
assert value_cache.is_contiguous()
kv_cache = dense_kv_cache_views(raw, spec, nb, 1, layout)[0].view(cache_dtype)
key_cache, value_cache = kv_cache.unbind(1)
x = 16 // cache_dtype.itemsize
pages_per_side = BLOCK_SIZE // 16
if key_cache.is_contiguous() and value_cache.is_contiguous():
k_src, v_src = key_cache, value_cache
block_pages, v_page_offset = pages_per_side, 0
else:
assert kv_cache.is_contiguous()
k_src = v_src = kv_cache
block_pages, v_page_offset = 2 * pages_per_side, pages_per_side
num_phys16 = nb * block_pages
k_view = k_src.view(num_phys16, h, HEAD_DIM // x, 16, x)
v_view = v_src.view(num_phys16, h, 16 // x, HEAD_DIM, x)[v_page_offset:]
assert k_view.is_contiguous()
assert v_view.is_contiguous()
if layout is KVCacheLayout.LHBNC:
assert k_view.shape == (24, 1, 8, 16, 16)
assert v_view.shape == (24, 1, 1, 128, 16)
else:
assert k_view.shape == (48, 1, 8, 16, 16)
assert v_view.shape == (40, 1, 1, 128, 16)
def test_aiter_sparse_pa_rejects_multiple_kv_heads(monkeypatch):
@@ -1769,6 +1796,330 @@ def test_aiter_indexer_requires_the_aiter_attend(monkeypatch):
assert reason is None or "AITER sparse PA attend" not in reason
def test_aiter_consolidated_qknorm_enabled(monkeypatch):
from vllm._aiter_ops import rocm_aiter_ops
monkeypatch.setattr("vllm._aiter_ops.is_aiter_found_and_supported", lambda: True)
monkeypatch.setattr(rocm_aiter_ops, "_AITER_ENABLED", True)
scale = torch.tensor([0.25])
assert rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("auto")
assert rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("fp8", scale, scale)
assert rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("fp8_e4m3", scale, scale)
assert not rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("fp8")
assert not rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("fp8", scale, None)
assert not rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("fp8_e5m2", scale, scale)
monkeypatch.setattr(rocm_aiter_ops, "_AITER_ENABLED", False)
assert not rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("auto")
monkeypatch.setattr(rocm_aiter_ops, "_AITER_ENABLED", True)
monkeypatch.setattr("vllm._aiter_ops.is_aiter_found_and_supported", lambda: False)
assert not rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("auto")
def _fake_aiter_qknorm_args(kv_cache_dtype: str = "auto") -> dict:
tensor = torch.empty(1)
return {
"qkv": tensor,
"q_norm_weight": tensor,
"k_norm_weight": tensor,
"cos_sin_cache": tensor,
"positions": tensor,
"num_heads": 16,
"num_kv_heads": 1,
"rotary_dim": 64,
"eps": 1e-6,
"slot_mapping": tensor,
"kv_cache_k": tensor,
"kv_cache_v": tensor,
"q_out": tensor,
"kv_cache_dtype": kv_cache_dtype,
}
def _install_fake_aiter_qknorm(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
"""Stub ``aiter.fused_qknorm_idxrqknorm`` so mapping tests run without AITER."""
import sys
import types
from typing import Any
calls: list[dict] = []
def fake_op(*args, **kwargs):
calls.append(kwargs)
existing = sys.modules.get("aiter")
if existing is not None:
monkeypatch.setattr(existing, "fused_qknorm_idxrqknorm", fake_op, raising=False)
else:
fake_mod: Any = types.ModuleType("aiter")
fake_mod.fused_qknorm_idxrqknorm = fake_op
monkeypatch.setitem(sys.modules, "aiter", fake_mod)
return calls
def test_aiter_consolidated_qknorm_packed_shuffle_unequal_spans(monkeypatch):
from vllm._aiter_ops import rocm_aiter_ops
calls = _install_fake_aiter_qknorm(monkeypatch)
call_args = _fake_aiter_qknorm_args()
call_args["kv_cache_k"] = torch.empty(2, 1)
call_args["kv_cache_v"] = torch.empty(1, 1)
rocm_aiter_ops.fused_qknorm_idxrqknorm(**call_args)
assert len(calls) == 1
@pytest.mark.parametrize(
("kv_cache_dtype", "aiter_dtype", "passes_scales"),
[
("auto", "auto", False),
("fp8", "fp8_e4m3_static", True),
("fp8_e4m3", "fp8_e4m3_static", True),
],
)
def test_aiter_consolidated_qknorm_dtype_and_layout_mapping(
monkeypatch, kv_cache_dtype, aiter_dtype, passes_scales
):
from vllm._aiter_ops import rocm_aiter_ops
calls = _install_fake_aiter_qknorm(monkeypatch)
call_args = _fake_aiter_qknorm_args(kv_cache_dtype)
k_scale = torch.tensor([0.25])
v_scale = torch.tensor([0.5])
call_args.update(k_scale=k_scale, v_scale=v_scale)
rocm_aiter_ops.fused_qknorm_idxrqknorm(**call_args)
assert len(calls) == 1
kwargs = calls[0]
assert kwargs["kv_cache_dtype"] == aiter_dtype
assert kwargs["index_cache_dtype"] == "auto"
assert kwargs["block_size"] == 16
assert kwargs["asm_layout"] is True
if passes_scales:
assert kwargs["k_scale"] is k_scale
assert kwargs["v_scale"] is v_scale
else:
assert kwargs["k_scale"] is None
assert kwargs["v_scale"] is None
def test_aiter_consolidated_qknorm_fp8_index_dtype_mapping(monkeypatch):
from vllm._aiter_ops import rocm_aiter_ops
calls = _install_fake_aiter_qknorm(monkeypatch)
fp8 = current_platform.fp8_dtype()
call_args = _fake_aiter_qknorm_args("fp8")
call_args.update(
k_scale=torch.tensor([0.25]),
v_scale=torch.tensor([0.5]),
index_cache=torch.empty(1, dtype=fp8),
index_q_out=torch.empty(1, dtype=fp8),
num_index_heads=1,
)
rocm_aiter_ops.fused_qknorm_idxrqknorm(**call_args)
assert calls[0]["index_cache_dtype"] == "fp8"
assert calls[0]["kv_cache_dtype"] == "fp8_e4m3_static"
@pytest.mark.parametrize("skip_index_branch", [False, True])
def test_aiter_consolidated_qknorm_full_and_skip_index_args(
monkeypatch, skip_index_branch
):
from vllm._aiter_ops import rocm_aiter_ops
calls = _install_fake_aiter_qknorm(monkeypatch)
call_args = _fake_aiter_qknorm_args()
if skip_index_branch:
call_args.update(skip_index_branch=True)
else:
tensor = torch.empty(1)
call_args.update(
index_q_norm_weight=tensor,
index_k_norm_weight=tensor,
num_index_heads=1,
index_cache=tensor,
index_q_out=tensor,
index_slot_mapping=tensor,
)
rocm_aiter_ops.fused_qknorm_idxrqknorm(**call_args)
kwargs = calls[0]
assert kwargs["skip_index_branch"] is skip_index_branch
if skip_index_branch:
assert kwargs["index_q_norm_weight"] is None
assert kwargs["index_k_norm_weight"] is None
assert kwargs["index_cache"] is None
assert kwargs["index_q_out"] is None
assert kwargs["index_slot_mapping"] is None
else:
assert kwargs["index_q_norm_weight"] is not None
assert kwargs["index_k_norm_weight"] is not None
assert kwargs["index_cache"] is not None
assert kwargs["index_q_out"] is not None
assert kwargs["index_slot_mapping"] is not None
def test_aiter_consolidated_qknorm_rejects_fp8_e5m2(monkeypatch):
from vllm._aiter_ops import rocm_aiter_ops
monkeypatch.setattr("vllm._aiter_ops.is_aiter_found_and_supported", lambda: True)
monkeypatch.setattr(rocm_aiter_ops, "_AITER_ENABLED", True)
scale = torch.tensor([0.25])
assert not rocm_aiter_ops.fused_qknorm_idxrqknorm_enabled("fp8_e5m2", scale, scale)
def test_aiter_sparse_pa_slot_rebase_preserves_page_offsets():
slots = torch.tensor([0, 15, 16, 127, 128, 129, -1])
actual = minimax_m3_rebase_slots_to_page16(slots, block_size=128)
expected = torch.tensor([0, 15, 16, 127, 256, 257, -1])
assert torch.equal(actual, expected)
@pytest.mark.skipif(
not current_platform.is_rocm(),
reason="The consolidated packed-SHUFFLE AITER op is ROCm-only",
)
@pytest.mark.parametrize("skip_index_branch", [False, True])
@pytest.mark.parametrize("fp8_index", [False, True])
def test_aiter_consolidated_qknorm_real_packed_shuffle(skip_index_branch, fp8_index):
from vllm._aiter_ops import rocm_aiter_ops
torch.manual_seed(20260831)
num_tokens = 4
num_heads = 16
num_kv_heads = 1
num_index_heads = 1
rotary_dim = 64
head_dim = 128
logical_block_size = 128
num_blocks = 3
fp8_dtype = current_platform.fp8_dtype()
qkv = torch.randn(
num_tokens,
(num_heads + 2 * num_kv_heads + num_index_heads + 1) * head_dim,
dtype=torch.bfloat16,
device="cuda",
)
weights = [
torch.randn(head_dim, dtype=torch.bfloat16, device="cuda") for _ in range(4)
]
cos_sin_cache = torch.randn(16, rotary_dim, dtype=torch.bfloat16, device="cuda")
positions = torch.arange(num_tokens, dtype=torch.int64, device="cuda")
logical_slots = torch.tensor([0, 127, 128, -1], dtype=torch.int64, device="cuda")
slot_mapping = minimax_m3_rebase_slots_to_page16(logical_slots, logical_block_size)
index_slot_mapping = logical_slots.clone()
packed = torch.zeros(
num_blocks,
2,
logical_block_size,
head_dim,
dtype=fp8_dtype,
device="cuda",
)
x = 16 // packed.element_size()
pages_per_side = logical_block_size // 16
num_phys16 = num_blocks * 2 * pages_per_side
kv_cache_k = packed.view(num_phys16, num_kv_heads, head_dim // x, 16, x)
kv_cache_v = packed.view(num_phys16, num_kv_heads, 16 // x, head_dim, x)[
pages_per_side:
]
assert kv_cache_k.shape == (48, 1, 8, 16, 16)
assert kv_cache_v.shape == (40, 1, 1, 128, 16)
q_out = torch.zeros(
num_tokens, num_heads * head_dim, dtype=torch.bfloat16, device="cuda"
)
index_dtype = fp8_dtype if fp8_index else torch.bfloat16
if fp8_index:
index_q_out = torch.empty(
(num_tokens, num_index_heads * head_dim),
dtype=index_dtype,
device="cuda",
)
index_cache = torch.empty(
(num_blocks, logical_block_size, head_dim),
dtype=index_dtype,
device="cuda",
)
index_q_out.view(torch.uint8).fill_(7)
index_cache.view(torch.uint8).fill_(7)
else:
index_q_out = torch.full(
(num_tokens, num_index_heads * head_dim),
7,
dtype=torch.bfloat16,
device="cuda",
)
index_cache = torch.full(
(num_blocks, logical_block_size, head_dim),
7,
dtype=torch.bfloat16,
device="cuda",
)
scale = torch.tensor([0.02], dtype=torch.float32, device="cuda")
kwargs = {}
if not skip_index_branch:
kwargs = {
"index_q_norm_weight": weights[2],
"index_k_norm_weight": weights[3],
"index_cache": index_cache,
"index_q_out": index_q_out,
"index_slot_mapping": index_slot_mapping,
}
rocm_aiter_ops.fused_qknorm_idxrqknorm(
qkv,
weights[0],
weights[1],
cos_sin_cache,
positions,
num_heads,
num_kv_heads,
rotary_dim,
1e-6,
slot_mapping,
kv_cache_k,
kv_cache_v,
q_out,
"fp8",
scale,
scale,
num_index_heads=num_index_heads,
skip_index_branch=skip_index_branch,
**kwargs,
)
torch.accelerator.synchronize()
assert torch.isfinite(q_out).all()
assert torch.count_nonzero(q_out) > 0
assert torch.count_nonzero(packed) > 0
if fp8_index:
index_q_untouched = torch.all(index_q_out.view(torch.uint8) == 7)
index_cache_untouched = torch.all(index_cache.view(torch.uint8) == 7)
index_cache_t0 = torch.all(index_cache[0, 0].view(torch.uint8) == 7)
index_cache_t127 = torch.all(index_cache[0, 127].view(torch.uint8) == 7)
index_cache_t128 = torch.all(index_cache[1, 0].view(torch.uint8) == 7)
else:
index_q_untouched = torch.all(index_q_out == 7)
index_cache_untouched = torch.all(index_cache == 7)
index_cache_t0 = torch.all(index_cache[0, 0] == 7)
index_cache_t127 = torch.all(index_cache[0, 127] == 7)
index_cache_t128 = torch.all(index_cache[1, 0] == 7)
if skip_index_branch:
assert index_q_untouched
assert index_cache_untouched
else:
assert not index_q_untouched
assert not index_cache_t0
assert not index_cache_t127
assert not index_cache_t128
def test_indexer_cache_squeezes_to_contiguous_3d():
"""The indexer side cache is standardized 4D with H=1: under both layouts
the allocator's logical view stays contiguous and squeezes (as
@@ -188,6 +188,7 @@ def _ref_sparse_decode_ragged(
extra_rows: list[list[int]] | None = None,
main_use_fnuz: bool = False,
extra_use_fnuz: bool = False,
extra_block_size: int | None = None,
) -> torch.Tensor:
q_f32 = q.float()
out = torch.empty_like(q_f32)
@@ -209,7 +210,10 @@ def _ref_sparse_decode_ragged(
)
row_kv.append(
_read_fp8_ds_mla_cache_rows(
extra_cache, extra_slots, block_size, extra_use_fnuz
extra_cache,
extra_slots,
extra_block_size or block_size,
extra_use_fnuz,
)
)
@@ -244,6 +248,12 @@ def _ragged_from_rows(
)
def _rows_from_ragged(indices: torch.Tensor, indptr: torch.Tensor) -> list[list[int]]:
ends = indptr.cpu().tolist()
values = indices[: ends[-1]].cpu().tolist()
return [values[start:end] for start, end in zip(ends, ends[1:])]
def _launch_sparse_decode_reduce(
part_m: torch.Tensor,
part_l: torch.Tensor,
@@ -1192,6 +1202,254 @@ def test_sparse_attn_decode_gfx950_graph_replay(monkeypatch) -> None:
torch.testing.assert_close(out, expected_long, atol=2e-2, rtol=2e-2)
@requires_gfx950
@torch.inference_mode()
def test_dsv4_adaptive_mla_swa_metadata_graph_replay(monkeypatch) -> None:
"""Replay the production ROCm decode path after device-only reallocation."""
from tests.v1.attention.utils import create_vllm_config
from vllm.models.deepseek_v4.amd.rocm import (
DeepseekV4ROCMAiterMLASparseMetadataBuilder,
DeepseekV4ROCMAiterSparseSWAMetadataBuilder,
)
from vllm.v1.attention.backend import AttentionCGSupport, CommonAttentionMetadata
from vllm.v1.attention.ops import rocm_aiter_mla_sparse as mod
from vllm.v1.kv_cache_interface import MLAAttentionSpec, SlidingWindowMLASpec
device = torch.device("cuda")
num_reqs = 3
upper_query_len = 8
graph_tokens = num_reqs * upper_query_len
block_size = 256
compressed_block_size = block_size // 128
window_size = 32
vllm_config = create_vllm_config(
model_name="facebook/opt-125m",
max_model_len=1024,
block_size=block_size,
max_num_seqs=num_reqs,
max_num_batched_tokens=graph_tokens,
hf_config_override={
"compress_ratios": [128],
"index_topk": 2048,
"sliding_window": window_size,
},
)
vllm_config.speculative_config = SimpleNamespace(
num_speculative_tokens=upper_query_len - 1,
parallel_drafting=False,
enable_adaptive_verification=True,
use_dspark=lambda: True,
)
mla_spec = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=HEAD_DIM,
dtype=torch.bfloat16,
tokens_per_state=128,
cache_dtype_str="fp8_ds_mla",
model_version="deepseek_v4",
)
swa_spec = SlidingWindowMLASpec(
block_size=block_size,
num_kv_heads=1,
head_size=HEAD_DIM,
dtype=torch.bfloat16,
sliding_window=window_size,
cache_dtype_str="fp8_ds_mla",
model_version="deepseek_v4",
)
mla_builder = DeepseekV4ROCMAiterMLASparseMetadataBuilder(
mla_spec, ["c128a"], vllm_config, device
)
swa_builder = DeepseekV4ROCMAiterSparseSWAMetadataBuilder(
swa_spec, ["c128a"], vllm_config, device
)
assert (
mla_builder.get_cudagraph_support(vllm_config, mla_spec)
== AttentionCGSupport.ALWAYS
)
assert (
swa_builder.get_cudagraph_support(vllm_config, swa_spec)
== AttentionCGSupport.ALWAYS
)
seq_lens = torch.tensor([520, 528, 536], dtype=torch.int32, device=device)
seq_lens_cpu = seq_lens.cpu()
cpu_query_start_loc = torch.arange(
0,
graph_tokens + 1,
upper_query_len,
dtype=torch.int32,
)
max_blocks = (int(seq_lens_cpu.max()) + block_size - 1) // block_size
block_table = torch.arange(
num_reqs * max_blocks, dtype=torch.int32, device=device
).view(num_reqs, max_blocks)
def build_metadata(query_lens: list[int]):
query_lens_tensor = torch.tensor(query_lens, dtype=torch.int32, device=device)
query_start_loc = torch.cat(
[
torch.zeros(1, dtype=torch.int32, device=device),
query_lens_tensor.cumsum(0),
]
)
active_tokens = sum(query_lens)
positions = torch.zeros(graph_tokens, dtype=torch.int64, device=device)
position_rows = [
torch.arange(
seq_len - query_len,
seq_len,
dtype=torch.int64,
device=device,
)
for seq_len, query_len in zip(seq_lens_cpu.tolist(), query_lens)
]
positions[:active_tokens] = torch.cat(position_rows)
slot_mapping = torch.full((graph_tokens,), -1, dtype=torch.int64, device=device)
slot_mapping[:active_tokens] = torch.arange(
active_tokens, dtype=torch.int64, device=device
)
common = CommonAttentionMetadata(
query_start_loc=query_start_loc,
query_start_loc_cpu=cpu_query_start_loc,
seq_lens=seq_lens,
seq_lens_cpu_upper_bound=seq_lens_cpu,
num_reqs=num_reqs,
num_actual_tokens=graph_tokens,
max_query_len=upper_query_len,
max_seq_len=int(seq_lens_cpu.max()),
block_table_tensor=block_table,
slot_mapping=slot_mapping,
positions=positions,
causal=True,
)
return (
mla_builder.build_for_cudagraph_capture(common),
swa_builder.build_for_cudagraph_capture(common),
)
mla_metadata, swa_metadata = build_metadata([8, 8, 8])
assert mla_metadata.for_cudagraph_capture
metadata_ptrs = (
mla_metadata.c128a_decode_topk_ragged_indices.data_ptr(),
mla_metadata.c128a_decode_topk_ragged_indptr.data_ptr(),
swa_metadata.decode_swa_ragged_indices.data_ptr(),
swa_metadata.decode_swa_ragged_indptr.data_ptr(),
)
torch.manual_seed(19)
num_heads = 16
q = (
torch.randn(
graph_tokens,
num_heads,
HEAD_DIM,
dtype=torch.bfloat16,
device=device,
)
* 0.125
)
num_cache_blocks = num_reqs * max_blocks
swa_cache = _pack_fp8_ds_mla_cache(
torch.randn(
num_cache_blocks * block_size,
HEAD_DIM,
dtype=torch.bfloat16,
device=device,
)
* 0.125,
block_size,
use_fnuz=False,
)
compressed_cache = _pack_fp8_ds_mla_cache(
torch.randn(
num_cache_blocks * compressed_block_size,
HEAD_DIM,
dtype=torch.bfloat16,
device=device,
)
* 0.125,
compressed_block_size,
use_fnuz=False,
)
attn_sink = torch.linspace(-0.1, 0.1, num_heads, dtype=torch.float32, device=device)
out = torch.empty_like(q)
monkeypatch.setattr(mod, "_decode_gfx950_num_splits", lambda *args: 1)
def run_decode(mla_md, swa_md) -> None:
mod.rocm_sparse_attn_decode(
q=q,
kv_cache=compressed_cache,
swa_k_cache=swa_cache,
swa_only=False,
topk_indices=mla_md.c128a_global_decode_topk_indices,
topk_lens=mla_md.c128a_decode_topk_lens,
swa_indices=swa_md.decode_swa_indices,
swa_lens=swa_md.decode_swa_lens,
swa_ragged_indices=swa_md.decode_swa_ragged_indices,
swa_ragged_indptr=swa_md.decode_swa_ragged_indptr,
topk_ragged_indices=mla_md.c128a_decode_topk_ragged_indices,
topk_ragged_indptr=mla_md.c128a_decode_topk_ragged_indptr,
attn_sink=attn_sink,
scale=HEAD_DIM**-0.5,
head_dim=HEAD_DIM,
nope_head_dim=NOPE_HEAD_DIM,
rope_head_dim=ROPE_HEAD_DIM,
output=out,
extra_cache_nan_free=True,
adaptive_splits=True,
)
def reference(mla_md, swa_md) -> torch.Tensor:
return _ref_sparse_decode_ragged(
q=q,
main_cache=swa_cache,
main_rows=_rows_from_ragged(
swa_md.decode_swa_ragged_indices,
swa_md.decode_swa_ragged_indptr,
),
scale=HEAD_DIM**-0.5,
attn_sink=attn_sink,
block_size=block_size,
extra_cache=compressed_cache,
extra_rows=_rows_from_ragged(
mla_md.c128a_decode_topk_ragged_indices,
mla_md.c128a_decode_topk_ragged_indptr,
),
extra_block_size=compressed_block_size,
)
run_decode(mla_metadata, swa_metadata)
torch.accelerator.synchronize()
expected_full = reference(mla_metadata, swa_metadata)
torch.testing.assert_close(out, expected_full, atol=2e-2, rtol=2e-2)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
run_decode(mla_metadata, swa_metadata)
torch.accelerator.synchronize()
captured_full = out.clone()
reallocated_mla, reallocated_swa = build_metadata([3, 8, 5])
assert metadata_ptrs == (
reallocated_mla.c128a_decode_topk_ragged_indices.data_ptr(),
reallocated_mla.c128a_decode_topk_ragged_indptr.data_ptr(),
reallocated_swa.decode_swa_ragged_indices.data_ptr(),
reallocated_swa.decode_swa_ragged_indptr.data_ptr(),
)
expected_reallocated = reference(reallocated_mla, reallocated_swa)
run_decode(reallocated_mla, reallocated_swa)
torch.accelerator.synchronize()
torch.testing.assert_close(out, expected_reallocated, atol=2e-2, rtol=2e-2)
assert not torch.equal(captured_full, expected_reallocated)
graph.replay()
torch.accelerator.synchronize()
torch.testing.assert_close(out, expected_reallocated, atol=2e-2, rtol=2e-2)
# ---------------------------------------------------------------------------
# o-projection: fused inverse-RoPE + cached bf16 wo_a (rocm_inv_rope_einsum)
# ---------------------------------------------------------------------------
@@ -135,6 +135,7 @@ def ref_paged_attn(
num_seqs = len(query_lens)
block_tables = block_tables.cpu().numpy()
_, block_size, num_kv_heads, head_size = key_cache.shape
head_size_v = value_cache.shape[-1]
outputs: list[torch.Tensor] = []
start_idx = 0
@@ -149,7 +150,7 @@ def ref_paged_attn(
k = key_cache[block_indices].view(-1, num_kv_heads, head_size)
k = k[:kv_len]
v = value_cache[block_indices].view(-1, num_kv_heads, head_size)
v = value_cache[block_indices].view(-1, num_kv_heads, head_size_v)
v = v[:kv_len]
if q.shape[1] != k.shape[1]:
@@ -5,6 +5,7 @@
import pytest
import torch
from tests.kernels.attention.test_triton_unified_attention import ref_paged_attn
from vllm.platforms import current_platform
from vllm.utils.math_utils import next_power_of_2
from vllm.utils.torch_utils import (
@@ -81,7 +82,7 @@ def _alloc_segm_buffers(seq_threshold_3D: int, num_query_heads: int, head_size_v
@pytest.mark.parametrize("dtype", DTYPES)
@pytest.mark.parametrize("seq_threshold_3D", SEQ_THRESHOLD_3D_VALUES)
@torch.inference_mode()
def test_triton_unified_attn_diffkv_vs_fa(
def test_triton_unified_attn_diffkv_vs_reference(
seq_lens: list[tuple[int, int]],
num_heads: tuple[int, int],
head_sizes: tuple[int, int],
@@ -93,12 +94,13 @@ def test_triton_unified_attn_diffkv_vs_fa(
) -> None:
head_size_qk, head_size_v = head_sizes
# DiffKV requires FA3 (Hopper) / FA4 (Blackwell) as the reference.
fa_version = get_flash_attn_version(head_size=head_size_qk, head_size_v=head_size_v)
if not is_flash_attn_varlen_func_available() or fa_version not in (3, 4):
pytest.skip(f"FA DiffKV needs FA3/FA4 (got version {fa_version}).")
from vllm.v1.attention.backends.fa_utils import flash_attn_varlen_func
# Keep the FA3/FA4 comparison on NVIDIA; ROCm uses the PyTorch oracle.
if not current_platform.is_rocm():
fa_version = get_flash_attn_version(
head_size=head_size_qk, head_size_v=head_size_v
)
if not is_flash_attn_varlen_func_available() or fa_version not in (3, 4):
pytest.skip(f"FA DiffKV needs FA3/FA4 (got version {fa_version}).")
torch.set_default_device(DEVICE_TYPE)
set_random_seed(0)
@@ -135,28 +137,44 @@ def test_triton_unified_attn_diffkv_vs_fa(
0, NUM_BLOCKS, (num_seqs, max_num_blocks_per_seq), dtype=torch.int32
)
# ---- FlashAttention DiffKV (ground truth) ---------------------------
# Mirror the backend: fix degenerate strides on size-1 dims so FA's
# TMA path sees ≥16-byte-aligned strides (matters for num_kv_heads==1).
fa_k = canonicalize_singleton_dim_strides(key_cache)
fa_v = canonicalize_singleton_dim_strides(value_cache)
fa_out = torch.empty(sum(query_lens), num_query_heads, head_size_v, dtype=dtype)
flash_attn_varlen_func(
q=query,
k=fa_k,
v=fa_v,
out=fa_out,
cu_seqlens_q=cu_query_lens,
max_seqlen_q=max_query_len,
seqused_k=kv_lens_t,
max_seqlen_k=max_kv_len,
softmax_scale=scale,
causal=True,
window_size=list(window_size),
block_table=block_tables,
softcap=soft_cap if soft_cap is not None else 0,
fa_version=fa_version,
)
if current_platform.is_rocm():
# FP32 also keeps the helper's in-place scaling off the kernel input.
ref_out = ref_paged_attn(
query.float(),
key_cache.float(),
value_cache.float(),
query_lens,
kv_lens,
block_tables,
scale,
sliding_window=sliding_window,
soft_cap=soft_cap,
).to(dtype)
else:
from vllm.v1.attention.backends.fa_utils import flash_attn_varlen_func
# FA's TMA path needs aligned singleton strides (num_kv_heads == 1).
fa_k = canonicalize_singleton_dim_strides(key_cache)
fa_v = canonicalize_singleton_dim_strides(value_cache)
ref_out = torch.empty(
sum(query_lens), num_query_heads, head_size_v, dtype=dtype
)
flash_attn_varlen_func(
q=query,
k=fa_k,
v=fa_v,
out=ref_out,
cu_seqlens_q=cu_query_lens,
max_seqlen_q=max_query_len,
seqused_k=kv_lens_t,
max_seqlen_k=max_kv_len,
softmax_scale=scale,
causal=True,
window_size=list(window_size),
block_table=block_tables,
softcap=soft_cap if soft_cap is not None else 0,
fa_version=fa_version,
)
# ---- Triton DiffKV --------------------------------------------------
segm_output, segm_max, segm_expsum = _alloc_segm_buffers(
@@ -183,7 +201,4 @@ def test_triton_unified_attn_diffkv_vs_fa(
softmax_segm_expsum=segm_expsum,
)
(
torch.testing.assert_close(triton_out, fa_out, atol=2e-2, rtol=2e-2),
f"triton vs FA max abs diff: {torch.max(torch.abs(triton_out - fa_out))}",
)
torch.testing.assert_close(triton_out, ref_out, atol=2e-2, rtol=2e-2)
+109 -42
View File
@@ -352,49 +352,46 @@ def test_masked_situ_and_mul(
)
@pytest.mark.parametrize(
("activation", "activation_config"),
[
(MoEActivation.SILU, ApplyMoEActivationConfig()),
(
MoEActivation.SILU,
ApplyMoEActivationConfig(clamp_limit=3.0),
MOE_ACTIVATION_CASES = [
pytest.param(MoEActivation.SILU, ApplyMoEActivationConfig(), id="silu"),
pytest.param(
MoEActivation.SILU, ApplyMoEActivationConfig(clamp_limit=3.0), id="silu_clamp"
),
pytest.param(MoEActivation.GELU, ApplyMoEActivationConfig(), id="gelu"),
pytest.param(MoEActivation.GELU_TANH, ApplyMoEActivationConfig(), id="gelu_tanh"),
pytest.param(
MoEActivation.SITU,
ApplyMoEActivationConfig(
activation_situ_beta=1.5,
activation_situ_linear_beta=2.0,
),
(MoEActivation.GELU, ApplyMoEActivationConfig()),
(MoEActivation.GELU_TANH, ApplyMoEActivationConfig()),
(
MoEActivation.SITU,
ApplyMoEActivationConfig(
activation_situ_beta=1.5,
activation_situ_linear_beta=2.0,
),
),
(MoEActivation.SWIGLUOAI, ApplyMoEActivationConfig()),
(
MoEActivation.SWIGLUOAI_UNINTERLEAVE,
ApplyMoEActivationConfig(clamp_limit=3.0, alpha=1.3, beta=0.5),
),
(MoEActivation.SWIGLUSTEP, ApplyMoEActivationConfig()),
(MoEActivation.SILU_NO_MUL, ApplyMoEActivationConfig()),
(MoEActivation.GELU_NO_MUL, ApplyMoEActivationConfig()),
(MoEActivation.GELU_TANH_NO_MUL, ApplyMoEActivationConfig()),
(MoEActivation.RELU2_NO_MUL, ApplyMoEActivationConfig()),
],
ids=[
"silu",
"silu_clamp",
"gelu",
"gelu_tanh",
"situ",
"swigluoai",
"swigluoai_uninterleave",
"swiglustep",
"silu_no_mul",
"gelu_no_mul",
"gelu_tanh_no_mul",
"relu2_no_mul",
],
)
id="situ",
),
pytest.param(MoEActivation.SWIGLUOAI, ApplyMoEActivationConfig(), id="swigluoai"),
pytest.param(
MoEActivation.SWIGLUOAI_UNINTERLEAVE,
ApplyMoEActivationConfig(clamp_limit=3.0, alpha=1.3, beta=0.5),
id="swigluoai_uninterleave",
),
pytest.param(MoEActivation.SWIGLUSTEP, ApplyMoEActivationConfig(), id="swiglustep"),
pytest.param(
MoEActivation.SILU_NO_MUL, ApplyMoEActivationConfig(), id="silu_no_mul"
),
pytest.param(
MoEActivation.GELU_NO_MUL, ApplyMoEActivationConfig(), id="gelu_no_mul"
),
pytest.param(
MoEActivation.GELU_TANH_NO_MUL,
ApplyMoEActivationConfig(),
id="gelu_tanh_no_mul",
),
pytest.param(
MoEActivation.RELU2_NO_MUL, ApplyMoEActivationConfig(), id="relu2_no_mul"
),
]
@pytest.mark.parametrize(("activation", "activation_config"), MOE_ACTIVATION_CASES)
@torch.inference_mode()
def test_masked_moe_activation_dispatch(
default_vllm_config,
@@ -497,3 +494,73 @@ def test_activation(
out = torch.empty_like(x)
opcheck(fn, (out, x))
HUMMING_ACTIVATION_CASES = MOE_ACTIVATION_CASES + [
pytest.param(MoEActivation.RELU2, ApplyMoEActivationConfig(), id="relu2"),
]
HUMMING_ACTIVATION_CASES += [
pytest.param(
MoEActivation.SITU,
ApplyMoEActivationConfig(
activation_situ_beta=1.5,
activation_situ_linear_beta=linear_beta,
),
id=f"situ-linear-beta-{linear_beta}",
)
for linear_beta in (None, 0.0, -1.0)
]
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Humming requires CUDA")
@pytest.mark.parametrize(("activation", "activation_config"), HUMMING_ACTIVATION_CASES)
@pytest.mark.parametrize("dtype", DTYPES)
@pytest.mark.parametrize(("num_tokens", "d"), [(1, 512), (7, 768), (83, 512)])
@torch.inference_mode()
def test_humming_activation_matches_framework(
activation: MoEActivation,
activation_config: ApplyMoEActivationConfig,
dtype: torch.dtype,
num_tokens: int,
d: int,
) -> None:
"""Compare activation math/layouts without quantization or Hadamard error."""
pytest.importorskip("humming")
from humming.ops import process_input
from vllm.model_executor.layers.quantization.utils.humming.activation import (
get_humming_activation,
)
set_random_seed(0)
width = d * 2 if activation.is_gated else d
x = 4 * torch.randn(num_tokens, width, dtype=dtype, device=CUDA_DEVICES[0])
# Exercise zero, saturation, and both sides of the clamp limits (3 and 7).
edges = x.new_tensor([0, 0.001, 1, 2.99, 3, 3.01, 6.99, 7, 7.01, 8, 16])
edges = torch.cat((-edges[1:].flip(0), edges))
x[0] = edges[torch.arange(width, device=x.device) % edges.numel()]
actual, _, _ = process_input(
x,
quant_mode="none",
hadamard_block_size=0,
**get_humming_activation(activation, activation_config),
)
expected = torch.empty(num_tokens, d, dtype=dtype, device=x.device)
if activation == MoEActivation.RELU2:
# apply_moe_activation has only the non-gated ReLU2 variant.
gate, up = x.float().chunk(2, dim=-1)
activated_gate = torch.empty_like(gate)
apply_moe_activation(MoEActivation.RELU2_NO_MUL, activated_gate, gate.clone())
expected.copy_(activated_gate * up)
else:
# The framework's non-gated ReLU2 path modifies its input in place.
apply_moe_activation(
activation, expected, x.clone(), activation_config=activation_config
)
torch.testing.assert_close(
actual,
expected,
atol=get_default_atol(expected),
rtol=get_default_rtol(expected),
)
@@ -0,0 +1,53 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shape contract for ``QwenGatedDeltaNetAttention._output_projection``.
Every ``forward_*`` already allocates ``core_attn_out`` and ``z`` as
``(N, H, D)``. The helper now norms those tensors as-is and flattens once
for ``out_proj``; it used to be rank-agnostic via ``reshape(z_shape_og)``.
"""
from __future__ import annotations
import types
import pytest
import torch
from vllm.model_executor.layers.layernorm import RMSNormGated
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
QwenGatedDeltaNetAttention,
)
@pytest.mark.parametrize("dtype", [torch.float32])
@torch.inference_mode()
def test_output_projection_norms_per_head_and_flattens(
default_vllm_config,
dtype: torch.dtype,
) -> None:
num_tokens, num_heads, head_dim = 3, 4, 8
hidden = num_heads * head_dim
layer = types.SimpleNamespace()
layer.norm = RMSNormGated(
head_dim,
eps=1e-5,
group_size=None,
norm_before_gate=True,
device="cpu",
dtype=dtype,
)
layer.out_proj = lambda x: (x, None)
layer._output_projection = types.MethodType(
QwenGatedDeltaNetAttention._output_projection, layer
)
core_attn_out = torch.randn(num_tokens, num_heads, head_dim, dtype=dtype)
z = torch.randn(num_tokens, num_heads, head_dim, dtype=dtype)
out = layer._output_projection(core_attn_out, z)
assert core_attn_out.shape == (num_tokens, num_heads, head_dim)
assert z.shape == (num_tokens, num_heads, head_dim)
assert out.shape == (num_tokens, hidden)
assert out.dtype == dtype
+3 -1
View File
@@ -3,6 +3,7 @@
import pytest
from vllm.distributed import cleanup_dist_env_and_memory
from vllm.v1.worker.workspace import reset_workspace_manager
NEEDS_CLEAN_ENTRY = frozenset(
{
@@ -57,5 +58,6 @@ def pytest_runtest_setup(item):
# Not tryfirst: the skipping plugin evaluates skip marks in a tryfirst
# hook, so tests about to be skipped never reach this, while fixture setup
# still runs afterwards.
if item.path.name in NEEDS_CLEAN_ENTRY:
if item.path.name in NEEDS_CLEAN_ENTRY or "dist_init" in item.fixturenames:
reset_workspace_manager()
cleanup_dist_env_and_memory()
+55
View File
@@ -25,6 +25,7 @@ from vllm.model_executor.layers.fused_moe.all2all_utils import (
from vllm.model_executor.layers.fused_moe.config import (
fp8_w8a8_moe_quant_config,
)
from vllm.model_executor.layers.fused_moe.experts import triton_moe
from vllm.model_executor.layers.fused_moe.experts.deep_gemm_moe import (
_valid_deep_gemm_shape,
)
@@ -246,6 +247,60 @@ def test_w8a8_block_fp8_fused_moe(
torch.testing.assert_close(m_out, ref_out_m, atol=tol, rtol=tol)
@pytest.mark.parametrize("clamp_limit", [None, 10.0])
@torch.inference_mode()
def test_w8a8_block_fp8_clamp_skips_fused_silu_quant(
clamp_limit, monkeypatch, workspace_init, disable_deepgemm_ue8m0
):
"""A SwiGLU clamp must bypass the fused SiLU+quant kernel, which cannot clamp."""
torch.manual_seed(0)
M, N, K, E, topk = 16, 256, 512, 8, 2
block_size = [128, 128]
a = torch.randn((M, K), dtype=torch.bfloat16) / 10
score = torch.randn((M, E), dtype=torch.bfloat16)
(_, w1, w1_s, _), (_, w2, w2_s, _) = make_test_weights(
E, N, K, torch.bfloat16, torch.float8_e4m3fn, block_shape=block_size
)
quant_config = fp8_w8a8_moe_quant_config(
w1_scale=w1_s,
w2_scale=w2_s,
block_shape=block_size,
gemm1_clamp_limit=clamp_limit,
)
m_fused_moe = modular_triton_fused_moe(make_dummy_moe_config(), quant_config)
topk_weights, topk_ids, _ = fused_topk(a, score.float(), topk, False)
fused_calls = 0
fused_op = triton_moe.ops.silu_and_mul_per_block_quant
def counting_fused_op(*args, **kwargs):
nonlocal fused_calls
fused_calls += 1
return fused_op(*args, **kwargs)
monkeypatch.setattr(
triton_moe.ops, "silu_and_mul_per_block_quant", counting_fused_op
)
with set_current_vllm_config(vllm_config):
m_fused_moe.apply(
a,
w1,
w2,
topk_weights,
topk_ids,
activation=MoEActivation.SILU,
apply_router_weight_on_input=False,
expert_map=None,
global_num_experts=E,
)
assert (fused_calls > 0) == (clamp_limit is None), (
f"fused fast path ran {fused_calls} times with clamp_limit={clamp_limit}"
)
@pytest.mark.parametrize(("M", "N", "K"), MNK_FACTORS_DG)
@pytest.mark.parametrize("E", E)
@pytest.mark.parametrize("topk", TOP_KS)
+75 -26
View File
@@ -1245,7 +1245,7 @@ def _make_humming_indexed_experts(activation: MoEActivation):
from vllm.model_executor.layers.fused_moe.experts.fused_humming_moe import (
HummingIndexedExperts,
)
from vllm.model_executor.layers.quantization.utils import humming_utils
from vllm.model_executor.layers.quantization.utils import humming as humming_utils
from vllm.utils import humming
top_k, num_experts = 6, 12
@@ -1306,6 +1306,56 @@ def _make_humming_indexed_experts(activation: MoEActivation):
return experts, layer
@pytest.mark.parametrize("valid_shape_m", [8192, 8193])
@pytest.mark.parametrize("w2_block_size", [64, 96, 128])
def test_humming_indexed_routing_matches_each_projection_tile(
valid_shape_m: int, w2_block_size: int
):
"""Independently tuned projections preserve routed rows and expert identity."""
from types import SimpleNamespace
from vllm.model_executor.layers.fused_moe.experts.fused_humming_moe import (
HummingIndexedExperts,
)
topk_ids = torch.tensor([[0, 1], [1, 2], [2, 0]], device="cuda")
expert_map = torch.tensor([1, -1, 0], dtype=torch.int32, device="cuda")
experts = SimpleNamespace(
global_num_experts=3,
estimate_local_valid_shape_m=lambda _: valid_shape_m,
w13_tuning_config=[
[0, 8192, {"block_shape": [64, 128, 64]}],
[8192, 16384, {"block_shape": [128, 128, 64]}],
],
w2_tuning_config=[
[0, 8192, {"block_shape": [64, 128, 64]}],
[8192, 16384, {"block_shape": [w2_block_size, 128, 64]}],
],
compute_config_str="compute",
w13_tuning_config_str="w13",
w2_tuning_config_str="w2",
)
first, second, _ = HummingIndexedExperts.prepare_humming_moe_kwargs(
experts, topk_ids, expert_map, None
)
block_sizes = (64, 64) if valid_shape_m == 8192 else (128, w2_block_size)
expected_rows = torch.where(expert_map[topk_ids.flatten()] >= 0)[0]
for kwargs, block_size in zip((first, second), block_sizes):
padded = kwargs["num_tokens_padded"].item()
assert padded % block_size == 0
rows = kwargs["sorted_ids"][:padded].long()
valid = rows < topk_ids.numel()
torch.testing.assert_close(rows[valid].sort().values, expected_rows)
routed_experts = kwargs["expert_ids"][: padded // block_size]
torch.testing.assert_close(
routed_experts.repeat_interleave(block_size)[valid],
expert_map[topk_ids.flatten()[rows[valid]]],
)
assert (first["top_k"], second["top_k"]) == (2, 1)
for key in ("sorted_ids", "expert_ids", "num_tokens_padded"):
assert (first[key] is second[key]) == (block_sizes[0] == block_sizes[1])
@pytest.mark.parametrize("activation", list(MoEActivation))
def test_humming_activation_metadata_tracks_shared_apply(activation: MoEActivation):
from vllm.model_executor.layers.fused_moe.experts.fused_humming_moe import (
@@ -1464,54 +1514,46 @@ def test_humming_delegates_to_instance_activation():
def test_humming_grouped_apply_forwards_valid_prefix(
monkeypatch: pytest.MonkeyPatch,
):
from types import MethodType, SimpleNamespace
from types import SimpleNamespace
from unittest.mock import Mock
import vllm.model_executor.layers.fused_moe.experts.fused_humming_moe as humming
from vllm.model_executor.layers.fused_moe.experts.fused_humming_moe import (
HummingExpertsBase,
HummingGroupedExperts,
)
activation_func = Mock()
buffers = {
"gate_up_output": torch.empty(6, 4),
"activation_output": torch.empty(6, 2),
"quanted_down_input": torch.empty(6, 2),
"down_output": torch.empty(6, 4),
}
experts = SimpleNamespace(
activation=activation_func,
num_experts=2,
estimate_local_valid_shape_m=lambda _: 6,
prepare_buffers=lambda *_: buffers,
_get_permute_scratch=lambda _: None,
quantize_input=lambda _, *, inputs, input_scale=None, quanted_input: (
inputs,
input_scale,
_get_permute_scratch=lambda _, *, indices_only=False: object(),
process_input=Mock(
side_effect=lambda _, **kwargs: (
kwargs["inputs"],
kwargs.get("input_scale"),
None,
)
),
humming_forward=Mock(),
compute_config_str="",
w13_tuning_config_str="",
w2_tuning_config_str="",
)
experts.apply_activation = MethodType(HummingExpertsBase.apply_activation, experts)
hidden_states = torch.empty(3, 4)
output = torch.empty_like(hidden_states)
topk_ids = torch.zeros((3, 2), dtype=torch.int64)
topk_weights = torch.ones_like(topk_ids, dtype=torch.float32)
expected_counts = torch.tensor([4], dtype=torch.int32)
expert_offsets = torch.tensor([0, 2, 4], dtype=torch.int64)
monkeypatch.setattr(
humming,
"moe_permute",
lambda **_: (
torch.empty(6, 4),
None,
expert_offsets,
torch.arange(6),
None,
),
"moe_prepare_scatter",
lambda *_: (expert_offsets, torch.arange(6).view(3, 2)),
)
monkeypatch.setattr(humming, "moe_unpermute", lambda **_: None)
@@ -1534,12 +1576,11 @@ def test_humming_grouped_apply_forwards_valid_prefix(
apply_router_weight_on_input=False,
)
activation_func.assert_called_once()
call_kwargs = activation_func.call_args.kwargs
call_kwargs = experts.process_input.call_args.kwargs
assert call_kwargs["activation"] == MoEActivation.SITU
assert call_kwargs["input"].shape == (6, 4)
assert call_kwargs["output"].shape == (6, 2)
torch.testing.assert_close(call_kwargs["valid_token_counts"], expected_counts)
assert call_kwargs["inputs"].shape == (6, 4)
assert call_kwargs["quanted_input"].shape == (6, 2)
torch.testing.assert_close(call_kwargs["num_valid_tokens"], expert_offsets[-1:])
def test_batched_marlin_activation_uses_expert_token_counts(
@@ -1653,7 +1694,8 @@ def test_humming_gated_non_gated_shape_contract(activation: MoEActivation):
activation=moe_config.activation,
)
assert buffer_metas["gate_up_output"]["shape"][-1] == gate_up_size
assert buffer_metas["activation_output"]["shape"][-1] == intermediate_size
assert "activation_output" not in buffer_metas
assert buffer_metas["quanted_down_input"]["shape"][-1] == intermediate_size
assert experts.moe_problem_size(
a1=torch.empty(1, hidden_size),
w1=torch.empty(num_experts, 1),
@@ -1661,6 +1703,13 @@ def test_humming_gated_non_gated_shape_contract(activation: MoEActivation):
topk_ids=torch.empty(1, top_k, dtype=torch.long),
) == (num_experts, 1, intermediate_size, hidden_size, top_k)
# Quantized batched input storage must cover every dispatcher's token slots.
experts.is_batched = lambda: True
experts.max_num_tokens = 17
experts.num_dispatchers = 2
batched_metas, _ = experts.get_buffer_metas(17, top_k, activation)
assert batched_metas["quanted_gate_up_input"]["shape"][0] == num_experts * 17 * 2
def test_humming_indexed_writes_supplied_output_buffer():
from vllm.forward_context import set_forward_context
@@ -22,6 +22,46 @@ BLOCK_SIZES = [32, 128]
set_random_seed(0)
@pytest.mark.parametrize("num_experts,num_tokens", [(32, 8), (256, 8), (256, 1024)])
@pytest.mark.parametrize("use_expert_map", [False, True])
def test_moe_align_scatter_masks_invalid_routes(
num_experts, num_tokens, use_expert_map
):
topk_ids = torch.arange(num_tokens * 4, device="cuda").reshape(-1, 4)
topk_ids %= num_experts
topk_ids[0] = torch.tensor([-1, num_experts, 0, 1], device="cuda")
expert_map = None
valid = (topk_ids >= 0) & (topk_ids < num_experts)
if use_expert_map:
expert_map = torch.full((num_experts,), -1, dtype=torch.int32, device="cuda")
expert_map[::2] = torch.arange(
num_experts // 2, device="cuda", dtype=torch.int32
)
valid &= topk_ids % 2 == 0
sorted_ids, expert_ids, num_padded, scatter_idx = moe_align_block_size(
topk_ids,
32,
num_experts,
expert_map,
ignore_invalid_experts=True,
return_scatter_idx=True,
)
expected = torch.arange(topk_ids.numel(), device="cuda", dtype=torch.int32)
expected[~valid.flatten()] = -1
torch.testing.assert_close(scatter_idx, expected[:, None])
active_sorted = sorted_ids[: num_padded.item()]
active_sorted = active_sorted[active_sorted < topk_ids.numel()]
torch.testing.assert_close(active_sorted.sort().values, expected[expected >= 0])
baseline = moe_align_block_size(
topk_ids, 32, num_experts, expert_map, ignore_invalid_experts=True
)
assert len(baseline) == 3
torch.testing.assert_close(num_padded, baseline[2])
torch.testing.assert_close(expert_ids, baseline[1])
def _group_tokens_by_expert(
sorted_ids: torch.Tensor,
expert_ids: torch.Tensor,
@@ -18,6 +18,7 @@ from vllm.model_executor.layers.fused_moe.moe_permute_unpermute import (
get_moe_permute_scratch,
moe_permute,
moe_permute_unpermute_supported,
moe_prepare_scatter,
moe_unpermute,
)
from vllm.platforms import current_platform
@@ -458,7 +459,7 @@ def test_moe_permute_ignores_invalid_expert_ids_with_scratch() -> None:
hidden_dtype=hidden_states.dtype,
)
permuted, _, expert_offsets, _, _ = moe_permute(
permuted, _, expert_offsets, inverse, _ = moe_permute(
hidden_states=hidden_states,
a1q_scale=None,
topk_ids=topk_ids,
@@ -473,3 +474,27 @@ def test_moe_permute_ignores_invalid_expert_ids_with_scratch() -> None:
torch.tensor([0, 1, 2], dtype=torch.int64, device="cuda"),
)
torch.testing.assert_close(permuted[:2], hidden_states[[0, 2]])
assert torch.all(inverse[[1, 3, 4]] >= expert_offsets[-1])
expected = torch.zeros_like(hidden_states)
expected[[0, 2]] = hidden_states[[0, 2]]
output = torch.empty_like(hidden_states)
moe_unpermute(
output, permuted, torch.ones(5, 1, device="cuda"), inverse, expert_offsets
)
torch.testing.assert_close(output, expected)
expected_inverse = inverse.clone()
expected_offsets = expert_offsets.clone()
expert_offsets, indices = moe_prepare_scatter(topk_ids, expert_map, scratch)
torch.testing.assert_close(indices.flatten(), expected_inverse)
torch.testing.assert_close(expert_offsets, expected_offsets)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
expert_offsets, indices = moe_prepare_scatter(topk_ids, expert_map, scratch)
topk_ids.zero_()
graph.replay()
expected_inverse = torch.arange(5, dtype=torch.int32, device="cuda")
expected_offsets = torch.tensor([0, 5, 5], dtype=torch.int64, device="cuda")
torch.testing.assert_close(indices.flatten(), expected_inverse)
torch.testing.assert_close(expert_offsets, expected_offsets)
+55
View File
@@ -1868,6 +1868,61 @@ def test_select_mxfp4_moe_backend_raises_with_unsupported_reasons(
mxfp4_oracle.select_mxfp4_moe_backend(moe_config)
@pytest.mark.parametrize("backend_name", ["AITER_TRITON_MXFP4_BF16", "AITER_MXFP4_FP8"])
@pytest.mark.parametrize("use_ep", [False, True])
def test_aiter_mxfp4_monolithic_rejects_expert_parallel(
monkeypatch: pytest.MonkeyPatch, backend_name: str, use_ep: bool
):
"""Global routing cannot index local expert weights, even without all-to-all."""
from tests.kernels.moe.utils import make_dummy_moe_config
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
from vllm.model_executor.layers.fused_moe.config import RoutingMethodType
from vllm.model_executor.layers.fused_moe.modular_kernel import (
FusedMoEActivationFormat,
)
from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import (
Mxfp4MoeBackend,
backend_to_kernel_cls,
)
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8StaticTensorSym,
kMxfp4Static,
)
experts_cls = backend_to_kernel_cls(Mxfp4MoeBackend[backend_name])[0]
monkeypatch.setattr(experts_cls, "_supports_current_device", lambda: True)
config = make_dummy_moe_config(
num_experts=256,
num_local_experts=64 if use_ep else 256,
experts_per_token=6,
hidden_dim=4096,
intermediate_size=2048,
activation=MoEActivation.SWIGLUOAI,
)
config = replace(
config,
routing_method=RoutingMethodType.Renormalize,
moe_parallel_config=replace(
config.moe_parallel_config,
tp_size=1 if use_ep else 4,
ep_size=4 if use_ep else 1,
use_ep=use_ep,
),
)
assert not config.moe_parallel_config.use_all2all_kernels
supported, reason = experts_cls.is_supported_config(
experts_cls,
config,
kMxfp4Static,
kFp8StaticTensorSym if backend_name == "AITER_MXFP4_FP8" else None,
FusedMoEActivationFormat.Standard,
)
assert supported is not use_ep
if use_ep:
assert "parallel config" in reason
# Every activation-quantizing OCP MX scheme must map to a `quant_dtype` that
# `moe_kernel_quantize_input` actually dispatches on. Its final `else` returns
# the activation untouched, so a name it does not know (e.g. "mxfp6" instead of
@@ -81,6 +81,65 @@ def _torch_topk_softplus_sqrt(
return topk_weights.to(torch.float32), topk_ids.to(torch.int32)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm backend selection")
@pytest.mark.parametrize("has_hash_routing", [False, True])
@pytest.mark.parametrize(
"backend,expected_experts",
[
("aiter_triton_mxfp4_bf16", "AiterW4A16ExpertsMonolithic"),
("aiter", "AiterExperts"),
("triton_unfused", "UnfusedOAITritonExperts"),
],
)
def test_hash_routing_backend_selection(
dist_init,
default_vllm_config,
monkeypatch,
has_hash_routing,
backend,
expected_experts,
):
"""Hash tables must reach backend selection; modular AITER remains eligible."""
from dataclasses import replace
from vllm._aiter_ops import rocm_aiter_ops
from vllm.model_executor.layers.fused_moe.layer import FusedMoEFactory
from vllm.model_executor.layers.fused_moe.oracle.mxfp4 import (
select_deepseek_v4_mxfp4_moe_backend,
)
from vllm.platforms import rocm
# Exercise both native MX and monolithic AITER selection on any ROCm device.
monkeypatch.setattr(rocm, "on_gfx950", lambda: True)
monkeypatch.setattr(rocm, "on_gfx1250", lambda: False)
monkeypatch.setattr(rocm_aiter_ops, "is_enabled", lambda: True)
monkeypatch.setattr(rocm_aiter_ops, "is_fused_moe_enabled", lambda: True)
default_vllm_config.kernel_config.moe_backend = "triton"
layer = FusedMoEFactory(
num_experts=8,
top_k=2,
hidden_size=256,
intermediate_size=256,
params_dtype=torch.bfloat16,
scoring_func="sqrtsoftplus",
e_score_correction_bias=torch.zeros(8),
hash_indices_table=(
torch.tensor([[0, 1], [2, 3]], dtype=torch.int32)
if has_hash_routing
else None
),
prefix="hash_routing_selection",
)
config = replace(layer.routed_experts.moe_config, moe_backend=backend)
if has_hash_routing and backend == "aiter_triton_mxfp4_bf16":
with pytest.raises(ValueError, match="hash routing"):
select_deepseek_v4_mxfp4_moe_backend(config)
else:
_, experts_cls = select_deepseek_v4_mxfp4_moe_backend(config)
assert experts_cls.__name__ == expected_experts
def test_torch_topk_softplus_sqrt_breaks_ties_by_expert_id():
gating_output = torch.tensor([[2.0, 1.0, 1.0, 0.0]])
@@ -5,16 +5,16 @@
Run `pytest tests/kernels/quantization/test_mxfp4_kernel_selection.py`.
"""
from unittest.mock import patch
from unittest.mock import MagicMock, patch
import pytest
import torch
import vllm.envs as envs
from vllm.model_executor.kernels.linear import (
AiterMxfp4LinearKernel,
EmulationMxfp4LinearKernel,
FlashInferMxFp4LinearKernel,
HummingMxFp4LinearKernel,
MarlinMxFp4LinearKernel,
MxFp4LinearKernel,
MxFp4LinearLayerConfig,
@@ -44,7 +44,20 @@ _TRUE_W4A4_KERNELS = [
# Weight-only (A16) kernels: they never quantize activations. They still accept
# MXFP4 activation keys as an intentional compatibility fallback.
_WEIGHT_ONLY_KERNELS = [MarlinMxFp4LinearKernel, HummingMxFp4LinearKernel]
_WEIGHT_ONLY_KERNELS = [MarlinMxFp4LinearKernel]
def _make_emulation_layer():
layer = torch.nn.Module()
layer.register_parameter(
"weight",
torch.nn.Parameter(torch.ones((2, 2), dtype=torch.uint8), False),
)
layer.register_parameter(
"weight_scale",
torch.nn.Parameter(torch.ones((2, 1), dtype=torch.uint8), False),
)
return layer
def test_can_implement_is_abstract():
@@ -156,6 +169,77 @@ def test_emulation_kernel_derives_quant_dequant_func_from_config(monkeypatch):
assert kernel.quant_dequant_func is quant_dequant_mxfp4
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
def test_emulation_kernel_dequantizes_at_load_and_keeps_activation_qdq(
dtype, monkeypatch
):
monkeypatch.setattr(
"vllm.model_executor.kernels.linear.mxfp4.emulation.has_quark",
lambda: True,
)
kernel = EmulationMxfp4LinearKernel(
MxFp4LinearLayerConfig(activation_quant_key=kMxfp4Dynamic)
)
kernel.quant_dequant_func = MagicMock(side_effect=lambda x: x * 0.5)
layer = _make_emulation_layer()
dequantized = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.bfloat16)
x = torch.tensor([[2.0, 4.0]], dtype=dtype)
with (
patch.object(envs, "VLLM_MXFP4_EMULATION_DEQUANT_AT_LOAD", True),
patch(
"vllm.model_executor.kernels.linear.mxfp4.emulation.dequant_mxfp4",
return_value=dequantized,
) as dequant,
):
kernel.process_weights_after_loading(layer)
actual = kernel.apply_weights(layer, x)
expected = torch.nn.functional.linear(x * 0.5, dequantized.to(dtype))
torch.testing.assert_close(actual, expected)
dequant.assert_called_once()
kernel.quant_dequant_func.assert_called_once_with(x)
assert layer.weight.dtype == torch.bfloat16
assert layer.weight.device == dequantized.device
assert not layer.weight.requires_grad
assert layer.weight_scale is not None
assert not layer.weight_scale.requires_grad
def test_emulation_kernel_opt_out_dequantizes_per_invocation(monkeypatch):
monkeypatch.setattr(
"vllm.model_executor.kernels.linear.mxfp4.emulation.has_quark",
lambda: True,
)
kernel = EmulationMxfp4LinearKernel(
MxFp4LinearLayerConfig(activation_quant_key=kMxfp4Dynamic)
)
kernel.quant_dequant_func = MagicMock(side_effect=lambda x: x * 0.5)
layer = _make_emulation_layer()
dequantized = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.bfloat16)
x = torch.tensor([[2.0, 4.0]], dtype=torch.bfloat16)
with (
patch.object(envs, "VLLM_MXFP4_EMULATION_DEQUANT_AT_LOAD", False),
patch(
"vllm.model_executor.kernels.linear.mxfp4.emulation.dequant_mxfp4",
return_value=dequantized,
) as dequant,
):
kernel.process_weights_after_loading(layer)
dequant.assert_not_called()
first = kernel.apply_weights(layer, x)
second = kernel.apply_weights(layer, x)
expected = torch.nn.functional.linear(x * 0.5, dequantized)
torch.testing.assert_close(first, expected)
torch.testing.assert_close(second, expected)
assert dequant.call_count == 2
assert kernel.quant_dequant_func.call_count == 2
assert layer.weight.dtype == torch.uint8
assert layer.weight_scale is not None
def test_aiter_kernel_is_supported_requires_native_mx_support():
"""AiterMxfp4LinearKernel must not be selected on platforms without
native MX compute, even if AITER itself is importable."""
+3 -11
View File
@@ -50,16 +50,7 @@ SKINNY_GEMM_PASS_RATES = {
}
PRESHUFFLED_SHAPES = [
(64, 4096, 8192),
# aiter 0.1.20 Triton preshuffled fp4 GEMM OOBs (GPU memory access fault ->
# SIGABRT, crashing the process) for (M=32, N=8192, K=8192) on gfx950, despite
# advertising the (N, K) as tuned. A hard GPU fault can't be xfail'd, so skip it
# until the aiter kernel is fixed (ROCm/aiter#4867).
pytest.param(
(32, 8192, 8192),
marks=pytest.mark.skip(
reason="aiter 0.1.20 preshuffled fp4 GEMM OOB (M32,N8192,K8192, gfx950)"
),
),
(32, 8192, 16384),
]
@@ -430,7 +421,8 @@ def test_aiter_fp4_gemm_preshuffled_tuned_shapes(shape):
M, K, N = shape
assert M <= 64
assert rocm_aiter_ops.is_triton_gemm_afp4wfp4_presh_ws_tuned(N, K)
# The predicate takes K as packed bytes, matching `weight.shape[1]`.
assert rocm_aiter_ops.is_triton_gemm_afp4wfp4_presh_ws_tuned(N, K // 2)
A = torch.randn(M, K, dtype=torch.bfloat16)
B = torch.randn(N, K, dtype=torch.bfloat16)
+29
View File
@@ -148,3 +148,32 @@ def test_concat_mla_q_values_preserved(num_tokens):
assert torch.equal(out_bits[..., :nope_dim], ql_nope_bits)
assert torch.equal(out_bits[..., nope_dim:], q_pe_bits)
@pytest.mark.parametrize("rope_dim,transposed", [(0, False), (0, True), (64, False)])
@pytest.mark.parametrize("enabled", [False, True])
def test_concat_mla_q_fp8_nope_and_rope(rope_dim, transposed, enabled):
"""FP8 query packing preserves values with empty RoPE and strided BMM output."""
from vllm.config import CompilationConfig, VllmConfig, set_current_vllm_config
from vllm.model_executor.layers.attention.mla_attention import _DecodeConcatQuantFP8
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
torch.manual_seed(42)
shape = (8, 17, 512) if transposed else (17, 8, 512)
ql = torch.randn(shape, dtype=torch.bfloat16, device="cuda") * 128
if transposed:
ql = ql.transpose(0, 1)
qp = torch.randn(17, 8, rope_dim, dtype=torch.bfloat16, device="cuda") * 128
scale = torch.tensor(0.3, device="cuda", dtype=torch.float32)
joined = torch.cat((ql, qp), dim=-1)
expected = (joined.float() * scale.reciprocal()).clamp(-448, 448)
expected = expected.to(torch.float8_e4m3fn)
custom_ops = ["none"] + (["+mla_decode_concat_quant_fp8"] if enabled else [])
config = VllmConfig(
compilation_config=CompilationConfig(mode=0, custom_ops=custom_ops)
)
with set_current_vllm_config(config):
quant = _DecodeConcatQuantFP8(static=True, group_shape=GroupShape.PER_TENSOR)
actual = quant(ql, qp, scale)
torch.testing.assert_close(actual.float(), expected.float(), atol=0, rtol=0)
assert actual.is_contiguous()
+6 -2
View File
@@ -599,7 +599,9 @@ def test_engram_rejects_empty_head_shards(tp_size, dp_size, n_heads, monkeypatch
ParallelEngramEmbedding(n_heads * 17, 64, (17,) * n_heads)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA required")
@pytest.mark.skipif(
not current_platform.is_cuda_alike(), reason="CUDA or ROCm required"
)
@pytest.mark.parametrize("cpu_offload", [False, True])
@pytest.mark.parametrize("tp_size", [1, 2, 4, 8])
def test_engram_head_shards_reconstruct_checkpoint(cpu_offload, tp_size, monkeypatch):
@@ -701,7 +703,9 @@ def test_engram_lookup_reuses_jit_across_token_shapes():
assert cache_sizes == [1] * len(cache_sizes)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA required")
@pytest.mark.skipif(
not current_platform.is_cuda_alike(), reason="CUDA or ROCm required"
)
@pytest.mark.parametrize("cpu_offload", [False, True])
@pytest.mark.parametrize("background", [False, True])
@pytest.mark.parametrize("num_tokens", [1, 7, 256])
+44
View File
@@ -501,6 +501,50 @@ def test_rmsnorm_gated_forward_native_dtype(
torch.testing.assert_close(out, ref_out, atol=1e-2, rtol=1e-2)
@pytest.mark.parametrize("dtype", [torch.bfloat16])
@torch.inference_mode()
def test_rmsnorm_gated_3d_matches_flattened_2d(
default_vllm_config,
dtype: torch.dtype,
) -> None:
"""Qwen GDN now norms (N, H, D) in place of a flatten to (N*H, D).
Last-dim RMS + gate must match the flattened layout on both the native
and CUDA/HIP kernels, including a 3D z view that is not contiguous.
"""
from vllm.model_executor.layers.layernorm import RMSNormGated
set_random_seed(42)
device = torch.device(DEVICE)
num_tokens, num_heads, head_dim = 5, 4, 64
layer = RMSNormGated(
head_dim,
eps=1e-5,
group_size=None,
norm_before_gate=True,
device=device,
dtype=dtype,
)
packed = torch.randn(num_tokens, num_heads, 2, head_dim, dtype=dtype, device=device)
x3 = packed[:, :, 0, :]
z3 = packed[:, :, 1, :]
assert not x3.is_contiguous()
assert not z3.is_contiguous()
x2 = x3.reshape(-1, head_dim).contiguous()
z2 = z3.reshape(-1, head_dim).contiguous()
native_3d = layer.forward_native(x3, z3)
native_2d = layer.forward_native(x2, z2).reshape(num_tokens, num_heads, head_dim)
torch.testing.assert_close(native_3d, native_2d, atol=0, rtol=0)
cuda_3d = layer.forward_cuda(x3, z3)
cuda_2d = layer.forward_cuda(x2, z2).reshape(num_tokens, num_heads, head_dim)
torch.testing.assert_close(cuda_3d, cuda_2d, atol=1e-3, rtol=1e-2)
torch.testing.assert_close(cuda_3d, native_3d, atol=1e-2, rtol=1e-2)
assert cuda_3d.shape == (num_tokens, num_heads, head_dim)
if __name__ == "__main__":
# Run a quick smoke test
test_layer_norm_fwd_basic(128, 1024, torch.float16, 42, False)
@@ -96,7 +96,7 @@ def apply_rope_gptj_last_k(
# `e*c - o*s` fused form. This keeps the reference close to the kernel, but
# the fp32 reference and the fp32 GPU kernel can still round to bf16 on
# opposite sides of a round-to-nearest tie for a tiny number of elements at
# high positions, so callers compare the RoPE region within 1 bf16 ULP.
# high positions, so callers allow for bf16 rounding in the RoPE region.
new_even = torch.addcmul(-odd * sin, even, cos)
new_odd = torch.addcmul(odd * cos, even, sin)
rope_rotated = torch.stack((new_even, new_odd), dim=-1).reshape(shape)
@@ -314,7 +314,19 @@ def test_q_path_without_qnorm_matches_rope_only_reference(num_tokens: int):
apply_q_norm=False,
)
torch.testing.assert_close(q_out[:, :n_heads], q_ref, rtol=0, atol=0)
torch.testing.assert_close(
q_out[:, :n_heads, :NOPE_DIM], q_ref[..., :NOPE_DIM], rtol=0, atol=0
)
# HIP and PyTorch can contract different FP32 products into an FMA.
# Allow bf16 rounding and small cancellation errors only in the RoPE region
# on ROCm; the unrotated dimensions and padded heads must remain exact.
rope_rtol, rope_atol = (1e-2, 1e-6) if current_platform.is_rocm() else (0, 0)
torch.testing.assert_close(
q_out[:, :n_heads, NOPE_DIM:],
q_ref[..., NOPE_DIM:],
rtol=rope_rtol,
atol=rope_atol,
)
assert q_out[:, n_heads:].count_nonzero().item() == 0
@@ -6,7 +6,7 @@ import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from tests.utils import ensure_current_vllm_config
from vllm.config import ModelConfig, VllmConfig, set_current_vllm_config
from vllm.distributed import cleanup_dist_env_and_memory
from vllm.distributed.parallel_state import (
init_distributed_environment,
@@ -17,6 +17,7 @@ from vllm.utils.network_utils import get_open_port
from vllm.utils.system_utils import update_environment_variables
_SHAPES = (
(129, 512),
(129, 768),
(257, 768),
(1023, 4224),
@@ -29,6 +30,7 @@ _N = 512
def _reference(
x: torch.Tensor,
weight: torch.Tensor,
weight_scale: torch.Tensor | None,
world_size: int,
group: dist.ProcessGroup,
all_reduce: bool,
@@ -40,7 +42,21 @@ def _reference(
dtype=x.dtype,
device=x.device,
)
torch.mm(x, weight.T, out=partial[:M])
if weight_scale is None:
torch.mm(x, weight.T, out=partial[:M])
else:
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
mxfp8_e4m3_quantize,
)
x_q, x_sf = mxfp8_e4m3_quantize(x, is_sf_swizzled_layout=True)
partial[:M] = torch._scaled_mm(
x_q,
weight.T,
x_sf.view(torch.float8_e8m0fnu),
weight_scale.view(torch.float8_e8m0fnu),
out_dtype=x.dtype,
)
if padded_M > M:
partial[M:].zero_()
@@ -75,6 +91,10 @@ def _assert_valid_rows_close(
rtol=5e-2,
atol=4.0,
)
# Sequence-parallel callers may pass an unpadded M and read the padding
# rows back (they flow through per-token kernels before being dropped),
# so RS must leave them zero like ``sp_reduce_scatter`` does.
assert not actual[valid_rows:].any()
def _run_mode(
@@ -85,19 +105,52 @@ def _run_mode(
rank: int,
world_size: int,
weights: dict[int, torch.Tensor],
backend: str,
) -> None:
# cute_dsl is unavailable off CUDA, so import it only inside the GPU worker.
from vllm.models.kimi_k3.nvidia.ops.cute_dsl.gemm_rs_ar import GemmRsAr
from vllm.model_executor.kernels.linear.cute_dsl.gemm_rs_ar import GemmRsAr
gemm_rs_ar = GemmRsAr(
max_M=max(M for M, _ in _SHAPES),
N=_N,
all_reduce=all_reduce,
)
from vllm.config.quantization import QuantizationConfigArgs
from vllm.model_executor.layers.linear import RowParallelLinear
from vllm.model_executor.layers.quantization.online.base import (
OnlineQuantizationConfig,
)
quant_config = (
None
if backend == "bf16"
else OnlineQuantizationConfig(QuantizationConfigArgs(linear="mxfp8"))
)
projections = {}
operands = {}
for K, w in weights.items():
with torch.device(device):
linear = RowParallelLinear(
K * world_size,
_N,
bias=False,
params_dtype=torch.bfloat16,
quant_config=quant_config,
)
# Select the fused path before online quantization replaces meta weights.
assert gemm_rs_ar.can_run(linear)
linear.weight = torch.nn.Parameter(w.clone(), requires_grad=False)
linear.quant_method.process_weights_after_loading(linear)
projections[K] = linear
weight = linear.weight
if backend == "flashinfer_cutedsl":
weight = weight.t()
operands[K] = (weight, getattr(linear, "weight_scale", None))
input_generator = torch.Generator(device=device)
# Alternating shapes exercise producer-flag reuse across different grids,
# CTA-group choices, and both BN=128 and BN=256 dispatches.
# Alternating shapes exercise producer-flag reuse across different grids
# and CTA-group choices.
for M, K in (*_SHAPES, *_SHAPES[::-1]):
input_generator.manual_seed(2000 + M + K)
x = torch.randn(
@@ -107,8 +160,8 @@ def _run_mode(
device=device,
generator=input_generator,
)
expected = _reference(x, weights[K], world_size, group, all_reduce)
actual = gemm_rs_ar(x, weights[K])
expected = _reference(x, *operands[K], world_size, group, all_reduce)
actual = gemm_rs_ar.apply(x, projections[K])
torch.accelerator.synchronize(device)
_assert_valid_rows_close(actual, expected, M, rank, all_reduce)
@@ -123,9 +176,9 @@ def _run_mode(
device=device,
generator=input_generator,
)
first_output = gemm_rs_ar(lifetime_x, weights[lifetime_K])
first_output = gemm_rs_ar.apply(lifetime_x, projections[lifetime_K])
first_snapshot = first_output.clone()
second_output = gemm_rs_ar(-lifetime_x, weights[lifetime_K])
second_output = gemm_rs_ar.apply(-lifetime_x, projections[lifetime_K])
torch.accelerator.synchronize(device)
assert first_output.data_ptr() != second_output.data_ptr()
torch.testing.assert_close(first_output, first_snapshot, rtol=0, atol=0)
@@ -141,7 +194,7 @@ def _run_mode(
)
graph_expected = _reference(
graph_x,
weights[graph_K],
*operands[graph_K],
world_size,
group,
all_reduce,
@@ -152,13 +205,13 @@ def _run_mode(
capture_stream.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(capture_stream):
for _ in range(3):
graph_output.copy_(gemm_rs_ar(graph_x, weights[graph_K]))
graph_output.copy_(gemm_rs_ar.apply(graph_x, projections[graph_K]))
capture_stream.synchronize()
dist.barrier(group=group)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=capture_stream):
graph_output.copy_(gemm_rs_ar(graph_x, weights[graph_K]))
graph_output.copy_(gemm_rs_ar.apply(graph_x, projections[graph_K]))
torch.cuda.current_stream().wait_stream(capture_stream)
dist.barrier(group=group)
@@ -177,7 +230,7 @@ def _run_mode(
del gemm_rs_ar, capture_stream, graph, graph_output
def _worker(local_rank: int, world_size: int, master_port: int) -> None:
def _worker(local_rank: int, world_size: int, master_port: int, backend: str) -> None:
# This module pulls in cute_dsl, which is unavailable off CUDA, so importing
# it at module level would fail collection. Import it where it is used, as
# `kda.py` does.
@@ -195,7 +248,10 @@ def _worker(local_rank: int, world_size: int, master_port: int) -> None:
)
init_distributed_environment()
with ensure_current_vllm_config():
config = VllmConfig()
config.model_config = ModelConfig(dtype="bfloat16")
config.kernel_config.linear_backend = "auto" if backend == "bf16" else backend
with set_current_vllm_config(config):
initialize_model_parallel(tensor_model_parallel_size=world_size)
group = dist.group.WORLD
@@ -215,24 +271,29 @@ def _worker(local_rank: int, world_size: int, master_port: int) -> None:
# Production binds one mode per worker; exercise both mode-bound instances
# sequentially in this test without implying that both are initialized.
for all_reduce in (False, True):
_run_mode(
all_reduce=all_reduce,
device=device,
group=group,
rank=rank,
world_size=world_size,
weights=weights,
)
with set_current_vllm_config(config):
for all_reduce in (False, True):
_run_mode(
all_reduce=all_reduce,
device=device,
group=group,
rank=rank,
world_size=world_size,
weights=weights,
backend=backend,
)
cleanup_dist_env_and_memory()
@pytest.mark.parametrize(
"backend", ["bf16", "flashinfer_cutlass", "flashinfer_cutedsl"]
)
@pytest.mark.distributed(num_gpus=2)
@pytest.mark.skipif(
not current_platform.is_device_capability_family(100),
reason="Kimi-K3 GEMM-RS/AR requires SM100",
reason="GEMM-RS/AR requires SM100",
)
def test_kimi_k3_gemm_rs_ar(monkeypatch: pytest.MonkeyPatch) -> None:
def test_gemm_rs_ar(monkeypatch: pytest.MonkeyPatch, backend: str) -> None:
world_size = 2
if torch.accelerator.device_count() < world_size:
pytest.skip("GEMM-RS/AR requires two GPUs")
@@ -242,7 +303,7 @@ def test_kimi_k3_gemm_rs_ar(monkeypatch: pytest.MonkeyPatch) -> None:
try:
mp.spawn(
_worker,
args=(world_size, get_open_port()),
args=(world_size, get_open_port(), backend),
nprocs=world_size,
)
finally:
+192 -12
View File
@@ -50,6 +50,40 @@ from vllm.utils.torch_utils import set_random_seed
DEVICE = current_platform.device_type
@pytest.mark.parametrize(
"tp,ep,hidden,hc,multicast,expected",
[
(4, False, 5120, 4, 1, True),
(2, False, 5120, 4, 1, False),
(4, True, 5120, 4, 1, False),
(4, False, 4096, 4, 1, False),
(4, False, 5120, 2, 1, False),
(4, False, 5120, 4, 0, False),
],
)
def test_deepseek_v41_all_reduce_fusion_requires_kernel_support(
monkeypatch, tp, ep, hidden, hc, multicast, expected
):
"""Eligibility depends on kernel inputs, not serving or attention settings."""
from vllm.models.deepseek_v41.nvidia.ops import mhc
config = SimpleNamespace(
parallel_config=SimpleNamespace(
tensor_parallel_size=tp, enable_expert_parallel=ep
),
model_config=SimpleNamespace(
hf_config=SimpleNamespace(hidden_size=hidden, hc_mult=hc)
),
)
group = SimpleNamespace(
device_communicator=SimpleNamespace(
ca_comm=SimpleNamespace(mnnvl_lamport_ag_multicast_ptr=multicast)
)
)
monkeypatch.setattr(mhc, "get_tp_group", lambda: group)
assert mhc.supports_mhc_all_reduce(config) is expected
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA required")
@pytest.mark.parametrize(
"num_tokens,hc_mult,hidden_size",
@@ -266,6 +300,77 @@ def test_deepseek_v41_mhc_pre_delayed(
torch.testing.assert_close(actual[2], expected[2], atol=1.6e-2, rtol=1e-2)
@pytest.mark.skipif(
not HAS_TILELANG_MHC or not current_platform.is_device_capability_family(100),
reason="SM100 TileLang mHC required",
)
@pytest.mark.parametrize("num_tokens", [0, 1, 8, 9, 32, 128, 256])
@pytest.mark.parametrize("entry", ["broadcast", "identity", "carried"])
@pytest.mark.parametrize("hidden_size,hc_mult", [(4096, 2), (5120, 4), (7168, 4)])
def test_deepseek_v41_mhc_overlap_preserves_outputs_on_replay(
num_tokens, entry, hidden_size, hc_mult
):
"""The input is usable before joining; coefficients stay exact on graph replay."""
from vllm.models.deepseek_v41.nvidia.ops.mhc import mhc_pre_delayed_overlap
from vllm.utils.deep_gemm import is_deep_gemm_supported
if not is_deep_gemm_supported():
pytest.skip("DeepGEMM required")
set_random_seed(42)
mix_size = hc_mult * (hc_mult + 2)
residual = torch.randn(
num_tokens, hc_mult, hidden_size, dtype=torch.bfloat16, device=DEVICE
)
fn = torch.randn(mix_size, hc_mult, hidden_size, device=DEVICE) * 0.02
x = None
pre_mix = None
if entry == "broadcast":
x = residual[:, 0].contiguous()
residual = x.unsqueeze(1).expand(-1, hc_mult, -1).contiguous()
fn = fn.sum(1)
else:
fn = fn.flatten(1)
if entry == "carried":
pre_mix = torch.rand(num_tokens, hc_mult, device=DEVICE)
scale = torch.tensor([0.5, 0.25, 1.0], device=DEVICE)
base = torch.randn(mix_size, device=DEVICE)
weight = torch.empty(hidden_size, dtype=torch.bfloat16, device=DEVICE).uniform_(
0.5, 1.5
)
args = (residual, fn, scale, base, 1e-20, 1e-6, 1e-6, 2.0, 20)
kwargs = dict(pre_mix=pre_mix, x=x, norm_weight=weight, norm_eps=1e-20)
side = torch.cuda.Stream()
def run():
outputs = mhc_pre_delayed_overlap(*args, **kwargs, stream=side)
consumed_input = outputs[2].clone()
torch.cuda.current_stream().wait_stream(side)
return (*outputs, consumed_input)
def check(actual):
expected = mhc_pre_delayed_tilelang(*args, **kwargs)
for a, b in zip(actual[:4], expected, strict=True):
torch.testing.assert_close(a, b, atol=0, rtol=0)
torch.testing.assert_close(actual[4], expected[2], atol=0, rtol=0)
check(run())
if num_tokens == 0:
return
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
captured = run()
for _ in range(5):
if x is not None:
x.normal_()
residual.copy_(x.unsqueeze(1).expand_as(residual))
else:
residual.normal_()
if pre_mix is not None:
pre_mix.uniform_()
graph.replay()
check(captured)
def mhc_fused_post_pre_delayed_ref(
x: torch.Tensor,
residual: torch.Tensor,
@@ -433,10 +538,16 @@ def test_mhc_fused_post_pre_delayed_custom_op_supports_compile(carried, capture_
@pytest.mark.skipif(not HAS_TILELANG_MHC, reason="TileLang MHC support required")
@pytest.mark.parametrize("entry", ["broadcast", "pipeline", "residual", "engram"])
@pytest.mark.parametrize(
"mhc_mode", ["disabled", "eager", "overlap", "piecewise", "large_batch"]
)
def test_deepseek_v41_decoder_mixes_match_torch(
entry, monkeypatch, default_vllm_config
entry, mhc_mode, monkeypatch, default_vllm_config
):
"""Preserve carried pre-mixes and Engram ordering at every decoder entry."""
from vllm.models.deepseek_v41.nvidia.ops.mhc import MHC_OVERLAP_MAX_TOKENS
num_tokens = MHC_OVERLAP_MAX_TOKENS + 1 if mhc_mode == "large_batch" else 3
set_random_seed(0)
decoder = DeepseekV41DecoderLayer.__new__(DeepseekV41DecoderLayer)
nn.Module.__init__(decoder)
@@ -446,6 +557,30 @@ def test_deepseek_v41_decoder_mixes_match_torch(
decoder.rms_norm_eps = 1e-20
decoder.hc_post_alpha = 2.0
decoder.use_sequence_parallel = False
decoder.fuse_mhc_all_reduce = False
decoder.mhc_stream = None
if mhc_mode != "disabled":
from vllm.utils.deep_gemm import is_deep_gemm_supported
if (
not current_platform.is_device_capability_family(100)
or not is_deep_gemm_supported()
):
pytest.skip("SM100 DeepGEMM required for overlap")
decoder.mhc_stream = torch.cuda.Stream()
if mhc_mode in ("eager", "piecewise", "large_batch"):
def unexpected_overlap(*args, **kwargs):
pytest.fail("unsupported execution must retain native mHC")
monkeypatch.setattr(
"vllm.models.deepseek_v41.nvidia.model.mhc_pre_delayed_overlap",
unexpected_overlap,
)
monkeypatch.setattr(
"vllm.models.deepseek_v41.nvidia.ops.mhc.mhc_pre_delayed_overlap",
unexpected_overlap,
)
decoder.engram = None
from vllm.model_executor.layers.layernorm import RMSNorm
@@ -461,18 +596,18 @@ def test_deepseek_v41_decoder_mixes_match_torch(
decoder.hc_attn_scale = decoder.hc_ffn_scale = torch.ones(3)
decoder.hc_attn_base = torch.randn(24)
decoder.hc_ffn_base = torch.randn(24)
x = torch.randn(3, 5120, dtype=torch.bfloat16)
positions = torch.arange(3)
x = torch.randn(num_tokens, 5120, dtype=torch.bfloat16)
positions = torch.arange(num_tokens)
kwargs = {}
if entry != "broadcast":
kwargs["pre_mix"] = torch.rand(3, 4)
kwargs["pre_mix"] = torch.rand(num_tokens, 4)
if entry == "pipeline":
x = torch.randn(3, 4, 5120, dtype=torch.bfloat16)
x = torch.randn(num_tokens, 4, 5120, dtype=torch.bfloat16)
if entry in ("residual", "engram"):
kwargs.update(
residual=torch.randn(3, 4, 5120, dtype=torch.bfloat16),
post_mix=torch.rand(3, 4, 1),
res_mix=torch.rand(3, 4, 4),
residual=torch.randn(num_tokens, 4, 5120, dtype=torch.bfloat16),
post_mix=torch.rand(num_tokens, 4, 1),
res_mix=torch.rand(num_tokens, 4, 4),
)
if entry == "engram":
@@ -483,15 +618,49 @@ def test_deepseek_v41_decoder_mixes_match_torch(
return residual + 0.125
decoder.engram = FakeEngram()
kwargs["engram_hashes"] = torch.zeros(3, 1, 1, dtype=torch.int32)
kwargs["engram_hashes"] = torch.zeros(num_tokens, 1, 1, dtype=torch.int32)
actual = decoder(x, positions, None, **kwargs)
from vllm.config import CUDAGraphMode
from vllm.forward_context import set_forward_context
mode = CUDAGraphMode.PIECEWISE if mhc_mode == "piecewise" else CUDAGraphMode.NONE
overlap_calls = []
if mhc_mode == "overlap":
from vllm.models.deepseek_v41.nvidia.ops.mhc import mhc_pre_delayed_overlap
def checked_overlap(*args, **kwargs):
overlap_calls.append(torch.cuda.is_current_stream_capturing())
return mhc_pre_delayed_overlap(*args, **kwargs)
for module in ("model", "ops.mhc"):
monkeypatch.setattr(
f"vllm.models.deepseek_v41.nvidia.{module}.mhc_pre_delayed_overlap",
checked_overlap,
)
with set_forward_context(None, default_vllm_config, cudagraph_runtime_mode=mode):
actual = decoder(x, positions, None, **kwargs)
if mhc_mode == "overlap":
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
actual = decoder(x, positions, None, **kwargs)
graph.replay()
assert overlap_calls and all(overlap_calls)
def reference(*args, norm_weight, norm_eps, **kwargs):
post, res, collapsed, pre = mhc_pre_delayed_torch(*args, **kwargs)
return post, res, decoder.attn_norm(collapsed), pre
def fused_reference(x, residual, post_mix, res_mix, *args, capture_aux=False, **kw):
def fused_reference(
x,
residual,
post_mix,
res_mix,
*args,
capture_aux=False,
stream=None,
reduce_results=False,
**kw,
):
residual = mhc_post_torch(x, residual, post_mix, res_mix)
aux = residual.mean(dim=1) if capture_aux else residual.new_empty(0)
return residual, *reference(residual, *args, **kw), aux
@@ -500,6 +669,7 @@ def test_deepseek_v41_decoder_mixes_match_torch(
"vllm.models.deepseek_v41.nvidia.model.mhc_pre_delayed_tilelang",
reference,
)
decoder.mhc_stream = None
monkeypatch.setattr(
"vllm.models.deepseek_v41.nvidia.model.mhc_shifted_post_pre",
fused_reference,
@@ -530,6 +700,8 @@ def test_deepseek_v41_capture_previous_aux(entry, monkeypatch, default_vllm_conf
decoder.rms_norm_eps = 1e-6
decoder.hc_post_alpha = 2.0
decoder.use_sequence_parallel = False
decoder.fuse_mhc_all_reduce = False
decoder.mhc_stream = None
decoder.engram = None
from vllm.model_executor.layers.layernorm import RMSNorm
@@ -772,7 +944,8 @@ def hc_head_ref(
@pytest.mark.parametrize("num_tokens", [1, 4, 8, 128])
@pytest.mark.parametrize("hidden_size", [4096, 7168])
@pytest.mark.parametrize("hc_mult", [4])
def test_mhc_pre_tilelang(num_tokens, hidden_size, hc_mult):
@pytest.mark.parametrize("fused_norm", [False, True])
def test_mhc_pre_tilelang(num_tokens, hidden_size, hc_mult, fused_norm):
torch.set_default_device(DEVICE)
set_random_seed(0)
@@ -802,6 +975,12 @@ def test_mhc_pre_tilelang(num_tokens, hidden_size, hc_mult):
hc_post_alpha,
sinkhorn_repeat,
)
norm_kwargs = {}
if fused_norm:
# Non-shifted mHC must still use its freshly computed pre-mix.
weight = torch.ones(hidden_size, dtype=torch.bfloat16)
norm_kwargs = dict(norm_weight=weight, norm_eps=rms_eps)
ref = (*ref[:2], F.rms_norm(ref[2], (hidden_size,), weight, rms_eps))
out = torch.ops.vllm.mhc_pre_tilelang(
residual,
fn,
@@ -812,6 +991,7 @@ def test_mhc_pre_tilelang(num_tokens, hidden_size, hc_mult):
hc_sinkhorn_eps,
hc_post_alpha,
sinkhorn_repeat,
**norm_kwargs,
)
for actual, expected in zip(out, ref, strict=True):
@@ -30,10 +30,19 @@ DAEMON_TIMEOUT_S = 600
class WeightCacheDaemon:
"""Context manager running the real weight cache daemon as a subprocess."""
def __init__(self, model: str, tp_size: int, extra_args: list[str] | None = None):
def __init__(
self,
model: str,
tp_size: int,
extra_args: list[str] | None = None,
num_groups: int = 1,
):
# Short base path: Unix socket paths are limited to ~107 characters.
self.socket_dir = tempfile.mkdtemp(prefix="vllm_ipc_")
self.tp_size = tp_size
# Each daemon group (target plus cached drafts) binds one socket per
# local rank.
self.num_sockets = tp_size * num_groups
self._cmd = [
sys.executable,
"-m",
@@ -87,7 +96,7 @@ class WeightCacheDaemon:
f"Weight cache daemon exited with {self._proc.returncode}:\n"
f"{self._logs()}"
)
if len(glob.glob(pattern)) >= self.tp_size:
if len(glob.glob(pattern)) >= self.num_sockets:
return
time.sleep(1.0)
raise TimeoutError(
@@ -112,6 +121,9 @@ class ModelCase:
images: list | None = None
llm_kwargs: dict[str, Any] = field(default_factory=dict)
daemon_args: list[str] = field(default_factory=list)
# Daemon groups the launcher starts; 2 when a cached draft group joins the
# target group (MTP/EAGLE speculative decoding).
daemon_groups: int = 1
def generate(
@@ -172,14 +184,41 @@ K3_CASE = ModelCase(
daemon_args=["--trust-remote-code"],
)
# Qwen3.5-0.8B ships one MTP layer in the target checkpoint, so method="mtp"
# loads the draft from the same model. The daemon must cache it in its draft
# group for the warm runs (fallback=False) to succeed.
QWEN_MTP_CASE = ModelCase(
model="Qwen/Qwen3.5-0.8B",
prompts=[
"Hello, my name is",
"The capital of France is",
],
llm_kwargs=dict(
gpu_memory_utilization=0.3,
enforce_eager=True,
enable_chunked_prefill=True,
speculative_config={"method": "mtp", "num_speculative_tokens": 1},
),
daemon_args=[
"--speculative-config",
'{"method": "mtp", "num_speculative_tokens": 1}',
],
daemon_groups=2,
)
@pytest.mark.parametrize("case", [QWEN_CASE, K3_CASE], ids=["qwen3.5", "kimi-k3"])
@pytest.mark.parametrize(
"case",
[QWEN_CASE, K3_CASE, QWEN_MTP_CASE],
ids=["qwen3.5", "kimi-k3", "qwen3.5-mtp"],
)
def test_ipc_cache_cold_start_and_warm_restart(vllm_runner, case: ModelCase):
"""Cold start falls back to disk; warm restarts load weights via CUDA IPC.
All runs must produce outputs identical to a default-loader baseline. The
warm runs disable the disk fallback, so they only pass if the weights
really came from the daemon.
really came from the daemon — for the MTP case, both the target's and the
draft's daemon groups.
"""
if not current_platform.is_cuda_alike():
pytest.skip("Weight cache IPC sharing requires CUDA or ROCm")
@@ -199,7 +238,12 @@ def test_ipc_cache_cold_start_and_warm_restart(vllm_runner, case: ModelCase):
with tempfile.TemporaryDirectory(prefix="vllm_ipc_empty_") as empty_socket_dir:
cold_outputs = generate(vllm_runner, case, empty_socket_dir, fallback=True)
with WeightCacheDaemon(case.model, tp_size=1, extra_args=case.daemon_args) as d:
with WeightCacheDaemon(
case.model,
tp_size=1,
extra_args=case.daemon_args,
num_groups=case.daemon_groups,
) as d:
warm_outputs = generate(vllm_runner, case, d.socket_dir, fallback=False)
# Warm restart: a second engine lifetime against the same daemon.
restart_outputs = generate(vllm_runner, case, d.socket_dir, fallback=False)
+2 -1
View File
@@ -369,11 +369,12 @@ def test_dspark_shares_target_embedding_with_smaller_draft_vocabulary():
draft_parallel_config=SimpleNamespace(tensor_parallel_size=1),
attention_backend=None,
kv_cache_dtype=None,
draft_load_config=None,
),
parallel_config=ParallelConfig(),
attention_config=SimpleNamespace(backend=None),
cache_config=SimpleNamespace(),
load_config=SimpleNamespace(),
load_config=SimpleNamespace(load_format="auto"),
model_config=SimpleNamespace(get_vocab_size=Mock(return_value=100)),
)
@@ -7,26 +7,19 @@ from unittest.mock import Mock, patch
import pytest
import torch
from vllm.config import ModelConfig, VllmConfig
from vllm.config import VllmConfig
from vllm.config.compilation import CompilationMode
from vllm.distributed.eplb.eplb_state import EplbLayerState
from vllm.model_executor.layers.fused_moe.config import RoutingMethodType
from vllm.model_executor.layers.fused_moe.routed_experts_capturer import (
RoutedExpertsCapturer,
RoutedExpertsManager,
bind_routed_experts_capturer,
get_routed_experts_attn_gid,
)
from vllm.model_executor.layers.fused_moe.router.base_router import BaseRouter
from vllm.transformers_utils.model_arch_config_convertor import (
ModelArchConfigConvertorBase,
)
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheConfig,
KVCacheGroupSpec,
MLAAttentionSpec,
SlidingWindowMLASpec,
UniformTypeKVCacheSpecs,
)
@@ -42,6 +35,7 @@ def _capturer_with_buffer(
num_experts_per_tok: int = 2,
dp_rank: int = 0,
tp_size: int = 1,
dtype: torch.dtype = torch.int32,
) -> RoutedExpertsCapturer:
# Bypass __init__ so the test can use a CPU buffer and skip the
# VllmConfig dependency. The CUDA device-tensor allocation in the
@@ -49,10 +43,11 @@ def _capturer_with_buffer(
c = RoutedExpertsCapturer.__new__(RoutedExpertsCapturer)
c.dp_rank = dp_rank
c.tp_size = tp_size
c.output_dtype = torch.uint8
c.device_buffer = torch.full(
(max_tokens, num_layers, num_experts_per_tok),
-1,
dtype=torch.int32,
dtype=dtype,
)
return c
@@ -88,74 +83,36 @@ def _make_modular_routed_experts():
)
def _make_model_config(hf_config):
num_experts_per_token = ModelArchConfigConvertorBase(
hf_config, hf_config
).get_num_experts_per_token()
model_config = SimpleNamespace(
hf_text_config=hf_config,
model_arch_config=SimpleNamespace(
num_experts_per_token=num_experts_per_token,
def _full_attention_kv_group(
spec_type: type[FullAttentionSpec] = FullAttentionSpec,
) -> KVCacheGroupSpec:
full_attention = spec_type(
block_size=16,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
)
return KVCacheGroupSpec(
["layer"],
UniformTypeKVCacheSpecs(
block_size=16,
kv_cache_specs={"layer": full_attention},
),
)
model_config.get_num_experts = lambda: hf_config.num_experts
model_config.get_num_experts_per_tok = lambda: (
ModelConfig.get_num_experts_per_tok(model_config)
)
model_config.get_total_num_hidden_layers = lambda: hf_config.num_hidden_layers
return model_config
def test_routed_experts_manager_uses_gemma4_top_k_experts():
hf_config = SimpleNamespace(
num_experts=8,
top_k_experts=2,
num_hidden_layers=3,
)
vllm_config = SimpleNamespace(model_config=_make_model_config(hf_config))
kv_cache_spec = FullAttentionSpec(
block_size=4,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
)
kv_cache_config = KVCacheConfig(
num_blocks=2,
kv_cache_tensors=[],
kv_cache_groups=[KVCacheGroupSpec(["layer"], kv_cache_spec)],
)
@pytest.mark.parametrize("eplb_enabled", [False, True])
def test_base_router_capture_pre_eplb_mapping(eplb_enabled):
eplb_state = None
if eplb_enabled:
eplb_state = EplbLayerState()
eplb_state.expert_load_view = torch.zeros(32, dtype=torch.int64)
eplb_state.logical_to_physical_map = torch.arange(32).view(32, 1)
eplb_state.logical_replica_count = torch.ones(32, dtype=torch.int64)
eplb_state.should_record_tensor = torch.ones((), dtype=torch.bool)
eplb_state.num_unpadded_tokens_tensors = [torch.tensor(0, dtype=torch.int32)]
router = _make_router(eplb_state)
manager = RoutedExpertsManager(vllm_config, kv_cache_config)
assert manager.routed_experts_by_slot.shape == (8, 3, 2)
def test_routed_experts_manager_uses_kimi_k3_experts_per_token():
hf_config = SimpleNamespace(
num_experts=8,
num_experts_per_token=2,
num_hidden_layers=3,
)
vllm_config = SimpleNamespace(model_config=_make_model_config(hf_config))
kv_cache_spec = FullAttentionSpec(
block_size=4,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
)
kv_cache_config = KVCacheConfig(
num_blocks=2,
kv_cache_tensors=[],
kv_cache_groups=[KVCacheGroupSpec(["layer"], kv_cache_spec)],
)
manager = RoutedExpertsManager(vllm_config, kv_cache_config)
assert manager.routed_experts_by_slot.shape == (8, 3, 2)
def test_base_router_capture_pre_eplb_mapping():
router = _make_router()
captured = []
def capture_fn(ids):
@@ -173,34 +130,7 @@ def test_base_router_capture_pre_eplb_mapping():
assert torch.equal(topk_ids, torch.tensor([[11, 12], [13, 14]]))
def test_base_router_capture_with_eplb_enabled():
eplb_state = EplbLayerState()
eplb_state.expert_load_view = torch.zeros(32, dtype=torch.int64)
eplb_state.logical_to_physical_map = torch.arange(32).view(32, 1)
eplb_state.logical_replica_count = torch.ones(32, dtype=torch.int64)
eplb_state.should_record_tensor = torch.ones((), dtype=torch.bool)
eplb_state.num_unpadded_tokens_tensors = [torch.tensor(0, dtype=torch.int32)]
router = _make_router(eplb_state=eplb_state)
captured = []
def capture_fn(ids):
captured.append(ids.clone())
router.set_capture_fn(capture_fn)
_, topk_ids = router.select_experts(
hidden_states=torch.empty(1),
router_logits=torch.empty(1),
)
assert len(captured) == 1
# Capture should see logical ids pre-EPLB mapping.
assert torch.equal(captured[0], torch.tensor([[1, 2], [3, 4]]))
# Our DummyRouter mapping adds +10.
assert torch.equal(topk_ids, torch.tensor([[11, 12], [13, 14]]))
def test_public_binding_only_visits_target_model(monkeypatch):
def test_public_binding_binds_target_model_router(monkeypatch):
class DummyFusedMoE:
def __init__(self, layer_id):
self.layer_id = layer_id
@@ -208,7 +138,6 @@ def test_public_binding_only_visits_target_model(monkeypatch):
self._quant_method = _make_modular_routed_experts().quant_method
target_module = DummyFusedMoE(layer_id=7)
draft_module = DummyFusedMoE(layer_id=0)
import vllm.model_executor.layers.fused_moe.layer as fused_moe_layer
@@ -221,12 +150,30 @@ def test_public_binding_only_visits_target_model(monkeypatch):
)
assert target_module.router.capture_fn is not None
assert draft_module.router.capture_fn is None
topk_ids = torch.tensor([[5, 6]])
target_module.router.capture_fn(topk_ids)
assert calls == [(7, topk_ids)]
def test_public_binding_supports_direct_capture_source():
class DirectCaptureSource(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer_id = 3
self.capture_fn = None
source = DirectCaptureSource()
calls = []
capturer = types.SimpleNamespace(capture=lambda *args: calls.append(args))
bind_routed_experts_capturer(source, capturer)
assert source.capture_fn is not None
topk_ids = torch.tensor([[1, 2]])
source.capture_fn(topk_ids)
assert calls == [(3, topk_ids)]
def test_public_binding_rejects_monolithic_without_replay_support(monkeypatch):
class DummyFusedMoE:
def __init__(self):
@@ -277,6 +224,51 @@ def test_routed_experts_capturer_single_dp_no_metadata():
assert capturer.device_buffer[3, 0, 0].item() == -1
@pytest.mark.parametrize(
("num_experts", "dtype_name", "torch_dtype"),
[(256, "uint8", torch.uint8), (257, "uint16", torch.uint16)],
)
def test_routed_experts_capturer_exposes_output_profile(
monkeypatch, num_experts, dtype_name, torch_dtype
):
import vllm.model_executor.layers.fused_moe.routed_experts_capturer as module
monkeypatch.setattr(module, "current_platform", SimpleNamespace(device_type="cpu"))
config = SimpleNamespace(
model_config=SimpleNamespace(
get_total_num_hidden_layers=lambda: 3,
get_num_experts=lambda: num_experts,
get_num_experts_per_tok=lambda: 2,
hf_text_config=SimpleNamespace(model_type="test"),
),
parallel_config=SimpleNamespace(data_parallel_rank=0, tensor_parallel_size=1),
)
capturer = RoutedExpertsCapturer(8, config)
assert capturer.shape_per_token == (3, 2)
assert capturer.output_dtype_name == dtype_name
assert capturer.output_dtype == torch_dtype
assert capturer.device_buffer.shape == (8, 3, 2)
@pytest.mark.parametrize("output_dtype", [torch.uint8, torch.uint16])
def test_routed_experts_capturer_narrows_snapshot(output_dtype):
capturer = _capturer_with_buffer(dtype=torch.int32)
capturer.output_dtype = output_dtype
topk = torch.tensor([[1, 2], [254, 255]], dtype=torch.int64)
ctx = SimpleNamespace(dp_metadata=None)
with patch(f"{_REC_MODULE}.get_forward_context", return_value=ctx):
capturer.capture(layer_id=0, topk_ids=topk)
output = capturer.snapshot_routing_data(2)
assert capturer.device_buffer.dtype == torch.int32
assert capturer.device_buffer[:2, 0, :].tolist() == topk.tolist()
assert output.dtype == output_dtype
assert output[:, 0, :].tolist() == topk.tolist()
assert output.data_ptr() != capturer.device_buffer.data_ptr()
def test_routed_experts_capturer_dp_naive_concatenated_all_ranks():
"""N == sum(num_tokens_dp): slice this rank's segment from concatenated topk."""
capturer = _capturer_with_buffer(dp_rank=1)
@@ -307,6 +299,47 @@ def test_routed_experts_capturer_dp_modular_local_tokens():
assert torch.equal(capturer.device_buffer[:3, 0, :], topk)
def test_routed_experts_capturer_dp_ep_gathered_shards():
capturer = _capturer_with_buffer(dp_rank=1, tp_size=2)
num_tokens_dp = torch.tensor([3, 2], dtype=torch.int32)
ctx = SimpleNamespace(
dp_metadata=SimpleNamespace(
num_tokens_across_dp_cpu=num_tokens_dp,
local_sizes=[2, 2, 1, 1],
)
)
topk = torch.tensor(
[[0, 1], [2, 3], [4, 5], [-1, -1], [10, 11], [12, 13]],
dtype=torch.int32,
)
with patch(f"{_REC_MODULE}.get_forward_context", return_value=ctx):
capturer.capture(layer_id=0, topk_ids=topk)
assert torch.equal(capturer.device_buffer[:2, 0], topk[4:])
def test_routed_experts_capturer_sp_modular_gathers_tp_shards():
capturer = _capturer_with_buffer(dp_rank=1, tp_size=2)
num_tokens_dp = torch.tensor([2, 3], dtype=torch.int32)
ctx = SimpleNamespace(
dp_metadata=SimpleNamespace(num_tokens_across_dp_cpu=num_tokens_dp)
)
local_shard = torch.tensor([[10, 11], [12, 13]], dtype=torch.int32)
gathered = torch.tensor([[10, 11], [12, 13], [14, 15], [-1, -1]], dtype=torch.int32)
tp_group = Mock()
tp_group.all_gather.return_value = gathered
with (
patch(f"{_REC_MODULE}.get_forward_context", return_value=ctx),
patch(f"{_REC_MODULE}.get_tp_group", return_value=tp_group),
):
capturer.capture(layer_id=0, topk_ids=local_shard)
tp_group.all_gather.assert_called_once_with(local_shard, dim=0)
assert torch.equal(capturer.device_buffer[:3, 0], gathered[:3])
def test_routed_experts_capturer_dp_unexpected_batch_raises():
"""Mismatch between topk batch dim and DP layout: fail fast."""
capturer = _capturer_with_buffer(dp_rank=0)
@@ -324,128 +357,119 @@ def test_routed_experts_capturer_dp_unexpected_batch_raises():
assert capturer.device_buffer[0, 0, 0].item() == -1
def test_routed_experts_attention_group_is_shared_and_fail_closed():
"""Both sides key routing data by this gid, so it must skip non-full-attention
groups rather than defaulting to 0, and fail closed when none exists."""
common = dict(num_kv_heads=1, head_size=1, dtype=torch.float32)
def test_get_aux_output_connector_passes_config(monkeypatch):
import vllm.distributed.aux_output_connector.worker as aux_output_worker
connector = Mock()
constructor = Mock(return_value=connector)
monkeypatch.setattr(aux_output_worker, "AuxOutputWorkerConnector", constructor)
config = SimpleNamespace(
kv_cache_groups=[
KVCacheGroupSpec(
["swa_layer"],
SlidingWindowMLASpec(block_size=4, sliding_window=8, **common),
),
KVCacheGroupSpec(["full_layer"], FullAttentionSpec(block_size=4, **common)),
]
scheduler_config=SimpleNamespace(max_num_batched_tokens=32)
)
assert get_routed_experts_attn_gid(config) == 1
model = Mock()
kv_cache_config = Mock()
with pytest.raises(ValueError, match="requires a full-attention KV cache group"):
get_routed_experts_attn_gid(SimpleNamespace(kv_cache_groups=[]))
result = aux_output_worker.get_aux_output_connector(model, config, kv_cache_config)
def test_routed_experts_attention_group_unwraps_uniform_type_specs():
"""DeepSeek-V4-shaped groups wrap their specs in ``UniformTypeKVCacheSpecs``.
The wrapper is not a ``FullAttentionSpec``, so a bare isinstance check finds
no group and fails closed on every worker. Unwrap semantics themselves are
covered by ``test_is_full_attention_spec_*`` in tests/v1/core.
"""
common = dict(num_kv_heads=1, head_size=1, dtype=torch.float32)
swa_spec = SlidingWindowMLASpec(block_size=4, sliding_window=8, **common)
mla_spec = MLAAttentionSpec(block_size=4, **common)
config = SimpleNamespace(
kv_cache_groups=[
KVCacheGroupSpec(
["swa_layer"],
UniformTypeKVCacheSpecs(
block_size=4, kv_cache_specs={"swa_layer": swa_spec}
),
),
KVCacheGroupSpec(
["mla_layer"],
UniformTypeKVCacheSpecs(
block_size=4, kv_cache_specs={"mla_layer": mla_spec}
),
),
]
constructor.assert_called_once_with(
model=model,
kv_cache_config=kv_cache_config,
vllm_config=config,
)
assert get_routed_experts_attn_gid(config) == 1
swa_only = SimpleNamespace(kv_cache_groups=[config.kv_cache_groups[0]])
with pytest.raises(ValueError, match="requires a full-attention KV cache group"):
get_routed_experts_attn_gid(swa_only)
assert result is connector
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
def test_mrv2_async_output_returns_existing_routed_experts_field():
from vllm.v1.outputs import ModelRunnerOutput, RoutedExpertsTensors
from vllm.v1.worker.gpu.async_utils import AsyncOutput
from vllm.v1.worker.gpu.sample.output import SamplerOutput
routed_experts = RoutedExpertsTensors(
routing_data=torch.arange(6, dtype=torch.int32, device="cuda").reshape(3, 1, 2),
slot_mapping=torch.tensor([11, 12, 13], device="cuda"),
)
num_sampled = torch.tensor([1], dtype=torch.int32, device="cuda")
sampler_output = SamplerOutput(
sampled_token_ids=torch.tensor([[1]], device="cuda"),
logprobs_tensors=None,
num_nans=None,
num_sampled=num_sampled,
num_rejected=torch.tensor([0], dtype=torch.int32, device="cuda"),
)
output = AsyncOutput(
model_runner_output=ModelRunnerOutput(req_ids=["req"], req_id_to_index={}),
sampler_output=sampler_output,
num_sampled_tokens=num_sampled,
main_stream=torch.cuda.current_stream(),
copy_stream=torch.cuda.Stream(),
routed_experts=routed_experts,
).get_output()
assert output.routed_experts is not None
assert output.routed_experts.routing_data[:, 0, 0].tolist() == [0, 2, 4]
assert output.routed_experts.slot_mapping.tolist() == [11, 12, 13]
@pytest.mark.parametrize("rank", [0, 1])
def test_all_tp_ranks_initialize_capture(monkeypatch, rank):
pytest.importorskip("vllm.vllm_flash_attn", exc_type=ImportError)
import vllm.v1.worker.gpu.model_runner as model_runner
def test_aux_output_worker_connector_binds_capture_on_non_output_rank(monkeypatch):
import vllm.distributed.aux_output_connector.worker as aux_output_worker
capturer = Mock()
constructor = Mock(return_value=capturer)
bind = Mock()
monkeypatch.setattr(model_runner, "RoutedExpertsCapturer", constructor)
monkeypatch.setattr(model_runner, "bind_routed_experts_capturer", bind)
monkeypatch.setattr(aux_output_worker, "RoutedExpertsCapturer", constructor)
monkeypatch.setattr(aux_output_worker, "bind_routed_experts_capturer", bind)
monkeypatch.setattr(
aux_output_worker,
"get_tp_group",
lambda: SimpleNamespace(is_first_rank=False, world_size=1),
)
runner = model_runner.GPUModelRunner.__new__(model_runner.GPUModelRunner)
runner.max_num_tokens = 32
runner.vllm_config = SimpleNamespace(parallel_config=SimpleNamespace(rank=rank))
runner.kv_cache_config = SimpleNamespace()
runner.model = Mock()
runner.init_routed_experts_capturer()
config = SimpleNamespace(
aux_output_config=SimpleNamespace(enable_return_routed_experts=True),
kv_transfer_config=None,
max_concurrent_batches=2,
scheduler_config=SimpleNamespace(max_num_batched_tokens=32),
)
model = Mock()
connector = aux_output_worker.AuxOutputWorkerConnector(
vllm_config=config,
model=model,
kv_cache_config=SimpleNamespace(kv_cache_groups=[_full_attention_kv_group()]),
)
constructor.assert_called_once_with(
max_num_batched_tokens=32,
vllm_config=runner.vllm_config,
kv_cache_config=runner.kv_cache_config,
vllm_config=config,
)
bind.assert_called_once_with(runner.model, capturer)
assert runner.routed_experts_capturer is capturer
bind.assert_called_once_with(model, capturer)
connector.begin_step(Mock())
assert connector.prepare_output(Mock()) is None
capturer.snapshot_routing_data.assert_not_called()
def test_aux_output_worker_connector_default_capacity(monkeypatch):
import vllm.distributed.aux_output_connector.worker as aux_output_worker
tp_group = SimpleNamespace(is_first_rank=True, world_size=1)
store_constructor = Mock()
background_store_constructor = Mock(side_effect=lambda store, **_: store)
capturer = SimpleNamespace(shape_per_token=(2,), output_dtype_name="int32")
monkeypatch.setattr(aux_output_worker, "get_tp_group", lambda: tp_group)
monkeypatch.setattr(
aux_output_worker, "RoutedExpertsCapturer", Mock(return_value=capturer)
)
monkeypatch.setattr(aux_output_worker, "bind_routed_experts_capturer", Mock())
monkeypatch.setattr(
aux_output_worker,
"resolve_kv_cache_block_sizes",
lambda *_: (32, 16),
)
monkeypatch.setattr(aux_output_worker, "BlockObjectStore", store_constructor)
monkeypatch.setattr(
aux_output_worker, "BackgroundBlockObjectStore", background_store_constructor
)
monkeypatch.setattr(aux_output_worker, "RoutedExpertsBuffer", Mock())
config = SimpleNamespace(
aux_output_config=SimpleNamespace(max_bytes=None),
kv_transfer_config=None,
cache_config=SimpleNamespace(enable_prefix_caching=True),
scheduler_config=SimpleNamespace(max_num_seqs=8, max_num_batched_tokens=32),
max_concurrent_batches=2,
)
kwargs = dict(
vllm_config=config,
model=Mock(),
kv_cache_config=SimpleNamespace(
num_blocks=10,
kv_cache_groups=[_full_attention_kv_group(MLAAttentionSpec)],
),
)
aux_output_worker.AuxOutputWorkerConnector(**kwargs)
assert store_constructor.call_args.kwargs["max_bytes"] == 2560
assert store_constructor.call_args.kwargs["object_nbytes"] == 128
assert background_store_constructor.call_args.kwargs["max_pending_batches"] == 16
def test_v2_model_runner_accepts_routed_experts(monkeypatch):
monkeypatch.setattr("importlib.metadata.entry_points", lambda **_: ())
config = SimpleNamespace(
model_config=SimpleNamespace(
enable_return_routed_experts=True,
use_mla=False,
logits_processors=None,
enable_prompt_embeds=False,
),
aux_output_config=SimpleNamespace(enable_return_routed_experts=True),
speculative_config=None,
parallel_config=SimpleNamespace(
prefill_context_parallel_size=1,
+13 -4
View File
@@ -4,18 +4,23 @@
The decode path hands the kernel column slices of the merged ``q|k|v`` conv
output and of the fused ``qkvbfg_a`` projection (beta), so q/k/v/beta are
token-strided rather than contiguous. The kernel must read them in place,
match a pure-PyTorch recurrence, and reject layouts it cannot address.
token-strided rather than contiguous. Both backends must match a pure-PyTorch
recurrence. CUDA reads these slices in place and rejects unsupported layouts;
the ROCm wrapper makes contiguous copies before launching its kernel.
"""
import pytest
import torch
from vllm.models.glm5next.nvidia.ops.third_party.kda import fused_recurrent_kda
from vllm.platforms import current_platform
if current_platform.is_rocm():
from vllm.models.glm5next.amd.ops.third_party.kda import fused_recurrent_kda
else:
from vllm.models.glm5next.nvidia.ops.third_party.kda import fused_recurrent_kda
pytestmark = pytest.mark.skipif(
not current_platform.is_cuda(), reason="CUDA-only Triton kernel"
not current_platform.is_cuda_alike(), reason="Requires CUDA or ROCm"
)
H, D = 16, 128
@@ -160,6 +165,10 @@ def test_fused_recurrent_kda_strided_inputs_bit_identical_to_contiguous(
torch.testing.assert_close(state, state_ref, rtol=0, atol=0)
@pytest.mark.skipif(
not current_platform.is_cuda(),
reason="Only the CUDA implementation requires zero-copy token-strided layouts",
)
@torch.inference_mode()
def test_fused_recurrent_kda_rejects_unaddressable_layouts():
"""Layouts the token-stride addressing cannot express must fail loudly
@@ -0,0 +1,114 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GLM-5.3-Flash sequence-parallel MoE layout.
With DP > 1, TP > 1 and expert parallelism, ``Glm5NextModel`` shards the token
dimension across the TP group once at the model entry and every layer runs its
MLP on that shard. A module that still does tensor-parallel collectives there
sums the partial results of *different* tokens held by different ranks, so the
dense MLP of the first ``first_k_dense_replace`` layers must hold replicated
weights and run without any collective, like the shared experts already do.
"""
from types import SimpleNamespace
import pytest
import torch
from torch import nn
from vllm.model_executor import parameter
from vllm.model_executor.layers import linear
from vllm.models.glm5next.common import model as glm_model
from vllm.transformers_utils.configs.glm5_next import Glm5NextTextConfig
HIDDEN, INTERMEDIATE, TP_SIZE = 8, 16, 2
class _Attention(nn.Module):
def __init__(self, *args, **kwargs) -> None:
super().__init__()
self.o_proj = SimpleNamespace(reduce_results=True)
def _fake_tensor_parallel_world(monkeypatch) -> None:
"""Pretend to be rank 1 of a TP=2 group whose all-reduce must never run."""
def _forbidden_all_reduce(*args, **kwargs):
raise AssertionError("tensor-parallel all-reduce on a sequence-parallel shard")
for module in (linear, parameter):
monkeypatch.setattr(
module, "get_tensor_model_parallel_world_size", lambda: TP_SIZE
)
monkeypatch.setattr(module, "get_tensor_model_parallel_rank", lambda: 1)
monkeypatch.setattr(
linear, "tensor_model_parallel_all_reduce", _forbidden_all_reduce
)
def _reference_mlp(mlp: glm_model.Glm5NextMLP, x: torch.Tensor) -> torch.Tensor:
gate_up = x @ mlp.gate_up_proj.weight.T
gate, up = gate_up.split(INTERMEDIATE, dim=-1)
return (torch.nn.functional.silu(gate) * up) @ mlp.down_proj.weight.T
def _assert_runs_locally_on_shard(mlp: glm_model.Glm5NextMLP) -> None:
device = "cuda" if torch.cuda.is_available() else "cpu"
mlp.to(device)
assert mlp.gate_up_proj.weight.shape == (2 * INTERMEDIATE, HIDDEN)
assert mlp.down_proj.weight.shape == (HIDDEN, INTERMEDIATE)
torch.manual_seed(0)
for param in mlp.parameters():
param.data.normal_()
shard = torch.randn(3, HIDDEN, device=device)
torch.testing.assert_close(mlp(shard), _reference_mlp(mlp, shard))
def test_dense_mlp_runs_locally_on_the_sequence_parallel_shard(
monkeypatch, default_vllm_config
):
_fake_tensor_parallel_world(monkeypatch)
sharded = glm_model.Glm5NextMLP(HIDDEN, INTERMEDIATE, "silu")
assert sharded.down_proj.tp_size == TP_SIZE
assert sharded.gate_up_proj.weight.shape == (2 * INTERMEDIATE // TP_SIZE, HIDDEN)
_assert_runs_locally_on_shard(
glm_model.Glm5NextMLP(HIDDEN, INTERMEDIATE, "silu", is_sequence_parallel=True)
)
@pytest.mark.parametrize("use_sequence_parallel_moe", [True, False])
def test_dense_layer_mlp_follows_the_sequence_parallel_layout(
monkeypatch, default_vllm_config, use_sequence_parallel_moe: bool
):
_fake_tensor_parallel_world(monkeypatch)
monkeypatch.setattr(glm_model, "Glm5NextLinearAttention", _Attention)
monkeypatch.setattr(glm_model, "Glm5NextMLAAttention", _Attention)
config = Glm5NextTextConfig(
hidden_size=HIDDEN,
intermediate_size=INTERMEDIATE,
num_hidden_layers=2,
first_k_dense_replace=1,
n_routed_experts=4,
layer_types=["linear_attention", "deepseek_sparse_attention"],
mhc=False,
)
vllm_config = SimpleNamespace(
cache_config=None,
quant_config=None,
parallel_config=SimpleNamespace(
use_sequence_parallel_moe=use_sequence_parallel_moe
),
kernel_config=SimpleNamespace(enable_jit_warmup=False),
)
layer = glm_model.Glm5NextDecoderLayer(vllm_config, config, layer_idx=0)
assert isinstance(layer.mlp, glm_model.Glm5NextMLP)
assert layer.self_attn.o_proj.reduce_results is not use_sequence_parallel_moe
if use_sequence_parallel_moe:
_assert_runs_locally_on_shard(layer.mlp)
else:
assert layer.mlp.down_proj.tp_size == TP_SIZE
@@ -0,0 +1,72 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import torch
from torch import nn
from vllm.models.kimi_k3.amd.kda import KimiK3DeltaAttention
from vllm.models.kimi_k3.amd.linear import KimiDecoderLayer
class _ReturningAttention(nn.Module):
def __init__(self, result: torch.Tensor) -> None:
super().__init__()
self.result = result
def forward(
self, hidden_states: torch.Tensor, positions: torch.Tensor
) -> torch.Tensor:
return self.result
class _TupleProjection(nn.Module):
def __init__(self, result: torch.Tensor) -> None:
super().__init__()
self.result = result
def forward(self, _: torch.Tensor) -> tuple[torch.Tensor, None]:
return self.result, None
def _make_layer(self_attn: nn.Module) -> KimiDecoderLayer:
layer = object.__new__(KimiDecoderLayer)
nn.Module.__init__(layer)
layer.self_attn = self_attn
return layer
def test_kda_self_attention_returns_projection_storage_directly() -> None:
hidden_states = torch.randn(4, 8)
projected = torch.randn_like(hidden_states)
layer = _make_layer(_ReturningAttention(projected))
output = layer._run_self_attn(torch.arange(4), hidden_states)
assert output is projected
assert output.data_ptr() == projected.data_ptr()
def test_k3_kda_forward_returns_output_projection_storage() -> None:
hidden_states = torch.randn(4, 8)
projected = torch.randn_like(hidden_states)
def fill_core_output(**kwargs: torch.Tensor) -> None:
kwargs["core_attn_out"].fill_(1)
attention = SimpleNamespace(
local_projection_size=4,
head_dim=2,
local_num_heads=2,
in_proj_padding=0,
in_proj_qkvgfab=_TupleProjection(torch.randn(4, 20)),
f_b_proj=_TupleProjection(torch.randn(4, 4)),
o_proj=_TupleProjection(projected),
_forward=fill_core_output,
)
output = KimiK3DeltaAttention.forward(attention, hidden_states, torch.arange(4))
assert output is projected
assert output.data_ptr() == projected.data_ptr()
@@ -0,0 +1,38 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from torch import nn
from vllm.models.kimi_k3.amd.linear import KimiDecoderLayer, KimiMLAAttention
class _DirectMLA(KimiMLAAttention):
def __init__(self, result: torch.Tensor) -> None:
nn.Module.__init__(self)
self.result = result
def forward(
self,
positions: torch.Tensor,
hidden_states: torch.Tensor,
) -> torch.Tensor:
return self.result
def _make_layer(self_attn: nn.Module) -> KimiDecoderLayer:
layer = object.__new__(KimiDecoderLayer)
nn.Module.__init__(layer)
layer.self_attn = self_attn
return layer
def test_mla_self_attention_returns_projection_storage_directly() -> None:
hidden_states = torch.randn(4, 8)
projected = torch.randn_like(hidden_states)
layer = _make_layer(_DirectMLA(projected))
output = layer._run_self_attn(torch.arange(4), hidden_states)
assert output is projected
assert output.data_ptr() == projected.data_ptr()
+11 -31
View File
@@ -14,6 +14,10 @@ import torch.nn.functional as F
from vllm import _custom_ops as ops
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
from vllm.model_executor.layers.mamba.checkpoint import MambaPrefillCheckpointMetadata
from vllm.model_executor.layers.mamba.kda_checkpoint import (
FlashKDAPrefillCheckpointExporter,
)
from vllm.model_executor.layers.mamba.ops.causal_conv1d import causal_conv1d_update
from vllm.model_executor.layers.mamba.ops.gather_initial_states import (
gather_initial_states,
@@ -25,7 +29,6 @@ from vllm.models.kimi_k3.nvidia import kda as nvidia_kda
from vllm.models.kimi_k3.nvidia.kda import (
_flashinfer_kda_prefill,
_flashkda_prefill,
_store_cache_checkpoints_kernel,
is_flashinfer_fused_kda_decode_supported,
is_flashinfer_recurrent_kda_prefill_supported,
is_flashkda_supported,
@@ -1498,36 +1501,13 @@ def test_flashkda_checkpoint_correctness(state_dtype: torch.dtype, tolerance: fl
checkpoint_state_indices = torch.tensor(
[1, NULL_BLOCK_ID], dtype=torch.int32, device=DEVICE
)
state_len = conv_state.shape[-1]
width = H * D
recurrent_row_size = checkpoint_state[0].numel()
block_size = 256
_store_cache_checkpoints_kernel[
(
checkpoint_state_indices.numel(),
(max(width * state_len, recurrent_row_size) + block_size - 1) // block_size,
)
](
conv_input,
conv_state,
checkpoint_state,
recurrent_state,
cu_seqlens,
checkpoint_offsets,
checkpoint_state_indices,
conv_input.stride(0),
conv_input.stride(1),
conv_state.stride(0),
conv_state.stride(1),
conv_state.stride(2),
checkpoint_state.stride(0),
recurrent_state.stride(0),
checkpoint_offsets.stride(0),
state_len,
width,
recurrent_row_size,
NULL_BLOCK_ID,
block_size,
FlashKDAPrefillCheckpointExporter().export(
MambaPrefillCheckpointMetadata(checkpoint_offsets, checkpoint_state_indices),
raw_qkv=conv_input,
conv_state=conv_state,
recurrent_checkpoint=checkpoint_state,
recurrent_state=recurrent_state,
cu_seqlens=cu_seqlens,
)
torch.testing.assert_close(conv_state[1], q[0, 13:16].flatten(1).transpose(0, 1))
torch.testing.assert_close(recurrent_state[1], checkpoint_state[0])
@@ -0,0 +1,31 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from torch import nn
from vllm.models.kimi_k3.nvidia.model import KimiDecoderLayer
class _ReturningSharedKDA(nn.Module):
def __init__(self, result: torch.Tensor) -> None:
super().__init__()
self.result = result
def forward(
self, hidden_states: torch.Tensor, positions: torch.Tensor
) -> torch.Tensor:
return self.result
def test_low_rank_kda_caller_returns_projection_storage_directly() -> None:
hidden_states = torch.randn(4, 8)
projected = torch.randn_like(hidden_states)
layer = object.__new__(KimiDecoderLayer)
nn.Module.__init__(layer)
layer.self_attn = _ReturningSharedKDA(projected)
output = layer._run_self_attn(torch.arange(4), hidden_states)
assert output is projected
assert output.data_ptr() == projected.data_ptr()
@@ -158,7 +158,9 @@ def test_models(
hf_model.model.device
)
if prompt_embeds is not None:
embed = hf_model.model.get_input_embeddings()(token_ids)
# Retained prompt values must not keep reference weights alive.
with torch.no_grad():
embed = hf_model.model.get_input_embeddings()(token_ids)
# MiniCPM models apply scale_emb to embeddings internally.
# vLLM expects pre-scaled embeddings when using inputs_embeds.
@@ -33,6 +33,8 @@ def release_gpu_memory_between_tests():
gc.collect()
if torch.accelerator.is_available():
torch.accelerator.empty_cache()
if current_platform.is_rocm():
return
try:
wait_for_memory_to_settle()
except ValueError as e:
@@ -9,6 +9,7 @@ import torch
from tests.utils import wait_for_memory_to_settle
from vllm.logger import init_logger
from vllm.platforms import current_platform
logger = init_logger(__name__)
@@ -26,6 +27,8 @@ def release_gpu_memory_between_tests():
gc.collect()
if torch.accelerator.is_available():
torch.accelerator.empty_cache()
if current_platform.is_rocm():
return
try:
wait_for_memory_to_settle()
except ValueError as e:
@@ -151,10 +151,12 @@ VLM_TEST_SETTINGS = {
img_idx_to_prompt=lambda idx: "<|vision_start|><|image_pad|><|vision_end|>",
video_idx_to_prompt=lambda idx: "<|vision_start|><|video_pad|><|vision_end|>",
enforce_eager=False,
needs_video_metadata=True,
max_model_len=4096,
max_num_seqs=2,
auto_cls=AutoModelForImageTextToText,
vllm_output_post_proc=model_utils.qwen2_vllm_to_hf_output,
patch_hf_runner=model_utils.qwen3_vl_patch_hf_runner,
image_size_factors=[(0.25,), (0.25, 0.25, 0.25), (0.25, 0.2, 0.15)],
marks=[pytest.mark.core_model, pytest.mark.cpu_model],
),
@@ -4,10 +4,10 @@
import pytest
from vllm.assets.image import ImageAsset
from vllm.multimodal.video import sample_frames_from_video
from vllm.platforms import current_platform
from ....conftest import VIDEO_ASSETS
from .vlm_utils.builders import sample_frames_with_video_metadata
models = ["Qwen/Qwen2.5-VL-3B-Instruct"]
target_dtype = "bfloat16"
@@ -81,7 +81,9 @@ def test_qwen2_5_vl_evs_functionality(
# Sample frames from video assets
sampled_vids = [
sample_frames_from_video(asset.np_ndarrays, num_frames)
sample_frames_with_video_metadata(
(asset.np_ndarrays, asset.metadata), num_frames
)
for asset in video_assets
]
@@ -145,7 +147,9 @@ def test_qwen2_5_vl_evs_batched_videos(
monkeypatch.setenv("VLLM_USE_BYTECODE_HOOK", "1" if use_bytecode_hook else "0")
# Sample frames from video assets
sampled_vids = [
sample_frames_from_video(asset.np_ndarrays, num_frames)
sample_frames_with_video_metadata(
(asset.np_ndarrays, asset.metadata), num_frames
)
for asset in video_assets
]
@@ -144,7 +144,7 @@ MODEL_CONFIGS: dict[str, VitCudagraphTestConfig] = {
"<|vision_start|><|video_pad|><|vision_end|>"
"Describe this video in one sentence."
),
needs_video_metadata=False,
needs_video_metadata=True,
marks=[pytest.mark.core_model],
),
"kimi_vl": VitCudagraphTestConfig(
@@ -236,7 +236,11 @@ MODEL_CONFIGS: dict[str, VitCudagraphTestConfig] = {
},
vllm_runner_kwargs={
"load_format": "dummy",
"attention_backend": "FLASHMLA_SPARSE_DSV41",
"attention_backend": (
"ROCM_FLASHMLA_SPARSE_DSV4"
if current_platform.is_rocm()
else "FLASHMLA_SPARSE_DSV41"
),
"hf_overrides": partial(
dummy_hf_overrides,
model_arch="DeepseekV41ForCausalLM",
@@ -9,6 +9,7 @@ import torch
from tests.utils import wait_for_memory_to_settle
from vllm.logger import init_logger
from vllm.platforms import current_platform
logger = init_logger(__name__)
@@ -26,6 +27,8 @@ def release_gpu_memory_between_tests():
gc.collect()
if torch.accelerator.is_available():
torch.accelerator.empty_cache()
if current_platform.is_rocm():
return
try:
wait_for_memory_to_settle()
except ValueError as e:
@@ -3,7 +3,7 @@
import pytest
import torch
import torch.nn as nn
from transformers import AutoConfig, AutoModel, CLIPImageProcessor
from transformers import AutoConfig, AutoModel, CLIPImageProcessor, PreTrainedModel
from vllm.distributed import cleanup_dist_env_and_memory
from vllm.platforms import current_platform
@@ -12,11 +12,6 @@ from vllm.utils.torch_utils import STR_DTYPE_TO_TORCH_DTYPE
from ....conftest import ImageTestAssets
pytestmark = pytest.mark.skip(
reason="InternVisionModel's custom code is incompatible with "
"transformers v5 (missing all_tied_weights_keys)"
)
# we use snapshot_download to prevent conflicts between
# dynamic_module and trust_remote_code for hf_runner
DOWNLOAD_PATTERN = ["*.json", "*.py", "*.safetensors", "*.txt", "*.model"]
@@ -45,9 +40,23 @@ def run_intern_vit_test(
if not getattr(config, "norm_type", None):
config.norm_type = "rms_norm"
hf_model = AutoModel.from_pretrained(
model, dtype=torch_dtype, trust_remote_code=True
).to(DEVICE_TYPE)
# Monkey-patch for transformers v5 compatibility: InternVisionModel's
# custom code doesn't call post_init(), so all_tied_weights_keys is
# never set. Remove once https://github.com/OpenGVLab/InternVL fixes it.
_orig_init = PreTrainedModel.__init__
def _patched_init(self, *args, **kwargs):
_orig_init(self, *args, **kwargs)
self.all_tied_weights_keys = {}
PreTrainedModel.__init__ = _patched_init
try:
hf_model = AutoModel.from_pretrained(
model, dtype=torch_dtype, trust_remote_code=True
).to(DEVICE_TYPE)
finally:
PreTrainedModel.__init__ = _orig_init
hf_outputs_per_image = [
hf_model(pixel_value.to(DEVICE_TYPE)).last_hidden_state
for pixel_value in pixel_values
@@ -22,7 +22,7 @@ import numpy as np
import pytest
from vllm.multimodal import MULTIMODAL_REGISTRY
from vllm.multimodal.cache import MultiModalProcessorSenderCache
from vllm.multimodal.cache import LruKeyReplicatedSenderCache
from ....multimodal.utils import random_audio, random_video
from ...utils import build_model_context
@@ -68,7 +68,7 @@ def test_audio_in_video_cache_correctness(model_id: str, num_videos: int) -> Non
# Sender cache: on a cache hit returns (None, prompt_updates) for each
# item, setting mm_kwargs["video"] = [None] – the exact condition that
# triggered the original bug.
sender_cache = MultiModalProcessorSenderCache(ctx.model_config)
sender_cache = LruKeyReplicatedSenderCache(ctx.model_config)
video_token_id = processor.info.get_hf_config().video_token_id
@@ -159,7 +159,6 @@ def get_token_prompt(
processor: BaseMultiModalProcessor,
mm_data: MultiModalDataDict,
) -> list[int]:
dummy_inputs = processor.dummy_inputs
tokenizer: TokenizerLike = processor.info.get_tokenizer()
model_config = processor.info.ctx.model_config
@@ -174,7 +173,7 @@ def get_token_prompt(
mm_counts = {k: len(vs) for k, vs in parsed_data.items()}
if is_mistral_tokenizer(tokenizer):
inputs = dummy_inputs.get_dummy_processor_inputs(
inputs = processor.get_dummy_inputs(
model_config.max_model_len,
mm_counts,
mm_options=MultiModalDummyOptions(),
@@ -182,7 +181,7 @@ def get_token_prompt(
mm_data=mm_data, # type: ignore[call-arg]
)
else:
inputs = dummy_inputs.get_dummy_processor_inputs(
inputs = processor.get_dummy_inputs(
model_config.max_model_len,
mm_counts,
mm_options=MultiModalDummyOptions(),
@@ -5,7 +5,7 @@
import pytest
import torch
from PIL import Image
from transformers import BatchFeature
from transformers import AutoProcessor, BatchFeature
from vllm.model_executor.models.lightonocr import LightOnOCRProcessingInfo
from vllm.model_executor.models.mistral3 import Mistral3HFEncoderInfo
@@ -22,25 +22,41 @@ _MODEL_ID = "mistralai/Mistral-Small-3.1-24B-Instruct-2503"
_LIGHTON_MODEL_ID = "lightonai/LightOnOCR-1B-1025"
def _processed_pixel_values(
def _process_images_with_hf(
hf_processor,
images: list[Image.Image],
mm_processor_kwargs: dict[str, object],
) -> list[torch.Tensor]:
"""Resize via the HF image processor and un-pad to per-image H×W."""
image_processor = hf_processor.image_processor
hf_out = image_processor(images=images, return_tensors="pt", **mm_processor_kwargs)
) -> tuple[list[torch.Tensor], list[int]]:
"""Process images and placeholders through the public HF processor."""
hf_out = hf_processor(
text=hf_processor.image_token * len(images),
images=images,
return_tensors="pt",
**mm_processor_kwargs,
)
pixel_values = hf_out["pixel_values"]
image_sizes = hf_out["image_sizes"]
return [p[:, :h, :w] for p, (h, w) in zip(pixel_values, image_sizes)]
unpadded = [p[:, :h, :w] for p, (h, w) in zip(pixel_values, image_sizes)]
special_token_ids = {
hf_processor.image_token_id,
hf_processor.image_break_token_id,
hf_processor.image_end_token_id,
}
placeholder_tokens = [
token_id
for token_id in hf_out["input_ids"][0].tolist()
if token_id in special_token_ids
]
return unpadded, placeholder_tokens
def _placeholder_count_from_prompt_updates(
def _placeholder_tokens_from_prompt_updates(
processor,
images: list[Image.Image],
pixel_values: list[torch.Tensor],
mm_processor_kwargs: dict[str, object],
) -> int:
) -> list[int]:
hf_inputs = BatchFeature({"pixel_values": pixel_values})
fields_config = processor._get_mm_fields_config(hf_inputs, mm_processor_kwargs)
out_mm_kwargs = MultiModalKwargsItems.from_hf_inputs(hf_inputs, fields_config)
@@ -49,13 +65,11 @@ def _placeholder_count_from_prompt_updates(
updates = processor._get_prompt_updates(
mm_items, mm_processor_kwargs, out_mm_kwargs
)
image_token_id = processor.info.get_hf_config().image_token_index
total = 0
placeholder_tokens: list[int] = []
for item_idx in range(len(images)):
details = updates[0].resolve(item_idx).content
total += details.full.count(image_token_id)
return total
placeholder_tokens.extend(details.full)
return placeholder_tokens
def _expected_placeholder_tokens_per_image(
@@ -72,12 +86,12 @@ def _expected_placeholder_tokens_per_image(
patch_h = patch_w = int(patch_size)
spatial_merge_size = getattr(hf_processor, "spatial_merge_size", 1)
assert image_h % patch_h == 0
assert image_w % patch_w == 0
merged_patch_h = patch_h * spatial_merge_size
merged_patch_w = patch_w * spatial_merge_size
assert image_h % merged_patch_h == 0
assert image_w % merged_patch_w == 0
return (image_h // (patch_h * spatial_merge_size)) * (
image_w // (patch_w * spatial_merge_size)
)
return (image_h // merged_patch_h) * (image_w // merged_patch_w)
@pytest.mark.parametrize("model_id", [_MODEL_ID])
@@ -87,8 +101,8 @@ def _expected_placeholder_tokens_per_image(
({}, (448, 448), 256),
({"size": {"longest_edge": 1008}}, (1540, 1540), 1296),
({"size": {"longest_edge": 1288}}, (1536, 1187), 1656),
({"size": {"longest_edge": 1008}}, (29, 29), 1),
({"size": {"longest_edge": 1000}}, (1540, 1700), 1152),
({"size": {"longest_edge": 1008}}, (29, 29), 4),
({"size": {"longest_edge": 1000}}, (1540, 1700), 1188),
],
)
@pytest.mark.parametrize("num_imgs", [1, 2])
@@ -109,21 +123,29 @@ def test_processor_size_override(
)
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
hf_processor_mm_kwargs = {} if kwargs_on_init else mm_processor_kwargs
hf_processor = processor.info.get_hf_processor(**hf_processor_mm_kwargs)
hf_processor = AutoProcessor.from_pretrained(
model_id,
fix_mistral_regex=True,
)
dummy_image = Image.new("RGB", image_size, color=(127, 127, 127))
images = [dummy_image] * num_imgs
merged_mm_kwargs = processor.info.ctx.get_merged_mm_kwargs(hf_processor_mm_kwargs)
pixel_values = _processed_pixel_values(hf_processor, images, merged_mm_kwargs)
pixel_values, hf_placeholder_tokens = _process_images_with_hf(
hf_processor, images, merged_mm_kwargs
)
image_token_count = _placeholder_count_from_prompt_updates(
prompt_update_tokens = _placeholder_tokens_from_prompt_updates(
processor, images, pixel_values, hf_processor_mm_kwargs
)
expected_from_pixel_values = _expected_placeholder_tokens_per_image(
hf_processor, pixel_values[0]
)
assert expected_from_pixel_values == expected_toks_per_img
assert image_token_count == expected_from_pixel_values * num_imgs
assert hf_placeholder_tokens.count(hf_processor.image_token_id) == (
expected_from_pixel_values * num_imgs
)
assert prompt_update_tokens == hf_placeholder_tokens
def test_lightonocr_keeps_vision_config_image_size():
@@ -1,6 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import numpy as np
import pytest
import torch
from PIL import Image
@@ -208,6 +211,35 @@ def test_get_image_size_with_most_features(
assert tokens < max_tokens
def _build_qwen2_5_vl_video_mm_data(num_frames: int, fps: float) -> dict[str, Any]:
video = np.zeros((num_frames, 56, 56, 3), dtype=np.uint8)
metadata = {
"fps": fps,
"duration": num_frames / fps,
"total_num_frames": num_frames,
"frames_indices": list(range(num_frames)),
"video_backend": "opencv",
"do_sample_frames": False,
}
return {"video": [(video, metadata)]}
@pytest.mark.parametrize("model_id", ["Qwen/Qwen2.5-VL-3B-Instruct"])
def test_qwen2_5_vl_video_fps_to_second_per_grid_ts(model_id: str) -> None:
ctx = build_model_context(model_id, limit_mm_per_prompt={"image": 0, "video": 1})
processor = MULTIMODAL_REGISTRY.create_processor(ctx.model_config)
temporal_patch_size = (
processor.info.get_hf_processor().video_processor.temporal_patch_size
)
prompt = "<|vision_start|><|video_pad|><|vision_end|>"
for fps in (1.0, 30.0):
mm_data = _build_qwen2_5_vl_video_mm_data(num_frames=32, fps=fps)
processed = processor(prompt, mm_items=processor.info.parse_mm_data(mm_data))
spg = processed["mm_kwargs"]["video"][0].get_data()["second_per_grid_ts"]
assert float(spg) == pytest.approx(temporal_patch_size / fps, rel=2e-2)
@pytest.mark.parametrize(
"model_id", ["Qwen/Qwen2-VL-2B-Instruct", "Qwen/Qwen2.5-VL-3B-Instruct"]
)
@@ -90,13 +90,12 @@ def create_batched_mm_kwargs(
size_factors: tuple[float, ...] = (1.0, 0.5, 0.25),
) -> Iterable[tuple[str, int, BatchedTensorInputs]]:
processing_info = processor.info
dummy_inputs = processor.dummy_inputs
supported_mm_limits = processing_info.get_supported_mm_limits()
mm_counts = {
modality: 3 if limit is None else limit
for modality, limit in supported_mm_limits.items()
}
processor_inputs = dummy_inputs.get_dummy_processor_inputs(
processor_inputs = processor.get_dummy_inputs(
seq_len=model_config.max_model_len,
mm_counts=mm_counts,
mm_options=MultiModalDummyOptions(),

Some files were not shown because too many files have changed in this diff Show More