Merge remote-tracking branch 'origin/main' into lesj/qwen4exp-bugfixes
Both sides edited the same import block in the Qwen4Exp NVIDIA and AMD
models and nothing else collided. This branch adds
`from ..common.mtp import make_mtp_hidden_buffer`, the helper the MTP
buffer extraction calls; upstream ec4a3a5370 widened the `..config`
import to `ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig` for the
layer-type constants it introduced. The two changes are independent, so
the resolution keeps both lines. Every symbol still has a use outside the
import in both files.
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
@@ -89,7 +89,7 @@ TARGET_TEST_SUITE = _resolve_target_test_suite()
|
||||
condition=current_platform.is_rocm(),
|
||||
)
|
||||
def test_vllm_gc_ed():
|
||||
"""Verify vllm instance is GC'ed when it is deleted"""
|
||||
"""Verify vllm instance is GC'ed when it is deleted."""
|
||||
llm = LLM("hmellor/tiny-random-LlamaForCausalLM")
|
||||
weak_llm = weakref.ref(llm)
|
||||
del llm
|
||||
|
||||
@@ -51,8 +51,7 @@ def _wake_up_with_poisoned_mappings(allocator, byte_value: int = 0xA5) -> None:
|
||||
|
||||
@create_new_process_for_each_test("fork" if current_platform.is_cuda() else "spawn")
|
||||
def test_python_error():
|
||||
"""
|
||||
Test if Python error occurs when there's low-level
|
||||
"""Test if Python error occurs when there's low-level
|
||||
error happening from the C++ side.
|
||||
"""
|
||||
allocator = get_mem_allocator_instance()
|
||||
|
||||
@@ -228,7 +228,7 @@ def test_decode_span_identity_is_exact(
|
||||
api_url: str,
|
||||
chat: bool,
|
||||
) -> None:
|
||||
"""latency - ttft must equal sum(itl) exactly.
|
||||
"""Latency - ttft must equal sum(itl) exactly.
|
||||
|
||||
On a scripted clock this can only drift if a code path reads the clock an
|
||||
extra time or attributes a read to the wrong event.
|
||||
|
||||
+1
-3
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
These envs only work for a small part of the tests, fix what you need!
|
||||
"""
|
||||
"""These envs only work for a small part of the tests, fix what you need!"""
|
||||
|
||||
import os
|
||||
from collections.abc import Callable
|
||||
|
||||
@@ -29,8 +29,7 @@ logger = init_logger("vllm.tests.compile.backend")
|
||||
|
||||
|
||||
class LazyInitPass(InductorPass):
|
||||
"""
|
||||
If there's a pass that we want to initialize lazily in a test,
|
||||
"""If there's a pass that we want to initialize lazily in a test,
|
||||
we can wrap it in LazyInitPass, which will initialize the pass when invoked
|
||||
and then immediately invoke it.
|
||||
"""
|
||||
@@ -45,8 +44,7 @@ class LazyInitPass(InductorPass):
|
||||
|
||||
|
||||
class TestBackend:
|
||||
"""
|
||||
This class provides a simple Inductor backend that can be used for testing.
|
||||
"""This class provides a simple Inductor backend that can be used for testing.
|
||||
It takes a list of custom passes and runs them after Inductor's passes.
|
||||
It also saves the graph before and after the custom passes for inspection.
|
||||
|
||||
|
||||
@@ -11,8 +11,7 @@ from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
@pytest.fixture
|
||||
def mock_cuda_platform():
|
||||
"""
|
||||
Fixture that returns a factory for creating mocked CUDA platforms.
|
||||
"""Fixture that returns a factory for creating mocked CUDA platforms.
|
||||
|
||||
Usage:
|
||||
def test_something(mock_cuda_platform):
|
||||
@@ -51,8 +50,7 @@ def mock_cuda_platform():
|
||||
|
||||
@pytest.fixture
|
||||
def mock_xpu_platform():
|
||||
"""
|
||||
Fixture that returns a factory for creating mocked XPU platforms.
|
||||
"""Fixture that returns a factory for creating mocked XPU platforms.
|
||||
|
||||
Usage:
|
||||
def test_something(mock_xpu_platform):
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# 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.
|
||||
"""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
|
||||
|
||||
@@ -17,8 +17,7 @@ from vllm.v1.attention.backends.registry import AttentionBackendEnum
|
||||
|
||||
@contextlib.contextmanager
|
||||
def temporary_environ(env_vars):
|
||||
"""
|
||||
Temporarily set environment variables and restore them afterward.
|
||||
"""Temporarily set environment variables and restore them afterward.
|
||||
We have to do this vs monkeypatch because monkeypatch doesn't work
|
||||
with "module" scoped fixtures.
|
||||
"""
|
||||
@@ -125,8 +124,7 @@ def llm_pair(request):
|
||||
indirect=True,
|
||||
)
|
||||
class TestFullCUDAGraph:
|
||||
"""
|
||||
Use a class such that an llm pair is constructed once for all
|
||||
"""Use a class such that an llm pair is constructed once for all
|
||||
batch_size/max_tokens combinations and released immediately after.
|
||||
|
||||
Module-scope fixtures would stick around the whole time,
|
||||
@@ -149,11 +147,9 @@ class TestFullCUDAGraph:
|
||||
],
|
||||
)
|
||||
def test_full_cudagraph(self, batch_size, max_tokens, llm_pair: tuple[LLM, LLM]):
|
||||
"""
|
||||
Test various batch sizes and max_tokens to ensure that the
|
||||
"""Test various batch sizes and max_tokens to ensure that the
|
||||
full cudagraph compilation works for padded cases too.
|
||||
"""
|
||||
|
||||
full_cudagraph_llm, piecewise_llm = llm_pair
|
||||
|
||||
prompts = ["the quick brown fox"] * batch_size
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Test (piecewise) compilation with a simple model where multiple submodules
|
||||
"""Test (piecewise) compilation with a simple model where multiple submodules
|
||||
are compiled and graph captured separately.
|
||||
"""
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Test the piecewise compilation with a simple model so that we
|
||||
"""Test the piecewise compilation with a simple model so that we
|
||||
can exactly calculate the expected output and side effects.
|
||||
"""
|
||||
|
||||
@@ -52,8 +51,7 @@ class SillyModel(nn.Module):
|
||||
self.intermediate_unbacked = intermediate_unbacked
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Overall effect:
|
||||
"""Overall effect:
|
||||
x = 3 * x + 19
|
||||
global_counter += 2
|
||||
"""
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Test the piecewise compilation with a simple model, comparing the output
|
||||
"""Test the piecewise compilation with a simple model, comparing the output
|
||||
with and without the piecewise compilation.
|
||||
|
||||
This is a tractable model, the weights and computation are specially designed
|
||||
|
||||
@@ -56,10 +56,7 @@ class TestMMRSModel(torch.nn.Module):
|
||||
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
|
||||
|
||||
"""
|
||||
"""Forward pass implementing the mm + reduce scatter in the FX graph."""
|
||||
# Reshape input
|
||||
view = hidden_states.reshape(-1, self.hidden_size)
|
||||
|
||||
@@ -88,9 +85,7 @@ class TestAGMMModel(torch.nn.Module):
|
||||
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
|
||||
"""
|
||||
"""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)
|
||||
@@ -122,10 +117,7 @@ class _BaseScaledMMModel(torch.nn.Module):
|
||||
|
||||
class TestScaledMMRSModel(_BaseScaledMMModel):
|
||||
def forward(self, input: torch.Tensor):
|
||||
"""
|
||||
Forward pass implementing the scaled_mm + reduce scatter in the FX graph
|
||||
|
||||
"""
|
||||
"""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(
|
||||
@@ -147,9 +139,7 @@ class TestScaledMMRSModel(_BaseScaledMMModel):
|
||||
|
||||
class TestAGScaledMMModel(_BaseScaledMMModel):
|
||||
def forward(self, input: torch.Tensor):
|
||||
"""
|
||||
Forward pass implementing the all gather + scaled_mm in the FX graph
|
||||
"""
|
||||
"""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)
|
||||
@@ -173,8 +163,7 @@ class TestAGScaledMMModel(_BaseScaledMMModel):
|
||||
|
||||
class TestCutlassScaledMMRSModel(_BaseScaledMMModel):
|
||||
def forward(self, input: torch.Tensor):
|
||||
"""
|
||||
Forward pass implementing the cutlass_scaled_mm + reduce scatter
|
||||
"""Forward pass implementing the cutlass_scaled_mm + reduce scatter
|
||||
in the FX graph
|
||||
|
||||
"""
|
||||
@@ -200,8 +189,7 @@ class TestCutlassScaledMMRSModel(_BaseScaledMMModel):
|
||||
|
||||
class TestAGCutlassScaledMMModel(_BaseScaledMMModel):
|
||||
def forward(self, input: torch.Tensor):
|
||||
"""
|
||||
Forward pass implementing the all gather + cutlass_scaled_mm
|
||||
"""Forward pass implementing the all gather + cutlass_scaled_mm
|
||||
in the FX graph
|
||||
"""
|
||||
# Reshape input
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Comprehensive tests for UnsafeCloneEliminationPass.
|
||||
"""Comprehensive tests for UnsafeCloneEliminationPass.
|
||||
|
||||
This test suite exercises all possible valid FX graph patterns involving clones:
|
||||
1. Clone with no users (dead code)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Tests for IR inplace functionalization pass integration.
|
||||
"""Tests for IR inplace functionalization pass integration.
|
||||
|
||||
This test suite verifies that the inplace functionalization pass, lowering pass,
|
||||
and clone cleanup pass work together correctly with donated buffer tracking.
|
||||
@@ -108,8 +107,7 @@ class MixedModel(nn.Module):
|
||||
|
||||
|
||||
class ModelWithTritonAfterMaybeInplace(nn.Module):
|
||||
"""
|
||||
Model using maybe_inplace followed by a Triton kernel.
|
||||
"""Model using maybe_inplace followed by a Triton kernel.
|
||||
Test clone elimination can handle Triton in the graph
|
||||
"""
|
||||
|
||||
@@ -410,8 +408,7 @@ def with_dyn_arg(fn: Callable, arg_index: int, dim_index: int):
|
||||
reason="Only test on cuda and rocm platform",
|
||||
)
|
||||
def test_piecewise_compilation_with_donated_buffers(monkeypatch, fresh_vllm_cache):
|
||||
"""
|
||||
Test piecewise compilation with donated buffers across graph splits.
|
||||
"""Test piecewise compilation with donated buffers across graph splits.
|
||||
Utilizes a custom splitting op. Uses fresh cache to avoid compilation caching.
|
||||
"""
|
||||
torch.set_default_device(current_platform.device_type)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Unit tests for the DoubleQuant fan-out variants registered by
|
||||
"""Unit tests for the DoubleQuant fan-out variants registered by
|
||||
``RocmAiterRMSNormQuantFusionPass``.
|
||||
|
||||
Both variants target a 1-to-2 fan-out where one ``rms_norm`` output feeds
|
||||
@@ -90,8 +89,7 @@ def test_double_aiter_rms_fp8_group_quant_fusion(
|
||||
model_cls: type[torch.nn.Module],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""
|
||||
Both fan-out shapes (with and without an intermediate view) must fuse
|
||||
"""Both fan-out shapes (with and without an intermediate view) must fuse
|
||||
into ``rocm_aiter_rmsnorm_fp8_group_quant``: the no-view shape via
|
||||
``DoubleAiterRMSFp8GroupQuantPattern`` and the viewed shape via the
|
||||
new ``DoubleAiterRMSFp8GroupQuantViewPattern`` sibling.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Unit test for the MLADualRMSNormFusionPass.
|
||||
"""Unit test for the MLADualRMSNormFusionPass.
|
||||
|
||||
The pass fuses paired q/kv RMS norms in MLA attention into a single
|
||||
fused_mla_dual_rms_norm op backed by AITER's fused_qk_rmsnorm kernel.
|
||||
@@ -38,13 +37,12 @@ FP8_DTYPE = current_platform.fp8_dtype()
|
||||
|
||||
|
||||
class MLADualRMSNormTestModel(torch.nn.Module):
|
||||
"""
|
||||
Minimal model reproducing the MLA dual RMS norm pattern:
|
||||
linear -> split([q_dim, kv_dim])
|
||||
+-- q_c (getitem 0) -> rms_norm(q_w, eps) -> linear
|
||||
+-- kv_lora (getitem 1) -> split([kv_c_dim, k_pe_dim])
|
||||
+-- kv_c (getitem 0) -> rms_norm(kv_w, eps)
|
||||
+-- k_pe
|
||||
"""Minimal model reproducing the MLA dual RMS norm pattern:
|
||||
linear -> split([q_dim, kv_dim])
|
||||
+-- q_c (getitem 0) -> rms_norm(q_w, eps) -> linear
|
||||
+-- kv_lora (getitem 1) -> split([kv_c_dim, k_pe_dim])
|
||||
+-- kv_c (getitem 0) -> rms_norm(kv_w, eps)
|
||||
+-- k_pe
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -155,13 +153,12 @@ def test_fuse_mla_dual_rms_norm(
|
||||
|
||||
|
||||
class MLADualRMSNormFp8PerTokenTestModel(torch.nn.Module):
|
||||
"""
|
||||
Minimal model reproducing the FP8 MLA attention path with *per-token* quant:
|
||||
linear -> split([q_dim, kv_dim])
|
||||
+-- q_c (getitem 0) -> rocm_aiter_rmsnorm_fused_dynamic_quant -> dequant
|
||||
+-- kv_lora (getitem 1) -> split([kv_c_dim, k_pe_dim])
|
||||
+-- kv_c (getitem 0) -> rms_norm (bf16)
|
||||
+-- k_pe
|
||||
"""Minimal model reproducing the FP8 MLA attention path with *per-token* quant:
|
||||
linear -> split([q_dim, kv_dim])
|
||||
+-- q_c (getitem 0) -> rocm_aiter_rmsnorm_fused_dynamic_quant -> dequant
|
||||
+-- kv_lora (getitem 1) -> split([kv_c_dim, k_pe_dim])
|
||||
+-- kv_c (getitem 0) -> rms_norm (bf16)
|
||||
+-- k_pe
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -107,7 +107,6 @@ class AttentionQuantPatternModel(torch.nn.Module):
|
||||
|
||||
def build_attn_metadata(self, batch_size: int) -> AttentionMetadata:
|
||||
"""Initialize attention metadata."""
|
||||
|
||||
# TODO (Rohan138) reuse utils from vllm/v1/worker/gpu/attn_utils.py
|
||||
|
||||
# Create common attn metadata
|
||||
@@ -304,7 +303,7 @@ def test_attention_quant_pattern(
|
||||
dist_init,
|
||||
disable_vllm_compile_cache,
|
||||
):
|
||||
"""Test AttentionStaticQuantPattern fusion pass"""
|
||||
"""Test AttentionStaticQuantPattern fusion pass."""
|
||||
if backend == AttentionBackendEnum.FLASHINFER and (
|
||||
not current_platform.is_device_capability((10, 0)) or not has_flashinfer()
|
||||
):
|
||||
|
||||
@@ -141,7 +141,6 @@ class MLAAttentionQuantPatternModel(torch.nn.Module):
|
||||
the full output[:num_actual_toks] buffer after both forward_mha and
|
||||
forward_mqa have written their results.
|
||||
"""
|
||||
|
||||
batch_spec = BatchSpec(seq_lens=[1] * batch_size, query_lens=[1] * batch_size)
|
||||
common_attn_metadata = create_common_attn_metadata(
|
||||
batch_spec, self.block_size, self.device, arange_block_indices=True
|
||||
@@ -408,7 +407,7 @@ def test_mla_attention_quant_pattern(
|
||||
dist_init,
|
||||
disable_vllm_compile_cache,
|
||||
):
|
||||
"""Test MLA AttentionQuantPattern fusion pass"""
|
||||
"""Test MLA AttentionQuantPattern fusion pass."""
|
||||
if (
|
||||
model_class is TestMLAAttentionNvfp4QuantPatternModel
|
||||
and not is_nvfp4_supported()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Tests for manual fusion via maybe_fused_act_quant.
|
||||
"""Tests for manual fusion via maybe_fused_act_quant.
|
||||
|
||||
Tests all fusion paths in _FUSED_ACT_QUANT:
|
||||
- kFp8StaticTensorSym: all platforms
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Shared PyTorch custom silly attention for compilation tests.
|
||||
"""Shared PyTorch custom silly attention for compilation tests.
|
||||
Centralizes custom operation definitions to avoid duplicate registrations.
|
||||
"""
|
||||
|
||||
@@ -21,12 +20,12 @@ _global_counter = 0
|
||||
|
||||
|
||||
def get_global_counter():
|
||||
"""Get the current global counter value"""
|
||||
"""Get the current global counter value."""
|
||||
return _global_counter
|
||||
|
||||
|
||||
def reset_global_counter():
|
||||
"""Reset the global counter to 0"""
|
||||
"""Reset the global counter to 0."""
|
||||
global _global_counter
|
||||
_global_counter = 0
|
||||
|
||||
@@ -34,8 +33,7 @@ def reset_global_counter():
|
||||
def silly_attention(
|
||||
q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, out: torch.Tensor
|
||||
) -> None:
|
||||
"""
|
||||
Unified attention implementation that depends on
|
||||
"""Unified attention implementation that depends on
|
||||
all inputs and affects the output.
|
||||
Always increments a global counter that tests can use or ignore.
|
||||
"""
|
||||
@@ -51,7 +49,7 @@ def silly_attention(
|
||||
def silly_attention_fake(
|
||||
q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, out: torch.Tensor
|
||||
) -> None:
|
||||
"""Fake implementation for testing"""
|
||||
"""Fake implementation for testing."""
|
||||
return
|
||||
|
||||
|
||||
|
||||
@@ -268,8 +268,7 @@ def test_save_and_load_slice(monkeypatch: pytest.MonkeyPatch):
|
||||
def test_cache_load_returns_tuple_consistency_tuple_output(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
):
|
||||
"""
|
||||
Test that cache loading correctly handles models that return tuples.
|
||||
"""Test that cache loading correctly handles models that return tuples.
|
||||
|
||||
This verifies that when a model returns a tuple of tensors, the output
|
||||
type is preserved as a tuple between fresh compilation and cache load.
|
||||
@@ -335,8 +334,7 @@ def test_cache_load_returns_tuple_consistency_tuple_output(
|
||||
|
||||
@pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10")
|
||||
def test_shape_env(monkeypatch: pytest.MonkeyPatch):
|
||||
"""
|
||||
Test that the shape environment is correctly serialized and preserved
|
||||
"""Test that the shape environment is correctly serialized and preserved
|
||||
when loading from cache.
|
||||
"""
|
||||
with monkeypatch.context() as m:
|
||||
@@ -374,8 +372,7 @@ def test_shape_env(monkeypatch: pytest.MonkeyPatch):
|
||||
def test_partition_wrapper_applied_on_aot_load(
|
||||
monkeypatch: pytest.MonkeyPatch, vllm_tmp_cache: Path, mocker
|
||||
):
|
||||
"""
|
||||
Test that partition wrappers are applied when loading AOT cached functions.
|
||||
"""Test that partition wrappers are applied when loading AOT cached functions.
|
||||
|
||||
This test verifies the fix for GitHub issue #31439 where AOT compile
|
||||
caused 2x latency regression when use_inductor_graph_partition=True.
|
||||
@@ -498,14 +495,12 @@ def test_standalone_compile_correctness():
|
||||
@pytest.mark.skipif(not is_torch_equal_or_newer("2.10.0"), reason="requires torch 2.10")
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_gpt2_cache_hit(monkeypatch: pytest.MonkeyPatch):
|
||||
"""
|
||||
Test that compiling gpt2 twice results in a cache hit.
|
||||
"""Test that compiling gpt2 twice results in a cache hit.
|
||||
|
||||
Counter values are read from the EngineCore subprocess via
|
||||
``LLM.collective_rpc`` so the test works under default V1
|
||||
multiprocessing (no shared memory between test and engine).
|
||||
"""
|
||||
|
||||
from vllm import LLM
|
||||
|
||||
def _snap(self):
|
||||
@@ -641,7 +636,7 @@ class TestStandaloneCompiledArtifacts:
|
||||
|
||||
@patch("torch._inductor.standalone_compile.AOTCompiledArtifact.deserialize")
|
||||
def test_load_all_success(self, mock_deserialize):
|
||||
"""Test successful loading of all artifacts"""
|
||||
"""Test successful loading of all artifacts."""
|
||||
cache = StandaloneCompiledArtifacts()
|
||||
|
||||
mock_artifact1 = Mock()
|
||||
@@ -658,7 +653,7 @@ class TestStandaloneCompiledArtifacts:
|
||||
|
||||
@patch("torch._inductor.standalone_compile.AOTCompiledArtifact.deserialize")
|
||||
def test_load_all_already_loaded(self, mock_deserialize):
|
||||
"""Test that load_all skips if already loaded"""
|
||||
"""Test that load_all skips if already loaded."""
|
||||
cache = StandaloneCompiledArtifacts()
|
||||
|
||||
mock_artifact = Mock()
|
||||
@@ -671,7 +666,7 @@ class TestStandaloneCompiledArtifacts:
|
||||
|
||||
@patch("torch._inductor.standalone_compile.AOTCompiledArtifact.deserialize")
|
||||
def test_get_loaded_artifact(self, mock_deserialize):
|
||||
"""Test retrieving loaded artifacts"""
|
||||
"""Test retrieving loaded artifacts."""
|
||||
cache = StandaloneCompiledArtifacts()
|
||||
|
||||
mock_artifact = Mock()
|
||||
|
||||
@@ -22,7 +22,7 @@ from vllm.utils.torch_utils import is_torch_equal_or_newer
|
||||
|
||||
|
||||
def get_test_models():
|
||||
"""Get list of models to test based on PyTorch version"""
|
||||
"""Get list of models to test based on PyTorch version."""
|
||||
models = [
|
||||
"Qwen/Qwen3-0.6B",
|
||||
"openai-community/gpt2",
|
||||
@@ -172,7 +172,6 @@ def test_model_specialization_with_evaluate_guards(
|
||||
"""Test that evaluate_guards correctly detects shape specialization
|
||||
violations.
|
||||
"""
|
||||
|
||||
if (
|
||||
use_aot_compile
|
||||
and dynamic_shapes_type == DynamicShapesType.BACKED
|
||||
|
||||
@@ -24,8 +24,7 @@ DEVICE_TYPE = current_platform.device_type
|
||||
|
||||
|
||||
def test_getitem_moved_to_producer_subgraph():
|
||||
"""
|
||||
Test that getitem operations are moved to the same subgraph as their input,
|
||||
"""Test that getitem operations are moved to the same subgraph as their input,
|
||||
preventing tuple inputs to submodules.
|
||||
"""
|
||||
|
||||
@@ -79,8 +78,7 @@ def test_getitem_moved_to_producer_subgraph():
|
||||
|
||||
|
||||
def test_no_tuple_inputs_with_multiple_consumers():
|
||||
"""
|
||||
Test that when a tuple is consumed by multiple split operations,
|
||||
"""Test that when a tuple is consumed by multiple split operations,
|
||||
getitem operations are properly moved to avoid tuple inputs.
|
||||
"""
|
||||
|
||||
@@ -138,13 +136,10 @@ def test_no_tuple_inputs_with_multiple_consumers():
|
||||
|
||||
|
||||
def test_consecutive_ops_in_split():
|
||||
"""
|
||||
Test that consecutive splitting operations are grouped into the same subgraph
|
||||
"""
|
||||
"""Test that consecutive splitting operations are grouped into the same subgraph."""
|
||||
|
||||
def model_fn(x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Define a simple model where consecutive operations create opportunities
|
||||
"""Define a simple model where consecutive operations create opportunities
|
||||
for splitting subgraphs.
|
||||
"""
|
||||
# Apply silly attention followed by consecutive operations
|
||||
@@ -211,8 +206,7 @@ def _subgraphs_with_empty_nodes(split_items, *, is_splitting_graph):
|
||||
|
||||
|
||||
def test_empty_only_partition_stays_separate_after_splitting_predecessor():
|
||||
"""
|
||||
Empty-only subgraphs should not be merged when the only predecessor is
|
||||
"""Empty-only subgraphs should not be merged when the only predecessor is
|
||||
a splitting-op subgraph.
|
||||
"""
|
||||
|
||||
@@ -248,8 +242,7 @@ def test_empty_only_partition_stays_separate_after_splitting_predecessor():
|
||||
|
||||
|
||||
def test_empty_only_partition_is_merged():
|
||||
"""
|
||||
Empty-only subgraphs should still be merged when a non-splitting predecessor
|
||||
"""Empty-only subgraphs should still be merged when a non-splitting predecessor
|
||||
exists. The merged empty node must remain outside splitting-op subgraphs.
|
||||
"""
|
||||
|
||||
@@ -294,8 +287,7 @@ def test_empty_only_partition_is_merged():
|
||||
|
||||
|
||||
def test_builtin_empty_only_partition_is_merged():
|
||||
"""
|
||||
In Dynamo graphs, torch.empty/empty_like may appear as builtin call targets
|
||||
"""In Dynamo graphs, torch.empty/empty_like may appear as builtin call targets
|
||||
(not aten OpOverload). Ensure empty-only partitions are still merged.
|
||||
"""
|
||||
|
||||
@@ -340,8 +332,7 @@ def test_builtin_empty_only_partition_is_merged():
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_sym_size_whole_shape_boundary():
|
||||
"""
|
||||
Test that using x.size() (whole shape) across a split boundary can be
|
||||
"""Test that using x.size() (whole shape) across a split boundary can be
|
||||
compiled by standalone_compile.
|
||||
|
||||
The dynamo graph looks like:
|
||||
@@ -400,8 +391,7 @@ def test_sym_size_whole_shape_boundary():
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_symint_crosses_split_boundary():
|
||||
"""
|
||||
Test that SymInt placeholders from torch.compile + mark_dynamic
|
||||
"""Test that SymInt placeholders from torch.compile + mark_dynamic
|
||||
cross split boundaries safely via split_module's natural threading.
|
||||
|
||||
SymInt values are threaded through subgraphs by split_module and
|
||||
@@ -459,8 +449,7 @@ def test_symint_crosses_split_boundary():
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_shape_boundary_standalone_compile():
|
||||
"""
|
||||
Repro for the original production bug:
|
||||
"""Repro for the original production bug:
|
||||
|
||||
AssertionError: out_spec mismatch
|
||||
TreeSpec(tuple, None, [*, *, TreeSpec(Size, None, [*, *]), *])
|
||||
@@ -529,8 +518,7 @@ def test_shape_boundary_standalone_compile():
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_size_used_in_multiple_consumer_subgraphs():
|
||||
"""
|
||||
Validates that x.size() (whole shape) used by multiple downstream subgraphs
|
||||
"""Validates that x.size() (whole shape) used by multiple downstream subgraphs
|
||||
does not cause torch.Size to cross split boundaries.
|
||||
|
||||
Model:
|
||||
@@ -584,8 +572,7 @@ def test_size_used_in_multiple_consumer_subgraphs():
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
|
||||
def test_sym_size_metadata_propagated():
|
||||
"""
|
||||
Validates that new sym_size.int nodes created by the pre-pass have
|
||||
"""Validates that new sym_size.int nodes created by the pre-pass have
|
||||
example_value metadata set. Without it, placeholder metadata in consumer
|
||||
subgraphs would be None, breaking any code that dynamically builds
|
||||
example inputs from metadata (e.g. standalone_compile per-submodule).
|
||||
@@ -634,8 +621,7 @@ def test_sym_size_metadata_propagated():
|
||||
|
||||
|
||||
def test_decompose_size_with_getitem_user():
|
||||
"""
|
||||
Regression test: _decompose_size_nodes must handle getitem users of size()
|
||||
"""Regression test: _decompose_size_nodes must handle getitem users of size()
|
||||
correctly.
|
||||
|
||||
When a graph contains x.shape[i], it can appear as:
|
||||
@@ -704,8 +690,7 @@ def test_decompose_size_with_getitem_user():
|
||||
|
||||
|
||||
def test_decompose_size_leaves_scalar_size_with_dim():
|
||||
"""
|
||||
Regression test: _decompose_size_nodes must leave x.size(dim) alone.
|
||||
"""Regression test: _decompose_size_nodes must leave x.size(dim) alone.
|
||||
|
||||
x.size() returns a torch.Size tuple that can't cross split boundaries and
|
||||
must be decomposed. x.size(dim), however, already returns a scalar
|
||||
|
||||
@@ -60,6 +60,7 @@ class TraceStructuredCapture:
|
||||
Args:
|
||||
event_type: The event type to filter by (e.g., "artifact", "graph_dump")
|
||||
name_pattern: Regex pattern to match against the artifact name
|
||||
|
||||
"""
|
||||
regex = re.compile(name_pattern)
|
||||
return [
|
||||
|
||||
@@ -40,7 +40,7 @@ class DummyLogprobsMode(Enum):
|
||||
|
||||
|
||||
def test_hash_factors_deterministic():
|
||||
"""Test that hash_factors produces consistent SHA-256 hashes"""
|
||||
"""Test that hash_factors produces consistent SHA-256 hashes."""
|
||||
factors = {"a": 1, "b": "test"}
|
||||
hash1 = hash_factors(factors)
|
||||
hash2 = hash_factors(factors)
|
||||
|
||||
@@ -9,12 +9,10 @@ from vllm.v1.engine.async_llm import AsyncLLM
|
||||
|
||||
|
||||
def test_mp_reducer():
|
||||
"""
|
||||
Test that _reduce_config reducer is registered when AsyncLLM is instantiated
|
||||
"""Test that _reduce_config reducer is registered when AsyncLLM is instantiated
|
||||
without transformers_modules. This is a regression test for
|
||||
https://github.com/vllm-project/vllm/pull/18640.
|
||||
"""
|
||||
|
||||
# Ensure transformers_modules is not in sys.modules
|
||||
if "transformers_modules" in sys.modules:
|
||||
del sys.modules["transformers_modules"]
|
||||
|
||||
@@ -11,7 +11,7 @@ from vllm.platforms import current_platform
|
||||
|
||||
|
||||
def check_cuda_context():
|
||||
"""Check CUDA driver context status"""
|
||||
"""Check CUDA driver context status."""
|
||||
try:
|
||||
cuda = ctypes.CDLL("libcuda.so")
|
||||
device = ctypes.c_int()
|
||||
@@ -22,7 +22,7 @@ def check_cuda_context():
|
||||
|
||||
|
||||
def run_cuda_test_in_thread(device_input, expected_device_id):
|
||||
"""Run CUDA context test in separate thread for isolation"""
|
||||
"""Run CUDA context test in separate thread for isolation."""
|
||||
try:
|
||||
# New thread should have no CUDA context initially
|
||||
valid_before, device_before = check_cuda_context()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Test that platform imports do not prematurely initialize CUDA.
|
||||
"""Test that platform imports do not prematurely initialize CUDA.
|
||||
|
||||
This is critical for Ray-based multi-GPU setups where workers need to
|
||||
set CUDA_VISIBLE_DEVICES after importing vLLM but before CUDA is initialized.
|
||||
|
||||
@@ -44,8 +44,7 @@ def _make_request(stop, include_stop_str_in_output: bool, min_tokens: int = 0):
|
||||
|
||||
|
||||
def test_stop_string_while_stop_token_terminates(include_stop_str_in_output: bool):
|
||||
"""
|
||||
This test verifies that the detokenizer correctly handles the case where
|
||||
"""This test verifies that the detokenizer correctly handles the case where
|
||||
the generated token sequence contains both:
|
||||
- a stop token
|
||||
- an <eos> token
|
||||
@@ -67,7 +66,6 @@ def test_stop_string_while_stop_token_terminates(include_stop_str_in_output: boo
|
||||
where stop-string evaluation occurs before the early-return on
|
||||
stop_terminated.
|
||||
"""
|
||||
|
||||
# Generate text "abcdeZ" and tokenize it.
|
||||
generated_text = "abcde"
|
||||
eos_token = "Z"
|
||||
|
||||
@@ -18,13 +18,13 @@ DP_RANK = 0
|
||||
|
||||
@pytest.fixture
|
||||
def random_port():
|
||||
"""Generate a random port number for testing"""
|
||||
"""Generate a random port number for testing."""
|
||||
return random.randint(10000, 59900)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def publisher_config(random_port, request):
|
||||
"""Create a publisher config with inproc transport"""
|
||||
"""Create a publisher config with inproc transport."""
|
||||
how = request.param if hasattr(request, "param") else "inproc"
|
||||
|
||||
if how == "inproc":
|
||||
@@ -47,7 +47,7 @@ def publisher_config(random_port, request):
|
||||
|
||||
@pytest.fixture
|
||||
def publisher(publisher_config):
|
||||
"""Create and return a publisher instance"""
|
||||
"""Create and return a publisher instance."""
|
||||
pub = EventPublisherFactory.create(publisher_config, DP_RANK)
|
||||
yield pub
|
||||
pub.shutdown()
|
||||
@@ -55,7 +55,7 @@ def publisher(publisher_config):
|
||||
|
||||
@pytest.fixture
|
||||
def subscriber(publisher_config):
|
||||
"""Create and return a subscriber for testing"""
|
||||
"""Create and return a subscriber for testing."""
|
||||
endpoint = publisher_config.endpoint
|
||||
replay_endpoint = publisher_config.replay_endpoint
|
||||
|
||||
@@ -74,7 +74,7 @@ def subscriber(publisher_config):
|
||||
|
||||
|
||||
class MockSubscriber:
|
||||
"""Helper class to receive and verify published events"""
|
||||
"""Helper class to receive and verify published events."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -113,7 +113,7 @@ class MockSubscriber:
|
||||
self.decoder = msgspec.msgpack.Decoder(type=decode_type)
|
||||
|
||||
def receive_one(self, timeout=1000) -> tuple[int, SampleBatch] | None:
|
||||
"""Receive a single message with timeout"""
|
||||
"""Receive a single message with timeout."""
|
||||
if not self.sub.poll(timeout):
|
||||
return None
|
||||
|
||||
@@ -127,7 +127,7 @@ class MockSubscriber:
|
||||
return seq, data
|
||||
|
||||
def request_replay(self, start_seq: int, socket_idx: int = 0) -> None:
|
||||
"""Request replay of messages starting from start_seq"""
|
||||
"""Request replay of messages starting from start_seq."""
|
||||
if not self.replay_sockets:
|
||||
raise ValueError("Replay sockets not initialized")
|
||||
if socket_idx >= len(self.replay_sockets):
|
||||
@@ -138,7 +138,7 @@ class MockSubscriber:
|
||||
)
|
||||
|
||||
def receive_replay(self, socket_idx: int = 0) -> list[tuple[int, SampleBatch]]:
|
||||
"""Receive replayed messages from a specific replay socket"""
|
||||
"""Receive replayed messages from a specific replay socket."""
|
||||
if not self.replay_sockets:
|
||||
raise ValueError("Replay sockets not initialized")
|
||||
if socket_idx >= len(self.replay_sockets):
|
||||
@@ -170,7 +170,7 @@ class MockSubscriber:
|
||||
return replayed
|
||||
|
||||
def close(self):
|
||||
"""Clean up resources"""
|
||||
"""Clean up resources."""
|
||||
self.sub.close()
|
||||
for replay in self.replay_sockets:
|
||||
replay.close()
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# 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.
|
||||
"""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
|
||||
|
||||
@@ -29,7 +29,7 @@ def test_eplb_load_stats_reduce_across_ranks():
|
||||
|
||||
|
||||
def test_basic_rebalance():
|
||||
"""Test basic rebalancing functionality"""
|
||||
"""Test basic rebalancing functionality."""
|
||||
# Example from https://github.com/deepseek-ai/eplb
|
||||
weight = torch.tensor(
|
||||
[
|
||||
@@ -92,7 +92,7 @@ def test_basic_rebalance():
|
||||
|
||||
|
||||
def test_single_gpu_case():
|
||||
"""Test single GPU case"""
|
||||
"""Test single GPU case."""
|
||||
weight = torch.tensor([[10, 20, 30, 40]])
|
||||
num_replicas = 4
|
||||
num_groups = 1
|
||||
@@ -115,7 +115,7 @@ def test_single_gpu_case():
|
||||
|
||||
|
||||
def test_equal_weights():
|
||||
"""Test case with equal weights"""
|
||||
"""Test case with equal weights."""
|
||||
weight = torch.tensor([[50, 50, 50, 50, 50, 50, 50, 50]])
|
||||
num_replicas = 8
|
||||
num_groups = 2
|
||||
@@ -139,7 +139,7 @@ def test_equal_weights():
|
||||
|
||||
|
||||
def test_extreme_weight_imbalance():
|
||||
"""Test extreme weight imbalance case"""
|
||||
"""Test extreme weight imbalance case."""
|
||||
weight = torch.tensor([[1000, 1, 1, 1, 1, 1, 1, 1]])
|
||||
num_replicas = 12
|
||||
num_groups = 2
|
||||
@@ -162,7 +162,7 @@ def test_extreme_weight_imbalance():
|
||||
|
||||
|
||||
def test_multiple_layers():
|
||||
"""Test multiple layers case"""
|
||||
"""Test multiple layers case."""
|
||||
weight = torch.tensor(
|
||||
[
|
||||
[10, 20, 30, 40, 50, 60], # First layer
|
||||
@@ -195,7 +195,7 @@ def test_multiple_layers():
|
||||
|
||||
|
||||
def test_parameter_validation():
|
||||
"""Test parameter validation"""
|
||||
"""Test parameter validation."""
|
||||
weight = torch.tensor([[10, 20, 30, 40]])
|
||||
|
||||
# Test non-divisible case - this should handle normally without throwing
|
||||
@@ -213,7 +213,7 @@ def test_parameter_validation():
|
||||
|
||||
|
||||
def test_small_scale_hierarchical():
|
||||
"""Test small-scale hierarchical load balancing"""
|
||||
"""Test small-scale hierarchical load balancing."""
|
||||
weight = torch.tensor(
|
||||
[
|
||||
[100, 50, 200, 75, 150, 25, 300, 80], # 8 experts
|
||||
@@ -243,7 +243,7 @@ def test_small_scale_hierarchical():
|
||||
|
||||
|
||||
def test_global_load_balance_fallback():
|
||||
"""Test global load balancing fallback case"""
|
||||
"""Test global load balancing fallback case."""
|
||||
# When num_groups % num_nodes != 0, should fall back to global load
|
||||
# balancing
|
||||
weight = torch.tensor([[10, 20, 30, 40, 50, 60]])
|
||||
@@ -265,7 +265,7 @@ def test_global_load_balance_fallback():
|
||||
|
||||
@pytest.mark.parametrize("device", ["cpu", "cuda"])
|
||||
def test_device_compatibility(device):
|
||||
"""Test device compatibility"""
|
||||
"""Test device compatibility."""
|
||||
if device == "cuda" and not torch.cuda.is_available():
|
||||
pytest.skip("CUDA not available")
|
||||
|
||||
@@ -287,8 +287,7 @@ def test_device_compatibility(device):
|
||||
|
||||
|
||||
def test_additional_cases():
|
||||
"""Test more edge cases and different parameter combinations"""
|
||||
|
||||
"""Test more edge cases and different parameter combinations."""
|
||||
# Test case 1: Large-scale distributed setup
|
||||
weight1 = torch.tensor(
|
||||
[[50, 100, 75, 120, 90, 60, 80, 110, 40, 70, 95, 85, 65, 55, 45, 35]]
|
||||
@@ -320,8 +319,7 @@ def test_additional_cases():
|
||||
|
||||
|
||||
def test_compute_logical_maps_with_negative_indices():
|
||||
"""
|
||||
Test that compute_logical_maps correctly handles physical slots containing
|
||||
"""Test that compute_logical_maps correctly handles physical slots containing
|
||||
-1 (unused slots).
|
||||
"""
|
||||
# 2 layers, 6 physical slots, 4 logical experts.
|
||||
|
||||
@@ -57,9 +57,8 @@ def test_reuse_across_multiple_cycles():
|
||||
|
||||
|
||||
def test_producer_consumer():
|
||||
"""
|
||||
This test uses the CpuGpuEvent to synchronize reads and writes to/from a shared GPU
|
||||
tensor on multiple CPU threads.
|
||||
"""This test uses the CpuGpuEvent to synchronize reads and writes to/from a shared
|
||||
GPU tensor on multiple CPU threads.
|
||||
"""
|
||||
worker_stream = torch.cuda.Stream()
|
||||
# Create a single element counter that will be shared between two threads
|
||||
|
||||
@@ -56,8 +56,7 @@ def create_expert_indices_with_redundancy(
|
||||
total_physical_experts: int,
|
||||
redundancy_config: list[int], # redundancy for each logical expert
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Create expert indices with redundancy.
|
||||
"""Create expert indices with redundancy.
|
||||
|
||||
Args:
|
||||
num_layers: number of layers
|
||||
@@ -67,6 +66,7 @@ def create_expert_indices_with_redundancy(
|
||||
|
||||
Returns:
|
||||
indices: Shape (num_layers, total_physical_experts)
|
||||
|
||||
"""
|
||||
assert sum(redundancy_config) == total_physical_experts
|
||||
assert len(redundancy_config) == num_logical_experts
|
||||
@@ -95,8 +95,7 @@ def create_expert_weights(
|
||||
device: torch.device,
|
||||
physical_to_logical_mapping: torch.Tensor,
|
||||
) -> list[list[torch.Tensor]]:
|
||||
"""
|
||||
Create fake expert weights tensor for testing.
|
||||
"""Create fake expert weights tensor for testing.
|
||||
|
||||
Use `arange` to generate predictable weights values, based on logical
|
||||
expert ID.
|
||||
@@ -105,6 +104,7 @@ def create_expert_weights(
|
||||
Args:
|
||||
physical_to_logical_mapping: Shape (num_layers, num_local_experts)
|
||||
mapping[layer, physical_pos] = logical_expert_id
|
||||
|
||||
"""
|
||||
expert_weights = []
|
||||
|
||||
@@ -209,9 +209,7 @@ def verify_redundant_experts_have_same_weights(
|
||||
world_size: int,
|
||||
num_local_experts: int,
|
||||
) -> bool:
|
||||
"""
|
||||
Verify that all replicas of the same logical expert have the same weights.
|
||||
"""
|
||||
"""Verify that all replicas of the same logical expert have the same weights."""
|
||||
num_layers = len(expert_weights)
|
||||
total_physical_experts = world_size * num_local_experts
|
||||
|
||||
@@ -568,7 +566,6 @@ def test_rearrange_expert_weights_with_redundancy(
|
||||
eplb_communicator,
|
||||
):
|
||||
"""Test the functionality of rearranging expert weights with redundancy."""
|
||||
|
||||
if eplb_communicator == "nixl" and not has_nixl():
|
||||
pytest.skip("NIXL is not available")
|
||||
if torch.accelerator.device_count() < world_size:
|
||||
@@ -678,7 +675,6 @@ def test_async_transfer_layer_without_mtp(
|
||||
eplb_communicator: str,
|
||||
):
|
||||
"""Exercise async EPLB transfer path without MTP/spec decode."""
|
||||
|
||||
if eplb_communicator == "nixl" and not has_nixl():
|
||||
pytest.skip("NIXL is not available")
|
||||
if torch.accelerator.device_count() < world_size:
|
||||
@@ -696,11 +692,9 @@ def test_async_transfer_layer_without_mtp(
|
||||
|
||||
@pytest.mark.parametrize("world_size", [2, 4])
|
||||
def test_rearrange_expert_weights_no_change(world_size):
|
||||
"""
|
||||
Test that when the indices do not change, the weights should remain
|
||||
"""Test that when the indices do not change, the weights should remain
|
||||
unchanged.
|
||||
"""
|
||||
|
||||
if torch.accelerator.device_count() < world_size:
|
||||
pytest.skip(f"Need at least {world_size} GPUs to run the test")
|
||||
distributed_run(
|
||||
@@ -800,7 +794,6 @@ def _test_rearrange_expert_weights_profile_mode(env, world_size) -> None:
|
||||
@pytest.mark.parametrize("world_size", [2, 4])
|
||||
def test_rearrange_expert_weights_profile_mode(world_size):
|
||||
"""Test profile mode (should not copy actual weights)"""
|
||||
|
||||
if torch.accelerator.device_count() < world_size:
|
||||
pytest.skip(f"Need at least {world_size} GPUs to run the test")
|
||||
distributed_run(
|
||||
|
||||
@@ -75,8 +75,7 @@ def test_eplb_spec_decode(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
model_setup: tuple[str, str, str, int, float],
|
||||
):
|
||||
"""
|
||||
Test the correctness of EPLB speculative decoding with GSM8K dataset.
|
||||
"""Test the correctness of EPLB speculative decoding with GSM8K dataset.
|
||||
Applicable to MoE models with mtp or eagle spec decode.
|
||||
"""
|
||||
method, model_name, spec_model_name, tp_size, expected_gsm8k_value = model_setup
|
||||
@@ -109,10 +108,7 @@ def test_eplb_spec_decode(
|
||||
|
||||
@large_gpu_mark(min_gb=80)
|
||||
def test_eplb_spec_decode_qwen3_next_mtp_async() -> None:
|
||||
"""
|
||||
Ensure async EPLB works with MTP speculative decoding for Qwen3-Next.
|
||||
"""
|
||||
|
||||
"""Ensure async EPLB works with MTP speculative decoding for Qwen3-Next."""
|
||||
TASK = "gsm8k"
|
||||
FILTER = "exact_match,strict-match"
|
||||
RTOL = 0.03
|
||||
|
||||
@@ -30,8 +30,7 @@ def _make_model_state(
|
||||
|
||||
|
||||
def test_commit_eplb_maps_shape_change():
|
||||
"""
|
||||
When the number of physical experts changes, resize the active map within its
|
||||
"""When the number of physical experts changes, resize the active map within its
|
||||
preallocated storage.
|
||||
"""
|
||||
num_layers, num_logical, num_physical = 2, 4, 6
|
||||
@@ -65,8 +64,7 @@ def test_commit_eplb_maps_shape_change():
|
||||
|
||||
|
||||
def test_commit_eplb_maps_for_layer_logical_padding():
|
||||
"""
|
||||
Test that logical_to_physical_map is padded with -1 to fill the
|
||||
"""Test that logical_to_physical_map is padded with -1 to fill the
|
||||
pre-allocated slots when the new map has fewer replicas than the max.
|
||||
"""
|
||||
num_layers, num_logical, num_physical = 2, 4, 6
|
||||
|
||||
@@ -20,27 +20,26 @@ class EventSample(
|
||||
tag=True, # type: ignore
|
||||
array_like=True, # type: ignore
|
||||
):
|
||||
"""Test event for publisher testing"""
|
||||
"""Test event for publisher testing."""
|
||||
|
||||
id: int
|
||||
value: str
|
||||
|
||||
|
||||
class SampleBatch(EventBatch):
|
||||
"""Test event batch for publisher testing"""
|
||||
"""Test event batch for publisher testing."""
|
||||
|
||||
events: list[EventSample]
|
||||
|
||||
|
||||
def create_test_events(count: int) -> SampleBatch:
|
||||
"""Create a batch of test events"""
|
||||
"""Create a batch of test events."""
|
||||
events = [EventSample(id=i, value=f"test-{i}") for i in range(count)]
|
||||
return SampleBatch(ts=time.time(), events=events)
|
||||
|
||||
|
||||
def test_basic_publishing(publisher, subscriber):
|
||||
"""Test basic event publishing works"""
|
||||
|
||||
"""Test basic event publishing works."""
|
||||
test_batch = create_test_events(5)
|
||||
publisher.publish(test_batch)
|
||||
|
||||
@@ -58,7 +57,7 @@ def test_basic_publishing(publisher, subscriber):
|
||||
|
||||
|
||||
def test_multiple_events(publisher, subscriber):
|
||||
"""Test publishing and receiving multiple event batches"""
|
||||
"""Test publishing and receiving multiple event batches."""
|
||||
for _ in range(10):
|
||||
batch = create_test_events(2)
|
||||
publisher.publish(batch)
|
||||
@@ -75,7 +74,7 @@ def test_multiple_events(publisher, subscriber):
|
||||
|
||||
|
||||
def test_replay_mechanism(publisher, subscriber):
|
||||
"""Test the replay mechanism works correctly"""
|
||||
"""Test the replay mechanism works correctly."""
|
||||
for _ in range(19):
|
||||
batch = create_test_events(1)
|
||||
publisher.publish(batch)
|
||||
@@ -96,7 +95,7 @@ def test_replay_mechanism(publisher, subscriber):
|
||||
|
||||
|
||||
def test_replay_includes_topic(publisher, subscriber, publisher_config):
|
||||
"""Test that replay responses include the topic, matching PUB format"""
|
||||
"""Test that replay responses include the topic, matching PUB format."""
|
||||
for _ in range(5):
|
||||
publisher.publish(create_test_events(1))
|
||||
|
||||
@@ -115,7 +114,7 @@ def test_replay_includes_topic(publisher, subscriber, publisher_config):
|
||||
|
||||
|
||||
def test_buffer_limit(publisher, subscriber, publisher_config):
|
||||
"""Test buffer limit behavior"""
|
||||
"""Test buffer limit behavior."""
|
||||
buffer_size = publisher_config.buffer_steps
|
||||
|
||||
# Publish more events than the buffer can hold
|
||||
@@ -139,9 +138,7 @@ def test_buffer_limit(publisher, subscriber, publisher_config):
|
||||
|
||||
|
||||
def test_topic_filtering(publisher_config):
|
||||
"""
|
||||
Test that a subscriber only receives messages matching its topic filter
|
||||
"""
|
||||
"""Test that a subscriber only receives messages matching its topic filter."""
|
||||
publisher_config.replay_endpoint = None
|
||||
|
||||
publisher_config.topic = "foo"
|
||||
@@ -174,7 +171,7 @@ def test_topic_filtering(publisher_config):
|
||||
|
||||
|
||||
def test_high_volume(publisher, subscriber):
|
||||
"""Test publishing and receiving a high volume of events"""
|
||||
"""Test publishing and receiving a high volume of events."""
|
||||
num_batches = 10_000
|
||||
events_per_batch = 100
|
||||
|
||||
@@ -210,7 +207,7 @@ def test_high_volume(publisher, subscriber):
|
||||
|
||||
|
||||
def test_null_publisher():
|
||||
"""Test that NullEventPublisher can be used without errors"""
|
||||
"""Test that NullEventPublisher can be used without errors."""
|
||||
publisher = NullEventPublisher(DP_RANK)
|
||||
|
||||
# This should not raise any errors
|
||||
@@ -220,8 +217,7 @@ def test_null_publisher():
|
||||
|
||||
|
||||
def test_data_parallel_rank_tagging(publisher_config):
|
||||
"""Test that events are properly tagged with their data parallel rank"""
|
||||
|
||||
"""Test that events are properly tagged with their data parallel rank."""
|
||||
publisher_config.topic = "foo"
|
||||
pub_0 = EventPublisherFactory.create(publisher_config, DP_RANK)
|
||||
pub_1 = EventPublisherFactory.create(publisher_config, DP_RANK + 1)
|
||||
@@ -285,7 +281,7 @@ def test_data_parallel_rank_tagging(publisher_config):
|
||||
|
||||
|
||||
def test_event_publisher_factory(random_port):
|
||||
"""Test event publisher factory creation behavior under different configurations"""
|
||||
"""Test event publisher factory creation behavior under different configurations."""
|
||||
from vllm.config.kv_events import KVEventsConfig
|
||||
from vllm.distributed.kv_events import ZmqEventPublisher
|
||||
|
||||
|
||||
@@ -49,7 +49,6 @@ def verify_round_robin_pattern(expert_map, ep_rank, ep_size, global_num_experts)
|
||||
@pytest.mark.parametrize("world_size", [2, 4])
|
||||
def test_expert_placement_various_sizes(expert_placement_strategy, world_size):
|
||||
"""Test round_robin expert placement with various expert counts."""
|
||||
|
||||
# Test with different global_num_experts values
|
||||
# Include both divisible and non-divisible cases
|
||||
if world_size == 2:
|
||||
@@ -116,7 +115,6 @@ def test_expert_placement_various_sizes(expert_placement_strategy, world_size):
|
||||
@pytest.mark.parametrize("world_size", [2, 4])
|
||||
def test_expert_placement_edge_cases(expert_placement_strategy, world_size):
|
||||
"""Test edge cases for round_robin expert placement."""
|
||||
|
||||
# Test case 1: ep_size = 1 (should return None for expert_map)
|
||||
local_num_experts, expert_map, _ = determine_expert_map(
|
||||
ep_size=1,
|
||||
@@ -139,7 +137,6 @@ def test_expert_placement_edge_cases(expert_placement_strategy, world_size):
|
||||
|
||||
def test_determine_expert_map_comprehensive():
|
||||
"""Test of determine_expert_map function with various configurations."""
|
||||
|
||||
# Test cases: (ep_size, ep_rank, global_num_experts,
|
||||
# expert_placement_strategy, expected_local, expected_map_pattern)
|
||||
test_cases = [
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Tests for MNNVL AllToAll operations.
|
||||
"""Tests for MNNVL AllToAll operations.
|
||||
|
||||
Requires: docker run ... --cap-add=SYS_PTRACE ...
|
||||
Run: pytest tests/distributed/test_mnnvl_alltoall.py -v
|
||||
@@ -87,6 +86,7 @@ def _run_worker(rank, world_size, port, worker_fn, dp_size, dp_port, err_queue):
|
||||
Otherwise use tp=world_size (default for EP-based tests).
|
||||
dp_port: Separate port for the DP master (only used when dp_size is set).
|
||||
err_queue: Queue for propagating tracebacks to the parent process.
|
||||
|
||||
"""
|
||||
try:
|
||||
os.environ.pop("CUDA_VISIBLE_DEVICES", None)
|
||||
@@ -115,6 +115,7 @@ def _init_dp_environment(world_size, rank, port, dp_size, dp_port):
|
||||
Args:
|
||||
port: Port for torch.distributed init.
|
||||
dp_port: Separate port for the DP master group init.
|
||||
|
||||
"""
|
||||
from vllm.config import VllmConfig, set_current_vllm_config
|
||||
from vllm.config.parallel import ParallelConfig
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Test that MessageQueue uses the local node's IP for binding,
|
||||
"""Test that MessageQueue uses the local node's IP for binding,
|
||||
not a remote master_addr. This validates the fix for cross-node
|
||||
data-parallel where each DP group leader must bind to its own IP.
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Integration tests for MultiprocExecutor at the executor level.
|
||||
"""Integration tests for MultiprocExecutor at the executor level.
|
||||
This test directly tests the executor without going through the LLM interface,
|
||||
focusing on executor initialization, RPC calls, and distributed execution.
|
||||
"""
|
||||
@@ -377,8 +376,7 @@ def test_multiproc_executor_properties():
|
||||
|
||||
@multi_gpu_test(num_gpus=4)
|
||||
def test_multiproc_executor_multi_node():
|
||||
"""
|
||||
Test MultiprocExecutor with multi-node configuration.
|
||||
"""Test MultiprocExecutor with multi-node configuration.
|
||||
This simulates 2 nodes with TP=4:
|
||||
- Node 0 (rank 0): Uses GPUs 0,1 (CUDA_VISIBLE_DEVICES=0,1) with TP=2
|
||||
- Node 1 (rank 1): Uses GPUs 2,3 (CUDA_VISIBLE_DEVICES=2,3) with TP=2
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
# 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.
|
||||
"""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
|
||||
|
||||
@@ -396,8 +396,7 @@ def test_custom_quick_allreduce_bf16_cast(monkeypatch: pytest.MonkeyPatch):
|
||||
|
||||
|
||||
def qr_variable_input(rank, world_size):
|
||||
"""
|
||||
When the tensor parallelism is set to 4 or 8, frequent changes
|
||||
"""When the tensor parallelism is set to 4 or 8, frequent changes
|
||||
in the input shape can cause QuickReduce to hang (this issue
|
||||
has been observed with the gpt_oss model).
|
||||
"""
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Integration tests for RayExecutorV2 at the executor level.
|
||||
"""Integration tests for RayExecutorV2 at the executor level.
|
||||
Validates executor initialization, placement group support, RPC calls,
|
||||
and distributed execution with various TP/PP configurations.
|
||||
"""
|
||||
@@ -299,7 +298,6 @@ def test_ray_v2_run_refs_stored_for_monitoring(executor):
|
||||
@pytest.mark.parametrize("tp_size, pp_size", [(2, 1), (2, 2)])
|
||||
def test_ray_v2_single_node_generation(tp_size, pp_size):
|
||||
"""End-to-end LLM generation with RayExecutorV2."""
|
||||
|
||||
llm = LLM(
|
||||
model=MODEL,
|
||||
tensor_parallel_size=tp_size,
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Orchestration-level integration tests for RayExecutorV2.
|
||||
"""
|
||||
"""Orchestration-level integration tests for RayExecutorV2."""
|
||||
|
||||
import gc
|
||||
import os
|
||||
@@ -158,8 +156,7 @@ def test_multi_replicas_with_bundle_indices(ray_init):
|
||||
|
||||
|
||||
def test_env_var_and_runtime_env_propagation():
|
||||
"""
|
||||
Verify env vars (NCCL_, HF_) and parallel_config.ray_runtime_env
|
||||
"""Verify env vars (NCCL_, HF_) and parallel_config.ray_runtime_env
|
||||
propagate to RayWorkerProc actors.
|
||||
"""
|
||||
sentinel_vars = {
|
||||
|
||||
@@ -845,7 +845,7 @@ class TestChunkModuleScatters:
|
||||
]
|
||||
|
||||
def test_scatters_carry_their_own_dtype(self):
|
||||
"""dtype rides the record from the bake, where it is the fake's dtype
|
||||
"""Dtype rides the record from the bake, where it is the fake's dtype
|
||||
AFTER its op chain — not a plan-time lookup of the source name, which
|
||||
would be wrong for any chain that reinterprets dtype."""
|
||||
layer = _FakeLayer("l")
|
||||
@@ -1110,7 +1110,7 @@ class TestSignalCompleteness:
|
||||
signaled parks a producer credit and hangs end_sync."""
|
||||
|
||||
def _moe_planner(self, worker_experts, *, ep_size=4, n_experts=8, n_layers=2):
|
||||
"""pre / n_layers MoE layers / post. Each layer: one norm (its own
|
||||
"""Pre / n_layers MoE layers / post. Each layer: one norm (its own
|
||||
module, stamp -1) + n_experts expert names stamped ``e // n_local``.
|
||||
The worker's bake covers only ``worker_experts`` (its placement);
|
||||
foreign expert names never copied => dropped entirely, as in the real
|
||||
@@ -1173,7 +1173,7 @@ class TestSignalCompleteness:
|
||||
assert self._signals(plan) == list(range(len(group_lens)))
|
||||
|
||||
def test_placement_changes_only_the_chunk_count_never_the_signals(self):
|
||||
"""linear experts 0-3 hit 2 owner classes; round_robin 0,2,4,6
|
||||
"""Linear experts 0-3 hit 2 owner classes; round_robin 0,2,4,6
|
||||
hits all 4. More chunks per group, identical signal set."""
|
||||
plans = {}
|
||||
for label, experts in (("linear", [0, 1, 2, 3]), ("round_robin", [0, 2, 4, 6])):
|
||||
|
||||
@@ -503,7 +503,7 @@ class TestGatherCredit:
|
||||
def test_the_residency_bound_scales_with_the_lookahead(
|
||||
self, server_factory, gather_engine
|
||||
):
|
||||
"""lookahead + 1, not a hardcoded 2: at lookahead=2 a free-nothing
|
||||
"""Lookahead + 1, not a hardcoded 2: at lookahead=2 a free-nothing
|
||||
consumer sees exactly 3 groups gathered before the loop parks."""
|
||||
server = server_factory(gather_lookahead=2)
|
||||
engine = gather_engine(server, 8, lookahead=2)
|
||||
|
||||
@@ -43,6 +43,7 @@ def distributed_run(fn, world_size, timeout=60):
|
||||
fn: Function to run in each process
|
||||
world_size: Number of processes to spawn
|
||||
timeout: Maximum time in seconds to wait for processes (default: 60)
|
||||
|
||||
"""
|
||||
number_of_processes = world_size
|
||||
processes = []
|
||||
@@ -634,11 +635,9 @@ def test_acquire_read_releases_slot_when_reader_raises():
|
||||
|
||||
|
||||
def test_warning_logs(caplog_vllm):
|
||||
"""
|
||||
Test that warning logs are emitted at VLLM_RINGBUFFER_WARNING_INTERVAL intervals
|
||||
"""Test that warning logs are emitted at VLLM_RINGBUFFER_WARNING_INTERVAL intervals
|
||||
when indefinite=False, and are not emitted when indefinite=True.
|
||||
"""
|
||||
|
||||
# Patch the warning log interval to every 1 ms during reads
|
||||
with mock.patch(
|
||||
"vllm.distributed.device_communicators.shm_broadcast.VLLM_RINGBUFFER_WARNING_INTERVAL",
|
||||
|
||||
@@ -12,20 +12,20 @@ from vllm.distributed.device_communicators.shm_object_storage import (
|
||||
|
||||
|
||||
class TestSingleWriterShmRingBuffer(unittest.TestCase):
|
||||
"""Test suite for the ring buffer implementation"""
|
||||
"""Test suite for the ring buffer implementation."""
|
||||
|
||||
def setUp(self):
|
||||
"""Set up test fixtures"""
|
||||
"""Set up test fixtures."""
|
||||
self.buffer_size = 4096
|
||||
self.ring_buffer = None
|
||||
|
||||
def tearDown(self):
|
||||
"""Clean up after tests"""
|
||||
"""Clean up after tests."""
|
||||
if self.ring_buffer:
|
||||
self.ring_buffer.close()
|
||||
|
||||
def test_buffer_opening(self):
|
||||
"""Test opening an existing buffer"""
|
||||
"""Test opening an existing buffer."""
|
||||
# First create a buffer
|
||||
self.ring_buffer = SingleWriterShmRingBuffer(
|
||||
data_buffer_size=self.buffer_size, create=True
|
||||
@@ -39,7 +39,7 @@ class TestSingleWriterShmRingBuffer(unittest.TestCase):
|
||||
)
|
||||
|
||||
def test_buffer_access(self):
|
||||
"""Test accessing allocated buffers"""
|
||||
"""Test accessing allocated buffers."""
|
||||
self.ring_buffer = SingleWriterShmRingBuffer(
|
||||
data_buffer_size=self.buffer_size, create=True
|
||||
)
|
||||
@@ -61,7 +61,7 @@ class TestSingleWriterShmRingBuffer(unittest.TestCase):
|
||||
self.assertEqual(read_id, monotonic_id)
|
||||
|
||||
def test_memory_error_on_full_buffer(self):
|
||||
"""Test that MemoryError is raised when buffer is full"""
|
||||
"""Test that MemoryError is raised when buffer is full."""
|
||||
small_buffer_size = 200
|
||||
self.ring_buffer = SingleWriterShmRingBuffer(
|
||||
data_buffer_size=small_buffer_size, create=True
|
||||
@@ -76,7 +76,7 @@ class TestSingleWriterShmRingBuffer(unittest.TestCase):
|
||||
self.ring_buffer.allocate_buf(1) # Would exceed buffer capacity
|
||||
|
||||
def test_allocation_and_free(self):
|
||||
"""Test allocation and freeing of buffers"""
|
||||
"""Test allocation and freeing of buffers."""
|
||||
small_buffer_size = 200
|
||||
self.ring_buffer = SingleWriterShmRingBuffer(
|
||||
data_buffer_size=small_buffer_size, create=True
|
||||
@@ -96,7 +96,7 @@ class TestSingleWriterShmRingBuffer(unittest.TestCase):
|
||||
self.assertEqual(freed_ids[0], i)
|
||||
|
||||
def test_clear_buffer(self):
|
||||
"""Test clearing the buffer"""
|
||||
"""Test clearing the buffer."""
|
||||
self.ring_buffer = SingleWriterShmRingBuffer(
|
||||
data_buffer_size=self.buffer_size, create=True
|
||||
)
|
||||
@@ -180,7 +180,7 @@ class TestSingleWriterShmRingBuffer(unittest.TestCase):
|
||||
|
||||
|
||||
def main():
|
||||
"""Main function demonstrating usage and running tests"""
|
||||
"""Main function demonstrating usage and running tests."""
|
||||
print("=== SingleWriterShmRingBuffer Test Suite ===\n")
|
||||
|
||||
# Run unit tests
|
||||
|
||||
@@ -254,10 +254,13 @@ def test_get_type_hints(type_hint, expected):
|
||||
assert get_type_hints(type_hint) == expected
|
||||
|
||||
|
||||
def test_get_kwargs():
|
||||
kwargs = get_kwargs(DummyConfig)
|
||||
print(kwargs)
|
||||
@pytest.fixture
|
||||
def dummy_config_kwargs():
|
||||
return get_kwargs(DummyConfig)
|
||||
|
||||
|
||||
def test_get_kwargs(dummy_config_kwargs):
|
||||
kwargs = dummy_config_kwargs
|
||||
# bools should not have their type set
|
||||
assert kwargs["regular_bool"].get("type") is None
|
||||
assert kwargs["optional_bool"].get("type") is None
|
||||
@@ -267,7 +270,7 @@ def test_get_kwargs():
|
||||
assert kwargs["optional_bool_or_str"]["const"] is True
|
||||
assert "action" not in kwargs["optional_bool_or_str"]
|
||||
# optional literals should have None as a choice
|
||||
assert kwargs["optional_literal"]["choices"] == ["x", "y", "None"]
|
||||
assert kwargs["optional_literal"]["choices"] == ["x", "y", None]
|
||||
# tuples should have the correct nargs
|
||||
assert kwargs["tuple_n"]["nargs"] == "+"
|
||||
assert kwargs["tuple_2"]["nargs"] == 2
|
||||
@@ -293,6 +296,22 @@ def test_get_kwargs():
|
||||
assert kwargs["nested_config"]["type"]('{"field": 2}') == NestedConfig(2) # type: ignore[call-arg]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("args", "expected"),
|
||||
[
|
||||
(["--optional-literal", "None"], None),
|
||||
(["--optional-literal", ""], None),
|
||||
(["--optional-literal", "x"], "x"),
|
||||
],
|
||||
)
|
||||
def test_optional_handling(args, expected, dummy_config_kwargs):
|
||||
parser = FlexibleArgumentParser()
|
||||
parser.add_argument("--optional-literal", **dummy_config_kwargs["optional_literal"])
|
||||
|
||||
assert parser.parse_args(args).optional_literal is expected
|
||||
assert "None" in parser.format_help()
|
||||
|
||||
|
||||
def test_jit_monitor_verbose_arg():
|
||||
parser = EngineArgs.add_cli_args(FlexibleArgumentParser())
|
||||
args = parser.parse_args(["--jit-monitor-verbose"])
|
||||
@@ -375,8 +394,7 @@ def test_media_io_kwargs_parser(arg, expected):
|
||||
],
|
||||
)
|
||||
def test_optimization_level(args, expected):
|
||||
"""
|
||||
Test space-separated optimization levels (-O 1, -O 2, -O 3) map to
|
||||
"""Test space-separated optimization levels (-O 1, -O 2, -O 3) map to
|
||||
optimization_level.
|
||||
"""
|
||||
parser = EngineArgs.add_cli_args(FlexibleArgumentParser())
|
||||
@@ -395,9 +413,7 @@ def test_optimization_level(args, expected):
|
||||
],
|
||||
)
|
||||
def test_mode_parser(args, expected):
|
||||
"""
|
||||
Test compilation config modes (-cc.mode=int) map to compilation_config.
|
||||
"""
|
||||
"""Test compilation config modes (-cc.mode=int) map to compilation_config."""
|
||||
parser = EngineArgs.add_cli_args(FlexibleArgumentParser())
|
||||
parsed_args = parser.parse_args(args)
|
||||
assert parsed_args.compilation_config.mode == expected
|
||||
|
||||
@@ -480,7 +480,7 @@ class TestThinkingBlockConversion:
|
||||
"""
|
||||
|
||||
def test_thinking_plus_text_in_assistant_message(self):
|
||||
"""thinking + text → reasoning field + plain-string content."""
|
||||
"""Thinking + text → reasoning field + plain-string content."""
|
||||
request = _make_request(
|
||||
[
|
||||
{"role": "user", "content": "Write me some code."},
|
||||
@@ -542,7 +542,7 @@ class TestThinkingBlockConversion:
|
||||
assert asst.get("content") is None
|
||||
|
||||
def test_thinking_plus_tool_use_in_assistant_message(self):
|
||||
"""thinking + tool_use: reasoning field set, tool_calls populated."""
|
||||
"""Thinking + tool_use: reasoning field set, tool_calls populated."""
|
||||
request = _make_request(
|
||||
[
|
||||
{"role": "user", "content": "What is 2+2?"},
|
||||
|
||||
@@ -152,7 +152,7 @@ def test_multiple_valid_inputs(serve_parser):
|
||||
|
||||
### Tests for serve argument validation that run prior to loading
|
||||
def test_enable_auto_choice_passes_without_tool_call_parser(serve_parser):
|
||||
"""Ensure validation fails if tool choice is enabled with no call 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"])
|
||||
with pytest.raises(TypeError):
|
||||
@@ -160,7 +160,7 @@ def test_enable_auto_choice_passes_without_tool_call_parser(serve_parser):
|
||||
|
||||
|
||||
def test_enable_auto_choice_passes_with_tool_call_parser(serve_parser):
|
||||
"""Ensure validation passes with tool choice enabled with a call parser"""
|
||||
"""Ensure validation passes with tool choice enabled with a call parser."""
|
||||
args = serve_parser.parse_args(
|
||||
args=[
|
||||
"--enable-auto-tool-choice",
|
||||
@@ -172,7 +172,7 @@ def test_enable_auto_choice_passes_with_tool_call_parser(serve_parser):
|
||||
|
||||
|
||||
def test_enable_auto_choice_fails_with_enable_reasoning(serve_parser):
|
||||
"""Ensure validation fails if reasoning is enabled with auto tool choice"""
|
||||
"""Ensure validation fails if reasoning is enabled with auto tool choice."""
|
||||
args = serve_parser.parse_args(
|
||||
args=[
|
||||
"--enable-auto-tool-choice",
|
||||
@@ -197,7 +197,7 @@ def test_passes_with_reasoning_parser(serve_parser):
|
||||
|
||||
|
||||
def test_chat_template_validation_for_happy_paths(serve_parser):
|
||||
"""Ensure validation passes if the chat template exists"""
|
||||
"""Ensure validation passes if the chat template exists."""
|
||||
args = serve_parser.parse_args(
|
||||
args=["--chat-template", CHATML_JINJA_PATH.absolute().as_posix()]
|
||||
)
|
||||
@@ -205,7 +205,7 @@ def test_chat_template_validation_for_happy_paths(serve_parser):
|
||||
|
||||
|
||||
def test_chat_template_validation_for_sad_paths(serve_parser):
|
||||
"""Ensure validation fails if the chat template doesn't exist"""
|
||||
"""Ensure validation fails if the chat template doesn't exist."""
|
||||
args = serve_parser.parse_args(args=["--chat-template", "does/not/exist"])
|
||||
with pytest.raises(VLLMValidationError):
|
||||
validate_parsed_serve_args(args)
|
||||
@@ -304,13 +304,13 @@ def test_sse_keep_alive_interval_non_integer(serve_parser, value):
|
||||
],
|
||||
)
|
||||
def test_middleware(serve_parser, cli_args, expected_middleware):
|
||||
"""Ensure multiple middleware args are parsed properly"""
|
||||
"""Ensure multiple middleware args are parsed properly."""
|
||||
args = serve_parser.parse_args(args=cli_args)
|
||||
assert args.middleware == expected_middleware
|
||||
|
||||
|
||||
def test_default_chat_template_kwargs_parsing(serve_parser):
|
||||
"""Ensure default_chat_template_kwargs JSON is parsed correctly"""
|
||||
"""Ensure default_chat_template_kwargs JSON is parsed correctly."""
|
||||
args = serve_parser.parse_args(
|
||||
args=["--default-chat-template-kwargs", '{"enable_thinking": false}']
|
||||
)
|
||||
@@ -318,7 +318,7 @@ def test_default_chat_template_kwargs_parsing(serve_parser):
|
||||
|
||||
|
||||
def test_default_chat_template_kwargs_complex(serve_parser):
|
||||
"""Ensure complex default_chat_template_kwargs JSON is parsed correctly"""
|
||||
"""Ensure complex default_chat_template_kwargs JSON is parsed correctly."""
|
||||
kwargs_json = '{"enable_thinking": false, "custom_param": "value", "num": 42}'
|
||||
args = serve_parser.parse_args(args=["--default-chat-template-kwargs", kwargs_json])
|
||||
assert args.default_chat_template_kwargs == {
|
||||
@@ -329,7 +329,7 @@ def test_default_chat_template_kwargs_complex(serve_parser):
|
||||
|
||||
|
||||
def test_default_chat_template_kwargs_default_none(serve_parser):
|
||||
"""Ensure default_chat_template_kwargs defaults to None"""
|
||||
"""Ensure default_chat_template_kwargs defaults to None."""
|
||||
args = serve_parser.parse_args(args=[])
|
||||
assert args.default_chat_template_kwargs is None
|
||||
|
||||
@@ -355,7 +355,7 @@ def test_resolve_default_chat_template_kwargs(default_kwargs, cohere_format, exp
|
||||
|
||||
|
||||
def test_default_chat_template_kwargs_invalid_json(serve_parser):
|
||||
"""Ensure invalid JSON raises an error"""
|
||||
"""Ensure invalid JSON raises an error."""
|
||||
with pytest.raises(SystemExit):
|
||||
serve_parser.parse_args(
|
||||
args=["--default-chat-template-kwargs", "not valid json"]
|
||||
@@ -402,7 +402,7 @@ def test_served_model_name_parsing(tmp_path, vllm_parser, args, raises):
|
||||
|
||||
### Tests for LoRA target modules parsing
|
||||
def test_lora_target_modules_single(serve_parser):
|
||||
"""Test parsing single lora-target-modules argument"""
|
||||
"""Test parsing single lora-target-modules argument."""
|
||||
args = serve_parser.parse_args(
|
||||
args=["--enable-lora", "--lora-target-modules", "o_proj"]
|
||||
)
|
||||
@@ -410,7 +410,7 @@ def test_lora_target_modules_single(serve_parser):
|
||||
|
||||
|
||||
def test_lora_target_modules_multiple(serve_parser):
|
||||
"""Test parsing multiple lora-target-modules arguments"""
|
||||
"""Test parsing multiple lora-target-modules arguments."""
|
||||
args = serve_parser.parse_args(
|
||||
args=[
|
||||
"--enable-lora",
|
||||
@@ -424,6 +424,6 @@ def test_lora_target_modules_multiple(serve_parser):
|
||||
|
||||
|
||||
def test_lora_target_modules_default_none(serve_parser):
|
||||
"""Test that lora-target-modules defaults to None"""
|
||||
"""Test that lora-target-modules defaults to None."""
|
||||
args = serve_parser.parse_args(args=[])
|
||||
assert args.lora_target_modules is None
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Tests for DPSupervisor: unit tests and lifecycle integration tests.
|
||||
"""Tests for DPSupervisor: unit tests and lifecycle integration tests.
|
||||
|
||||
Lifecycle integration tests replace child vLLM servers with lightweight
|
||||
aiohttp "fake" servers controlled by the test, so the suite runs without GPUs.
|
||||
@@ -463,8 +462,7 @@ async def test_start_server_no_log_config_when_no_filter(monkeypatch):
|
||||
|
||||
|
||||
class MockVLLMServer:
|
||||
"""
|
||||
Minimal FastAPI server that mimics one vLLM replica.
|
||||
"""Minimal FastAPI server that mimics one vLLM replica.
|
||||
GET /health returns 200 when healthy, 503 otherwise.
|
||||
Health state is toggled by the test via set_healthy().
|
||||
"""
|
||||
@@ -582,8 +580,7 @@ def launch_mock_vllm_with_drain(
|
||||
|
||||
|
||||
async def _poll_supervisor_health(expected_status: int, use_ssl: bool = False) -> bool:
|
||||
"""
|
||||
GET /health on the supervisor once and check for expected_status.
|
||||
"""GET /health on the supervisor once and check for expected_status.
|
||||
|
||||
Pass expected_status=-1 to assert the supervisor is not listening yet
|
||||
(a connection error is expected). The supervisor only starts its HTTP
|
||||
@@ -705,8 +702,7 @@ async def _run_supervisor(
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_basic_lifecycle(monkeypatch):
|
||||
"""
|
||||
A) Supervisor is not listening while children are unhealthy.
|
||||
"""A) Supervisor is not listening while children are unhealthy.
|
||||
B) /health returns 200 once every child reports healthy.
|
||||
C) SIGTERM and shutdown
|
||||
"""
|
||||
@@ -777,8 +773,7 @@ async def test_basic_lifecycle_with_ssl(monkeypatch):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_startup(monkeypatch):
|
||||
"""
|
||||
A) One of the vLLM servers crashes during startup.
|
||||
"""A) One of the vLLM servers crashes during startup.
|
||||
B) DPSupervisor detects this, and cleans up resources.
|
||||
"""
|
||||
args = _make_args()
|
||||
@@ -801,8 +796,7 @@ async def test_failed_startup(monkeypatch):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_becomes_unhealthy(monkeypatch):
|
||||
"""
|
||||
A) Supervisor is not listening while children are unhealthy.
|
||||
"""A) Supervisor is not listening while children are unhealthy.
|
||||
B) /health returns 200 once every child reports healthy.
|
||||
C) Child process becomes unhealthy.
|
||||
D) Detected and shutdown.
|
||||
@@ -842,8 +836,7 @@ async def test_becomes_unhealthy(monkeypatch):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dp_server_fails(monkeypatch):
|
||||
"""
|
||||
A) Supervisor is not listening while children are unhealthy.
|
||||
"""A) Supervisor is not listening while children are unhealthy.
|
||||
B) /health returns 200 once every child reports healthy.
|
||||
C) Child process fails.
|
||||
D) Detected and shutdown.
|
||||
@@ -886,8 +879,7 @@ async def test_dp_server_fails(monkeypatch):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_shutdown_timeout(monkeypatch: pytest.MonkeyPatch):
|
||||
"""
|
||||
Child mock servers delay shutdown by 10s on SIGTERM (simulating in-flight
|
||||
"""Child mock servers delay shutdown by 10s on SIGTERM (simulating in-flight
|
||||
request drain). The supervisor is configured with shutdown_timeout=10,
|
||||
so its total wait budget is 10 + CHILD_EXIT_GRACE_S seconds. The
|
||||
children exit naturally within that window, so no force-kill should occur
|
||||
|
||||
@@ -509,9 +509,7 @@ def test_completions():
|
||||
|
||||
|
||||
def test_completions_invalid_input():
|
||||
"""
|
||||
Ensure that we fail when the input doesn't conform to the openai api.
|
||||
"""
|
||||
"""Ensure that we fail when the input doesn't conform to the openai api."""
|
||||
with (
|
||||
tempfile.NamedTemporaryFile("w") as input_file,
|
||||
tempfile.NamedTemporaryFile("r") as output_file,
|
||||
@@ -602,9 +600,7 @@ def test_score(input_batch):
|
||||
|
||||
|
||||
def test_reasoning_parser():
|
||||
"""
|
||||
Test that reasoning_parser parameter works correctly in run_batch.
|
||||
"""
|
||||
"""Test that reasoning_parser parameter works correctly in run_batch."""
|
||||
with (
|
||||
tempfile.NamedTemporaryFile("w") as input_file,
|
||||
tempfile.NamedTemporaryFile("r") as output_file,
|
||||
@@ -767,8 +763,7 @@ def test_translation():
|
||||
|
||||
|
||||
def test_tool_calling():
|
||||
"""
|
||||
Test that tool calling works correctly in run_batch.
|
||||
"""Test that tool calling works correctly in run_batch.
|
||||
Verifies that requests with tools return tool_calls in the response.
|
||||
"""
|
||||
with (
|
||||
|
||||
@@ -134,7 +134,6 @@ async def test_shutdown_on_engine_failure(tmp_path: Path):
|
||||
Starts a vLLM server, kills it to simulate a crash, then verifies that
|
||||
subsequent API calls fail appropriately.
|
||||
"""
|
||||
|
||||
port = get_open_port()
|
||||
|
||||
# Redirect server output to a file rather than a pipe: nothing drains the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Tests for HF_HUB_OFFLINE mode"""
|
||||
"""Tests for HF_HUB_OFFLINE mode."""
|
||||
|
||||
import importlib
|
||||
import sys
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
This file test accuracy of the vLLM server via LMEval.
|
||||
"""This file test accuracy of the vLLM server via LMEval.
|
||||
It uses local-completions, which interacts with vLLM
|
||||
through the OAI API with N concurrent connections.
|
||||
This simulates real work usage of the API and makes
|
||||
@@ -33,7 +32,6 @@ EXPECTED_VALUES = {
|
||||
|
||||
def run_test(model_name, more_args=None):
|
||||
"""Run the end to end accuracy test."""
|
||||
|
||||
model_args = f"pretrained={model_name},max_model_len=4096"
|
||||
|
||||
if more_args is not None:
|
||||
@@ -64,7 +62,6 @@ TPU_TP_TEST_STR = "" # "tensor_parallel_size=4"
|
||||
@pytest.mark.parametrize("model", MODEL_NAMES)
|
||||
def test_lm_eval_accuracy_v1_engine(model):
|
||||
"""Run with the V1 Engine."""
|
||||
|
||||
more_args = None
|
||||
if current_platform.is_tpu():
|
||||
# Limit compilation time for TPU V1
|
||||
@@ -81,7 +78,6 @@ def test_lm_eval_accuracy_v1_engine(model):
|
||||
@pytest.mark.parametrize("model", FP8_KV_MODEL_NAMES)
|
||||
def test_lm_eval_accuracy_v1_engine_fp8_kv_cache(model):
|
||||
"""Run with the V1 Engine."""
|
||||
|
||||
more_args = None
|
||||
if current_platform.is_tpu():
|
||||
# Limit compilation time for TPU V1
|
||||
|
||||
@@ -20,8 +20,7 @@ def text_llm(vllm_runner):
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def llm_for_failure_test(vllm_runner):
|
||||
"""
|
||||
Fixture for testing issue #26081.
|
||||
"""Fixture for testing issue #26081.
|
||||
Uses a small max_model_len to easily trigger length errors.
|
||||
"""
|
||||
with vllm_runner(
|
||||
@@ -67,8 +66,7 @@ def test_multi_chat(text_llm):
|
||||
|
||||
|
||||
def test_llm_chat_tokenization_no_double_bos(text_llm):
|
||||
"""
|
||||
LLM.chat() should not add special tokens when using chat templates.
|
||||
"""LLM.chat() should not add special tokens when using chat templates.
|
||||
Check we get a single BOS token for llama chat.
|
||||
"""
|
||||
messages = [
|
||||
@@ -127,8 +125,7 @@ def test_chat_extra_kwargs(thinking_llm, enable_thinking):
|
||||
|
||||
|
||||
def test_chat_batch_failure_cleanup(llm_for_failure_test):
|
||||
"""
|
||||
Tests that if a batch call to llm.chat() fails mid-way
|
||||
"""Tests that if a batch call to llm.chat() fails mid-way
|
||||
(e.g., due to one invalid prompt), the requests that
|
||||
were already enqueued are properly aborted and do not
|
||||
pollute the queue for subsequent calls.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Test that ``InputProcessor.inject_into_mm_cache()`` correctly injects
|
||||
"""Test that ``InputProcessor.inject_into_mm_cache()`` correctly injects
|
||||
pre-processed mm_kwargs into the processor cache and reports MM cache
|
||||
hit rate metrics accurately.
|
||||
|
||||
|
||||
@@ -47,8 +47,7 @@ async def client(server):
|
||||
async def test_online_audio_in_video(
|
||||
client: openai.AsyncOpenAI, video_assets: VideoTestAssets
|
||||
):
|
||||
"""Test video input with `audio_in_video=True`"""
|
||||
|
||||
"""Test video input with `audio_in_video=True`."""
|
||||
# we don't use video_urls above because they missed audio stream.
|
||||
video_path = video_assets[0].video_path
|
||||
with open(video_path, "rb") as f:
|
||||
@@ -97,8 +96,7 @@ async def test_online_audio_in_video(
|
||||
async def test_online_audio_in_video_multi_videos(
|
||||
client: openai.AsyncOpenAI, video_assets: VideoTestAssets
|
||||
):
|
||||
"""Test multi-video input with `audio_in_video=True`"""
|
||||
|
||||
"""Test multi-video input with `audio_in_video=True`."""
|
||||
# we don't use video_urls above because they missed audio stream.
|
||||
video_path = video_assets[0].video_path
|
||||
with open(video_path, "rb") as f:
|
||||
@@ -151,8 +149,7 @@ async def test_online_audio_in_video_multi_videos(
|
||||
async def test_online_audio_in_video_interleaved(
|
||||
client: openai.AsyncOpenAI, video_assets: VideoTestAssets
|
||||
):
|
||||
"""Test interleaved video/audio input with `audio_in_video=True`"""
|
||||
|
||||
"""Test interleaved video/audio input with `audio_in_video=True`."""
|
||||
# we don't use video_urls above because they missed audio stream.
|
||||
video_path = video_assets[0].video_path
|
||||
with open(video_path, "rb") as f:
|
||||
|
||||
@@ -34,8 +34,7 @@ REQUIRED_BEAM_SEARCH_TERMS = [
|
||||
|
||||
|
||||
def check_output_matches_terms(content: str, term_groups: list[list[str]]) -> bool:
|
||||
"""
|
||||
Check if content matches all required term groups.
|
||||
"""Check if content matches all required term groups.
|
||||
Each term group requires at least one of its terms to be present.
|
||||
All term groups must be satisfied.
|
||||
"""
|
||||
|
||||
@@ -259,7 +259,7 @@ async def _generator(prompt_idx: int, text: str) -> AsyncGenerator[RequestOutput
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.skip_global_cleanup
|
||||
async def test_batched_echo_does_not_prepend_user_prompt() -> None:
|
||||
"""echo must only echo the assistant turn, never the user's prompt.
|
||||
"""Echo must only echo the assistant turn, never the user's prompt.
|
||||
|
||||
With `add_generation_prompt` (the default) the response role is `assistant`
|
||||
while the last conversation message is the user's, so there is nothing to
|
||||
|
||||
@@ -121,7 +121,7 @@ def _build_serving_chat(engine: AsyncLLM) -> OpenAIServingChat:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_error_non_stream():
|
||||
"""test finish_reason='error' returns 500 InternalServerError (non-streaming)"""
|
||||
"""Test finish_reason='error' returns 500 InternalServerError (non-streaming)."""
|
||||
mock_engine = MagicMock(spec=AsyncLLM)
|
||||
mock_engine.errored = False
|
||||
mock_engine.model_config = MockModelConfig()
|
||||
@@ -246,7 +246,7 @@ async def test_renderer_only_chat_request_skips_mm_cache():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_error_stream():
|
||||
"""test finish_reason='error' returns 500 InternalServerError (streaming)"""
|
||||
"""Test finish_reason='error' returns 500 InternalServerError (streaming)."""
|
||||
mock_engine = MagicMock(spec=AsyncLLM)
|
||||
mock_engine.errored = False
|
||||
mock_engine.model_config = MockModelConfig()
|
||||
|
||||
@@ -451,7 +451,7 @@ async def test_inconsistent_tool_choice_and_tools(
|
||||
async def test_max_tokens_with_tool_choice_required(
|
||||
client: openai.AsyncOpenAI, tool_choice
|
||||
):
|
||||
""" """
|
||||
"""Requesting a single token with a required tool choice must not crash."""
|
||||
models = await client.models.list()
|
||||
model_name: str = models.data[0].id
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ def stop_sign_image_url():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_translategemma_extra_lang_code_fields(client: openai.AsyncOpenAI):
|
||||
"""en -> es translation through TranslateGemma's bundled chat template's
|
||||
"""En -> es translation through TranslateGemma's bundled chat template's
|
||||
``text`` content branch, which depends on ``source_lang_code`` /
|
||||
``target_lang_code`` extra fields being preserved on the content part."""
|
||||
completion = await client.chat.completions.create(
|
||||
@@ -92,7 +92,7 @@ async def test_translategemma_image_extra_lang_code_fields(
|
||||
client: openai.AsyncOpenAI,
|
||||
stop_sign_image_url: str,
|
||||
):
|
||||
"""en -> es OCR-translation through TranslateGemma's bundled chat
|
||||
"""En -> es OCR-translation through TranslateGemma's bundled chat
|
||||
template's ``image`` content branch. Exercises the multimodal branch of
|
||||
``_collect_extra_fields`` in ``_parse_chat_message_content_part``: the
|
||||
``source_lang_code`` / ``target_lang_code`` extras must survive parsing
|
||||
|
||||
@@ -1232,7 +1232,6 @@ async def test_serving_chat_mistral_token_ids_prompt_is_validated():
|
||||
"""Regression test: when the Mistral tokenizer path returns token IDs
|
||||
directly, we must still apply input length + max_tokens validation.
|
||||
"""
|
||||
|
||||
mock_engine = MagicMock(spec=AsyncLLM)
|
||||
mock_engine.errored = False
|
||||
mock_engine.model_config = MockModelConfig(skip_tokenizer_init=True)
|
||||
@@ -1271,7 +1270,6 @@ async def test_serving_chat_mistral_token_ids_prompt_too_long_is_rejected():
|
||||
"""Regression test: MistralTokenizer token-id prompts must still enforce
|
||||
the max context length for the input itself (token_num >= max_model_len).
|
||||
"""
|
||||
|
||||
mock_engine = MagicMock(spec=AsyncLLM)
|
||||
mock_engine.errored = False
|
||||
mock_engine.model_config = MockModelConfig(skip_tokenizer_init=True)
|
||||
@@ -1512,8 +1510,7 @@ async def _render_chat_prompt_token_ids(
|
||||
|
||||
|
||||
class TestServingChatWithHarmony:
|
||||
"""
|
||||
These tests ensure Chat Completion requests are being properly converted into
|
||||
"""These tests ensure Chat Completion requests are being properly converted into
|
||||
Harmony messages and Harmony response messages back into Chat Completion responses.
|
||||
These tests are not exhaustive, but each one was created to cover a specific case
|
||||
that we got wrong but is now fixed.
|
||||
|
||||
@@ -33,7 +33,6 @@ def _count_reasoning_decode_token_ids_between_markers(
|
||||
reasoning_end_ids: list[int],
|
||||
) -> int | None:
|
||||
"""Count decode tokens in the thinking span (after last start, before first end)."""
|
||||
|
||||
if not reasoning_start_ids or not reasoning_end_ids:
|
||||
raise ValueError("reasoning marker token id lists must be non-empty")
|
||||
|
||||
@@ -153,7 +152,6 @@ async def client(request, server, server_with_auto_reasoning_config):
|
||||
async def test_thinking_token_budget_mixed_requests(client: openai.AsyncOpenAI):
|
||||
"""Test that mixed requests (some with thinking_token_budget, some without)
|
||||
complete successfully without errors."""
|
||||
|
||||
response_with_budget = await client.chat.completions.create(
|
||||
model=MODEL_NAME,
|
||||
messages=MESSAGES,
|
||||
@@ -182,7 +180,6 @@ async def test_thinking_token_budget_limits_reasoning(client: openai.AsyncOpenAI
|
||||
grouped into streamed chunks (a single chunk can carry several tokens under
|
||||
async scheduling / stream_interval > 1). Counting chunks under-counts.
|
||||
"""
|
||||
|
||||
tokenizer = get_tokenizer(tokenizer_name=MODEL_NAME)
|
||||
start_ids = list(tokenizer.encode(REASONING_START_STR, add_special_tokens=False))
|
||||
end_ids = list(tokenizer.encode(REASONING_END_STR, add_special_tokens=False))
|
||||
@@ -227,7 +224,6 @@ async def test_thinking_token_budget_qwen35_fp8_mtp_concurrent_mixed_budget_and_
|
||||
Qwen3.5 FP8 + MTP (TP=2) server. Budgeted calls are checked with
|
||||
``_count_reasoning_decode_token_ids_between_markers`` on full token ids.
|
||||
"""
|
||||
|
||||
_batch_spec: list[tuple[Literal["budget"], int] | tuple[Literal["plain"], None]] = [
|
||||
("budget", 1),
|
||||
("budget", 12),
|
||||
|
||||
@@ -350,7 +350,6 @@ async def test_parallel_no_streaming(client: openai.AsyncOpenAI, model_name: str
|
||||
"""Parallel sampling without streaming.
|
||||
A single request output contains a list of completions.
|
||||
"""
|
||||
|
||||
prompt = "What is an LLM?"
|
||||
n = 3
|
||||
max_tokens = 50
|
||||
@@ -396,7 +395,6 @@ async def test_parallel_streaming(client: openai.AsyncOpenAI, model_name: str):
|
||||
The tokens from multiple samples, are flattened into a single stream,
|
||||
with an index to indicate which sample the token belongs to.
|
||||
"""
|
||||
|
||||
prompt = "What is an LLM?"
|
||||
n = 3
|
||||
max_tokens = 50
|
||||
|
||||
@@ -303,7 +303,7 @@ def test_completion_metrics_carries_both_timing_and_spec_decode():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completion_error_non_stream():
|
||||
"""test finish_reason='error' returns 500 InternalServerError (non-streaming)"""
|
||||
"""Test finish_reason='error' returns 500 InternalServerError (non-streaming)."""
|
||||
mock_engine = MagicMock(spec=AsyncLLM)
|
||||
mock_engine.errored = False
|
||||
mock_engine.model_config = MockModelConfig()
|
||||
@@ -439,7 +439,7 @@ async def test_renderer_only_completion_request_skips_mm_cache():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_completion_error_stream():
|
||||
"""test finish_reason='error' returns 500 InternalServerError (streaming)"""
|
||||
"""Test finish_reason='error' returns 500 InternalServerError (streaming)."""
|
||||
mock_engine = MagicMock(spec=AsyncLLM)
|
||||
mock_engine.errored = False
|
||||
mock_engine.model_config = MockModelConfig()
|
||||
|
||||
@@ -39,8 +39,7 @@ def server():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_token_in_token_out_and_logprobs(server):
|
||||
"""
|
||||
Test token-in-token-out and token_ids align with prompt_logprobs
|
||||
"""Test token-in-token-out and token_ids align with prompt_logprobs
|
||||
& logprobs when return_tokens_as_token_ids is enabled.
|
||||
"""
|
||||
tokenizer = get_tokenizer(tokenizer_name=MODEL_NAME)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
This file test accuracy of the vLLM server via LMEval.
|
||||
"""This file test accuracy of the vLLM server via LMEval.
|
||||
It uses local-completions, which interacts with vLLM
|
||||
through the OAI API with N concurrent connections.
|
||||
This simulates real work usage of the API and makes
|
||||
@@ -37,7 +36,6 @@ if current_platform.is_tpu():
|
||||
|
||||
def run_test(more_args):
|
||||
"""Run the end to end accuracy test."""
|
||||
|
||||
args = list(DEFAULT_ARGS)
|
||||
args.extend(more_args)
|
||||
print(f"Running with: {args}")
|
||||
@@ -68,7 +66,6 @@ def run_test(more_args):
|
||||
|
||||
def test_lm_eval_accuracy_v1_engine():
|
||||
"""Run with the V1 Engine."""
|
||||
|
||||
more_args = []
|
||||
|
||||
# Limit compilation time for V1 on TPU
|
||||
|
||||
@@ -170,7 +170,7 @@ class TestIsFunctionRecipientWithAllowedNames:
|
||||
"""Tests for is_function_recipient with allowed_function_tool_names."""
|
||||
|
||||
def test_prefixed_always_accepted(self):
|
||||
"""functions. prefix is always accepted regardless of allowed names."""
|
||||
"""Functions. prefix is always accepted regardless of allowed names."""
|
||||
fn_names = frozenset({"other_tool"})
|
||||
assert is_function_recipient("functions.get_weather", fn_names) is True
|
||||
|
||||
@@ -252,8 +252,7 @@ class TestExtractFunctionFromRecipient:
|
||||
|
||||
|
||||
class TestCommonParseInputToHarmonyMessage:
|
||||
"""
|
||||
Tests for scenarios that are common to both Chat Completion
|
||||
"""Tests for scenarios that are common to both Chat Completion
|
||||
parse_chat_input_to_harmony_message and Responses API
|
||||
response_previous_input_to_harmony functions.
|
||||
"""
|
||||
@@ -448,8 +447,7 @@ class TestCommonParseInputToHarmonyMessage:
|
||||
|
||||
|
||||
class TestParseChatInputToHarmonyMessage:
|
||||
"""
|
||||
Tests for scenarios that are specific to the Chat Completion API
|
||||
"""Tests for scenarios that are specific to the Chat Completion API
|
||||
parse_chat_input_to_harmony_message function.
|
||||
"""
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from vllm.exceptions import GenerationError
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_raise_if_error_raises_generation_error():
|
||||
"""test _raise_if_error raises GenerationError"""
|
||||
"""Test _raise_if_error raises GenerationError."""
|
||||
# create a minimal GenerateBaseServing instance
|
||||
mock_engine = MagicMock()
|
||||
mock_engine.model_config = MagicMock()
|
||||
@@ -42,7 +42,7 @@ async def test_raise_if_error_raises_generation_error():
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_convert_generation_error_to_streaming_response():
|
||||
"""test _convert_generation_error_to_streaming_response output"""
|
||||
"""Test _convert_generation_error_to_streaming_response output."""
|
||||
mock_engine = MagicMock()
|
||||
mock_engine.model_config = MagicMock()
|
||||
mock_engine.model_config.max_model_len = 100
|
||||
|
||||
@@ -168,8 +168,7 @@ async def test_max_tokens_with_tool_choice_required(
|
||||
@pytest.mark.asyncio
|
||||
async def test_named_tool_use(client: openai.AsyncOpenAI):
|
||||
def get_weather(latitude: float, longitude: float) -> str:
|
||||
"""
|
||||
Mock function to simulate getting weather data.
|
||||
"""Mock function to simulate getting weather data.
|
||||
In a real application, this would call an external weather API.
|
||||
"""
|
||||
return f"Current temperature at ({latitude}, {longitude}) is 20°C."
|
||||
|
||||
@@ -57,7 +57,6 @@ def test_direct_function_call_object_preservation():
|
||||
|
||||
def test_mixed_input_types_with_function_calls():
|
||||
"""Test parsing with mixed input types including function calls."""
|
||||
|
||||
request_data = {
|
||||
"model": "gpt-oss",
|
||||
"input": [
|
||||
@@ -177,7 +176,6 @@ def test_empty_list_input():
|
||||
|
||||
def test_function_call_output_not_affected():
|
||||
"""Test that FunctionCallOutput is not affected by the function_call parsing."""
|
||||
|
||||
# Test with FunctionCallOutput as dict (should not be parsed)
|
||||
request_data = {
|
||||
"model": "gpt-oss",
|
||||
@@ -265,7 +263,6 @@ def test_function_call_validation_failure_logs_debug(caplog):
|
||||
|
||||
def test_validator_handles_iterator_input():
|
||||
"""Test that validator can handle ValidatorIterator input (Pydantic internal)."""
|
||||
|
||||
# This test simulates when Pydantic passes a ValidatorIterator instead of a list
|
||||
# This happened with complex nested structures containing reasoning + function_call
|
||||
|
||||
|
||||
@@ -20,8 +20,7 @@ from vllm.exceptions import VLLMValidationError
|
||||
|
||||
|
||||
class TestResponsePreviousInputToHarmony:
|
||||
"""
|
||||
Tests for scenarios that are specific to the Responses API
|
||||
"""Tests for scenarios that are specific to the Responses API
|
||||
response_previous_input_to_harmony function.
|
||||
"""
|
||||
|
||||
|
||||
@@ -36,9 +36,6 @@ class _NoOpParser(DelegatingParser):
|
||||
def is_reasoning_end(self, input_ids: list[int]) -> bool:
|
||||
return False
|
||||
|
||||
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
|
||||
return input_ids
|
||||
|
||||
def extract_reasoning(self, model_output, request):
|
||||
return None, model_output
|
||||
|
||||
@@ -63,9 +60,6 @@ class _ReasoningOnlyParser(DelegatingParser):
|
||||
def is_reasoning_end(self, input_ids: list[int]) -> bool:
|
||||
return False
|
||||
|
||||
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
|
||||
return input_ids
|
||||
|
||||
def extract_reasoning(self, model_output, request):
|
||||
if "<think>" in model_output and "</think>" in model_output:
|
||||
start = model_output.index("<think>") + len("<think>")
|
||||
@@ -131,9 +125,6 @@ class _ToolCallingParser(DelegatingParser):
|
||||
def is_reasoning_end(self, input_ids: list[int]) -> bool:
|
||||
return False
|
||||
|
||||
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
|
||||
return input_ids
|
||||
|
||||
def extract_reasoning(self, model_output, request):
|
||||
return None, model_output
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ from openai.types.responses import (
|
||||
ResponseTextConfig,
|
||||
ResponseTextDeltaEvent,
|
||||
)
|
||||
from openai.types.responses import (
|
||||
ResponseUsage as OpenAIResponseUsage,
|
||||
)
|
||||
from openai.types.responses.response_format_text_json_schema_config import (
|
||||
ResponseFormatTextJSONSchemaConfig,
|
||||
)
|
||||
@@ -45,6 +48,7 @@ from vllm.entrypoints.openai.responses.context import (
|
||||
SimpleContext,
|
||||
)
|
||||
from vllm.entrypoints.openai.responses.protocol import (
|
||||
ResponseCompletedEvent,
|
||||
ResponseCreatedEvent,
|
||||
ResponseRawMessageAndToken,
|
||||
ResponsesRequest,
|
||||
@@ -68,6 +72,7 @@ from vllm.renderers.online_renderer import (
|
||||
_extract_allowed_tools_from_mcp_requests,
|
||||
)
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.metrics.stats import RequestStateStats
|
||||
|
||||
pytestmark = pytest.mark.skip_global_cleanup
|
||||
|
||||
@@ -81,7 +86,7 @@ def _new_online_renderer() -> OnlineRenderer:
|
||||
|
||||
|
||||
class MockConversationContext(ConversationContext):
|
||||
"""Mock conversation context for testing"""
|
||||
"""Mock conversation context for testing."""
|
||||
|
||||
def __init__(self):
|
||||
self.init_tool_sessions_called = False
|
||||
@@ -123,7 +128,7 @@ def test_serialize_message_pydantic_model_returns_dict() -> None:
|
||||
|
||||
@pytest.fixture
|
||||
def mock_serving_responses():
|
||||
"""Create a mock OpenAIServingResponses instance"""
|
||||
"""Create a mock OpenAIServingResponses instance."""
|
||||
serving_responses = MagicMock(spec=OpenAIServingResponses)
|
||||
serving_responses.tool_server = MagicMock(spec=ToolServer)
|
||||
return serving_responses
|
||||
@@ -131,13 +136,13 @@ def mock_serving_responses():
|
||||
|
||||
@pytest.fixture
|
||||
def mock_context():
|
||||
"""Create a mock conversation context"""
|
||||
"""Create a mock conversation context."""
|
||||
return MockConversationContext()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_exit_stack():
|
||||
"""Create a mock async exit stack"""
|
||||
"""Create a mock async exit stack."""
|
||||
return MagicMock(spec=AsyncExitStack)
|
||||
|
||||
|
||||
@@ -550,7 +555,7 @@ def test_responses_render_result_rejects_non_single_prompt(engine_inputs):
|
||||
|
||||
|
||||
class TestInitializeToolSessions:
|
||||
"""Test class for _initialize_tool_sessions method"""
|
||||
"""Test class for _initialize_tool_sessions method."""
|
||||
|
||||
@pytest.fixture(params=[ParsableContext, HarmonyContext])
|
||||
def tool_context(self, request):
|
||||
@@ -635,7 +640,7 @@ class TestInitializeToolSessions:
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def serving_responses_instance(self):
|
||||
"""Create a real OpenAIServingResponses instance for testing"""
|
||||
"""Create a real OpenAIServingResponses instance for testing."""
|
||||
# Create minimal mocks for required dependencies
|
||||
engine_client = MagicMock()
|
||||
|
||||
@@ -792,6 +797,7 @@ class TestInitializeToolSessions:
|
||||
pass
|
||||
|
||||
assert serving_responses_instance.engine_client.generate.call_count == 2
|
||||
assert context.request_metrics_cover_all_generation_turns is False
|
||||
followup_engine_input = (
|
||||
serving_responses_instance.engine_client.generate.call_args_list[1].args[0]
|
||||
)
|
||||
@@ -802,8 +808,7 @@ class TestInitializeToolSessions:
|
||||
async def test_initialize_tool_sessions(
|
||||
self, serving_responses_instance, mock_context, mock_exit_stack
|
||||
):
|
||||
"""Test that method works correctly with only MCP tools"""
|
||||
|
||||
"""Test that method works correctly with only MCP tools."""
|
||||
request = ResponsesRequest(input="test input", tools=[])
|
||||
|
||||
# Call the method
|
||||
@@ -852,11 +857,11 @@ class TestInitializeToolSessions:
|
||||
|
||||
|
||||
class TestValidateGeneratorInput:
|
||||
"""Test class for _validate_generator_input method"""
|
||||
"""Test class for _validate_generator_input method."""
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def serving_responses_instance(self):
|
||||
"""Create a real OpenAIServingResponses instance for testing"""
|
||||
"""Create a real OpenAIServingResponses instance for testing."""
|
||||
# Create minimal mocks for required dependencies
|
||||
engine_client = MagicMock()
|
||||
|
||||
@@ -884,7 +889,7 @@ class TestValidateGeneratorInput:
|
||||
return instance
|
||||
|
||||
def test_validate_generator_input(self, serving_responses_instance):
|
||||
"""Test _validate_generator_input with valid prompt length"""
|
||||
"""Test _validate_generator_input with valid prompt length."""
|
||||
# Create an engine prompt with valid length (less than max_model_len)
|
||||
valid_prompt_token_ids = list(range(5)) # 5 tokens < 100 max_model_len
|
||||
engine_input = tokens_input(valid_prompt_token_ids)
|
||||
@@ -976,6 +981,7 @@ async def test_reasoning_tokens_counted_for_text_reasoning_model(monkeypatch):
|
||||
outputs=[completion],
|
||||
finished=True,
|
||||
num_cached_tokens=0,
|
||||
num_cache_creation_tokens=3,
|
||||
)
|
||||
context.append_output(req_output)
|
||||
|
||||
@@ -996,10 +1002,13 @@ async def test_reasoning_tokens_counted_for_text_reasoning_model(monkeypatch):
|
||||
)
|
||||
|
||||
assert response.usage.output_tokens_details.reasoning_tokens == 1
|
||||
assert response.usage.input_tokens_details.cache_write_tokens == 3
|
||||
|
||||
OpenAIResponseUsage.model_validate(response.usage.model_dump(mode="json"))
|
||||
|
||||
|
||||
class TestExtractAllowedToolsFromMcpRequests:
|
||||
"""Test class for _extract_allowed_tools_from_mcp_requests function"""
|
||||
"""Test class for _extract_allowed_tools_from_mcp_requests function."""
|
||||
|
||||
def test_extract_allowed_tools_basic_formats(self):
|
||||
"""Test extraction with list format, object format, and None."""
|
||||
@@ -1113,7 +1122,7 @@ class TestHarmonyPreambleStreaming:
|
||||
return item
|
||||
|
||||
def test_preamble_delta_emits_text_events(self) -> None:
|
||||
"""commentary + recipient=None should emit output_text.delta events."""
|
||||
"""Commentary + recipient=None should emit output_text.delta events."""
|
||||
from vllm.entrypoints.openai.responses.streaming_events import (
|
||||
emit_content_delta_events,
|
||||
)
|
||||
@@ -1146,7 +1155,7 @@ class TestHarmonyPreambleStreaming:
|
||||
assert "response.output_item.added" not in type_names
|
||||
|
||||
def test_commentary_with_function_recipient_not_preamble(self) -> None:
|
||||
"""commentary + recipient='functions.X' must NOT use preamble path."""
|
||||
"""Commentary + recipient='functions.X' must NOT use preamble path."""
|
||||
from vllm.entrypoints.openai.responses.streaming_events import (
|
||||
emit_content_delta_events,
|
||||
)
|
||||
@@ -1184,7 +1193,7 @@ class TestHarmonyPreambleStreaming:
|
||||
assert "response.output_item.done" in type_names
|
||||
|
||||
def test_commentary_with_recipient_no_preamble_done(self) -> None:
|
||||
"""commentary + recipient='functions.X' should route to function call
|
||||
"""Commentary + recipient='functions.X' should route to function call
|
||||
done, not preamble done."""
|
||||
from vllm.entrypoints.openai.responses.streaming_events import (
|
||||
emit_previous_item_done_events,
|
||||
@@ -1242,9 +1251,19 @@ class TestHarmonyPreambleStreaming:
|
||||
assert "response.output_item.done" in type_names
|
||||
|
||||
|
||||
def _make_simple_context_with_output(text, token_ids, response_parser=None):
|
||||
"""Create a SimpleContext with a RequestOutput containing the given text."""
|
||||
ctx = SimpleContext(response_parser=response_parser)
|
||||
_PER_REQUEST_STATS = RequestStateStats(
|
||||
queued_ts=1.0,
|
||||
scheduled_ts=1.5,
|
||||
first_token_ts=2.0,
|
||||
last_token_ts=3.0,
|
||||
)
|
||||
|
||||
|
||||
def _make_request_output(
|
||||
text,
|
||||
token_ids,
|
||||
metrics: RequestStateStats | None = None,
|
||||
):
|
||||
completion = CompletionOutput(
|
||||
index=0,
|
||||
text=text,
|
||||
@@ -1254,7 +1273,7 @@ def _make_simple_context_with_output(text, token_ids, response_parser=None):
|
||||
finish_reason=None,
|
||||
stop_reason=None,
|
||||
)
|
||||
req_output = RequestOutput(
|
||||
return RequestOutput(
|
||||
request_id="req",
|
||||
prompt="hi",
|
||||
prompt_token_ids=[7, 8],
|
||||
@@ -1262,13 +1281,29 @@ def _make_simple_context_with_output(text, token_ids, response_parser=None):
|
||||
outputs=[completion],
|
||||
finished=False,
|
||||
num_cached_tokens=0,
|
||||
metrics=metrics,
|
||||
)
|
||||
|
||||
|
||||
def _make_simple_context_with_output(
|
||||
text,
|
||||
token_ids,
|
||||
response_parser=None,
|
||||
metrics: RequestStateStats | None = None,
|
||||
):
|
||||
"""Create a SimpleContext with a RequestOutput containing the given text."""
|
||||
ctx = SimpleContext(response_parser=response_parser)
|
||||
req_output = _make_request_output(text, token_ids, metrics)
|
||||
ctx.append_output(req_output)
|
||||
ctx.request_metrics = metrics
|
||||
return ctx
|
||||
|
||||
|
||||
def _make_serving_instance_with_reasoning():
|
||||
"""Create an OpenAIServingResponses with a mocked reasoning parser."""
|
||||
def _make_serving_instance(
|
||||
*,
|
||||
reasoning_parser: str = "",
|
||||
enable_per_request_metrics: bool = False,
|
||||
) -> OpenAIServingResponses:
|
||||
engine_client = MagicMock()
|
||||
model_config = MagicMock()
|
||||
model_config.max_model_len = 100
|
||||
@@ -1279,18 +1314,112 @@ def _make_serving_instance_with_reasoning():
|
||||
engine_client.input_processor = MagicMock()
|
||||
engine_client.renderer = MagicMock()
|
||||
|
||||
models = MagicMock()
|
||||
|
||||
serving = OpenAIServingResponses(
|
||||
return OpenAIServingResponses(
|
||||
engine_client=engine_client,
|
||||
models=models,
|
||||
models=MagicMock(),
|
||||
online_renderer=MagicMock(),
|
||||
request_logger=None,
|
||||
chat_template=None,
|
||||
chat_template_content_format="auto",
|
||||
reasoning_parser="qwen3",
|
||||
reasoning_parser=reasoning_parser,
|
||||
enable_per_request_metrics=enable_per_request_metrics,
|
||||
)
|
||||
return serving
|
||||
|
||||
|
||||
async def _empty_context_generator():
|
||||
if False:
|
||||
yield
|
||||
|
||||
|
||||
async def _make_full_metrics_response(
|
||||
enable_per_request_metrics: bool,
|
||||
request_metrics_cover_all_generation_turns: bool = True,
|
||||
):
|
||||
serving = _make_serving_instance(
|
||||
enable_per_request_metrics=enable_per_request_metrics
|
||||
)
|
||||
request = ResponsesRequest(input="hi", tools=[], stream=False, store=False)
|
||||
sampling_params = SamplingParams(max_tokens=16)
|
||||
context = SimpleContext()
|
||||
context.request_metrics_cover_all_generation_turns = (
|
||||
request_metrics_cover_all_generation_turns
|
||||
)
|
||||
|
||||
async def generate(*args, **kwargs):
|
||||
yield _make_request_output("hello", [10, 20], _PER_REQUEST_STATS)
|
||||
|
||||
serving.engine_client.generate.side_effect = generate
|
||||
result_generator = serving._generate_with_builtin_tools(
|
||||
request_id=request.request_id,
|
||||
engine_input=tokens_input([7, 8]),
|
||||
sampling_params=sampling_params,
|
||||
context=context,
|
||||
)
|
||||
response = await serving.responses_full_generator(
|
||||
request=request,
|
||||
sampling_params=sampling_params,
|
||||
result_generator=result_generator,
|
||||
context=context,
|
||||
model_name="test-model",
|
||||
tokenizer=MagicMock(),
|
||||
request_metadata=RequestResponseMetadata(request_id="req"),
|
||||
)
|
||||
assert isinstance(response, ResponsesResponse)
|
||||
return response
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_responses_per_request_metrics_follow_server_flag():
|
||||
disabled_response = await _make_full_metrics_response(False)
|
||||
assert disabled_response.metrics is None
|
||||
assert "metrics" not in disabled_response.model_dump(mode="json")
|
||||
|
||||
enabled_response = await _make_full_metrics_response(True)
|
||||
assert enabled_response.metrics is not None
|
||||
assert enabled_response.metrics.time_to_first_token_ms == pytest.approx(500.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_responses_streaming_metrics_only_on_completed_event():
|
||||
serving = _make_serving_instance(enable_per_request_metrics=True)
|
||||
request = ResponsesRequest(input="hi", tools=[], stream=True, store=False)
|
||||
context = _make_simple_context_with_output(
|
||||
"hello", [10, 20], metrics=_PER_REQUEST_STATS
|
||||
)
|
||||
|
||||
events = [
|
||||
event
|
||||
async for event in serving.responses_stream_generator(
|
||||
request=request,
|
||||
sampling_params=SamplingParams(max_tokens=16),
|
||||
result_generator=_empty_context_generator(),
|
||||
context=context,
|
||||
model_name="test-model",
|
||||
tokenizer=MagicMock(),
|
||||
request_metadata=RequestResponseMetadata(request_id="req"),
|
||||
)
|
||||
]
|
||||
|
||||
for event in events[:-1]:
|
||||
assert "metrics" not in event.response.model_dump(mode="json")
|
||||
assert isinstance(events[-1], ResponseCompletedEvent)
|
||||
assert events[-1].response.metrics is not None
|
||||
assert events[-1].response.metrics.time_to_first_token_ms == pytest.approx(500.0)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_responses_metrics_suppressed_for_multiple_generation_turns():
|
||||
response = await _make_full_metrics_response(
|
||||
True, request_metrics_cover_all_generation_turns=False
|
||||
)
|
||||
|
||||
assert response.metrics is None
|
||||
assert "metrics" not in response.model_dump(mode="json")
|
||||
|
||||
|
||||
def _make_serving_instance_with_reasoning():
|
||||
"""Create an OpenAIServingResponses with a mocked reasoning parser."""
|
||||
return _make_serving_instance(reasoning_parser="qwen3")
|
||||
|
||||
|
||||
def _identity_increment(event):
|
||||
@@ -1342,7 +1471,6 @@ class TestStreamingReasoningToContentTransition:
|
||||
chunk), the trailing reasoning text must be emitted as a
|
||||
ResponseReasoningTextDeltaEvent and included in the
|
||||
ResponseReasoningTextDoneEvent text."""
|
||||
|
||||
monkeypatch.setattr(envs, "VLLM_USE_EXPERIMENTAL_PARSER_CONTEXT", False)
|
||||
serving = _make_serving_instance_with_reasoning()
|
||||
|
||||
@@ -1412,7 +1540,6 @@ class TestStreamingReasoningToContentTransition:
|
||||
):
|
||||
"""When the transition from reasoning to content is clean (no mixed
|
||||
delta), no extra reasoning delta event should be emitted."""
|
||||
|
||||
monkeypatch.setattr(envs, "VLLM_USE_EXPERIMENTAL_PARSER_CONTEXT", False)
|
||||
serving = _make_serving_instance_with_reasoning()
|
||||
|
||||
@@ -1474,7 +1601,6 @@ class TestStreamingReasoningToContentTransition:
|
||||
"""When the stream has only reasoning deltas and no content, the
|
||||
reasoning done event should be emitted at finalization with the
|
||||
full accumulated text, and no text delta events should appear."""
|
||||
|
||||
monkeypatch.setattr(envs, "VLLM_USE_EXPERIMENTAL_PARSER_CONTEXT", False)
|
||||
serving = _make_serving_instance_with_reasoning()
|
||||
|
||||
|
||||
@@ -83,8 +83,7 @@ def before_generate_case(context: schemathesis.HookContext, strategy):
|
||||
assert op is not None
|
||||
|
||||
def no_invalid_types(case: schemathesis.Case):
|
||||
"""
|
||||
Skips tool_calls with `"type": "custom"` which schemathesis incorrectly
|
||||
"""Skips tool_calls with `"type": "custom"` which schemathesis incorrectly
|
||||
generates instead of the valid `"type": "function"`.
|
||||
|
||||
Example test case that is skipped:
|
||||
|
||||
@@ -189,8 +189,7 @@ async def test_chat_completion_with_tool_use(server):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_comparison_with_prompt_logprobs_and_logprobs(server):
|
||||
"""
|
||||
Test that token_ids align with prompt_logprobs and
|
||||
"""Test that token_ids align with prompt_logprobs and
|
||||
logprobs when return_tokens_as_token_ids is enabled.
|
||||
"""
|
||||
async with server.get_async_client() as client:
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Unit tests for stop_token_ids propagation from default_sampling_params
|
||||
"""Unit tests for stop_token_ids propagation from default_sampling_params
|
||||
to SamplingParams in ChatCompletionRequest and CompletionRequest.
|
||||
|
||||
Regression test for https://github.com/vllm-project/vllm/issues/22519
|
||||
|
||||
@@ -31,9 +31,6 @@ class _DummyDelegatingParser(DelegatingParser):
|
||||
def is_reasoning_end(self, input_ids: list[int]) -> bool:
|
||||
return False
|
||||
|
||||
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
|
||||
return input_ids
|
||||
|
||||
def extract_reasoning(self, model_output: str, request):
|
||||
return None, model_output
|
||||
|
||||
|
||||
@@ -16,8 +16,7 @@ from vllm.entrypoints.serve.engine.protocol import UsageInfo
|
||||
async def accumulate_streaming_response(
|
||||
stream_generator: AsyncGenerator[str, None],
|
||||
) -> ChatCompletionResponse:
|
||||
"""
|
||||
Accumulate streaming SSE chunks into a complete ChatCompletionResponse.
|
||||
"""Accumulate streaming SSE chunks into a complete ChatCompletionResponse.
|
||||
|
||||
This helper parses the SSE format and builds up the complete response
|
||||
by combining all the delta chunks.
|
||||
|
||||
@@ -30,8 +30,7 @@ def llm(vllm_runner):
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_tiling_engine_basic(llm):
|
||||
"""
|
||||
Basic test with a small number of prompts (less than max_num_seqs).
|
||||
"""Basic test with a small number of prompts (less than max_num_seqs).
|
||||
No tiling should be triggered, but the engine still processes correctly.
|
||||
"""
|
||||
prompts = ["Hello", "World"]
|
||||
@@ -41,8 +40,7 @@ def test_tiling_engine_basic(llm):
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_tiling_engine_many_requests(llm):
|
||||
"""
|
||||
Test with a large number of prompts that exceeds max_num_seqs.
|
||||
"""Test with a large number of prompts that exceeds max_num_seqs.
|
||||
This verifies that _run_tiling_engine correctly chunks requests,
|
||||
processes all of them, and returns outputs in the correct order.
|
||||
"""
|
||||
@@ -54,8 +52,7 @@ def test_tiling_engine_many_requests(llm):
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_tiling_engine_with_pooling_params(llm):
|
||||
"""
|
||||
Test the tiling engine when different PoolingParams are provided.
|
||||
"""Test the tiling engine when different PoolingParams are provided.
|
||||
The engine must handle a list of params that matches the number of prompts.
|
||||
"""
|
||||
num_prompts = 10
|
||||
@@ -77,8 +74,7 @@ def test_tiling_engine_with_pooling_params(llm):
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_tiling_engine_abort_on_exception(llm):
|
||||
"""
|
||||
Test that abort_request IS called with the correct arguments when an
|
||||
"""Test that abort_request IS called with the correct arguments when an
|
||||
exception occurs inside the engine's step() loop.
|
||||
"""
|
||||
prompts = ["Prompt 0", "Prompt 1", "Prompt 2"]
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Run `pytest tests/entrypoints/openai/test_embedding_dimensions.py`.
|
||||
"""
|
||||
"""Run `pytest tests/entrypoints/openai/test_embedding_dimensions.py`."""
|
||||
|
||||
import openai
|
||||
import pytest
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Test cases for long text embedding with automatic chunking mechanism.
|
||||
"""Test cases for long text embedding with automatic chunking mechanism.
|
||||
|
||||
This test suite validates vLLM's automatic chunking functionality for handling
|
||||
text inputs that exceed the model's maximum token length, specifically targeting
|
||||
@@ -242,7 +241,6 @@ async def test_long_text_embedding_1500_chars(
|
||||
):
|
||||
"""Test embedding processing for ~1500 character long text
|
||||
(~1028 tokens, exceeding 512 token limit)."""
|
||||
|
||||
# Verify text length
|
||||
# Verify text has sufficient word count (approximately 1500 words)
|
||||
word_count = len(LONG_TEXT_1500_WORDS.split())
|
||||
@@ -291,7 +289,6 @@ async def test_long_text_embedding_2500_chars(
|
||||
):
|
||||
"""Test embedding processing for ~2500 character long text
|
||||
(~2048 tokens, requiring multiple chunks)."""
|
||||
|
||||
# Verify text length
|
||||
# Verify text has sufficient word count (approximately 2500 words)
|
||||
word_count = len(LONG_TEXT_2500_WORDS.split())
|
||||
@@ -339,7 +336,6 @@ async def test_batch_long_text_embedding(
|
||||
client_with_chunked_processing: openai.AsyncOpenAI, model_name: str
|
||||
):
|
||||
"""Test batch long text embedding processing."""
|
||||
|
||||
input_texts = [
|
||||
LONG_TEXT_1500_WORDS,
|
||||
LONG_TEXT_2500_WORDS,
|
||||
@@ -385,7 +381,6 @@ async def test_chunked_vs_normal_consistency(
|
||||
):
|
||||
"""Test consistency between chunked and
|
||||
normal processing (using short text)."""
|
||||
|
||||
# Use a short text within the 512 token limit
|
||||
short_text = (
|
||||
"Artificial intelligence technology is changing our world, "
|
||||
@@ -424,7 +419,6 @@ async def test_chunked_processing_response_format(
|
||||
client_with_chunked_processing: openai.AsyncOpenAI, model_name: str
|
||||
):
|
||||
"""Test response format and structure during chunked processing."""
|
||||
|
||||
# Test with long text to trigger chunking
|
||||
embedding_response = await client_with_chunked_processing.embeddings.create(
|
||||
model=model_name,
|
||||
|
||||
@@ -555,7 +555,7 @@ async def test_derender_chat_oversized_token_ids_rejected(client):
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_derender_chat_too_many_choices_rejected(client):
|
||||
"""choices count exceeding VLLM_MAX_N_SEQUENCES returns 400."""
|
||||
"""Choices count exceeding VLLM_MAX_N_SEQUENCES returns 400."""
|
||||
# Default VLLM_MAX_N_SEQUENCES is 16384; use a larger count.
|
||||
oversized_choices = [
|
||||
{"index": i, "token_ids": [42], "finish_reason": "stop"} for i in range(20_000)
|
||||
|
||||
@@ -41,7 +41,6 @@ def _make_stream_chunk(
|
||||
usage: dict | None = None,
|
||||
) -> GenerateStreamResponse:
|
||||
"""Build a GenerateStreamResponse SSE chunk."""
|
||||
|
||||
return GenerateStreamResponse(
|
||||
request_id=request_id,
|
||||
choices=[
|
||||
@@ -61,7 +60,6 @@ def _make_usage_chunk(
|
||||
request_id: str = "test-req",
|
||||
) -> GenerateStreamResponse:
|
||||
"""Build a usage only final SSE chunk (empty choices)."""
|
||||
|
||||
return GenerateStreamResponse(
|
||||
request_id=request_id,
|
||||
choices=[],
|
||||
@@ -531,7 +529,6 @@ async def client(server):
|
||||
|
||||
async def _render_chat(client) -> dict:
|
||||
"""Render a minimal chat request and return the GenerateRequest dict."""
|
||||
|
||||
resp = await client.post(
|
||||
"/v1/chat/completions/render",
|
||||
json={
|
||||
|
||||
@@ -337,7 +337,6 @@ async def test_chat_completion_render_multi_turn(client):
|
||||
@pytest.mark.asyncio
|
||||
async def test_chat_completion_render_with_stream_true(client):
|
||||
"""Render accepts stream params but still returns JSON (non-streamed)."""
|
||||
|
||||
response = await client.post(
|
||||
"/v1/chat/completions/render",
|
||||
json={
|
||||
|
||||
@@ -16,7 +16,6 @@ VISION_MODEL_NAME = "Qwen/Qwen3-VL-2B-Instruct"
|
||||
@pytest.fixture(scope="module")
|
||||
def vision_server():
|
||||
"""Vision-capable server used for multimodal /render tests."""
|
||||
|
||||
args = [
|
||||
"--enforce-eager",
|
||||
"--max-model-len",
|
||||
@@ -48,7 +47,6 @@ async def test_chat_completion_render_with_base64_image_url(
|
||||
local_asset_server,
|
||||
):
|
||||
"""Render a multimodal chat request and verify tokens are returned."""
|
||||
|
||||
image = local_asset_server.get_image_asset("RGBA_comp.png")
|
||||
data_url = encode_image_url(image, format="PNG")
|
||||
|
||||
@@ -112,7 +110,6 @@ async def test_tokenize_matches_render_for_multimodal_input(
|
||||
local_asset_server,
|
||||
):
|
||||
"""`/tokenize` should match `/v1/chat/completions/render` token output."""
|
||||
|
||||
image = local_asset_server.get_image_asset("RGBA_comp.png")
|
||||
data_url = encode_image_url(image, format="PNG")
|
||||
|
||||
|
||||
@@ -12,6 +12,9 @@ from vllm.config.multimodal import MultiModalConfig
|
||||
from vllm.entrypoints.generate.base.protocol import StreamOptions
|
||||
from vllm.entrypoints.openai.models.protocol import BaseModelPath
|
||||
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.mm_features import (
|
||||
placeholder_ranges_from_engine_input,
|
||||
)
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
GenerateRequest,
|
||||
GenerateResponse,
|
||||
@@ -19,6 +22,7 @@ from vllm.entrypoints.scale_out.token_in_token_out.protocol import (
|
||||
from vllm.entrypoints.scale_out.token_in_token_out.serving import ServingTokens
|
||||
from vllm.exceptions import GenerationError
|
||||
from vllm.logprobs import Logprob
|
||||
from vllm.multimodal.inputs import PlaceholderRange
|
||||
from vllm.outputs import CompletionOutput, RequestOutput
|
||||
from vllm.renderers import renderer_from_config
|
||||
from vllm.renderers.online_renderer import OnlineRenderer
|
||||
@@ -176,6 +180,29 @@ def _parse_sse_chunks(chunks: list[str]) -> list[Any]:
|
||||
return parsed
|
||||
|
||||
|
||||
def test_placeholder_ranges_from_engine_input():
|
||||
engine_input: Any = {
|
||||
"type": "multimodal",
|
||||
"mm_placeholders": {
|
||||
"image": [
|
||||
PlaceholderRange(offset=1, length=5),
|
||||
PlaceholderRange(offset=8, length=2),
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
placeholders = placeholder_ranges_from_engine_input(engine_input)
|
||||
|
||||
assert placeholders is not None
|
||||
assert [item.model_dump() for item in placeholders["image"]] == [
|
||||
{"offset": 1, "length": 5},
|
||||
{"offset": 8, "length": 2},
|
||||
]
|
||||
|
||||
text_only: Any = {"type": "token", "prompt_token_ids": [1, 2, 3]}
|
||||
assert placeholder_ranges_from_engine_input(text_only) is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_serve_tokens_skips_mm_cache_for_remote_engine_execution():
|
||||
engine = _mock_engine()
|
||||
@@ -294,6 +321,336 @@ async def test_stream_basic():
|
||||
assert data_chunks[2]["choices"][0]["finish_reason"] == "stop"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_stream_returns_final_prompt_token_ids_when_requested():
|
||||
engine = _mock_engine()
|
||||
final_prompt_token_ids = [1, 2, 2, 2, 3]
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1",
|
||||
token_ids=[10],
|
||||
finish_reason="stop",
|
||||
finished=True,
|
||||
prompt_token_ids=final_prompt_token_ids,
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
return_token_ids=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
|
||||
assert isinstance(response, GenerateResponse)
|
||||
assert response.prompt_token_ids == final_prompt_token_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_returns_prompt_token_ids_only_once_when_requested():
|
||||
engine = _mock_engine()
|
||||
final_prompt_token_ids = [1, 2, 2, 2, 3]
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[10], prompt_token_ids=final_prompt_token_ids
|
||||
)
|
||||
yield _make_request_output(
|
||||
"req-1",
|
||||
token_ids=[20],
|
||||
finish_reason="stop",
|
||||
finished=True,
|
||||
prompt_token_ids=final_prompt_token_ids,
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=2),
|
||||
model=MODEL_NAME,
|
||||
stream=True,
|
||||
return_token_ids=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
parsed = _parse_sse_chunks([chunk async for chunk in response])
|
||||
data_chunks = [c for c in parsed if isinstance(c, dict) and c.get("choices")]
|
||||
|
||||
assert data_chunks[0]["prompt_token_ids"] == final_prompt_token_ids
|
||||
assert "prompt_token_ids" not in data_chunks[1]
|
||||
|
||||
|
||||
MM_ENGINE_INPUT: Any = {
|
||||
"type": "multimodal",
|
||||
"prompt_token_ids": [1, 2, 2, 2, 3],
|
||||
"mm_placeholders": {"image": [PlaceholderRange(offset=1, length=3)]},
|
||||
}
|
||||
MM_PLACEHOLDERS = {"image": [{"offset": 1, "length": 3}]}
|
||||
|
||||
|
||||
def _build_mm_serving_tokens(engine: AsyncLLM) -> ServingTokens:
|
||||
serving = _build_serving_tokens(engine)
|
||||
|
||||
async def _fake_preprocess(*args, **kwargs):
|
||||
return [MM_ENGINE_INPUT]
|
||||
|
||||
serving.online_renderer.preprocess_completion = AsyncMock(
|
||||
side_effect=_fake_preprocess
|
||||
)
|
||||
return serving
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("return_token_ids", [False, True])
|
||||
async def test_non_stream_prompt_metadata_requires_return_token_ids(
|
||||
return_token_ids: bool,
|
||||
):
|
||||
engine = _mock_engine()
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[10], finish_reason="stop", finished=True
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_mm_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
return_token_ids=return_token_ids,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
|
||||
assert isinstance(response, GenerateResponse)
|
||||
if return_token_ids:
|
||||
assert response.prompt_token_ids == [1, 2, 3]
|
||||
assert response.model_dump()["mm_placeholders"] == MM_PLACEHOLDERS
|
||||
else:
|
||||
assert response.prompt_token_ids is None
|
||||
assert response.mm_placeholders is None
|
||||
assert request._response_mm_placeholders is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_stream_text_only_prompt_has_no_mm_placeholders():
|
||||
engine = _mock_engine()
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[10], finish_reason="stop", finished=True
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
return_token_ids=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
|
||||
assert isinstance(response, GenerateResponse)
|
||||
assert response.prompt_token_ids == [1, 2, 3]
|
||||
assert response.mm_placeholders is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_stream_encoder_decoder_omits_mm_placeholders():
|
||||
engine = _mock_engine()
|
||||
engine.model_config.is_encoder_decoder = True
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[10], finish_reason="stop", finished=True
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_mm_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
return_token_ids=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
|
||||
assert isinstance(response, GenerateResponse)
|
||||
assert response.prompt_token_ids == [1, 2, 3]
|
||||
assert response.mm_placeholders is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_prompt_metadata_lands_on_first_emitted_chunk():
|
||||
"""An empty first output is skipped; metadata goes on the first real chunk,
|
||||
once, and never on the sibling chunk of the same iteration (n=2)."""
|
||||
engine = _mock_engine()
|
||||
|
||||
def _two_outputs(tokens0: list[int], tokens1: list[int], **kwargs):
|
||||
res = _make_request_output("req-1", token_ids=tokens0, **kwargs)
|
||||
res.outputs.append(
|
||||
CompletionOutput(
|
||||
index=1,
|
||||
text="",
|
||||
token_ids=tokens1,
|
||||
cumulative_logprob=None,
|
||||
logprobs=None,
|
||||
finish_reason=kwargs.get("finish_reason"),
|
||||
)
|
||||
)
|
||||
return res
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _two_outputs([], [])
|
||||
yield _two_outputs([10], [11])
|
||||
yield _two_outputs([20], [21], finish_reason="stop", finished=True)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_mm_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=2, n=2),
|
||||
model=MODEL_NAME,
|
||||
stream=True,
|
||||
return_token_ids=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
parsed = _parse_sse_chunks([chunk async for chunk in response])
|
||||
data_chunks = [c for c in parsed if isinstance(c, dict) and c.get("choices")]
|
||||
|
||||
assert [c["choices"][0]["token_ids"] for c in data_chunks] == [
|
||||
[10],
|
||||
[11],
|
||||
[20],
|
||||
[21],
|
||||
]
|
||||
assert data_chunks[0]["prompt_token_ids"] == [1, 2, 3]
|
||||
assert data_chunks[0]["mm_placeholders"] == MM_PLACEHOLDERS
|
||||
for chunk in data_chunks[1:]:
|
||||
assert "prompt_token_ids" not in chunk
|
||||
assert "mm_placeholders" not in chunk
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_omits_prompt_metadata_by_default():
|
||||
engine = _mock_engine()
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[10], finish_reason="stop", finished=True
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_mm_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
parsed = _parse_sse_chunks([chunk async for chunk in response])
|
||||
data_chunks = [c for c in parsed if isinstance(c, dict) and c.get("choices")]
|
||||
|
||||
assert data_chunks
|
||||
for chunk in data_chunks:
|
||||
assert "prompt_token_ids" not in chunk
|
||||
assert "mm_placeholders" not in chunk
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_text_only_prompt_omits_mm_placeholders_key():
|
||||
engine = _mock_engine()
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[10], finish_reason="stop", finished=True
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
stream=True,
|
||||
return_token_ids=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
parsed = _parse_sse_chunks([chunk async for chunk in response])
|
||||
data_chunks = [c for c in parsed if isinstance(c, dict) and c.get("choices")]
|
||||
|
||||
assert data_chunks[0]["prompt_token_ids"] == [1, 2, 3]
|
||||
assert "mm_placeholders" not in data_chunks[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_zero_token_completion_still_delivers_prompt_metadata():
|
||||
engine = _mock_engine()
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[], finish_reason="stop", finished=True
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_mm_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
stream=True,
|
||||
return_token_ids=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
parsed = _parse_sse_chunks([chunk async for chunk in response])
|
||||
data_chunks = [c for c in parsed if isinstance(c, dict) and c.get("choices")]
|
||||
|
||||
assert len(data_chunks) == 1
|
||||
assert data_chunks[0]["choices"][0]["token_ids"] == []
|
||||
assert data_chunks[0]["choices"][0]["finish_reason"] == "stop"
|
||||
assert data_chunks[0]["prompt_token_ids"] == [1, 2, 3]
|
||||
assert data_chunks[0]["mm_placeholders"] == MM_PLACEHOLDERS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_zero_token_completion_emits_no_chunk_by_default():
|
||||
engine = _mock_engine()
|
||||
|
||||
async def mock_generate(*args, **kwargs):
|
||||
yield _make_request_output(
|
||||
"req-1", token_ids=[], finish_reason="stop", finished=True
|
||||
)
|
||||
|
||||
engine.generate = MagicMock(side_effect=mock_generate)
|
||||
serving = _build_serving_tokens(engine)
|
||||
request = GenerateRequest(
|
||||
token_ids=[1, 2, 3],
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
model=MODEL_NAME,
|
||||
stream=True,
|
||||
)
|
||||
|
||||
response = await serving.serve_tokens(request)
|
||||
parsed = _parse_sse_chunks([chunk async for chunk in response])
|
||||
|
||||
assert not [c for c in parsed if isinstance(c, dict) and c.get("choices")]
|
||||
assert parsed[-1] == "[DONE]"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stream_error_mid_generation():
|
||||
"""finish_reason='error' mid-stream yields error chunk then [DONE]."""
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Roundtrip tests for multimodal serde used by the
|
||||
"""Roundtrip tests for multimodal serde used by the
|
||||
token_in_token_out generate endpoint.
|
||||
"""
|
||||
|
||||
|
||||
@@ -154,11 +154,28 @@ async def test_render_to_generate_roundtrip(client, test_image):
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_content_parts_generates_tokens(client, test_image):
|
||||
"""content_parts with raw media should produce output tokens."""
|
||||
data_url = encode_image_url(test_image, format="PNG")
|
||||
def _collapse_placeholders(
|
||||
token_ids: list[int], mm_placeholders: dict[str, list[dict[str, int]]]
|
||||
) -> list[int]:
|
||||
"""Undo placeholder expansion: each expanded range becomes one token.
|
||||
|
||||
``/generate`` with ``content_parts`` expects unexpanded placeholders and
|
||||
expands them itself, so the roundtrip must start from a collapsed prompt.
|
||||
"""
|
||||
ranges = sorted(
|
||||
(r["offset"], r["length"]) for rs in mm_placeholders.values() for r in rs
|
||||
)
|
||||
collapsed: list[int] = []
|
||||
pos = 0
|
||||
for offset, length in ranges:
|
||||
collapsed.extend(token_ids[pos:offset])
|
||||
collapsed.append(token_ids[offset])
|
||||
pos = offset + length
|
||||
collapsed.extend(token_ids[pos:])
|
||||
return collapsed
|
||||
|
||||
|
||||
async def _render_image_prompt(client, data_url: str) -> dict:
|
||||
render_resp = await client.post(
|
||||
RENDER_ENDPOINT,
|
||||
json={
|
||||
@@ -175,14 +192,26 @@ async def test_content_parts_generates_tokens(client, test_image):
|
||||
},
|
||||
)
|
||||
render_resp.raise_for_status()
|
||||
token_ids = render_resp.json()["token_ids"]
|
||||
return render_resp.json()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_content_parts_generates_tokens(client, test_image):
|
||||
"""Unexpanded prompt + content_parts must expand exactly like /render."""
|
||||
data_url = encode_image_url(test_image, format="PNG")
|
||||
render_data = await _render_image_prompt(client, data_url)
|
||||
expanded = render_data["token_ids"]
|
||||
mm_placeholders = render_data["features"]["mm_placeholders"]
|
||||
unexpanded = _collapse_placeholders(expanded, mm_placeholders)
|
||||
assert len(unexpanded) < len(expanded)
|
||||
|
||||
gen_resp = await client.post(
|
||||
GEN_ENDPOINT,
|
||||
json={
|
||||
"token_ids": token_ids,
|
||||
"token_ids": unexpanded,
|
||||
"content_parts": [{"type": "image_url", "url": data_url}],
|
||||
"sampling_params": {"max_tokens": 10, "temperature": 0.0},
|
||||
"return_token_ids": True,
|
||||
},
|
||||
)
|
||||
gen_resp.raise_for_status()
|
||||
@@ -192,6 +221,8 @@ async def test_content_parts_generates_tokens(client, test_image):
|
||||
choice = gen_data["choices"][0]
|
||||
assert "token_ids" in choice
|
||||
assert len(choice["token_ids"]) > 0
|
||||
assert gen_data["prompt_token_ids"] == expanded
|
||||
assert gen_data["mm_placeholders"] == mm_placeholders
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -200,33 +231,20 @@ async def test_content_parts_streaming(client, test_image):
|
||||
import json as json_mod
|
||||
|
||||
data_url = encode_image_url(test_image, format="PNG")
|
||||
|
||||
render_resp = await client.post(
|
||||
RENDER_ENDPOINT,
|
||||
json={
|
||||
"model": MODEL_NAME,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "image_url", "image_url": {"url": data_url}},
|
||||
{"type": "text", "text": "Describe this."},
|
||||
],
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
render_resp.raise_for_status()
|
||||
token_ids = render_resp.json()["token_ids"]
|
||||
render_data = await _render_image_prompt(client, data_url)
|
||||
expanded = render_data["token_ids"]
|
||||
mm_placeholders = render_data["features"]["mm_placeholders"]
|
||||
unexpanded = _collapse_placeholders(expanded, mm_placeholders)
|
||||
|
||||
async with client.stream(
|
||||
"POST",
|
||||
GEN_ENDPOINT,
|
||||
json={
|
||||
"token_ids": token_ids,
|
||||
"token_ids": unexpanded,
|
||||
"content_parts": [{"type": "image_url", "url": data_url}],
|
||||
"sampling_params": {"max_tokens": 8, "temperature": 0.0},
|
||||
"stream": True,
|
||||
"return_token_ids": True,
|
||||
},
|
||||
) as resp:
|
||||
resp.raise_for_status()
|
||||
@@ -236,3 +254,9 @@ async def test_content_parts_streaming(client, test_image):
|
||||
chunks.append(json_mod.loads(line[6:]))
|
||||
|
||||
assert len(chunks) > 0
|
||||
prompt_metadata_chunks = [
|
||||
chunk for chunk in chunks if chunk.get("prompt_token_ids") is not None
|
||||
]
|
||||
assert len(prompt_metadata_chunks) == 1
|
||||
assert prompt_metadata_chunks[0]["prompt_token_ids"] == expanded
|
||||
assert prompt_metadata_chunks[0]["mm_placeholders"] == mm_placeholders
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Shared fixtures and helpers for the RL lifecycle test suite.
|
||||
"""Shared fixtures and helpers for the RL lifecycle test suite.
|
||||
|
||||
All test modules under this directory import from here to avoid duplication.
|
||||
|
||||
@@ -92,6 +91,7 @@ def server(
|
||||
port: HTTP port to bind (caller is responsible for uniqueness).
|
||||
timeout: Seconds to wait for /health before giving up.
|
||||
dummy_weights: If True, use --load-format dummy (fast, no real weights).
|
||||
|
||||
"""
|
||||
env = {**os.environ, "VLLM_SERVER_DEV_MODE": "1"}
|
||||
base = _DUMMY_ARGS if dummy_weights else _BASE_ARGS
|
||||
|
||||
@@ -25,7 +25,7 @@ class TestWorkerExtension:
|
||||
)
|
||||
|
||||
def return_none(self, *args, **kwargs) -> None:
|
||||
"""Test method that does not return anything"""
|
||||
"""Test method that does not return anything."""
|
||||
return
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ def server():
|
||||
|
||||
|
||||
def test_get_model_name(server):
|
||||
"""Test basic response"""
|
||||
"""Test basic response."""
|
||||
response = requests.post(
|
||||
server.url_for("collective_rpc"), json={"method": "get_model_name"}
|
||||
)
|
||||
@@ -59,7 +59,7 @@ def test_get_model_name(server):
|
||||
|
||||
|
||||
def test_return_none(server):
|
||||
"""Test return none"""
|
||||
"""Test return none."""
|
||||
response = requests.post(
|
||||
server.url_for("collective_rpc"), json={"method": "return_none"}
|
||||
)
|
||||
@@ -69,7 +69,7 @@ def test_return_none(server):
|
||||
|
||||
|
||||
def test_echo_args_kwargs(server):
|
||||
"""Test args, kwargs, and dict response"""
|
||||
"""Test args, kwargs, and dict response."""
|
||||
args = ["arg1", "arg2"]
|
||||
kwargs = {"key1": "value1", "key2": "value2"}
|
||||
response = requests.post(
|
||||
|
||||
@@ -87,8 +87,7 @@ def test_sleep_mode():
|
||||
|
||||
|
||||
def _get_sleep_metrics_from_api(response: requests.Response):
|
||||
"""Return (awake, weights_offloaded, discard_all)"""
|
||||
|
||||
"""Return (awake, weights_offloaded, discard_all)."""
|
||||
awake, weights_offloaded, discard_all = None, None, None
|
||||
|
||||
for family in text_string_to_metric_families(response.text):
|
||||
|
||||
@@ -21,7 +21,7 @@ MODEL_NAME = "Qwen/Qwen3-0.6B"
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def server_args(request: pytest.FixtureRequest) -> list[str]:
|
||||
"""Provide extra arguments to the server via indirect parametrization
|
||||
"""Provide extra arguments to the server via indirect parametrization.
|
||||
|
||||
Usage:
|
||||
|
||||
|
||||
@@ -403,8 +403,7 @@ async def _poll_until(
|
||||
|
||||
|
||||
def _get_running_metrics_from_api(server: RemoteOpenAIServer):
|
||||
"""Return (running_count, waiting_count, kv_cache_usage)"""
|
||||
|
||||
"""Return (running_count, waiting_count, kv_cache_usage)."""
|
||||
response = requests.get(server.url_for("metrics"))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ BADREQUEST_CASES = [
|
||||
(
|
||||
"test_modules_to_save",
|
||||
{"modules_to_save": ["lm_head"]},
|
||||
"only supports modules_to_save being None",
|
||||
"Unsupported modules_to_save",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Tests for middleware that's off by default and can be toggled through
|
||||
"""Tests for middleware that's off by default and can be toggled through
|
||||
server arguments, mainly --api-key and --enable-request-id-headers.
|
||||
"""
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user