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:
@@ -15,6 +15,7 @@ from tests.kernels.quantization.nvfp4_utils import (
|
||||
dequantize_nvfp4_to_dtype,
|
||||
)
|
||||
from tests.kernels.utils import torch_experts
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed import (
|
||||
get_dp_group,
|
||||
@@ -33,7 +34,9 @@ from vllm.model_executor.layers.fused_moe.config import (
|
||||
FusedMoEQuantConfig,
|
||||
RoutingMethodType,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils.fp8_utils import is_fp8
|
||||
from vllm.model_executor.layers.quantization.utils.quant_utils import (
|
||||
QuantKey,
|
||||
kFp8Dynamic128Sym,
|
||||
kFp8DynamicTensorSym,
|
||||
kFp8DynamicTokenSym,
|
||||
@@ -165,31 +168,34 @@ class Config:
|
||||
|
||||
return vllm_config, env_dict
|
||||
|
||||
def fp8_quant_key_pair(self) -> tuple[QuantKey, QuantKey]:
|
||||
"""Derive the (weight_quant_key, activation_quant_key) pair an FP8
|
||||
quant config of this shape corresponds to (either OCP or FNUZ FP8,
|
||||
see ``current_platform.fp8_dtype()``)."""
|
||||
if self.quant_block_shape is not None:
|
||||
return kFp8Static128BlockSym, kFp8Dynamic128Sym
|
||||
if self.is_per_out_ch_quant:
|
||||
return (
|
||||
kFp8StaticChannelSym,
|
||||
kFp8DynamicTokenSym
|
||||
if self.is_per_act_token_quant
|
||||
else kFp8StaticTensorSym,
|
||||
)
|
||||
return (
|
||||
kFp8StaticTensorSym,
|
||||
kFp8DynamicTensorSym
|
||||
if self.is_per_act_token_quant
|
||||
else kFp8StaticTensorSym,
|
||||
)
|
||||
|
||||
def fe_supports_quant_scheme(self) -> bool:
|
||||
"""Check if the fused experts class supports this quant config.
|
||||
See https://github.com/ROCm/aiter/issues/2419 for AITER gaps."""
|
||||
if self.quant_config is None or self.quant_dtype is None:
|
||||
return True
|
||||
if self.quant_dtype != torch.float8_e4m3fn:
|
||||
if not is_fp8(self.quant_dtype):
|
||||
return True
|
||||
# Derive QuantKeys from test config
|
||||
if self.quant_block_shape is not None:
|
||||
w_key = kFp8Static128BlockSym
|
||||
a_key = kFp8Dynamic128Sym
|
||||
elif self.is_per_out_ch_quant:
|
||||
w_key = kFp8StaticChannelSym
|
||||
a_key = (
|
||||
kFp8DynamicTokenSym
|
||||
if self.is_per_act_token_quant
|
||||
else kFp8StaticTensorSym
|
||||
)
|
||||
else:
|
||||
w_key = kFp8StaticTensorSym
|
||||
a_key = (
|
||||
kFp8DynamicTensorSym
|
||||
if self.is_per_act_token_quant
|
||||
else kFp8StaticTensorSym
|
||||
)
|
||||
w_key, a_key = self.fp8_quant_key_pair()
|
||||
fe_cls = self.fused_experts_type
|
||||
if hasattr(fe_cls, "_supports_quant_scheme"):
|
||||
try:
|
||||
@@ -199,10 +205,7 @@ class Config:
|
||||
return True
|
||||
|
||||
def is_fp8_block_quantized(self):
|
||||
return (
|
||||
self.quant_dtype == torch.float8_e4m3fn
|
||||
and self.quant_block_shape is not None
|
||||
)
|
||||
return is_fp8(self.quant_dtype) and self.quant_block_shape is not None
|
||||
|
||||
def is_batched_prepare_finalize(self):
|
||||
info = prepare_finalize_info(self.prepare_finalize_type)
|
||||
@@ -334,6 +337,11 @@ class Config:
|
||||
return False, "Needs Aiter, but Aiter not available."
|
||||
if self.needs_mori() and not has_mori(): # noqa: SIM103
|
||||
return False, "Needs MoRI, but MoRI not available."
|
||||
if self.needs_mori() and not rocm_aiter_ops.is_fused_moe_enabled():
|
||||
return False, (
|
||||
"Mori requires AITER's fused-moe backend to be enabled "
|
||||
"(VLLM_ROCM_USE_AITER=1 and VLLM_ROCM_USE_AITER_MOE=1)."
|
||||
)
|
||||
|
||||
try:
|
||||
if not self.fused_experts_type._supports_current_device():
|
||||
@@ -370,7 +378,7 @@ class WeightTensors:
|
||||
def is_quantized(self) -> bool:
|
||||
# or w1_scale is not None?
|
||||
return (
|
||||
self.w1.dtype == torch.float8_e4m3fn
|
||||
is_fp8(self.w1.dtype)
|
||||
or self.w1.dtype == torch.uint8
|
||||
or self.w1.dtype == torch.int8
|
||||
)
|
||||
|
||||
@@ -86,14 +86,14 @@ MK_FUSED_EXPERT_TYPES: list[mk.FusedMoEExpertsModular] = []
|
||||
standard_format = mk.FusedMoEActivationFormat.Standard
|
||||
batched_format = mk.FusedMoEActivationFormat.BatchedExperts
|
||||
common_float_types: list[torch.dtype | str] = [
|
||||
torch.float8_e4m3fn,
|
||||
current_platform.fp8_dtype(),
|
||||
torch.bfloat16,
|
||||
torch.float16,
|
||||
torch.float32,
|
||||
]
|
||||
common_float_and_int_types = common_float_types + [torch.int8]
|
||||
nvfp4_types = ["nvfp4"]
|
||||
fp8_types = [torch.float8_e4m3fn]
|
||||
fp8_types = [current_platform.fp8_dtype()]
|
||||
|
||||
|
||||
def register_prepare_and_finalize(
|
||||
@@ -324,7 +324,9 @@ if has_aiter():
|
||||
register_experts(
|
||||
AiterExperts,
|
||||
standard_format,
|
||||
fp8_types,
|
||||
# AiterExperts also supports the fully-unquantized (None, None)
|
||||
# scheme (see SUPPORTED_W_A in rocm_aiter_moe.py), not just fp8.
|
||||
common_float_types,
|
||||
blocked_quantization_support=True,
|
||||
needs_aiter=True,
|
||||
)
|
||||
@@ -397,35 +399,35 @@ MK_QUANT_CONFIGS: list[TestMoEQuantConfig | None] = [
|
||||
None,
|
||||
# per-channel / per-column weights and per-tensor activations
|
||||
TestMoEQuantConfig(
|
||||
quant_dtype=torch.float8_e4m3fn,
|
||||
quant_dtype=current_platform.fp8_dtype(),
|
||||
per_out_ch_quant=True,
|
||||
per_act_token_quant=False,
|
||||
block_shape=None,
|
||||
),
|
||||
# per-channel / per-column weights and per-token activations
|
||||
TestMoEQuantConfig(
|
||||
quant_dtype=torch.float8_e4m3fn,
|
||||
quant_dtype=current_platform.fp8_dtype(),
|
||||
per_out_ch_quant=True,
|
||||
per_act_token_quant=True,
|
||||
block_shape=None,
|
||||
),
|
||||
# per-tensor weights and per-tensor activations
|
||||
TestMoEQuantConfig(
|
||||
quant_dtype=torch.float8_e4m3fn,
|
||||
quant_dtype=current_platform.fp8_dtype(),
|
||||
per_out_ch_quant=False,
|
||||
per_act_token_quant=False,
|
||||
block_shape=None,
|
||||
),
|
||||
# per-tensor weights and per-token activations
|
||||
TestMoEQuantConfig(
|
||||
quant_dtype=torch.float8_e4m3fn,
|
||||
quant_dtype=current_platform.fp8_dtype(),
|
||||
per_out_ch_quant=False,
|
||||
per_act_token_quant=True,
|
||||
block_shape=None,
|
||||
),
|
||||
# block-quantized weights and 128 block per-token activations
|
||||
TestMoEQuantConfig(
|
||||
quant_dtype=torch.float8_e4m3fn,
|
||||
quant_dtype=current_platform.fp8_dtype(),
|
||||
per_out_ch_quant=False,
|
||||
per_act_token_quant=False,
|
||||
block_shape=[128, 128],
|
||||
|
||||
@@ -384,9 +384,8 @@ def test_routing_data_from_sparse_topk_parity(n_tokens, n_experts, topk):
|
||||
|
||||
make_routing_data = gptoss_moe.make_routing_data
|
||||
routing_data_from_sparse_topk = gptoss_moe.routing_data_from_sparse_topk
|
||||
use_legacy_triton_kernels = gptoss_moe.use_legacy_triton_kernels
|
||||
|
||||
if use_legacy_triton_kernels:
|
||||
if gptoss_moe.triton_kernels_version == "3.5.1":
|
||||
pytest.skip("SparseMatrix path requires triton_kernels v3.6.0+")
|
||||
|
||||
from triton_kernels.topk import topk as topk_fn
|
||||
|
||||
@@ -37,6 +37,7 @@ from .modular_kernel_tools.parallel_utils import (
|
||||
ProcessGroupInfo,
|
||||
parallel_launch_with_config,
|
||||
)
|
||||
from .utils import check_accuracy
|
||||
|
||||
has_any_multi_gpu_package = (
|
||||
has_deep_ep() or has_deep_gemm() or has_flashinfer_cutlass_fused_moe()
|
||||
@@ -47,12 +48,6 @@ meets_multi_gpu_requirements = pytest.mark.skipif(
|
||||
reason="Requires deep_ep or deep_gemm or flashinfer packages",
|
||||
)
|
||||
|
||||
if current_platform.is_fp8_fnuz():
|
||||
pytest.skip(
|
||||
"Tests in this file require float8_e4m3fn and platform does not support",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
|
||||
def format_result(verbose, msg, ex=None):
|
||||
if ex is not None:
|
||||
@@ -70,6 +65,28 @@ def format_result(verbose, msg, ex=None):
|
||||
print(".", end="")
|
||||
|
||||
|
||||
def assert_aiter_quant_scheme_case(config: Config) -> None:
|
||||
"""Make the AITER (weight_quant_key, activation_quant_key) pair this
|
||||
config exercises explicit, instead of AiterExperts being reached only
|
||||
indirectly through the general quant-config sweep.
|
||||
See https://github.com/vllm-project/vllm/issues/54966."""
|
||||
fe_cls = config.fused_experts_type
|
||||
if getattr(fe_cls, "__name__", "") != "AiterExperts":
|
||||
return
|
||||
|
||||
if config.quant_config is None:
|
||||
w_key, a_key = None, None
|
||||
else:
|
||||
w_key, a_key = config.fp8_quant_key_pair()
|
||||
|
||||
assert fe_cls._supports_quant_scheme(w_key, a_key), (
|
||||
f"AITER case (weight_key={w_key}, activation_key={a_key}) reached "
|
||||
"the modular-kernel harness, but AiterExperts._supports_quant_scheme "
|
||||
"does not declare it supported."
|
||||
)
|
||||
print(f"[AITER case] weight_key={w_key}, activation_key={a_key}")
|
||||
|
||||
|
||||
def rank_worker(
|
||||
pgi: ProcessGroupInfo,
|
||||
vllm_config: VllmConfig,
|
||||
@@ -125,6 +142,25 @@ def rank_worker(
|
||||
count -= 1
|
||||
continue
|
||||
|
||||
# Skip unsupported: AITER x DeepEP-HT/Mori dispatch crashes
|
||||
# with an illegal memory access at world_size>1 on gfx942.
|
||||
# https://github.com/vllm-project/vllm/issues/57029
|
||||
if (
|
||||
config.world_size > 1
|
||||
and getattr(config.fused_experts_type, "__name__", "") == "AiterExperts"
|
||||
and getattr(config.prepare_finalize_type, "__name__", "")
|
||||
in ("DeepEPHTPrepareAndFinalize", "MoriPrepareAndFinalize")
|
||||
):
|
||||
print(
|
||||
f"Skipping[{pgi.rank}]: m={m}, topk={topk}"
|
||||
" (AITER x DeepEP-HT/Mori illegal memory access,"
|
||||
" https://github.com/vllm-project/vllm/issues/57029)"
|
||||
)
|
||||
count -= 1
|
||||
continue
|
||||
|
||||
assert_aiter_quant_scheme_case(config)
|
||||
|
||||
# modular kernel out
|
||||
mk_out = run_modular_kernel(pgi, vllm_config, config, weights, rank_tensors)
|
||||
|
||||
@@ -152,32 +188,7 @@ def rank_worker(
|
||||
and config.quant_config is not None
|
||||
)
|
||||
if is_aiter_fp8:
|
||||
diff = (ref_out - mk_out).abs()
|
||||
n_total = diff.numel()
|
||||
max_diff = diff.max().item()
|
||||
n_exceed = int((diff > atol).sum().item())
|
||||
pct_exceed = n_exceed / n_total * 100
|
||||
# FP8 hw matmul vs f32 reference: up to ~4% of
|
||||
# elements may exceed base tolerance, but max
|
||||
# error should stay within 3x base tolerance.
|
||||
max_pct_allowed = 5.0
|
||||
relaxed_atol = atol * 4
|
||||
print(
|
||||
f"[AITER FP8 precision] "
|
||||
f"max_diff={max_diff:.6f}, "
|
||||
f"exceed_atol={n_exceed}/{n_total} "
|
||||
f"({pct_exceed:.4f}%), "
|
||||
f"max_pct_allowed={max_pct_allowed}%, "
|
||||
f"relaxed_limit={relaxed_atol}"
|
||||
)
|
||||
assert pct_exceed <= max_pct_allowed, (
|
||||
f"AITER FP8: {pct_exceed:.2f}% elements exceed "
|
||||
f"atol={atol} (max allowed {max_pct_allowed}%)"
|
||||
)
|
||||
assert max_diff <= relaxed_atol, (
|
||||
f"AITER FP8: max_diff={max_diff:.6f} exceeds "
|
||||
f"relaxed limit {relaxed_atol}"
|
||||
)
|
||||
check_accuracy(ref_out, mk_out, atol=atol, rtol=rtol, percent=0.9)
|
||||
else:
|
||||
torch.testing.assert_close(ref_out, mk_out, atol=atol, rtol=rtol)
|
||||
format_result(verbose, config.describe())
|
||||
|
||||
@@ -1520,6 +1520,115 @@ def test_draft_model_enables_async_scheduling_by_default():
|
||||
assert cfg.scheduler_config.async_scheduling is True
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
@pytest.mark.parametrize("tp_size", [1, 2])
|
||||
@pytest.mark.parametrize("target_ep", [False, True], ids=["ep-off", "ep-on"])
|
||||
@pytest.mark.parametrize(
|
||||
("method", "draft_is_moe"),
|
||||
[
|
||||
pytest.param("draft_model", False, id="dense-draft"),
|
||||
pytest.param("eagle", False, id="eagle"),
|
||||
pytest.param("eagle3", False, id="eagle3"),
|
||||
pytest.param("draft_model", True, id="moe-draft"),
|
||||
pytest.param("mtp", True, id="mtp"),
|
||||
pytest.param("dspark", True, id="dspark"),
|
||||
],
|
||||
)
|
||||
def test_draft_inherits_ep_only_for_moe(
|
||||
tmp_path: Path,
|
||||
tp_size: int,
|
||||
target_ep: bool,
|
||||
method: str,
|
||||
draft_is_moe: bool,
|
||||
):
|
||||
"""Validate final draft configs without loading weights or mocking validation."""
|
||||
from transformers import LlamaConfig, MixtralConfig
|
||||
|
||||
from vllm.transformers_utils.configs.deepseek_v4 import DeepseekV4Config
|
||||
|
||||
common = dict(
|
||||
hidden_size=128,
|
||||
intermediate_size=256,
|
||||
num_hidden_layers=2,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=2,
|
||||
vocab_size=128,
|
||||
max_position_embeddings=2048,
|
||||
)
|
||||
if method in ("mtp", "dspark"):
|
||||
target_hf_config = DeepseekV4Config(
|
||||
architectures=["DeepseekV4ForCausalLM"],
|
||||
n_routed_experts=4,
|
||||
num_experts_per_tok=2,
|
||||
num_nextn_predict_layers=1,
|
||||
compress_ratios=[1, 1],
|
||||
head_dim=32,
|
||||
**common,
|
||||
)
|
||||
else:
|
||||
target_hf_config = MixtralConfig(
|
||||
architectures=["MixtralForCausalLM"], num_local_experts=4, **common
|
||||
)
|
||||
target_path = tmp_path / "target"
|
||||
draft_path = tmp_path / "draft"
|
||||
_write_json(target_path / "config.json", target_hf_config.to_dict())
|
||||
_write_json(
|
||||
draft_path / "config.json",
|
||||
LlamaConfig(architectures=["LlamaForCausalLM"], **common).to_dict(),
|
||||
)
|
||||
target_model_config = ModelConfig(
|
||||
model=str(target_path), tokenizer_mode="skip", max_model_len=2048
|
||||
)
|
||||
target_parallel_config = ParallelConfig(
|
||||
tensor_parallel_size=tp_size,
|
||||
enable_expert_parallel=target_ep,
|
||||
distributed_executor_backend="mp",
|
||||
)
|
||||
target_model_config.verify_with_parallel_config(target_parallel_config)
|
||||
speculative_config = SpeculativeConfig(
|
||||
method=method,
|
||||
model=str(target_path if draft_is_moe else draft_path),
|
||||
num_speculative_tokens=1,
|
||||
target_model_config=target_model_config,
|
||||
target_parallel_config=target_parallel_config,
|
||||
)
|
||||
|
||||
assert speculative_config.method == method
|
||||
assert speculative_config.draft_model_config.is_moe is draft_is_moe
|
||||
assert speculative_config.draft_parallel_config.enable_expert_parallel is (
|
||||
target_ep and draft_is_moe
|
||||
)
|
||||
assert speculative_config.draft_parallel_config.tensor_parallel_size == tp_size
|
||||
assert target_parallel_config.enable_expert_parallel is target_ep
|
||||
assert target_parallel_config.tensor_parallel_size == tp_size
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
@pytest.mark.parametrize("target_ep", [False, True], ids=["ep-off", "ep-on"])
|
||||
@pytest.mark.parametrize("pass_none", [False, True], ids=["omitted", "explicit-none"])
|
||||
def test_draft_parallel_config_preserves_ep_without_model(
|
||||
target_ep: bool, pass_none: bool
|
||||
):
|
||||
"""Legacy callers without draft model information keep EP inheritance."""
|
||||
target_parallel_config = ParallelConfig(
|
||||
tensor_parallel_size=2,
|
||||
enable_expert_parallel=target_ep,
|
||||
distributed_executor_backend="mp",
|
||||
)
|
||||
if pass_none:
|
||||
draft_parallel_config = SpeculativeConfig.create_draft_parallel_config(
|
||||
target_parallel_config, 2, draft_model_config=None
|
||||
)
|
||||
else:
|
||||
draft_parallel_config = SpeculativeConfig.create_draft_parallel_config(
|
||||
target_parallel_config, 2
|
||||
)
|
||||
|
||||
assert draft_parallel_config.enable_expert_parallel is target_ep
|
||||
assert draft_parallel_config.tensor_parallel_size == 2
|
||||
assert target_parallel_config.enable_expert_parallel is target_ep
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("method", "parallel_drafting", "expected_slots"),
|
||||
[
|
||||
|
||||
@@ -243,14 +243,19 @@ def create_and_prepopulate_kv_cache(
|
||||
class MockAttentionLayer:
|
||||
"""A mock attention layer for testing."""
|
||||
|
||||
def __init__(self, device: torch.device):
|
||||
def __init__(
|
||||
self,
|
||||
device: torch.device,
|
||||
k_scale: float = 1.0,
|
||||
v_scale: float = 1.0,
|
||||
):
|
||||
self._q_scale = torch.tensor(1.0, device=device)
|
||||
self._k_scale = torch.tensor(1.0, device=device)
|
||||
self._v_scale = torch.tensor(1.0, device=device)
|
||||
self._k_scale = torch.tensor(k_scale, device=device)
|
||||
self._v_scale = torch.tensor(v_scale, device=device)
|
||||
# Add float versions for flashinfer
|
||||
self._q_scale_float = 1.0
|
||||
self._k_scale_float = 1.0
|
||||
self._v_scale_float = 1.0
|
||||
self._k_scale_float = k_scale
|
||||
self._v_scale_float = v_scale
|
||||
|
||||
|
||||
def _clone_kv_cache_in_layout(
|
||||
@@ -285,6 +290,8 @@ def run_attention_backend(
|
||||
kv_cache_dtype: str = "auto",
|
||||
sinks: torch.Tensor | None = None,
|
||||
use_cuda_graph: bool = False,
|
||||
layer_k_scale: float = 1.0,
|
||||
layer_v_scale: float = 1.0,
|
||||
) -> torch.Tensor:
|
||||
"""Run attention computation using the specified backend's AttentionImpl."""
|
||||
use_direct_block_mask = is_torch_equal_or_newer("2.9.0.dev0")
|
||||
@@ -356,7 +363,7 @@ def run_attention_backend(
|
||||
)
|
||||
|
||||
# Create mock layer and output buffer
|
||||
mock_layer = MockAttentionLayer(device)
|
||||
mock_layer = MockAttentionLayer(device, layer_k_scale, layer_v_scale)
|
||||
output = torch.empty_like(query)
|
||||
|
||||
if is_quantized_kv_cache(kv_cache_dtype) and impl.supports_quant_query_input:
|
||||
@@ -386,9 +393,11 @@ def run_attention_backend(
|
||||
)
|
||||
graph.replay()
|
||||
else:
|
||||
output = impl.forward(
|
||||
backend_output = impl.forward(
|
||||
mock_layer, query, key, value, kv_cache, attn_metadata, output=output
|
||||
)
|
||||
if backend_output is not None:
|
||||
output = backend_output
|
||||
|
||||
return output
|
||||
|
||||
@@ -413,6 +422,8 @@ def _test_backend_correctness(
|
||||
model_dtype: torch.dtype | None = None,
|
||||
max_num_seqs: int | None = None,
|
||||
max_num_batched_tokens: int | None = None,
|
||||
layer_k_scale: float = 1.0,
|
||||
layer_v_scale: float = 1.0,
|
||||
):
|
||||
"""Test that all backends produce similar outputs to a reference implementation
|
||||
using FlexAttention or an explicit attention-sink reference.
|
||||
@@ -687,6 +698,8 @@ def _test_backend_correctness(
|
||||
kv_cache_dtype=kv_cache_dtype,
|
||||
sinks=sinks,
|
||||
use_cuda_graph=use_cuda_graph,
|
||||
layer_k_scale=layer_k_scale,
|
||||
layer_v_scale=layer_v_scale,
|
||||
)
|
||||
|
||||
# Check shape and dtype consistency
|
||||
@@ -1317,6 +1330,45 @@ def test_sliding_window_backend_correctness(
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm-specific test")
|
||||
def test_rocm_aiter_fa_unquantized_cache_ignores_kv_scales(
|
||||
default_vllm_config,
|
||||
):
|
||||
"""Stale scale tensors must not affect an unquantized KV cache."""
|
||||
from vllm._aiter_ops import is_aiter_found_and_supported
|
||||
|
||||
if not is_aiter_found_and_supported():
|
||||
pytest.skip("AITER is required")
|
||||
|
||||
def sliding_window_mask_mod(
|
||||
b: torch.Tensor,
|
||||
h: torch.Tensor,
|
||||
q_idx: torch.Tensor,
|
||||
kv_idx: torch.Tensor,
|
||||
*,
|
||||
context_len: int,
|
||||
sliding_window: int,
|
||||
):
|
||||
causal_mask = q_idx + context_len >= kv_idx
|
||||
window_mask = q_idx + context_len - kv_idx < sliding_window
|
||||
return causal_mask & window_mask
|
||||
|
||||
model = "microsoft/Phi-tiny-MoE-instruct"
|
||||
batch_spec = BATCH_SPECS["small_decode"]
|
||||
model_config = ModelConfig(model=model, max_model_len=max(batch_spec.seq_lens))
|
||||
sliding_window = model_config.get_sliding_window()
|
||||
assert sliding_window is not None
|
||||
|
||||
_test_backend_correctness(
|
||||
batch_spec,
|
||||
model,
|
||||
[AttentionBackendEnum.ROCM_AITER_FA],
|
||||
partial(sliding_window_mask_mod, sliding_window=sliding_window),
|
||||
layer_k_scale=0.25,
|
||||
layer_v_scale=0.5,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"batch_spec_name",
|
||||
[
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Replay fixed chat histories and check per-turn cache hits and metrics."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from openai.types.chat import ChatCompletionMessageParam
|
||||
from prometheus_client.parser import text_string_to_metric_families
|
||||
|
||||
from tests.utils import RemoteOpenAIServer
|
||||
|
||||
MODEL = "Qwen/Qwen3.5-0.8B"
|
||||
NUM_CONVERSATIONS = 8
|
||||
MAX_TOKENS = 32
|
||||
# Long first turns leave room for hybrid cache alignment and MTP recomputation.
|
||||
MIN_PROMPT_TOKENS = 2048
|
||||
METRICS_TIMEOUT = 30
|
||||
|
||||
|
||||
def _user_turns(conversation: int) -> list[str]:
|
||||
records = "\n".join(
|
||||
f"Sensor {conversation}-{i}: temperature {20 + i % 10} C, "
|
||||
f"humidity {40 + i % 20} percent."
|
||||
for i in range(160 + conversation)
|
||||
)
|
||||
return [
|
||||
f"Session {conversation}. Summarize these sensor readings briefly:\n{records}",
|
||||
"Which readings should an operator investigate first? Explain briefly.",
|
||||
"Suggest two checks the operator should perform next.",
|
||||
]
|
||||
|
||||
|
||||
async def _prefix_cache_counters(
|
||||
client: httpx.AsyncClient,
|
||||
) -> tuple[float, float]:
|
||||
response = await client.get("/metrics")
|
||||
response.raise_for_status()
|
||||
names = ("vllm:prefix_cache_queries_total", "vllm:prefix_cache_hits_total")
|
||||
counters: dict[str, float] = {}
|
||||
for family in text_string_to_metric_families(response.text):
|
||||
for sample in family.samples:
|
||||
if sample.name in names:
|
||||
counters[sample.name] = counters.get(sample.name, 0) + sample.value
|
||||
assert all(name in counters for name in names), (
|
||||
f"missing prefix-cache metrics: {set(names) - counters.keys()}"
|
||||
)
|
||||
return counters[names[0]], counters[names[1]]
|
||||
|
||||
|
||||
async def _wait_for_counters(
|
||||
client: httpx.AsyncClient, expected: tuple[float, float]
|
||||
) -> None:
|
||||
"""Allow engine stats to reach the frontend after completions are returned."""
|
||||
deadline = asyncio.get_running_loop().time() + METRICS_TIMEOUT
|
||||
while True:
|
||||
actual = await _prefix_cache_counters(client)
|
||||
if actual == expected:
|
||||
return
|
||||
assert all(a <= e for a, e in zip(actual, expected)), (
|
||||
f"prefix-cache counters exceeded usage: {actual=}, {expected=}"
|
||||
)
|
||||
assert asyncio.get_running_loop().time() < deadline, (
|
||||
f"prefix-cache counters did not match usage: {actual=}, {expected=}"
|
||||
)
|
||||
await asyncio.sleep(0.1)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def server(request):
|
||||
args = ["--enable-prompt-tokens-details"]
|
||||
if request.param:
|
||||
args += [
|
||||
"--speculative-config",
|
||||
json.dumps({"method": "mtp", "num_speculative_tokens": 1}),
|
||||
]
|
||||
with RemoteOpenAIServer(MODEL, args) as remote_server:
|
||||
yield remote_server
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"server, min_hit_rate",
|
||||
# MTP re-prefills an extra block; both floors reject one more missed block.
|
||||
[pytest.param(False, 0.90, id="base"), pytest.param(True, 0.75, id="mtp")],
|
||||
indirect=["server"],
|
||||
)
|
||||
async def test_prefix_cache_hit_rate(
|
||||
server: RemoteOpenAIServer, min_hit_rate: float
|
||||
) -> None:
|
||||
# Isolate sessions so another conversation cannot hide a cache miss.
|
||||
salts = [uuid4().hex for _ in range(NUM_CONVERSATIONS)]
|
||||
histories: list[list[ChatCompletionMessageParam]] = [
|
||||
[] for _ in range(NUM_CONVERSATIONS)
|
||||
]
|
||||
prompt_lengths: list[list[int]] = [[] for _ in range(NUM_CONVERSATIONS)]
|
||||
|
||||
async with (
|
||||
server.get_async_client() as client,
|
||||
httpx.AsyncClient(base_url=server.url_root, timeout=METRICS_TIMEOUT) as metrics,
|
||||
):
|
||||
|
||||
async def run_conversation(session: int, *, replay: bool) -> tuple[int, int]:
|
||||
history = histories[session]
|
||||
queries = hits = 0
|
||||
for turn, user_text in enumerate(_user_turns(session)):
|
||||
if not replay:
|
||||
history.append({"role": "user", "content": user_text})
|
||||
# Reuse the original replies, even if replay generates different ones.
|
||||
response = await client.chat.completions.create(
|
||||
model=MODEL,
|
||||
messages=history[: 2 * turn + 1],
|
||||
temperature=0,
|
||||
max_tokens=MAX_TOKENS,
|
||||
extra_body={"cache_salt": salts[session]},
|
||||
)
|
||||
usage = response.usage
|
||||
assert usage is not None
|
||||
assert usage.prompt_tokens_details is not None
|
||||
prompt = usage.prompt_tokens
|
||||
cached = usage.prompt_tokens_details.cached_tokens
|
||||
context = f"{session=}, {turn=}, {replay=}: {cached=}, {prompt=}"
|
||||
assert cached is not None, context
|
||||
assert 0 <= cached < prompt, context
|
||||
assert prompt >= MIN_PROMPT_TOKENS, context
|
||||
if not replay and turn == 0:
|
||||
assert cached == 0, context
|
||||
else:
|
||||
assert cached / prompt >= min_hit_rate, (
|
||||
f"{context}, {min_hit_rate=}"
|
||||
)
|
||||
if replay:
|
||||
assert prompt == prompt_lengths[session][turn], context
|
||||
else:
|
||||
prompt_lengths[session].append(prompt)
|
||||
history.append(
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": response.choices[0].message.content or "",
|
||||
}
|
||||
)
|
||||
queries += prompt
|
||||
hits += cached
|
||||
return queries, hits
|
||||
|
||||
queries, hits = await _prefix_cache_counters(metrics)
|
||||
for replay in (False, True):
|
||||
counts = await asyncio.gather(
|
||||
*(run_conversation(i, replay=replay) for i in range(NUM_CONVERSATIONS))
|
||||
)
|
||||
queries += sum(prompt for prompt, _ in counts)
|
||||
hits += sum(cached for _, cached in counts)
|
||||
await _wait_for_counters(metrics, (queries, hits))
|
||||
@@ -193,6 +193,22 @@ def test_get_num_unfinished_requests():
|
||||
assert scheduler.get_num_unfinished_requests() == len(requests) - i - 1
|
||||
|
||||
|
||||
def test_max_num_active_seqs_caps_admission():
|
||||
"""Admission is capped by max_num_active_seqs, not max_num_seqs."""
|
||||
scheduler = create_scheduler(max_num_seqs=16, max_num_active_seqs=3)
|
||||
requests = create_requests(num_requests=10)
|
||||
for request in requests:
|
||||
scheduler.add_request(request)
|
||||
|
||||
output = scheduler.schedule()
|
||||
|
||||
assert len(output.scheduled_new_reqs) == 3
|
||||
assert len(scheduler.running) == 3
|
||||
assert len(scheduler.waiting) == 7
|
||||
# Execution capacity is untouched.
|
||||
assert scheduler.max_num_running_reqs == 16
|
||||
|
||||
|
||||
def _bind_hisparse_connector(scheduler):
|
||||
connector = object.__new__(HiSparseConnector)
|
||||
connector.connector_scheduler = HiSparseConnectorScheduler(async_speculative=False)
|
||||
|
||||
@@ -52,6 +52,7 @@ def mock_kv(matched_tokens: int, is_async: bool, num_defers_before_matching: int
|
||||
def create_scheduler(
|
||||
model: str = "facebook/opt-125m",
|
||||
max_num_seqs: int = 16,
|
||||
max_num_active_seqs: int | None = None,
|
||||
max_num_batched_tokens: int = 8192,
|
||||
enable_chunked_prefill: bool = True,
|
||||
enable_prefix_caching: bool = False,
|
||||
@@ -107,6 +108,7 @@ def create_scheduler(
|
||||
max_model_len = max_num_batched_tokens
|
||||
scheduler_config = SchedulerConfig(
|
||||
max_num_seqs=max_num_seqs,
|
||||
max_num_active_seqs=max_num_active_seqs,
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
max_model_len=max_model_len,
|
||||
long_prefill_token_threshold=long_prefill_token_threshold,
|
||||
|
||||
@@ -133,7 +133,56 @@ def test_base_config_parser():
|
||||
assert result.num_attention_heads == 16
|
||||
assert result.num_hidden_layers == 24
|
||||
assert result.weight_byte_size == 2 # float16 is 2 bytes
|
||||
assert result.activation_byte_size == 2 # default activation size
|
||||
assert result.activation_byte_size == 2 # float16 activations are 2 bytes
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"model_dtype,expected_byte_size",
|
||||
[("float16", 2), ("bfloat16", 2), ("float32", 4)],
|
||||
)
|
||||
def test_base_config_parser_activation_byte_size_follows_dtype(
|
||||
model_dtype: str, expected_byte_size: int
|
||||
):
|
||||
"""Activation traffic is sized from the model's compute dtype.
|
||||
|
||||
Activations are produced in the model dtype, so pinning them to 2 bytes
|
||||
under-reported memory traffic by half for a float32 model while that same
|
||||
model's weight traffic was sized correctly.
|
||||
"""
|
||||
hf_config = Qwen3Config(
|
||||
hidden_size=2048,
|
||||
num_attention_heads=16,
|
||||
num_hidden_layers=24,
|
||||
)
|
||||
vllm_config = create_mock_vllm_config(hf_config, model_dtype=model_dtype)
|
||||
|
||||
result = BaseConfigParser().parse(ParsedArgs(), vllm_config)
|
||||
|
||||
assert result.activation_byte_size == expected_byte_size
|
||||
assert result.weight_byte_size == expected_byte_size
|
||||
|
||||
|
||||
def test_attention_read_bytes_scale_with_activation_dtype():
|
||||
"""A float32 model reads twice the activation bytes of a bfloat16 one."""
|
||||
hf_config = Qwen3Config(
|
||||
hidden_size=2048,
|
||||
num_attention_heads=16,
|
||||
num_key_value_heads=16,
|
||||
num_hidden_layers=4,
|
||||
)
|
||||
ctx = ExecutionContext.from_single_request(
|
||||
num_tokens=128, context_len=128, is_prefill=True
|
||||
)
|
||||
|
||||
bf16 = AttentionMetrics.from_vllm_config(
|
||||
create_mock_vllm_config(hf_config, model_dtype="bfloat16")
|
||||
).get_read_bytes_breakdown(ctx)
|
||||
fp32 = AttentionMetrics.from_vllm_config(
|
||||
create_mock_vllm_config(hf_config, model_dtype="float32")
|
||||
).get_read_bytes_breakdown(ctx)
|
||||
|
||||
# qkv_input is pure activation traffic, so it doubles exactly.
|
||||
assert fp32["qkv_input"] == 2 * bf16["qkv_input"]
|
||||
|
||||
|
||||
def test_base_attention_config_parser_with_gqa():
|
||||
|
||||
Reference in New Issue
Block a user