Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 17:41:13 +00:00
1122 changed files with 60114 additions and 20956 deletions
@@ -359,7 +359,7 @@ def test_runtime_state_survives_sleep(level):
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.skipif(current_platform.is_xpu(), reason="Uses the CuMem allocator")
def test_level2_discards_ordinary_tensor_with_weights_tag():
"""Reproduce the level-2 variant for an ordinary tensor in weights."""
"""Discarded weights-tag memory is remapped; ROCm zeroes it over stale pages."""
allocator = get_mem_allocator_instance()
with allocator.use_memory_pool("weights"):
@@ -374,8 +374,9 @@ def test_level2_discards_ordinary_tensor_with_weights_tag():
torch.accelerator.synchronize()
assert (fake_weight.data_ptr(), ordinary_tensor.data_ptr()) == pointers
assert torch.all(fake_weight == 0xA5)
assert torch.all(ordinary_tensor == 0xA5)
expected = 0 if current_platform.is_rocm() else 0xA5
assert torch.all(fake_weight == expected)
assert torch.all(ordinary_tensor == expected)
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@@ -427,7 +428,9 @@ def test_cumem_with_cudagraph():
@pytest.mark.parametrize("level", [1, 2], ids=["sleep-1", "sleep-2"])
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
@pytest.mark.skipif(not current_platform.is_cuda(), reason="cuMem CUDA graph pool")
@pytest.mark.skipif(
not current_platform.is_cuda_alike(), reason="cuMem CUDA graph pool"
)
def test_cudagraph_pool_sleep(level):
"""Routing, and the graph pool backed up at both sleep levels and restored
in place by any wake."""
@@ -209,8 +209,20 @@ def _cudagraph_bytes(worker) -> int:
def _custom_ar_active(worker) -> bool:
from vllm.distributed.parallel_state import get_tp_group
ca_comm = get_tp_group().device_communicator.ca_comm
return ca_comm is not None and not ca_comm.disabled
comm = get_tp_group().device_communicator
return any(
c is not None and not c.disabled for c in (comm.ca_comm, comm.aiter_ar_comm)
)
def _capture_registers_buffers(worker) -> bool:
from vllm.distributed.parallel_state import get_tp_group
comm = get_tp_group().device_communicator
ca, aiter = comm.ca_comm, comm.aiter_ar_comm
return (ca is not None and ca._capture_registered) or (
aiter is not None and aiter.aiter_ca.enable_register_for_capturing
)
@pytest.mark.parametrize(
@@ -227,7 +239,9 @@ def _custom_ar_active(worker) -> bool:
ids=["full", "piecewise", "breakable", "custom-ar-tp2", "off-by-default"],
)
@create_new_process_for_each_test()
@pytest.mark.skipif(not current_platform.is_cuda(), reason="cuMem CUDA graph pool")
@pytest.mark.skipif(
not current_platform.is_cuda_alike(), reason="cuMem CUDA graph pool"
)
def test_sleep_cudagraph_pool(monkeypatch, mode, breakable, tp, offload):
"""Each capture site uses the pool, exact across sleeps; TP=2 needs
unregistered custom AR; off changes nothing."""
@@ -255,8 +269,10 @@ def test_sleep_cudagraph_pool(monkeypatch, mode, breakable, tp, offload):
assert all(graph_bytes) if offload else not any(graph_bytes)
if not offload:
return
if tp > 1 and not all(llm.collective_rpc(_custom_ar_active)):
pytest.skip("Custom allreduce is unavailable on these GPUs")
if tp > 1:
if not all(llm.collective_rpc(_custom_ar_active)):
pytest.skip("Custom allreduce is unavailable on these GPUs")
assert not any(llm.collective_rpc(_capture_registers_buffers))
prompt, params = "How are you?", SamplingParams(temperature=0, max_tokens=10)
expected = llm.generate(prompt, params)[0].outputs[0].text
for level in (1, 2):
@@ -268,6 +284,42 @@ def test_sleep_cudagraph_pool(monkeypatch, mode, breakable, tp, offload):
assert llm.generate(prompt, params)[0].outputs[0].text == expected
@multi_gpu_test(num_gpus=2)
@create_new_process_for_each_test()
@pytest.mark.skipif(not current_platform.is_rocm(), reason="AITER fused allreduce")
def test_sleep_cudagraph_pool_aiter_fused_ar_group_quant(monkeypatch):
"""The fused AITER AR + RMSNorm + per-group FP8 quant captures into the
cuMem pool without IPC-registering its input, across sleeps."""
for name, value in [
("VLLM_USE_V2_MODEL_RUNNER", "1"),
("VLLM_ROCM_USE_AITER", "1"),
("VLLM_ALLOW_INSECURE_SERIALIZATION", "1"),
]:
monkeypatch.setenv(name, value)
monkeypatch.delenv("NCCL_GRAPH_REGISTER", raising=False)
llm = LLM(
"Qwen/Qwen3-0.6B-FP8",
enable_sleep_mode=True,
sleep_mode_offload_cudagraph=True,
tensor_parallel_size=2,
max_model_len=1024,
compilation_config={"pass_config": {"fuse_allreduce_rms": True}},
)
if not all(llm.collective_rpc(_custom_ar_active)):
pytest.skip("AITER custom allreduce is unavailable on these GPUs")
assert not any(llm.collective_rpc(_capture_registers_buffers))
assert all(llm.collective_rpc(_cudagraph_bytes))
prompt, params = "How are you?", SamplingParams(temperature=0, max_tokens=10)
assert llm.generate(prompt, params)[0].outputs[0].text
for level in (1, 2):
llm.sleep(level=level)
llm.wake_up(tags=["weights"])
if level == 2:
llm.collective_rpc("reload_weights")
llm.wake_up(tags=["kv_cache"])
assert llm.generate(prompt, params)[0].outputs[0].text
@create_new_process_for_each_test()
def test_deep_sleep_async(gpu_memory_cleared):
async def test():
@@ -323,7 +375,6 @@ def _attn_kv_scales(model) -> dict[str, list[float]]:
}
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Segfaults on ROCm.")
@requires_fp8
@create_new_process_for_each_test()
def test_deep_sleep_compressed_tensors_kv_scales(
+47
View File
@@ -98,6 +98,17 @@ class _FakeSession:
return _FakeResponse()
class _FakeProfileSession:
def __init__(self) -> None:
self.url: str | None = None
self.headers: dict[str, str] | None = None
def post(self, *, url: str, headers: dict[str, str]):
self.url = url
self.headers = headers
return _FakeResponse()
def test_asr_dataset_sample_handles_local_audio_paths(tmp_path: Path) -> None:
audio_path = tmp_path / "earnings.wav"
_write_wav(audio_path, duration_s=0.1)
@@ -222,6 +233,42 @@ def test_async_request_openai_audio_handles_decoded_audio_arrays(
assert output.generated_text == "hello"
def test_audio_request_rejects_profile_endpoint() -> None:
request_input = RequestFuncInput(
prompt="",
api_url="http://localhost:8000/start_profile",
prompt_len=1,
output_len=32,
model="openai/whisper-large-v3",
)
with pytest.raises(ValueError, match="OpenAI Audio API"):
asyncio.run(
request_func_module.async_request_openai_audio(
request_input, _FakeProfileSession()
)
)
@pytest.mark.parametrize("endpoint", ["start_profile", "stop_profile"])
def test_audio_benchmark_profile_request_has_no_inference_payload(
endpoint: str,
) -> None:
session = _FakeProfileSession()
output = asyncio.run(
request_func_module.async_request_profile(
f"http://localhost:8000/{endpoint}",
session,
extra_headers={"X-Test-Header": "profile"},
)
)
assert output.success is True
assert session.url == f"http://localhost:8000/{endpoint}"
assert session.headers == {"X-Test-Header": "profile"}
_COHERE_ASR_PROMPT = (
"<|startofcontext|><|startoftranscript|>"
"<|emo:undefined|><|en|><|en|><|pnc|><|noitn|>"
@@ -183,6 +183,7 @@ def test_request_payload_is_accepted_by_the_server_schema():
"temperature": 0.7,
"top_p": 0.9,
"top_k": 20,
"min_p": 0.05,
"frequency_penalty": 0.2,
"presence_penalty": 0.1,
"repetition_penalty": 1.05,
@@ -217,9 +218,6 @@ def test_request_payload_is_accepted_by_the_server_schema():
assert set(seen["payload"]) <= set(ResponsesRequest.model_fields)
ResponsesRequest.model_validate(seen["payload"])
# `vllm bench serve` rejects --min-p for this backend for the same reason.
assert "min_p" not in ResponsesRequest.model_fields
def test_latency_accounting_matches_the_other_endpoints():
"""`latency - ttft` must equal `sum(itl)`.
@@ -1,270 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import logging
from contextlib import nullcontext
import pytest
from tests.compile.fusions_e2e.common import FUSION_LOG_PATTERNS
from tests.models.registry import HF_EXAMPLE_MODELS
from tests.utils import (
compare_two_settings,
create_new_process_for_each_test,
multi_gpu_test,
)
from vllm.config import (
CompilationMode,
)
from vllm.platforms import current_platform
from vllm.transformers_utils.repo_utils import hf_api
from vllm.utils.flashinfer import has_flashinfer
NVFP4_MODEL_ID = "nvidia/Llama-3.1-8B-Instruct-NVFP4"
NVFP4_HF_OVERRIDES = {
"num_hidden_layers": 4,
"hidden_size": 512,
"intermediate_size": 800,
"num_attention_heads": 4,
"num_key_value_heads": 1,
}
@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm AsyncTP contract")
def test_rocm_async_tp_bf16_output_correctness(caplog_mp_spawn):
"""Trained-model outputs must agree with unfused TP, including padded decode."""
# A snapshot path pins both servers and the comparison helper's tokenizer.
model = hf_api().snapshot_download(
"Qwen/Qwen3-0.6B", revision="c1899de289a04d12100db370d81485cdf75e47ca"
)
common_args = [
"--dtype",
"bfloat16",
"--load-format",
"auto",
"--tensor-parallel-size",
"2",
"--distributed-executor-backend",
"mp",
"--max-model-len",
"512",
"--max-num-batched-tokens",
"512",
"--max-num-seqs",
"8",
"--kv-cache-memory-bytes",
str(64 * 1024**2),
"--gpu-memory-utilization",
"0.01",
"--attention-backend",
"TRITON_ATTN",
"--disable-custom-all-reduce",
]
def settings(enabled):
return [
*common_args,
"--compilation-config",
json.dumps(
{
"mode": CompilationMode.VLLM_COMPILE,
"cudagraph_mode": "NONE",
"splitting_ops": [],
"inductor_compile_config": {"force_disable_caches": True},
"pass_config": {
"enable_sp": enabled,
"fuse_gemm_comms": enabled,
"fuse_allreduce_rms": False,
"sp_min_token_num": 1,
},
}
),
]
env = {"VLLM_ROCM_USE_AITER": "0", "VLLM_DISABLE_COMPILE_CACHE": "1"}
with caplog_mp_spawn(logging.DEBUG) as logs:
compare_two_settings(
model,
settings(False),
settings(True),
env1=env,
env2=env,
method="generate",
force_v1_runner=True,
)
matches = [
int(count) for count in FUSION_LOG_PATTERNS["async_tp"].findall(logs.text)
]
print(f"AsyncTP rewrite counts: {matches}")
assert len(matches) >= 2 and all(count > 0 for count in matches), (
f"Expected positive AsyncTP rewrites on both TP workers, found {matches}"
)
@create_new_process_for_each_test()
@pytest.mark.parametrize(
"model_id",
["meta-llama/Llama-3.2-1B-Instruct", "RedHatAI/Llama-3.2-1B-Instruct-FP8"],
)
@pytest.mark.parametrize("tp_size", [2])
@pytest.mark.parametrize("async_tp_enabled", [True])
@pytest.mark.parametrize("distributed_backend", ["mp"])
def test_async_tp_pass_correctness(
model_id: str,
tp_size: int,
async_tp_enabled: bool,
distributed_backend: str,
num_gpus_available: int,
monkeypatch,
):
# Disable FlashInfer FP8 scaled_mm kernel as it is incompatible with
# async TP patterns. No-op on H100 (kernel requires CC >= 100).
monkeypatch.setenv("VLLM_DISABLED_KERNELS", "FlashInferFP8ScaledMMLinearKernel")
model_info = HF_EXAMPLE_MODELS.find_hf_info(model_id)
model_info.check_transformers_version(on_fail="skip")
model_info.check_available_online(on_fail="skip")
pp_size = 1
if num_gpus_available < tp_size:
pytest.skip(f"Need at least {tp_size} x {pp_size} GPUs")
common_args = [
"--dtype",
"bfloat16",
"--max-model-len",
"2048",
"--max-num-seqs",
"8",
]
compilation_config = {
"mode": CompilationMode.VLLM_COMPILE,
"compile_sizes": [2, 4, 8],
"splitting_ops": [],
"pass_config": {"fuse_gemm_comms": async_tp_enabled},
}
async_tp_args = [
*common_args,
"--tensor-parallel-size",
str(tp_size),
"--distributed-executor-backend",
distributed_backend,
"--compilation_config",
json.dumps(compilation_config),
]
tp_args = [
*common_args,
"--tensor-parallel-size",
str(tp_size),
"--distributed-executor-backend",
"mp",
]
compare_two_settings(
model_id,
async_tp_args,
tp_args,
method="generate",
force_v1_runner=True,
)
@create_new_process_for_each_test()
def test_async_tp_pass_nvfp4_correctness(num_gpus_available: int, caplog_mp_spawn):
is_blackwell = current_platform.is_cuda() and (
current_platform.is_device_capability_family(100)
)
is_rocm_cdna = False
if current_platform.is_rocm():
from vllm.platforms.rocm import on_cdna
is_rocm_cdna = on_cdna()
if not (is_blackwell or is_rocm_cdna):
pytest.skip("NVFP4 AsyncTP requires Blackwell or ROCm CDNA")
if is_blackwell and not has_flashinfer():
pytest.skip("FlashInfer is required for the NVFP4 AsyncTP path")
tp_size = 2
if num_gpus_available < tp_size:
pytest.skip(f"Need at least {tp_size} GPUs")
common_args = [
"--dtype",
"bfloat16",
"--max-model-len",
"2048",
"--max-num-seqs",
"8",
"--load-format",
"dummy",
*(["--linear-backend", "flashinfer_cutlass"] if is_blackwell else []),
"--hf-overrides",
json.dumps(NVFP4_HF_OVERRIDES),
]
compilation_config = {
"mode": CompilationMode.VLLM_COMPILE,
"compile_sizes": [2, 4, 8],
"splitting_ops": [],
"pass_config": {
"enable_sp": True,
"fuse_gemm_comms": True,
"fuse_allreduce_rms": False,
"sp_min_token_num": 1,
},
}
if is_rocm_cdna:
compilation_config["inductor_compile_config"] = {"force_disable_caches": True}
async_tp_args = [
*common_args,
"--tensor-parallel-size",
str(tp_size),
"--distributed-executor-backend",
"mp",
"--compilation_config",
json.dumps(compilation_config),
]
tp_args = [
*common_args,
"--tensor-parallel-size",
str(tp_size),
"--distributed-executor-backend",
"mp",
]
env = {"VLLM_DISABLE_COMPILE_CACHE": "1"} if is_rocm_cdna else None
log_context = caplog_mp_spawn(logging.DEBUG) if is_rocm_cdna else nullcontext()
with log_context as logs:
compare_two_settings(
NVFP4_MODEL_ID,
async_tp_args,
tp_args,
env1=env,
env2=env,
method="generate",
force_v1_runner=True,
)
if is_rocm_cdna:
assert logs is not None
matches_by_rank = {
rank: [
int(count)
for line in logs.text.splitlines()
if line.startswith(f"(Worker_TP{rank} pid=")
for count in FUSION_LOG_PATTERNS["async_tp"].findall(line)
]
for rank in range(tp_size)
}
assert all(
any(count > 0 for count in matches) for matches in matches_by_rank.values()
), (
"Expected positive NVFP4 AsyncTP rewrites on both TP workers, "
f"found {matches_by_rank}"
)
@@ -1,414 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""WARNING: This test runs in both single-node (4 GPUs) and multi-node
(2 node with 2 GPUs each) modes. If the test only uses 2 GPUs, it is
important to set the distributed backend to "mp" to avoid Ray scheduling
all workers in a node other than the head node, which can cause the test
to fail.
"""
import json
import os
from dataclasses import dataclass
from typing import Literal, NamedTuple
import pytest
from vllm.config.compilation import CompilationMode
from vllm.config.model import RunnerOption
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.torch_utils import is_torch_equal_or_newer
from ...models.registry import HF_EXAMPLE_MODELS, _HfExamplesInfo
from ...utils import compare_all_settings, create_new_process_for_each_test
logger = init_logger("test_sequence_parallel")
VLLM_MULTI_NODE = os.getenv("VLLM_MULTI_NODE", "0") == "1"
NVFP4_MODEL_ID = "nvidia/Llama-3.1-8B-Instruct-NVFP4"
NVFP4_MODEL_INFO = _HfExamplesInfo(NVFP4_MODEL_ID)
class ParallelSetup(NamedTuple):
tp_size: int
pp_size: int
fuse_norm_quant: bool
fuse_act_quant: bool
eager_mode: bool
class SPTestOptions(NamedTuple):
multi_node_only: bool
load_format: str | None = None
model_info: _HfExamplesInfo | None = None
@dataclass
class SPTestSettings:
parallel_setups: list[ParallelSetup]
distributed_backends: list[str]
runner: RunnerOption
test_options: SPTestOptions
@staticmethod
def fast(
*,
tp_base: int = 2,
pp_base: int = 1,
runner: RunnerOption = "auto",
multi_node_only: bool = False,
load_format: str | None = None,
):
parallel_setups = [
ParallelSetup(
tp_size=tp_base,
pp_size=pp_multiplier * pp_base,
fuse_norm_quant=False,
fuse_act_quant=False,
eager_mode=False,
)
for pp_multiplier in [1, 2]
]
return SPTestSettings(
parallel_setups=parallel_setups,
distributed_backends=["mp", "ray"],
runner=runner,
test_options=SPTestOptions(
multi_node_only=multi_node_only, load_format=load_format
),
)
@staticmethod
def fp8_quant(
*,
tp_base: int = 2,
pp_base: int = 1,
runner: RunnerOption = "auto",
multi_node_only: bool = False,
load_format: str | None = None,
):
parallel_setups = []
for fusion_val in [False, True]:
parallel_setups.append(
ParallelSetup(
tp_size=tp_base,
pp_size=pp_base,
fuse_norm_quant=fusion_val,
fuse_act_quant=fusion_val,
eager_mode=True,
)
)
return SPTestSettings(
parallel_setups=parallel_setups,
distributed_backends=["mp", "ray"],
runner=runner,
test_options=SPTestOptions(
multi_node_only=multi_node_only, load_format=load_format
),
)
def iter_params(self, model_id: str):
opts = self.test_options
for parallel_setup in self.parallel_setups:
for backend in self.distributed_backends:
yield (
model_id,
parallel_setup,
backend,
self.runner,
opts,
)
def _build_sp_args(
model_id: str,
parallel_setup: ParallelSetup,
distributed_backend: str,
runner: RunnerOption,
test_options: SPTestOptions,
num_gpus_available: int,
use_inductor_graph_partition: bool,
fuse_gemm_comms: bool,
enable_prompt_embeds: bool,
*,
is_multimodal: bool,
) -> tuple[list[str], list[str]] | None:
(
tp_size,
pp_size,
fuse_norm_quant,
fuse_act_quant,
eager_mode,
) = parallel_setup
multi_node_only = test_options.multi_node_only
load_format = test_options.load_format
model_info = test_options.model_info or HF_EXAMPLE_MODELS.find_hf_info(model_id)
model_info.check_transformers_version(on_fail="skip")
trust_remote_code = model_info.trust_remote_code
tokenizer_mode = model_info.tokenizer_mode
hf_overrides = dict(model_info.hf_overrides)
require_embed_inputs = model_info.require_embed_inputs
if load_format == "dummy":
# Avoid OOM
text_overrides = {
"num_hidden_layers": 4,
"hidden_size": 512,
"intermediate_size": 800,
"num_attention_heads": 4,
"num_key_value_heads": 1,
}
if is_multimodal:
hf_overrides.update({"text_config": text_overrides})
else:
hf_overrides.update(text_overrides)
else:
model_info.check_available_online(on_fail="skip")
if num_gpus_available < tp_size * pp_size:
return None
if VLLM_MULTI_NODE and distributed_backend == "mp":
return None
if multi_node_only and not VLLM_MULTI_NODE:
return None
common_args = [
"--dtype",
"bfloat16",
"--max-model-len",
"2048",
"--max-num-seqs",
"8",
]
if eager_mode:
common_args.append("-cc.cudagraph_mode=none")
if runner != "auto":
common_args.extend(["--runner", runner])
if trust_remote_code:
common_args.append("--trust-remote-code")
if tokenizer_mode:
common_args.extend(["--tokenizer-mode", tokenizer_mode])
if load_format:
common_args.extend(["--load-format", load_format])
if hf_overrides:
common_args.extend(["--hf-overrides", json.dumps(hf_overrides)])
if require_embed_inputs:
common_args.extend(
[
"--skip-tokenizer-init",
"--enable-prompt-embeds",
"--enable-mm-embeds",
]
)
elif enable_prompt_embeds:
common_args.append("--enable-prompt-embeds")
compilation_config = {
"mode": CompilationMode.VLLM_COMPILE,
"compile_sizes": [4, 8],
"pass_config": {
"enable_sp": True,
"fuse_gemm_comms": fuse_gemm_comms,
"fuse_norm_quant": fuse_norm_quant,
"fuse_act_quant": fuse_act_quant,
"fuse_allreduce_rms": False,
"eliminate_noops": True,
"sp_min_token_num": 0,
},
"use_inductor_graph_partition": use_inductor_graph_partition,
}
if not use_inductor_graph_partition:
compilation_config["splitting_ops"] = []
tp_sp_args = [
*common_args,
"--tensor-parallel-size",
str(tp_size),
"--pipeline-parallel-size",
str(pp_size),
"--distributed-executor-backend",
distributed_backend,
"--compilation_config",
json.dumps(compilation_config),
]
tp_args = [
*common_args,
"--tensor-parallel-size",
str(tp_size),
"--distributed-executor-backend",
"mp",
]
return tp_args, tp_sp_args
def _compare_sp_settings(
model_id: str,
settings: list[tuple[list[str], list[str]]],
*,
method: Literal["generate", "encode"],
) -> None:
if not settings:
pytest.skip("No supported sequence-parallel configurations")
settings_by_tp_args: dict[tuple[str, ...], list[list[str]]] = {}
for tp_args, tp_sp_args in settings:
settings_by_tp_args.setdefault(tuple(tp_args), []).append(tp_sp_args)
for tp_args_key, grouped_tp_sp_args in settings_by_tp_args.items():
all_args = [list(tp_args_key), *grouped_tp_sp_args]
compare_all_settings(
model_id,
all_args,
[None] * len(all_args),
method=method,
force_v1_runner=True,
)
SP_TEXT_GENERATION_MODELS = {
# [Decoder-only]
"hmellor/tiny-random-LlamaForCausalLM": SPTestSettings.fast(),
"RedHatAI/Llama-3.2-1B-Instruct-FP8": SPTestSettings.fp8_quant(),
}
@pytest.mark.parametrize(
("model_id", "settings"),
[
pytest.param(model_id, settings, id=model_id)
for model_id, settings in SP_TEXT_GENERATION_MODELS.items()
],
)
@create_new_process_for_each_test()
def test_tp_sp_generation(
model_id: str,
settings: SPTestSettings,
num_gpus_available,
):
# Skip FP8 SP-only test on sm89 (compute capability 8.9).
# An unknown capability (None) is left to fail in the test body rather than
# being silently skipped here.
capability = current_platform.get_device_capability()
if "fp8" in model_id.lower() and capability is not None and capability < (9, 0):
pytest.skip("FP8 reduction support begins with sm90 capable devices.")
graph_partition_options = [False]
if is_torch_equal_or_newer("2.9.0.dev"):
graph_partition_options.append(True)
comparisons = []
for _, parallel_setup, backend, runner, test_options in settings.iter_params(
model_id
):
for use_inductor_graph_partition in graph_partition_options:
comparison = _build_sp_args(
model_id,
parallel_setup,
backend,
runner,
test_options,
num_gpus_available,
use_inductor_graph_partition,
fuse_gemm_comms=False, # TODO: enable async TP
enable_prompt_embeds=False,
is_multimodal=False,
)
if comparison is not None:
comparisons.append(comparison)
_compare_sp_settings(model_id, comparisons, method="generate")
# Focused regression test for the SP + prompt_embeds graph-rewrite path.
# Covers pp_size=1 (SP only) and pp_size=2 (SP + PP); kept small on purpose so
# we don't double the matrix of `test_tp_sp_generation` above.
SP_PROMPT_EMBEDS_PARALLEL_SETUPS = [
ParallelSetup(
tp_size=2,
pp_size=pp_size,
fuse_norm_quant=False,
fuse_act_quant=False,
eager_mode=False,
)
for pp_size in [1, 2]
]
@create_new_process_for_each_test()
def test_tp_sp_generation_prompt_embeds(
num_gpus_available,
):
model_id = "hmellor/tiny-random-LlamaForCausalLM"
graph_partition_options = [False]
if is_torch_equal_or_newer("2.9.0.dev"):
graph_partition_options.append(True)
comparisons = []
for parallel_setup in SP_PROMPT_EMBEDS_PARALLEL_SETUPS:
for use_inductor_graph_partition in graph_partition_options:
comparison = _build_sp_args(
model_id,
parallel_setup,
distributed_backend="mp",
runner="auto",
test_options=SPTestOptions(multi_node_only=False, load_format=None),
num_gpus_available=num_gpus_available,
use_inductor_graph_partition=use_inductor_graph_partition,
fuse_gemm_comms=False,
enable_prompt_embeds=True,
is_multimodal=False,
)
if comparison is not None:
comparisons.append(comparison)
_compare_sp_settings(model_id, comparisons, method="generate")
@create_new_process_for_each_test()
def test_tp_sp_nvfp4_generation(num_gpus_available: int):
is_blackwell = current_platform.is_cuda() and (
current_platform.is_device_capability_family(100)
)
is_rocm_cdna = False
if current_platform.is_rocm():
from vllm.platforms.rocm import on_cdna
is_rocm_cdna = on_cdna()
if not (is_blackwell or is_rocm_cdna):
pytest.skip("NVFP4 sequence parallelism requires Blackwell or ROCm CDNA")
comparison = _build_sp_args(
NVFP4_MODEL_ID,
ParallelSetup(
tp_size=2,
pp_size=1,
fuse_norm_quant=True,
fuse_act_quant=True,
eager_mode=True,
),
"mp",
"auto",
SPTestOptions(
multi_node_only=False,
load_format="dummy",
model_info=NVFP4_MODEL_INFO,
),
num_gpus_available,
use_inductor_graph_partition=False,
fuse_gemm_comms=False,
enable_prompt_embeds=False,
is_multimodal=False,
)
_compare_sp_settings(
NVFP4_MODEL_ID,
[] if comparison is None else [comparison],
method="generate",
)
+16 -2
View File
@@ -10,11 +10,17 @@ import torch
from tests.quantization.utils import is_quant_method_supported
from vllm import LLM, SamplingParams
from vllm.config import CompilationConfig, CompilationMode, CUDAGraphMode, PassConfig
from vllm.config import (
CacheConfig,
CompilationConfig,
CompilationMode,
CUDAGraphMode,
PassConfig,
)
from vllm.platforms import current_platform
from vllm.utils.torch_utils import is_torch_equal_or_newer
from ...utils import create_new_process_for_each_test
from ...utils import create_new_process_for_each_test, wait_for_memory_to_settle
def models_list(*, all: bool = True, keywords: list[str] | None = None):
@@ -173,6 +179,14 @@ def run_model(
if compilation_config.cudagraph_mode is None:
compilation_config.cudagraph_mode = CUDAGraphMode.NONE
# V1 startup requires free_memory >= total * gpu_memory_utilization, so a
# device that is not free yet fails engine init rather than waiting for it.
# VllmRunner guards this; building LLM directly does not. No-op off ROCm.
wait_for_memory_to_settle(
threshold_ratio=1.0
- model_kwargs.get("gpu_memory_utilization", CacheConfig.gpu_memory_utilization)
)
llm = LLM(
model=model,
compilation_config=compilation_config,
-6
View File
@@ -21,8 +21,6 @@ class Matches(NamedTuple):
# distributed
ar_rms_fusion: int = 0
aiter_ar_rms_fusion: int = 0
sequence_parallel: int = 0
async_tp: int = 0
class ModelFusionInfo(NamedTuple):
@@ -143,8 +141,4 @@ FUSION_LOG_PATTERNS: dict[str, re.Pattern] = {
"aiter_ar_rms_fusion": re.compile(
r"RocmAiterAllReduceFusionPass Replaced (\d+) patterns"
),
"sequence_parallel": re.compile(
r"sequence_parallelism.py:\d+] Replaced (\d+) patterns"
),
"async_tp": re.compile(r"collective_fusion.py:\d+] Replaced (\d+) patterns"),
}
+2 -71
View File
@@ -170,26 +170,8 @@ def run_e2e_fusion_test(monkeypatch, caplog_mp_spawn, vllm_runner):
for match_name in matches_check:
log_matches = list(int(ms) for ms in log_matches_dict[match_name])
# AR+RMS skips the largest range; SP skips the smallest.
# When both are enabled, AR+RMS activation count is
# model-dependent (hidden_size affects threshold), so derive
# from log data.
if (
match_name == "ar_rms_fusion"
and "sequence_parallel" in matches_check
and num_compile_ranges >= 2
):
assert (
len(log_matches) >= tp_size and len(log_matches) % tp_size == 0
), (
f"Expected multiple of {tp_size} ar_rms log entries, "
f"found {len(log_matches)}"
)
num_ranges_activated = len(log_matches) // tp_size
elif (
match_name in ("ar_rms_fusion", "sequence_parallel")
and num_compile_ranges >= 2
):
# AR+RMS skips the largest range.
if match_name == "ar_rms_fusion" and num_compile_ranges >= 2:
num_ranges_activated = num_compile_ranges - 1
else:
num_ranges_activated = num_compile_ranges
@@ -233,44 +215,6 @@ def run_e2e_fusion_test(monkeypatch, caplog_mp_spawn, vllm_runner):
f"Expecting at least {expected_matches - matches.ar_rms_fusion} "
f"where ar+rms+quant was activated"
)
elif (
match_name == "async_tp"
and "sequence_parallel" in matches_check
and num_compile_ranges >= 2
):
# AsyncTP only finds patterns on ranges where SP ran.
n_sp_ranges = num_compile_ranges - 1
assert (
sum(m == expected_matches for m in log_matches)
== tp_size * n_sp_ranges
), (
f"Expecting {expected_matches} async_tp on "
f"{tp_size * n_sp_ranges} SP-range entries, "
f"found: {log_matches}"
)
assert sum(m == 0 for m in log_matches) == tp_size, (
f"Expecting 0 async_tp on {tp_size} small-range entries "
f"(no SP), found: {log_matches}"
)
elif (
match_name == "ar_rms_fusion"
and "sequence_parallel" in matches_check
and num_compile_ranges >= 2
):
# SP consumes allreduce patterns first, so AR+RMS finds
# full matches only on the smallest range (no SP).
assert sum(m == expected_matches for m in log_matches) == tp_size, (
f"Expecting {expected_matches} ar_rms on "
f"{tp_size} small-range entries, found: {log_matches}"
)
assert sum(m == 0 for m in log_matches) == tp_size * (
num_ranges_activated - 1
), (
f"Expecting 0 ar_rms on "
f"{tp_size * (num_ranges_activated - 1)} large-range "
f"entries (SP took precedence), found: {log_matches}"
)
elif match_name == "act_quant_fusion":
actual_match = match_table.get("activation_quant_fusion_pass", 0)
assert actual_match == expected_matches * n_expected, (
@@ -305,17 +249,4 @@ def run_e2e_fusion_test(monkeypatch, caplog_mp_spawn, vllm_runner):
f"(found {len(log_matches)}) in:\n {log_holder.text}"
)
if match_name == "sequence_parallel" and num_compile_ranges >= 2:
log_matches = re.findall(
r"pass_manager.py:\d+] Skipping "
r".*SequenceParallelismPass.* with compile range",
log_holder.text,
)
n_expected = tp_size * (num_compile_ranges - num_ranges_activated)
assert len(log_matches) == n_expected, (
f'Could not find {n_expected} "Skipping SequenceParallelismPass" '
f"(found {len(log_matches)}) in:\n {log_holder.text}"
)
return run
-19
View File
@@ -73,8 +73,6 @@ llama3_8b = ModelFusionInfo(
matches=lambda n_layers: Matches(
ar_rms_fusion=n_layers * 2 + 1,
aiter_ar_rms_fusion=n_layers * 2 + 1,
sequence_parallel=n_layers * 2 + 1,
async_tp=n_layers * 4,
),
)
@@ -85,8 +83,6 @@ llama3_8b_fp8 = ModelFusionInfo(
act_quant_fusion=n_layers,
attn_quant_fusion=n_layers,
ar_rms_fusion=n_layers * 2 + 1,
sequence_parallel=n_layers * 2 + 1,
async_tp=n_layers * 4,
),
)
@@ -96,8 +92,6 @@ llama3_8b_fp4 = ModelFusionInfo(
act_quant_fusion=n_layers,
attn_quant_fusion=n_layers,
ar_rms_fusion=n_layers * 2 + 1,
sequence_parallel=n_layers * 2 + 1,
async_tp=n_layers * 4,
),
)
@@ -127,8 +121,6 @@ llama4_scout_fp8 = ModelFusionInfo(
rms_quant_fusion=n_layers,
attn_quant_fusion=n_layers,
ar_rms_fusion=n_layers * 2,
sequence_parallel=n_layers * 2,
async_tp=n_layers * 2 - 1,
),
)
@@ -138,8 +130,6 @@ llama4_scout_fp4 = ModelFusionInfo(
matches=lambda n_layers: Matches(
attn_quant_fusion=n_layers,
ar_rms_fusion=n_layers * 2,
sequence_parallel=n_layers * 2,
async_tp=n_layers * 2 - 1,
),
)
@@ -149,8 +139,6 @@ qwen3_a3b = ModelFusionInfo(
norm_rope_fusion=n_layers,
ar_rms_fusion=n_layers * 2 + 1,
aiter_ar_rms_fusion=n_layers * 2 + 1,
sequence_parallel=n_layers * 2 + 1,
async_tp=n_layers * 2,
),
)
@@ -161,8 +149,6 @@ qwen3_a3b_fp8 = ModelFusionInfo(
norm_rope_fusion=n_layers,
attn_quant_fusion=0, # attn + group quant not supported
ar_rms_fusion=n_layers * 2 + 1,
sequence_parallel=n_layers * 2 + 1,
async_tp=n_layers * 2,
),
)
@@ -192,9 +178,6 @@ deepseek_v3_fp8 = ModelFusionInfo(
# MLA attn + per-group FP8 quant
attn_quant_fusion=n_layers,
ar_rms_fusion=n_layers * 2 + 1,
# TODO
# sequence_parallel= n_layers * 2 + 1,
# async_tp=n_layers * 2,
),
)
@@ -213,8 +196,6 @@ gpt_oss_20b = ModelFusionInfo(
matches=lambda n_layers: Matches(
ar_rms_fusion=n_layers * 2 + 1,
aiter_ar_rms_fusion=n_layers + 1,
sequence_parallel=n_layers * 2 + 1,
async_tp=n_layers * 2,
),
model_kwargs=(
{"quantization_config": {"moe": {"activation": "mxfp8"}}}
@@ -1,339 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
import pytest
from vllm.config import PassConfig
from vllm.platforms import current_platform
from ...utils import multi_gpu_test
from .common import (
INDUCTOR_GRAPH_PARTITION,
AttentionBackendCase,
Matches,
custom_ops_combos,
is_blackwell,
nvfp4_kernel_exposes_input_quant_key,
)
from .models import (
FLASHINFER_ATTN,
TRITON_ATTN,
llama3_8b,
llama3_8b_fp4,
llama3_8b_fp8,
llama4_scout_fp8,
qwen3_a3b,
)
pytestmark = pytest.mark.skipif(not current_platform.is_cuda(), reason="Only test CUDA")
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"model_name, matches_fn, model_kwargs, hf_overrides",
[llama3_8b_fp8, llama4_scout_fp8],
)
@pytest.mark.parametrize("attn_backend", [TRITON_ATTN, FLASHINFER_ATTN])
@pytest.mark.parametrize("n_layers", [4])
@pytest.mark.parametrize("custom_ops", custom_ops_combos("quant_fp8", "rms_norm"))
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
def test_tp2_async_tp_fp8_fusions(
model_name: str,
matches_fn: Callable[[int], Matches],
model_kwargs: dict,
hf_overrides: Callable[[int], dict],
attn_backend: AttentionBackendCase,
n_layers: int,
custom_ops: str,
inductor_graph_partition: bool,
run_e2e_fusion_test,
):
matches = matches_fn(n_layers)
# Reduce size of model and skip weight loading time
model_kwargs["hf_overrides"] = hf_overrides(n_layers)
model_kwargs["load_format"] = "dummy"
model_kwargs["max_model_len"] = 1024
model_kwargs["kernel_config"] = {"enable_flashinfer_autotune": False}
compilation_config = dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=custom_ops.split(","),
pass_config=PassConfig(
fuse_norm_quant=True,
fuse_act_quant=False,
fuse_attn_quant=True,
enable_qk_norm_rope_fusion=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=False,
# Override threshold for testing (models have small hidden_size)
sp_min_token_num=512,
),
)
matches_check = [
"rms_quant_fusion",
"norm_rope_fusion",
"attn_quant_fusion",
"sequence_parallel",
"async_tp",
]
run_e2e_fusion_test(
model_name,
matches,
model_kwargs,
attn_backend,
compilation_config,
matches_check,
tp_size=2,
)
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"model_name, matches_fn, model_kwargs, hf_overrides",
[llama3_8b_fp4],
)
@pytest.mark.parametrize("attn_backend", [FLASHINFER_ATTN])
@pytest.mark.parametrize("n_layers", [4])
@pytest.mark.parametrize("custom_ops", custom_ops_combos("rms_norm"))
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
@pytest.mark.skipif(not is_blackwell(), reason="Blackwell required for fp4")
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Only test CUDA")
def test_tp2_async_tp_nvfp4_fusions(
model_name: str,
matches_fn: Callable[[int], Matches],
model_kwargs: dict,
hf_overrides: Callable[[int], dict],
attn_backend: AttentionBackendCase,
n_layers: int,
custom_ops: str,
inductor_graph_partition: bool,
run_e2e_fusion_test,
):
if nvfp4_kernel_exposes_input_quant_key():
pytest.skip(
"NVFP4 kernel exposes input_quant_key; manual fusion fires "
"instead of compiler pass-based fusion"
)
# NVFP4 currently wires the all-gather + GEMM path only.
matches = matches_fn(n_layers)._replace(async_tp=n_layers * 2)
# Reduce size of model and skip weight loading time
model_kwargs["hf_overrides"] = hf_overrides(n_layers)
model_kwargs["load_format"] = "dummy"
model_kwargs["max_model_len"] = 1024
model_kwargs["kernel_config"] = {"enable_flashinfer_autotune": False}
compilation_config = dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=custom_ops.split(","),
pass_config=PassConfig(
fuse_act_quant=False,
fuse_attn_quant=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=False,
# Override threshold for testing (models have small hidden_size)
sp_min_token_num=512,
),
)
matches_check = [
"attn_quant_fusion",
"sequence_parallel",
"async_tp",
]
run_e2e_fusion_test(
model_name,
matches,
model_kwargs,
attn_backend,
compilation_config,
matches_check,
tp_size=2,
)
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"model_name, matches_fn, model_kwargs, hf_overrides",
[llama3_8b, qwen3_a3b],
)
@pytest.mark.parametrize("attn_backend", [TRITON_ATTN])
@pytest.mark.parametrize("n_layers", [4])
@pytest.mark.parametrize("custom_ops", custom_ops_combos("rms_norm"))
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
def test_tp2_async_tp_fusions(
model_name: str,
matches_fn: Callable[[int], Matches],
model_kwargs: dict,
hf_overrides: Callable[[int], dict],
attn_backend: AttentionBackendCase,
n_layers: int,
custom_ops: str,
inductor_graph_partition: bool,
run_e2e_fusion_test,
):
matches = matches_fn(n_layers)
# Reduce size of model and skip weight loading time
model_kwargs["hf_overrides"] = hf_overrides(n_layers)
model_kwargs["load_format"] = "dummy"
model_kwargs["max_model_len"] = 1024
model_kwargs["kernel_config"] = {"enable_flashinfer_autotune": False}
compilation_config = dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=custom_ops.split(","),
pass_config=PassConfig(
enable_qk_norm_rope_fusion=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=False,
# Override threshold for testing (models have small hidden_size)
sp_min_token_num=512,
),
)
matches_check = [
"norm_rope_fusion",
"sequence_parallel",
"async_tp",
]
run_e2e_fusion_test(
model_name,
matches,
model_kwargs,
attn_backend,
compilation_config,
matches_check,
tp_size=2,
)
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"model_name, matches_fn, model_kwargs, hf_overrides",
[llama3_8b_fp8, llama4_scout_fp8],
)
@pytest.mark.parametrize("attn_backend", [TRITON_ATTN, FLASHINFER_ATTN])
@pytest.mark.parametrize("n_layers", [4])
@pytest.mark.parametrize("custom_ops", custom_ops_combos("quant_fp8", "rms_norm"))
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
def test_tp2_sp_ar_rms_fp8_fusions(
model_name: str,
matches_fn: Callable[[int], Matches],
model_kwargs: dict,
hf_overrides: Callable[[int], dict],
attn_backend: AttentionBackendCase,
n_layers: int,
custom_ops: str,
inductor_graph_partition: bool,
run_e2e_fusion_test,
):
matches = matches_fn(n_layers)
# Reduce size of model and skip weight loading time
model_kwargs["hf_overrides"] = hf_overrides(n_layers)
model_kwargs["load_format"] = "dummy"
model_kwargs["max_model_len"] = 1024
compilation_config = dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=custom_ops.split(","),
pass_config=PassConfig(
fuse_norm_quant=True,
fuse_act_quant=False,
fuse_attn_quant=True,
enable_qk_norm_rope_fusion=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=True,
# Override threshold for testing (models have small hidden_size)
sp_min_token_num=512,
),
)
matches_check = [
"rms_quant_fusion",
"norm_rope_fusion",
"attn_quant_fusion",
"ar_rms_fusion",
"sequence_parallel",
"async_tp",
]
run_e2e_fusion_test(
model_name,
matches,
model_kwargs,
attn_backend,
compilation_config,
matches_check,
tp_size=2,
)
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"model_name, matches_fn, model_kwargs, hf_overrides",
[llama3_8b, qwen3_a3b],
)
@pytest.mark.parametrize("attn_backend", [TRITON_ATTN])
@pytest.mark.parametrize("n_layers", [4])
@pytest.mark.parametrize("custom_ops", custom_ops_combos("rms_norm"))
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
def test_tp2_sp_ar_rms_fusions(
model_name: str,
matches_fn: Callable[[int], Matches],
model_kwargs: dict,
hf_overrides: Callable[[int], dict],
attn_backend: AttentionBackendCase,
n_layers: int,
custom_ops: str,
inductor_graph_partition: bool,
run_e2e_fusion_test,
):
matches = matches_fn(n_layers)
# Reduce size of model and skip weight loading time
model_kwargs["hf_overrides"] = hf_overrides(n_layers)
model_kwargs["load_format"] = "dummy"
model_kwargs["max_model_len"] = 1024
compilation_config = dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=custom_ops.split(","),
pass_config=PassConfig(
enable_qk_norm_rope_fusion=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=True,
# Override threshold for testing (models have small hidden_size)
sp_min_token_num=512,
),
)
matches_check = [
"norm_rope_fusion",
"ar_rms_fusion",
"sequence_parallel",
"async_tp",
]
run_e2e_fusion_test(
model_name,
matches,
model_kwargs,
attn_backend,
compilation_config,
matches_check,
tp_size=2,
)
@@ -1,58 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Bounded ROCm model coverage for actual sequence-parallel AsyncTP rewrites."""
import pytest
from tests.utils import multi_gpu_test
from vllm.config import PassConfig
from vllm.platforms import current_platform
from .common import INDUCTOR_GRAPH_PARTITION, custom_ops_combos
from .models import TRITON_ATTN, llama3_8b
@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm AsyncTP contract")
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION)
@pytest.mark.parametrize("custom_ops", tuple(custom_ops_combos("rms_norm")))
@pytest.mark.parametrize("attn_backend", [TRITON_ATTN])
def test_tp2_rocm_async_tp_bf16_fusions(
inductor_graph_partition, custom_ops, attn_backend, run_e2e_fusion_test
):
n_layers = 4
model_kwargs = dict(
hf_overrides=dict(
num_hidden_layers=n_layers,
hidden_size=512,
intermediate_size=1024,
num_attention_heads=8,
num_key_value_heads=2,
head_dim=64,
),
load_format="dummy",
max_model_len=1024,
kv_cache_memory_bytes=64 * 1024**2,
gpu_memory_utilization=0.01,
max_num_batched_tokens=1024,
max_num_seqs=32,
)
run_e2e_fusion_test(
llama3_8b.model_name,
llama3_8b.matches(n_layers),
model_kwargs,
attn_backend,
dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=custom_ops.split(","),
pass_config=PassConfig(
enable_qk_norm_rope_fusion=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=False,
sp_min_token_num=512,
),
),
["norm_rope_fusion", "sequence_parallel", "async_tp"],
tp_size=2,
)
@@ -1,60 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ROCm MoE coverage for the TP2 GEMM/collective fusion contract."""
import pytest
from tests.utils import multi_gpu_test
from vllm.config import PassConfig
from vllm.platforms import current_platform
from .common import INDUCTOR_GRAPH_PARTITION
from .models import TRITON_ATTN, qwen3_a3b
@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm AsyncTP contract")
@pytest.mark.parametrize("inductor_graph_partition", INDUCTOR_GRAPH_PARTITION[:1])
@pytest.mark.parametrize("attn_backend", [TRITON_ATTN])
def test_tp2_rocm_moe_async_tp_bf16_fusions(
inductor_graph_partition, attn_backend, run_e2e_fusion_test
):
"""MoE dense projections retain the Qwen SP/AsyncTP rewrite counts."""
n_layers = 4
run_e2e_fusion_test(
qwen3_a3b.model_name,
qwen3_a3b.matches(n_layers),
dict(
hf_overrides=dict(
num_hidden_layers=n_layers,
hidden_size=512,
intermediate_size=1024,
moe_intermediate_size=128,
num_attention_heads=8,
num_key_value_heads=2,
head_dim=64,
num_experts=8,
num_experts_per_tok=2,
),
load_format="dummy",
max_model_len=1024,
kv_cache_memory_bytes=64 * 1024**2,
gpu_memory_utilization=0.01,
max_num_batched_tokens=1024,
max_num_seqs=32,
),
attn_backend,
dict(
use_inductor_graph_partition=inductor_graph_partition,
custom_ops=["-rms_norm"],
pass_config=PassConfig(
enable_qk_norm_rope_fusion=True,
enable_sp=True,
fuse_gemm_comms=True,
fuse_allreduce_rms=False,
sp_min_token_num=512,
),
),
["norm_rope_fusion", "sequence_parallel", "async_tp"],
tp_size=2,
)
@@ -1,394 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
import vllm.envs as envs
from tests.compile.backend import TestBackend
from tests.utils import (
multi_gpu_test,
)
from vllm.compilation.passes.fusion.collective_fusion import AsyncTPPass
from vllm.config import (
CompilationConfig,
DeviceConfig,
ModelConfig,
PassConfig,
VllmConfig,
set_current_vllm_config,
)
from vllm.config.utils import Range
from vllm.distributed import (
tensor_model_parallel_all_gather,
tensor_model_parallel_reduce_scatter,
)
from vllm.distributed.parallel_state import (
init_distributed_environment,
initialize_model_parallel,
)
from vllm.platforms import current_platform
from vllm.utils.network_utils import get_file_store_init_method
from vllm.utils.system_utils import update_environment_variables
from vllm.utils.torch_utils import set_random_seed
DEVICE_TYPE = current_platform.device_type
FP8_DTYPE = current_platform.fp8_dtype()
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
class TestMMRSModel(torch.nn.Module):
def __init__(self, hidden_size=16, dtype=torch.bfloat16):
super().__init__()
self.hidden_size = hidden_size
self.dtype = dtype
self.gate_proj = torch.nn.Parameter(
torch.empty((self.hidden_size * 2, hidden_size)), requires_grad=False
)
# Initialize weights
torch.nn.init.normal_(self.gate_proj, std=0.02)
def forward(self, hidden_states):
"""Forward pass implementing the mm + reduce scatter in the FX graph."""
# Reshape input
view = hidden_states.reshape(-1, self.hidden_size)
# matrix multiplication
permute = self.gate_proj.permute(1, 0)
mm = torch.mm(view, permute)
reduce_scatter = tensor_model_parallel_reduce_scatter(mm, dim=0)
return reduce_scatter
def ops_in_model_before(self):
return [torch.ops.vllm.reduce_scatter.default]
def ops_in_model_after(self):
return [torch.ops.symm_mem.fused_matmul_reduce_scatter.default]
class TestAGMMModel(torch.nn.Module):
def __init__(self, hidden_size=16, dtype=torch.bfloat16):
super().__init__()
self.hidden_size = hidden_size
self.dtype = dtype
self.weight = torch.nn.Parameter(
torch.empty((hidden_size, hidden_size)), requires_grad=False
)
# Initialize weights
torch.nn.init.normal_(self.weight, std=0.02)
def forward(self, hidden_states):
"""Forward pass implementing the mm + all gather in the FX graph."""
# Reshape input
view = hidden_states.reshape(-1, self.hidden_size)
all_gather = tensor_model_parallel_all_gather(view, dim=0)
permute = self.weight.permute(1, 0)
mm = torch.mm(all_gather, permute)
return mm
def ops_in_model_before(self):
return [torch.ops.vllm.all_gather.default]
def ops_in_model_after(self):
return [torch.ops.symm_mem.fused_all_gather_matmul.default]
class _BaseScaledMMModel(torch.nn.Module):
def __init__(self, hidden_size=16, dtype=torch.bfloat16):
super().__init__()
self.hidden_size = hidden_size
self.dtype = dtype
self.weight = (
torch.empty([hidden_size, hidden_size], dtype=FP8_DTYPE)
.contiguous()
.transpose(0, 1)
)
# Initialize scale_b for _scaled_mm.
self.scale_b = torch.ones(1, self.hidden_size, dtype=torch.float32)
class TestScaledMMRSModel(_BaseScaledMMModel):
def forward(self, input: torch.Tensor):
"""Forward pass implementing the scaled_mm + reduce scatter in the FX graph."""
fp8_input = input.to(FP8_DTYPE)
scale_a = torch.ones(input.shape[0], 1, dtype=torch.float32)
scaled_mm = torch._scaled_mm(
fp8_input,
self.weight,
scale_a=scale_a,
scale_b=self.scale_b,
out_dtype=self.dtype,
)
reduce_scatter = tensor_model_parallel_reduce_scatter(scaled_mm, dim=0)
return reduce_scatter
def ops_in_model_before(self):
return [torch.ops.vllm.reduce_scatter.default]
def ops_in_model_after(self):
return [torch.ops.vllm.patched_fused_scaled_matmul_reduce_scatter.default]
class TestAGScaledMMModel(_BaseScaledMMModel):
def forward(self, input: torch.Tensor):
"""Forward pass implementing the all gather + scaled_mm in the FX graph."""
# Reshape input
fp8_input = input.to(FP8_DTYPE)
all_gather = tensor_model_parallel_all_gather(fp8_input, dim=0)
scale_a = torch.ones(all_gather.shape[0], 1, dtype=torch.float32)
scaled_mm = torch._scaled_mm(
all_gather,
self.weight,
scale_a=scale_a,
scale_b=self.scale_b,
out_dtype=self.dtype,
)
return scaled_mm
def ops_in_model_before(self):
return [torch.ops.vllm.all_gather.default]
def ops_in_model_after(self):
return [torch.ops.symm_mem.fused_all_gather_scaled_matmul.default]
class TestCutlassScaledMMRSModel(_BaseScaledMMModel):
def forward(self, input: torch.Tensor):
"""Forward pass implementing the cutlass_scaled_mm + reduce scatter
in the FX graph
"""
fp8_input = input.to(FP8_DTYPE)
scale_a = torch.ones(input.shape[0], 1, dtype=torch.float32)
mm_out = torch.empty(
(fp8_input.shape[0], self.weight.shape[1]),
dtype=self.dtype,
device=input.device,
)
torch.ops._C.cutlass_scaled_mm(
mm_out, fp8_input, self.weight, scale_a, self.scale_b, None
)
reduce_scatter = tensor_model_parallel_reduce_scatter(mm_out, dim=0)
return reduce_scatter
def ops_in_model_before(self):
return [torch.ops.vllm.reduce_scatter.default]
def ops_in_model_after(self):
return [torch.ops.vllm.patched_fused_scaled_matmul_reduce_scatter.default]
class TestAGCutlassScaledMMModel(_BaseScaledMMModel):
def forward(self, input: torch.Tensor):
"""Forward pass implementing the all gather + cutlass_scaled_mm
in the FX graph
"""
# Reshape input
fp8_input = input.to(FP8_DTYPE)
all_gather = tensor_model_parallel_all_gather(fp8_input, dim=0)
scale_a = torch.ones(all_gather.shape[0], 1, dtype=torch.float32)
mm_out = torch.empty(
(all_gather.shape[0], self.weight.shape[1]),
dtype=self.dtype,
device=all_gather.device,
)
torch.ops._C.cutlass_scaled_mm(
mm_out, all_gather, self.weight, scale_a, self.scale_b, None
)
return mm_out
def ops_in_model_before(self):
return [torch.ops.vllm.all_gather.default]
def ops_in_model_after(self):
return [torch.ops.symm_mem.fused_all_gather_scaled_matmul.default]
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"test_model",
[
TestMMRSModel,
TestAGMMModel,
TestScaledMMRSModel,
TestAGScaledMMModel,
pytest.param(
TestCutlassScaledMMRSModel,
marks=pytest.mark.skipif(
not hasattr(torch.ops._C, "cutlass_scaled_mm"),
reason="Requires cutlass_scaled_mm",
),
),
pytest.param(
TestAGCutlassScaledMMModel,
marks=pytest.mark.skipif(
not hasattr(torch.ops._C, "cutlass_scaled_mm"),
reason="Requires cutlass_scaled_mm",
),
),
],
)
@pytest.mark.parametrize("batch_size", [8])
@pytest.mark.parametrize("seq_len", [16])
@pytest.mark.parametrize("hidden_size", [16])
@pytest.mark.parametrize("dtype", [torch.bfloat16])
@pytest.mark.parametrize("dynamic", [True, False])
@pytest.mark.skipif(envs.VLLM_TARGET_DEVICE not in ["cuda"], reason="Only test on CUDA")
def test_async_tp_pass_replace(
test_model: str,
batch_size: int,
seq_len: int,
hidden_size: int,
dtype: torch.dtype,
dynamic: bool,
):
num_processes = 2
distributed_init_method = get_file_store_init_method()
def run_torch_spawn(fn, nprocs):
# need to use torch.mp.spawn otherwise will have problems with
# torch.distributed and cuda
torch.multiprocessing.spawn(
fn,
args=(
num_processes,
test_model,
batch_size,
seq_len,
hidden_size,
dtype,
dynamic,
distributed_init_method,
),
nprocs=nprocs,
)
run_torch_spawn(async_tp_pass_on_test_model, num_processes)
def test_async_tp_pass_requires_full_graph_compilation():
vllm_config = VllmConfig()
vllm_config.compilation_config.use_inductor_graph_partition = False
vllm_config.compilation_config.splitting_ops = [
"vllm::unified_attention_with_output"
]
async_tp_pass = object.__new__(AsyncTPPass)
async_tp_pass.compilation_config = vllm_config.compilation_config
with pytest.raises(
AssertionError, match="AsyncTPPass requires full-graph compilation"
):
async_tp_pass.is_applicable_for_range(Range(start=8, end=8))
def async_tp_pass_on_test_model(
local_rank: int,
world_size: int,
test_model_cls: torch.nn.Module,
batch_size: int,
seq_len: int,
hidden_size: int,
dtype: torch.dtype,
dynamic: bool,
distributed_init_method: str,
check_numerics: bool = False,
):
set_random_seed(0)
device = torch.device(f"{DEVICE_TYPE}:{local_rank}")
torch.accelerator.set_device_index(device)
torch.set_default_device(device)
torch.set_default_dtype(dtype)
update_environment_variables(
{
"RANK": str(local_rank),
"LOCAL_RANK": str(local_rank),
"WORLD_SIZE": str(world_size),
}
)
# initialize distributed
init_distributed_environment(
world_size=world_size,
rank=local_rank,
distributed_init_method=distributed_init_method,
local_rank=local_rank,
)
# configure vllm config for SequenceParallelismPass
vllm_config = VllmConfig()
vllm_config.compilation_config = CompilationConfig(
pass_config=PassConfig(
fuse_gemm_comms=True,
),
)
vllm_config.device_config = DeviceConfig(device=torch.device(DEVICE_TYPE))
# this is a fake model name to construct the model config
# in the vllm_config, it's not really used.
model_name = "RedHatAI/Llama-3.2-1B-Instruct-FP8"
vllm_config.model_config = ModelConfig(
model=model_name, trust_remote_code=True, dtype=dtype, seed=42
)
with set_current_vllm_config(vllm_config):
initialize_model_parallel(tensor_model_parallel_size=world_size)
async_tp_pass = AsyncTPPass(vllm_config)
backend = TestBackend(async_tp_pass)
assert (
async_tp_pass.compilation_config.splitting_ops
== vllm_config.compilation_config.splitting_ops
)
assert (
async_tp_pass.compilation_config.use_inductor_graph_partition
== vllm_config.compilation_config.use_inductor_graph_partition
)
model = test_model_cls(hidden_size, dtype) # Pass dtype to model constructor
hidden_states = torch.randn(
(batch_size * seq_len, hidden_size), dtype=dtype, requires_grad=False
)
if check_numerics:
hidden_states += local_rank * 0.125
if dynamic:
torch._dynamo.mark_dynamic(hidden_states, 0)
compiled_model = torch.compile(model, backend=backend)
actual = compiled_model(hidden_states)
if check_numerics:
# These are new checks, so no existing tolerance is relaxed.
# Allow BF16 rounding vs. eager, but keep the lifetime check exact.
expected = model(hidden_states)
torch.testing.assert_close(actual, expected, rtol=1e-2, atol=1e-2)
snapshot = actual.clone()
changed = compiled_model(-hidden_states)
torch.testing.assert_close(changed, -expected, rtol=1e-2, atol=1e-2)
torch.testing.assert_close(actual, snapshot, rtol=0, atol=0)
assert async_tp_pass.matched_count == 1
# In pre-nodes, all gather or reduce scatter should exist,
# fused_matmul_reduce_scatter or fused_all_gather_matmul should not
backend.check_before_ops(model.ops_in_model_before(), fully_replaced=False)
# In post-nodes, fused_matmul_reduce_scatter or \
# fused_all_gather_matmul should exist
backend.check_after_ops(model.ops_in_model_after())
@@ -1,343 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
import vllm.envs as envs
from tests.compile.backend import TestBackend
from tests.utils import TestFP8Layer, multi_gpu_test
from vllm.compilation.passes.fusion.rms_quant_fusion import RMSNormQuantFusionPass
from vllm.compilation.passes.fusion.sequence_parallelism import SequenceParallelismPass
from vllm.compilation.passes.utility.noop_elimination import NoOpEliminationPass
from vllm.compilation.passes.utility.post_cleanup import PostCleanupPass
from vllm.compilation.passes.vllm_inductor_pass import VllmInductorPass
from vllm.config import (
CompilationConfig,
CUDAGraphMode,
DeviceConfig,
ModelConfig,
PassConfig,
VllmConfig,
get_current_vllm_config,
set_current_vllm_config,
)
from vllm.config.utils import Range
from vllm.distributed import tensor_model_parallel_all_reduce
from vllm.distributed.parallel_state import (
init_distributed_environment,
initialize_model_parallel,
)
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8StaticTensorSym,
)
from vllm.platforms import current_platform
from vllm.utils.system_utils import update_environment_variables
from vllm.utils.torch_utils import set_random_seed
DEVICE_TYPE = current_platform.device_type
pytestmark = pytest.mark.skipif(not current_platform.is_cuda(), reason="Only test CUDA")
FP8_DTYPE = current_platform.fp8_dtype()
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
class TestAllReduceRMSNormModel(torch.nn.Module):
def __init__(self, hidden_size=16, eps=1e-6):
super().__init__()
self.hidden_size = hidden_size
self.eps = eps
self.norm = [RMSNorm(hidden_size, eps) for i in range(4)]
self.w = [torch.rand(hidden_size, hidden_size) for _ in range(3)]
def forward(self, x):
z = torch.relu(x)
x = resid = tensor_model_parallel_all_reduce(z)
y = self.norm[0](x)
z2 = torch.mm(y, self.w[0])
x2 = tensor_model_parallel_all_reduce(z2)
y2, resid = self.norm[1](x2, resid)
z3 = torch.mm(y2, self.w[1])
x3 = tensor_model_parallel_all_reduce(z3)
y3, resid = self.norm[2](x3, resid)
z4 = torch.mm(y3, self.w[2])
x4 = tensor_model_parallel_all_reduce(z4)
y4, resid = self.norm[3](x4, resid)
return y4
def ops_in_model_before(self):
return [torch.ops.vllm.all_reduce.default]
def ops_in_model_after(self):
return [
torch.ops.vllm.all_gather.default,
torch.ops.vllm.reduce_scatter.default,
]
def ops_in_model(self):
return [
torch.ops.vllm_ir.rms_norm,
torch.ops.vllm_ir.fused_add_rms_norm,
]
class TestAllReduceRMSNormStaticQuantFP8Model(torch.nn.Module):
quant_key = kFp8StaticTensorSym
def __init__(self, hidden_size=16, eps=1e-6):
super().__init__()
self.vllm_config = get_current_vllm_config()
self.hidden_size = hidden_size
self.eps = eps
self.norm = [RMSNorm(hidden_size, eps) for i in range(4)]
self.fp8_linear_layers = [
TestFP8Layer(
weight_shape=(hidden_size, hidden_size),
activation_quant_key=self.quant_key,
weight_quant_key=self.quant_key,
input_dtype=self.vllm_config.model_config.dtype,
)
for i in range(3)
]
def forward(self, hidden_states):
# avoid having graph input be an arg to a pattern directly
z = torch.relu(hidden_states)
x = resid = tensor_model_parallel_all_reduce(z)
y = self.norm[0](x)
z2 = self.fp8_linear_layers[0](y)
x2 = tensor_model_parallel_all_reduce(z2)
y2, resid = self.norm[1](x2, resid)
z3 = self.fp8_linear_layers[1](y2)
x3 = tensor_model_parallel_all_reduce(z3)
y3, resid = self.norm[2](x3, resid) # use resid here
z4 = self.fp8_linear_layers[2](y3)
x4 = tensor_model_parallel_all_reduce(z4)
y4, resid = self.norm[3](x4, resid) # use resid here
return y4
def ops_in_model_after(self):
return [
torch.ops.vllm.all_gather.default,
torch.ops.vllm.reduce_scatter.default,
]
def ops_in_model_before(self):
return [
torch.ops.vllm.all_reduce.default,
]
def ops_in_model(self):
if self.vllm_config.compilation_config.pass_config.fuse_norm_quant:
return [torch.ops._C.fused_add_rms_norm_static_fp8_quant.default]
else:
quant_ops = (
[torch.ops._C.static_scaled_fp8_quant.default]
if any(layer.is_quant_fp8_enabled() for layer in self.fp8_linear_layers)
else [torch.ops.aten.reciprocal]
)
return [
torch.ops.vllm_ir.rms_norm,
torch.ops.vllm_ir.fused_add_rms_norm,
*quant_ops,
]
@multi_gpu_test(num_gpus=2)
@pytest.mark.parametrize(
"test_model_cls, custom_ops",
[
(TestAllReduceRMSNormModel, "+rms_norm"),
(TestAllReduceRMSNormModel, "-rms_norm"),
(TestAllReduceRMSNormStaticQuantFP8Model, "+rms_norm,+quant_fp8"),
(TestAllReduceRMSNormStaticQuantFP8Model, "+rms_norm,-quant_fp8"),
(TestAllReduceRMSNormStaticQuantFP8Model, "-rms_norm,+quant_fp8"),
(TestAllReduceRMSNormStaticQuantFP8Model, "-rms_norm,-quant_fp8"),
],
)
@pytest.mark.parametrize("batch_size", [8])
@pytest.mark.parametrize("seq_len", [16])
@pytest.mark.parametrize("hidden_size", [16])
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("fuse_norm_quant", [True, False])
@pytest.mark.parametrize("dynamic", [False, True])
@pytest.mark.skipif(envs.VLLM_TARGET_DEVICE not in ["cuda"], reason="Only test on CUDA")
def test_sequence_parallelism_pass(
test_model_cls: type[torch.nn.Module],
custom_ops: str,
batch_size: int,
seq_len: int,
hidden_size: int,
dtype: torch.dtype,
fuse_norm_quant: bool,
dynamic: bool,
):
num_processes = 2
def run_torch_spawn(fn, nprocs):
# need to use torch.mp.spawn otherwise will have problems with
# torch.distributed and cuda
torch.multiprocessing.spawn(
fn,
args=(
num_processes,
test_model_cls,
custom_ops,
batch_size,
seq_len,
hidden_size,
dtype,
fuse_norm_quant,
dynamic,
),
nprocs=nprocs,
)
run_torch_spawn(sequence_parallelism_pass_on_test_model, num_processes)
def test_sequence_parallelism_pass_requires_full_graph_compilation():
vllm_config = VllmConfig()
vllm_config.compilation_config.use_inductor_graph_partition = False
vllm_config.compilation_config.splitting_ops = [
"vllm::unified_attention_with_output"
]
sequence_parallelism_pass = object.__new__(SequenceParallelismPass)
sequence_parallelism_pass.compilation_config = vllm_config.compilation_config
sequence_parallelism_pass.min_token_num = 1
with pytest.raises(
AssertionError,
match="SequenceParallelismPass requires full-graph compilation",
):
sequence_parallelism_pass.is_applicable_for_range(Range(start=8, end=8))
def sequence_parallelism_pass_on_test_model(
local_rank: int,
world_size: int,
test_model_cls: type[torch.nn.Module],
custom_ops: str,
batch_size: int,
seq_len: int,
hidden_size: int,
dtype: torch.dtype,
fuse_norm_quant: bool,
dynamic: bool,
):
set_random_seed(0)
device = torch.device(f"{DEVICE_TYPE}:{local_rank}")
torch.accelerator.set_device_index(device)
torch.set_default_device(device)
torch.set_default_dtype(dtype)
update_environment_variables(
{
"RANK": str(local_rank),
"LOCAL_RANK": str(local_rank),
"WORLD_SIZE": str(world_size),
"MASTER_ADDR": "localhost",
"MASTER_PORT": "12345",
}
)
# initialize distributed
init_distributed_environment()
# configure vllm config for SequenceParallelismPass
custom_ops_list = custom_ops.split(",") if custom_ops else []
compilation_config = CompilationConfig(
splitting_ops=[], # avoid automatic rms_norm enablement
cudagraph_mode=CUDAGraphMode.NONE, # avoid piecewise warnings
custom_ops=custom_ops_list,
pass_config=PassConfig(
enable_sp=True,
fuse_norm_quant=fuse_norm_quant,
eliminate_noops=True,
),
) # NoOp needed for fusion
device_config = DeviceConfig(device=torch.device(DEVICE_TYPE))
# this is a fake model name to construct the model config
# in the vllm_config, it's not really used.
model_name = "RedHatAI/Llama-3.2-1B-Instruct-FP8"
model_config = ModelConfig(
model=model_name, trust_remote_code=True, dtype=dtype, seed=42
)
vllm_config = VllmConfig(
model_config=model_config,
device_config=device_config,
compilation_config=compilation_config,
)
with set_current_vllm_config(vllm_config):
initialize_model_parallel(tensor_model_parallel_size=world_size)
noop_pass = NoOpEliminationPass(vllm_config)
sequence_parallelism_pass = SequenceParallelismPass(vllm_config)
cleanup_pass = PostCleanupPass(vllm_config)
assert (
sequence_parallelism_pass.compilation_config.splitting_ops
== vllm_config.compilation_config.splitting_ops
)
assert (
sequence_parallelism_pass.compilation_config.use_inductor_graph_partition
== vllm_config.compilation_config.use_inductor_graph_partition
)
passes_for_backend: list[VllmInductorPass] = [
noop_pass,
sequence_parallelism_pass,
]
if fuse_norm_quant:
fusion_pass = RMSNormQuantFusionPass(vllm_config)
passes_for_backend.append(fusion_pass)
passes_for_backend.append(cleanup_pass)
backend = TestBackend(*passes_for_backend)
model = test_model_cls(hidden_size)
hidden_states = torch.randn((batch_size * seq_len, hidden_size), dtype=dtype)
if dynamic:
torch._dynamo.mark_dynamic(hidden_states, 0)
compiled_model = torch.compile(model, backend=backend)
compiled_model(hidden_states)
assert sequence_parallelism_pass.matched_count == 4
# In pre-nodes, all reduce should be there,
# reduce scatter and all gather should not
for op in model.ops_in_model_before():
assert backend.op_count(op, before=True) == 4
# In post-nodes, reduce scatter and all gather should be there,
# all reduce should not
for op in model.ops_in_model_after():
assert backend.op_count(op, before=False) == 4
for op in model.ops_in_model():
assert backend.op_count(op, before=False) > 0
@@ -285,3 +285,134 @@ def test_fuse_mla_dual_rms_norm_fp8_per_token(
backend.check_before_ops(model.ops_in_model_before())
backend.check_after_ops(model.ops_in_model_after())
class MLADualRMSNormFp8GroupTestModel(torch.nn.Module):
"""Minimal model reproducing the FP8 MLA attention path with *group* quant
(block-scaled fp8 weights, 128-wide activation groups):
linear -> split([q_dim, kv_dim])
+-- q_c (getitem 0) -> rocm_aiter_rmsnorm_fp8_group_quant -> dequant
+-- kv_lora (getitem 1) -> split([kv_c_dim, k_pe_dim])
+-- kv_c (getitem 0) -> rms_norm (bf16)
+-- k_pe
"""
GROUP_SIZE = 128
def __init__(
self,
hidden_size: int,
q_dim: int = Q_DIM,
kv_c_dim: int = KV_C_DIM,
k_pe_dim: int = K_PE_DIM,
eps: float = EPS,
):
super().__init__()
self.q_dim = q_dim
self.kv_dim = kv_c_dim + k_pe_dim
self.kv_c_dim = kv_c_dim
self.k_pe_dim = k_pe_dim
self.eps = eps
self.proj = torch.nn.Linear(hidden_size, q_dim + self.kv_dim, bias=False)
self.q_weight = torch.nn.Parameter(torch.ones(q_dim))
self.kv_norm = RMSNorm(kv_c_dim, eps=eps)
def _dequant(self, x_fp8: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
# Group: one (M, N / 128) scale per 128-column group of the row.
m = x_fp8.shape[0]
x = x_fp8.to(torch.float32).view(m, -1, self.GROUP_SIZE)
return (x * scale.view(m, -1, 1)).view(m, -1).to(torch.bfloat16)
def forward(self, x: torch.Tensor):
# Avoid graph input being a direct arg to a matched pattern node
x = torch.relu(x)
projected = self.proj(x)
q_c, kv_lora = projected.split([self.q_dim, self.kv_dim], dim=-1)
kv_c, k_pe = kv_lora.split([self.kv_c_dim, self.k_pe_dim], dim=-1)
q_fp8, q_scale = torch.ops.vllm.rocm_aiter_rmsnorm_fp8_group_quant(
q_c, self.q_weight, self.eps, self.GROUP_SIZE
)
kv_normed = self.kv_norm(kv_c)
# Also return the group scales so the test can check them directly:
# equal scales pin any fp8 payload difference to rounding alone.
return self._dequant(q_fp8, q_scale), q_scale, kv_normed, k_pe
def ops_in_model_before(self):
return [
torch.ops.vllm.rocm_aiter_rmsnorm_fp8_group_quant.default,
torch.ops.vllm_ir.rms_norm.default,
]
def ops_in_model_after(self):
return [torch.ops.vllm.fused_mla_dual_rms_norm_group_quant.default]
@pytest.mark.parametrize("dtype", [torch.bfloat16])
@pytest.mark.parametrize("hidden_size", [7168])
@pytest.mark.skipif(
not is_aiter_found_and_supported(),
reason="Only test on ROCm with AITER installed and supported",
)
def test_fuse_mla_dual_rms_norm_fp8_group(
dtype: torch.dtype,
hidden_size: int,
monkeypatch: pytest.MonkeyPatch,
):
torch._dynamo.reset()
vllm_config = VllmConfig(
model_config=ModelConfig(dtype=dtype),
compilation_config=CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
custom_ops=["+rms_norm"],
pass_config=PassConfig(
fuse_mla_dual_rms_norm=True,
eliminate_noops=True,
),
),
)
with vllm.config.set_current_vllm_config(vllm_config), monkeypatch.context() as m:
from vllm.compilation.passes.fusion.rocm_aiter_fusion import (
MLADualRMSNormFusionPass,
)
torch.set_default_device("cuda")
torch.set_default_dtype(dtype)
torch.manual_seed(42)
m.setenv("VLLM_ROCM_USE_AITER", "1")
rocm_aiter_ops.refresh_env_variables()
fusion_pass = MLADualRMSNormFusionPass(vllm_config)
passes = [
NoOpEliminationPass(vllm_config),
fusion_pass,
PostCleanupPass(vllm_config),
]
backend = TestBackend(*passes)
model = MLADualRMSNormFp8GroupTestModel(hidden_size)
x = torch.randn(64, hidden_size)
torch._dynamo.mark_dynamic(x, 0)
with torch.inference_mode():
outputs_unfused = model(x)
model_fused = torch.compile(model, backend=backend)
outputs_fused = model_fused(x)
q_deq_u, q_scale_u, kv_normed_u, k_pe_u = outputs_unfused
q_deq_f, q_scale_f, kv_normed_f, k_pe_f = outputs_fused
torch.testing.assert_close(k_pe_u, k_pe_f, atol=0, rtol=0)
torch.testing.assert_close(kv_normed_u, kv_normed_f, atol=1e-2, rtol=1e-2)
torch.testing.assert_close(q_scale_u, q_scale_f, atol=0, rtol=1e-5)
E4M3_STEP = 0.125
exact_frac = (q_deq_u == q_deq_f).float().mean().item()
assert exact_frac > 0.99, f"q: only {exact_frac:.4f} of elements bit-exact"
torch.testing.assert_close(q_deq_u, q_deq_f, atol=1e-2, rtol=E4M3_STEP)
assert fusion_pass.matched_count == 1, (
f"Expected 1 fused pair, got {fusion_pass.matched_count}"
)
backend.check_before_ops(model.ops_in_model_before())
backend.check_after_ops(model.ops_in_model_after())
-75
View File
@@ -1,75 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""ROCm AsyncTP numerical coverage kept outside the shared distributed suite."""
import pytest
import torch
from tests.compile.passes.distributed.test_async_tp import (
TestAGMMModel,
TestMMRSModel,
async_tp_pass_on_test_model,
)
from tests.utils import multi_gpu_test
from vllm.distributed import (
tensor_model_parallel_all_gather,
tensor_model_parallel_reduce_scatter,
)
from vllm.platforms import current_platform
from vllm.utils.network_utils import get_file_store_init_method
class TestRocmMMRSModel(TestMMRSModel):
def forward(self, hidden_states):
view = hidden_states.reshape(-1, self.hidden_size)
mm = torch.ops.vllm.rocm_unquantized_gemm(view, self.gate_proj, None)
return tensor_model_parallel_reduce_scatter(mm, dim=0)
def ops_in_model_before(self):
return super().ops_in_model_before() + [
torch.ops.vllm.rocm_unquantized_gemm.default
]
class TestRocmAGMMModel(TestAGMMModel):
def __init__(self, hidden_size=16, dtype=torch.bfloat16):
super().__init__(hidden_size, dtype)
self.weight = torch.nn.Parameter(
torch.empty((hidden_size * 2, hidden_size)), requires_grad=False
)
torch.nn.init.normal_(self.weight, std=0.02)
def forward(self, hidden_states):
view = hidden_states.reshape(-1, self.hidden_size)
gathered = tensor_model_parallel_all_gather(view, dim=0)
return torch.ops.vllm.rocm_unquantized_gemm(gathered, self.weight, None)
def ops_in_model_before(self):
return super().ops_in_model_before() + [
torch.ops.vllm.rocm_unquantized_gemm.default
]
@multi_gpu_test(num_gpus=2)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm backend contract")
@pytest.mark.parametrize(
"test_model", [TestMMRSModel, TestAGMMModel, TestRocmMMRSModel, TestRocmAGMMModel]
)
@pytest.mark.parametrize("dynamic", [False, True])
def test_rocm_async_tp_bf16_rewrite_and_correctness(test_model, dynamic):
"""Real symmetric-memory AG/GEMM and GEMM/RS must replace the collectives."""
torch.multiprocessing.spawn(
async_tp_pass_on_test_model,
args=(
2,
test_model,
8,
16,
128,
torch.bfloat16,
dynamic,
get_file_store_init_method(),
True,
),
nprocs=2,
)
+79 -172
View File
@@ -464,49 +464,41 @@ def test_should_split():
(
"cudagraph_capture_sizes",
"max_cudagraph_capture_size",
"tp_size",
"enable_sp",
"max_num_batched_tokens",
"cudagraph_mode",
"expected_max_size",
),
[
(None, None, 1, False, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 256),
([1, 2, 4], 4, 1, False, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 4),
(None, None, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 256),
([1, 2, 4], 4, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 4),
(
[1, 2, 4],
8,
1,
False,
2048,
CUDAGraphMode.FULL_AND_PIECEWISE,
ValidationError,
),
([1, 256], None, 1, False, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 256),
([], None, 1, False, 2048, CUDAGraphMode.NONE, 0),
(None, 0, 1, False, 2048, CUDAGraphMode.NONE, 0),
([1, 256], None, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 256),
([], None, 2048, CUDAGraphMode.NONE, 0),
(None, 0, 2048, CUDAGraphMode.NONE, 0),
# truncated to nearest multiple of 8 or 16
(None, 257, 1, False, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 256),
(None, 257, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 256),
# max_num_batched_tokens <= max_cudagraph_capture_size should always be
# captured even if not landing on a 16-stride step
(None, 2048, 1, False, 257, CUDAGraphMode.FULL_AND_PIECEWISE, 257),
(None, 2048, 257, CUDAGraphMode.FULL_AND_PIECEWISE, 257),
# max from list
([1, 2, 4, 15], None, 1, False, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 15),
# SP forces full-graph compilation, sizes are filtered by TP
([1, 2, 4, 15], None, 2, True, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 4),
([1, 2, 4, 15], None, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, 15),
# limited by the max_tokens
([1, 2, 4, 15], None, 1, False, 8, CUDAGraphMode.FULL_AND_PIECEWISE, 4),
([1, 2, 4, 15], None, 8, CUDAGraphMode.FULL_AND_PIECEWISE, 4),
# the list should contain at least 1 element when use cudagraph
([], None, 1, False, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, ValidationError),
([], None, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, ValidationError),
# the max capturing size should be >= 1 when use cudagraph
(None, 0, 1, False, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, ValidationError),
(None, 0, 2048, CUDAGraphMode.FULL_AND_PIECEWISE, ValidationError),
],
)
def test_cudagraph_sizes_post_init(
cudagraph_capture_sizes,
max_cudagraph_capture_size,
tp_size,
enable_sp,
max_num_batched_tokens,
cudagraph_mode,
expected_max_size,
@@ -515,10 +507,7 @@ def test_cudagraph_sizes_post_init(
if expected_max_size == ValidationError:
ctx = pytest.raises(expected_max_size)
with (
ctx,
patch.object(current_platform, "device_count", return_value=tp_size),
):
with ctx:
kwargs = {}
if cudagraph_capture_sizes is not None:
kwargs["cudagraph_capture_sizes"] = cudagraph_capture_sizes
@@ -526,18 +515,15 @@ def test_cudagraph_sizes_post_init(
kwargs["max_cudagraph_capture_size"] = max_cudagraph_capture_size
compilation_config = CompilationConfig(
pass_config=PassConfig(
enable_sp=enable_sp,
fuse_norm_quant=True,
fuse_act_quant=True,
eliminate_noops=True,
sp_min_token_num=512 if enable_sp else None,
),
cudagraph_mode=cudagraph_mode,
**kwargs,
)
engine_args = EngineArgs(
model="facebook/opt-125m",
tensor_parallel_size=tp_size,
max_num_seqs=min(max_num_batched_tokens, 128),
max_num_batched_tokens=max_num_batched_tokens,
compilation_config=compilation_config,
@@ -728,35 +714,6 @@ def test_default_cudagraph_capture_sizes_keep_all_sizes_bounded():
)
def test_cudagraph_capture_sizes_respect_sequence_parallelism():
"""Sequence-parallel capture sizes stay divisible by tensor parallel size."""
compilation_config = CompilationConfig(
cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE
)
compilation_config.pass_config.enable_sp = True
config = _mock_config_for_cudagraph_sizes(
max_num_seqs=32,
num_speculative_tokens=16,
max_num_batched_tokens=32768,
compilation_config=compilation_config,
)
config.parallel_config = SimpleNamespace(tensor_parallel_size=2)
config.update_sizes_for_sequence_parallelism = lambda sizes: (
VllmConfig.update_sizes_for_sequence_parallelism(config, sizes)
)
with patch.object(
current_platform,
"is_device_capability_family",
return_value=False,
):
VllmConfig._set_cudagraph_sizes(config)
assert all(size % 2 == 0 for size in compilation_config.cudagraph_capture_sizes)
assert 544 not in compilation_config.cudagraph_capture_sizes
assert compilation_config.max_cudagraph_capture_size == 512
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Only test CUDA")
def test_real_vllm_config_caps_widest_ngram_decode_batch():
"""Real config post-init preserves the default capture ceiling."""
@@ -1046,123 +1003,6 @@ def test_blackwell_cudagraph_default(is_blackwell, expected_max_size):
)
@pytest.mark.skipif(
not current_platform.support_static_graph_mode(),
reason="Skip if not cudagraph mode supported",
)
@pytest.mark.parametrize(
(
"cudagraph_mode",
"use_inductor_graph_partition",
"expected_enable_sp",
"expected_cudagraph_mode",
"expected_piecewise_compile",
"expected_capture_sizes",
"expected_max_size",
),
[
(CUDAGraphMode.PIECEWISE, False, True, CUDAGraphMode.FULL, False, [2, 4], 4),
(
CUDAGraphMode.FULL_DECODE_ONLY,
False,
True,
CUDAGraphMode.FULL_DECODE_ONLY,
False,
[2, 4],
4,
),
(
CUDAGraphMode.FULL_AND_PIECEWISE,
False,
True,
CUDAGraphMode.FULL,
False,
[2, 4],
4,
),
(
CUDAGraphMode.FULL_AND_PIECEWISE,
True,
True,
CUDAGraphMode.FULL_AND_PIECEWISE,
True,
[2, 4],
4,
),
],
)
def test_sequence_parallelism_requires_full_graph_compilation(
cudagraph_mode: CUDAGraphMode,
use_inductor_graph_partition: bool,
expected_enable_sp: bool,
expected_cudagraph_mode: CUDAGraphMode,
expected_piecewise_compile: bool,
expected_capture_sizes: list[int],
expected_max_size: int,
):
with patch.object(current_platform, "device_count", return_value=2):
vllm_config = VllmConfig(
parallel_config=ParallelConfig(tensor_parallel_size=2),
scheduler_config=SchedulerConfig(
max_num_seqs=128,
max_num_batched_tokens=2048,
max_model_len=2048,
is_encoder_decoder=False,
),
)
vllm_config.model_config = MagicMock(
dtype=torch.float16,
enforce_eager=False,
is_moe=False,
disable_cascade_attn=False,
get_hidden_size=MagicMock(return_value=4096),
)
vllm_config.compilation_config = CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
cudagraph_capture_sizes=[1, 2, 4, 15],
max_cudagraph_capture_size=None,
compile_sizes=["cudagraph_capture_sizes"],
use_inductor_graph_partition=use_inductor_graph_partition,
pass_config=PassConfig(
enable_sp=True,
fuse_gemm_comms=True,
fuse_norm_quant=True,
fuse_act_quant=True,
eliminate_noops=True,
sp_min_token_num=512,
),
cudagraph_mode=cudagraph_mode,
)
vllm_config.compilation_config.set_splitting_ops_for_v1(
all2all_backend=vllm_config.parallel_config.all2all_backend,
data_parallel_size=1,
)
vllm_config._set_compile_ranges()
vllm_config._set_cudagraph_sizes()
assert (
vllm_config.compilation_config.use_inductor_graph_partition
== use_inductor_graph_partition
)
assert (
bool(vllm_config.compilation_config.splitting_ops) == expected_piecewise_compile
)
assert vllm_config.compilation_config.pass_config.enable_sp == expected_enable_sp
assert (
vllm_config.compilation_config.pass_config.fuse_gemm_comms == expected_enable_sp
)
assert vllm_config.compilation_config.cudagraph_mode == expected_cudagraph_mode
assert (
vllm_config.compilation_config.cudagraph_capture_sizes == expected_capture_sizes
)
assert (
vllm_config.compilation_config.max_cudagraph_capture_size == expected_max_size
)
assert (
511 in vllm_config.compilation_config.compile_ranges_endpoints
) == expected_enable_sp
def test_cached_compilation_config(default_vllm_config):
import torch
from torch._inductor.utils import run_and_get_code
@@ -1366,3 +1206,70 @@ def test_inductor_asserts_user_override(monkeypatch):
assert config.inductor_compile_config.get("size_asserts") is True
if not _is_torch_equal_or_newer(torch.__version__, "2.12.0.dev"):
assert config.inductor_compile_config.get("alignment_asserts") is False
@pytest.mark.parametrize("deterministic", [False, True])
@pytest.mark.parametrize("override", [None, False, True])
def test_combo_kernel_benchmarking_respects_deterministic(deterministic, override):
from torch._inductor import config as inductor_config
overrides = {} if override is None else {"deterministic": override}
with (
inductor_config.patch(deterministic=deterministic),
patch("vllm.config.compilation.current_platform.is_cpu", return_value=False),
):
config = CompilationConfig(inductor_compile_config=overrides)
assert config.inductor_compile_config["combo_kernels"] is True
effective_deterministic = deterministic if override is None else override
assert config.inductor_compile_config["benchmark_combo_kernel"] is (
not effective_deterministic
)
@pytest.mark.parametrize("deterministic", [False, True])
@pytest.mark.parametrize(
"overrides",
[
{"combo_kernels": False},
{"combo_kernels": True},
{"benchmark_combo_kernel": False},
{"benchmark_combo_kernel": True},
],
)
def test_combo_kernel_explicit_settings_preserved(deterministic, overrides):
from torch._inductor import config as inductor_config
with (
inductor_config.patch(deterministic=deterministic),
patch("vllm.config.compilation.current_platform.is_cpu", return_value=False),
):
config = CompilationConfig(inductor_compile_config=overrides.copy())
for key in ("combo_kernels", "benchmark_combo_kernel"):
assert config.inductor_compile_config.get(key) == overrides.get(key)
@pytest.mark.parametrize("is_cpu,torch_version", [(True, "2.13.0"), (False, "2.8.0")])
def test_combo_kernel_defaults_require_supported_platform_and_torch(
is_cpu, torch_version
):
with (
patch("vllm.config.compilation.current_platform.is_cpu", return_value=is_cpu),
patch("torch.__version__", torch_version),
):
config = CompilationConfig()
assert "combo_kernels" not in config.inductor_compile_config
assert "benchmark_combo_kernel" not in config.inductor_compile_config
def test_combo_kernel_defaults_without_inductor_deterministic_setting():
with (
patch("torch._inductor.config", SimpleNamespace()),
patch("vllm.config.compilation.current_platform.is_cpu", return_value=False),
):
config = CompilationConfig()
assert config.inductor_compile_config["combo_kernels"] is True
assert config.inductor_compile_config["benchmark_combo_kernel"] is True
@@ -1,192 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from vllm.compilation.passes.fusion.sequence_parallelism import (
SP_MIN_HIDDEN_SIZE,
SP_MIN_PER_GPU_SIZE_MB,
get_sequence_parallelism_threshold,
)
class TestGetSequenceParallelismThreshold:
"""Tests for get_sequence_parallelism_threshold function."""
def test_non_cuda_returns_none(self, mock_cuda_platform):
"""Non-CUDA platforms should return None."""
with mock_cuda_platform(is_cuda=False):
result = get_sequence_parallelism_threshold(
hidden_size=8192, tp_size=2, element_size=2
)
assert result is None
def test_unsupported_device_capability_returns_none(self, mock_cuda_platform):
"""Unsupported device capabilities (e.g., sm80) should return None."""
with mock_cuda_platform(capability=(8, 0)):
result = get_sequence_parallelism_threshold(
hidden_size=8192, tp_size=2, element_size=2
)
assert result is None
def test_small_hidden_size_returns_none(self, mock_cuda_platform):
"""H100 with hidden_size below threshold should return None."""
with mock_cuda_platform(capability=(9, 0)):
result = get_sequence_parallelism_threshold(
hidden_size=4096,
tp_size=2,
element_size=2, # 4096 < 8192
)
assert result is None
def test_h100_large_model_returns_threshold(self, mock_cuda_platform):
"""H100 with large enough hidden_size should return calculated threshold."""
with mock_cuda_platform(capability=(9, 0)):
hidden_size = 8192
tp_size = 2
element_size = 2 # float16/bfloat16
result = get_sequence_parallelism_threshold(
hidden_size=hidden_size,
tp_size=tp_size,
element_size=element_size,
)
# Verify calculation: (8 * 2 * 1024 * 1024) // (8192 * 2) = 1024
MiB = 1024 * 1024
expected = int(
(SP_MIN_PER_GPU_SIZE_MB[90] * tp_size * MiB)
// (hidden_size * element_size)
)
assert result == expected
assert result == 1024
@pytest.mark.parametrize(
"hidden_size,tp_size,element_size,expected",
[
# Boundary: exactly at min hidden size threshold, tp_size=1
# (8 * 1 * 1024 * 1024) // (8192 * 2) = 512
(8192, 1, 2, 512),
# Larger hidden size reduces token threshold
# (8 * 1 * 1024 * 1024) // (16384 * 2) = 256
(16384, 1, 2, 256),
# Larger tp_size increases token threshold
# (8 * 4 * 1024 * 1024) // (8192 * 2) = 2048
(8192, 4, 2, 2048),
# Larger element_size (fp32) reduces token threshold
# (8 * 2 * 1024 * 1024) // (8192 * 4) = 512
(8192, 2, 4, 512),
],
)
def test_threshold_calculation_variations(
self, mock_cuda_platform, hidden_size, tp_size, element_size, expected
):
"""Test threshold calculation with various parameter combinations."""
with mock_cuda_platform(capability=(9, 0)):
result = get_sequence_parallelism_threshold(
hidden_size=hidden_size,
tp_size=tp_size,
element_size=element_size,
)
assert result == expected
def test_hidden_size_boundary(self, mock_cuda_platform):
"""Test behavior at the exact hidden_size boundary."""
with mock_cuda_platform(capability=(9, 0)):
# Just below threshold
result = get_sequence_parallelism_threshold(
hidden_size=SP_MIN_HIDDEN_SIZE[90] - 1,
tp_size=2,
element_size=2,
)
assert result is None
# Exactly at threshold
result = get_sequence_parallelism_threshold(
hidden_size=SP_MIN_HIDDEN_SIZE[90],
tp_size=2,
element_size=2,
)
assert result is not None
# XPU-specific constants (must match sequence_parallelism.py values)
_XPU_MIN_HIDDEN_SIZE = 4096
_XPU_MIN_PER_GPU_SIZE_MB = 8.0
class TestGetSequenceParallelismThresholdXPU:
"""Tests for get_sequence_parallelism_threshold on XPU platform."""
def test_xpu_small_hidden_size_returns_none(self, mock_xpu_platform):
"""XPU with hidden_size below threshold should return None."""
with mock_xpu_platform():
result = get_sequence_parallelism_threshold(
hidden_size=_XPU_MIN_HIDDEN_SIZE - 1,
tp_size=2,
element_size=2,
)
assert result is None
def test_xpu_large_model_returns_threshold(self, mock_xpu_platform):
"""XPU with hidden_size >= threshold should return calculated value."""
with mock_xpu_platform():
hidden_size = _XPU_MIN_HIDDEN_SIZE
tp_size = 2
element_size = 2
result = get_sequence_parallelism_threshold(
hidden_size=hidden_size,
tp_size=tp_size,
element_size=element_size,
)
# (8 * 2 * 1024 * 1024) // (4096 * 2) = 2048
MiB = 1024 * 1024
expected = int(
(_XPU_MIN_PER_GPU_SIZE_MB * tp_size * MiB) // (hidden_size * element_size)
)
assert result == expected
assert result == 2048
@pytest.mark.parametrize(
"hidden_size,tp_size,element_size,expected",
[
# (8 * 1 * 1024 * 1024) // (4096 * 2) = 1024
(4096, 1, 2, 1024),
# (8 * 4 * 1024 * 1024) // (4096 * 2) = 4096
(4096, 4, 2, 4096),
# (8 * 2 * 1024 * 1024) // (8192 * 2) = 1024
(8192, 2, 2, 1024),
# (8 * 2 * 1024 * 1024) // (4096 * 4) = 1024
(4096, 2, 4, 1024),
],
)
def test_xpu_threshold_calculation_variations(
self, mock_xpu_platform, hidden_size, tp_size, element_size, expected
):
"""Test XPU threshold calculation with various parameter combinations."""
with mock_xpu_platform():
result = get_sequence_parallelism_threshold(
hidden_size=hidden_size,
tp_size=tp_size,
element_size=element_size,
)
assert result == expected
def test_xpu_hidden_size_boundary(self, mock_xpu_platform):
"""Test behavior at the exact XPU hidden_size boundary."""
with mock_xpu_platform():
# Just below threshold
result = get_sequence_parallelism_threshold(
hidden_size=_XPU_MIN_HIDDEN_SIZE - 1,
tp_size=2,
element_size=2,
)
assert result is None
# Exactly at threshold
result = get_sequence_parallelism_threshold(
hidden_size=_XPU_MIN_HIDDEN_SIZE,
tp_size=2,
element_size=2,
)
assert result is not None
+5 -11
View File
@@ -10,13 +10,11 @@ from typing import cast
from unittest.mock import Mock
import pytest
from transformers import PreTrainedConfig
from transformers import DiffusionGemmaConfig, PreTrainedConfig
from transformers.models.gemma4.configuration_gemma4 import Gemma4TextConfig
from vllm.config import ModelConfig, ParallelConfig, SpeculativeConfig
from vllm.config.model_arch import ModelArchitectureConfig
from vllm.transformers_utils.configs.diffusion_gemma import DiffusionGemmaConfig
from vllm.transformers_utils.configs.gemma4 import gemma4_layer_config
from vllm.transformers_utils.model_arch_config_convertor import (
MODEL_ARCH_CONFIG_CONVERTORS,
Gemma4ModelArchConfigConvertor,
@@ -318,11 +316,7 @@ def _gemma4_text_config(**overrides) -> Gemma4TextConfig:
def test_gemma4_head_dims_vary_by_layer_type():
"""Gemma4's full attention layers are wider than its sliding ones.
Transformers >= 5.15.0 says so in the config; this exercises the convertor
building the same per-layer view from the flat attributes used before that.
"""
"""Gemma4's full attention layers are wider than its sliding ones."""
text_config = _gemma4_text_config(
num_global_key_value_heads=8, attention_k_eq_v=True
)
@@ -332,9 +326,9 @@ def test_gemma4_head_dims_vary_by_layer_type():
assert (arch.head_size, arch.total_num_kv_heads) == (32, 8)
assert [arch[i].head_size for i in range(6)] == [16] * 5 + [32]
assert [arch[i].total_num_kv_heads for i in range(6)] == [4] * 5 + [8]
# The model files resolve each layer through the same helper, so the KV cache
# vLLM allocates and the projections the model builds cannot disagree.
assert [gemma4_layer_config(text_config, i).head_dim for i in range(6)] == [
# The model files read the same per-layer configs, so the KV cache vLLM
# allocates and the projections the model builds cannot disagree.
assert [text_config.per_layer_config[i].head_dim for i in range(6)] == [
arch[i].head_size for i in range(6)
]
@@ -96,6 +96,10 @@ class _SchedulerRequest:
default_factory=lambda: SimpleNamespace(routed_experts_prompt_start=0)
)
@property
def num_prompt_tokens(self) -> int:
return self.num_tokens - self.num_output_tokens
def is_finished(self) -> bool:
return self.finished
@@ -247,9 +251,6 @@ def test_next_step_does_not_consume_pending_output(monkeypatch):
event = Mock()
monkeypatch.setattr(torch.cuda, "Event", lambda **kwargs: event)
monkeypatch.setattr(async_utils, "stream", lambda *args: nullcontext())
monkeypatch.setattr(
async_utils, "async_copy_to_np", lambda tensor: tensor.numpy().copy()
)
worker = _make_worker(1)
worker.begin_step(
_metadata(0, [_request_metadata("request", 0, 1, 0, [])], {}).metadata
@@ -1439,6 +1440,18 @@ def test_scheduler_starts_worker_output_at_requested_prompt_token():
assert metadata.requests == {request.request_id: 2}
# A P/D prefiller cuts its prompt short of the last token, which can pass
# the requested start; the rows then start at the end of the cut prompt.
connector = _make_connector()
request = _scheduler_request(
"cut", [b"a" * 32], num_tokens=3, num_output_tokens=0, prompt_start=4
)
metadata = connector.build_connector_meta(
_step_output([request.request_id], [0], [3]),
{request.request_id: request},
)
assert metadata.requests == {request.request_id: 3}
def test_scheduler_connector_preserves_request_finish_order():
connector = _make_connector()
+73
View File
@@ -39,9 +39,16 @@ from vllm.distributed.parallel_state import (
initialize_model_parallel,
)
from vllm.forward_context import set_forward_context
from vllm.model_executor.layers.quantization.utils.mxfp8_utils import (
dequant_mxfp8_to_bf16,
)
from vllm.model_executor.layers.quantization.utils.nvfp4_emulation_utils import (
convert_swizzled_to_linear,
)
from vllm.models.deepseek_v41.common import engram as engram_ops
from vllm.models.deepseek_v41.common.engram import (
Engram,
EngramBatch,
EngramLayout,
ParallelEngramEmbedding,
engram_head_shard_rank,
@@ -207,10 +214,75 @@ def _worker(rank: int, tp_size: int, port: int) -> None:
n_heads,
sequence_parallel,
)
if tp_size == 1:
_check_fp8_batch(vllm_config)
finally:
cleanup_dist_env_and_memory()
def _check_fp8_batch(vllm_config):
"""MXFP8 staging matches the tables across peer/all-to-all slots, idle
replicas and graph replays."""
from vllm.compilation.breakable_cudagraph import BreakableCUDAGraphCapture
dp_rank = vllm_config.parallel_config.data_parallel_rank
layers = []
for index in range(2):
weight, scale = _full_table(sum(HEAD_SIZES))
weight = (weight.float() * (1 - 2 * index)).to(torch.float8_e4m3fn)
table = ParallelEngramEmbedding(
sum(HEAD_SIZES), DIM, HEAD_SIZES, cpu_offload=True
)
table.weight.weight_loader(table.weight, weight)
table.weight_scale_inv.weight_loader(table.weight_scale_inv, scale)
staged = torch.empty(0, device="cuda")
reference = (weight.cuda(), scale.cuda())
layers.append(SimpleNamespace(embed_tokens=table, staged_rows=staged))
layers[-1].layer_hash_index, layers[-1].reference = index, reference
batch = EngramBatch(layers, 257)
def check(ids):
tokens = ids.shape[0]
for layer in layers:
x = batch.wkv_input(layer, tokens)
sf = convert_swizzled_to_linear(x.scale, tokens, x.data.shape[1], BLOCK)
actual = dequant_mxfp8_to_bf16(x.data, sf).unflatten(-1, (-1, DIM))
weight, scale = layer.reference
expected = _reference(weight, scale, ids[:, layer.layer_hash_index])
torch.testing.assert_close(actual, expected, atol=0, rtol=0)
for counts in ((7, 0, 5, 1), (127,) * 4, (128,) * 4, (257, 0, 129, 1)):
tokens = counts[dp_rank]
seed = 700 + 10 * dp_rank
ids = torch.stack([_make_ids(HEAD_SIZES, tokens, seed + i) for i in (0, 1)], 1)
with set_forward_context(
None,
vllm_config,
num_tokens=tokens,
num_tokens_across_dp=torch.tensor(counts, dtype=torch.int32),
):
batch.prepare_embeddings(ids)
check(ids)
for capture in ("full", "breakable") if len(set(counts)) == 1 else ():
warmup = torch.cuda.Stream()
warmup.wait_stream(torch.cuda.current_stream())
if capture == "full":
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph, stream=warmup):
batch.prepare_embeddings(ids)
else:
graph = BreakableCUDAGraphCapture()
with torch.cuda.stream(warmup), graph:
batch.prepare_embeddings(ids)
torch.cuda.current_stream().wait_stream(warmup)
for step in (2, 3):
replay_ids = _make_ids(HEAD_SIZES, tokens, seed + step)
ids.copy_(torch.stack([replay_ids] * 2, 1))
graph.replay()
check(ids)
del graph
def _check_shared_storage_lifetime_and_failures(failure):
"""One peer's failure must roll back every mapping/registration, without hangs."""
import gc
@@ -516,6 +588,7 @@ def _check_dummy_hash_model_forward(
model.use_native_mega_moe = False
model.use_sequence_parallel = False
model.fuse_mhc_all_reduce = False
model.engram_batch = None
model.engram_hash = state
model.engram_swa_prefix = "swa"
model.engram_dp_shared_memory = dp_shared_memory
+44 -1
View File
@@ -36,7 +36,11 @@ def test_gloo_receive_staging_does_not_force_gpu_sync(monkeypatch):
gsd._install_copy_checkers()
monkeypatch.setattr(eplb_comm, "is_local_first_rank", lambda: False)
monkeypatch.setattr(eplb_comm, "P2POp", lambda op, tensor, peer, group: tensor)
monkeypatch.setattr(
eplb_comm,
"P2POp",
lambda op, tensor, peer=None, group=None, tag=0, group_peer=None: tensor,
)
def receive(tensors):
for tensor in tensors:
@@ -849,3 +853,42 @@ def test_rearrange_expert_weights_profile_mode(world_size):
_test_rearrange_expert_weights_profile_mode,
world_size,
)
def _test_eplb_communicator_pipeline_parallel(env, world_size, backend):
set_env_vars_and_device(env)
config = VllmConfig()
config.parallel_config.tensor_parallel_size = 2
config.parallel_config.pipeline_parallel_size = world_size // 2
with set_current_vllm_config(config):
ensure_model_parallel_initialized(
tensor_model_parallel_size=2,
pipeline_model_parallel_size=world_size // 2,
)
ep_group = get_tp_group()
peer_rank = 1 - ep_group.rank_in_group
rank = torch.distributed.get_rank()
send_tensor = torch.full((16,), rank, device="cuda", dtype=torch.int32)
recv_tensor = torch.empty_like(send_tensor)
communicator = create_eplb_communicator_or_raise(
group_coordinator=ep_group,
backend=backend,
expert_weights=[[send_tensor]],
expert_buffer=[recv_tensor],
)
communicator.add_send([send_tensor], peer_rank, expert_id=0)
communicator.add_recv([recv_tensor], peer_rank, expert_id=0)
communicator.execute()
expected = torch.full_like(recv_tensor, ep_group.ranks[peer_rank])
torch.testing.assert_close(recv_tensor, expected)
@pytest.mark.parametrize("world_size", [2, 4])
@pytest.mark.parametrize("backend", ["torch_nccl", "torch_gloo"])
def test_eplb_communicator_pipeline_parallel(world_size, backend):
"""Transfer weights within each PP stage, including nonzero global ranks."""
if torch.accelerator.device_count() < world_size:
pytest.skip(f"Need at least {world_size} GPUs to run the test")
distributed_run(_test_eplb_communicator_pipeline_parallel, world_size, backend)
+203 -6
View File
@@ -150,7 +150,9 @@ def _init_dp_environment(world_size, rank, port, dp_size, dp_port):
@contextmanager
def _make_forward_context(rank, world_size, num_tokens_per_rank):
def _make_forward_context(
rank, world_size, num_tokens_per_rank, num_tokens_across_dp=None
):
"""Keep the vLLM config and mock-DP forward context active together.
Returns a context manager suitable for ``with`` statements.
@@ -175,15 +177,15 @@ def _make_forward_context(rank, world_size, num_tokens_per_rank):
is_moe_model=True,
data_parallel_rank=rank,
)
if num_tokens_across_dp is None:
num_tokens_across_dp = [num_tokens_per_rank] * world_size
with (
set_current_vllm_config(vllm_config),
set_forward_context(
_AttnMeta(),
vllm_config,
num_tokens=num_tokens_per_rank,
num_tokens_across_dp=torch.tensor(
[num_tokens_per_rank] * world_size, dtype=torch.int
),
num_tokens_across_dp=torch.tensor(num_tokens_across_dp, dtype=torch.int),
),
):
yield
@@ -516,6 +518,121 @@ def test_one_sided_manager_workspace_grow(world_size):
# ---------------------------------------------------------------------------
class _FakeCombineGroup:
def __init__(self, combine_input):
self.combine_input = combine_input
self.allocation_calls = 0
self.combined_input = None
def allocate_combine_input(self, shape, dtype, device, **kwargs):
self.allocation_calls += 1
assert self.combine_input is not None
assert self.combine_input.shape == shape
assert self.combine_input.dtype == dtype
assert self.combine_input.device == device
return self.combine_input
def combine_into_output(self, hidden_states, output, **kwargs):
self.combined_input = hidden_states
output.copy_(hidden_states)
return output
def test_args_cpu_workspace_allocation(monkeypatch):
from types import SimpleNamespace
import vllm.model_executor.layers.fused_moe.modular_kernel as mk
from vllm.model_executor.layers.fused_moe.activation import MoEActivation
kernel = object.__new__(mk.FusedMoEKernelModularImpl)
kernel.fused_experts = SimpleNamespace(
workspace_dtype=lambda dtype: dtype,
workspace_shapes=lambda *args: ((0,), (0,), (2, 3)),
finalize_weight_and_reduce_impl=lambda: None,
)
kernel.prepare_finalize = SimpleNamespace(
allocate_fused_expert_output=lambda *args: None,
)
monkeypatch.setattr(mk.current_platform, "is_cpu", lambda: True)
workspace13, workspace2, output, specialized = kernel._allocate_buffers(
torch.float32,
torch.device("cpu"),
2,
2,
3,
3,
1,
1,
1,
None,
MoEActivation.SILU,
)
assert workspace13.numel() == workspace2.numel() == 0
assert output.shape == (2, 3)
assert output.device.type == "cpu"
assert not specialized
def test_args_finalize_noop_reuses_fused_expert_output(monkeypatch):
import vllm.model_executor.layers.fused_moe.prepare_finalize.naive_dp_ep as pf
from vllm.model_executor.layers.fused_moe.topk_weight_and_reduce import (
TopKWeightAndReduceNoOP,
)
fused_expert_output = torch.arange(6, dtype=torch.float32).view(2, 3)
output = torch.empty_like(fused_expert_output)
group = _FakeCombineGroup(combine_input=None)
monkeypatch.setattr(pf, "get_ep_group", lambda: group)
impl = pf.MoEPrepareAndFinalizeNaiveDPEPModular()
impl.finalize(
output,
fused_expert_output,
torch.ones((2, 1)),
torch.zeros((2, 1), dtype=torch.long),
False,
TopKWeightAndReduceNoOP(),
)
assert group.allocation_calls == 0
assert group.combined_input is fused_expert_output
torch.testing.assert_close(output, fused_expert_output)
def test_args_finalize_contiguous_writes_combine_input(monkeypatch):
import vllm.model_executor.layers.fused_moe.prepare_finalize.naive_dp_ep as pf
import vllm.model_executor.layers.fused_moe.topk_weight_and_reduce as wr
fused_expert_output = torch.arange(12, dtype=torch.float32).view(2, 2, 3)
original = fused_expert_output.clone()
topk_weights = torch.tensor([[0.25, 0.75], [0.4, 0.6]])
combine_input = torch.empty((2, 3), dtype=torch.float32)
output = torch.empty_like(combine_input)
group = _FakeCombineGroup(combine_input)
monkeypatch.setattr(pf, "get_ep_group", lambda: group)
monkeypatch.setattr(
wr.ops,
"moe_sum",
lambda hidden_states, out: out.copy_(hidden_states.sum(dim=1)),
)
impl = pf.MoEPrepareAndFinalizeNaiveDPEPModular()
impl.finalize(
output,
fused_expert_output,
topk_weights,
torch.zeros((2, 2), dtype=torch.long),
False,
wr.TopKWeightAndReduceContiguous(),
)
expected = (original * topk_weights.unsqueeze(-1)).sum(dim=1)
assert group.allocation_calls == 1
assert group.combined_input is combine_input
torch.testing.assert_close(output, expected)
def _args_dispatch_combine_worker(rank, world_size):
from vllm.distributed.device_communicators.all2all import AgRsAll2AllManager
from vllm.forward_context import get_forward_context
@@ -604,14 +721,39 @@ def _args_dispatch_combine_worker(rank, world_size):
# -- combine (reduce-scatter) --
# Each token i has value i in all columns; after reduce-scatter
# each rank gets its slice, summed across ranks.
expert_out = (
expert_values = (
torch.arange(total_tokens, device=device, dtype=torch.float32)
.unsqueeze(1)
.expand(total_tokens, hidden_size)
.contiguous()
)
expert_out = manager.allocate_combine_input(
expert_values.shape,
expert_values.dtype,
expert_values.device,
is_sequence_parallel=True,
)
if expert_out is None:
expert_out = expert_values
else:
from vllm.distributed.device_communicators.pynccl_allocator import (
is_symmetric_memory_tensor,
)
combined = manager.combine(expert_out, is_sequence_parallel=True)
assert is_symmetric_memory_tensor(expert_out)
expert_out.copy_(expert_values)
combine_output = torch.empty(
(tokens_per_rank, hidden_size),
device=device,
dtype=expert_out.dtype,
)
combined = manager.combine_into_output(
expert_out,
combine_output,
is_sequence_parallel=True,
)
assert combined.data_ptr() == combine_output.data_ptr()
assert combined.shape == (tokens_per_rank, hidden_size)
for i in range(tokens_per_rank):
@@ -623,6 +765,61 @@ def _args_dispatch_combine_worker(rank, world_size):
torch.distributed.barrier()
uneven_sizes = [tokens_per_rank + r for r in range(world_size)]
with _make_forward_context(
rank,
world_size,
uneven_sizes[rank],
num_tokens_across_dp=uneven_sizes,
):
dp_metadata = get_forward_context().dp_metadata
assert dp_metadata is not None
with dp_metadata.sp_local_sizes(sequence_parallel_size=1):
assert (
manager.allocate_combine_input(
(sum(uneven_sizes), hidden_size),
torch.float32,
device,
is_sequence_parallel=True,
)
is None
)
total_uneven_tokens = sum(uneven_sizes)
uneven_input = (
torch.arange(
total_uneven_tokens,
dtype=torch.float32,
device=device,
)
.unsqueeze(1)
.expand(total_uneven_tokens, hidden_size)
.contiguous()
)
uneven_input.add_(rank)
uneven_output = torch.empty(
(uneven_sizes[rank], hidden_size),
dtype=torch.float32,
device=device,
)
combined = get_ep_group().reduce_scatterv_into_output(
uneven_input,
uneven_output,
dim=0,
sizes=uneven_sizes,
)
assert combined.data_ptr() == uneven_output.data_ptr()
start = sum(uneven_sizes[:rank])
expected = torch.arange(
start,
start + uneven_sizes[rank],
dtype=torch.float32,
device=device,
) * world_size + sum(range(world_size))
expected = expected.unsqueeze(1).expand_as(combined)
torch.testing.assert_close(combined, expected)
@requires_multi_gpu
@pytest.mark.parametrize("world_size", [2])
+149 -5
View File
@@ -3,6 +3,7 @@
import random
import typing
from types import SimpleNamespace
import pytest
import torch
@@ -12,11 +13,15 @@ import torch.multiprocessing as mp
import vllm.envs as envs
from tests.utils import ensure_current_vllm_config
from vllm.distributed import cleanup_dist_env_and_memory
from vllm.distributed.device_communicators.cuda_communicator import CudaCommunicator
from vllm.distributed.device_communicators.cuda_communicator import (
NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION,
CudaCommunicator,
)
from vllm.distributed.device_communicators.pynccl import register_nccl_symmetric_ops
from vllm.distributed.device_communicators.pynccl_allocator import (
get_nccl_mem_pool,
is_symmetric_memory_enabled,
is_symmetric_memory_tensor,
)
from vllm.distributed.parallel_state import (
get_tp_group,
@@ -32,6 +37,53 @@ random.seed(44)
test_size_elements = 4 * 1024 * 1024
def test_disabled_pynccl_does_not_allocate_symmetric_buffer():
communicator = object.__new__(CudaCommunicator)
communicator.pynccl_comm = SimpleNamespace(disabled=True)
assert (
communicator.get_symmetric_memory_buffer(
"test", (1,), torch.float32, torch.device("cuda")
)
is None
)
@pytest.mark.parametrize("use_aiter", [False, True])
def test_reduce_scatterv_preserves_caller_output(monkeypatch, use_aiter):
import vllm.distributed.device_communicators.cuda_communicator as cc
communicator = object.__new__(CudaCommunicator)
communicator.world_size = 2
communicator.rank_in_group = 0
input_ = torch.arange(12, dtype=torch.float32).view(4, 3)
output = torch.full((2, 3), float("nan"))
def reduce_scatter(out, inp):
assert out is output
out.copy_(inp.view(2, 2, 3).sum(dim=0))
communicator.pynccl_comm = SimpleNamespace(
disabled=False, nccl_version=22902, reduce_scatter=reduce_scatter
)
communicator._can_use_aiter_ag_rs = lambda sizes: use_aiter and sizes is None
communicator.aiter_ar_comm = SimpleNamespace(
should_custom_rs=lambda inp, dim: True,
custom_reduce_scatter=lambda inp, out, dim: reduce_scatter(out, inp),
)
monkeypatch.setattr(cc, "should_nccl_symm_mem_ag_rs", lambda: True)
monkeypatch.setattr(cc, "is_symmetric_memory_tensor", lambda tensor: False)
monkeypatch.setenv("VLLM_BATCH_INVARIANT", "0")
# Explicit uniform sizes must not stage an ordinary input into symmetric
# scratch, and AITER must write the supplied output after normalization.
result = communicator.reduce_scatterv_into_output(
input_, output, dim=0, sizes=[2, 2]
)
assert result.data_ptr() == output.data_ptr()
torch.testing.assert_close(output, input_.view(2, 2, 3).sum(dim=0))
def nccl_symm_mem_allreduce_worker(local_rank: int, world_size: int):
monkeypatch = pytest.MonkeyPatch()
with monkeypatch.context() as m:
@@ -193,15 +245,107 @@ def nccl_symm_mem_reduce_scatter_worker(local_rank: int, world_size: int):
pytest.skip("NCCL symmetric memory is disabled.")
per_rank_size = test_size_elements // world_size
input_tensor = torch.randint(
ordinary_input = torch.randint(
1, 23, (test_size_elements,), dtype=dtype, device=device
)
input_clone = input_tensor.clone()
output = cuda_communicator.reduce_scatter(input_tensor, dim=0)
ordinary_clone = ordinary_input.clone()
ordinary_output = cuda_communicator.reduce_scatter(ordinary_input, dim=0)
group = get_tp_group().device_group
expected = torch.empty(per_rank_size, dtype=dtype, device=device)
ordinary_expected = torch.empty(per_rank_size, dtype=dtype, device=device)
dist.reduce_scatter_tensor(ordinary_expected, ordinary_clone, group=group)
torch.testing.assert_close(
ordinary_output, ordinary_expected, atol=2.5, rtol=0.1
)
assert is_symmetric_memory_tensor(ordinary_output)
# Both calls reuse rs_out; validate the first result before overwriting it.
for sizes in (None, [per_rank_size] * world_size):
ordinary_v_output = cuda_communicator.reduce_scatterv(
ordinary_input, dim=0, sizes=sizes
)
torch.testing.assert_close(
ordinary_v_output, ordinary_expected, atol=2.5, rtol=0.1
)
assert is_symmetric_memory_tensor(ordinary_v_output)
pynccl_comm = cuda_communicator.pynccl_comm
assert pynccl_comm is not None
if pynccl_comm.nccl_version < NCCL_DIRECT_SYMM_RS_OUTPUT_MIN_VERSION:
return
from vllm.v1.worker import ubatching
m.setattr(ubatching, "dbo_current_ubatch_id", lambda: 0)
ubatch0 = cuda_communicator._get_symm_scratch("ag_out", (128,), dtype, device)
ubatch0.fill_(1)
m.setattr(ubatching, "dbo_current_ubatch_id", lambda: 1)
ubatch1 = cuda_communicator._get_symm_scratch("ag_out", (128,), dtype, device)
ubatch1.fill_(2)
assert ubatch0.data_ptr() != ubatch1.data_ptr()
assert (ubatch0 == 1).all()
m.setattr(ubatching, "dbo_current_ubatch_id", lambda: 0)
smaller = cuda_communicator._get_symm_scratch("ag_out", (64,), dtype, device)
assert smaller.shape == (64,)
assert smaller.data_ptr() == ubatch0.data_ptr()
grown = cuda_communicator._get_symm_scratch("ag_out", (129,), dtype, device)
assert grown.shape == (129,)
assert grown.data_ptr() != ubatch0.data_ptr()
reused = cuda_communicator._get_symm_scratch("ag_out", (200,), dtype, device)
assert reused.data_ptr() == grown.data_ptr()
input_tensor = cuda_communicator._get_symm_scratch(
"test_graph_rs_input", (test_size_elements,), dtype, device
)
input_tensor.random_(1, 23)
input_clone = input_tensor.clone()
output = torch.empty(per_rank_size, dtype=dtype, device=device)
assert is_symmetric_memory_tensor(input_tensor)
assert not is_symmetric_memory_tensor(output)
result = cuda_communicator.reduce_scatterv_into_output(
input_tensor,
output,
dim=0,
sizes=[per_rank_size] * world_size,
)
assert result.data_ptr() == output.data_ptr()
expected = torch.empty_like(output)
dist.reduce_scatter_tensor(expected, input_clone, group=group)
torch.testing.assert_close(result, expected, atol=2.5, rtol=0.1)
dist.barrier(group=get_tp_group().cpu_group)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
graph_result = cuda_communicator.reduce_scatterv_into_output(
input_tensor,
output,
dim=0,
sizes=[per_rank_size] * world_size,
)
assert graph_result.data_ptr() == output.data_ptr()
input_tensor.random_(24, 47)
input_clone.copy_(input_tensor)
dist.reduce_scatter_tensor(expected, input_clone, group=group)
captured_input_ptr = input_tensor.data_ptr()
del input_tensor
grown_input = cuda_communicator._get_symm_scratch(
"test_graph_rs_input", (test_size_elements + 1,), dtype, device
)
assert grown_input.data_ptr() != captured_input_ptr
retired = cuda_communicator.__dict__["_retired_symm_scratch_bufs"]
assert any(
buf.data_ptr() == captured_input_ptr
for buffers in retired.values()
for buf in buffers
)
output.zero_()
graph.replay()
torch.accelerator.synchronize()
torch.testing.assert_close(output, expected, atol=2.5, rtol=0.1)
+22
View File
@@ -1,11 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import gc
import io
import pickle
import random
import threading
import time
import weakref
from types import SimpleNamespace
from unittest import mock
@@ -634,6 +636,26 @@ def test_acquire_read_releases_slot_when_reader_raises():
reader.shutdown()
def test_reader_in_reference_cycle_is_collected_without_blocking():
writer = MessageQueue(
n_reader=1,
n_local_reader=1,
max_chunk_bytes=1024 * 1024,
max_chunks=1,
)
reader = MessageQueue.create_from_handle(writer.export_handle(), rank=0)
reader.cycle = reader
reader_ref = weakref.ref(reader)
del reader
collector = threading.Thread(target=gc.collect, daemon=True)
collector.start()
collector.join(timeout=10)
assert not collector.is_alive()
assert reader_ref() is None
def test_warning_logs(caplog_vllm):
"""Test that warning logs are emitted at VLLM_RINGBUFFER_WARNING_INTERVAL intervals
when indefinite=False, and are not emitted when indefinite=True.
+3 -2
View File
@@ -857,13 +857,14 @@ def test_cloud_storage_tokenizer_skips_get_model_path(monkeypatch):
class TestDeviceIds:
def test_device_ids_with_cvd_out_of_range(self, monkeypatch):
@pytest.mark.parametrize("device_ids", [[0, 2], [-1]])
def test_device_ids_with_cvd_out_of_range(self, monkeypatch, device_ids):
"""--device-ids index beyond the CVD set raises ValueError."""
from vllm.platforms import current_platform
key = current_platform.device_control_env_var
monkeypatch.setenv(key, "4,5")
args = EngineArgs(model="m", device_ids=[0, 2])
args = EngineArgs(model="m", device_ids=device_ids)
with pytest.raises(ValueError, match="out of range"):
args._resolve_device_ids()
@@ -1987,6 +1987,32 @@ class TestThinkingConfig:
assert result.include_reasoning is True
assert result.thinking_token_budget is None
@pytest.mark.parametrize(
"config",
[
pytest.param({"output_config": {"effort": "low"}}, id="effort"),
pytest.param({"thinking": {"type": "disabled"}}, id="disabled"),
pytest.param(
{"thinking": {"type": "enabled", "budget_tokens": 2048}},
id="enabled",
),
],
)
def test_count_tokens_matches_messages(self, config):
"""Effort and thinking change the rendered prompt, so count_tokens must
apply them the same way /v1/messages does."""
messages = [{"role": "user", "content": "Hello"}]
expected = _convert(
AnthropicMessagesRequest(
model="test-model", max_tokens=4096, messages=messages, **config
)
)
result = _convert(
AnthropicCountTokensRequest(model="test-model", messages=messages, **config)
)
assert result.reasoning_effort == expected.reasoning_effort
assert result.thinking_token_budget == expected.thinking_token_budget
class TestProbeDisabledThinkingEffort:
"""``auto`` falls back to ``low`` when ``none`` cannot turn thinking off."""
@@ -2117,3 +2143,30 @@ class TestMidConversationToolChanges:
ValidationError, match='only allowed in messages with role "system"'
):
request_cls(model="test-model", max_tokens=128, **fields)
class TestWatermarking:
def test_defaults_to_unspecified(self):
request = _make_request([{"role": "user", "content": "hi"}])
assert _convert(request).watermarking is None
def test_forwards_explicit_enable(self):
request = _make_request([{"role": "user", "content": "hi"}], watermarking=True)
assert _convert(request).watermarking is True
def test_forwards_the_opt_out(self):
request = _make_request([{"role": "user", "content": "hi"}], watermarking=False)
assert _convert(request).watermarking is False
@pytest.mark.parametrize("watermarking", [None, True, False])
def test_reaches_sampling_params(self, watermarking):
request = _make_request(
[{"role": "user", "content": "hi"}], watermarking=watermarking
)
params = _convert(request).to_sampling_params(16, {})
assert params.watermarking is watermarking
+54 -8
View File
@@ -32,8 +32,14 @@ from vllm.entrypoints.cohere.protocol import (
AssistantMessageResponse,
CohereChatV2Response,
)
from vllm.entrypoints.cohere.serving import CohereServingChatV2
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateRequest
from vllm.entrypoints.cohere.serving import (
_API_SERVER_ONLY_TEMPLATE_KWARGS,
CohereServingChatV2,
)
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateRequest,
ReasoningParserKwargs,
)
from vllm.entrypoints.serve.engine.protocol import ErrorInfo, ErrorResponse
from vllm.entrypoints.serve.exception_handling.handlers.http import (
http_exception_handler,
@@ -44,7 +50,7 @@ from vllm.entrypoints.serve.exception_handling.handlers.validation import (
from vllm.entrypoints.serve.exception_handling.handlers.vllm_error import (
vllm_error_handler,
)
from vllm.exceptions import VLLMError
from vllm.exceptions import VLLMError, VLLMValidationError
from vllm.sampling_params import SamplingParams
@@ -72,7 +78,7 @@ class _Handler:
* a :class:`CohereChatV2Response` (non-streaming JSON path);
* an async generator yielding SSE frames (streaming path);
* an :class:`ErrorResponse` (error envelope path); or
* an exception (router-level 500 path).
* an exception (router-level error path).
"""
def __init__(self, result):
@@ -97,6 +103,12 @@ class _RenderChatHandler:
def to_chat_completion_request(self, request):
return CohereServingChatV2._convert_v2_to_chat_completion(request)
def _engine_chat_template_kwargs(self, chat_template_kwargs):
return CohereServingChatV2._engine_chat_template_kwargs(
self, # type: ignore[arg-type]
chat_template_kwargs,
)
class _RenderHandler:
"""Minimal stand-in for :class:`ServingRender`.
@@ -359,6 +371,22 @@ class TestEndpoint:
body = r.json()
assert body == {"message": "kaboom"}
@pytest.mark.parametrize(
"exc",
[
VLLMValidationError("bad temperature", parameter="temperature"),
ValueError("bad temperature"),
],
ids=["vllm_validation_error", "value_error"],
)
def test_handler_client_error_returns_400_envelope(self, exc):
"""Client-caused handler errors are 4xx, matching the OpenAI routes."""
app = _build_app(handler=_Handler(exc))
with TestClient(app) as client:
r = client.post("/cohere/v2/chat", json=_minimal_request_body())
assert r.status_code == HTTPStatus.BAD_REQUEST
assert "bad temperature" in r.json()["message"]
def test_non_json_content_type_rejected(self):
"""The ``validate_json_request`` dependency raises
``RequestValidationError`` (HTTP 422) for non-JSON content
@@ -459,6 +487,24 @@ class TestRenderEndpoint:
# The conversion lower-cases safety_mode for the renderer.
assert kwargs["safety_mode"] == "strict"
def test_api_server_only_kwargs_not_forwarded(self):
"""As on ``/cohere/v2/chat``, the engine's reasoning parser must not
receive the template kwargs that only the API server reads."""
result = _generate_request()
result.reasoning_parser_kwargs = ReasoningParserKwargs(
chat_template_kwargs={
"safety_mode": "strict",
**dict.fromkeys(_API_SERVER_ONLY_TEMPLATE_KWARGS, "x"),
}
)
app = _build_render_app(_RenderChatHandler(), _RenderHandler(result))
with TestClient(app) as client:
r = client.post("/cohere/v2/chat/render", json=_minimal_request_body())
assert r.status_code == HTTPStatus.OK
assert r.json()["reasoning_parser_kwargs"] == {
"chat_template_kwargs": {"safety_mode": "strict"}
}
def test_501_when_chat_handler_missing(self):
app = _build_render_app(None, _RenderHandler(_generate_request()))
with TestClient(app) as client:
@@ -495,10 +541,10 @@ class TestRenderEndpoint:
assert r.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
assert r.json() == {"message": "tokenizer exploded"}
def test_conversion_exception_returns_500_envelope(self):
def test_conversion_client_error_returns_400_envelope(self):
"""Conversion runs inside the same ``try`` as the render call, so
a bad v2 body that slips past Pydantic still yields the Cohere
error envelope rather than an unhandled 500 with vLLM's shape.
a bad v2 body that slips past Pydantic still yields a 4xx in the
Cohere error envelope rather than an unhandled 500 with vLLM's shape.
"""
class _Boom:
@@ -508,7 +554,7 @@ class TestRenderEndpoint:
app = _build_render_app(_Boom(), _RenderHandler(_generate_request()))
with TestClient(app) as client:
r = client.post("/cohere/v2/chat/render", json=_minimal_request_body())
assert r.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
assert r.status_code == HTTPStatus.BAD_REQUEST
assert r.json() == {"message": "unconvertible message"}
def test_invalid_body_returns_422(self):
@@ -25,6 +25,7 @@ from vllm.entrypoints.cohere.cohere_chat_message import (
from vllm.entrypoints.cohere.protocol import (
CohereChatV2Request,
CohereChatV2Response,
CohereLogprobItem,
)
from vllm.entrypoints.cohere.serving import (
_FINISH_REASON_MAP,
@@ -130,6 +131,8 @@ def _build_chat_completion_response(
citations: list[Any] | None = None,
usage: dict[str, Any] | None = None,
kv_transfer_params: dict[str, Any] | None = None,
logprobs: list[tuple[str, float]] | None = None,
token_ids: list[int] | None = None,
) -> ChatCompletionResponse:
message: dict[str, Any] = {"role": "assistant"}
if content is not None:
@@ -151,6 +154,12 @@ def _build_chat_completion_response(
"message": message,
"finish_reason": finish_reason,
"stop_reason": stop_reason,
"logprobs": (
{"content": [{"token": t, "logprob": lp} for t, lp in logprobs]}
if logprobs is not None
else None
),
"token_ids": token_ids,
}
],
# ``usage`` is a required field on ChatCompletionResponse, but the
@@ -689,6 +698,8 @@ class TestBuildBaseChatCompletion:
assert result.top_k == 50
assert result.top_p == 0.95
assert result.logprobs is True
# Needed to fill ``token_ids`` in the Cohere logprobs response.
assert result.return_token_ids is True
assert result.priority == 2
assert result.kv_transfer_params == {"x": 1}
# ``chat_template_kwargs`` may be expanded by _apply_cohere_*; the
@@ -1907,6 +1918,7 @@ class TestChatCompletionToV2:
assert v2.message.tool_calls is None
assert v2.message.tool_plan is None
assert v2.usage is None
assert v2.logprobs is None
def test_stop_sequence_finish_reason(self):
serving = _serving()
@@ -1990,6 +2002,19 @@ class TestChatCompletionToV2:
v2 = serving._chat_completion_to_v2(resp, _make_request())
assert v2.kv_transfer_params == {"k": 1}
def test_logprobs_propagated(self):
serving = _serving()
resp = _build_chat_completion_response(
content="Hello",
logprobs=[("Hel", -0.25), ("lo", -0.5)],
token_ids=[101, 102],
)
v2 = serving._chat_completion_to_v2(resp, _make_request(logprobs=True))
assert v2.logprobs == [
CohereLogprobItem(text="Hel", token_ids=[101], logprobs=[-0.25]),
CohereLogprobItem(text="lo", token_ids=[102], logprobs=[-0.5]),
]
# ======================================================================
# _build_usage
@@ -2510,3 +2535,24 @@ class TestCreateErrorResponse:
assert err.error.message == "oops"
assert err.error.code == 400
assert err.error.type == "bad_request"
def test_watermarking_defaults_to_unspecified():
assert _convert(_make_request()).watermarking is None
def test_watermarking_explicit_enable_is_forwarded():
assert _convert(_make_request(watermarking=True)).watermarking is True
def test_watermarking_opt_out_is_forwarded():
assert _convert(_make_request(watermarking=False)).watermarking is False
@pytest.mark.parametrize("watermarking", [None, True, False])
def test_watermarking_reaches_sampling_params(watermarking):
request = _make_request(watermarking=watermarking)
params = _convert(request).to_sampling_params(16, {})
assert params.watermarking is watermarking
@@ -12,6 +12,7 @@ Tests cover:
import math
from dataclasses import dataclass, field
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock
@@ -138,6 +139,7 @@ class TestProtocolModels:
assert req_str.apply_softmax is True # default
assert req_str.item_first is False # default
assert req_str.add_special_tokens is True # default
assert req_str.cache_salt is None
# Test request with pre-tokenized inputs and custom options
req_tok = GenerativeScoringRequest(
@@ -295,28 +297,49 @@ class TestGeneration:
"""Tests for the full generation flow with mocked engine."""
@pytest.mark.asyncio
async def test_successful_generation(self):
"""Test successful score generation returns valid response."""
@pytest.mark.parametrize("cache_salt", [None, "tenant-a"])
@pytest.mark.parametrize(
"query,items",
[
("Is this city the capital of France? ", ["Paris", "London"]),
([100, 101], [[200, 201], [300, 301]]),
],
ids=["text", "token_ids"],
)
async def test_successful_generation(self, cache_salt, query, items):
"""Test scoring succeeds and preserves cache_salt for every item."""
mock_engine = _create_mock_engine()
serving = _create_serving(mock_engine)
mock_logprobs = {1234: -0.5, 5678: -2.0, 100: -3.0}
mock_output = _create_mock_request_output(mock_logprobs)
state = SimpleNamespace(sampling_params=None, prompts=[])
async def mock_generate(*args, **kwargs):
state.prompts.append(args[0])
state.sampling_params = args[1]
yield mock_output
mock_engine.generate = mock_generate
request = GenerativeScoringRequest(
model=MODEL_NAME,
query="Is Paris the capital?",
items=["Yes", "No"],
query=query,
items=items,
label_token_ids=[1234, 5678],
cache_salt=cache_salt,
)
result = await serving.create_generative_scoring(request, None)
assert isinstance(result, GenerativeScoringResponse)
assert state.sampling_params is not None
assert state.sampling_params.watermarking is False
assert len(state.prompts) == len(items)
for prompt in state.prompts:
if cache_salt is None:
assert "cache_salt" not in prompt
else:
assert prompt["cache_salt"] == cache_salt
assert len(result.data) == 2
for item_result in result.data:
assert 0.0 <= item_result.score <= 1.0
@@ -0,0 +1,179 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import pytest
from vllm.entrypoints.generate.structured_decisions.question_types import (
QUESTION_TYPES,
Option,
Question,
QuestionType,
StructuredDecisionError,
build_question,
register_question_type,
)
def choice(qid="bucket", criteria=None, instructions="Which team?", max_options=128):
return build_question(
qid,
"choice",
instructions,
criteria or {"billing": "money", "outage": None, "other": None},
max_options,
)
def noul(qid="urgent", criteria=None, instructions="Reply within the hour?"):
return build_question(qid, "noul", instructions, criteria, 128)
def score(qid="tone", criteria=None, instructions="How angry?", max_options=128):
return build_question(
qid,
"score",
instructions,
criteria or ["calm", "annoyed", "furious"],
max_options,
)
def test_choice_labels_follow_option_order():
q = choice()
assert q.labels == ("A", "B", "C")
assert [a.name for a in q.options] == ["billing", "outage", "other"]
assert q.options[0].description == "money"
wide = choice(criteria={str(i): None for i in range(26)})
assert wide.labels[-1] == "Z"
def test_choice_prompt():
q = choice()
assert q.type.prompt(q) == (
"Question: Which team?\n"
"A: billing - money\n"
"B: outage\n"
"C: other\n"
"Answer with the letter of one option only."
)
def test_choice_answer_shape():
q = choice()
answer = q.type.answer(q, [0.2, 0.7, 0.1], 0.5)
assert answer == {
"type": "choice",
"choice": "outage",
"probabilities": {"billing": 0.2, "outage": 0.7, "other": 0.1},
"confidence": 0.35,
}
@pytest.mark.parametrize(
"qid,type_name,criteria,match",
[
("", "choice", {"x": None, "y": None}, "non-empty"),
("q", "nope", {"x": None, "y": None}, "unknown question type"),
("q", "choice", ["x", "y"], "must map option names"),
("q", "noul", ["yes", "no"], "must be an object"),
("q", "noul", {"maybe": "same day"}, "must be an object"),
("q", "score", {"0": "calm", "1": "furious"}, "ordered list of levels"),
("q", "score", ["calm"], "ordered list of levels"),
],
)
def test_build_question_rejects(qid, type_name, criteria, match):
with pytest.raises(StructuredDecisionError, match=match):
build_question(qid, type_name, "", criteria, 128)
def test_one_option_choice():
q = choice(criteria={"only": None})
assert q.labels == ("A",)
assert q.type.answer(q, [1.0], 0.4)["confidence"] == 0.4
def test_option_limit():
with pytest.raises(StructuredDecisionError, match="at most 2 options"):
choice(criteria={"x": None, "y": None, "z": None}, max_options=2)
with pytest.raises(StructuredDecisionError, match="at most 26 options"):
choice(criteria={str(i): None for i in range(27)})
def test_noul_labels_and_prompt():
q = noul()
assert q.labels == ("yes", "no")
assert [a.name for a in q.options] == ["yes", "no"]
assert q.type.prompt(q) == (
"Question: Reply within the hour?\nAnswer with yes or no only."
)
described = noul(criteria={"true": "same day", "false": "later"})
assert described.type.prompt(described) == (
"Question: Reply within the hour?\n"
"yes: same day\n"
"no: later\n"
"Answer with yes or no only."
)
def test_noul_answer_shape():
q = noul()
answer = q.type.answer(q, [0.8, 0.2], 0.5)
assert answer == {
"type": "noul",
"noul": 0.8,
"probabilities": {"yes": 0.8, "no": 0.2},
"confidence": 0.4,
}
def test_score_labels_are_levels():
assert score().labels == ("0", "1", "2")
with pytest.raises(StructuredDecisionError, match="at most 10"):
score(criteria=[str(i) for i in range(11)])
def test_score_prompt():
q = score()
assert q.type.prompt(q) == (
"Question: How angry?\n"
"0: calm\n"
"1: annoyed\n"
"2: furious\n"
"Answer with the number of one level only."
)
def test_score_answer_shape():
q = score()
answer = q.type.answer(q, [0.5, 0.25, 0.25], 0.4)
assert answer == {
"type": "score",
"score": 0.75,
"legend": {"0": "calm", "1": "annoyed", "2": "furious"},
"probabilities": {"0": 0.5, "1": 0.25, "2": 0.25},
"confidence": 0.2,
}
def test_registered_type_plugs_in():
class BinaryQuestion(QuestionType):
name = "test_binary"
def parse_options(self, qid: str, criteria: Any) -> list[Option]:
return [Option("yes"), Option("no")]
def answer(
self, question: Question, probs: list[float], label_mass: float
) -> dict[str, Any]:
return {"type": self.name, "yes": probs[0]}
register_question_type(BinaryQuestion)
try:
q = build_question("ok", "test_binary", "Is it fine?", None, 128)
assert q.labels == ("A", "B")
assert q.type.answer(q, [0.9, 0.1], 1.0) == {"type": "test_binary", "yes": 0.9}
with pytest.raises(ValueError, match="already registered"):
register_question_type(BinaryQuestion)
finally:
del QUESTION_TYPES["test_binary"]
@@ -0,0 +1,222 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from vllm.config import ModelConfig
from vllm.engine.protocol import EngineClient
from vllm.entrypoints.generate.structured_decisions.api_router import (
register_structured_decisions_api_router,
)
from vllm.entrypoints.generate.structured_decisions.protocol import (
StructuredDecisionRequest,
StructuredDecisionResponse,
)
from vllm.entrypoints.generate.structured_decisions.question_types import LABELS
from vllm.entrypoints.generate.structured_decisions.serving import (
ServingStructuredDecisions,
state_text,
)
from vllm.entrypoints.generate.structured_decisions.strategies import (
NextTokenStrategy,
ReadContext,
reply_label_ids,
select_read_strategy,
)
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.entrypoints.serve.exception_handling.register import (
init_exception_handler,
)
from vllm.logprobs import Logprob
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.renderers.hf import HfRenderer
from vllm.renderers.online_renderer import OnlineRenderer
TRACE_HEADERS = {
"traceparent": "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01",
"tracestate": "vendor=value",
}
def model(architecture: str, logprobs_mode: str = "raw_logprobs") -> Any:
return SimpleNamespace(architecture=architecture, logprobs_mode=logprobs_mode)
def test_strategy_selection():
qwen = "Qwen3ForCausalLM"
assert select_read_strategy(model(qwen)) is NextTokenStrategy
assert select_read_strategy(model(qwen, "processed_logprobs")) is NextTokenStrategy
with pytest.raises(ValueError, match="does not support LlamaForCausalLM"):
select_read_strategy(model("LlamaForCausalLM"))
with pytest.raises(ValueError, match="not raw_logits"):
select_read_strategy(model(qwen, "raw_logits"))
def test_route_is_registered_by_default():
app = FastAPI()
register_structured_decisions_api_router(app)
paths = {getattr(route, "path", None) for route in app.routes}
assert "/v1/systemone" in paths
def test_unsupported_model_returns_501():
app = FastAPI()
app.state.args = SimpleNamespace(log_error_stack=False)
app.state.serving_structured_decisions = None
init_exception_handler(app)
register_structured_decisions_api_router(app)
with TestClient(app) as client:
response = client.post(
"/v1/systemone",
json={
"model": "unsupported",
"state": "x",
"questions": {"answer": {"type": "choice", "criteria": {"yes": None}}},
},
)
assert response.status_code == 501
def test_structured_state_keeps_unicode_in_prompt():
state = {"message": "Français 日本語"}
assert state_text(state) == '{"message": "Français 日本語"}'
@pytest.fixture(scope="module")
def qwen():
from vllm.tokenizers import get_tokenizer
tokenizer = get_tokenizer("Qwen/Qwen3-0.6B")
prompt_ids = tokenizer.apply_chat_template(
[{"role": "user", "content": "state"}],
add_generation_prompt=True,
enable_thinking=False,
tokenize=True,
return_dict=False,
)
return tokenizer, prompt_ids
def test_labels_start_the_reply(qwen):
tokenizer, prompt_ids = qwen
tail, ids = reply_label_ids(tokenizer, prompt_ids)
assert tokenizer.decode(tail) == "\n\n"
assert [tokenizer.decode([i]) for i in ids] == list(LABELS)
# A noul's and a score's labels are one token here too.
_, ids = reply_label_ids(tokenizer, prompt_ids, ("yes", "no", *"0123456789"))
assert len(set(ids)) == 12
# After a colon, Qwen writes ":A" as one token, so "A" is not one token.
with pytest.raises(ValueError, match="not one distinct token"):
reply_label_ids(tokenizer, tokenizer.encode("team:"))
@pytest.fixture
def serving_and_engine(qwen):
tokenizer, _ = qwen
model_config = ModelConfig(model="Qwen/Qwen3-0.6B", dtype="float32")
renderer = HfRenderer(
SimpleNamespace(
model_config=model_config,
parallel_config=SimpleNamespace(_api_process_rank=0),
),
tokenizer,
)
engine = MagicMock(spec=EngineClient)
engine.errored = False
engine.model_config = model_config
engine.renderer = renderer
engine.input_processor = MagicMock()
online_renderer = OnlineRenderer(
model_config,
renderer,
request_logger=None,
chat_template=None,
chat_template_content_format="auto",
)
async def generate(prompt, params, request_id, **kwargs):
label_ids = params.logprob_token_ids
yield RequestOutput(
request_id=request_id,
prompt=None,
prompt_token_ids=prompt["prompt_token_ids"],
prompt_logprobs=None,
outputs=[
CompletionOutput(
index=0,
text="A",
token_ids=[label_ids[0]],
cumulative_logprob=None,
logprobs=[{token_id: Logprob(-1.0) for token_id in label_ids}],
finish_reason="length",
)
],
finished=True,
)
engine.generate.side_effect = generate
strategy = NextTokenStrategy(ReadContext(engine, online_renderer, None, "auto", {}))
models = OpenAIServingModels(
engine, [BaseModelPath(name=model_config.model, model_path=model_config.model)]
)
yield ServingStructuredDecisions(models, strategy), engine
renderer.shutdown()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"cache_salt,tracing_enabled,request_headers",
[
("tenant-a", True, {"authorization": "Bearer test", **TRACE_HEADERS}),
("tenant-b", False, {"authorization": "Bearer test", **TRACE_HEADERS}),
(None, True, {"authorization": "Bearer test", **TRACE_HEADERS}),
(None, True, {}),
("tenant-direct", True, None),
],
)
async def test_request_metadata_reaches_every_question(
serving_and_engine, cache_salt, tracing_enabled, request_headers
):
serving, engine = serving_and_engine
engine.is_tracing_enabled.return_value = tracing_enabled
raw_request = None
if request_headers is not None:
raw_request = Request(
{
"type": "http",
"headers": [
(k.encode(), v.encode()) for k, v in request_headers.items()
],
}
)
request = StructuredDecisionRequest(
state={"team": "billing", "language": "English"},
questions={
"team": {
"type": "choice",
"instructions": "Which team does the message name?",
"criteria": {"billing": "payments", "shipping": "deliveries"},
},
"lang": {
"type": "choice",
"instructions": "Which language does the message name?",
"criteria": {"English": "English text", "French": "French text"},
},
},
cache_salt=cache_salt,
)
response = await serving.create_decision(request, raw_request)
assert isinstance(response, StructuredDecisionResponse)
assert engine.generate.call_count == 2
for call in engine.generate.call_args_list:
assert call.args[0].get("cache_salt") == cache_salt
assert call.kwargs["trace_headers"] == (
TRACE_HEADERS if tracing_enabled and request_headers else None
)
@@ -0,0 +1,260 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import requests
from tests.utils import RemoteOpenAIServer
MODEL_NAME = "Qwen/Qwen3-0.6B"
@pytest.fixture(scope="module")
def server():
args = [
"--dtype",
"bfloat16",
"--max-model-len",
"1024",
"--enforce-eager",
"--max-num-seqs",
"32",
"--enable-prefix-caching",
]
with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
yield remote_server
def post(server, body):
return requests.post(server.url_for("v1/systemone"), json=body)
def choice(instructions, *names):
return {
"type": "choice",
"instructions": instructions,
"criteria": dict.fromkeys(names),
}
COPY = {
"team": choice(
"Which team does the message name?", "billing", "shipping", "security"
),
"lang": choice("Which language does the message name?", "English", "French"),
}
def test_choice_decision(server):
response = post(
server,
{
"model": MODEL_NAME,
"state": {"team": "billing", "language": "French"},
"questions": COPY,
"chat_template_kwargs": {"enable_thinking": False},
},
)
assert response.status_code == 200, response.text
body = response.json()
assert body["object"] == "structured_decision"
assert list(body["answers"]) == ["team", "lang"]
team = body["answers"]["team"]
assert team["type"] == "choice"
assert set(team["probabilities"]) == {"billing", "shipping", "security"}
assert sum(team["probabilities"].values()) == pytest.approx(1.0, abs=1e-4)
assert team["confidence"] == pytest.approx(
max(team["probabilities"].values()) * body["diagnostics"]["team"]["label_mass"]
)
for diag in body["diagnostics"].values():
assert 0.0 < diag["label_mass"] <= 1.0 + 1e-6
assert body["usage"]["output_tokens"] == 2
assert body["usage"]["input_tokens"] > 0
def test_one_option_choice(server):
response = post(
server,
{
"model": MODEL_NAME,
"state": "Team: billing.",
"questions": {
"team": choice("Which team does the message name?", "billing")
},
"chat_template_kwargs": {"enable_thinking": False},
},
)
assert response.status_code == 200, response.text
body = response.json()
team = body["answers"]["team"]
assert team["choice"] == "billing"
assert team["probabilities"] == {"billing": 1.0}
assert team["confidence"] == pytest.approx(
body["diagnostics"]["team"]["label_mass"]
)
def test_one_option_coin_flip(server):
# A fair coin with only "heads" allowed. The answer is forced, so its
# confidence must come from the model's probability of the label.
response = post(
server,
{
"model": MODEL_NAME,
"state": "I flip a fair coin.",
"questions": {"coin": choice("How did the coin land?", "heads")},
"chat_template_kwargs": {"enable_thinking": False},
},
)
assert response.status_code == 200, response.text
body = response.json()
coin = body["answers"]["coin"]
assert coin["probabilities"] == {"heads": 1.0}
assert coin["confidence"] == pytest.approx(
body["diagnostics"]["coin"]["label_mass"]
)
@pytest.mark.parametrize(
"state,questions,expected",
[
(
{"team": "billing", "language": "French"},
COPY,
{"team": "billing", "lang": "French"},
),
(
"My card was charged twice for one order.",
{
"card": choice("Does the message mention a card?", "yes", "no"),
"mood": choice("How does the customer feel?", "happy", "angry"),
},
{"card": "yes", "mood": "angry"},
),
(
"Hello.",
{
"sky": choice(
"What color is the sky on a clear day?", "blue", "green", "red"
)
},
{"sky": "blue"},
),
],
)
def test_single_read_answers(server, state, questions, expected):
response = post(
server,
{
"model": MODEL_NAME,
"state": state,
"questions": questions,
"chat_template_kwargs": {"enable_thinking": False},
},
)
assert response.status_code == 200, response.text
answers = response.json()["answers"]
assert {qid: a["choice"] for qid, a in answers.items()} == expected
def test_option_limit(server):
body = {
"model": MODEL_NAME,
"state": "Pick option 7.",
"chat_template_kwargs": {"enable_thinking": False},
}
ok = post(
server, {**body, "questions": {"n": choice("Which?", *map(str, range(26)))}}
)
assert ok.status_code == 200, ok.text
assert len(ok.json()["answers"]["n"]["probabilities"]) == 26
over = post(
server, {**body, "questions": {"n": choice("Which?", *map(str, range(27)))}}
)
assert over.status_code == 400
assert "at most 26 options" in over.json()["error"]["message"]
def test_thinking_is_refused(server):
response = post(
server,
{
"model": MODEL_NAME,
"state": "x",
"questions": {"q": choice("Which?", "a", "b")},
"chat_template_kwargs": {"enable_thinking": True},
},
)
assert response.status_code == 400
assert "thinking must be off" in response.json()["error"]["message"]
def test_noul_and_score(server):
response = post(
server,
{
"model": MODEL_NAME,
"state": {"ticket": "My card was charged twice for one order."},
"questions": {
"urgent": {"type": "noul", "instructions": "Is money moving?"},
"tone": {
"type": "score",
"instructions": "How upset is the customer?",
"criteria": ["calm", "annoyed", "furious"],
},
},
"chat_template_kwargs": {"enable_thinking": False},
},
)
assert response.status_code == 200, response.text
body = response.json()
urgent = body["answers"]["urgent"]
assert urgent["type"] == "noul"
assert set(urgent["probabilities"]) == {"yes", "no"}
assert urgent["probabilities"]["yes"] + urgent["probabilities"]["no"] == (
pytest.approx(1.0, abs=1e-4)
)
assert urgent["noul"] == urgent["probabilities"]["yes"]
assert urgent["confidence"] == pytest.approx(
max(urgent["probabilities"].values())
* body["diagnostics"]["urgent"]["label_mass"]
)
tone = body["answers"]["tone"]
assert tone["type"] == "score"
assert tone["legend"] == {"0": "calm", "1": "annoyed", "2": "furious"}
assert set(tone["probabilities"]) == {"0", "1", "2"}
assert sum(tone["probabilities"].values()) == pytest.approx(1.0, abs=1e-4)
assert tone["score"] == pytest.approx(
sum(i * p for i, p in enumerate(tone["probabilities"].values()))
)
assert 0 <= tone["score"] <= 2
assert body["usage"]["output_tokens"] == 2
@pytest.mark.parametrize(
"questions,match",
[
(
{
"q": {
"type": "choice",
"criteria": {"a": None, "b": None},
"depends_on": ["x"],
}
},
"unknown field(s)",
),
(
{
f"q{i}": {"type": "choice", "criteria": {"a": None, "b": None}}
for i in range(65)
},
"at most 64",
),
({"q": {"type": "noul", "criteria": ["yes", "no"]}}, "must be an object"),
({"q": {"type": "score", "criteria": ["calm"]}}, "ordered list of levels"),
],
)
def test_validation_errors(server, questions, match):
response = post(server, {"model": MODEL_NAME, "state": "x", "questions": questions})
assert response.status_code == 400
assert match in response.json()["error"]["message"]
@@ -1,14 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Spawn worker targets kept free of heavy imports.
``multiprocessing`` with the ``spawn`` start method re-imports the module that
defines a process target in the child. Housing these stubs in a stdlib-only
module keeps child startup fast and deterministic, instead of paying a multi-
second ``import vllm`` before the child can run.
"""
def exit_before_report_worker(listen_address, sock, args, client_config=None):
"""Exit immediately without touching ``actual_address_pipe``."""
return
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import multiprocessing
import os
import socket
import threading
import time
@@ -11,14 +12,10 @@ from unittest.mock import patch
import pytest
import zmq
from tests.entrypoints.launchers.api_server._api_server_spawn_workers import (
exit_before_report_worker,
)
from vllm.utils.network_utils import make_zmq_socket, split_zmq_path
from vllm.utils.network_utils import make_zmq_listener, make_zmq_socket
from vllm.v1.engine.admission_control import SharedAdmissionStats
from vllm.v1.utils import (
APIServerProcessManager,
get_engine_client_zmq_addr,
wait_for_completion_or_failure,
)
@@ -46,36 +43,30 @@ def update_admission_stats_worker(listen_address, sock, args, client_config):
args.results.put(stats.get_num_requests())
# Module-level stub for the gather_actual_addresses test. Must be
# importable by `multiprocessing.spawn` (no closures, no nesting).
def defer_addresses_stub_worker(listen_address, sock, args, client_config):
"""Bind ROUTER/PULL with a kernel-assigned port, report the actual
endpoints back via the pipe, then exit."""
def _adopt_zmq_listener_worker(listen_address, sock, args, client_config):
ctx = zmq.Context()
router = make_zmq_socket(
ctx,
client_config["input_address"],
zmq.ROUTER,
bind=True,
listener=client_config["input_listener"],
)
pull = make_zmq_socket(
ctx,
client_config["output_address"],
zmq.PULL,
bind=True,
listener=client_config["output_listener"],
)
try:
in_sock = make_zmq_socket(
ctx, client_config["input_address"], zmq.ROUTER, bind=True
)
out_sock = make_zmq_socket(
ctx, client_config["output_address"], zmq.PULL, bind=True
)
try:
pipe = client_config["actual_address_pipe"]
try:
pipe.send(
{
"input_address": in_sock.getsockopt(zmq.LAST_ENDPOINT).decode(),
"output_address": out_sock.getsockopt(
zmq.LAST_ENDPOINT
).decode(),
}
)
finally:
pipe.close()
finally:
in_sock.close(linger=0)
out_sock.close(linger=0)
identity, payload = router.recv_multipart()
assert payload == b"input"
assert pull.recv() == b"output"
router.send_multipart([identity, b"ok"])
finally:
router.close(linger=0)
pull.close(linger=0)
ctx.term()
@@ -89,15 +80,11 @@ def api_server_args():
"sock": sock,
"args": "test_args", # Simple string to avoid pickling issues
"num_servers": 3,
"input_addresses": [
"tcp://127.0.0.1:5001",
"tcp://127.0.0.1:5002",
"tcp://127.0.0.1:5003",
"input_listeners": [
make_zmq_listener("tcp://127.0.0.1:0", zmq.ROUTER) for _ in range(3)
],
"output_addresses": [
"tcp://127.0.0.1:6001",
"tcp://127.0.0.1:6002",
"tcp://127.0.0.1:6003",
"output_listeners": [
make_zmq_listener("tcp://127.0.0.1:0", zmq.PULL) for _ in range(3)
],
"stats_update_address": "tcp://127.0.0.1:7000",
}
@@ -120,6 +107,13 @@ def test_api_server_process_manager_init(api_server_args, with_stats_update):
try:
# Verify the manager was initialized correctly
assert len(manager.processes) == 3
assert all(
listener.socket.fileno() == -1
for listener in (
*args["input_listeners"],
*args["output_listeners"],
)
)
# Verify all processes are running
for proc in manager.processes:
@@ -145,6 +139,70 @@ def test_api_server_process_manager_init(api_server_args, with_stats_update):
assert not proc.is_alive()
def _assert_endpoint_reserved(address: str) -> None:
"""A competing bind must fail while the endpoint has a listener owner."""
if address.startswith("ipc://"):
competitor = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
bind_address: str | tuple[str, int] = address.removeprefix("ipc://")
else:
competitor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
bind_address = ("127.0.0.1", int(address.rsplit(":", 1)[1]))
with competitor, pytest.raises(OSError, match="Address already in use"):
competitor.bind(bind_address)
@pytest.mark.parametrize("scheme", ["tcp", "ipc"])
def test_api_server_child_adopts_inherited_zmq_listeners(tmp_path, scheme):
if scheme == "tcp":
input_path = output_path = "tcp://127.0.0.1:0"
else:
input_path = f"ipc://{tmp_path}/input.sock"
output_path = f"ipc://{tmp_path}/output.sock"
input_listener = make_zmq_listener(input_path, zmq.ROUTER)
output_listener = make_zmq_listener(output_path, zmq.PULL)
input_address = input_listener.address
output_address = output_listener.address
# The supervisor reserves each endpoint as soon as it allocates it.
_assert_endpoint_reserved(input_address)
_assert_endpoint_reserved(output_address)
http_socket = socket.socket()
manager = APIServerProcessManager(
target_server_fn=_adopt_zmq_listener_worker,
listen_address="localhost:8000",
sock=http_socket,
args="test_args",
num_servers=1,
input_listeners=[input_listener],
output_listeners=[output_listener],
)
ctx = zmq.Context()
dealer = make_zmq_socket(
ctx, input_address, zmq.DEALER, bind=False, identity=b"test"
)
push = make_zmq_socket(ctx, output_address, zmq.PUSH, bind=False)
dealer.setsockopt(zmq.RCVTIMEO, 30_000)
try:
assert input_listener.socket.fileno() == -1
assert output_listener.socket.fileno() == -1
# After the parent closes its copies, the child's inherited descriptors
# keep both endpoints reserved; closing must not unlink IPC paths.
assert manager.processes[0].is_alive()
_assert_endpoint_reserved(input_address)
_assert_endpoint_reserved(output_address)
dealer.send(b"input")
push.send(b"output")
assert dealer.recv() == b"ok"
manager.processes[0].join(timeout=10)
assert manager.processes[0].exitcode == 0
finally:
manager.shutdown()
dealer.close(linger=0)
push.close(linger=0)
ctx.term()
http_socket.close()
@pytest.mark.skip_global_cleanup
def test_api_server_processes_share_admission_stats(api_server_args):
args = api_server_args.copy()
@@ -354,96 +412,7 @@ def test_external_process_monitoring(api_server_args):
WORKER_RUNTIME_SECONDS = prev_worker_runtime
@pytest.mark.timeout(60)
def test_gather_actual_addresses_end_to_end():
"""Each child binds ROUTER/PULL with a kernel-picked port and reports
the bound endpoints back via its per-child pipe; the manager surfaces
them via :py:meth:`gather_actual_addresses`."""
host = "127.0.0.1"
num_servers = 4
placeholder_inputs = [
get_engine_client_zmq_addr(local_only=False, host=host)
for _ in range(num_servers)
]
placeholder_outputs = [
get_engine_client_zmq_addr(local_only=False, host=host)
for _ in range(num_servers)
]
for addr in placeholder_inputs + placeholder_outputs:
assert addr == f"tcp://{host}:0", addr
sock = socket.socket()
manager = APIServerProcessManager(
listen_address=f"tcp://{host}:0",
sock=sock,
args="test_args",
num_servers=num_servers,
input_addresses=placeholder_inputs,
output_addresses=placeholder_outputs,
target_server_fn=defer_addresses_stub_worker,
)
try:
assert len(manager.processes) == num_servers
actual_inputs, actual_outputs = manager.gather_actual_addresses(timeout=15.0)
finally:
manager.shutdown()
time.sleep(0.2)
sock.close()
assert len(actual_inputs) == num_servers
assert len(actual_outputs) == num_servers
for addr in actual_inputs + actual_outputs:
scheme, parsed_host, port = split_zmq_path(addr)
assert scheme == "tcp", addr
assert parsed_host == host, addr
assert port and int(port) > 0, addr
all_addrs = actual_inputs + actual_outputs
assert len(set(all_addrs)) == len(all_addrs), all_addrs
@pytest.mark.timeout(30)
def test_gather_actual_addresses_child_crash_before_report():
"""A child that exits before sending its endpoints must surface a
clear ``RuntimeError`` rather than hang or return ``None`` slots."""
host = "127.0.0.1"
num_servers = 2
placeholder_inputs = [
get_engine_client_zmq_addr(local_only=False, host=host)
for _ in range(num_servers)
]
placeholder_outputs = [
get_engine_client_zmq_addr(local_only=False, host=host)
for _ in range(num_servers)
]
sock = socket.socket()
manager = APIServerProcessManager(
listen_address=f"tcp://{host}:0",
sock=sock,
args="test_args",
num_servers=num_servers,
input_addresses=placeholder_inputs,
output_addresses=placeholder_outputs,
# exit_before_report_worker exits without touching
# ``actual_address_pipe`` — simulates a child that dies before
# reporting its bound addresses.
target_server_fn=exit_before_report_worker,
)
try:
# Sentinel-first vs pipe-EOF-first both produce "reporting".
with pytest.raises(RuntimeError, match="reporting"):
manager.gather_actual_addresses(timeout=10.0)
finally:
manager.shutdown()
time.sleep(0.2)
sock.close()
def test_rust_frontend_launch_log_redacts_credentials(monkeypatch, caplog):
def test_rust_frontend_launch_log_redacts_credentials(monkeypatch):
"""The Rust frontend command carries every non-default arg as JSON.
Credentials must not reach the log line."""
import subprocess as subprocess_mod
@@ -469,15 +438,17 @@ def test_rust_frontend_launch_log_redacts_credentials(monkeypatch, caplog):
return 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
input_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.ROUTER)
output_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.PULL)
try:
monkeypatch.setattr(subprocess_mod, "Popen", lambda *a, **kw: _FakeProc())
with caplog.at_level("INFO", logger="vllm.v1.utils"):
with patch("vllm.v1.utils.logger.info") as log_info:
RustFrontendProcessManager(
binary_path="/nonexistent/vllm-rs",
sock=sock,
args=args,
input_address="ipc:///tmp/in",
output_address="ipc:///tmp/out",
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
@@ -485,11 +456,13 @@ def test_rust_frontend_launch_log_redacts_credentials(monkeypatch, caplog):
finally:
sock.close()
message = caplog.text
log_format, *log_args = log_info.call_args.args
message = log_format % tuple(log_args)
assert "Launching Rust frontend:" in message
assert hf_token not in message
assert api_key not in message
assert '"hf_token": "***"' in message
assert '"api_key": "***"' in message
def test_rust_frontend_uses_config_model_as_model_tag(monkeypatch, caplog, tmp_path):
@@ -519,6 +492,8 @@ def test_rust_frontend_uses_config_model_as_model_tag(monkeypatch, caplog, tmp_p
return 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
input_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.ROUTER)
output_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.PULL)
try:
monkeypatch.setattr(subprocess_mod, "Popen", lambda *a, **kw: _FakeProc())
with caplog.at_level("INFO", logger="vllm.v1.utils"):
@@ -526,8 +501,8 @@ def test_rust_frontend_uses_config_model_as_model_tag(monkeypatch, caplog, tmp_p
binary_path="/nonexistent/vllm-rs",
sock=sock,
args=args,
input_address="ipc:///tmp/in",
output_address="ipc:///tmp/out",
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
@@ -568,14 +543,18 @@ def test_rust_frontend_inherits_grpc_listener(monkeypatch):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
grpc_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
input_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.ROUTER)
output_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.PULL)
input_fd = input_listener.socket.fileno()
output_fd = output_listener.socket.fileno()
try:
monkeypatch.setattr(subprocess_mod, "Popen", fake_popen)
RustFrontendProcessManager(
binary_path="/nonexistent/vllm-rs",
sock=sock,
args=args,
input_address="ipc:///tmp/in",
output_address="ipc:///tmp/out",
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
@@ -585,7 +564,44 @@ def test_rust_frontend_inherits_grpc_listener(monkeypatch):
grpc_fd = grpc_sock.fileno()
flag_index = cmd.index("--grpc-listen-fd")
assert cmd[flag_index + 1] == str(grpc_fd)
assert list(kwargs["pass_fds"]) == [sock.fileno(), grpc_fd]
assert list(kwargs["pass_fds"]) == [
sock.fileno(),
input_fd,
output_fd,
grpc_fd,
]
finally:
sock.close()
grpc_sock.close()
def test_rust_frontend_spawn_failure_cleans_up_listeners(tmp_path):
"""No child owns the listeners when Popen fails, so the parent removes them."""
from vllm.entrypoints.launchers.cli_args import make_arg_parser
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.v1.utils import RustFrontendProcessManager
args = make_arg_parser(FlexibleArgumentParser()).parse_args(
["--model", "org/model"]
)
input_listener = make_zmq_listener(f"ipc://{tmp_path}/input.sock", zmq.ROUTER)
output_listener = make_zmq_listener(f"ipc://{tmp_path}/output.sock", zmq.PULL)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
with pytest.raises(FileNotFoundError):
RustFrontendProcessManager(
binary_path=str(tmp_path / "missing-vllm-rs"),
sock=sock,
args=args,
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
)
finally:
sock.close()
for listener in (input_listener, output_listener):
assert listener.socket.fileno() == -1
assert not os.path.exists(listener.address.removeprefix("ipc://"))
@@ -0,0 +1,84 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from argparse import Namespace
import pytest
from starlette.datastructures import State
import vllm.entrypoints.launchers.render.app_state as app_state_mod
from vllm.config import ModelConfig, VllmConfig
from vllm.entrypoints.launchers.cli_args import make_arg_parser
from vllm.utils.argparse_utils import FlexibleArgumentParser
class _CaptureKwargs:
"""Stands in for OnlineRenderer/OnlineDerenderer; records init kwargs."""
captured: list[dict]
def __init__(self, **kwargs):
type(self).captured.append(kwargs)
def warmup(self):
pass
def _render_cli_args(*argv: str) -> Namespace:
"""Parse ``argv`` the way ``vllm launch render`` does, so new serve flags
carry their defaults instead of needing a hand-maintained ``Namespace``."""
args = make_arg_parser(FlexibleArgumentParser()).parse_args(list(argv))
if args.model_tag is not None:
args.model = args.model_tag
return args
@pytest.mark.asyncio
async def test_render_app_state_uses_config_resolved_reasoning_parser(monkeypatch):
"""gpt_oss defaults its reasoning parser through verify_and_update_config;
the render server must pick up that resolved value like the main API
server does, otherwise harmony markup leaks unparsed into derender output.
"""
model_config = ModelConfig("openai/gpt-oss-20b")
vllm_config = VllmConfig(model_config=model_config)
assert vllm_config.structured_outputs_config.reasoning_parser == "openai_gptoss"
class _Renderer(_CaptureKwargs):
captured = []
class _Derenderer(_CaptureKwargs):
captured = []
async def _noop_async(*args, **kwargs):
return None
monkeypatch.setattr(app_state_mod, "renderer_from_config", lambda cfg: object())
monkeypatch.setattr(app_state_mod, "OnlineRenderer", _Renderer)
monkeypatch.setattr(app_state_mod, "OnlineDerenderer", _Derenderer)
monkeypatch.setattr(app_state_mod, "ServingTokenization", lambda *a, **kw: object())
monkeypatch.setattr(app_state_mod, "init_render_state", lambda *a, **kw: None)
monkeypatch.setattr(app_state_mod, "init_endpoint_plugins_state", _noop_async)
args = _render_cli_args("openai/gpt-oss-20b")
await app_state_mod.init_render_app_state(vllm_config, State(), args)
assert _Renderer.captured[0]["reasoning_parser"] == "openai_gptoss"
assert _Derenderer.captured[0]["reasoning_parser"] == "openai_gptoss"
def test_explicit_reasoning_parser_flag_wins_over_model_default():
"""An explicit --reasoning-parser must survive VllmConfig construction
for models that define their own default (gpt_oss); the default only
applies when the resolved value is empty."""
from vllm.engine.arg_utils import AsyncEngineArgs
engine_args = AsyncEngineArgs(
model="openai/gpt-oss-20b", reasoning_parser="deepseek_r1"
)
model_config = engine_args.create_model_config()
vllm_config = VllmConfig(
model_config=model_config,
structured_outputs_config=engine_args.create_structured_outputs_config(),
)
assert vllm_config.structured_outputs_config.reasoning_parser == "deepseek_r1"
@@ -0,0 +1,218 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""NoSignalServer(peer_loads=...): API workers sharing one listening socket
accept each connection on the worker with the fewest open connections."""
import asyncio
import datetime
import multiprocessing
import os
import socket
import ssl
from collections import Counter
import pytest
import uvicorn
import uvloop
from vllm.entrypoints.launchers.launcher import NoSignalServer
TIMEOUT_S = 30
def _bound_socket() -> socket.socket:
# Like setup_server: bound, not yet listening.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 0))
return sock
def _app(hold_s: float = 0.0):
pid = str(os.getpid()).encode()
async def app(scope, receive, send):
if scope["type"] == "lifespan":
while (await receive())["type"] != "lifespan.shutdown":
await send({"type": "lifespan.startup.complete"})
await send({"type": "lifespan.shutdown.complete"})
return
await asyncio.sleep(hold_s)
headers = [(b"content-length", str(len(pid)).encode())]
await send({"type": "http.response.start", "status": 200, "headers": headers})
await send({"type": "http.response.body", "body": pid})
return app
async def _get(port: int, requests: int = 1, ssl_ctx=None) -> list[bytes]:
"""``requests`` requests on one keep-alive connection; returns the bodies."""
reader, writer = await asyncio.open_connection("127.0.0.1", port, ssl=ssl_ctx)
bodies = []
for _ in range(requests):
writer.write(b"GET / HTTP/1.1\r\nHost: t\r\n\r\n")
head = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), TIMEOUT_S)
assert head.startswith(b"HTTP/1.1 200")
length = int(head.split(b"content-length: ")[1].split(b"\r\n")[0])
bodies.append(await asyncio.wait_for(reader.readexactly(length), TIMEOUT_S))
writer.close()
return bodies
async def _serve(sock, requests, loads=None, **config_kwargs):
config = uvicorn.Config(_app(), lifespan="on", log_level="warning", **config_kwargs)
loads = loads if loads is not None else [0]
server = NoSignalServer(config, peer_loads=(loads, 0))
task = asyncio.create_task(server.serve(sockets=[sock]))
while not server.started:
assert not task.done(), task.result()
await asyncio.sleep(0.01)
try:
return await requests(sock.getsockname()[1], server)
finally:
server.should_exit = True
await asyncio.wait_for(task, TIMEOUT_S)
# The listener is closed, nothing is left accepting, and peers no
# longer see this worker as a target.
assert sock.fileno() == -1
assert not server._accept_tasks
assert loads[0] == 2**31 - 1
def _run(coro, loop_impl):
return uvloop.run(coro) if loop_impl == "uvloop" else asyncio.run(coro)
@pytest.mark.parametrize("loop_impl", ["asyncio", "uvloop"])
def test_requests_and_keep_alive_served(loop_impl):
async def requests(port, server):
return await _get(port), await _get(port, requests=3)
one, three = _run(_serve(_bound_socket(), requests), loop_impl)
assert one == [str(os.getpid()).encode()]
assert len(three) == 3
def _self_signed(tmp_path):
x509 = pytest.importorskip("cryptography.x509")
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")])
now = datetime.datetime.now(datetime.UTC)
cert = (
x509.CertificateBuilder()
.subject_name(name)
.issuer_name(name)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=1))
.not_valid_after(now + datetime.timedelta(hours=1))
.sign(key, hashes.SHA256())
)
keyfile, certfile = tmp_path / "key.pem", tmp_path / "cert.pem"
keyfile.write_bytes(
key.private_bytes(
serialization.Encoding.PEM,
serialization.PrivateFormat.PKCS8,
serialization.NoEncryption(),
)
)
certfile.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
return str(keyfile), str(certfile)
def test_tls_handshake_failure_keeps_serving(tmp_path):
keyfile, certfile = _self_signed(tmp_path)
client_ctx = ssl.create_default_context()
client_ctx.check_hostname = False
client_ctx.verify_mode = ssl.CERT_NONE
async def requests(port, server):
# A plain-text client fails the handshake; the next TLS client is served.
reader, writer = await asyncio.open_connection("127.0.0.1", port)
writer.write(b"GET / HTTP/1.1\r\nHost: t\r\n\r\n")
await asyncio.wait_for(reader.read(), TIMEOUT_S)
writer.close()
return await _get(port, ssl_ctx=client_ctx)
bodies = uvloop.run(
_serve(_bound_socket(), requests, ssl_keyfile=keyfile, ssl_certfile=certfile)
)
assert bodies == [str(os.getpid()).encode()]
def test_busier_worker_still_serves():
# This worker is index 0; peer 1 claims no connections but never accepts.
loads = [0, 0]
async def requests(port, server):
reader, writer = await asyncio.open_connection("127.0.0.1", port)
bodies = await _get(port)
assert loads[0] >= 1 # the held connection was published
writer.close()
return bodies
assert uvloop.run(_serve(_bound_socket(), requests, loads)) == [
str(os.getpid()).encode()
]
def _worker(sock, loads, index, ready, stop):
async def main():
config = uvicorn.Config(_app(hold_s=1), lifespan="on", log_level="warning")
server = NoSignalServer(config, peer_loads=(loads, index))
task = asyncio.create_task(server.serve(sockets=[sock]))
while not server.started:
await asyncio.sleep(0.01)
ready.release()
await asyncio.get_running_loop().run_in_executor(None, stop.wait)
server.should_exit = True
await task
# API workers run on uvloop, whose own server accepts a whole burst at once.
uvloop.run(main())
@pytest.mark.skipif((os.cpu_count() or 1) < 8, reason="needs idle cores per worker")
@pytest.mark.parametrize("arrival_s", [0, 1])
def test_connections_balanced_over_workers(arrival_s):
"""Both a burst and a steady stream of connections end up balanced; with
the event loop's own server one worker takes most of either."""
workers, connections = 4, 400
sock = _bound_socket()
ctx = multiprocessing.get_context("spawn")
ready, stop = ctx.Semaphore(0), ctx.Event()
loads = ctx.RawArray("i", workers)
procs = [
ctx.Process(target=_worker, args=(sock, loads, i, ready, stop))
for i in range(workers)
]
for p in procs:
p.start()
try:
for _ in range(workers):
assert ready.acquire(timeout=120)
async def get_after(delay):
await asyncio.sleep(delay)
return await _get(sock.getsockname()[1])
async def arrive():
delays = [arrival_s * i / connections for i in range(connections)]
results = await asyncio.gather(*(get_after(d) for d in delays))
return Counter(body for (body,) in results)
counts = uvloop.run(arrive())
assert sum(counts.values()) == connections
# Fair share is 100.
assert max(counts.values()) <= 5 * connections // (4 * workers), counts
finally:
stop.set()
for p in procs:
p.join(30)
if p.is_alive():
p.kill()
sock.close()
+11 -5
View File
@@ -242,7 +242,7 @@ def test_rust_grpc_port_requires_serve_subcommand(monkeypatch):
validate_parsed_serve_args(args)
def test_enable_auto_choice_passes_without_tool_call_parser(serve_parser):
def test_enable_auto_choice_fails_without_tool_call_parser(serve_parser):
"""Ensure validation fails if tool choice is enabled with no call parser."""
# If we enable-auto-tool-choice, explode with no tool-call-parser
args = serve_parser.parse_args(args=["--enable-auto-tool-choice"])
@@ -262,17 +262,23 @@ def test_enable_auto_choice_passes_with_tool_call_parser(serve_parser):
validate_parsed_serve_args(args)
def test_enable_auto_choice_fails_with_enable_reasoning(serve_parser):
"""Ensure validation fails if reasoning is enabled with auto tool choice."""
def test_auto_tool_choice_with_reasoning_parser_passes(serve_parser):
"""Auto tool choice combined with a reasoning parser is supported.
See docs/features/tool_calling.md, which documents using
``--tool-call-parser`` together with ``--reasoning-parser``. This
combination must pass validation as long as a tool call parser is set.
"""
args = serve_parser.parse_args(
args=[
"--enable-auto-tool-choice",
"--tool-call-parser",
"mistral",
"--reasoning-parser",
"deepseek_r1",
]
)
with pytest.raises(TypeError):
validate_parsed_serve_args(args)
validate_parsed_serve_args(args)
def test_passes_with_reasoning_parser(serve_parser):
@@ -630,7 +630,7 @@ async def _poll_until_api_server_running(
timeout=request_timeout,
):
return
except (aiohttp.ClientError, asyncio.TimeoutError) as exc:
except (TimeoutError, aiohttp.ClientError) as exc:
last_exc = exc
print("Test detected not started yet, sleeping for 1s")
remaining_s = deadline - time.monotonic()
+22 -7
View File
@@ -1071,17 +1071,32 @@ def _make_aiohttp_put_session(status: int = 200, body_text: str = ""):
@pytest.mark.asyncio
async def test_upload_data_uploads_once_on_success():
"""A successful upload must not be retried (regression guard)."""
session = _make_aiohttp_put_session(status=200)
with patch(
"vllm.entrypoints.launchers.run_batch.aiohttp.ClientSession",
return_value=session,
@pytest.mark.parametrize("status", [200, 201, 204])
@pytest.mark.parametrize("from_file", [False, True])
async def test_upload_data_uploads_once_on_success(status, from_file, tmp_path):
"""Successful PUT responses must not retry either upload path."""
session = _make_aiohttp_put_session(status=status)
data_or_file = "payload"
if from_file:
path = tmp_path / "output.jsonl"
path.write_text(data_or_file, encoding="utf-8")
data_or_file = str(path)
with (
patch(
"vllm.entrypoints.launchers.run_batch.aiohttp.ClientSession",
return_value=session,
),
patch(
"vllm.entrypoints.launchers.run_batch.asyncio.sleep",
new_callable=AsyncMock,
) as sleep,
):
await upload_data(
"https://example.com/output.jsonl", "payload", from_file=False
"https://example.com/output.jsonl", data_or_file, from_file=from_file
)
assert session.put.call_count == 1
sleep.assert_not_awaited()
@pytest.mark.asyncio
+3 -3
View File
@@ -285,7 +285,7 @@ async def test_wait_timeout_completes_requests():
sigterm_sent.set()
await asyncio.wait_for(request_task, timeout=_SHUTDOWN_DETECTION_TIMEOUT)
except asyncio.TimeoutError:
except TimeoutError:
pass
finally:
state.stop_requesting = True
@@ -463,7 +463,7 @@ async def test_abort_timeout_fails_inflight_requests():
try:
await asyncio.wait_for(request_task, timeout=5)
except asyncio.TimeoutError:
except TimeoutError:
pass
finally:
state.stop_requesting = True
@@ -592,7 +592,7 @@ async def test_multi_api_server_shutdown():
try:
await asyncio.wait_for(request_task, timeout=_SHUTDOWN_DETECTION_TIMEOUT)
except asyncio.TimeoutError:
except TimeoutError:
pass
finally:
state.stop_requesting = True
@@ -212,7 +212,7 @@ def test_preprocess_cmpl_applies_mm_processor_kwargs_to_renderer(
llm.renderer = renderer
monkeypatch.setattr(
"vllm.entrypoints.offline_utils.parse_model_prompt",
"vllm.entrypoints.common.offline.parse_model_prompt",
lambda _model_config, parsed_prompt: parsed_prompt,
)
@@ -246,7 +246,7 @@ def test_preprocess_cmpl_keeps_prompt_mm_processor_kwargs_when_no_override(
llm.renderer = renderer
monkeypatch.setattr(
"vllm.entrypoints.offline_utils.parse_model_prompt",
"vllm.entrypoints.common.offline.parse_model_prompt",
lambda _model_config, parsed_prompt: parsed_prompt,
)
@@ -10,6 +10,7 @@ import pytest
from tests.entrypoints.openai.chat_completion.test_serving_chat import (
BASE_MODEL_PATHS,
CHAT_TEMPLATE,
MockHFConfig,
MockModelConfig,
_build_renderer,
@@ -24,10 +25,13 @@ from vllm.entrypoints.openai.chat_completion.batch_serving import (
)
from vllm.entrypoints.openai.chat_completion.protocol import (
BatchChatCompletionRequest,
ChatCompletionRequest,
)
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.exceptions import VLLMValidationError
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.reasoning import ReasoningParserManager
from vllm.renderers.online_renderer import OnlineRenderer
from vllm.v1.engine.async_llm import AsyncLLM
@@ -454,3 +458,101 @@ async def test_batched_parser_receives_each_prompt_prefix() -> None:
)
assert prefixes == [[1], [2]]
REASONING_PARSER = "kimi_k3"
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_batched_reasoning_wiring_matches_single_chat() -> None:
"""`/v1/chat/completions/batch` must hand the engine the same reasoning
wiring as `/v1/chat/completions`.
Both `reasoning_ended` and `reasoning_parser_kwargs` are carried on the
request into `EngineCoreRequest`, where
`StructuredOutputManager._get_reasoner()` rebuilds the request-local
reasoning parser from the forwarded `chat_template_kwargs` -- "so the
structured-output gate observes the same template kwargs used by the
frontend". A divergence makes a template-kwarg-driven parser fall back to
its default (`thinking` on) for a request that disabled thinking, so
`is_reasoning_end()` keeps reporting False, the structured-output gate
never opens, and the grammar is silently never applied.
Both frontends run over one and the same model and renderer, so the only
thing that can differ between the two calls is the serving code itself.
"""
mock_model_config = MockModelConfig()
shared_renderer = _build_renderer(mock_model_config)
def _build_serving(cls):
mock_engine = MagicMock(spec=AsyncLLM)
mock_engine.model_config = mock_model_config
mock_engine.errored = False
mock_engine.input_processor = MagicMock()
mock_engine.renderer = shared_renderer
mock_engine.generate.side_effect = lambda *args, **kwargs: _generator(0, "ok")
models = OpenAIServingModels(mock_engine, BASE_MODEL_PATHS)
online_renderer = OnlineRenderer(
model_config=mock_model_config,
renderer=mock_engine.renderer,
request_logger=None,
chat_template=CHAT_TEMPLATE,
chat_template_content_format="auto",
reasoning_parser=REASONING_PARSER,
)
return mock_engine, cls(
mock_engine,
models,
response_role="assistant",
online_renderer=online_renderer,
chat_template=CHAT_TEMPLATE,
chat_template_content_format="auto",
request_logger=None,
reasoning_parser=REASONING_PARSER,
)
conversation = [{"role": "user", "content": "What is the capital of France?"}]
chat_template_kwargs = {"enable_thinking": False}
single_engine, single_serving = _build_serving(OpenAIServingChat)
await single_serving.create_chat_completion(
ChatCompletionRequest(
model=MOCK_MODEL_NAME,
messages=conversation,
chat_template_kwargs=chat_template_kwargs,
)
)
single_call = single_engine.generate.call_args_list[-1]
batch_engine, batch_serving = _build_serving(OpenAIServingChatBatch)
await batch_serving.create_batch_chat_completion(
BatchChatCompletionRequest(
model=MOCK_MODEL_NAME,
messages=[conversation],
chat_template_kwargs=chat_template_kwargs,
)
)
batch_call = batch_engine.generate.call_args_list[-1]
# Guard against a vacuous comparison: the reference path must be wired up.
assert single_call.kwargs["reasoning_ended"] is not None
assert single_call.kwargs["reasoning_parser_kwargs"] is not None
assert batch_call.kwargs["reasoning_ended"] == single_call.kwargs["reasoning_ended"]
assert (
batch_call.kwargs["reasoning_parser_kwargs"]
== single_call.kwargs["reasoning_parser_kwargs"]
)
# ...and the forwarded kwargs must actually turn thinking off for the
# engine-side parser, i.e. the structured-output gate opens right away.
engine_chat_template_kwargs = batch_call.kwargs["reasoning_parser_kwargs"][
"chat_template_kwargs"
]
reasoner = ReasoningParserManager.get_reasoning_parser(REASONING_PARSER)(
tokenizer=batch_engine.renderer.tokenizer,
chat_template_kwargs=engine_chat_template_kwargs,
)
assert reasoner.is_reasoning_end([]) is True
@@ -16,6 +16,7 @@ from openai import BadRequestError
from tests.utils import RemoteOpenAIServer
from vllm.entrypoints.openai.chat_completion.protocol import (
BatchChatCompletionRequest,
ChatCompletionRequest,
)
from vllm.exceptions import VLLMValidationError
@@ -1012,6 +1013,22 @@ def test_chat_completion_request_n_parameter_default():
assert sampling_params.n == 1, f"Expected n=1 (default), got n={sampling_params.n}"
@pytest.mark.parametrize(
("request_cls", "messages"),
[
(ChatCompletionRequest, [{"role": "user", "content": "Hello"}]),
(BatchChatCompletionRequest, [[{"role": "user", "content": "Hello"}]]),
],
)
def test_null_top_logprobs_is_same_as_omitted(request_cls, messages):
"""`top_logprobs: null` must not switch off `logprobs: true`."""
request = request_cls.model_validate(
{"messages": messages, "logprobs": True, "top_logprobs": None}
)
assert request.top_logprobs == 0
def test_chat_completion_request_accepts_model_specific_reasoning_effort():
request = ChatCompletionRequest(
model="test-model",
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
from dataclasses import dataclass, field
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
@@ -642,7 +643,15 @@ def test_batch_structural_tag_response_format_invalid(format_value):
)
@pytest.mark.parametrize("structural_tag", ["not json", ""])
@pytest.mark.parametrize(
"structural_tag",
[
"not json",
"",
# json.loads raises a plain ValueError, not JSONDecodeError
'{"type": "structural_tag", "x": ' + "1" * 5000 + "}",
],
)
def test_structured_outputs_structural_tag_invalid(structural_tag):
"""Malformed direct structured_outputs structural tags should be rejected."""
with pytest.raises(
@@ -656,6 +665,25 @@ def test_structured_outputs_structural_tag_invalid(structural_tag):
)
@pytest.mark.parametrize("field", ["response_format", "structured_outputs"])
def test_deeply_nested_structural_tag_rejected(field):
"""Structural tags are compiled during request parsing, so a deeply nested
one must be rejected there instead of blocking the server while converting,
and reported as too deep rather than malformed."""
schema = '{"type": "array", "items": ' * 200 + "{}" + "}" * 200
tag = (
'{"type": "structural_tag", "format": {"type": "json_schema", '
f'"json_schema": {schema}}}}}'
)
value = json.loads(tag) if field == "response_format" else {"structural_tag": tag}
with pytest.raises(VLLMValidationError, match="nested too deeply"):
ChatCompletionRequest(
model=MODEL_NAME,
messages=[{"role": "user", "content": "hello"}],
**{field: value},
)
@pytest.mark.parametrize("field_name", ["prompt_logprobs", "top_logprobs"])
def test_non_numeric_logprobs_rejected(field_name):
"""A non-numeric logprobs value must be a clean 400 validation error, not a
@@ -154,6 +154,40 @@ async def client(server):
yield async_client
@pytest.fixture(scope="module")
def watermarked_server():
args = [
"--dtype",
"half",
"--enable-auto-tool-choice",
"--structured-outputs-config.backend",
"xgrammar",
"--tool-call-parser",
"hermes",
"--reasoning-parser",
"qwen3",
"--gpu-memory-utilization",
"0.4",
"--enforce-eager",
"--watermark-config",
'{"algorithm":"gumbel","key":42}',
] + ROCM_EXTRA_ARGS
with RemoteOpenAIServer(MODEL_NAME, args) as remote_server:
yield remote_server
@pytest.fixture(params=["server", "watermarked_server"], ids=["plain", "watermarked"])
def tool_use_server(request: pytest.FixtureRequest):
return request.getfixturevalue(request.param)
@pytest_asyncio.fixture
async def tool_use_client(tool_use_server):
async with tool_use_server.get_async_client() as async_client:
yield async_client
@pytest.mark.asyncio
@pytest.mark.parametrize("model_name", [MODEL_NAME])
@pytest.mark.parametrize("stream", [True, False])
@@ -167,12 +201,13 @@ async def client(server):
)
@pytest.mark.parametrize("enable_thinking", [True, False])
async def test_function_tool_use(
client: openai.AsyncOpenAI,
tool_use_client: openai.AsyncOpenAI,
model_name: str,
stream: bool,
tool_choice: str | dict,
enable_thinking: bool,
):
client = tool_use_client
if not stream:
# Non-streaming test
chat_completion = await client.chat.completions.create(
@@ -0,0 +1,97 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import pytest
from vllm.entrypoints.generate.base.protocol import RequestResponseMetadata
from vllm.entrypoints.openai.completion.protocol import CompletionRequest
from vllm.entrypoints.openai.completion.serving import OpenAIServingCompletion
from vllm.logprobs import Logprob
from vllm.outputs import CompletionOutput, RequestOutput
TOKENS = [(1, "abc"), (2, " de"), (3, "!")]
# Text deltas as the detokenizer streams them with stop=["\n\n"]: one char is
# held back until the request finishes, so the text lags the tokens.
TEXT_DELTAS = ["ab", "c d", "e!"]
def _logprobs(i: int) -> dict[int, Logprob]:
token_id, token = TOKENS[i]
return {token_id: Logprob(logprob=-1.0, rank=1, decoded_token=token)}
def _output(text: str, idxs: list[int], finished: bool) -> RequestOutput:
return RequestOutput(
request_id="r",
prompt="Hi",
prompt_token_ids=[9],
prompt_logprobs=None,
outputs=[
CompletionOutput(
index=0,
text=text,
token_ids=[TOKENS[i][0] for i in idxs],
cumulative_logprob=None,
logprobs=[_logprobs(i) for i in idxs],
finish_reason="stop" if finished else None,
)
],
finished=finished,
)
def _serving() -> OpenAIServingCompletion:
serving = OpenAIServingCompletion.__new__(OpenAIServingCompletion)
serving.enable_prompt_tokens_details = False
serving.enable_force_include_usage = False
serving.enable_per_request_metrics = False
serving.system_fingerprint = None
serving.return_tokens_as_token_ids = False
return serving
def _request(stream: bool) -> CompletionRequest:
return CompletionRequest(
model="m", prompt="Hi", max_tokens=8, logprobs=0, stop=["\n\n"], stream=stream
)
@pytest.mark.asyncio
async def test_stream_text_offset_matches_non_stream_with_stop_holdback():
async def results():
for i, text in enumerate(TEXT_DELTAS):
yield 0, _output(text, [i], finished=i == len(TEXT_DELTAS) - 1)
serving = _serving()
stream_offsets = []
async for line in serving.completion_stream_generator(
_request(stream=True),
[{"prompt": "Hi"}],
results(),
"r",
0,
"m",
num_prompts=1,
tokenizer=None,
request_metadata=RequestResponseMetadata(request_id="r"),
):
data = line.removeprefix("data: ").strip()
if data == "[DONE]":
continue
for choice in json.loads(data)["choices"]:
stream_offsets += choice["logprobs"]["text_offset"]
response = serving.request_output_to_completion_response(
[_output("".join(TEXT_DELTAS), [0, 1, 2], finished=True)],
_request(stream=False),
"r",
0,
"m",
None,
RequestResponseMetadata(request_id="r"),
)
assert response.choices[0].logprobs is not None
assert response.choices[0].logprobs.text_offset == [0, 3, 6]
assert stream_offsets == [0, 3, 6]
@@ -13,13 +13,11 @@ from tests.utils import RemoteOpenAIServer
from vllm.engine.arg_utils import EngineArgs
from vllm.model_executor.model_loader.tensorizer import (
TensorizerConfig,
tensorize_lora_adapter,
tensorize_vllm_model,
)
from vllm.platforms import current_platform
MODEL_NAME = "unsloth/llama-3.2-1b-Instruct"
LORA_PATH = "davzoku/finqa_adapter_1b"
def _cleanup():
@@ -44,11 +42,10 @@ def model_uri(tmp_dir):
@pytest.fixture(scope="module")
def tensorize_model_and_lora(tmp_dir, model_uri):
tensorizer_config = TensorizerConfig(tensorizer_uri=model_uri, lora_dir=tmp_dir)
def tensorize_model(model_uri):
tensorizer_config = TensorizerConfig(tensorizer_uri=model_uri)
args = EngineArgs(model=MODEL_NAME)
tensorize_lora_adapter(LORA_PATH, tensorizer_config)
tensorize_vllm_model(args, tensorizer_config)
# Manually invoke a _cleanup() here, as the cleanup()
@@ -59,7 +56,7 @@ def tensorize_model_and_lora(tmp_dir, model_uri):
@pytest.fixture(scope="module")
def server(model_uri, tensorize_model_and_lora):
def server(model_uri, tensorize_model):
# In this case, model_uri is a directory with a model.tensors
# file and all necessary model artifacts, particularly a
# HF `config.json` file. In this case, Tensorizer can infer the
@@ -72,7 +69,6 @@ def server(model_uri, tensorize_model_and_lora):
"tensorizer",
"--served-model-name",
MODEL_NAME,
"--enable-lora",
]
if current_platform.is_rocm():
args += ["--attention-backend", "TRITON_ATTN"]
@@ -29,6 +29,7 @@ class TestResponsesRequestSamplingParams:
temperature=0.8,
top_p=0.95,
top_k=50,
min_p=0.1,
max_output_tokens=100,
)
@@ -37,8 +38,20 @@ class TestResponsesRequestSamplingParams:
assert sampling_params.temperature == 0.8
assert sampling_params.top_p == 0.95
assert sampling_params.top_k == 50
assert sampling_params.min_p == 0.1
assert sampling_params.max_tokens == 100
def test_min_p_default(self):
"""Test that min_p defaults to 0.0 when unset (parity with top_k)."""
request = ResponsesRequest(
model="test-model",
input="test input",
)
sampling_params = request.to_sampling_params(default_max_tokens=1000)
assert sampling_params.min_p == 0.0
def test_extra_sampling_params(self):
"""Test extra sampling parameters are correctly mapped."""
request = ResponsesRequest(
@@ -47,6 +60,7 @@ class TestResponsesRequestSamplingParams:
repetition_penalty=1.2,
seed=42,
stop=["END", "STOP"],
stop_token_ids=[42, 43],
ignore_eos=True,
vllm_xargs={"custom": "value"},
)
@@ -56,6 +70,7 @@ class TestResponsesRequestSamplingParams:
assert sampling_params.repetition_penalty == 1.2
assert sampling_params.seed == 42
assert sampling_params.stop == ["END", "STOP"]
assert sampling_params.stop_token_ids == [42, 43]
assert sampling_params.ignore_eos is True
assert sampling_params.extra_args == {"custom": "value"}
@@ -84,6 +99,20 @@ class TestResponsesRequestSamplingParams:
assert sampling_params.stop == [] # Empty list
assert sampling_params.extra_args == {} # Empty dict
def test_null_top_logprobs_is_same_as_omitted(self):
"""`top_logprobs: null` must not drop the requested output logprobs."""
request = ResponsesRequest.model_validate(
{
"input": "test input",
"include": ["message.output_text.logprobs"],
"top_logprobs": None,
}
)
sampling_params = request.to_sampling_params(default_max_tokens=1000)
assert sampling_params.logprobs == 0
def test_seed_bounds_validation(self):
"""Test that seed values outside torch.long bounds are rejected."""
# Test seed below minimum
@@ -7,6 +7,7 @@ import pytest
import schemathesis
from hypothesis import HealthCheck, settings
from schemathesis import GenerationMode
from schemathesis.checks import not_a_server_error
from schemathesis.config import (
ChecksConfig,
CoveragePhaseConfig,
@@ -161,8 +162,13 @@ def test_openapi_stateless(case: schemathesis.Case):
}.get(key, DEFAULT_TIMEOUT_SECONDS)
# No need to verify SSL certificate for localhost
case.call_and_validate(
systemone = case.operation.path == "/v1/systemone"
response = case.call_and_validate(
verify=False,
timeout=timeout,
headers={"Content-Type": "application/json"},
excluded_checks=[not_a_server_error] if systemone else None,
)
if systemone:
# SmolVLM does not support structured decisions.
assert response.status_code < 500 or response.status_code == 501
@@ -2,7 +2,8 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for presence_penalty / frequency_penalty resolution from
default_sampling_params in ChatCompletionRequest and CompletionRequest.
default_sampling_params in ChatCompletionRequest, BatchChatCompletionRequest
and CompletionRequest.
Regression test for https://github.com/vllm-project/vllm/issues/50767:
these two penalties defaulted to 0.0 (not None) and to_sampling_params()
@@ -12,6 +13,7 @@ discarded on the /v1/chat/completions and /v1/completions endpoints.
"""
from vllm.entrypoints.openai.chat_completion.protocol import (
BatchChatCompletionRequest,
ChatCompletionRequest,
)
from vllm.entrypoints.openai.completion.protocol import (
@@ -29,6 +31,14 @@ def _chat(**kwargs):
)
def _batch(**kwargs):
conversation = [{"role": "user", "content": "hi"}]
request = BatchChatCompletionRequest(
model="test-model", messages=[conversation], **kwargs
)
return request.to_chat_completion_request(conversation)
class TestChatCompletionPenaltyDefaults:
def test_defaults_applied_when_client_omits(self):
"""Server-default penalties are applied when the client sends none."""
@@ -49,6 +59,22 @@ class TestChatCompletionPenaltyDefaults:
assert sp.frequency_penalty == 0.0
class TestBatchChatCompletionPenaltyDefaults:
def test_defaults_applied_when_client_omits(self):
"""Server-default penalties reach every conversation of a batch."""
sp = _batch().to_sampling_params(100, _DEFAULTS)
assert sp.presence_penalty == 1.5
assert sp.frequency_penalty == 0.5
def test_client_value_overrides_default(self):
"""An explicit client penalty, even 0.0, wins over the server default."""
sp = _batch(presence_penalty=0.0, frequency_penalty=0.2).to_sampling_params(
100, _DEFAULTS
)
assert sp.presence_penalty == 0.0
assert sp.frequency_penalty == 0.2
class TestCompletionPenaltyDefaults:
def test_defaults_applied_when_client_omits(self):
sp = CompletionRequest(model="test-model", prompt="hi").to_sampling_params(
+224 -7
View File
@@ -1,32 +1,249 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from io import BytesIO
import pytest
from fastapi import UploadFile
from vllm.entrypoints.openai.chat_completion.protocol import (
BatchChatCompletionRequest,
ChatCompletionRequest,
)
from vllm.entrypoints.openai.completion.protocol import CompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
from vllm.entrypoints.speech_to_text.transcription.protocol import (
TranscriptionRequest,
)
from vllm.entrypoints.speech_to_text.translation.protocol import TranslationRequest
from vllm.sampling_params import StructuredOutputsParams
def test_chat_request_disables_watermarking():
def test_chat_request_preserves_watermarking_opt_out():
request = ChatCompletionRequest(
messages=[{"role": "user", "content": "hello"}], watermarking=False
)
params = request.to_sampling_params(max_tokens=1, default_sampling_params={})
assert not params.watermarking
assert params.watermarking is False
def test_completion_request_disables_watermarking():
def test_completion_request_preserves_watermarking_opt_out():
request = CompletionRequest(prompt="hello", watermarking=False)
params = request.to_sampling_params(max_tokens=1)
assert not params.watermarking
assert params.watermarking is False
def test_responses_request_disables_watermarking():
def test_responses_request_preserves_watermarking_opt_out():
request = ResponsesRequest(input="hello", watermarking=False)
params = request.to_sampling_params(default_max_tokens=1)
assert not params.watermarking
assert params.watermarking is False
def test_batch_chat_request_preserves_watermarking_opt_out():
request = BatchChatCompletionRequest(
messages=[[{"role": "user", "content": "hello"}]], watermarking=False
)
converted = request.to_chat_completion_request(request.messages[0])
params = converted.to_sampling_params(max_tokens=1, default_sampling_params={})
assert params.watermarking is False
@pytest.mark.parametrize(
"api_request,conversion,kwargs",
[
(
ChatCompletionRequest(
messages=[{"role": "user", "content": "hello"}],
use_beam_search=True,
watermarking=False,
),
"to_beam_search_params",
{"max_tokens": 1, "default_sampling_params": {}},
),
(
CompletionRequest(prompt="hello", use_beam_search=True, watermarking=False),
"to_beam_search_params",
{"max_tokens": 1, "default_sampling_params": {}},
),
(
TranscriptionRequest(
file=UploadFile(file=BytesIO(), filename="audio.wav"),
watermarking=False,
),
"to_sampling_params",
{"default_max_tokens": 1},
),
(
TranscriptionRequest(
file=UploadFile(file=BytesIO(), filename="audio.wav"),
watermarking=False,
),
"to_beam_search_params",
{"default_max_tokens": 1},
),
(
TranslationRequest(
file=UploadFile(file=BytesIO(), filename="audio.wav"),
watermarking=False,
),
"to_sampling_params",
{"default_max_tokens": 1},
),
(
TranslationRequest(
file=UploadFile(file=BytesIO(), filename="audio.wav"),
watermarking=False,
),
"to_beam_search_params",
{"default_max_tokens": 1},
),
],
)
def test_request_preserves_watermarking_opt_out(api_request, conversion, kwargs):
params = getattr(api_request, conversion)(**kwargs)
assert params.watermarking is False
@pytest.mark.parametrize("request_cls", [TranscriptionRequest, TranslationRequest])
def test_speech_requests_leave_watermarking_unspecified(request_cls):
request = request_cls(
file=UploadFile(file=BytesIO(), filename="audio.wav"),
temperature=0.8,
)
sampling_params = request.to_sampling_params(default_max_tokens=1)
beam_params = request.to_beam_search_params(default_max_tokens=1)
assert request.watermarking is None
assert sampling_params.watermarking is None
assert beam_params.watermarking is None
@pytest.mark.parametrize(
"api_request,kwargs",
[
(
ChatCompletionRequest(
messages=[{"role": "user", "content": "choose A or B"}],
temperature=0.8,
structured_outputs=StructuredOutputsParams(choice=["A", "B"]),
),
{"max_tokens": 8, "default_sampling_params": {}},
),
(
CompletionRequest(
prompt="choose A or B",
temperature=0.8,
structured_outputs=StructuredOutputsParams(choice=["A", "B"]),
),
{"max_tokens": 8},
),
(
ResponsesRequest(
input="choose A or B",
temperature=0.8,
structured_outputs=StructuredOutputsParams(choice=["A", "B"]),
),
{"default_max_tokens": 8},
),
],
)
def test_request_preserves_unspecified_watermarking_with_structured_outputs(
api_request, kwargs
):
params = api_request.to_sampling_params(**kwargs)
assert params.watermarking is None
assert params.structured_outputs is not None
assert params.structured_outputs.choice == ["A", "B"]
@pytest.mark.parametrize(
"api_request,conversion,kwargs",
[
(
ChatCompletionRequest(
messages=[{"role": "user", "content": "hello"}], watermarking=True
),
"to_sampling_params",
{"max_tokens": 1, "default_sampling_params": {}},
),
(
ChatCompletionRequest(
messages=[{"role": "user", "content": "hello"}],
use_beam_search=True,
watermarking=True,
),
"to_beam_search_params",
{"max_tokens": 1, "default_sampling_params": {}},
),
(
CompletionRequest(prompt="hello", watermarking=True),
"to_sampling_params",
{"max_tokens": 1},
),
(
CompletionRequest(prompt="hello", use_beam_search=True, watermarking=True),
"to_beam_search_params",
{"max_tokens": 1},
),
(
ResponsesRequest(input="hello", watermarking=True),
"to_sampling_params",
{"default_max_tokens": 1},
),
(
TranscriptionRequest(
file=UploadFile(file=BytesIO(), filename="audio.wav"),
watermarking=True,
),
"to_sampling_params",
{"default_max_tokens": 1},
),
(
TranslationRequest(
file=UploadFile(file=BytesIO(), filename="audio.wav"),
watermarking=True,
),
"to_sampling_params",
{"default_max_tokens": 1},
),
],
)
def test_request_preserves_explicit_watermarking(api_request, conversion, kwargs):
params = getattr(api_request, conversion)(**kwargs)
assert params.watermarking is True
def test_batch_chat_request_preserves_explicit_watermarking():
request = BatchChatCompletionRequest(
messages=[[{"role": "user", "content": "hello"}]], watermarking=True
)
converted = request.to_chat_completion_request(request.messages[0])
params = converted.to_sampling_params(max_tokens=1, default_sampling_params={})
assert converted.watermarking is True
assert params.watermarking is True
def test_batch_chat_request_inherits_watermarking():
request = BatchChatCompletionRequest(
messages=[[{"role": "user", "content": "hello"}]]
)
converted = request.to_chat_completion_request(request.messages[0])
params = converted.to_sampling_params(max_tokens=1, default_sampling_params={})
assert converted.watermarking is None
assert params.watermarking is None
@@ -7,6 +7,8 @@ import pytest
from vllm import PoolingParams
from vllm.entrypoints.pooling.base.io_processor import PoolingIOProcessor
from vllm.entrypoints.pooling.offline import PoolingOfflineMixin
from vllm.entrypoints.pooling.scoring.io_processor import CrossEncoderIOProcessor
from vllm.entrypoints.pooling.typing import OfflineEncodeInputsContext
from vllm.exceptions import VLLMValidationError
from vllm.renderers import TokenizeParams
@@ -221,3 +223,38 @@ def test_qwen3_reranker_no_warning_when_template_provided(monkeypatch):
)
mock_logger.warning.assert_not_called()
def _make_score_llm(monkeypatch) -> PoolingOfflineMixin:
"""A scoring LLM with no model behind it.
Input validation runs for real; only the rendering, engine and
post-processing boundaries are stubbed out. The pooling task is filled in
before any of them, so the mutation is observable without inference.
"""
proc = CrossEncoderIOProcessor.__new__(CrossEncoderIOProcessor)
proc.is_multimodal_model = False
proc.architecture = "CrossEncoder"
monkeypatch.setattr(proc, "get_request_factory_offline", lambda ctx: (None, 0))
monkeypatch.setattr(proc, "post_process_offline", lambda ctx: [])
llm = PoolingOfflineMixin.__new__(PoolingOfflineMixin)
llm.runner_type = "pooling"
llm.pooling_task = "classify" # SCORE_TYPE_MAP -> "cross-encoder"
llm.model_config = SimpleNamespace(hf_config=SimpleNamespace(num_labels=1))
llm.pooling_io_processors = {"cross-encoder": proc}
monkeypatch.setattr(llm, "_run_tiling_engine", lambda *args, **kwargs: [])
return llm
def test_score_leaves_caller_pooling_params_untouched(monkeypatch):
llm = _make_score_llm(monkeypatch)
params = PoolingParams()
llm.score("query", "doc", pooling_params=params)
assert params.task is None, (
"LLM.score() wrote the model's own pooling task into the caller's "
"PoolingParams; reusing that object with another pooling model now "
"fails with 'You cannot overwrite ...' before any inference runs."
)
@@ -7,7 +7,7 @@ import numpy as np
import pybase64 as base64
import pytest
from ...utils import RemoteOpenAIServer
from tests.utils import RemoteOpenAIServer
MODEL_NAME = "TitanML/tiny-mixtral"
@@ -9,7 +9,7 @@ import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from vllm.entrypoints.serve.dev.rlhf.api_router import router as rlhf_router
from vllm.entrypoints.rl.online.api_router import router as rl_router
from vllm.entrypoints.serve.dev.rpc.api_router import router as rpc_router
from vllm.entrypoints.serve.exception_handling.register import init_exception_handler
@@ -30,7 +30,7 @@ class Engine:
@pytest.fixture
def client():
app = FastAPI()
app.include_router(rlhf_router)
app.include_router(rl_router)
app.include_router(rpc_router)
init_exception_handler(app)
app.state.engine_client = Engine()
@@ -10,7 +10,7 @@ from unittest.mock import patch
import pytest
import requests
from tests.entrypoints.serve.dev.rlhf.conftest import (
from tests.entrypoints.rl.conftest import (
cached_tokens,
completion_with_cache_details,
gen,
@@ -9,7 +9,7 @@ import requests
import torch
from transformers import AutoModelForCausalLM
from tests.entrypoints.serve.dev.rlhf.conftest import (
from tests.entrypoints.rl.conftest import (
MODEL_NAME,
gen,
health,
@@ -15,6 +15,7 @@ from unittest.mock import patch
import pytest
import torch
from tests.utils import create_new_process_for_each_test
from vllm.config import WeightTransferConfig
from vllm.distributed.weight_transfer.base import (
WeightTransferEngine,
@@ -24,8 +25,6 @@ from vllm.distributed.weight_transfer.base import (
WeightTransferUpdateRequest,
)
from ...utils import create_new_process_for_each_test
# Use a tiny model for fast testing
MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
@@ -7,7 +7,7 @@ import torch
from prometheus_client.parser import text_string_to_metric_families
from transformers import AutoModelForCausalLM
from tests.entrypoints.serve.dev.rlhf.conftest import MODEL_NAME
from tests.entrypoints.rl.conftest import MODEL_NAME
from tests.utils import RemoteOpenAIServer
from vllm.distributed.weight_transfer import (
HTTPVLLMWeightSyncClient,
@@ -13,9 +13,9 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from prometheus_client import CollectorRegistry
from vllm.entrypoints.serve.dev.rlhf import api_router
from vllm.entrypoints.serve.dev.rlhf import metrics as rlhf_metrics
from vllm.entrypoints.serve.dev.rlhf.metrics import WeightOperationMetrics
from vllm.entrypoints.rl.online import api_router
from vllm.entrypoints.rl.online import metrics as rl_metrics
from vllm.entrypoints.rl.online.metrics import WeightOperationMetrics
from vllm.entrypoints.serve.exception_handling.register import init_exception_handler
from vllm.v1.metrics.prometheus import get_prometheus_registry
@@ -52,13 +52,13 @@ class Engine:
@pytest.fixture
def registry(monkeypatch):
registry = CollectorRegistry()
monkeypatch.setattr(rlhf_metrics, "_metrics", WeightOperationMetrics(registry))
monkeypatch.setattr(rl_metrics, "_metrics", WeightOperationMetrics(registry))
return registry
@pytest.mark.parametrize("fail", [False, True])
def test_record_releases_in_flight_and_observes_duration(registry, fail):
metrics = rlhf_metrics.weight_operation_metrics()
metrics = rl_metrics.weight_operation_metrics()
with (
pytest.raises(RuntimeError) if fail else nullcontext(),
metrics.record("update"),
@@ -108,7 +108,7 @@ async def test_cancelled_route_releases_in_flight(registry):
HOLD_OPERATION = """
import sys
from vllm.entrypoints.serve.dev.rlhf.metrics import weight_operation_metrics
from vllm.entrypoints.rl.online.metrics import weight_operation_metrics
with weight_operation_metrics().record("update"):
print("entered", flush=True)
sys.stdin.readline()
@@ -163,19 +163,19 @@ def test_default_recorder_is_created_lazily_on_the_default_registry():
probe = """
from prometheus_client import REGISTRY
from vllm.entrypoints.serve.dev.rlhf import metrics as rlhf_metrics
from vllm.entrypoints.rl.online import metrics as rl_metrics
NAMES = [
"vllm:rl_weight_update_operation_duration_seconds",
"vllm:rl_weight_update_operations_in_flight",
]
assert rlhf_metrics._metrics is None
assert rl_metrics._metrics is None
assert not set(NAMES) & set(REGISTRY._names_to_collectors)
metrics = rlhf_metrics.weight_operation_metrics()
metrics = rl_metrics.weight_operation_metrics()
assert REGISTRY._names_to_collectors[NAMES[0]] is metrics.duration
assert REGISTRY._names_to_collectors[NAMES[1]] is metrics.in_flight
assert rlhf_metrics.weight_operation_metrics() is metrics
assert rl_metrics.weight_operation_metrics() is metrics
print("lazy registration ok")
"""
result = subprocess.run(
@@ -74,14 +74,13 @@ def _make_generate_response(
}
def _make_logprobs_with_placeholders(token_id: int = 1234) -> dict:
def _make_generate_logprobs(token_id: int = 1234) -> dict:
"""A `GenerateLogProbs` payload: integer token ids, no token/bytes."""
entry = {
"token": f"token_id:{token_id}",
"token_id": token_id,
"logprob": -1.0,
"bytes": None,
"top_logprobs": [
{"token": f"token_id:{token_id + 1}", "logprob": -2.0, "bytes": None}
],
"rank": 1,
"top_logprobs": [{"token_id": token_id + 1, "logprob": -2.0, "rank": 2}],
}
return {"content": [entry]}
@@ -154,7 +153,7 @@ async def test_derender_chat_usage_default(client):
@pytest.mark.asyncio
async def test_derender_chat_logprobs(client):
"""token_id:N placeholders in content.token are resolved to real strings."""
"""Integer token ids are decoded to real strings by derender."""
gen_req = await _render_chat(client)
synthetic_ids = gen_req["token_ids"][:3]
token_id = synthetic_ids[0]
@@ -165,7 +164,7 @@ async def test_derender_chat_logprobs(client):
"model": MODEL_NAME,
"generate_response": _make_generate_response(
synthetic_ids,
logprobs=_make_logprobs_with_placeholders(token_id),
logprobs=_make_generate_logprobs(token_id),
),
},
)
@@ -176,8 +175,8 @@ async def test_derender_chat_logprobs(client):
content = logprobs["content"]
assert content is not None and len(content) == 1
token_str = content[0]["token"]
assert not token_str.startswith("token_id:"), (
f"Placeholder was not resolved: {token_str!r}"
assert token_str and not token_str.startswith("token_id:"), (
f"token id was not decoded: {token_str!r}"
)
@@ -194,7 +193,7 @@ async def test_derender_chat_logprobs_bytes(client):
"model": MODEL_NAME,
"generate_response": _make_generate_response(
synthetic_ids,
logprobs=_make_logprobs_with_placeholders(token_id),
logprobs=_make_generate_logprobs(token_id),
),
},
)
@@ -208,7 +207,7 @@ async def test_derender_chat_logprobs_bytes(client):
@pytest.mark.asyncio
async def test_derender_chat_top_logprobs(client):
"""top_logprobs entries also have their placeholders resolved."""
"""top_logprobs entries are decoded too."""
gen_req = await _render_chat(client)
synthetic_ids = gen_req["token_ids"][:3]
token_id = synthetic_ids[0]
@@ -219,7 +218,7 @@ async def test_derender_chat_top_logprobs(client):
"model": MODEL_NAME,
"generate_response": _make_generate_response(
synthetic_ids,
logprobs=_make_logprobs_with_placeholders(token_id),
logprobs=_make_generate_logprobs(token_id),
),
},
)
@@ -228,7 +227,7 @@ async def test_derender_chat_top_logprobs(client):
top = content[0]["top_logprobs"]
assert len(top) == 1
assert not top[0]["token"].startswith("token_id:"), (
f"top_logprobs placeholder not resolved: {top[0]['token']!r}"
f"top_logprobs token id not decoded: {top[0]['token']!r}"
)
@@ -633,8 +632,8 @@ async def test_derender_completion_empty_generate_responses(client):
@pytest.mark.asyncio
async def test_derender_completion_logprobs(client):
"""token_id:N placeholders in logprobs are resolved; CompletionLogProbs
flat-list structure is returned with non-empty tokens and text_offsets."""
"""Integer token ids are decoded; CompletionLogProbs flat-list structure is
returned with non-empty tokens and text_offsets."""
gr1 = await _render_completion(client, "Hello world")
ids1 = gr1["token_ids"][:3]
token_id = ids1[0]
@@ -647,7 +646,7 @@ async def test_derender_completion_logprobs(client):
_make_completion_generate_response(
ids1,
gr1["request_id"],
logprobs=_make_logprobs_with_placeholders(token_id),
logprobs=_make_generate_logprobs(token_id),
),
],
},
@@ -658,7 +657,7 @@ async def test_derender_completion_logprobs(client):
tokens = logprobs["tokens"]
assert len(tokens) == 1
assert not tokens[0].startswith("token_id:"), (
f"Placeholder was not resolved: {tokens[0]!r}"
f"token id was not decoded: {tokens[0]!r}"
)
assert len(logprobs["token_logprobs"]) == 1
assert isinstance(logprobs["token_logprobs"][0], float)
@@ -794,7 +793,7 @@ async def test_derender_chat_oversized_logprobs_rejected(client):
"""logprobs.content longer than max_model_len returns 400."""
oversized_logprobs: dict = {
"content": [
{"token": "x", "logprob": -1.0, "bytes": None, "top_logprobs": []}
{"token_id": 42, "logprob": -1.0, "rank": 1, "top_logprobs": []}
for _ in range(1_000_000)
]
}
@@ -825,11 +824,11 @@ async def test_derender_chat_oversized_top_logprobs_rejected(client):
oversized_top_logprobs = {
"content": [
{
"token": "x",
"token_id": 42,
"logprob": -1.0,
"bytes": None,
"rank": 1,
"top_logprobs": [
{"token": f"t{i}", "logprob": -float(i), "bytes": None}
{"token_id": i, "logprob": -float(i), "rank": i + 1}
for i in range(25)
],
}
@@ -1298,6 +1297,72 @@ async def test_e2e_harmony_plain_roundtrip(harmony_client, harmony_tokenizer):
assert "Four" in content
@pytest.fixture(scope="module")
def harmony_default_server():
"""gpt-oss render server with NO parser flags.
Regression fixture: the model-default reasoning parser
("openai_gptoss", applied by verify_and_update_config) must be
resolved by the render server without any --reasoning-parser flag,
otherwise harmony markup leaks unparsed into derender output.
"""
_ensure_harmony_vocab()
with RemoteLaunchRenderServer(
HARMONY_MODEL, ["--trust-remote-code"]
) as remote_server:
yield remote_server
@pytest_asyncio.fixture
async def harmony_default_client(harmony_default_server):
async with httpx.AsyncClient(
base_url=harmony_default_server.url_for(""), timeout=60.0
) as http_client:
yield http_client
@pytest.mark.asyncio
async def test_e2e_harmony_reasoning_default_parser(
harmony_default_client, harmony_tokenizer
):
"""GPT-OSS reasoning parses on a bare launch (no parser flags)."""
messages = [{"role": "user", "content": "Add 2 and 3."}]
gen_req = await _e2e_render_chat(harmony_default_client, HARMONY_MODEL, messages)
reasoning_text = "The user wants 2 plus 3."
answer_text = "The answer is 5."
assistant_msg = {
"role": "assistant",
"thinking": reasoning_text,
"content": answer_text,
}
output_ids = _harmony_extract_assistant_ids(harmony_tokenizer, assistant_msg)
decoded = harmony_tokenizer.decode(output_ids)
if reasoning_text not in decoded:
pytest.skip("Harmony template did not render thinking")
resp = await harmony_default_client.post(
"/v1/chat/completions/derender",
json={
"model": HARMONY_MODEL,
"generate_response": _e2e_generate_response(output_ids),
"prompt_tokens": len(gen_req["token_ids"]),
"chat_request": {
"model": HARMONY_MODEL,
"messages": messages,
"include_reasoning": True,
},
},
)
assert resp.status_code == 200, resp.text
msg = resp.json()["choices"][0]["message"]
assert msg["reasoning"] is not None
assert reasoning_text in msg["reasoning"]
assert answer_text in (msg["content"] or "")
assert "<|channel|>" not in (msg["content"] or "")
@pytest.mark.asyncio
async def test_e2e_harmony_reasoning(harmony_client, harmony_tokenizer):
"""GPT-OSS reasoning: analysis channel extracted."""
@@ -237,21 +237,47 @@ async def test_parity_reasoning_and_tool_call(client):
assert _tool_sig(disagg["choices"][0])
def _to_generate_logprobs(openai_logprobs: dict) -> dict:
"""Turn a coupled response's `token_id:N` logprobs into `GenerateLogProbs`.
A real GPU-less worker emits integer ids directly; here the coupled server
with `return_tokens_as_token_ids=True` is the only source of the same ids,
so the placeholders are parsed back out to build the generate-shaped
payload that `/derender` now consumes.
"""
def _id(token: str) -> int:
assert token.startswith("token_id:"), token
return int(token.removeprefix("token_id:"))
return {
"content": [
{
"token_id": _id(entry["token"]),
"logprob": entry["logprob"],
"top_logprobs": [
{"token_id": _id(top["token"]), "logprob": top["logprob"]}
for top in entry["top_logprobs"]
],
}
for entry in openai_logprobs["content"]
]
}
@pytest.mark.asyncio
async def test_parity_logprobs(client):
"""token_id:N resolution parity vs. the coupled server's real strings.
"""Integer-id logprob decoding parity vs. the coupled server's strings.
A real disaggregated worker only has token IDs so it emits logprobs
with `token_id:N` placeholders (`return_tokens_as_token_ids=True`
reproduces that shape here). `/derender` must resolve those
placeholders to the same token strings/bytes the coupled server
resolves them to directly.
A real disaggregated worker only has token IDs, so it emits
`GenerateLogProbs` with integer `token_id`s. `/derender` must decode those
to the same token strings/bytes the coupled server produces directly.
"""
messages = [{"role": "user", "content": "What is 2+2?"}]
extra = {"logprobs": True, "top_logprobs": 3}
# What a real GPU less worker would hand to /derender is token IDs plus
# logprobs still in token_id:N placeholder form
# The coupled server with placeholders is used only as a source of the
# token ids a GPU-less worker would have had.
placeholder = await _coupled(
client, messages, return_tokens_as_token_ids=True, **extra
)
@@ -263,7 +289,7 @@ async def test_parity_logprobs(client):
placeholder["usage"]["prompt_tokens"],
ch["finish_reason"],
chat_request,
logprobs=ch["logprobs"],
logprobs=_to_generate_logprobs(ch["logprobs"]),
)
# The coupled server resolving the same greedy generation
@@ -64,6 +64,7 @@ from vllm.renderers.online_derenderer import (
_seed_stream_state,
)
from vllm.tokenizers import get_tokenizer
from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens
from vllm.utils import random_uuid
MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
@@ -212,17 +213,12 @@ def _make_stream_chunk(
)
def _placeholder_logprobs(token_ids: list[int]) -> dict:
"""Per-token logprob entries using token_id:N placeholders, as sent by
the generate worker."""
def _generate_logprobs(token_ids: list[int]) -> dict:
"""Per-token `GenerateLogProbs` entries (integer token ids, no token or
bytes), as sent by the generate worker."""
return {
"content": [
{
"token": f"token_id:{tid}",
"logprob": -0.5,
"bytes": None,
"top_logprobs": [],
}
{"token_id": tid, "logprob": -0.5, "rank": 1, "top_logprobs": []}
for tid in token_ids
]
}
@@ -892,12 +888,12 @@ class TestDerenderCompletionStream:
class TestStreamLogprobs:
"""Streaming derender must carry per-chunk logprobs with placeholders
resolved, matching what the generate streaming path emits."""
"""Streaming derender must carry per-chunk logprobs with token ids
decoded, matching what the generate streaming path emits."""
@pytest.mark.asyncio
async def test_chat_stream_logprobs_resolved_per_chunk(self, derenderer, tokenizer):
"""Each streamed chunk carries logprobs with token_id:N resolved."""
"""Each streamed chunk carries logprobs with its token ids decoded."""
token_ids = tokenizer.encode("hello world")[:6]
mid = len(token_ids) // 2
@@ -906,17 +902,15 @@ class TestStreamLogprobs:
chunk, state = await derenderer.derender_chat_stream(
model=MODEL_NAME,
generate_chunk=_make_stream_chunk(
part, logprobs=_placeholder_logprobs(part)
part, logprobs=_generate_logprobs(part)
),
state=state,
)
logprobs = chunk.choices[0].logprobs
assert logprobs is not None and logprobs.content is not None
assert len(logprobs.content) == len(part)
for entry in logprobs.content:
assert not entry.token.startswith("token_id:"), (
f"placeholder not resolved: {entry.token!r}"
)
assert [entry.token for entry in logprobs.content] == (
convert_ids_list_to_tokens(tokenizer, part)
)
@pytest.mark.asyncio
async def test_chat_stream_logprobs_multibyte_across_chunks(
@@ -936,7 +930,7 @@ class TestStreamLogprobs:
last_chunk, state = await derenderer.derender_chat_stream(
model=MODEL_NAME,
generate_chunk=_make_stream_chunk(
[tid], logprobs=_placeholder_logprobs([tid])
[tid], logprobs=_generate_logprobs([tid])
),
state=state,
)
@@ -959,13 +953,13 @@ class TestStreamLogprobs:
chunk1, state = await derenderer.derender_completion_stream(
model=MODEL_NAME,
generate_chunk=_make_stream_chunk(
token_ids[:mid], logprobs=_placeholder_logprobs(token_ids[:mid])
token_ids[:mid], logprobs=_generate_logprobs(token_ids[:mid])
),
)
chunk2, _ = await derenderer.derender_completion_stream(
model=MODEL_NAME,
generate_chunk=_make_stream_chunk(
token_ids[mid:], logprobs=_placeholder_logprobs(token_ids[mid:])
token_ids[mid:], logprobs=_generate_logprobs(token_ids[mid:])
),
state=state,
)
@@ -982,7 +976,7 @@ class TestStreamLogprobs:
_, state = await derenderer.derender_chat_stream(
model=MODEL_NAME,
generate_chunk=_make_stream_chunk(
[tid], logprobs=_placeholder_logprobs([tid])
[tid], logprobs=_generate_logprobs([tid])
),
state=state,
)
@@ -0,0 +1,172 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for the generate -> OpenAI logprob conversion in derender.
These exercise `_resolve_logprobs` directly. A stub tokenizer covers the
byte-fallback correction path; a real SentencePiece tokenizer covers the
leading-space restoration.
"""
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
GenerateLogProb,
GenerateLogProbs,
GenerateLogProbsContent,
)
from vllm.renderers.online_derenderer import (
_convert_chat_logprobs_to_completion_logprobs,
_resolve_logprobs,
)
from vllm.tokenizers import get_tokenizer
from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens
# A two-byte character split across two byte-fallback tokens: neither decodes
# to anything printable on its own, but the pair decodes to "é".
FIRST_BYTE = 10
SECOND_BYTE = 11
PLAIN = 12
VOCAB = {FIRST_BYTE: "<0xC3>", SECOND_BYTE: "<0xA9>", PLAIN: "ok"}
class _StubTokenizer:
"""Decodes byte-fallback tokens only when both halves are present."""
def convert_ids_to_tokens(self, ids: list[int]) -> list[str | None]:
return [VOCAB.get(i) for i in ids]
def convert_tokens_to_string(self, tokens: list[str]) -> str:
return self.decode([k for t in tokens for k, v in VOCAB.items() if v == t])
def decode(self, ids: list[int], **kwargs) -> str:
out = ""
i = 0
while i < len(ids):
if ids[i] == FIRST_BYTE and i + 1 < len(ids) and ids[i + 1] == SECOND_BYTE:
out += "é"
i += 2
elif ids[i] in (FIRST_BYTE, SECOND_BYTE):
out += "�"
i += 1
else:
out += VOCAB.get(ids[i], "")
i += 1
return out
def test_token_ids_are_decoded_with_bytes_and_order_preserved():
logprobs = GenerateLogProbs(
content=[
GenerateLogProbsContent(
token_id=PLAIN,
logprob=-0.5,
rank=1,
top_logprobs=[
GenerateLogProb(token_id=PLAIN, logprob=-0.5, rank=1),
GenerateLogProb(token_id=FIRST_BYTE, logprob=-2.0, rank=2),
],
)
]
)
resolved = _resolve_logprobs(logprobs, _StubTokenizer())
assert resolved.content is not None
entry = resolved.content[0]
assert entry.token == "ok"
assert entry.logprob == -0.5
assert entry.bytes == list(b"ok")
# Rank order survives the conversion (the OpenAI shape has no rank field).
assert [t.logprob for t in entry.top_logprobs] == [-0.5, -2.0]
assert entry.top_logprobs[0].token == "ok"
def test_byte_fallback_second_half_uses_preceding_token_as_context():
"""U+FFFD correction needs the preceding sampled ids, which the integer
shape carries directly (no placeholder parsing)."""
logprobs = GenerateLogProbs(
content=[
GenerateLogProbsContent(token_id=FIRST_BYTE, logprob=-0.1),
GenerateLogProbsContent(token_id=SECOND_BYTE, logprob=-0.2),
]
)
resolved = _resolve_logprobs(logprobs, _StubTokenizer())
assert resolved.content is not None
# The first half has no preceding context to repair it with, so it stays
# empty (existing `_correct_decoded_token` behaviour). The second resolves
# to the complete character once the first is used as context.
assert resolved.content[0].token == ""
assert resolved.content[0].bytes == []
assert resolved.content[1].token == "é"
assert resolved.content[1].bytes == list("é".encode())
def test_content_none_is_not_an_error():
resolved = _resolve_logprobs(GenerateLogProbs(), _StubTokenizer())
assert resolved.content is None
def test_sentencepiece_leading_space_matches_engine():
"""`▁true` and `true` are distinct tokens and must stay distinct: the
strings match the engine's per-token detokenization (leading space
restored), so `/v1/completions/derender` top_logprobs keys do not collide.
Regression test for #59241."""
tokenizer = get_tokenizer("hmellor/tiny-random-LlamaForCausalLM")
spaced = tokenizer.convert_tokens_to_ids("▁true")
bare = tokenizer.convert_tokens_to_ids("true")
assert spaced != bare
logprobs = GenerateLogProbs(
content=[
GenerateLogProbsContent(
token_id=spaced,
logprob=-0.5,
rank=1,
top_logprobs=[
GenerateLogProb(token_id=spaced, logprob=-0.5, rank=1),
GenerateLogProb(token_id=bare, logprob=-1.5, rank=2),
],
)
]
)
resolved = _resolve_logprobs(logprobs, tokenizer)
assert resolved.content is not None
entry = resolved.content[0]
assert entry.token == " true"
assert entry.bytes == list(b" true")
assert [t.token for t in entry.top_logprobs] == convert_ids_list_to_tokens(
tokenizer, [spaced, bare]
)
completion = _convert_chat_logprobs_to_completion_logprobs(resolved)
assert completion.top_logprobs == [{" true": -0.5, "true": -1.5}]
def test_unknown_top_id_does_not_shift_the_other_candidates():
"""Ids are decoded in one batch per position; an id with no vocab entry
becomes an empty token without shifting its neighbours."""
unknown = 99
logprobs = GenerateLogProbs(
content=[
GenerateLogProbsContent(
token_id=PLAIN,
logprob=-0.5,
rank=1,
top_logprobs=[
GenerateLogProb(token_id=unknown, logprob=-1.0, rank=1),
GenerateLogProb(token_id=PLAIN, logprob=-0.5, rank=2),
],
)
]
)
resolved = _resolve_logprobs(logprobs, _StubTokenizer())
assert resolved.content is not None
entry = resolved.content[0]
assert entry.token == "ok"
assert [(t.token, t.bytes) for t in entry.top_logprobs] == [
("", None),
("ok", list(b"ok")),
]
@@ -38,6 +38,7 @@ def _build_responses_serving_render() -> ServingRender:
OnlineRenderer.validate_chat_template.__get__(serving.online_renderer)
)
serving.online_renderer.trust_request_chat_template = True
serving.online_renderer.parser = None
serving._check_model = AsyncMock(return_value=None)
return serving
@@ -135,6 +136,37 @@ async def test_render_responses_rejects_empty_token_ids():
assert response.error.message == "No token_ids rendered"
@pytest.mark.asyncio
@pytest.mark.skip_global_cleanup
async def test_render_responses_carries_reasoning_parser_kwargs():
"""/v1/responses gives the engine's reasoning parser the effective template
kwargs, so the rendered request must carry them to generate."""
serving = _build_responses_serving_render()
online = serving.online_renderer
online.parser = MagicMock(reasoning_parser_cls=object)
online.chat_template = None
online.chat_template_content_format = "auto"
online.default_chat_template_kwargs = {"enable_thinking": True}
online.effective_chat_template_kwargs = (
OnlineRenderer.effective_chat_template_kwargs.__get__(online)
)
online.render_responses = AsyncMock(
return_value=MagicMock(messages=[], engine_input={"prompt_token_ids": [7]})
)
request = ResponsesRequest(
model=MODEL_NAME,
input="Test prompt",
chat_template_kwargs={"enable_thinking": False},
)
response = await serving.render_responses_request(request)
assert not isinstance(response, ErrorResponse)
assert response.reasoning_parser_kwargs is not None
kwargs = response.reasoning_parser_kwargs.chat_template_kwargs
assert kwargs["enable_thinking"] is False
@pytest.fixture(scope="module")
def server():
args: list[str] = ["--trust-request-chat-template"]
@@ -1123,7 +1123,8 @@ async def test_stream_with_logprobs():
lp = dc["choices"][0]["logprobs"]
assert lp is not None
assert len(lp["content"]) == 1
assert lp["content"][0]["token"].startswith("token_id:")
assert isinstance(lp["content"][0]["token_id"], int)
assert "token" not in lp["content"][0]
@pytest.mark.asyncio
@@ -168,6 +168,20 @@ def test_render_extracts_metadata_fields_separately():
assert torch.equal(full_data["pixel_values"].data, pixel_values.data)
def test_extract_without_kwargs_keeps_layout():
"""Layout-only callers get hashes and placeholders, no serialized tensors."""
engine_input, _pixel_values, _image_grid_thw = _image_engine_input()
full = extract_mm_features(engine_input)
layout = extract_mm_features(engine_input, include_mm_kwargs=False)
assert full is not None and layout is not None
assert layout.kwargs_data is None
assert layout.mm_metadata is None
assert layout.mm_hashes == full.mm_hashes
assert layout.mm_placeholders == full.mm_placeholders
def test_extract_includes_declared_placeholder_metadata_fields():
"""EC placeholder metadata is kept even when keep_on_cpu is unset."""
engine_input, _pixel_values, image_grid_thw = _image_engine_input(
@@ -124,6 +124,14 @@ def test_generate_request_rejects_placeholder_outside_prompt():
)
def test_reasoning_parser_kwargs_rejects_unknown_keys():
"""The engine splats these into its reasoning parser's constructor, so a
client must not be able to pass arbitrary keyword arguments."""
payload = {**_base_payload(), "reasoning_parser_kwargs": {"tokenizer": None}}
with pytest.raises(ValidationError, match="tokenizer"):
GenerateRequest.model_validate(payload)
def test_output_mode_defaults_to_tokens():
assert GenerateRequest.model_validate(_base_payload()).output_mode == "tokens"
@@ -5,8 +5,8 @@
Mirrors test_serving_tokens.py but exercises the multimodal piping
using Qwen/Qwen3-VL-2B-Instruct end-to-end via the server's /render ->
/generate -> /detokenize path. Intentionally avoids running the HF
processor in the pytest parent process to keep os.fork() in sibling
tests (e.g. test_weight_transfer_llm.py) deadlock-free.
processor in the pytest parent process to keep os.fork() in other
tests (e.g. entrypoints/rl/weight_transfer/test_offline.py) deadlock-free.
"""
import httpx
@@ -14,7 +14,6 @@ from transformers import AutoTokenizer
import vllm.envs as envs
from tests.utils import RemoteOpenAIServer
from vllm.config import ModelConfig
from vllm.config.utils import getattr_iter
from vllm.v1.engine.detokenizer import check_stop_strings
MODEL_NAME = "Qwen/Qwen3-0.6B"
@@ -183,7 +182,7 @@ async def test_generate_sampling_mask(client):
assert token_id in support
# processed_logprobs: exactly the support carries finite probability.
for top in entry["top_logprobs"]:
in_support = int(top["token"].removeprefix("token_id:")) in support
in_support = top["token_id"] in support
assert in_support == (top["logprob"] > -9999.0)
@@ -402,14 +401,7 @@ async def test_same_response_as_chat_completions(client, tokenizer, messages):
# Post-EOS generation is undefined and may differ
eos_tokens = {
tokenizer.eos_token_id,
*getattr_iter(
tokenizer,
[
"extra_special_tokens_ids", # Transformers v5
"additional_special_tokens_ids", # Transformers v4
],
[],
),
*tokenizer.extra_special_tokens_ids,
}
# Find first EOS in generated tokens
eos_pos = None
@@ -589,6 +581,83 @@ async def test_generate_with_lora_adapter(client, tokenizer, messages):
assert generate_res == completions_res
def _structured_chat_body(messages, **overrides) -> dict:
return {
"model": MODEL_NAME,
"messages": messages,
"max_tokens": 64,
"temperature": 0.0,
"chat_template_kwargs": {"enable_thinking": True},
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "answer",
"schema": {
"type": "object",
"properties": {"count": {"type": "integer"}},
"required": ["count"],
},
},
},
**overrides,
}
async def _render_then_generate(client, body) -> tuple[dict, list[int]]:
render_resp = await client.post("/v1/chat/completions/render", json=body)
render_resp.raise_for_status()
generate_request = render_resp.json()
generate_resp = await client.post(GEN_ENDPOINT, json=generate_request)
generate_resp.raise_for_status()
return generate_request, generate_resp.json()["choices"][0]["token_ids"]
# deepseek_v3 reads `enable_thinking` from the template kwargs and uses Qwen3's
# <think> tokens, so the engine gates structured outputs differently when
# either reasoning field is dropped between render and generate.
@pytest.mark.asyncio
@pytest.mark.skipif(
envs.VLLM_USE_RUST_FRONTEND,
reason="the Rust frontend does not forward reasoning fields to the engine",
)
@pytest.mark.parametrize(
"server", [["--reasoning-parser", "deepseek_v3"]], indirect=True
)
async def test_render_then_generate_forwards_reasoning_parser_kwargs(client, messages):
"""With thinking on, structured outputs must wait for the reasoning to
end on generate, the same as on chat."""
body = _structured_chat_body(messages, return_token_ids=True)
chat_resp = await client.post("/v1/chat/completions", json=body)
chat_resp.raise_for_status()
generate_request, token_ids = await _render_then_generate(client, body)
assert generate_request["reasoning_ended"] is False
assert token_ids == chat_resp.json()["choices"][0]["token_ids"]
@pytest.mark.asyncio
@pytest.mark.skipif(
envs.VLLM_USE_RUST_FRONTEND,
reason="the Rust frontend does not forward reasoning fields to the engine",
)
@pytest.mark.parametrize(
"server", [["--reasoning-parser", "deepseek_v3"]], indirect=True
)
async def test_render_then_generate_forwards_reasoning_ended(
client, tokenizer, messages
):
"""`include_reasoning=false` constrains from the first token on chat, so
generate must too, even though the engine's parser expects thinking."""
body = _structured_chat_body(messages, include_reasoning=False)
generate_request, token_ids = await _render_then_generate(client, body)
assert generate_request["reasoning_ended"] is True
output = json.loads(tokenizer.decode(token_ids, skip_special_tokens=True))
assert isinstance(output["count"], int)
def _chat_prompt_token_ids(tokenizer, messages) -> list[int]:
return tokenizer.apply_chat_template(
messages,
@@ -1,22 +1,62 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
from unittest.mock import MagicMock
import pytest
from pydantic import ValidationError
from vllm.entrypoints.scale_out.token_in_token_out.protocol import GenerateLogProb
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
from vllm.logprobs import Logprob
def test_top_logprobs_alternatives_have_own_token_ids():
"""Each top_logprobs alternative must carry its own token_id placeholder."""
"""Each top_logprobs alternative must carry its own integer token id."""
result = ServingTokens._create_tokens_logprobs(
None,
token_ids=[262],
top_logprobs=[{262: Logprob(-0.1), 257: Logprob(-1.2), 428: Logprob(-2.3)}],
num_output_top_logprobs=2,
)
tokens = {e.token for e in result.content[0].top_logprobs}
assert tokens == {"token_id:262", "token_id:257"}, f"got {tokens}"
token_ids = {e.token_id for e in result.content[0].top_logprobs}
assert token_ids == {262, 257}, f"got {token_ids}"
def test_sampled_entry_carries_token_id_and_rank():
"""The sampled token is identified by id, and the engine's rank survives."""
result = ServingTokens._create_tokens_logprobs(
None,
token_ids=[262],
top_logprobs=[
{262: Logprob(-0.1, rank=1), 257: Logprob(-1.2, rank=2)},
],
num_output_top_logprobs=2,
)
entry = result.content[0]
assert entry.token_id == 262
assert entry.logprob == -0.1
assert entry.rank == 1
assert [(t.token_id, t.rank) for t in entry.top_logprobs] == [(262, 1), (257, 2)]
# No tokenizer on the generate server: no string token, no bytes.
assert not hasattr(entry, "token")
assert not hasattr(entry, "bytes")
def test_sampled_token_absent_from_topk_uses_sentinel():
"""A sampled token missing from the engine's map keeps the -9999.0 sentinel."""
result = ServingTokens._create_tokens_logprobs(
None,
token_ids=[5],
top_logprobs=[{7: Logprob(-0.9)}],
num_output_top_logprobs=1,
)
entry = result.content[0]
assert entry.token_id == 5
assert entry.logprob == -9999.0
assert entry.rank is None
assert entry.top_logprobs == []
def test_logprobs_zero_emits_sampled_token():
@@ -40,21 +80,23 @@ def test_logprobs_minus_one_emits_all_tokens():
assert len(result.content[0].top_logprobs) == 2
def test_tokens_level_logprobs_have_no_bytes():
result = ServingTokens._create_tokens_logprobs(
def test_text_logprobs_without_tokenizer_are_placeholders_without_bytes():
"""--return-tokens-as-token-ids keeps `token_id:N` placeholders in text mode."""
result = ServingTokens._create_text_logprobs(
None,
token_ids=[7],
top_logprobs=[{7: Logprob(-0.9), 8: Logprob(-1.1)}],
num_output_top_logprobs=2,
)
entry = result.content[0]
assert entry.token == "token_id:7"
assert entry.bytes is None
assert all(t.bytes is None for t in entry.top_logprobs)
def test_resolved_logprobs_use_engine_decoded_tokens_and_bytes():
tokenizer = MagicMock()
result = ServingTokens._create_tokens_logprobs(
result = ServingTokens._create_text_logprobs(
None,
token_ids=[7],
top_logprobs=[
@@ -75,7 +117,7 @@ def test_resolved_logprobs_use_engine_decoded_tokens_and_bytes():
def test_resolved_logprobs_decode_tokens_the_engine_did_not():
tokenizer = MagicMock()
tokenizer.decode.side_effect = lambda ids: f"<{ids[0]}>"
result = ServingTokens._create_tokens_logprobs(
result = ServingTokens._create_text_logprobs(
None,
token_ids=[7, 9],
top_logprobs=[{7: Logprob(-0.9)}, None],
@@ -85,3 +127,59 @@ def test_resolved_logprobs_decode_tokens_the_engine_did_not():
assert [e.token for e in result.content] == ["<7>", "<9>"]
assert result.content[0].top_logprobs[0].token == "<7>"
assert result.content[1].bytes == list(b"<9>")
def test_sampled_token_outside_topk_comes_first():
"""The engine puts the sampled token first, then ranks 1..k. When the
sampled token is outside the top k it takes one of the k slots, so rank k
is left out (same as the OpenAI endpoints)."""
result = ServingTokens._create_tokens_logprobs(
None,
token_ids=[50],
top_logprobs=[
{
50: Logprob(-3.0, rank=5),
10: Logprob(-0.2, rank=1),
20: Logprob(-1.0, rank=2),
}
],
num_output_top_logprobs=2,
)
assert [t.rank for t in result.content[0].top_logprobs] == [5, 1]
def test_logprob_is_required_on_the_wire():
"""A payload missing logprob is rejected rather than read as -9999."""
with pytest.raises(ValidationError):
GenerateLogProb.model_validate({"token_id": 1})
def test_rank_zero_from_a_nan_logprob_is_none():
"""The engine reports rank 0 for a sampled token whose logprob is NaN."""
result = ServingTokens._create_tokens_logprobs(
None,
token_ids=[7],
top_logprobs=[{7: Logprob(float("nan"), rank=0), 8: Logprob(-0.2, rank=1)}],
num_output_top_logprobs=1,
)
entry = result.content[0]
assert entry.rank is None
assert entry.top_logprobs[0].rank is None
# Clamped like the Rust frontend (max(nan, x) is nan in Python).
assert entry.logprob == -9999.0
assert entry.top_logprobs[0].logprob == -9999.0
json.dumps(result.model_dump(), allow_nan=False)
def test_text_logprobs_clamp_a_nan_logprob():
result = ServingTokens._create_text_logprobs(
None,
token_ids=[7],
top_logprobs=[{7: Logprob(float("nan"), rank=0, decoded_token="a")}],
num_output_top_logprobs=1,
tokenizer=MagicMock(),
)
entry = result.content[0]
assert entry.logprob == -9999.0
assert entry.top_logprobs[0].logprob == -9999.0
json.dumps(result.model_dump(), allow_nan=False)
@@ -23,6 +23,7 @@ BADREQUEST_CASES = [
"is greater than max_lora_rank",
),
("test_dora", {"use_dora": True}, "does not yet support DoRA"),
("test_pissa", {"init_lora_weights": "pissa"}, "init_lora_weights='pissa'"),
(
"test_modules_to_save",
{"modules_to_save": ["lm_head"]},
@@ -0,0 +1,86 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from unittest.mock import AsyncMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from vllm.entrypoints.serve.profile.api_router import router
@pytest.fixture
def engine_client() -> AsyncMock:
return AsyncMock()
@pytest.fixture
def client(engine_client: AsyncMock) -> TestClient:
app = FastAPI()
app.state.engine_client = engine_client
app.include_router(router)
return TestClient(app)
def test_start_profile_without_body_is_backwards_compatible(
client: TestClient, engine_client: AsyncMock
) -> None:
response = client.post("/start_profile")
assert response.status_code == 200
engine_client.start_profile.assert_awaited_once_with()
def test_start_profile_ignores_completion_payload(
client: TestClient, engine_client: AsyncMock
) -> None:
response = client.post(
"/start_profile",
json={
"model": "Qwen/Qwen3-0.6B",
"prompt": "profile this request",
"max_tokens": 16,
"stream": False,
},
)
assert response.status_code == 200
engine_client.start_profile.assert_awaited_once_with()
def test_start_profile_forwards_session_overrides(
client: TestClient, engine_client: AsyncMock
) -> None:
response = client.post(
"/start_profile",
json={
"profile_prefix": "sharegpt_run-1",
"delay_iterations": 5000,
"max_iterations": 20,
},
)
assert response.status_code == 200
engine_client.start_profile.assert_awaited_once_with(
profile_prefix="sharegpt_run-1",
delay_iterations=5000,
max_iterations=20,
)
@pytest.mark.parametrize(
"body",
[
{"profile_prefix": 1},
{"delay_iterations": "1"},
{"max_iterations": "20"},
],
)
def test_start_profile_rejects_wrongly_typed_overrides(
client: TestClient, engine_client: AsyncMock, body: dict
) -> None:
response = client.post("/start_profile", json=body)
assert response.status_code == 422
engine_client.start_profile.assert_not_awaited()
@@ -4,6 +4,9 @@
import logging
from unittest.mock import MagicMock, patch
import pytest
from vllm.entrypoints.openai.completion.protocol import CompletionRequest
from vllm.entrypoints.serve.utils.request_logger import RequestLogger
@@ -269,3 +272,18 @@ def test_streaming_complete_logs_full_text_content():
assert call_args[1] == "test-streaming-full-text"
assert call_args[2] == " (streaming complete)"
assert call_args[4] == "streaming_complete"
@pytest.mark.parametrize("max_log_len", [None, 10])
def test_request_logger_log_request_body_truncation(max_log_len):
"""The JSON body is logged in full unless max_log_len truncates it."""
request = CompletionRequest(model="test-model", prompt="Hello, world!")
full_body = request.model_dump_json(exclude_unset=True)
mock_logger = MagicMock()
with patch("vllm.entrypoints.serve.utils.request_logger.logger", mock_logger):
RequestLogger(max_log_len=max_log_len).log_request_body(request)
mock_logger.debug.assert_called_once()
logged_body = mock_logger.debug.call_args.args[2]
assert logged_body == full_body[:max_log_len]
@@ -4,6 +4,7 @@
import asyncio
import json
import warnings
from types import SimpleNamespace
import numpy as np
import pybase64 as base64
@@ -12,6 +13,7 @@ import websockets
from tests.utils import ROCM_EXTRA_ARGS, RemoteOpenAIServer
from vllm.assets.audio import AudioAsset
from vllm.entrypoints.speech_to_text.realtime.connection import RealtimeConnection
from vllm.multimodal.media.audio import load_audio
MISTRAL_FORMAT_ARGS = [
@@ -26,6 +28,46 @@ MISTRAL_FORMAT_ARGS = [
MODEL_NAME = "mistralai/Voxtral-Mini-4B-Realtime-2602"
def test_realtime_generation_preserves_watermarking():
transcription_outputs = []
class EngineClient:
def generate(self, **kwargs):
async def outputs():
output = SimpleNamespace(
outputs=[],
prompt_token_ids=[],
is_watermarked=kwargs["sampling_params"].watermarking,
)
transcription_outputs.append(output)
yield output
return outputs()
async def streaming_input():
chunk: np.ndarray
for chunk in ():
yield chunk
async def send(_event):
return None
connection = object.__new__(RealtimeConnection)
connection.connection_id = "test"
connection.serving = SimpleNamespace(
model_cls=SimpleNamespace(realtime_max_tokens=1),
engine_client=EngineClient(),
)
connection.audio_queue = asyncio.Queue()
connection._is_connected = True
connection.send = send
asyncio.run(connection._run_generation(streaming_input(), asyncio.Queue()))
assert len(transcription_outputs) == 1
assert transcription_outputs[0].is_watermarked is None
def _get_websocket_url(server: RemoteOpenAIServer) -> str:
"""Convert HTTP URL to WebSocket URL for realtime endpoint."""
http_url = server.url_root
@@ -198,4 +198,6 @@ async def test_language_detection_cancel_aborts_engine_request():
with pytest.raises(asyncio.CancelledError):
await task
sampling_params = engine_client.generate.call_args.args[1]
assert sampling_params.watermarking is False
engine_client.abort.assert_awaited_once_with(request_id)
@@ -24,6 +24,10 @@ def server():
"4096",
"--max-num-seqs",
"2",
# Streaming and non-streaming runs must match bitwise; a prefix-cache
# hit resumes the second from a mid-prefill Mamba checkpoint, whose
# numerics differ slightly from the cold single-pass prefill.
"--no-enable-prefix-caching",
]
with RemoteOpenAIServer(model, args_for_model, max_wait_seconds=480) as server:
yield server
@@ -13,6 +13,12 @@ request models whose before-validators were missing the same guard.
import pytest
from pydantic import ValidationError
from vllm.entrypoints.generate.generative_scoring.serving import (
GenerativeScoringRequest,
)
from vllm.entrypoints.generate.structured_decisions.protocol import (
StructuredDecisionRequest,
)
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.openai.completion.protocol import CompletionRequest
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
@@ -28,6 +34,7 @@ from vllm.exceptions import VLLMValidationError
pytestmark = pytest.mark.skip_global_cleanup
REQUEST_MODELS = [
GenerativeScoringRequest,
CompletionRequest,
ResponsesRequest,
EmbeddingChatRequest,
@@ -74,6 +81,26 @@ def test_tokenize_chat_request_still_validates_dict_bodies():
CACHE_SALT_MODELS = [
(
GenerativeScoringRequest,
{
"query": "Is this city the capital of France?",
"items": ["Paris"],
"label_token_ids": [9454, 2753],
},
),
(
StructuredDecisionRequest,
{
"state": "hello",
"questions": {
"lang": {
"type": "choice",
"criteria": {"English": "Text written in English."},
}
},
},
),
(CompletionRequest, {"prompt": "hello"}),
(ChatCompletionRequest, {"messages": [{"role": "user", "content": "hello"}]}),
(ResponsesRequest, {"input": "hello"}),
@@ -4,7 +4,7 @@
import pytest
from vllm import SamplingParams
from vllm.entrypoints.offline_utils import OfflineInferenceMixin
from vllm.entrypoints.common.offline import OfflineInferenceMixin
from vllm.exceptions import VLLMValidationError
from vllm.lora.request import LoRARequest
+16
View File
@@ -21,6 +21,22 @@ vllm serve Qwen/Qwen2.5-1.5B-Instruct --port 8000
python tests/evals/gsm8k/gsm8k_eval.py --port 8000
```
For chat-only models, send the prompts through `/v1/chat/completions`:
```bash
python tests/evals/gsm8k/gsm8k_eval.py --port 8000 \
--use-chat-completions --max-tokens 1024 \
--chat-template-kwargs '{"enable_thinking": false}'
```
The server applies the chat template and uses its served model, so `--model` is
optional. In chat mode, `temperature` is sent only when `--temperature` is given,
so the server's default sampling applies otherwise; completions mode keeps the
default of 0. Chat mode sends no stop strings; completions mode keeps them.
`--reasoning-effort`, `--top-p`, and `--top-k` set the matching request fields
when given. With a reasoning parser, only the final answer `content` is scored.
`--save-results` records the request settings used.
## Configuration Format
Model configs in `configs/` directory use this YAML format:
@@ -0,0 +1,15 @@
model_name: "nvidia/DeepSeek-V4.1-Flash-NVFP4"
accuracy_threshold: 0.88
tolerance: 0.03
# The bundled DSpark draft (mtp.*) stays MXFP4 in this checkpoint. Loading it
# as NVFP4 keeps accuracy but drops acceptance length to 1.0 (3.57 when correct).
min_acceptance_length: 2.5
num_questions: 1319
num_fewshot: 5
startup_max_wait_seconds: 1800
server_args: >-
--tokenizer-mode deepseek_v41
--trust-remote-code
--max-model-len 8192
--tensor-parallel-size 4
--speculative-config '{"method":"dspark","num_speculative_tokens":5}'
@@ -0,0 +1,14 @@
model_name: "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4"
accuracy_threshold: 0.93
num_questions: 1319
num_fewshot: 5
startup_max_wait_seconds: 1200
server_args: >-
--enforce-eager
--max-model-len 4096
--tensor-parallel-size 2
--enable-expert-parallel
--mamba-backend flashinfer
--moe-backend flashinfer_trtllm
--quantization-config.moe.activation nvfp4_per_token
--speculative-config '{"method":"mtp","num_speculative_tokens":5}'
@@ -1,3 +1,4 @@
Qwen3-Next-80B-A3B-NVFP4-EP2.yaml
Qwen3-Next-FP8-EP2.yaml
Nemotron-3-Super-120B-A12B-NVFP4.yaml
Nemotron-3-Super-120B-A12B-NVFP4-per-token.yaml
@@ -1,2 +1,3 @@
DeepSeek-V4-Flash-DSpark-confidence-TEP4.yaml
Kimi-K3-pruned75-DSpark-TP4.yaml
DeepSeek-V4.1-Flash-NVFP4-DSpark-TP4.yaml
+123 -20
View File
@@ -76,14 +76,20 @@ def get_answer_value(answer_str: str) -> int:
return INVALID
def _optional_params(**params: object) -> dict[str, object]:
return {k: v for k, v in params.items() if v is not None}
async def call_vllm_api(
session: aiohttp.ClientSession,
prompt: str,
temperature: float,
temperature: float | None,
max_tokens: int,
stop: list[str] | None = None,
url: str | None = None,
seed: int | None = None,
top_p: float | None = None,
top_k: int | None = None,
) -> tuple[str, int]:
"""Call vLLM's OpenAI-compatible completions endpoint.
@@ -93,12 +99,12 @@ async def call_vllm_api(
"""
data = {
"prompt": prompt,
"temperature": temperature,
"max_tokens": max_tokens,
"stop": stop,
}
if seed is not None:
data["seed"] = seed
data.update(
_optional_params(temperature=temperature, seed=seed, top_p=top_p, top_k=top_k)
)
try:
async with session.post(f"{url}/v1/completions", json=data) as response:
@@ -114,24 +120,45 @@ async def call_vllm_api(
async def call_vllm_chat_api(
session: aiohttp.ClientSession,
model: str,
model: str | None,
prompt: str,
temperature: float,
temperature: float | None,
max_tokens: int,
stop: list[str] | None = None,
url: str | None = None,
seed: int | None = None,
top_p: float | None = None,
top_k: int | None = None,
reasoning_effort: str | None = None,
chat_template_kwargs: dict[str, object] | None = None,
) -> tuple[str, int]:
"""Call vLLM's OpenAI-compatible chat completions endpoint."""
"""Call vLLM's OpenAI-compatible chat completions endpoint.
``model``, ``temperature``, ``stop`` and the other optional fields are
omitted from the request when ``None``, so the server defaults apply (vLLM
uses its served model when ``model`` is omitted).
Returns:
Tuple of (final answer content, completion_tokens). Reasoning returned
separately by a reasoning parser is not part of the answer.
"""
data = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": temperature,
"max_tokens": max_tokens,
"stop": stop,
}
if seed is not None:
data["seed"] = seed
data.update(
_optional_params(
stop=stop,
model=model,
temperature=temperature,
seed=seed,
top_p=top_p,
top_k=top_k,
reasoning_effort=reasoning_effort,
chat_template_kwargs=chat_template_kwargs,
)
)
try:
async with session.post(f"{url}/v1/chat/completions", json=data) as response:
@@ -214,16 +241,34 @@ def evaluate_gsm8k(
use_chat_completions: bool = False,
host: str = "http://127.0.0.1",
port: int = 8000,
temperature: float = 0.0,
temperature: float | None = 0.0,
seed: int | None = 42,
request_timeout_seconds: float = 600,
gen_prefix: str = "",
max_concurrency: int | None = None,
top_p: float | None = None,
top_k: int | None = None,
reasoning_effort: str | None = None,
chat_template_kwargs: dict[str, object] | None = None,
) -> dict[str, float | int]:
"""Evaluate GSM8K accuracy using vLLM serve endpoint.
``temperature``, ``top_p`` and ``top_k`` are sent only when not ``None``;
otherwise the server default applies. ``model`` is used only in chat mode,
where it may be ``None`` (the server uses its served model).
``reasoning_effort`` and ``chat_template_kwargs`` require
``use_chat_completions=True``. Stop strings are sent only in completions
mode.
Returns dict with accuracy, invalid_rate, latency, etc.
"""
if not use_chat_completions and (
reasoning_effort is not None or chat_template_kwargs is not None
):
raise ValueError(
"reasoning_effort and chat_template_kwargs require "
"use_chat_completions=True"
)
base_url = f"{host}:{port}"
prompts, labels = _build_gsm8k_prompts(num_questions, num_shots, gen_prefix)
num_questions = len(prompts)
@@ -233,19 +278,21 @@ def evaluate_gsm8k(
output_tokens: list[int] = [0] * num_questions
async def get_answer(session: aiohttp.ClientSession, i: int) -> tuple[str, int]:
stop = ["Question", "Assistant:", "<|separator|>"]
if use_chat_completions:
if model is None:
raise ValueError("model is required for chat completions")
# No stop strings: the chat template delimits the turn, and they
# would also cut off reasoning.
answer, tokens = await call_vllm_chat_api(
session=session,
model=model,
prompt=prompts[i],
temperature=temperature,
max_tokens=max_tokens,
stop=stop,
url=base_url,
seed=seed,
top_p=top_p,
top_k=top_k,
reasoning_effort=reasoning_effort,
chat_template_kwargs=chat_template_kwargs,
)
else:
answer, tokens = await call_vllm_api(
@@ -253,9 +300,11 @@ def evaluate_gsm8k(
prompt=prompts[i],
temperature=temperature,
max_tokens=max_tokens,
stop=stop,
stop=["Question", "Assistant:", "<|separator|>"],
url=base_url,
seed=seed,
top_p=top_p,
top_k=top_k,
)
states[i] = answer
output_tokens[i] = tokens
@@ -352,7 +401,38 @@ def main() -> None:
parser.add_argument("--host", type=str, default="http://127.0.0.1", help="Host URL")
parser.add_argument("--port", type=int, default=8000, help="Port number")
parser.add_argument(
"--temperature", type=float, default=0.0, help="Temperature for generation"
"--temperature",
type=float,
help="Temperature for generation (default: 0 for completions; "
"server default with --use-chat-completions)",
)
parser.add_argument(
"--top-p", type=float, help="Top-p for generation (server default if unset)"
)
parser.add_argument(
"--top-k", type=int, help="Top-k for generation (server default if unset)"
)
parser.add_argument(
"--use-chat-completions",
action="store_true",
help="Send each few-shot prompt as a user message to /v1/chat/completions "
"instead of /v1/completions (for chat-only models)",
)
parser.add_argument(
"--model",
type=str,
help="Model name to send with chat requests (default: omitted, so the "
"server uses its served model)",
)
parser.add_argument(
"--reasoning-effort",
type=str,
help="reasoning_effort for chat completions, e.g. none, low, high",
)
parser.add_argument(
"--chat-template-kwargs",
type=json.loads,
help="JSON chat_template_kwargs, e.g. '{\"enable_thinking\": false}'",
)
parser.add_argument(
"--seed", type=int, default=42, help="Random seed for reproducibility"
@@ -371,6 +451,9 @@ def main() -> None:
parser.add_argument("--save-results", type=str, help="Save results to JSON file")
args = parser.parse_args()
temperature = args.temperature
if temperature is None and not args.use_chat_completions:
temperature = 0.0
result = evaluate_gsm8k(
num_questions=args.num_questions,
@@ -378,10 +461,16 @@ def main() -> None:
max_tokens=args.max_tokens,
host=args.host,
port=args.port,
temperature=args.temperature,
temperature=temperature,
seed=args.seed,
max_concurrency=args.max_concurrency,
request_timeout_seconds=args.request_timeout_seconds,
model=args.model,
use_chat_completions=args.use_chat_completions,
top_p=args.top_p,
top_k=args.top_k,
reasoning_effort=args.reasoning_effort,
chat_template_kwargs=args.chat_template_kwargs,
)
# Print results to terminal
@@ -395,6 +484,20 @@ def main() -> None:
# Optional file saving
if args.save_results:
# None means the field was not sent and the server default applied.
result["request_params"] = {
"endpoint": "chat" if args.use_chat_completions else "completions",
"model": args.model,
"temperature": temperature,
"top_p": args.top_p,
"top_k": args.top_k,
"seed": args.seed,
"stop": None
if args.use_chat_completions
else ["Question", "Assistant:", "<|separator|>"],
"reasoning_effort": args.reasoning_effort,
"chat_template_kwargs": args.chat_template_kwargs,
}
with open(args.save_results, "w") as f:
json.dump(result, f, indent=2)
print(f"Results saved to {args.save_results}")
@@ -21,6 +21,7 @@ from vllm.model_executor.kernels.linear.nvfp4.base import (
NvFp4LinearLayerConfig,
)
from vllm.model_executor.kernels.linear.nvfp4.flashinfer import (
FlashInferCuteDslNvFp4LinearKernel,
FlashInferCutlassNvFp4LinearKernel,
FlashInferTrtllmNvFp4LinearKernel,
)
@@ -59,6 +60,7 @@ from vllm.platforms import current_platform
SUPPORTING = {
CutlassFP8ScaledMMLinearKernel,
FlashInferFP8ScaledMMLinearKernel,
FlashInferCuteDslNvFp4LinearKernel,
FlashInferCutlassNvFp4LinearKernel,
PerTensorTorchFP8ScaledMMLinearKernel,
AiterHipbMMPerTokenFp8ScaledMMLinearKernel,
+4 -1
View File
@@ -65,10 +65,13 @@ def _fake_tilelang_import_modules():
key, _ = self.func.parse_args(*args, **kwargs)
kernel = self._kernel_cache.get(key)
if kernel is None:
kernel = "compiled"
kernel = self.compile(*args, **kwargs)
self._kernel_cache[key] = kernel
return kernel
def compile(self, *args, **kwargs):
return "compiled"
fake_kernel = cast(Any, ModuleType("tilelang.jit.kernel"))
fake_kernel.JITKernel = FakeJITKernel
+1 -1
View File
@@ -472,7 +472,7 @@ def varlen_with_paged_kv(
scale = head_size**-0.5
token_num = sum(query_lens)
dynamic_causal_tensor = (
torch.tensor(dynamic_causal, dtype=torch.bool)
torch.tensor(dynamic_causal, dtype=torch.int32)
if dynamic_causal is not None
else None
)
@@ -6,6 +6,7 @@ import pytest
from vllm.platforms import current_platform
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.kv_cache_layout import KVCacheLayout
try:
import flashinfer
@@ -702,3 +703,35 @@ def test_flashinfer_decode_with_paged_fp8_kv(
torch.testing.assert_close(output, ref_output, atol=2e-2, rtol=1e-2),
f"{torch.max(torch.abs(output - ref_output))}",
)
@pytest.mark.skipif(
not any(current_platform.is_device_capability_family(f) for f in (80, 90, 120)),
reason="NVFP4 fa2 path",
)
@pytest.mark.parametrize("layout", ["LBNHC", "LBHNC", "BLNHC", "BLHNC"])
def test_flashinfer_nvfp4_kv_cache_update(default_vllm_config, layout):
from vllm.v1.attention.backends import flashinfer as fi
torch.set_default_device("cuda")
order = KVCacheLayout[layout].stride_order
# [L, B, 2H, N, 64 + 8] NVFP4 pages for two layers; layer 1 is written.
shape = (2, 6, 4, 16, 64 + 8)
layers = torch.zeros([shape[i] for i in order], dtype=torch.uint8)
layers = layers.permute(*(order.index(i) for i in range(5)))
one = torch.ones(())
layer = torch.nn.Module()
layer._k_scale = layer._v_scale = one
kv = torch.randn(2, 96, 2, 128, dtype=torch.bfloat16)
impl = fi.FlashInferImpl(4, 128, 1.0, 2, None, None, "nvfp4")
impl.do_kv_cache_update(layer, kv[0], kv[1], layers[1], torch.arange(96))
data, scales, kv_layout = fi._nvfp4_kv_views(layers[1], 2)
pages = torch.arange(6, dtype=torch.int32)[None]
seq_lens = torch.tensor([96], dtype=torch.int32)
deq = torch.empty_like(kv)[:, None]
flashinfer.nvfp4_kv_dequantize_paged(
data, scales, pages, seq_lens, one, one, *deq, kv_layout
)
assert ((deq[:, 0] - kv).norm() / kv.norm()) < 0.2
assert not layers[0].any()

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