Merge branch 'main' into qwen4exp-qsa-fused-draft-metadata

This commit is contained in:
vr8vr8
2026-09-23 23:37:13 +03:00
committed by GitHub
74 changed files with 3474 additions and 387 deletions
+4 -1
View File
@@ -128,8 +128,11 @@ FUSION_LOG_PATTERNS: dict[str, re.Pattern] = {
),
"rms_quant_fusion": re.compile(r"rms_quant_fusion.py:\d+] Replaced (\d+) patterns"),
"act_quant_fusion": re.compile(r"act_quant_fusion.py:\d+] Replaced (\d+) patterns"),
# The combined pass can consume these sites before the standalone pass.
"norm_rope_fusion": re.compile(
r"qk_norm_rope_fusion.py:\d+] Fused QK Norm\+RoPE on (\d+) sites"
r"(?:qk_norm_rope_fusion.py:\d+] Fused QK Norm\+RoPE on|"
r"qk_norm_rope_kvcache_fusion.py:\d+] "
r"QK-Norm\+RoPE(?:/MRoPE)?\+KVCache fusion: replaced) (\d+)"
),
"attn_quant_fusion": re.compile(
r"attn_quant_fusion.py:\d+] Fused quant onto (\d+) attention nodes"
+15 -2
View File
@@ -182,7 +182,11 @@ def run_e2e_fusion_test(monkeypatch, caplog_mp_spawn):
# TODO: Remove log counting in unit tests
# once all matchers implement VllmFusionPatternMatcherPass
n_expected = tp_size * num_ranges_activated
if match_name not in ("attn_quant_fusion", "act_quant_fusion"):
if match_name not in (
"attn_quant_fusion",
"act_quant_fusion",
"norm_rope_fusion",
):
assert len(log_matches) == n_expected, (
f"Could not find {n_expected} {match_name} "
f"(found {len(log_matches)}) in:\n {log_holder.text}"
@@ -190,7 +194,16 @@ def run_e2e_fusion_test(monkeypatch, caplog_mp_spawn):
expected_matches = getattr(matches, match_name)
if match_name == "rms_quant_fusion" and "ar_rms_fusion" in matches_check:
if match_name == "norm_rope_fusion":
# Opaque LayerName lets the combined pass consume short-range
# sites before the standalone pass; count either owner.
assert len(log_matches) >= n_expected
assert all(m in (0, expected_matches) for m in log_matches)
assert sum(log_matches) == expected_matches * n_expected, (
f"{match_name} expected {expected_matches * n_expected} "
f"sites across both passes, found: {log_matches}"
)
elif match_name == "rms_quant_fusion" and "ar_rms_fusion" in matches_check:
# AR+rms+quant takes precedence over rms+quant if activated.
# That means we get full matching where ar+rms+quant was not
# activated, and less where it was (only the smallest range).
@@ -8,6 +8,7 @@ import pytest
import torch
from packaging.version import Version
import vllm.compilation.passes.fusion.qk_norm_rope_kvcache_fusion as fusion_module
import vllm.config
from tests.compile.backend import TestBackend
from tests.v1.attention.utils import (
@@ -15,8 +16,12 @@ from tests.v1.attention.utils import (
create_common_attn_metadata,
dense_kv_cache_views,
)
from vllm._aiter_ops import is_aiter_found_and_supported, rocm_aiter_ops
from vllm.compilation.passes.fusion.matcher_utils import ROTARY_OP
from vllm._aiter_ops import (
IS_AITER_FOUND,
is_aiter_found_and_supported,
rocm_aiter_ops,
)
from vllm.compilation.passes.fusion.matcher_utils import MROPE_OP, ROTARY_OP
from vllm.compilation.passes.fusion.qk_norm_rope_kvcache_fusion import (
QkNormRopeKvCacheFusionPass,
)
@@ -37,8 +42,12 @@ from vllm.config import (
from vllm.forward_context import get_forward_context, set_forward_context
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.quantization.quark.quark import QuarkConfig
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
from vllm.model_executor.layers.rotary_embedding import RotaryEmbedding
from vllm.model_executor.layers.rotary_embedding.mrope import MRotaryEmbedding
from vllm.platforms import current_platform
from vllm.utils.torch_utils import _USE_LAYERNAME, _encode_layer_name
from vllm.v1.attention.backend import (
AttentionBackend,
CommonAttentionMetadata,
@@ -94,6 +103,7 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
device: torch.device,
rotary_dim: int | None = None,
prefix: str = "model.layers.0.self_attn.attn",
expected_query_quant_group_shape: GroupShape | None = None,
):
super().__init__()
self.num_heads = num_heads
@@ -133,6 +143,9 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
attn_backend=attn_backend.get_class(),
)
self.attn_backend: type[AttentionBackend] = self.attn.get_attn_backend()
if expected_query_quant_group_shape is not None:
assert self.attn.query_quant is not None
assert self.attn.query_quant.group_shape == expected_query_quant_group_shape
assert not self.attn_backend.forward_includes_kv_cache_update, (
f"Attention backend {self.attn_backend} does not support "
"fuse_qk_norm_rope_kvcache."
@@ -227,18 +240,15 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
self.kv_cache_dtype != self.dtype
and self.attn.impl.supports_quant_query_input
):
q_fp8 = torch.empty_like(q, dtype=FP8_DTYPE)
torch.ops.vllm.rocm_aiter_per_tensor_quant(
q_fp8, q, self.attn._q_scale, False
)
q = q_fp8
assert self.attn.query_quant is not None
q, _ = self.attn.query_quant(q, self.attn._q_scale)
# Final views + KV cache update
q = q.view(-1, self.num_heads, self.head_size)
k = k.view(-1, self.num_kv_heads, self.head_size)
v = v.view(-1, self.num_kv_heads, self.head_size)
kv_cache_dummy_dep = torch.ops.vllm.unified_kv_cache_update(
k, v, self.layer_name
k, v, _encode_layer_name(self.layer_name)
)
return q, k, v, kv_cache_dummy_dep
@@ -260,6 +270,64 @@ class QKNormRoPEKVCacheTestModel(torch.nn.Module):
return [torch.ops.vllm.fused_qk_norm_rope_and_unified_kv_cache_update.default]
class QKNormMRoPEKVCacheTestModel(QKNormRoPEKVCacheTestModel):
def __init__(
self,
*,
mrope_section: tuple[int, int, int],
mrope_interleaved: bool,
**kwargs,
):
super().__init__(**kwargs)
self.rotary_emb = MRotaryEmbedding(
self.head_size,
rotary_dim=self.rotary_dim,
max_position_embeddings=4096,
base=10000,
is_neox_style=self.is_neox,
dtype=self.dtype,
mrope_section=list(mrope_section),
mrope_interleaved=mrope_interleaved,
)
self.enable_rope_custom_op = self.rotary_emb.enabled()
def forward(
self, qkv: torch.Tensor, positions: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
q, k, v, kv_cache_dummy_dep = super().forward(qkv, positions)
output = torch.empty(
q.shape[0],
self.num_heads * self.head_size,
device=q.device,
dtype=self.dtype,
)
torch.ops.vllm.unified_attention_with_output(
q,
k,
v,
output,
_encode_layer_name(self.layer_name),
kv_cache_dummy_dep=kv_cache_dummy_dep,
)
# Production decoder attention consumes K from the cache rather than
# its direct K argument. Returning `output` keeps that production user
# in the graph without exposing K to an unsupported consumer.
return q, output, v, kv_cache_dummy_dep
def ops_in_model_before(self) -> list[torch._ops.OpOverload]:
return [MROPE_OP, torch.ops.vllm.unified_kv_cache_update.default]
def ops_in_model_after(self) -> list[torch._ops.OpOverload]:
return [torch.ops.vllm.fused_qk_norm_mrope_and_unified_kv_cache_update.default]
class QKNormMRoPEObservableKTestModel(QKNormMRoPEKVCacheTestModel):
def forward(
self, qkv: torch.Tensor, positions: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
return QKNormRoPEKVCacheTestModel.forward(self, qkv, positions)
def _run_qk_norm_rope_kvcache_fusion_test(
*,
attn_backend: AttentionBackendEnum,
@@ -278,18 +346,33 @@ def _run_qk_norm_rope_kvcache_fusion_test(
rms_norm_eps: float,
custom_op: str,
monkeypatch: pytest.MonkeyPatch,
mrope_section: tuple[int, int, int] | None = None,
mrope_interleaved: bool = False,
observe_mrope_k: bool = False,
expect_fusion: bool = True,
use_quark_scalar_query_scale: bool = False,
) -> None:
device = os.environ.get("VLLM_TEST_CUDA_DEVICE", "cuda")
torch.set_default_device(device)
torch.set_default_dtype(dtype)
torch.manual_seed(0)
# Set AITER toggles before VllmConfig initialization enables env caching.
monkeypatch.setenv("VLLM_ROCM_USE_AITER", "1")
monkeypatch.setenv("VLLM_ROCM_USE_AITER_LINEAR", "1")
rocm_aiter_ops.refresh_env_variables()
vllm_config = VllmConfig(
model_config=ModelConfig(dtype=dtype),
cache_config=CacheConfig(
block_size=block_size,
cache_dtype=kv_cache_dtype,
),
quant_config=(
QuarkConfig(quant_config={"exclude": []})
if use_quark_scalar_query_scale
else None
),
compilation_config=CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
custom_ops=[custom_op],
@@ -302,6 +385,7 @@ def _run_qk_norm_rope_kvcache_fusion_test(
with vllm.config.set_current_vllm_config(vllm_config), monkeypatch.context() as m:
m.setenv("VLLM_ROCM_USE_AITER", "1")
m.setenv("VLLM_ROCM_USE_AITER_LINEAR", "1")
m.setenv(
"VLLM_ROCM_USE_AITER_TRITON_ROPE",
"1" if enable_aiter_triton_rope else "0",
@@ -309,18 +393,49 @@ def _run_qk_norm_rope_kvcache_fusion_test(
m.setenv("VLLM_ROCM_SHUFFLE_KV_CACHE_LAYOUT", use_shuffle_kv_layout)
rocm_aiter_ops.refresh_env_variables()
model = QKNormRoPEKVCacheTestModel(
vllm_config=vllm_config,
attn_backend=attn_backend,
num_heads=num_heads,
num_kv_heads=num_kv_heads,
head_size=head_size,
rotary_dim=rotary_dim,
is_neox=is_neox,
rms_norm_eps=rms_norm_eps,
dtype=dtype,
device=torch.get_default_device(),
)
expected_query_quant_group_shape = None
if use_quark_scalar_query_scale:
expected_query_quant_group_shape = (
GroupShape(-1, num_heads * head_size)
if num_kv_heads == 1
else GroupShape.PER_TENSOR
)
model_kwargs = {
"vllm_config": vllm_config,
"attn_backend": attn_backend,
"num_heads": num_heads,
"num_kv_heads": num_kv_heads,
"head_size": head_size,
"rotary_dim": rotary_dim,
"is_neox": is_neox,
"rms_norm_eps": rms_norm_eps,
"dtype": dtype,
"device": torch.get_default_device(),
"expected_query_quant_group_shape": expected_query_quant_group_shape,
}
if mrope_section is None:
model = QKNormRoPEKVCacheTestModel(**model_kwargs)
else:
alternate_section = (8, 8, 8)
m.setattr(
fusion_module,
"_discover_mrope_configs",
lambda _: (
(mrope_section, mrope_interleaved),
(alternate_section, not mrope_interleaved),
),
)
model_cls = (
QKNormMRoPEObservableKTestModel
if observe_mrope_k
else QKNormMRoPEKVCacheTestModel
)
model = model_cls(
**model_kwargs,
mrope_section=mrope_section,
mrope_interleaved=mrope_interleaved,
)
fusion_pass = QkNormRopeKvCacheFusionPass(vllm_config)
passes = [
@@ -337,7 +452,12 @@ def _run_qk_norm_rope_kvcache_fusion_test(
num_heads * head_size + 2 * num_kv_heads * head_size,
dtype=dtype,
)
pos = torch.arange(num_tokens, dtype=torch.long)
if mrope_section is None:
pos = torch.arange(num_tokens, dtype=torch.long)
else:
# Real Qwen-VL position IDs can be a strided [3, N] view.
pos = torch.randint(0, 4096, (3, 2 * num_tokens), dtype=torch.long)[:, ::2]
assert not pos.is_contiguous()
qkv_unfused = qkv.clone()
pos_unfused = pos.clone()
@@ -356,7 +476,7 @@ def _run_qk_norm_rope_kvcache_fusion_test(
# Run fused (compiled) forward
torch._dynamo.mark_dynamic(qkv, 0)
torch._dynamo.mark_dynamic(pos, 0)
torch._dynamo.mark_dynamic(pos, 0 if mrope_section is None else 1)
with set_forward_context(None, vllm_config):
model_fused = torch.compile(model, backend=backend)
forward_context = get_forward_context()
@@ -369,14 +489,33 @@ def _run_qk_norm_rope_kvcache_fusion_test(
kv_cache_fused = attn_layer.kv_cache
del dummy
assert fusion_pass.matched_count == 1
assert fusion_pass.matched_count == int(expect_fusion)
backend.check_before_ops(model.ops_in_model_before())
backend.check_after_ops(model.ops_in_model_after())
if expect_fusion:
backend.check_before_ops(model.ops_in_model_before())
backend.check_after_ops(model.ops_in_model_after())
else:
for op in model.ops_in_model_before():
assert backend.op_count(op, before=True) > 0
assert backend.op_count(op) > 0
if use_quark_scalar_query_scale:
expected_quant_op = (
torch.ops.vllm.rocm_aiter_per_tensor_quant.default
if num_kv_heads != 1
else torch.ops._C.static_scaled_fp8_quant.default
)
assert backend.op_count(expected_quant_op, before=True) > 0
# Query quantization remains separate after the prologue fusion.
assert backend.op_count(expected_quant_op) > 0
# Sweep-backed (18.2k pts, PR #42749): native-rope ref worst 7.7e-3 -> 1e-2;
# AITER-triton-rope ref is itself approximate (plateau 1.28e-2) -> 2e-2.
ATOL, RTOL = (2e-2, 2e-2) if enable_aiter_triton_rope else (1e-2, 1e-2)
ATOL, RTOL = (
(2e-2, 2e-2)
if enable_aiter_triton_rope or mrope_section is not None
else (1e-2, 1e-2)
)
is_fp8_cache = model.kv_cache_dtype != dtype
if q_fused.dtype == FP8_DTYPE:
@@ -387,7 +526,7 @@ def _run_qk_norm_rope_kvcache_fusion_test(
else:
torch.testing.assert_close(q_unfused, q_fused, atol=ATOL, rtol=RTOL)
if not is_fp8_cache:
if not expect_fusion or (not is_fp8_cache and mrope_section is None):
# The AITER PTS kernel populates k_out only for non-FP8 caches.
# With FP8, the kernel writes quantized K directly to the cache
# and may leave k_out uninitialised. In production this is fine
@@ -397,15 +536,16 @@ def _run_qk_norm_rope_kvcache_fusion_test(
# Should be bit exact since no processing had been done on v for both paths
torch.testing.assert_close(v_unfused, v_fused, atol=0.0, rtol=0.0)
# fp8 vs triton-rope ref requires loosening tolerance to 1.25e-1.
if is_fp8_cache and enable_aiter_triton_rope:
# Fused and unfused arithmetic can straddle an FP8 rounding boundary.
# Allow one E4M3 quantization step while still comparing every block.
if is_fp8_cache:
cache_atol = cache_rtol = 1.25e-1
else:
cache_atol, cache_rtol = ATOL, RTOL
torch.testing.assert_close(
kv_cache_unfused[0].float(),
kv_cache_fused[0].float(),
kv_cache_unfused.float(),
kv_cache_fused.float(),
atol=cache_atol,
rtol=cache_rtol,
)
@@ -494,3 +634,225 @@ def test_qk_norm_rope_kvcache_fusion(
custom_op=custom_op,
monkeypatch=monkeypatch,
)
@pytest.mark.parametrize(
"mrope_section",
[
pytest.param((16, 24, 24), id="full_rotary"),
pytest.param((4, 6, 6), id="partial_rotary"),
],
)
@pytest.mark.parametrize("mrope_interleaved", [False, True])
@pytest.mark.parametrize("is_neox", [False, True])
@pytest.mark.parametrize(
"kv_layout",
[
pytest.param(KVCacheLayout.LBHNC, id="head_major"),
pytest.param(KVCacheLayout.LBNHC, id="token_major"),
pytest.param(KVCacheLayout.LHBNC, id="block_major"),
],
)
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
@pytest.mark.skipif(
not IS_AITER_FOUND,
reason="Requires AITER",
)
def test_qk_norm_mrope_kvcache_fusion(
mrope_section: tuple[int, int, int],
mrope_interleaved: bool,
is_neox: bool,
kv_layout: KVCacheLayout,
kv_cache_dtype: str,
monkeypatch: pytest.MonkeyPatch,
):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=8,
num_kv_heads=2,
head_size=128,
rotary_dim=2 * sum(mrope_section),
block_size=16,
is_neox=is_neox,
use_shuffle_kv_layout="0",
kv_layout=kv_layout,
dtype=torch.bfloat16,
kv_cache_dtype=kv_cache_dtype,
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=mrope_section,
mrope_interleaved=mrope_interleaved,
)
@pytest.mark.parametrize(
("num_heads", "num_kv_heads"),
[(32, 2), (16, 1), (8, 1)],
ids=["tp2", "tp4", "tp8"],
)
def test_qk_norm_mrope_kvcache_fusion_quark_scalar_query_scale(
num_heads: int,
num_kv_heads: int,
monkeypatch: pytest.MonkeyPatch,
):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=num_heads,
num_kv_heads=num_kv_heads,
head_size=128,
rotary_dim=128,
block_size=16,
is_neox=True,
use_shuffle_kv_layout="0",
kv_layout=KVCacheLayout.LBHNC,
dtype=torch.bfloat16,
kv_cache_dtype="fp8",
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=(24, 20, 20),
mrope_interleaved=True,
use_quark_scalar_query_scale=True,
)
def test_mrope_fusion_rejects_observable_k(monkeypatch: pytest.MonkeyPatch):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=8,
num_kv_heads=2,
head_size=128,
rotary_dim=128,
block_size=16,
is_neox=True,
use_shuffle_kv_layout="0",
kv_layout=KVCacheLayout.LBHNC,
dtype=torch.bfloat16,
kv_cache_dtype="auto",
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=(16, 24, 24),
observe_mrope_k=True,
expect_fusion=False,
)
def test_mrope_fusion_rejects_unaligned_rotary_dim(
monkeypatch: pytest.MonkeyPatch,
):
_run_qk_norm_rope_kvcache_fusion_test(
attn_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
enable_aiter_triton_rope=False,
num_tokens=5,
num_heads=8,
num_kv_heads=2,
head_size=128,
rotary_dim=6,
block_size=16,
is_neox=True,
use_shuffle_kv_layout="0",
kv_layout=KVCacheLayout.LBHNC,
dtype=torch.bfloat16,
kv_cache_dtype="auto",
rms_norm_eps=1e-6,
custom_op="+rotary_embedding",
monkeypatch=monkeypatch,
mrope_section=(1, 1, 1),
expect_fusion=False,
)
@pytest.mark.skipif(not _USE_LAYERNAME, reason="requires opaque LayerName")
def test_opaque_layer_name_patterns_register_once(monkeypatch: pytest.MonkeyPatch):
device = os.environ.get("VLLM_TEST_CUDA_DEVICE", "cuda")
vllm_config = VllmConfig(
model_config=ModelConfig(dtype=torch.bfloat16),
cache_config=CacheConfig(block_size=16, cache_dtype="fp8_e4m3"),
compilation_config=CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
custom_ops=["+rotary_embedding"],
pass_config=PassConfig(fuse_qk_norm_rope_kvcache=True),
),
)
with vllm.config.set_current_vllm_config(vllm_config), monkeypatch.context() as m:
m.setenv("VLLM_ROCM_USE_AITER", "1")
rocm_aiter_ops.refresh_env_variables()
model_kwargs = {
"vllm_config": vllm_config,
"attn_backend": AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
"num_heads": 8,
"num_kv_heads": 2,
"head_size": 128,
"is_neox": True,
"rms_norm_eps": 1e-6,
"dtype": torch.bfloat16,
"device": torch.device(device),
}
models = [
QKNormRoPEKVCacheTestModel(
**model_kwargs,
prefix=f"model.layers.{index}.self_attn.attn",
)
for index in range(2)
]
# Opaque layer names are wildcards in the pattern graph. Registering
# once per physical layer raises "Duplicate pattern" on torch >= 2.11.
fusion_pass = QkNormRopeKvCacheFusionPass(vllm_config)
assert models
assert fusion_pass.patterns
def _call_fused_mrope_impl(q_out: torch.Tensor) -> None:
device = q_out.device
fusion_module.fused_qk_norm_mrope_and_unified_kv_cache_update_impl(
q_out=q_out,
qkv=torch.zeros(2, 16, device=device),
positions=torch.arange(2, device=device),
q_weight=torch.ones(4, device=device),
k_weight=torch.ones(4, device=device),
rms_norm_eps=1e-6,
cos_sin_cache=torch.zeros(16, 4, device=device),
is_neox=True,
mrope_section_t=1,
mrope_section_h=1,
mrope_section_w=0,
is_interleaved=False,
rotary_dim=4,
layer_name="model.layers.0.self_attn.attn",
)
def test_mrope_profiling_pass_initializes_query(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
fusion_module,
"get_attention_context",
lambda _: (None, None, None, None),
)
q_out = torch.full((2, 8), torch.nan, device="cpu")
_call_fused_mrope_impl(q_out)
torch.testing.assert_close(q_out, torch.zeros_like(q_out))
def test_mrope_attention_context_failure_propagates(
monkeypatch: pytest.MonkeyPatch,
):
def fail_context(_):
raise RuntimeError("missing attention context")
monkeypatch.setattr(fusion_module, "get_attention_context", fail_context)
with pytest.raises(RuntimeError, match="missing attention context"):
_call_fused_mrope_impl(torch.empty(2, 8, device="cpu"))
@@ -14,8 +14,10 @@ from vllm.entrypoints.openai.completion.serving import OpenAIServingCompletion
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.scale_out.render.serving import ServingRender
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.exceptions import GenerationError, VLLMValidationError
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.renderers.deepseek_v4 import DeepseekV4Renderer
from vllm.renderers.hf import HfRenderer
from vllm.renderers.online_renderer import OnlineRenderer
from vllm.tokenizers.registry import cached_tokenizer_from_config
@@ -24,6 +26,9 @@ from vllm.v1.metrics.stats import RequestSpecDecodeMetrics, RequestStateStats
MODEL_NAME = "openai-community/gpt2"
MODEL_NAME_SHORT = "gpt2"
DEEPSEEK_V4_FIM_BEGIN = "<|fim▁begin|>"
DEEPSEEK_V4_FIM_HOLE = "<|fim▁hole|>"
DEEPSEEK_V4_FIM_END = "<|fim▁end|>"
_PER_REQUEST_STATS = RequestStateStats(
queued_ts=1.0,
scheduled_ts=1.5,
@@ -302,6 +307,179 @@ def test_completion_metrics_carries_both_timing_and_spec_decode():
assert response.metrics.speculative_decoding.num_spec_steps == 2
def _build_online_renderer_for_completion(
model_config: MockModelConfig,
renderer: Any | None = None,
) -> OnlineRenderer:
if renderer is None:
renderer = MagicMock()
renderer.render_completion_suffix.return_value = None
return OnlineRenderer(
model_config=model_config,
renderer=renderer,
request_logger=None,
chat_template=None,
chat_template_content_format="auto",
)
def _deepseek_v4_suffix_renderer(
model_config: MockModelConfig,
) -> DeepseekV4Renderer:
return DeepseekV4Renderer(
MockVllmConfig(model_config, parallel_config=MockParallelConfig()),
None,
)
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_uses_renderer_capability():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock(return_value=[{"ok": True}])
request = CompletionRequest(
model=MODEL_NAME,
prompt="def fib(n):\n return ",
suffix="\n\nprint(fib(10))",
max_tokens=64,
)
result = await online_renderer.render_completion(request)
assert result == [{"ok": True}]
online_renderer.preprocess_completion.assert_awaited_once()
assert online_renderer.preprocess_completion.call_args.kwargs["prompt_input"] == (
f"{DEEPSEEK_V4_FIM_BEGIN}def fib(n):\n return "
f"{DEEPSEEK_V4_FIM_HOLE}\n\nprint(fib(10))"
f"{DEEPSEEK_V4_FIM_END}"
)
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_supports_text_prompt_list():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock(return_value=[{"ok": True}])
request = CompletionRequest(
model=MODEL_NAME,
prompt=["prefix A", "prefix B"],
suffix=" suffix",
)
result = await online_renderer.render_completion(request)
assert result == [{"ok": True}]
assert online_renderer.preprocess_completion.call_args.kwargs["prompt_input"] == [
f"{DEEPSEEK_V4_FIM_BEGIN}prefix A"
f"{DEEPSEEK_V4_FIM_HOLE} suffix{DEEPSEEK_V4_FIM_END}",
f"{DEEPSEEK_V4_FIM_BEGIN}prefix B"
f"{DEEPSEEK_V4_FIM_HOLE} suffix{DEEPSEEK_V4_FIM_END}",
]
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_rejects_renderer_without_fim_support():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(model_config)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt="prefix",
suffix="suffix",
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "FIM completion rendering" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_rejects_echo():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt="prefix",
suffix="suffix",
echo=True,
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "Echo is unsupported with suffix" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_completion_suffix_rejects_prompt_embeds():
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt="prefix",
suffix="suffix",
prompt_embeds=b"embeds",
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "suffix is not supported with prompt_embeds" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
@pytest.mark.parametrize("prompt", ([1, 2, 3], [[1, 2, 3]]))
async def test_completion_suffix_rejects_token_prompt(prompt):
model_config = MockModelConfig()
online_renderer = _build_online_renderer_for_completion(
model_config,
renderer=_deepseek_v4_suffix_renderer(model_config),
)
online_renderer.preprocess_completion = AsyncMock()
request = CompletionRequest(
model=MODEL_NAME,
prompt=prompt,
suffix="suffix",
)
result = await online_renderer.render_completion(request)
assert isinstance(result, ErrorResponse)
assert "requires text prompt input" in result.error.message
online_renderer.preprocess_completion.assert_not_awaited()
@pytest.mark.asyncio
async def test_completion_error_non_stream():
"""Test finish_reason='error' returns 500 InternalServerError (non-streaming)."""
@@ -3,6 +3,5 @@ accuracy_threshold: 0.39
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 8192
--linear-backend humming
@@ -3,7 +3,6 @@ accuracy_threshold: 0.86
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 8192
--moe-backend humming
--linear-backend humming
@@ -1,5 +1,5 @@
model_name: "nm-testing/Qwen3-4B-mixed-quant-RTN-wNaM"
accuracy_threshold: 0.78
model_name: "nm-testing/Qwen3-4B-mixed-quant-RTN-wNaM-a4"
accuracy_threshold: 0.70
num_questions: 1319
num_fewshot: 5
server_args: >-
@@ -0,0 +1,8 @@
model_name: "nm-testing/Qwen3-4B-mixed-quant-RTN-wNaM-asym"
accuracy_threshold: 0.85
num_questions: 1319
num_fewshot: 5
server_args: >-
--enforce-eager
--max-model-len 4096
--linear-backend humming
@@ -1,3 +1,4 @@
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
Qwen3-4B-mixed-quant-RTN-no-w4a4-humming.yaml
@@ -4,4 +4,4 @@ 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
Qwen3-4B-mixed-quant-RTN-no-w4a4-humming.yaml
+49 -3
View File
@@ -428,6 +428,7 @@ def varlen_with_paged_kv(
k_scale: float = 1.0,
v_scale: float = 1.0,
dynamic_causal: list[bool] | None = None,
s_aux_dtype: torch.dtype = torch.bfloat16,
) -> None:
set_random_seed(0)
num_seqs = len(seq_lens)
@@ -449,9 +450,7 @@ def varlen_with_paged_kv(
# 2^(-8/n)
alibi_slopes = _get_alibi_slopes(num_query_heads) if use_alibi else None
s_aux = (
15 * torch.rand((num_query_heads,), dtype=torch.bfloat16) if use_sink else None
)
s_aux = 15 * torch.rand((num_query_heads,), dtype=s_aux_dtype) if use_sink else None
is_fp8 = kv_cache_dtype != "auto"
if is_fp8 and current_platform.get_cpu_architecture() != CpuArchEnum.X86:
@@ -538,6 +537,8 @@ def varlen_with_paged_kv(
)
out_without_split = torch.empty_like(query)
if s_aux is not None and s_aux.dtype != torch.bfloat16:
s_aux = s_aux.to(torch.float32)
cpu_attention_with_kv_cache(
query=query,
key_cache=packed_key_cache,
@@ -1128,6 +1129,51 @@ def test_varlen_with_paged_kv_sink(
)
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8_e4m3"])
@pytest.mark.parametrize("seq_lens", SEQ_LENS)
@pytest.mark.parametrize("num_heads", NUM_HEADS)
@pytest.mark.parametrize("head_size", [96])
@pytest.mark.parametrize("block_size", [128])
@pytest.mark.parametrize("sliding_window", SLIDING_WINDOWS)
@pytest.mark.parametrize("dtype", [torch.bfloat16])
@pytest.mark.parametrize("soft_cap", [None])
@pytest.mark.parametrize("num_blocks", NUM_BLOCKS)
@pytest.mark.parametrize("use_alibi", [False])
@pytest.mark.parametrize("use_sink", [True])
@pytest.mark.parametrize("isa", [get_attn_isa()])
@pytest.mark.parametrize("s_aux_dtype", [torch.float16])
def test_varlen_with_paged_kv_sink_fp16(
seq_lens: list[tuple[int, int]],
num_heads: tuple[int, int],
head_size: int,
sliding_window: int | None,
dtype: torch.dtype,
block_size: int,
soft_cap: float | None,
num_blocks: int,
use_alibi: bool,
use_sink: bool,
isa: str,
kv_cache_dtype: str,
s_aux_dtype: torch.dtype,
) -> None:
varlen_with_paged_kv(
seq_lens=seq_lens,
num_heads=num_heads,
head_size=head_size,
sliding_window=sliding_window,
dtype=dtype,
block_size=block_size,
soft_cap=soft_cap,
num_blocks=num_blocks,
use_alibi=use_alibi,
use_sink=use_sink,
isa=isa,
kv_cache_dtype=kv_cache_dtype,
s_aux_dtype=s_aux_dtype,
)
@pytest.mark.parametrize(
"kv_cache_dtype",
[
+61 -1
View File
@@ -107,7 +107,16 @@ SEEDS = [0]
def torch_w8a8_block_fp8_moe(
a, w1, w2, w1_s, w2_s, topk_weight, topk_ids, block_shape, silu_fp32=False
a,
w1,
w2,
w1_s,
w2_s,
topk_weight,
topk_ids,
block_shape,
silu_fp32=False,
expert_map=None,
):
"""Fused MoE with block-wise fp8 quantization using native torch.
@@ -123,6 +132,9 @@ def torch_w8a8_block_fp8_moe(
topk_weight = topk_weight.view(-1)
topk_ids = topk_ids.view(-1)
if expert_map is not None:
# w1/w2 hold this rank's experts; slots mapped to -1 contribute nothing.
topk_ids = expert_map[topk_ids]
_, block_k = block_shape[0], block_shape[1]
# Quantize with the production per-token-group fp8 kernel (same HIP/CUDA op the
@@ -301,6 +313,54 @@ def test_w8a8_block_fp8_clamp_skips_fused_silu_quant(
)
@pytest.mark.parametrize(("M", "N", "K"), [(83, 512, 512), (2048, 4608, 512)])
@pytest.mark.parametrize("topk", [2, 6])
@pytest.mark.parametrize("ep_size", [2, 4])
@torch.inference_mode()
def test_w8a8_block_fp8_fused_moe_expert_map(M, N, K, topk, ep_size, workspace_init):
"""One EP rank: local expert shard plus an expert_map with -1 entries."""
E, block_size, dtype = 16, [128, 128], torch.bfloat16
torch.manual_seed(0)
a = torch.randn((M, K), dtype=dtype) / 10
score = torch.randn((M, E), dtype=dtype)
w1, w2, quant_config = make_test_quant_config(
E, N, K, dtype, quant_dtype=torch.float8_e4m3fn, block_shape=block_size
)
local_e = E // ep_size
e_ids = torch.randperm(E, dtype=torch.int32)[:local_e]
e_map = torch.full((E,), -1, dtype=torch.int32)
e_map[e_ids] = torch.arange(local_e, dtype=torch.int32)
w1, w2 = w1[e_ids].contiguous(), w2[e_ids].contiguous()
w1_s = quant_config.w1_scale[e_ids].contiguous()
w2_s = quant_config.w2_scale[e_ids].contiguous()
quant_config = fp8_w8a8_moe_quant_config(
w1_scale=w1_s, w2_scale=w2_s, block_shape=block_size
)
m_fused_moe = modular_triton_fused_moe(make_dummy_moe_config(), quant_config)
topk_weights, topk_ids, _ = fused_topk(a, score.float(), topk, False)
with set_current_vllm_config(vllm_config):
ref_out = torch_w8a8_block_fp8_moe(
a, w1, w2, w1_s, w2_s, topk_weights, topk_ids, block_size, expert_map=e_map
)
m_out = m_fused_moe.apply(
a,
w1,
w2,
topk_weights,
topk_ids,
activation=MoEActivation.SILU,
apply_router_weight_on_input=False,
expert_map=e_map,
global_num_experts=E,
)
torch.testing.assert_close(m_out, ref_out, atol=0.035, rtol=0.035)
@pytest.mark.parametrize(("M", "N", "K"), MNK_FACTORS_DG)
@pytest.mark.parametrize("E", E)
@pytest.mark.parametrize("topk", TOP_KS)
@@ -339,6 +339,136 @@ def test_dsv4_fast_topk(
)
@pytest.mark.skipif(
not current_platform.is_cuda(),
reason="The DeepSeek V4 fast path is CUDA-only.",
)
def test_dsv4_fast_topk_padding_uint32_falls_back(monkeypatch: pytest.MonkeyPatch):
"""Padded rows need the -1 sentinel, which uint32 cannot represent: the
router must skip the dsv4 fast path and still route the real rows."""
torch.manual_seed(0)
num_tokens = 17
num_experts = 256
hidden_states = torch.randn((num_tokens, 64), dtype=torch.float32, device="cuda")
gating_output = torch.randn(
(num_tokens, num_experts), dtype=torch.float32, device="cuda"
)
correction_bias = torch.randn(num_experts, dtype=torch.float32, device="cuda")
is_padding = torch.zeros(num_tokens, dtype=torch.bool, device="cuda")
is_padding[1::2] = True
gating_output[is_padding] = float("nan")
monkeypatch.setattr(
"vllm.model_executor.layers.fused_moe.router."
"fused_topk_bias_router._get_padding_mask",
lambda _: is_padding,
)
# uint32 + padding would trip dsv4_topk's signed-indices assertion; the
# generic path must take over instead.
topk_weights, topk_ids = fused_topk_bias(
hidden_states=hidden_states,
gating_output=gating_output,
scoring_func="sqrtsoftplus",
e_score_correction_bias=correction_bias,
topk=6,
renormalize=True,
indices_type=torch.uint32,
routed_scaling_factor=1.5,
)
assert topk_ids.dtype == torch.uint32
topk_weights_ref, topk_ids_ref = _torch_topk_softplus_sqrt(
gating_output=gating_output[~is_padding],
topk=6,
renormalize=True,
routed_scaling_factor=1.5,
e_score_correction_bias=correction_bias,
)
# uint32 CUDA tensors do not support boolean-mask indexing; widen first.
torch.testing.assert_close(
topk_ids.to(torch.int64)[~is_padding],
topk_ids_ref.to(torch.int64),
atol=0,
rtol=0,
)
torch.testing.assert_close(
topk_weights[~is_padding], topk_weights_ref, atol=2e-5, rtol=2e-5
)
@pytest.mark.skipif(
not current_platform.is_cuda(),
reason="The DeepSeek V4 fast path is CUDA-only.",
)
def test_dsv4_fast_topk_padding(monkeypatch: pytest.MonkeyPatch):
"""Verify the DSV4 fast path removes graph-padding rows from routing."""
torch.manual_seed(0)
num_tokens = 17
num_experts = 256
hidden_states = torch.randn((num_tokens, 64), dtype=torch.float32, device="cuda")
gating_output = torch.randn(
(num_tokens, num_experts), dtype=torch.float32, device="cuda"
)
correction_bias = torch.randn(num_experts, dtype=torch.float32, device="cuda")
is_padding = torch.zeros(num_tokens, dtype=torch.bool, device="cuda")
is_padding[1::2] = True
gating_output[is_padding] = float("nan")
monkeypatch.setattr(
"vllm.model_executor.layers.fused_moe.router."
"fused_topk_bias_router._get_padding_mask",
lambda _: is_padding,
)
topk_weights, topk_ids = fused_topk_bias(
hidden_states=hidden_states,
gating_output=gating_output,
scoring_func="sqrtsoftplus",
e_score_correction_bias=correction_bias,
topk=6,
renormalize=True,
routed_scaling_factor=1.5,
)
assert torch.equal(topk_ids[is_padding], torch.full_like(topk_ids[is_padding], -1))
assert torch.equal(
topk_weights[is_padding], torch.zeros_like(topk_weights[is_padding])
)
topk_weights_ref, topk_ids_ref = _torch_topk_softplus_sqrt(
gating_output=gating_output[~is_padding],
topk=6,
renormalize=True,
routed_scaling_factor=1.5,
e_score_correction_bias=correction_bias,
)
torch.testing.assert_close(topk_ids[~is_padding], topk_ids_ref, atol=0, rtol=0)
torch.testing.assert_close(
topk_weights[~is_padding], topk_weights_ref, atol=2e-5, rtol=2e-5
)
# The mask buffer is persistent under CUDA graph replay, but its contents
# change with every batch. Verify that the kernel reads those contents at
# runtime rather than specializing on the mask captured above.
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
graph_weights, graph_ids = dsv4_topk(
gating_output,
correction_bias,
torch.int32,
1.5,
is_padding=is_padding,
)
is_padding.logical_not_()
graph.replay()
assert torch.equal(
graph_ids[is_padding], torch.full_like(graph_ids[is_padding], -1)
)
assert torch.equal(
graph_weights[is_padding], torch.zeros_like(graph_weights[is_padding])
)
@pytest.mark.skipif(
not current_platform.is_cuda_alike(),
reason="This test is skipped on non-CUDA platform.",
+23
View File
@@ -17,6 +17,26 @@ EPS = 1e-5
attn_res_module = importlib.import_module("vllm.models.kimi_k3.nvidia.ops.attn_res")
def _on_rocm_below_10() -> bool:
if not current_platform.is_rocm():
return False
from vllm.platforms.rocm import get_rocm_version
return (get_rocm_version() or (0,)) < (10,)
# The Triton bundled with ROCm < 10 (3.7.x) crashes in the AMD
# CanonicalizePointers pass on the kernel's tl.where over pointer tensors. Only
# the num_blocks > 0 loop contains it. ROCm serves AttnRes from
# vllm/models/kimi_k3/amd/ops/attn_res.py instead, so nothing real is lost.
_OLD_ROCM = _on_rocm_below_10()
def _skip_on_old_rocm(num_blocks: int) -> None:
if _OLD_ROCM and num_blocks > 0:
pytest.skip("Triton on ROCm < 10 cannot compile this kernel's pointer select")
def _randn_with_row_padding(*shape: int, padding: int = 0) -> torch.Tensor:
storage = torch.randn(
*shape[:-1],
@@ -79,6 +99,7 @@ def test_attn_res(
):
if backend == "nvidia" and not current_platform.is_device_capability_family(100):
pytest.skip("NVIDIA AttnRes requires the SM100 family")
_skip_on_old_rocm(num_blocks)
prefix = _randn_with_row_padding(num_tokens, HIDDEN_SIZE, padding=row_padding)
delta = (
@@ -133,6 +154,7 @@ def test_attn_res(
@pytest.mark.parametrize("num_blocks", range(MAX_BLOCKS + 1))
def test_attn_res_block_counts(num_blocks: int):
_skip_on_old_rocm(num_blocks)
prefix = torch.randn(1, HIDDEN_SIZE, device="cuda", dtype=torch.bfloat16)
blocks = torch.randn(
1, MAX_BLOCKS, HIDDEN_SIZE, device="cuda", dtype=torch.bfloat16
@@ -169,6 +191,7 @@ def test_attn_res_block_counts(num_blocks: int):
def test_attn_res_without_output_norm():
_skip_on_old_rocm(MAX_BLOCKS)
prefix = torch.randn(7, HIDDEN_SIZE, device="cuda", dtype=torch.bfloat16)
delta = torch.randn_like(prefix)
blocks = torch.randn(
+16 -17
View File
@@ -855,7 +855,7 @@ def test_quant_method_dispatch_ignored(default_vllm_config):
UnquantizedFusedMoEMethod,
)
dynamic_mxfp4_config = _make_qtensor_config(
mxfp4_config = _make_qtensor_config(
{
"dtype": "fp4",
"qscheme": "per_group",
@@ -866,24 +866,23 @@ def test_quant_method_dispatch_ignored(default_vllm_config):
None,
exclude=["self_attn.q_proj", "mlp.down_proj"],
)
dynamic_mxfp4_config.dynamic_mxfp4_quant = True
assert dynamic_mxfp4_config.get_quant_method_target(
"self_attn.q_proj", LinearBase
) == (kMxfp4Static, None, QuarkLinearMethod)
attention_proj = TestLinear()
assert isinstance(
dynamic_mxfp4_config.get_quant_method(attention_proj, "self_attn.q_proj"),
QuarkLinearMethod,
assert mxfp4_config.get_quant_method_target("self_attn.q_proj", LinearBase) == (
None,
None,
UnquantizedLinearMethod,
)
assert isinstance(attention_proj.scheme, QuarkOCP_MX)
assert attention_proj.scheme.dynamic_mxfp4_quant
assert dynamic_mxfp4_config.get_quant_method_target(
"mlp.down_proj", LinearBase
) == (None, None, UnquantizedLinearMethod)
assert isinstance(
dynamic_mxfp4_config.get_quant_method(TestLinear(), "mlp.down_proj"),
mxfp4_config.get_quant_method(TestLinear(), "self_attn.q_proj"),
UnquantizedLinearMethod,
)
assert mxfp4_config.get_quant_method_target("mlp.down_proj", LinearBase) == (
None,
None,
UnquantizedLinearMethod,
)
assert isinstance(
mxfp4_config.get_quant_method(TestLinear(), "mlp.down_proj"),
UnquantizedLinearMethod,
)
+66 -1
View File
@@ -12,6 +12,7 @@ from unittest.mock import patch
import pydantic
import pytest
import torch
from huggingface_hub import ResolvedRevision
from pydantic import ValidationError
@@ -37,7 +38,7 @@ from vllm.config import (
WatermarkConfig,
update_config,
)
from vllm.config.compilation import CompilationMode, CUDAGraphMode
from vllm.config.compilation import CompilationMode, CUDAGraphMode, PassConfig
from vllm.config.kernel import IrOpPriorityConfig
from vllm.config.load import LoadConfig
from vllm.config.mamba import MambaBackendEnum
@@ -656,6 +657,70 @@ def test_breakable_cudagraph_platform_default(
default_breakable_cudagraph_architectures.cache_clear()
@pytest.mark.parametrize(
"case,hidden,heads,intermediate,tp,expected",
[
("bf16", 2048, (16, 8), 6144, 1, True),
("bi-off", 2048, (16, 8), 6144, 1, False),
("opt-out", 2048, (16, 8), 6144, 1, False),
("eager", 2048, (16, 8), 6144, 1, False),
("sp", 2048, (16, 8), 6144, 1, False),
("fp16", 2048, (16, 8), 6144, 1, False),
("quantized", 2048, (16, 8), 6144, 1, False),
("untuned", 4096, (32, 32), 11008, 1, False),
("tp4-tuned", 4096, (8, 2), 12288, 4, True),
("list-intermediate", 2048, (16, 8), [2048, 4096], 1, False),
("no-table", 2048, None, 6144, 1, False),
],
)
def test_batch_invariant_breakable_cudagraph(
monkeypatch, case, hidden, heads, intermediate, tp, expected
):
from vllm.config.vllm import default_breakable_cudagraph_architectures
from vllm.model_executor.determinism import batch_invariant_configs as bi_configs
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "0" if case == "bi-off" else "1")
monkeypatch.delenv("VLLM_USE_BREAKABLE_CUDAGRAPH", raising=False)
if case == "opt-out":
monkeypatch.setenv("VLLM_USE_BREAKABLE_CUDAGRAPH", "0")
monkeypatch.setattr(current_platform, "is_cuda", lambda: True)
monkeypatch.setattr(current_platform, "is_rocm", lambda: False)
table = None if case == "no-table" else {(12288, 2048): None, (6144, 4096): None}
monkeypatch.setattr(current_platform, "get_device_capability", lambda: None)
monkeypatch.setattr(bi_configs, "_get_tuned_matmul_arch_family", lambda cap: "test")
monkeypatch.setattr(
bi_configs,
"_BATCH_INVARIANT_MATMUL_TUNED_CONFIGS",
{"test": table} if table else {},
)
default_breakable_cudagraph_architectures.cache_clear()
config = object.__new__(VllmConfig)
config.model_config = SimpleNamespace(
architectures=["Qwen3ForCausalLM"],
enforce_eager=case == "eager",
dtype=torch.float16 if case == "fp16" else torch.bfloat16,
quantization="fp8" if case == "quantized" else None,
hf_text_config=SimpleNamespace(intermediate_size=intermediate),
get_hidden_size=lambda: hidden,
get_head_size=lambda: 128,
get_num_attention_heads=lambda pc: heads[0],
get_num_kv_heads=lambda pc: heads[1],
)
config.parallel_config = SimpleNamespace(tensor_parallel_size=tp)
config.compilation_config = (
CompilationConfig(pass_config=PassConfig(enable_sp=True))
if case == "sp"
else CompilationConfig()
)
try:
assert config._maybe_enable_breakable_cudagraph() is expected
if expected:
assert config.compilation_config.mode == CompilationMode.NONE
finally:
os.environ.pop("VLLM_USE_BREAKABLE_CUDAGRAPH", None)
default_breakable_cudagraph_architectures.cache_clear()
@pytest.mark.parametrize(
("model_type", "expected_architecture"),
[
@@ -0,0 +1,29 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Mooncake P/D accuracy with same-host HIP transport on ROCm."""
import pytest
from tests.utils import spawn_new_process_for_each_test
from tests.v1.kv_connector.rocm_pd_accuracy_utils import (
QWEN_MODEL,
run_rocm_pd_accuracy,
)
from vllm.platforms import current_platform
pytestmark = [
pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm P/D equivalents"),
pytest.mark.distributed(num_gpus=4),
]
@pytest.mark.parametrize(
"model,prefill_tp,decode_tp",
[
pytest.param(QWEN_MODEL, 1, 1, id="mooncake-hip-qwen-p1-d1"),
pytest.param(QWEN_MODEL, 2, 2, id="mooncake-hip-qwen-p2-d2"),
],
)
@spawn_new_process_for_each_test
def test_rocm_pd_accuracy(model, prefill_tp, decode_tp, monkeypatch):
run_rocm_pd_accuracy("mooncake", model, prefill_tp, decode_tp, monkeypatch)
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""NIXL P/D accuracy with AITER unified attention on ROCm."""
import pytest
from tests.utils import spawn_new_process_for_each_test
from tests.v1.kv_connector.rocm_pd_accuracy_utils import (
DEEPSEEK_MODEL,
QWEN_MODEL,
run_rocm_pd_accuracy,
)
from vllm.platforms import current_platform
pytestmark = [
pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm P/D equivalents"),
pytest.mark.distributed(num_gpus=4),
]
@pytest.mark.parametrize(
"model,prefill_tp,decode_tp",
[
pytest.param(QWEN_MODEL, 2, 2, id="nixl-aiter-qwen-p2-d2"),
pytest.param(QWEN_MODEL, 1, 2, id="nixl-aiter-qwen-p1-d2"),
pytest.param(QWEN_MODEL, 2, 1, id="nixl-aiter-qwen-p2-d1"),
pytest.param(DEEPSEEK_MODEL, 1, 1, id="nixl-aiter-deepseek-p1-d1"),
pytest.param(DEEPSEEK_MODEL, 1, 2, id="nixl-aiter-deepseek-p1-d2"),
pytest.param(DEEPSEEK_MODEL, 2, 1, id="nixl-aiter-deepseek-p2-d1"),
],
)
@spawn_new_process_for_each_test
def test_rocm_pd_accuracy(model, prefill_tp, decode_tp, monkeypatch):
run_rocm_pd_accuracy("nixl", model, prefill_tp, decode_tp, monkeypatch)
@@ -0,0 +1,254 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared ROCm P/D accuracy harness for Mooncake and NIXL integration tests.
Keep the models, TP pairs, full GSM8K workload, and acceptance checks of the
Mooncake and FlashInfer/NIXL sweeps. Mooncake uses same-host HIP IPC; NIXL uses
AITER unified attention. These cases do not exercise RDMA or FlashInfer.
"""
import contextlib
import importlib
import json
import os
import signal
import subprocess
import sys
import time
from pathlib import Path
import requests
from prometheus_client.parser import text_string_to_metric_families
from tests.utils import RemoteOpenAIServer
from vllm.platforms import current_platform
from vllm.utils.network_utils import get_open_port
_ROOT = Path(__file__).resolve().parents[3]
QWEN_MODEL = "Qwen/Qwen3-0.6B"
DEEPSEEK_MODEL = "deepseek-ai/deepseek-vl2-tiny"
_REVISIONS = {
QWEN_MODEL: "c1899de289a04d12100db370d81485cdf75e47ca",
DEEPSEEK_MODEL: "66c54660eae7e90c9ba259bfdf92d07d6e3ce8aa",
}
def _metric_total(server, name: str, **labels: str) -> float:
response = requests.get(server.url_for("metrics"), timeout=10)
response.raise_for_status()
return sum(
sample.value
for family in text_string_to_metric_families(response.text)
for sample in family.samples
if sample.name == name
and all(sample.labels.get(key) == value for key, value in labels.items())
)
@contextlib.contextmanager
def _proxy(connector: str, prefill, decode, bootstrap_port: int):
port = get_open_port()
if connector == "mooncake":
script = (
_ROOT / "examples/disaggregated/mooncake_connector/"
"mooncake_connector_proxy.py"
)
args = [
"--prefill",
prefill.url_root,
str(bootstrap_port),
"--decode",
decode.url_root,
]
else:
script = Path(__file__).parent / "nixl_integration/toy_proxy_server.py"
args = [
"--prefiller-hosts",
"127.0.0.1",
"--prefiller-ports",
str(prefill.port),
"--decoder-hosts",
"127.0.0.1",
"--decoder-ports",
str(decode.port),
]
process = subprocess.Popen(
[sys.executable, str(script), "--port", str(port), *args],
start_new_session=True,
)
try:
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
assert process.poll() is None, "P/D proxy exited during startup"
try:
requests.get(f"http://127.0.0.1:{port}/", timeout=1)
break
except requests.ConnectionError:
time.sleep(0.2)
else:
raise TimeoutError("P/D proxy did not start")
yield f"http://127.0.0.1:{port}/v1"
finally:
if process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=10)
def run_rocm_pd_accuracy(connector, model, prefill_tp, decode_tp, monkeypatch):
"""Transferred KV must feed decoding while full upstream accuracy holds."""
# Preserve the caller's allocation instead of querying host-wide SMI indices.
selectors = ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "CUDA_VISIBLE_DEVICES")
selector = next((key for key in selectors if key in os.environ), selectors[0])
visible = os.getenv(selector)
devices = (
visible.split(",")
if visible is not None
else [str(i) for i in range(current_platform.device_count())]
)
assert len(devices) >= prefill_tp + decode_tp, "Insufficient allocated GPUs"
for key in selectors:
if key != selector:
monkeypatch.delenv(key, raising=False)
if connector == "mooncake":
import mooncake.engine
assert mooncake.engine.SUPPORT_HIP, "Mooncake requires its ROCm/HIP build"
connector_name = "MooncakeConnector"
extra = {"mooncake_protocol": "hip", "device_name": ""}
else:
from vllm.distributed.nixl_utils import NixlWrapper
assert NixlWrapper is not None, "NIXL ROCm bindings must import"
connector_name = "NixlConnector"
extra = {}
common_args = [
"--revision",
_REVISIONS[model],
"--dtype",
"bfloat16",
"--enforce-eager",
"--distributed-executor-backend",
"mp",
"--block-size",
"128",
"--max-num-seqs",
"128",
"--max-num-batched-tokens",
"4096",
"--gpu-memory-utilization",
"0.2",
"--kv-cache-memory-bytes",
str(8 * 1024**3),
"--moe-backend",
"triton",
"--attention-backend",
"ROCM_AITER_UNIFIED_ATTN",
]
common_env = {
"PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"],
"VLLM_HOST_IP": "127.0.0.1",
"VLLM_WORKER_MULTIPROC_METHOD": "spawn",
"VLLM_USE_V2_MODEL_RUNNER": "1",
"VLLM_ROCM_USE_AITER": "1",
"VLLM_KV_CACHE_LAYOUT": "HND",
}
bootstrap_port = get_open_port()
with contextlib.ExitStack() as stack:
servers: list[RemoteOpenAIServer] = []
stack.callback(RemoteOpenAIServer.shutdown_many, servers)
for role, tp, assigned in (
("kv_producer", prefill_tp, devices[:prefill_tp]),
("kv_consumer", decode_tp, devices[prefill_tp : prefill_tp + decode_tp]),
):
config = {
"kv_connector": connector_name,
"kv_role": role,
"kv_connector_extra_config": extra,
}
env = {
**common_env,
selector: ",".join(assigned),
"VLLM_PORT": str(get_open_port()),
"VLLM_NIXL_SIDE_CHANNEL_PORT": str(get_open_port()),
"VLLM_MOONCAKE_BOOTSTRAP_PORT": str(bootstrap_port),
}
servers.append(
RemoteOpenAIServer(
model,
[
*common_args,
"--tensor-parallel-size",
str(tp),
"--kv-transfer-config",
json.dumps(config),
],
env_dict=env,
max_wait_seconds=1200,
)
)
prefill, decode = servers
proxy_url = stack.enter_context(
_proxy(connector, prefill, decode, bootstrap_port)
)
# Reuse the full upstream evaluation and its model-specific assertions.
accuracy = importlib.import_module(
f"tests.v1.kv_connector.{connector}_integration.test_accuracy"
)
monkeypatch.setattr(accuracy, "MODEL_NAME", model)
monkeypatch.setattr(accuracy, "BASE_URL", proxy_url)
assert model in accuracy.EXPECTED_VALUES
def transfer_totals():
totals = {
"external_tokens": _metric_total(
decode,
"vllm:prompt_tokens_by_source_total",
source="external_kv_transfer",
)
}
if connector == "nixl":
totals["nixl_bytes"] = _metric_total(
decode, "vllm:nixl_bytes_transferred_sum"
)
return totals
simple_evaluate = accuracy.lm_eval.simple_evaluate
def evaluate_with_transfer_checks(*args, **kwargs):
# The upstream helper runs a smoke prompt before GSM8K. Wait until
# its counters appear, then require new transfers during evaluation.
deadline = time.monotonic() + 15
before = transfer_totals()
while not all(value > 0 for value in before.values()):
assert time.monotonic() < deadline, (
f"Smoke prompt did not transfer KV: {before}"
)
time.sleep(1)
before = transfer_totals()
# The API adapter loads a local tokenizer because these proxies do
# not expose /tokenize. Match it to the server's pinned checkpoint.
kwargs["model_args"] += f",revision={_REVISIONS[model]}"
results = simple_evaluate(*args, **kwargs)
deadline = time.monotonic() + 15
after = transfer_totals()
while not all(after[key] > value for key, value in before.items()):
assert time.monotonic() < deadline, (
f"GSM8K did not transfer KV: before={before}, after={after}"
)
time.sleep(1)
after = transfer_totals()
print(f"GSM8K transfer counters: before={before}, after={after}")
return results
monkeypatch.setattr(
accuracy.lm_eval, "simple_evaluate", evaluate_with_transfer_checks
)
accuracy.test_accuracy()
@@ -50,7 +50,10 @@ from vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker import (
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.stats import (
NixlKVConnectorStats,
)
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.tp_mapping import TPMapping
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.tp_mapping import (
ReadSpec,
TPMapping,
)
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.utils import (
get_base_request_id,
)
@@ -344,6 +347,7 @@ class _StubWriterWorker(NixlPushConnectorWorker):
)
w._sending_transfers = defaultdict[ReqId, list[TransferHandle]](list)
w._send_failures = set()
w._sending_transfers_lock = threading.Lock()
w._push_finished_blocks = {}
w._pending_d_registrations = {}
@@ -941,9 +945,10 @@ class TestPushWriterNotifs:
assert request_id not in w._sending_transfers
@pytest.mark.parametrize(("pp_size", "is_hma"), [(1, False), (2, True)])
def test_completed_push_send_waits_for_consumer_notif(self, pp_size, is_hma):
"""P-side sends are completed by consumer notifs / lease expiry,
not by local WRITE-handle completion."""
def test_completed_push_send_releases_blocks_without_consumer_notif(
self, pp_size, is_hma
):
"""All WRITEs completing lets P reclaim its blocks without a D ACK."""
w = self._pollable_worker()
w.pp_size = pp_size
w._is_hma_required = is_hma
@@ -951,20 +956,14 @@ class TestPushWriterNotifs:
w.nixl_wrapper.check_xfer_state.side_effect = ["DONE", "PROC", "DONE"]
results = w.get_transfer_results()
assert request_id not in results.finished_sending
assert request_id in w._reqs_to_send
assert w._sending_transfers[request_id] == [102]
assert request_id in w._reqs_to_send
assert w._evict_finished_inbox.empty()
results = w.get_transfer_results()
assert request_id not in results.finished_sending
assert request_id in w._reqs_to_send
assert request_id not in w._sending_transfers
# The consumer notif is what completes the send.
w._pending_completion_notifs.put(f"{request_id}:1".encode())
results = w.get_transfer_results()
assert request_id in results.finished_sending
assert results.finished_sending == {request_id}
assert request_id not in w._reqs_to_send
assert request_id not in w._reqs_to_process
assert w._evict_finished_inbox.get_nowait() == request_id
@@ -973,6 +972,91 @@ class TestPushWriterNotifs:
assert w.nixl_wrapper.release_xfer_handle.call_count == 2
w.xfer_stats.record_kv_expired_req.assert_not_called()
@pytest.mark.parametrize("sibling_state", ["ERR", "DONE"])
def test_push_failure_survives_until_lease_expiry(self, sibling_state):
"""A later sibling completion must not turn a failed send into success."""
w = self._pollable_worker()
request_id = self._make_sending_req(w)
w.nixl_wrapper.check_xfer_state.side_effect = ["ERR", "PROC", sibling_state]
assert w.get_transfer_results().finished_sending == set()
assert w._sending_transfers[request_id] == [102]
assert w.get_transfer_results().finished_sending == set()
assert request_id not in w._sending_transfers
assert request_id in w._reqs_to_send
assert w._evict_finished_inbox.empty()
w.expected_consumer_notifications_by_req = {}
w._reqs_to_send[request_id] = time.perf_counter() - 1
assert w.get_transfer_results().finished_sending == {request_id}
assert request_id not in w._send_failures
assert w._evict_finished_inbox.get_nowait() == request_id
@pytest.mark.parametrize("release_fails", [False, True])
def test_push_submission_failure_is_remembered_after_sibling_success(
self, release_fails
):
"""A submission error remains a failure even if later polls succeed."""
w = self._pollable_worker()
request_id = self._make_sending_req(w)
w.transfer_topo.block_size_ratio.return_value = 1
w._apply_prefix_caching = MagicMock(return_value=([[1]], [[1]]))
w._compute_desc_ids = MagicMock(return_value=[0])
w.dst_num_blocks = {w.engine_id: 8}
w.dst_region_num_blocks[w.engine_id] = [8]
w.dst_region_group_ids[w.engine_id] = [0]
w.dst_uses_region_group_mapping[w.engine_id] = False
w.nixl_wrapper.make_prepped_xfer.return_value = 101
w.nixl_wrapper.transfer.side_effect = RuntimeError("submit")
if release_fails:
w.nixl_wrapper.release_xfer_handle.side_effect = [
RuntimeError("release"),
None,
None,
]
handle = w._xfer_blocks(
read_spec=ReadSpec(0, [[1]], [[1]]),
dst_engine_id=w.engine_id,
request_id=request_id,
remote_request_id="decode-request",
local_xfer_side_handle=1,
remote_xfer_side_handle=2,
)
assert handle == (101 if release_fails else None)
w._sending_transfers[request_id] = [102]
if handle is not None:
w._sending_transfers[request_id].append(handle)
w.nixl_wrapper.check_xfer_state.return_value = "DONE"
assert w.get_transfer_results().finished_sending == set()
assert request_id in w._reqs_to_send
assert request_id not in w._sending_transfers
assert w._evict_finished_inbox.empty()
@pytest.mark.parametrize("first_state", ["ERR", "DONE"])
def test_push_completion_after_expiry_is_not_reported_twice(self, first_state):
"""A WRITE finishing after lease expiry must not complete the request again."""
w = self._pollable_worker()
request_id = self._make_sending_req(w)
w.nixl_wrapper.check_xfer_state.side_effect = [
first_state,
"PROC",
"PROC",
"DONE",
]
assert w.get_transfer_results().finished_sending == set()
w.expected_consumer_notifications_by_req = {}
w._reqs_to_send[request_id] = time.perf_counter() - 1
assert w.get_transfer_results().finished_sending == {request_id}
assert w._evict_finished_inbox.get_nowait() == request_id
assert w.get_transfer_results().finished_sending == set()
assert request_id not in w._sending_transfers
assert request_id not in w._send_failures
assert w._evict_finished_inbox.empty()
# ----------------------------------------------------------------- #
# Negative / error-path tests #
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from contextlib import contextmanager
from types import SimpleNamespace
import numpy as np
@@ -8,7 +9,9 @@ import pytest
import torch
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
from vllm.v1.worker.gpu.spec_decode.dflash import speculator as dflash_speculator
from vllm.v1.worker.gpu.spec_decode.dflash.speculator import (
DFlashSpeculator,
prepare_dflash_inputs,
)
@@ -33,6 +36,7 @@ def _run_prepare(
input_buffers = SimpleNamespace(
input_ids=torch.full((max_num_tokens,), -1, dtype=torch.int32, device=device),
positions=torch.full((max_num_tokens,), -1, dtype=torch.int64, device=device),
is_padding=torch.zeros(max_num_tokens, dtype=torch.bool, device=device),
query_start_loc=torch.full(
(max_num_reqs + 1,), -1, dtype=torch.int32, device=device
),
@@ -140,6 +144,114 @@ def test_prepare_dflash_inputs_excludes_rejected_context_suffix():
assert out.temperature[2].item() == 1.0
assert out.seeds[2].item() == 17
assert not out.input_buffers.is_padding[:3].any()
assert out.input_buffers.is_padding[3:].all()
assert out.input_buffers.input_ids[3:].cpu().tolist() == [0] * 13
assert out.input_buffers.positions[3:].cpu().tolist() == [0] * 13
def test_prepare_dflash_inputs_compacts_noncontiguous_request_slots():
device = torch.device("cuda")
max_num_reqs = 4
max_num_tokens = 16
num_speculative_steps = 3
input_buffers = SimpleNamespace(
input_ids=torch.full((max_num_tokens,), -1, dtype=torch.int32, device=device),
positions=torch.full((max_num_tokens,), -1, dtype=torch.int64, device=device),
is_padding=torch.zeros(max_num_tokens, dtype=torch.bool, device=device),
query_start_loc=torch.full(
(max_num_reqs + 1,), -1, dtype=torch.int32, device=device
),
seq_lens=torch.full((max_num_reqs,), -1, dtype=torch.int32, device=device),
)
input_batch = SimpleNamespace(
num_reqs=2,
num_scheduled_tokens=np.array([4, 4], dtype=np.int32),
positions=torch.tensor(
[10, 11, 12, 13, 20, 21, 22, 23],
dtype=torch.int64,
device=device,
),
query_start_loc=torch.tensor([0, 4, 8], dtype=torch.int32, device=device),
# Active batch rows are compact, while request state remains in slots 3 and 1.
idx_mapping=torch.tensor([3, 1], dtype=torch.int32, device=device),
)
query_slot_mapping = torch.full(
(max_num_tokens,), -2, dtype=torch.int64, device=device
)
context_positions = torch.full(
(max_num_tokens,), -1, dtype=torch.int64, device=device
)
context_slot_mapping = torch.full(
(max_num_tokens,), -2, dtype=torch.int64, device=device
)
sample_indices = torch.full(
(max_num_reqs * num_speculative_steps,),
-1,
dtype=torch.int64,
device=device,
)
sample_pos = torch.full_like(sample_indices, -1)
sample_idx_mapping = torch.full(
sample_indices.shape, -1, dtype=torch.int32, device=device
)
temperature = torch.zeros(max_num_reqs, dtype=torch.float32, device=device)
seeds = torch.zeros(max_num_reqs, dtype=torch.int64, device=device)
input_temperature = torch.tensor(
[0.0, 0.5, 0.0, 1.0], dtype=torch.float32, device=device
)
input_seeds = torch.tensor([0, 11, 0, 33], dtype=torch.int64, device=device)
last_sampled = torch.tensor([0, 77, 0, 99], dtype=torch.int64, device=device)
next_prefill_tokens = torch.zeros_like(last_sampled)
block_table = torch.tensor(
[[0, 0, 7, 8, 9, 10, 11, 12], [0, 0, 13, 14, 15, 16, 17, 18]],
dtype=torch.int32,
device=device,
)
prepare_dflash_inputs(
input_buffers,
query_slot_mapping,
context_positions,
context_slot_mapping,
sample_indices,
sample_pos,
sample_idx_mapping,
temperature,
seeds,
input_batch,
torch.tensor([1, 1], dtype=torch.int32, device=device),
torch.tensor([2, 1], dtype=torch.int32, device=device),
last_sampled,
next_prefill_tokens,
input_temperature,
input_seeds,
block_table,
4,
0,
1,
1,
123,
num_speculative_steps,
num_speculative_steps,
max_num_reqs,
max_num_tokens,
128,
sample_from_anchor=True,
)
torch.accelerator.synchronize()
# Query rows follow compact batch order, but every persistent state lookup
# follows idx_mapping instead of accidentally using the compact row index.
assert input_buffers.input_ids[:6].cpu().tolist() == [99, 123, 123, 77, 123, 123]
assert input_buffers.positions[:6].cpu().tolist() == [12, 13, 14, 23, 24, 25]
assert sample_indices[:6].cpu().tolist() == [0, 1, 2, 3, 4, 5]
assert sample_idx_mapping[:6].cpu().tolist() == [3, 3, 3, 1, 1, 1]
assert temperature.cpu().tolist() == [0.0, 0.5, 0.0, 1.0]
assert seeds.cpu().tolist() == [0, 11, 0, 33]
assert not input_buffers.is_padding[:6].any()
assert input_buffers.is_padding[6:].all()
def test_prepare_dflash_inputs_excludes_rejected_context_suffix_with_dcp():
out = _run_prepare(
@@ -174,3 +286,40 @@ def test_prepare_dflash_inputs_never_writes_the_null_block():
PAD_SLOT_ID,
PAD_SLOT_ID,
]
def test_dflash_forward_context_receives_draft_padding_mask(monkeypatch):
device = torch.device("cuda")
input_buffers = SimpleNamespace(
input_ids=torch.tensor([11, 12, 0, 0], dtype=torch.int32, device=device),
positions=torch.tensor([7, 8, 0, 0], dtype=torch.int64, device=device),
is_padding=torch.tensor([False, False, True, True], device=device),
)
observed = None
@contextmanager
def fake_set_forward_context(*args, **kwargs):
nonlocal observed
observed = kwargs["is_padding"].clone()
yield
monkeypatch.setattr(
dflash_speculator, "set_forward_context", fake_set_forward_context
)
speculator = SimpleNamespace(
input_buffers=input_buffers,
vllm_config=SimpleNamespace(),
model=lambda **kwargs: kwargs["input_ids"],
)
result = DFlashSpeculator._run_model(
speculator,
num_tokens=4,
attn_metadata=None,
slot_mappings=None,
num_tokens_across_dp=None,
)
assert result.tolist() == [11, 12, 0, 0]
assert observed is not None
assert observed.tolist() == [False, False, True, True]
+57
View File
@@ -31,6 +31,7 @@ from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.mamba.mamba_mixer2 import MambaMixer2
from vllm.multimodal.inputs import MultiModalFeatureSpec, PlaceholderRange
from vllm.platforms import current_platform
from vllm.platforms.interface import Platform
from vllm.sampling_params import SamplingParams
from vllm.utils.mem_constants import GiB_bytes
from vllm.utils.system_utils import update_environment_variables
@@ -425,6 +426,62 @@ def test_select_common_block_size_no_valid_option():
select_common_block_size(48, [backend_a, backend_b])
def _mock_backend(supported: list, *, exact: bool = False):
"""Backend accepting multiples of ``supported``, or only those exact sizes
when ``exact`` (as CPU_MLA does)."""
from vllm.v1.attention.backend import AttentionBackend
class _MockBackendCls(AttentionBackend):
@staticmethod
def get_name() -> str:
return "MOCK_EXACT" if exact else "MOCK"
@staticmethod
def get_supported_kernel_block_sizes():
return list(supported)
if exact:
@classmethod
def supports_block_size(cls, block_size: int | None) -> bool:
return block_size is None or block_size in supported
return _MockBackendCls
@pytest.mark.parametrize(
"backends,expected",
[
# A lone backend keeps the default; MultipleOf(8) makes a
# minimum-based regression return 8 instead of 16.
([[MultipleOf(8)]], 16),
# Sparse-MLA main backend (32 or 64) beside an indexer supporting only
# 64: the main backend alone picks 32, which the indexer rejects at
# select_common_block_size time.
([[32, 64], [64]], 64),
([[32, 64]], 32),
# Neither divides the other, so only the LCM satisfies both.
([[32], [48]], 96),
],
)
def test_preferred_block_size_satisfies_every_backend(backends, expected):
classes = [_mock_backend(s) for s in backends]
assert Platform._preferred_block_size_for_backends(classes, 16, None) == expected
def test_preferred_block_size_searches_past_an_exact_size_backend():
# Extending greedily picks lcm(16, 32) = 32, which the exact backend
# rejects; 96 is accepted by both.
classes = [_mock_backend([16, 96], exact=True), _mock_backend([MultipleOf(32)])]
assert Platform._preferred_block_size_for_backends(classes, 16, None) == 96
def test_preferred_block_size_rejects_backends_with_no_common_size():
classes = [_mock_backend([16], exact=True), _mock_backend([MultipleOf(64)])]
with pytest.raises(ValueError, match="share no supported KV cache block size"):
Platform._preferred_block_size_for_backends(classes, 16, None)
def test_set_active_mm_loras_builds_tower_and_connector_mappings():
model = Mock()
model.get_mm_lora_token_counts.side_effect = (
+149 -3
View File
@@ -5,16 +5,35 @@
from unittest.mock import Mock
import numpy as np
import pytest
import torch
from vllm.v1.worker.gpu import pp_utils
from vllm.v1.worker.gpu import model_runner, pp_utils
def _batch(num_computed, prefill_len, num_scheduled):
def _cuda_handler(max_sample_len=6):
handler = object.__new__(pp_utils.PPHandler)
handler.is_last_rank = True
handler.disabled = False
handler.max_sample_len = max_sample_len
handler.last_rank = 1
handler.broadcast_group = Mock()
handler.device = torch.device("cuda")
handler.main_stream = torch.cuda.current_stream()
handler.broadcast_stream = torch.cuda.Stream()
return handler
def _batch(num_computed, prefill_len, num_scheduled, idx_mapping=None):
num_reqs = len(num_computed)
if idx_mapping is None:
idx_mapping = list(range(num_reqs))
return Mock(
num_reqs=len(num_computed),
num_reqs=num_reqs,
num_computed_tokens_np=np.array(num_computed, dtype=np.int32),
prefill_len_np=np.array(prefill_len, dtype=np.int32),
num_scheduled_tokens=np.array(num_scheduled, dtype=np.int32),
idx_mapping=torch.tensor(idx_mapping, dtype=torch.int64),
)
@@ -81,3 +100,130 @@ def test_decode_row_ahead_of_a_prefill_chunk():
assert mask is not None
assert mask.tolist() == [True, False]
def test_disabled_handler_skips_broadcast_and_receive(monkeypatch):
"""While disabled (warmup), neither side enqueues a broadcast op."""
sent = []
monkeypatch.setattr(
pp_utils.torch.distributed,
"broadcast",
lambda *args, **kwargs: sent.append((args, kwargs)),
)
handler = object.__new__(pp_utils.PPHandler)
handler.set_disabled(True)
handler.is_last_rank = False
assert handler.receive(Mock()) is False
handler.is_last_rank = True
assert handler.broadcast(Mock(), Mock(), Mock(), Mock()) is None
assert sent == []
handler.set_disabled(False)
assert handler.disabled is False
def test_alloc_combined_keeps_unbind_views_16_byte_aligned():
"""Triton specializes on pointer alignment: an unaligned `num_rejected`
would compile a second `_post_update_kernel` variant at serving time,
where the in-flight broadcast NCCL kernel can block the module load."""
for num_reqs in range(1, 9):
combined = pp_utils._alloc_combined(num_reqs, torch.device("cpu"))
num_sampled, num_rejected = combined.unbind(dim=0)
assert num_sampled.data_ptr() % 16 == 0
assert num_rejected.data_ptr() % 16 == 0
assert combined.shape[1] >= num_reqs
def test_warmup_pp_decode_update_matches_serving_specialization(monkeypatch):
"""The warmup launch must hit the same triton specialization as serving.
A mismatch means the first real ``update_pp_decode_requests`` recompiles
mid-serving, where the in-flight broadcast NCCL kernel blocks the CUDA
module load and deadlocks the pipeline.
"""
calls = []
monkeypatch.setattr(model_runner, "post_update", lambda *args: calls.append(args))
runner = object.__new__(model_runner.GPUModelRunner)
runner.device = torch.device("cpu")
runner.pp_handler = Mock(max_sample_len=3)
runner.req_states = Mock()
runner.warmup_pp_decode_update()
assert len(calls) == 1
args = calls[0]
idx_mapping, _, _, output_bin_counts = args[:4]
sampled_tokens, num_sampled, num_rejected, query_start_loc = args[4:8]
broadcast_drafts, draft_tokens_out = args[10:12]
assert idx_mapping.tolist() == [-1] and idx_mapping.dtype == torch.int64
assert output_bin_counts is None
assert query_start_loc is None
assert sampled_tokens.shape == (1, 3) and sampled_tokens.dtype == torch.int64
assert num_sampled.dtype == torch.int32
assert num_rejected.dtype == torch.int32
# Spec-enabled PP handlers receive drafts over the broadcast; the warmup
# must compile that specialization (non-None draft pointers) too.
assert broadcast_drafts.shape == (1, 2) and broadcast_drafts.dtype == torch.int64
assert draft_tokens_out is runner.req_states.draft_tokens
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA stream")
def test_broadcast_pads_plain_sampler_rows_to_max_sample_len(monkeypatch):
"""The wire shape must not depend on whether the batch carried drafts:
the receiver always allocates [num_reqs, max_sample_len], and a NCCL
broadcast with mismatched counts hangs the receiver."""
sent = []
monkeypatch.setattr(
pp_utils.torch.distributed,
"broadcast",
lambda tensor, **kw: sent.append(tensor),
)
handler = _cuda_handler()
batch = _batch(num_computed=[10], prefill_len=[8], num_scheduled=[1])
handler.broadcast(
torch.zeros(1, 1, dtype=torch.int64, device="cuda"), # plain sampler
torch.ones(1, dtype=torch.int32, device="cuda"),
torch.zeros(1, dtype=torch.int32, device="cuda"),
batch,
)
assert sent[0].shape == (1, 6)
assert sent[1].shape == (2, 4)
torch.accelerator.synchronize()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA stream")
def test_broadcast_drafts_gathers_fresh_rows_from_the_table(monkeypatch):
sent = []
monkeypatch.setattr(
pp_utils.torch.distributed,
"broadcast",
lambda tensor, **kw: sent.append(tensor),
)
handler = _cuda_handler()
# The batch's single row maps to request-state row 2.
batch = _batch(num_computed=[10], prefill_len=[8], num_scheduled=[1])
batch.idx_mapping = torch.tensor([2], dtype=torch.int64, device="cuda")
table = torch.arange(20, dtype=torch.int64, device="cuda").view(4, 5)
handler.broadcast_drafts(table, batch)
assert sent[0].shape == (1, 5)
# The payload is a gather into a fresh tensor: propose() overwrites its
# persistent buffer on the next step, possibly before this send completes.
assert sent[0].data_ptr() != table.data_ptr()
assert sent[0].cpu().tolist() == [table[2].cpu().tolist()]
# An all-prefill batch sends nothing (receive() enqueues nothing either).
sent.clear()
prefill_batch = _batch(num_computed=[0], prefill_len=[4096], num_scheduled=[448])
prefill_batch.idx_mapping = prefill_batch.idx_mapping.cuda()
handler.broadcast_drafts(table, prefill_batch)
assert sent == []
torch.accelerator.synchronize()