[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests
- Drop dead model modules, keeping files live imports require - Remove anthropic, cohere, codegen entrypoints and batch STT modes - Delete unused attention backends, MoE experts, and NPU/XPU util leaves - Strip dead third_party trees and ROCm leaves with no CUDA path - Remove mooncake EC connectors: dependency missing since branch base - Re-audit verified by full import sweep and Qwen3.5 smoke test Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,332 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Test for the fix in PR #29987: Eagerly abort cancelled final-step requests.
|
||||
|
||||
This test verifies that when a request is aborted during its final execution
|
||||
step (when it would naturally complete), it is properly marked as aborted
|
||||
rather than being treated as normally completed.
|
||||
|
||||
The test uses a dummy KV connector to verify that the connector receives
|
||||
the correct finish status (FINISHED_ABORTED, not FINISHED_LENGTH_CAPPED).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorBase_V1,
|
||||
KVConnectorMetadata,
|
||||
KVConnectorRole,
|
||||
)
|
||||
from vllm.engine.arg_utils import AsyncEngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.utils.torch_utils import set_default_torch_num_threads
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.engine.async_llm import AsyncLLM
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.request import Request
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip(reason="V1 currently only supported on CUDA.", allow_module_level=True)
|
||||
|
||||
TEXT_PROMPT = "Hello"
|
||||
|
||||
|
||||
class DummyKVConnectorMetadata(KVConnectorMetadata):
|
||||
"""Dummy metadata for the test connector."""
|
||||
|
||||
def __init__(self):
|
||||
self.requests: list = []
|
||||
|
||||
|
||||
class DummyKVConnector(KVConnectorBase_V1):
|
||||
"""Dummy KV connector that captures request finish statuses to a file.
|
||||
This is used to verify the fix - without the fix, a request aborted
|
||||
during its final step would be captured as FINISHED_LENGTH_CAPPED
|
||||
instead of FINISHED_ABORTED.
|
||||
|
||||
The connector runs in a separate process, so we write statuses to a file
|
||||
that can be read by the test process.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
role: KVConnectorRole,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
):
|
||||
super().__init__(vllm_config, role, kv_cache_config)
|
||||
# Get the status file path from extra config
|
||||
extra_config = vllm_config.kv_transfer_config.kv_connector_extra_config or {}
|
||||
self.status_file = extra_config.get("status_file")
|
||||
# Log that we were initialized
|
||||
if self.status_file:
|
||||
try:
|
||||
with open(self.status_file, "a") as f:
|
||||
f.write(f"INIT:{role.name}\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def get_num_new_matched_tokens(
|
||||
self,
|
||||
request: Request,
|
||||
num_computed_tokens: int,
|
||||
) -> tuple[int | None, bool]:
|
||||
return (0, False)
|
||||
|
||||
def update_state_after_alloc(
|
||||
self,
|
||||
request: Request,
|
||||
blocks: Any,
|
||||
num_external_tokens: int,
|
||||
):
|
||||
pass
|
||||
|
||||
def build_connector_meta(
|
||||
self, scheduler_output: SchedulerOutput
|
||||
) -> KVConnectorMetadata:
|
||||
return DummyKVConnectorMetadata()
|
||||
|
||||
def request_finished(
|
||||
self,
|
||||
request: Request,
|
||||
block_ids: list[int],
|
||||
) -> tuple[bool, dict[str, Any] | None]:
|
||||
"""Capture the request status when finished by writing to a file."""
|
||||
if self.status_file:
|
||||
try:
|
||||
with open(self.status_file, "a") as f:
|
||||
# Write the status name (e.g., "FINISHED_ABORTED")
|
||||
f.write(f"{request.status.name}\n")
|
||||
except Exception as e:
|
||||
# Log but don't fail - this is just test instrumentation
|
||||
print(f"[DummyKVConnector] Failed to write status: {e}")
|
||||
return False, None
|
||||
|
||||
def start_load_kv(self, forward_context: Any, **kwargs: Any) -> None:
|
||||
pass
|
||||
|
||||
def wait_for_layer_load(self, layer_name: str) -> None:
|
||||
pass
|
||||
|
||||
def save_kv_layer(
|
||||
self,
|
||||
layer_name: str,
|
||||
kv_layer: Any,
|
||||
attn_metadata: Any,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def wait_for_save(self):
|
||||
pass
|
||||
|
||||
|
||||
# Register the dummy connector
|
||||
KVConnectorFactory.register_connector(
|
||||
"DummyKVConnector", __name__, DummyKVConnector.__name__
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_scheduling", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_abort_during_final_step(async_scheduling: bool):
|
||||
"""Test that a request aborted during its final execution step is treated as
|
||||
aborted rather than completed.
|
||||
|
||||
This test:
|
||||
1. Monkeypatches execute_model to wait for a file to be deleted
|
||||
2. Configures a dummy KV connector to capture finish statuses
|
||||
3. Starts a request with max_tokens=1 (will complete on first decode step)
|
||||
4. Aborts the request, then deletes the file to unblock execute_model
|
||||
5. Verifies the KV connector received FINISHED_ABORTED not FINISHED_LENGTH_CAPPED
|
||||
|
||||
See https://github.com/vllm-project/vllm/pull/29987.
|
||||
|
||||
Without the fix, the KV connector would see FINISHED_LENGTH_CAPPED because
|
||||
update_from_output() would mark the request as completed before processing
|
||||
the abort. This causes KV cache blocks to not be freed properly in
|
||||
disaggregated prefill scenarios.
|
||||
|
||||
With the fix, _process_aborts_queue() runs before update_from_output(), so the
|
||||
abort takes precedence and the KV connector sees FINISHED_ABORTED.
|
||||
"""
|
||||
# Create three temporary files:
|
||||
# 1. ready_file: deleted by execute_model to signal it has started
|
||||
# 2. block_file: execute_model waits for this to be deleted
|
||||
# 3. status_file: KV connector writes finish statuses here
|
||||
with tempfile.NamedTemporaryFile(delete=False) as f:
|
||||
ready_file = Path(f.name)
|
||||
with tempfile.NamedTemporaryFile(delete=False) as f2:
|
||||
block_file = Path(f2.name)
|
||||
with tempfile.NamedTemporaryFile(delete=False, mode="w") as f3:
|
||||
status_file = Path(f3.name)
|
||||
|
||||
try:
|
||||
# Get the original execute_model method
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
|
||||
original_execute_model = Worker.execute_model
|
||||
|
||||
def execute_model_with_wait(self, scheduler_output):
|
||||
# V2's `gpu_worker.compile_or_warm_up_model` calls
|
||||
# `warmup_kernels(...)` during engine init, which itself calls
|
||||
# `Worker.execute_model` three times (prefill / decode / cleanup)
|
||||
# to JIT compile triton kernels. None of those carry the test's
|
||||
# request id, so we only stall when our actual request is being
|
||||
# processed.
|
||||
scheduled = scheduler_output.num_scheduled_tokens or {}
|
||||
finished = scheduler_output.finished_req_ids or set()
|
||||
|
||||
def is_target_request(req_ids):
|
||||
return any(
|
||||
rid == request_id or rid.startswith(f"{request_id}-")
|
||||
for rid in req_ids
|
||||
)
|
||||
|
||||
if is_target_request(scheduled) or is_target_request(finished):
|
||||
# Signal that execute_model has been called by deleting ready_file
|
||||
if ready_file.exists():
|
||||
ready_file.unlink()
|
||||
|
||||
# Wait for the block file to be deleted (triggered from test after
|
||||
# abort). This runs in the worker process (after fork), so we poll
|
||||
# the filesystem.
|
||||
while block_file.exists():
|
||||
time.sleep(0.01)
|
||||
return original_execute_model(self, scheduler_output)
|
||||
|
||||
# Patch execute_model to inject the wait
|
||||
# This happens before the worker process is forked, so the patch applies there
|
||||
with patch.object(Worker, "execute_model", execute_model_with_wait):
|
||||
request_id = "test-abort-final-step"
|
||||
|
||||
# Configure engine with dummy KV connector
|
||||
# Pass the status file path so the connector can write to it
|
||||
kv_transfer_config = KVTransferConfig(
|
||||
kv_connector="DummyKVConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"status_file": str(status_file)},
|
||||
)
|
||||
engine_args = AsyncEngineArgs(
|
||||
model="meta-llama/Llama-3.2-1B-Instruct",
|
||||
enforce_eager=True,
|
||||
async_scheduling=async_scheduling,
|
||||
kv_transfer_config=kv_transfer_config,
|
||||
)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine = AsyncLLM.from_engine_args(engine_args)
|
||||
|
||||
try:
|
||||
# Create a request that will complete after just 1 token
|
||||
sampling_params = SamplingParams(
|
||||
max_tokens=1,
|
||||
ignore_eos=True,
|
||||
output_kind=RequestOutputKind.DELTA,
|
||||
)
|
||||
|
||||
# Start generation in a task
|
||||
outputs = []
|
||||
|
||||
async def generate():
|
||||
async for output in engine.generate(
|
||||
request_id=request_id,
|
||||
prompt=TEXT_PROMPT,
|
||||
sampling_params=sampling_params,
|
||||
):
|
||||
outputs.append(output)
|
||||
|
||||
gen_task = asyncio.create_task(generate())
|
||||
|
||||
# Wait for execute_model to signal it has started (with timeout)
|
||||
timeout = 5.0 # 5 second timeout
|
||||
start_time = time.time()
|
||||
while ready_file.exists():
|
||||
if time.time() - start_time > timeout:
|
||||
raise TimeoutError(
|
||||
"Timeout waiting for execute_model to start. "
|
||||
"The monkeypatch may not be working correctly, "
|
||||
"for example if spawn was used instead of fork."
|
||||
)
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
# Abort the request while execute_model is blocked
|
||||
await engine.abort(request_id)
|
||||
|
||||
# Now unblock execute_model by deleting the file
|
||||
# The abort should be processed before the model output
|
||||
block_file.unlink()
|
||||
|
||||
# Wait for generation to complete
|
||||
await gen_task
|
||||
|
||||
# Poll for the KV connector to record the finish status
|
||||
timeout = 5.0
|
||||
start = time.time()
|
||||
captured_statuses = []
|
||||
while time.time() - start < timeout:
|
||||
with open(status_file) as f4:
|
||||
status_lines = f4.read().strip().split("\n")
|
||||
captured_statuses = [
|
||||
line
|
||||
for line in status_lines
|
||||
if line and line.startswith("FINISHED_")
|
||||
]
|
||||
if captured_statuses:
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
else:
|
||||
raise TimeoutError(
|
||||
"Timeout waiting for KV connector to record finish status."
|
||||
)
|
||||
|
||||
# Verify we got output
|
||||
assert len(outputs) > 0, "Should have received at least one output"
|
||||
|
||||
# The final output should have finish_reason="abort"
|
||||
final_output = outputs[-1]
|
||||
assert final_output.finished, (
|
||||
"Final output should be marked as finished"
|
||||
)
|
||||
assert final_output.outputs[0].finish_reason == "abort", (
|
||||
f"Expected finish_reason='abort' but got "
|
||||
f"'{final_output.outputs[0].finish_reason}'. "
|
||||
)
|
||||
|
||||
assert len(captured_statuses) >= 1, (
|
||||
f"Expected at least 1 captured finish status, got "
|
||||
f"{len(captured_statuses)}. File content: {status_lines}"
|
||||
)
|
||||
|
||||
assert "FINISHED_ABORTED" in captured_statuses, (
|
||||
f"KV connector should see FINISHED_ABORTED but got "
|
||||
f"{captured_statuses}. "
|
||||
)
|
||||
|
||||
# Verify cleanup
|
||||
assert not engine.output_processor.has_unfinished_requests()
|
||||
|
||||
finally:
|
||||
# Shutdown the engine
|
||||
engine.shutdown()
|
||||
|
||||
finally:
|
||||
# Clean up temporary files if they still exist
|
||||
if ready_file.exists():
|
||||
ready_file.unlink()
|
||||
if block_file.exists():
|
||||
block_file.unlink()
|
||||
if status_file.exists():
|
||||
status_file.unlink()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,794 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import copy
|
||||
import time
|
||||
import uuid
|
||||
from collections import deque
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from unittest.mock import MagicMock, PropertyMock, patch
|
||||
|
||||
import pytest
|
||||
from transformers import AutoTokenizer
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import (
|
||||
CacheConfig,
|
||||
ECTransferConfig,
|
||||
KVTransferConfig,
|
||||
ModelConfig,
|
||||
ParallelConfig,
|
||||
SchedulerConfig,
|
||||
VllmConfig,
|
||||
)
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import set_default_torch_num_threads
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
from vllm.v1.engine import EngineCoreRequest, EngineCoreRequestType
|
||||
from vllm.v1.engine.core import DPEngineCoreProc, EngineCore, EngineCoreProc
|
||||
from vllm.v1.executor.abstract import Executor
|
||||
from vllm.v1.executor.uniproc_executor import UniProcExecutor
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.outputs import ModelRunnerOutput
|
||||
|
||||
from ...utils import create_new_process_for_each_test, multi_gpu_test
|
||||
|
||||
if not current_platform.is_cuda():
|
||||
pytest.skip(reason="V1 currently only supported on CUDA.", allow_module_level=True)
|
||||
|
||||
MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
|
||||
TOKENIZER = AutoTokenizer.from_pretrained(MODEL_NAME)
|
||||
# test_engine_core_concurrent_batches assumes exactly 12 tokens per prompt.
|
||||
# Adjust prompt if changing model to maintain 12-token length.
|
||||
PROMPT = "I am Gyoubu Masataka Oniwa"
|
||||
PROMPT_TOKENS = TOKENIZER(PROMPT).input_ids
|
||||
|
||||
_REQUEST_COUNTER = 0
|
||||
|
||||
|
||||
def make_request() -> EngineCoreRequest:
|
||||
global _REQUEST_COUNTER
|
||||
_REQUEST_COUNTER += 1
|
||||
request_id = f"request-{_REQUEST_COUNTER}"
|
||||
return EngineCoreRequest(
|
||||
request_id=request_id,
|
||||
external_req_id=f"{request_id}-{uuid.uuid4()}",
|
||||
prompt_token_ids=PROMPT_TOKENS,
|
||||
mm_features=None,
|
||||
sampling_params=SamplingParams(),
|
||||
pooling_params=None,
|
||||
arrival_time=time.time(),
|
||||
lora_request=None,
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core():
|
||||
"""Setup the EngineCore."""
|
||||
engine_args = EngineArgs(model=MODEL_NAME)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
"""Test basic request lifecycle."""
|
||||
|
||||
# First request.
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 1
|
||||
|
||||
# Second request.
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 1
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
# Add two requests in a row.
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(make_request()))
|
||||
assert len(engine_core.scheduler.waiting) == 2
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 4
|
||||
|
||||
# Loop through until they are all done.
|
||||
while (outs := engine_core.step_fn()[0].get(0)) and outs.outputs:
|
||||
pass
|
||||
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
"""Test abort cycle."""
|
||||
|
||||
# Basic abort.
|
||||
req = make_request()
|
||||
request_id = req.request_id
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
assert engine_core.scheduler.has_unfinished_requests()
|
||||
assert not engine_core.scheduler.has_finished_requests()
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 1
|
||||
assert engine_core.scheduler.has_unfinished_requests()
|
||||
assert not engine_core.scheduler.has_finished_requests()
|
||||
|
||||
engine_core.abort_requests([request_id])
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
assert not engine_core.scheduler.has_unfinished_requests()
|
||||
assert engine_core.scheduler.has_finished_requests()
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert not engine_core.scheduler.has_unfinished_requests()
|
||||
assert not engine_core.scheduler.has_finished_requests()
|
||||
|
||||
# Add, step, abort 1 of the 3.
|
||||
req0 = make_request()
|
||||
req1 = make_request()
|
||||
req2 = make_request()
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req0))
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req1))
|
||||
assert len(engine_core.scheduler.waiting) == 2
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req2))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 3
|
||||
|
||||
# Abort just one.
|
||||
engine_core.abort_requests([req1.request_id])
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
_ = engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 2
|
||||
|
||||
# Abort the other requests at the same time.
|
||||
engine_core.abort_requests([req2.request_id, req0.request_id])
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
# Sending duplicate requests with same request_id
|
||||
req0 = make_request()
|
||||
req1 = make_request()
|
||||
req0.request_id = req1.request_id = "test"
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req0))
|
||||
|
||||
while engine_core.scheduler.has_requests():
|
||||
engine_core.step_fn()
|
||||
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req1))
|
||||
while engine_core.scheduler.has_requests():
|
||||
engine_core.step_fn()
|
||||
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core_advanced_sampling():
|
||||
"""A basic end-to-end test to verify that the engine functions correctly
|
||||
when additional sampling parameters, such as top_p, min_tokens, and
|
||||
presence_penalty, are set.
|
||||
"""
|
||||
"""Setup the EngineCore."""
|
||||
engine_args = EngineArgs(model=MODEL_NAME)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
"""Test basic request lifecycle."""
|
||||
# First request.
|
||||
request: EngineCoreRequest = make_request()
|
||||
request.sampling_params = SamplingParams(
|
||||
min_tokens=4,
|
||||
presence_penalty=1.0,
|
||||
frequency_penalty=1.0,
|
||||
repetition_penalty=0.1,
|
||||
stop_token_ids=[1001, 1002],
|
||||
)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(request))
|
||||
|
||||
def _check_engine_state():
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
# Loop through until they are all done.
|
||||
while engine_core.scheduler.has_requests():
|
||||
engine_core.step_fn()
|
||||
assert len(engine_core.scheduler.waiting) == 0
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
_check_engine_state()
|
||||
|
||||
# Second request.
|
||||
request2 = make_request()
|
||||
request2.sampling_params = SamplingParams(
|
||||
top_p=0.99,
|
||||
top_k=50,
|
||||
)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(request2))
|
||||
_check_engine_state()
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core_concurrent_batches():
|
||||
"""Test that the engine can handle multiple concurrent batches."""
|
||||
|
||||
def make_request_with_max_tokens(req_id: str, max_tokens: int) -> EngineCoreRequest:
|
||||
request = make_request()
|
||||
request.request_id = req_id
|
||||
request.sampling_params.max_tokens = max_tokens
|
||||
return request
|
||||
|
||||
class DummyExecutor(UniProcExecutor):
|
||||
def initialize_from_config(self, kv_cache_configs: list[KVCacheConfig]) -> None:
|
||||
super().initialize_from_config(kv_cache_configs)
|
||||
|
||||
# Create a thread pool with a single worker
|
||||
self.thread_pool = ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
def execute_model(
|
||||
self,
|
||||
scheduler_output,
|
||||
non_block=False,
|
||||
) -> Future[ModelRunnerOutput | None]:
|
||||
"""Make execute_model non-blocking."""
|
||||
# DummyExecutor used only for testing async case.
|
||||
assert non_block
|
||||
|
||||
def _execute():
|
||||
output = self.collective_rpc("execute_model", args=(scheduler_output,))
|
||||
# Make a copy because output[0] may be reused
|
||||
# by the next batch.
|
||||
return copy.deepcopy(output[0])
|
||||
|
||||
# Use the thread pool instead of creating a new thread
|
||||
return self.thread_pool.submit(_execute)
|
||||
|
||||
def sample_tokens(
|
||||
self, grammar_output, non_block=False
|
||||
) -> Future[ModelRunnerOutput]:
|
||||
"""Make sample_tokens non-blocking."""
|
||||
# DummyExecutor used only for testing async case.
|
||||
assert non_block
|
||||
|
||||
def _execute():
|
||||
output = self.collective_rpc("sample_tokens", args=(grammar_output,))
|
||||
# Make a copy because output[0] may be reused
|
||||
# by the next batch.
|
||||
return copy.deepcopy(output[0])
|
||||
|
||||
# Use the thread pool instead of creating a new thread
|
||||
return self.thread_pool.submit(_execute)
|
||||
|
||||
def shutdown(self):
|
||||
if hasattr(self, "thread_pool"):
|
||||
self.thread_pool.shutdown(wait=False)
|
||||
|
||||
engine_args = EngineArgs(
|
||||
model=MODEL_NAME,
|
||||
# To test concurrent batches.
|
||||
max_num_seqs=2,
|
||||
# Avoid all requests being scheduled once.
|
||||
enable_prefix_caching=False,
|
||||
max_num_batched_tokens=10,
|
||||
# Reduce startup time.
|
||||
enforce_eager=True,
|
||||
# Test concurrent batch behaviour independently of async scheduling.
|
||||
async_scheduling=False,
|
||||
)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
# Force two concurrent batches to exercise the batch queue independently
|
||||
# of async scheduling (which is disabled above).
|
||||
with (
|
||||
set_default_torch_num_threads(1),
|
||||
patch.object(
|
||||
VllmConfig,
|
||||
"max_concurrent_batches",
|
||||
new_callable=PropertyMock,
|
||||
return_value=2,
|
||||
),
|
||||
):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, log_stats=False, executor_class=DummyExecutor
|
||||
)
|
||||
assert engine_core.batch_queue is not None
|
||||
|
||||
# Add two requests in a row. Each request have 12 prompt tokens.
|
||||
req0 = make_request_with_max_tokens("0", 5)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req0))
|
||||
req1 = make_request_with_max_tokens("1", 5)
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(req1))
|
||||
|
||||
# Schedule Batch 1: (10, req0)
|
||||
assert engine_core.step_with_batch_queue()[0] is None
|
||||
assert len(engine_core.batch_queue) == 1
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["0"] == 10
|
||||
# num_computed_tokens should have been updated immediately.
|
||||
assert engine_core.scheduler.requests[req0.request_id].num_computed_tokens == 10
|
||||
|
||||
# Schedule Batch 2: (2, req0), (8, req1)
|
||||
assert engine_core.step_with_batch_queue()[0] == {}
|
||||
assert len(engine_core.batch_queue) == 1
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["0"] == 2
|
||||
assert scheduler_output.num_scheduled_tokens["1"] == 8
|
||||
# num_computed_tokens should have been updated immediately.
|
||||
assert engine_core.scheduler.requests["0"].num_computed_tokens == 12
|
||||
assert engine_core.scheduler.requests["1"].num_computed_tokens == 8
|
||||
|
||||
assert engine_core.scheduler.get_num_unfinished_requests() == 2
|
||||
|
||||
# Finish Batch 1 and schedule Batch 3: (4, req1).
|
||||
# Note that req0 cannot be scheduled
|
||||
# because it is in the decoding stage now.
|
||||
engine_core.step_with_batch_queue()
|
||||
assert len(engine_core.batch_queue) == 1
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["1"] == 4
|
||||
|
||||
# Finish Batch 2. Get first token of req0.
|
||||
# Schedule Batch 4: (1, req0).
|
||||
output = engine_core.step_with_batch_queue()[0].get(0)
|
||||
assert output is not None
|
||||
assert len(output.outputs) == 1
|
||||
assert engine_core.scheduler.requests[req0.request_id].num_tokens == 13
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["0"] == 1
|
||||
|
||||
# Finish Batch 3. Get first token of req1. Schedule Batch 5: (1, req1).
|
||||
output = engine_core.step_with_batch_queue()[0].get(0)
|
||||
assert output is not None
|
||||
assert len(output.outputs) == 1
|
||||
assert engine_core.scheduler.requests[req1.request_id].num_tokens == 13
|
||||
scheduler_output = engine_core.batch_queue[-1][1]
|
||||
assert scheduler_output.num_scheduled_tokens["1"] == 1
|
||||
|
||||
# Loop until req0 is finished.
|
||||
req_id = 0
|
||||
expected_num_tokens = [
|
||||
engine_core.scheduler.requests["0"].num_tokens + 1,
|
||||
engine_core.scheduler.requests["1"].num_tokens + 1,
|
||||
]
|
||||
while engine_core.scheduler.get_num_unfinished_requests() == 2:
|
||||
output = engine_core.step_with_batch_queue()[0]
|
||||
# Every step consumes an output.
|
||||
assert output is not None
|
||||
assert len(output[0].outputs) == 1
|
||||
if req_id in engine_core.scheduler.requests:
|
||||
assert (
|
||||
engine_core.scheduler.requests[req_id].num_tokens
|
||||
== expected_num_tokens[req_id]
|
||||
)
|
||||
expected_num_tokens[req_id] += 1
|
||||
req_id = (req_id + 1) % 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encoder_only", [True, False])
|
||||
def test_async_step_skips_sampling_for_mm_encoder_only(encoder_only):
|
||||
"""Encoder outputs are complete; only language-model steps need sampling."""
|
||||
core = MagicMock()
|
||||
core.batch_queue = deque()
|
||||
core.batch_queue_size = 2
|
||||
core.is_mm_encoder_only = encoder_only
|
||||
core.is_pooling_model = False
|
||||
core.scheduler.has_requests.side_effect = [True, False, False]
|
||||
scheduled = core.scheduler.schedule.return_value
|
||||
scheduled.total_num_scheduled_tokens = 16
|
||||
scheduled.pending_structured_output_tokens = False
|
||||
|
||||
output = MagicMock()
|
||||
executed: Future[ModelRunnerOutput | None] = Future()
|
||||
executed.set_result(output if encoder_only else None)
|
||||
sampled: Future[ModelRunnerOutput | None] = Future()
|
||||
sampled.set_result(None if encoder_only else output)
|
||||
core.model_executor.execute_model.return_value = executed
|
||||
core.model_executor.sample_tokens.return_value = sampled
|
||||
|
||||
EngineCore.step_with_batch_queue(core)
|
||||
if core.batch_queue:
|
||||
EngineCore.step_with_batch_queue(core)
|
||||
|
||||
core.scheduler.update_from_output.assert_called_once_with(scheduled, output)
|
||||
if encoder_only:
|
||||
core.model_executor.sample_tokens.assert_not_called()
|
||||
else:
|
||||
core.model_executor.sample_tokens.assert_called_once()
|
||||
|
||||
|
||||
@multi_gpu_test(num_gpus=2)
|
||||
def test_engine_core_tp():
|
||||
"""Test engine can initialize worker in tp properly."""
|
||||
"""Setup the EngineCore."""
|
||||
engine_args = EngineArgs(
|
||||
model=MODEL_NAME,
|
||||
tensor_parallel_size=2,
|
||||
# Reduce startup time.
|
||||
enforce_eager=True,
|
||||
)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
|
||||
def get_worker_cache_config_field(worker, key: str):
|
||||
return getattr(worker.cache_config, key)
|
||||
|
||||
num_gpu_blocks = engine_core.collective_rpc(
|
||||
get_worker_cache_config_field, args=("num_gpu_blocks",)
|
||||
)
|
||||
num_cpu_blocks = engine_core.collective_rpc(
|
||||
get_worker_cache_config_field, args=("num_cpu_blocks",)
|
||||
)
|
||||
assert all(x is not None for x in num_gpu_blocks)
|
||||
assert all(x is not None for x in num_cpu_blocks)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
def test_engine_core_invalid_request_id_type():
|
||||
"""Test that engine raises TypeError for non-string request_id."""
|
||||
engine_args = EngineArgs(model=MODEL_NAME)
|
||||
vllm_config = engine_args.create_engine_config()
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
|
||||
# Test with UUID object (common mistake)
|
||||
uuid_request = make_request()
|
||||
uuid_request.request_id = uuid.uuid4() # UUID object instead of string
|
||||
|
||||
with pytest.raises(TypeError, match="request_id must be a string, got.*UUID"):
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(uuid_request))
|
||||
|
||||
# Test with integer
|
||||
int_request = make_request()
|
||||
int_request.request_id = 12345
|
||||
|
||||
with pytest.raises(TypeError, match="request_id must be a string, got.*int"):
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(int_request))
|
||||
|
||||
# Test with None
|
||||
none_request = make_request()
|
||||
none_request.request_id = None
|
||||
|
||||
with pytest.raises(TypeError, match="request_id must be a string, got.*NoneType"):
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(none_request))
|
||||
|
||||
# Verify engine is still functional after errors
|
||||
valid_request = make_request()
|
||||
engine_core.add_request(*engine_core.preprocess_add_request(valid_request))
|
||||
assert len(engine_core.scheduler.waiting) == 1
|
||||
assert len(engine_core.scheduler.running) == 0
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
@pytest.mark.parametrize(
|
||||
("ec_role", "gpu_memory_utilization", "enable_prefix_caching"),
|
||||
[
|
||||
("ec_producer", 0.01, False),
|
||||
# NOTE: ec_producer never allows prefix caching
|
||||
("ec_consumer", 0.7, True),
|
||||
("ec_consumer", 0.7, False),
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("use_kv_connector", [False, True])
|
||||
def test_encoder_instance_zero_kv_cache(
|
||||
ec_role: str,
|
||||
gpu_memory_utilization: float,
|
||||
enable_prefix_caching: bool,
|
||||
use_kv_connector: bool,
|
||||
):
|
||||
"""EPD (Encoder-Prefill-Decode) Encoder-cache-specific tests.
|
||||
|
||||
This test verifies encoder-only instance initializes with 0 KV cache blocks.
|
||||
Under EPD disagg mode, Encoder instances (EC producer role) only execute
|
||||
vision encoder, so they don't need KV cache for text generation.
|
||||
"""
|
||||
# Form vllm config
|
||||
model_config = ModelConfig(
|
||||
model="llava-hf/llava-1.5-7b-hf", # Multimodal model
|
||||
enforce_eager=True,
|
||||
trust_remote_code=True,
|
||||
dtype="float16",
|
||||
seed=42,
|
||||
)
|
||||
scheduler_config = SchedulerConfig(
|
||||
max_num_seqs=10,
|
||||
max_num_batched_tokens=512,
|
||||
max_model_len=512,
|
||||
disable_hybrid_kv_cache_manager=True,
|
||||
is_encoder_decoder=model_config.is_encoder_decoder,
|
||||
)
|
||||
cache_config = CacheConfig(
|
||||
block_size=16,
|
||||
gpu_memory_utilization=gpu_memory_utilization,
|
||||
cache_dtype="auto",
|
||||
enable_prefix_caching=enable_prefix_caching,
|
||||
)
|
||||
kv_transfer_config = (
|
||||
KVTransferConfig(
|
||||
kv_connector="ExampleConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={"shared_storage_path": "local_storage"},
|
||||
)
|
||||
if use_kv_connector
|
||||
else None
|
||||
)
|
||||
ec_transfer_config = ECTransferConfig(
|
||||
ec_connector="ECExampleConnector",
|
||||
ec_role=ec_role,
|
||||
ec_connector_extra_config={"shared_storage_path": "/tmp/ec_test_encoder"},
|
||||
)
|
||||
|
||||
vllm_config = VllmConfig(
|
||||
model_config=model_config,
|
||||
cache_config=cache_config,
|
||||
scheduler_config=scheduler_config,
|
||||
kv_transfer_config=kv_transfer_config,
|
||||
ec_transfer_config=ec_transfer_config,
|
||||
)
|
||||
|
||||
executor_class = Executor.get_class(vllm_config)
|
||||
print(f"executor_class: {executor_class}")
|
||||
|
||||
with set_default_torch_num_threads(1):
|
||||
engine_core = EngineCore(
|
||||
vllm_config=vllm_config, executor_class=executor_class, log_stats=True
|
||||
)
|
||||
|
||||
# Check encoder cache manager exists
|
||||
assert engine_core.scheduler.encoder_cache_manager is not None, (
|
||||
"encoder_cache_manager should exist"
|
||||
)
|
||||
|
||||
if ec_role == "ec_producer":
|
||||
# Check 1: num_blocks should be 0
|
||||
# NOTE: num_blocks=1 as BlockPool always needs a null_block.
|
||||
kv_cache_config = engine_core.scheduler.kv_cache_manager.kv_cache_config
|
||||
print(f"kv_cache_config: {kv_cache_config}")
|
||||
assert kv_cache_config.num_blocks == 1, (
|
||||
f"ec_producer should only have 1 KV blocks, "
|
||||
f"got {kv_cache_config.num_blocks}"
|
||||
)
|
||||
|
||||
# Check 2: kv_cache_groups should be empty
|
||||
assert len(kv_cache_config.kv_cache_groups) == 0, (
|
||||
f"ec_producer should have 0 KV cache groups, "
|
||||
f"got {len(kv_cache_config.kv_cache_groups)}"
|
||||
)
|
||||
|
||||
# Check 3: kv_cache_tensors should be empty
|
||||
assert len(kv_cache_config.kv_cache_tensors) == 0, (
|
||||
f"Encoder instance should have 0 KV cache tensors, "
|
||||
f"got {len(kv_cache_config.kv_cache_tensors)}"
|
||||
)
|
||||
|
||||
# Check 4: Verify EC connector is initialized and is producer
|
||||
assert engine_core.scheduler.ec_connector is not None, (
|
||||
"Encoder instance should have EC connector"
|
||||
)
|
||||
assert engine_core.scheduler.ec_connector.is_producer, (
|
||||
"Encoder instance EC connector should be producer"
|
||||
)
|
||||
|
||||
# Check 5: Verify chunked prefill is disabled
|
||||
assert not vllm_config.scheduler_config.enable_chunked_prefill, (
|
||||
"Encoder instance should disable chunked prefill (no KV cache)"
|
||||
)
|
||||
|
||||
elif ec_role == "ec_consumer":
|
||||
# Check 1: num_blocks should be > 1
|
||||
kv_cache_config = engine_core.scheduler.kv_cache_manager.kv_cache_config
|
||||
print(f"kv_cache_config: {kv_cache_config}")
|
||||
assert kv_cache_config.num_blocks > 1, (
|
||||
f"ec_consumer should have >1 KV blocks, got {kv_cache_config.num_blocks}"
|
||||
)
|
||||
|
||||
# Check 2: kv_cache_groups should NOT be empty
|
||||
assert len(kv_cache_config.kv_cache_groups) > 0, (
|
||||
f"ec_consumer should have KV cache groups, "
|
||||
f"got {len(kv_cache_config.kv_cache_groups)}"
|
||||
)
|
||||
|
||||
# Check 3: Verify EC connector is consumer
|
||||
assert engine_core.scheduler.ec_connector is not None, (
|
||||
"Consumer instance should have EC connector"
|
||||
)
|
||||
assert not engine_core.scheduler.ec_connector.is_producer, (
|
||||
"Consumer instance EC connector should be consumer"
|
||||
)
|
||||
|
||||
|
||||
def _cadenced_dp_engine_core(
|
||||
monkeypatch, results: list[tuple[bool, bool]], dp_sync_interval: int = 32
|
||||
):
|
||||
"""A bare DPEngineCoreProc whose all-reduce is scripted by `results`;
|
||||
returns the core and the step numbers at which the all-reduce ran."""
|
||||
core = object.__new__(DPEngineCoreProc)
|
||||
core.dp_group = object()
|
||||
core.dp_sync_interval = dp_sync_interval
|
||||
core.step_counter = 0
|
||||
core.pending_pause = False
|
||||
core.ignore_start_dp_wave = False
|
||||
synced: list[int] = []
|
||||
|
||||
def scripted_sync(dp_group, has_unfinished, pending_pause):
|
||||
synced.append(core.step_counter)
|
||||
return results.pop(0)
|
||||
|
||||
monkeypatch.setattr(ParallelConfig, "sync_dp_state", staticmethod(scripted_sync))
|
||||
return core, synced
|
||||
|
||||
|
||||
def test_dp_sync_interval_default_is_16():
|
||||
"""Regression pin: lowering the default narrows the mid-wave pause tail
|
||||
for async RL, where the engine is rarely idle when pause lands."""
|
||||
assert ParallelConfig.dp_sync_interval == 16
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dp_sync_interval", [32, 16])
|
||||
def test_dp_sync_interval_normal_wave(monkeypatch, dp_sync_interval: int):
|
||||
"""First all-reduce of a wave after one step, then every N."""
|
||||
core, synced = _cadenced_dp_engine_core(
|
||||
monkeypatch, [(True, False)] * 3, dp_sync_interval=dp_sync_interval
|
||||
)
|
||||
for _ in range(dp_sync_interval * 2 + 6):
|
||||
assert DPEngineCoreProc._has_global_unfinished_reqs(core, True)
|
||||
assert synced == [1, dp_sync_interval, dp_sync_interval * 2]
|
||||
|
||||
|
||||
def test_dp_sync_interval_idle_pause_consensus_on_first_step(monkeypatch):
|
||||
"""A pause of an idle engine arms every rank before its kick-started
|
||||
first step, so the step-1 sync reaches consensus after one dummy batch
|
||||
regardless of the configured cadence."""
|
||||
core, synced = _cadenced_dp_engine_core(
|
||||
monkeypatch, [(False, True)], dp_sync_interval=32
|
||||
)
|
||||
core.pending_pause = True
|
||||
assert DPEngineCoreProc._has_global_unfinished_reqs(core, False) is False
|
||||
assert synced == [1]
|
||||
assert core.ignore_start_dp_wave
|
||||
assert not core.pending_pause
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"request_wave,engines_running,pause_state,announces",
|
||||
[
|
||||
pytest.param(3, False, PauseState.UNPAUSED, True, id="current-wave"),
|
||||
pytest.param(2, False, PauseState.UNPAUSED, True, id="stale-wave"),
|
||||
pytest.param(4, False, PauseState.UNPAUSED, True, id="newer-wave"),
|
||||
pytest.param(3, True, PauseState.UNPAUSED, False, id="running"),
|
||||
pytest.param(3, False, PauseState.PAUSED_ALL, False, id="paused"),
|
||||
],
|
||||
)
|
||||
def test_idle_dp_rank_announces_wave_for_new_work(
|
||||
request_wave, engines_running, pause_state, announces
|
||||
):
|
||||
"""An idle rank handed work announces the wave itself, since only engines
|
||||
start waves; a paused rank waits for resume."""
|
||||
core = object.__new__(DPEngineCoreProc)
|
||||
core.has_coordinator = True
|
||||
core.current_wave = 3
|
||||
core.engines_running = engines_running
|
||||
core.scheduler = MagicMock(pause_state=pause_state)
|
||||
core.output_queue = MagicMock()
|
||||
|
||||
with patch.object(EngineCore, "add_request"):
|
||||
core.add_request(MagicMock(), request_wave)
|
||||
|
||||
if announces:
|
||||
assert core.engines_running
|
||||
_, outputs = core.output_queue.put_nowait.call_args.args[0]
|
||||
assert outputs.start_wave == max(request_wave, 3)
|
||||
else:
|
||||
core.output_queue.put_nowait.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("paused", [False, True])
|
||||
def test_paused_dp_rank_ignores_start_wave(paused):
|
||||
"""A START_DP_WAVE still in flight when the pause completes must not wake
|
||||
the paused rank."""
|
||||
core = object.__new__(DPEngineCoreProc)
|
||||
core.ignore_start_dp_wave = paused
|
||||
core.engine_index = 0
|
||||
core.current_wave = 3
|
||||
core.engines_running = False
|
||||
|
||||
core._handle_client_request(EngineCoreRequestType.START_DP_WAVE, (3, 1))
|
||||
|
||||
assert core.engines_running != paused
|
||||
|
||||
|
||||
def _pausable_engine_core_proc() -> EngineCoreProc:
|
||||
"""A bare EngineCoreProc holding just the state pause_scheduler touches."""
|
||||
core = object.__new__(EngineCoreProc)
|
||||
core.model_executor = MagicMock()
|
||||
core.scheduler = MagicMock()
|
||||
core.scheduler.has_requests.return_value = False
|
||||
core.batch_queue = None
|
||||
core.engines_running = False
|
||||
core._idle_state_callbacks = []
|
||||
return core
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"pause_state,has_requests,has_batches",
|
||||
[
|
||||
pytest.param(PauseState.UNPAUSED, False, False, id="not-paused"),
|
||||
pytest.param(PauseState.PAUSED_ALL, True, False, id="pending-requests"),
|
||||
pytest.param(PauseState.PAUSED_ALL, False, True, id="pending-batches"),
|
||||
],
|
||||
)
|
||||
def test_kv_cache_release_rejects_unsafe_state(pause_state, has_requests, has_batches):
|
||||
"""Reject release before touching caches or memory if work can still use KV."""
|
||||
core = _pausable_engine_core_proc()
|
||||
core.scheduler.pause_state = pause_state
|
||||
core.scheduler.has_requests.return_value = has_requests
|
||||
core.batch_queue = [object()] if has_batches else None
|
||||
core._reset_caches = MagicMock()
|
||||
|
||||
with pytest.raises(RuntimeError, match="requires a completed pause"):
|
||||
core.release_kv_cache_memory()
|
||||
|
||||
core._reset_caches.assert_not_called()
|
||||
core.model_executor.discard.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("deferred", [False, True])
|
||||
def test_pause_synchronizes_device_before_cache_reset(deferred: bool):
|
||||
"""A resolved pause promises an idle device: the barrier must run before
|
||||
caches are cleared and before the caller is unblocked."""
|
||||
core = _pausable_engine_core_proc()
|
||||
core.engines_running = deferred
|
||||
order: list[str] = []
|
||||
core.model_executor.collective_rpc.side_effect = lambda method: order.append(method)
|
||||
core._reset_caches = lambda: order.append("reset_caches")
|
||||
|
||||
result = EngineCoreProc.pause_scheduler(core, mode="keep", clear_cache=True)
|
||||
if deferred:
|
||||
assert isinstance(result, Future)
|
||||
assert not result.done() and order == []
|
||||
core.engines_running = False
|
||||
core._notify_idle_state_callbacks()
|
||||
assert result.result(timeout=0) is None
|
||||
else:
|
||||
assert result is None
|
||||
assert order == ["synchronize_device", "reset_caches"]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,118 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.v1.core.sched.utils import check_stop
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
|
||||
pytestmark = pytest.mark.skip_global_cleanup
|
||||
|
||||
|
||||
def _make_request(params: SamplingParams) -> Request:
|
||||
return Request(
|
||||
request_id="req-0",
|
||||
client_index=0,
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
sampling_params=params,
|
||||
pooling_params=None,
|
||||
arrival_time=time.time(),
|
||||
)
|
||||
|
||||
|
||||
def _normalize(params: SamplingParams, prompt_len: int, max_model_len: int) -> None:
|
||||
processor = SimpleNamespace(
|
||||
model_config=SimpleNamespace(max_model_len=max_model_len)
|
||||
)
|
||||
InputProcessor._normalize_trace_replay_params(processor, params, prompt_len)
|
||||
|
||||
|
||||
def test_normalize_trace_replay_params():
|
||||
params = SamplingParams(
|
||||
max_tokens=16,
|
||||
min_tokens=10,
|
||||
stop_token_ids=[20],
|
||||
trace_decode_token_ids=[10, 20, 30],
|
||||
)
|
||||
params.update_from_generation_config({}, eos_token_id=20)
|
||||
|
||||
_normalize(params, prompt_len=3, max_model_len=128)
|
||||
|
||||
assert params.max_tokens == 3
|
||||
assert params.min_tokens == 0
|
||||
assert params.ignore_eos is True
|
||||
assert params.eos_token_id is None
|
||||
assert params.stop_token_ids == []
|
||||
assert params.all_stop_token_ids == set()
|
||||
|
||||
request = _make_request(params)
|
||||
assert request.max_tokens == 3
|
||||
request.append_output_token_ids([10, 20, 30])
|
||||
assert check_stop(request, max_model_len=128)
|
||||
assert request.status == RequestStatus.FINISHED_LENGTH_CAPPED
|
||||
|
||||
|
||||
def test_trace_longer_than_remaining_context_is_truncated():
|
||||
"""The trace is staged into a max_model_len-wide row, so it must be cut.
|
||||
|
||||
An explicitly set max_tokens is never clamped to max_model_len, so it cannot
|
||||
bound the staged write.
|
||||
"""
|
||||
params = SamplingParams(max_tokens=100, trace_decode_token_ids=list(range(20)))
|
||||
|
||||
_normalize(params, prompt_len=6, max_model_len=10)
|
||||
|
||||
assert params.trace_decode_token_ids == [0, 1, 2, 3]
|
||||
assert params.max_tokens == 4
|
||||
|
||||
|
||||
def _validate(enable_trace_replay: bool) -> None:
|
||||
"""Run _validate_params' trace gating with the rest of verify() stubbed."""
|
||||
processor = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
return_sampling_mask=False,
|
||||
enable_trace_replay=enable_trace_replay,
|
||||
is_diffusion=False,
|
||||
),
|
||||
vllm_config=SimpleNamespace(
|
||||
reasoning_config=None,
|
||||
# Engine has no watermark configuration.
|
||||
_check_supports_watermarking=lambda params: False,
|
||||
),
|
||||
resolve_watermarking=lambda params: False,
|
||||
speculative_config=None,
|
||||
structured_outputs_config=None,
|
||||
diffusion_config=None,
|
||||
tokenizer=None,
|
||||
validate_logits_processors_params=lambda params: None,
|
||||
)
|
||||
params = SamplingParams(trace_decode_token_ids=[1, 2, 3])
|
||||
with patch.object(SamplingParams, "verify"):
|
||||
InputProcessor._validate_params(processor, params, ("generate",))
|
||||
|
||||
|
||||
def test_trace_request_rejected_when_feature_disabled():
|
||||
with pytest.raises(VLLMValidationError, match="--enable-trace-replay"):
|
||||
_validate(enable_trace_replay=False)
|
||||
|
||||
|
||||
def test_trace_request_accepted_when_feature_enabled():
|
||||
_validate(enable_trace_replay=True)
|
||||
|
||||
|
||||
def test_trace_replay_requires_v2_model_runner():
|
||||
config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(enable_trace_replay=True),
|
||||
use_v2_model_runner=False,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="trace replay requires Model Runner V2"):
|
||||
VllmConfig._verify_trace_replay_config(config)
|
||||
@@ -1,299 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import random
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, call
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM
|
||||
from vllm.exceptions import ProfilerAlreadyActiveError
|
||||
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
|
||||
from vllm.v1.engine.llm_engine import LLMEngine
|
||||
from vllm.v1.metrics.reader import Counter, Gauge, Histogram, Metric, Vector
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from tests.conftest import VllmRunner
|
||||
else:
|
||||
VllmRunner = object
|
||||
|
||||
MODEL = "facebook/opt-125m"
|
||||
DTYPE = "half"
|
||||
|
||||
|
||||
@pytest.mark.skip_global_cleanup
|
||||
def test_step_invalidates_mm_processor_cache_misses():
|
||||
engine = object.__new__(LLMEngine)
|
||||
engine.should_execute_dummy_batch = False
|
||||
engine.log_stats = False
|
||||
engine.logger_manager = None
|
||||
|
||||
mm_processor_cache = MagicMock()
|
||||
engine.renderer = MagicMock(mm_processor_cache=mm_processor_cache)
|
||||
|
||||
engine_core_output = MagicMock(
|
||||
mm_cache_miss_hashes=["missing-hash-1", "missing-hash-2"]
|
||||
)
|
||||
outputs = MagicMock(
|
||||
outputs=[engine_core_output],
|
||||
timestamp=0.0,
|
||||
scheduler_stats=None,
|
||||
)
|
||||
engine.engine_core = MagicMock()
|
||||
engine.engine_core.get_output.return_value = outputs
|
||||
|
||||
processed_outputs = MagicMock(reqs_to_abort=[], request_outputs=[])
|
||||
engine.output_processor = MagicMock()
|
||||
engine.output_processor.process_outputs.return_value = processed_outputs
|
||||
|
||||
assert engine.step() == []
|
||||
assert mm_processor_cache.invalidate.call_args_list == [
|
||||
call("missing-hash-1"),
|
||||
call("missing-hash-2"),
|
||||
]
|
||||
|
||||
|
||||
def test_duplicate_profile_start_rejected_before_engine_core_dispatch():
|
||||
engine = object.__new__(LLMEngine)
|
||||
engine.engine_core = MagicMock()
|
||||
engine._profile_session_active = False
|
||||
|
||||
engine.start_profile("first")
|
||||
|
||||
with pytest.raises(ProfilerAlreadyActiveError):
|
||||
engine.start_profile("duplicate")
|
||||
|
||||
engine.engine_core.profile.assert_called_once_with(True, "first", None, None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kwargs",
|
||||
[
|
||||
{"profile_prefix": "../trace"},
|
||||
{"delay_iterations": -1},
|
||||
{"max_iterations": -1},
|
||||
],
|
||||
)
|
||||
def test_invalid_profile_controls_rejected_before_engine_core_dispatch(kwargs):
|
||||
engine = object.__new__(LLMEngine)
|
||||
engine.engine_core = MagicMock()
|
||||
engine._profile_session_active = False
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
engine.start_profile(**kwargs)
|
||||
|
||||
engine.engine_core.profile.assert_not_called()
|
||||
|
||||
|
||||
def _vllm_model(
|
||||
apc: bool,
|
||||
vllm_runner: type[VllmRunner],
|
||||
*,
|
||||
skip_tokenizer_init: bool = False,
|
||||
):
|
||||
"""Set up VllmRunner instance."""
|
||||
return vllm_runner(
|
||||
MODEL,
|
||||
dtype=DTYPE,
|
||||
max_model_len=128,
|
||||
enforce_eager=True,
|
||||
enable_prefix_caching=apc,
|
||||
gpu_memory_utilization=0.5,
|
||||
skip_tokenizer_init=skip_tokenizer_init,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
# Function scope decouples tests & allows
|
||||
# env var adjustment via monkeypatch
|
||||
scope="function",
|
||||
# Prefix caching
|
||||
params=[False, True],
|
||||
)
|
||||
def vllm_model(vllm_runner, request):
|
||||
"""VllmRunner test fixture parameterized by APC True/False."""
|
||||
with _vllm_model(request.param, vllm_runner) as vllm_model:
|
||||
yield vllm_model
|
||||
|
||||
|
||||
@pytest.fixture(
|
||||
# Function scope decouples tests & allows
|
||||
# env var adjustment via monkeypatch
|
||||
scope="function",
|
||||
# Prefix caching
|
||||
params=[False, True],
|
||||
)
|
||||
def vllm_model_skip_tokenizer_init(vllm_runner, request):
|
||||
"""VllmRunner test fixture with APC."""
|
||||
with _vllm_model(
|
||||
request.param,
|
||||
vllm_runner,
|
||||
skip_tokenizer_init=True,
|
||||
) as vllm_model:
|
||||
yield vllm_model
|
||||
|
||||
|
||||
def _get_test_sampling_params(
|
||||
prompt_list: list[str],
|
||||
seed: int | None = 42,
|
||||
structured_outputs: bool = False,
|
||||
) -> tuple[list[SamplingParams], list[int]]:
|
||||
"""Generate random sampling params for a batch."""
|
||||
rng = random.Random(seed)
|
||||
|
||||
def get_mostly_n_gt1() -> int:
|
||||
r"""Mostly n \in [2,20], ~1/3 n=1."""
|
||||
x = rng.randint(0, 28)
|
||||
if x < 10:
|
||||
return 1
|
||||
else:
|
||||
return x - 8
|
||||
|
||||
n_list = [get_mostly_n_gt1() for _ in range(len(prompt_list))]
|
||||
# High temperature to maximize the chance of unique completions
|
||||
return [
|
||||
SamplingParams(
|
||||
temperature=0.95,
|
||||
top_p=0.95,
|
||||
n=n,
|
||||
seed=seed,
|
||||
structured_outputs=StructuredOutputsParams(regex="[0-9]+")
|
||||
if structured_outputs
|
||||
else None,
|
||||
)
|
||||
for n in n_list
|
||||
], n_list
|
||||
|
||||
|
||||
def test_compatibility_with_skip_tokenizer_init(
|
||||
vllm_model_skip_tokenizer_init: VllmRunner,
|
||||
example_prompts: list[str],
|
||||
):
|
||||
# Case 1: Structured output request should raise an error.
|
||||
sampling_params_list, _ = _get_test_sampling_params(
|
||||
example_prompts,
|
||||
structured_outputs=True,
|
||||
)
|
||||
llm: LLM = vllm_model_skip_tokenizer_init.llm
|
||||
with pytest.raises(ValueError):
|
||||
_ = llm.generate(example_prompts, sampling_params_list)
|
||||
|
||||
|
||||
def test_parallel_sampling(vllm_model, example_prompts) -> None:
|
||||
"""Test passes if parallel sampling `n>1` yields `n` unique completions.
|
||||
|
||||
Args:
|
||||
vllm_model: VllmRunner instance under test.
|
||||
example_prompt: test fixture providing prompts for testing.
|
||||
|
||||
"""
|
||||
sampling_params_list, n_list = _get_test_sampling_params(example_prompts)
|
||||
llm: LLM = vllm_model.llm
|
||||
outputs = llm.generate(example_prompts, sampling_params_list)
|
||||
|
||||
# Validate each request response
|
||||
for out, n in zip(outputs, n_list):
|
||||
completion_counts: dict[str, int] = {}
|
||||
# Assert correct number of completions
|
||||
assert len(out.outputs) == n, f"{len(out.outputs)} completions; {n} expected."
|
||||
for idx in range(n):
|
||||
comp = out.outputs[idx]
|
||||
# Assert correct completion indices
|
||||
assert comp.index == idx, f"Index {comp.index}; expected {idx}."
|
||||
text = comp.text
|
||||
completion_counts[text] = completion_counts.get(text, 0) + 1
|
||||
# Assert unique completions
|
||||
if len(completion_counts) != n:
|
||||
repeats = {txt: num for (txt, num) in completion_counts.items() if num > 1}
|
||||
raise AssertionError(
|
||||
f"{len(completion_counts)} unique completions; expected"
|
||||
f" {n}. Repeats: {repeats}"
|
||||
)
|
||||
|
||||
|
||||
def test_engine_metrics(vllm_runner, example_prompts):
|
||||
max_tokens = 100
|
||||
# Use spec decoding to test num_accepted_tokens_per_pos
|
||||
speculative_config = {
|
||||
"method": "ngram",
|
||||
"prompt_lookup_max": 5,
|
||||
"prompt_lookup_min": 3,
|
||||
"num_speculative_tokens": 5,
|
||||
}
|
||||
|
||||
with vllm_runner(
|
||||
MODEL,
|
||||
speculative_config=speculative_config,
|
||||
disable_log_stats=False,
|
||||
) as vllm_model:
|
||||
llm: LLM = vllm_model.llm
|
||||
sampling_params = SamplingParams(temperature=0.0, max_tokens=max_tokens)
|
||||
outputs = llm.generate(example_prompts, sampling_params)
|
||||
|
||||
n_prompts = len(example_prompts)
|
||||
assert len(outputs) == n_prompts
|
||||
|
||||
total_tokens = 0
|
||||
for out in outputs:
|
||||
assert len(out.outputs) == 1
|
||||
total_tokens += len(out.outputs[0].token_ids)
|
||||
assert total_tokens == max_tokens * n_prompts
|
||||
|
||||
metrics = llm.get_metrics()
|
||||
|
||||
def find_metric(name) -> list[Metric]:
|
||||
found = []
|
||||
for metric in metrics:
|
||||
if metric.name == name:
|
||||
found.append(metric)
|
||||
return found
|
||||
|
||||
num_requests_running = find_metric("vllm:num_requests_running")
|
||||
assert len(num_requests_running) == 1
|
||||
assert isinstance(num_requests_running[0], Gauge)
|
||||
assert num_requests_running[0].value == 0.0
|
||||
|
||||
generation_tokens = find_metric("vllm:generation_tokens")
|
||||
assert len(generation_tokens) == 1
|
||||
assert isinstance(generation_tokens[0], Counter)
|
||||
assert generation_tokens[0].value == total_tokens
|
||||
|
||||
request_generation_tokens = find_metric("vllm:request_generation_tokens")
|
||||
assert len(request_generation_tokens) == 1
|
||||
assert isinstance(request_generation_tokens[0], Histogram)
|
||||
assert "+Inf" in request_generation_tokens[0].buckets
|
||||
assert request_generation_tokens[0].buckets["+Inf"] == n_prompts
|
||||
assert request_generation_tokens[0].count == n_prompts
|
||||
assert request_generation_tokens[0].sum == total_tokens
|
||||
|
||||
num_accepted_tokens_per_pos = find_metric(
|
||||
"vllm:spec_decode_num_accepted_tokens_per_pos"
|
||||
)
|
||||
assert len(num_accepted_tokens_per_pos) == 1
|
||||
assert isinstance(num_accepted_tokens_per_pos[0], Vector)
|
||||
assert len(num_accepted_tokens_per_pos[0].values) == 5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["meta-llama/Llama-3.2-1B-Instruct"])
|
||||
def test_skip_tokenizer_initialization(model: str):
|
||||
# This test checks if the flag skip_tokenizer_init skips the initialization
|
||||
# of tokenizer and detokenizer. The generated output is expected to contain
|
||||
# token ids.
|
||||
llm = LLM(
|
||||
model=model,
|
||||
skip_tokenizer_init=True,
|
||||
enforce_eager=True,
|
||||
)
|
||||
sampling_params = SamplingParams(prompt_logprobs=True, detokenize=True)
|
||||
|
||||
with pytest.raises(ValueError, match="`skip_tokenizer_init=True`"):
|
||||
llm.generate("abc", sampling_params)
|
||||
|
||||
outputs = llm.generate(
|
||||
{"prompt_token_ids": [1, 2, 3]}, sampling_params=sampling_params
|
||||
)
|
||||
assert len(outputs) > 0
|
||||
completions = outputs[0].outputs
|
||||
assert len(completions) > 0
|
||||
assert completions[0].text == ""
|
||||
assert completions[0].token_ids
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,99 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from copy import copy
|
||||
|
||||
from vllm import SamplingParams
|
||||
from vllm.outputs import CompletionOutput
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.parallel_sampling import ParentRequest
|
||||
|
||||
|
||||
def test_parent_request_to_output_stream() -> None:
|
||||
parent_request = ParentRequest(make_request(SamplingParams(n=2)))
|
||||
parent_request.child_requests = {"child_id_0", "child_id_1"}
|
||||
output_0 = CompletionOutput(
|
||||
index=0, text="child 0", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
output_1 = CompletionOutput(
|
||||
index=1, text="child 1", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
# Request not finished
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert ([output_1], False) == parent_request.get_outputs("child_id_1", output_1)
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert ([output_1], False) == parent_request.get_outputs("child_id_1", output_1)
|
||||
|
||||
# output_1 finished
|
||||
output_1.finish_reason = "ended"
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert ([output_1], False) == parent_request.get_outputs("child_id_1", output_1)
|
||||
# Finished output_1 had already returned, DO NOT returned again
|
||||
assert ([output_0], False) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], False)
|
||||
|
||||
# output_0 finished
|
||||
output_0.finish_reason = "ended"
|
||||
assert ([output_0], True) == parent_request.get_outputs("child_id_0", output_0)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], True)
|
||||
# Finished output_0 had already returned, DO NOT returned again
|
||||
assert parent_request.get_outputs("child_id_0", output_0) == ([], True)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], True)
|
||||
|
||||
|
||||
def test_parent_request_to_output_final_only() -> None:
|
||||
parent_request = ParentRequest(
|
||||
make_request(SamplingParams(n=2, output_kind=RequestOutputKind.FINAL_ONLY))
|
||||
)
|
||||
parent_request.child_requests = {"child_id_0", "child_id_1"}
|
||||
output_0 = CompletionOutput(
|
||||
index=0, text="child 0", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
output_1 = CompletionOutput(
|
||||
index=1, text="child 1", token_ids=[], cumulative_logprob=None, logprobs=None
|
||||
)
|
||||
# Request not finished, return nothing
|
||||
assert parent_request.get_outputs("child_id_0", output_0) == ([], False)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], False)
|
||||
# output_1 finished, but outputs won't be returned until all child requests finished
|
||||
output_1.finish_reason = "ended"
|
||||
assert parent_request.get_outputs("child_id_0", output_0) == ([], False)
|
||||
assert parent_request.get_outputs("child_id_1", output_1) == ([], False)
|
||||
# output_0 finished, as all child requests finished, the output would be returned
|
||||
output_0.finish_reason = "ended"
|
||||
assert ([output_0, output_1], True) == parent_request.get_outputs(
|
||||
"child_id_0", output_0
|
||||
)
|
||||
assert ([output_0, output_1], True) == parent_request.get_outputs(
|
||||
"child_id_1", output_1
|
||||
)
|
||||
|
||||
|
||||
def test_parallel_sampling_child_requests_preserve_session_id() -> None:
|
||||
request = make_request(SamplingParams(n=2))
|
||||
request.session_id = "session-1"
|
||||
parent_request = ParentRequest(request)
|
||||
|
||||
for idx in range(parent_request.n):
|
||||
request_id, child_params = parent_request.get_child_info(idx)
|
||||
child_request = request if idx == parent_request.n - 1 else copy(request)
|
||||
child_request.request_id = request_id
|
||||
child_request.sampling_params = child_params
|
||||
|
||||
assert child_request.session_id == "session-1"
|
||||
|
||||
|
||||
def make_request(sampling_params: SamplingParams) -> EngineCoreRequest:
|
||||
return EngineCoreRequest(
|
||||
request_id="parent_id",
|
||||
external_req_id="ext_parent_id",
|
||||
prompt_token_ids=None,
|
||||
mm_features=None,
|
||||
sampling_params=sampling_params,
|
||||
pooling_params=None,
|
||||
arrival_time=0.0,
|
||||
lora_request=None,
|
||||
cache_salt=None,
|
||||
data_parallel_rank=None,
|
||||
)
|
||||
@@ -1,62 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch.cuda
|
||||
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.core import EngineCore
|
||||
|
||||
MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
|
||||
|
||||
|
||||
def test_preprocess_error_handling(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Test that preprocessing errors are handled gracefully."""
|
||||
if current_platform.is_rocm() or current_platform.is_xpu():
|
||||
pytest.skip(
|
||||
"Skipped on ROCm/XPU: this test only works with 'fork', "
|
||||
"but ROCm/XPU uses 'spawn'."
|
||||
)
|
||||
|
||||
assert not torch.cuda.is_initialized(), (
|
||||
"fork needs to be used for the engine "
|
||||
"core process and this isn't possible if cuda is already initialized"
|
||||
)
|
||||
|
||||
# Store original method to call for non-failing requests
|
||||
original_preprocess = EngineCore.preprocess_add_request
|
||||
|
||||
# Monkeypatch to make preprocess_add_request raise an exception
|
||||
# only for requests with "FAIL" in the first token
|
||||
def conditional_failing_preprocess(self, request: EngineCoreRequest):
|
||||
# Fail if the first token id is 333
|
||||
if request.prompt_token_ids and request.prompt_token_ids[0] == 333:
|
||||
raise ValueError("Simulated preprocessing error!")
|
||||
return original_preprocess(self, request)
|
||||
|
||||
monkeypatch.setattr(
|
||||
EngineCore, "preprocess_add_request", conditional_failing_preprocess
|
||||
)
|
||||
|
||||
llm = LLM(model=MODEL_NAME)
|
||||
|
||||
# Create a failing request by crafting a request with an invalid token
|
||||
# We need to use a direct approach since LLM.generate tokenizes for us
|
||||
from vllm.inputs import TokensPrompt
|
||||
|
||||
# This should raise an exception due to the preprocessing failure
|
||||
# Special token id to trigger the failure
|
||||
failing_prompt = TokensPrompt(prompt_token_ids=[333])
|
||||
outputs = llm.generate(failing_prompt, SamplingParams(max_tokens=10)) # type: ignore
|
||||
assert len(outputs) == 1
|
||||
assert len(outputs[0].outputs[0].token_ids) == 0
|
||||
assert outputs[0].finished
|
||||
assert outputs[0].outputs[0].finish_reason == "error"
|
||||
|
||||
# Verify the engine is still functional with a normal request
|
||||
outputs = llm.generate("Hello, my name is", SamplingParams(max_tokens=10))
|
||||
assert len(outputs) == 1
|
||||
assert len(outputs[0].outputs[0].token_ids) > 0
|
||||
assert outputs[0].outputs[0].finish_reason in ("stop", "length")
|
||||
@@ -1,321 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import os
|
||||
from contextlib import nullcontext
|
||||
from multiprocessing import connection
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
import zmq
|
||||
|
||||
import vllm.platforms as platforms
|
||||
from vllm.utils import torch_utils
|
||||
from vllm.v1.engine import core as core_module
|
||||
from vllm.v1.engine import utils as engine_utils
|
||||
from vllm.v1.engine.core import EngineCoreProc, EngineShutdownState
|
||||
from vllm.v1.engine.utils import (
|
||||
CoreEngine,
|
||||
CoreEngineLaunch,
|
||||
CoreEngineProcManager,
|
||||
EngineZmqAddresses,
|
||||
wait_for_engine_startup,
|
||||
)
|
||||
from vllm.v1.executor import UniProcExecutor, multiproc_executor
|
||||
|
||||
pytestmark = pytest.mark.skip_global_cleanup
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"executor_class",
|
||||
"local_engine_count",
|
||||
"initial_threads",
|
||||
"user_threads",
|
||||
"fail_start",
|
||||
"expected",
|
||||
),
|
||||
[
|
||||
(UniProcExecutor, 1, 192, None, False, (12, "12", "1")),
|
||||
(UniProcExecutor, 2, 192, None, False, (6, "6", "1")),
|
||||
(UniProcExecutor, 2, 192, None, True, (6, "6", "1")),
|
||||
(UniProcExecutor, 2, 5, None, False, (5, "5", "1")),
|
||||
(UniProcExecutor, 2, 1, None, False, (1, "1", "1")),
|
||||
(UniProcExecutor, 2, 5, "5", False, (5, "5", None)),
|
||||
(
|
||||
multiproc_executor.MultiprocExecutor,
|
||||
2,
|
||||
192,
|
||||
None,
|
||||
False,
|
||||
(192, None, None),
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_engine_core_startup_threads_are_scoped_to_launch(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
executor_class,
|
||||
local_engine_count: int,
|
||||
initial_threads: int,
|
||||
user_threads: str | None,
|
||||
fail_start: bool,
|
||||
expected: tuple[int, str | None, str | None],
|
||||
):
|
||||
"""UniProc workers inherit their CPU share and restore the parent."""
|
||||
marker = torch_utils.OMP_NUM_THREADS_SET_BY_VLLM
|
||||
monkeypatch.delenv(marker, raising=False)
|
||||
monkeypatch.delenv("OMP_NUM_THREADS", raising=False)
|
||||
if user_threads is not None:
|
||||
monkeypatch.setenv("OMP_NUM_THREADS", user_threads)
|
||||
monkeypatch.setattr(torch_utils, "available_cpu_count", lambda: 12)
|
||||
platform = SimpleNamespace(
|
||||
is_cpu=lambda: False, is_cuda_alike=lambda: True, is_xpu=lambda: False
|
||||
)
|
||||
monkeypatch.setattr(engine_utils, "current_platform", platform)
|
||||
threads = SimpleNamespace(count=initial_threads)
|
||||
setter_calls = []
|
||||
|
||||
def set_threads(count):
|
||||
setter_calls.append(count)
|
||||
threads.count = count
|
||||
|
||||
monkeypatch.setattr(torch, "get_num_threads", lambda: threads.count)
|
||||
monkeypatch.setattr(torch, "set_num_threads", set_threads)
|
||||
start_states = []
|
||||
|
||||
def thread_state():
|
||||
return (
|
||||
threads.count,
|
||||
os.environ.get("OMP_NUM_THREADS"),
|
||||
os.environ.get(marker),
|
||||
)
|
||||
|
||||
def start_process():
|
||||
start_states.append(thread_state())
|
||||
if fail_start:
|
||||
raise RuntimeError("start failed")
|
||||
|
||||
def get_context():
|
||||
assert thread_state() == (initial_threads, user_threads, None)
|
||||
return SimpleNamespace(
|
||||
Process=lambda **kwargs: SimpleNamespace(
|
||||
name=kwargs["name"],
|
||||
exitcode=1 if fail_start else None,
|
||||
start=start_process,
|
||||
)
|
||||
)
|
||||
|
||||
monkeypatch.setattr(engine_utils, "get_mp_context", get_context)
|
||||
monkeypatch.setattr(engine_utils, "shutdown", lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
engine_utils.numa_utils,
|
||||
"configure_subprocess",
|
||||
lambda *args, **kwargs: nullcontext(),
|
||||
)
|
||||
with (
|
||||
pytest.raises(RuntimeError, match="start failed")
|
||||
if fail_start
|
||||
else nullcontext()
|
||||
):
|
||||
manager = CoreEngineProcManager(
|
||||
local_engine_count=local_engine_count,
|
||||
start_index=0,
|
||||
local_start_index=0,
|
||||
vllm_config=SimpleNamespace(
|
||||
shutdown_timeout=0,
|
||||
parallel_config=SimpleNamespace(
|
||||
data_parallel_size=local_engine_count,
|
||||
assigned_physical_gpu_ids=None,
|
||||
use_ray=False,
|
||||
),
|
||||
),
|
||||
local_client=True,
|
||||
handshake_address="unused",
|
||||
executor_class=executor_class,
|
||||
log_stats=False,
|
||||
)
|
||||
manager._finalizer.detach()
|
||||
assert start_states == [expected] * (1 if fail_start else local_engine_count)
|
||||
assert thread_state() == (initial_threads, user_threads, None)
|
||||
assert setter_calls == (
|
||||
[expected[0], initial_threads]
|
||||
if executor_class is UniProcExecutor and expected[0] < initial_threads
|
||||
else []
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("is_rocm", "request_timeout", "manager_timeout", "process_timeout"),
|
||||
[
|
||||
(True, 0, 0, 15.0),
|
||||
(True, 0, 7, 7),
|
||||
(True, 0, None, None),
|
||||
(False, 0, 0, 0),
|
||||
(True, 7, 0, 0),
|
||||
],
|
||||
)
|
||||
def test_engine_core_process_shutdown_timeout(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
is_rocm: bool,
|
||||
request_timeout: float | None,
|
||||
manager_timeout: float | None,
|
||||
process_timeout: float | None,
|
||||
):
|
||||
manager = object.__new__(CoreEngineProcManager)
|
||||
manager._request_shutdown_timeout = request_timeout
|
||||
manager.manager_stopped = Event()
|
||||
manager.processes = [object()]
|
||||
detach_results = iter((object(), None))
|
||||
manager._finalizer = SimpleNamespace(detach=lambda: next(detach_results))
|
||||
|
||||
shutdown_calls = []
|
||||
monkeypatch.setattr(
|
||||
engine_utils,
|
||||
"current_platform",
|
||||
SimpleNamespace(is_rocm=lambda: is_rocm),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
engine_utils,
|
||||
"shutdown",
|
||||
lambda processes, timeout: shutdown_calls.append((processes, timeout)),
|
||||
)
|
||||
|
||||
manager.shutdown(timeout=manager_timeout)
|
||||
manager.shutdown(timeout=manager_timeout)
|
||||
|
||||
assert manager.manager_stopped.is_set()
|
||||
assert shutdown_calls == [(manager.processes, process_timeout)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"is_rocm",
|
||||
"shutdown_state",
|
||||
"has_work",
|
||||
"shutdown_timeout",
|
||||
"exit_code",
|
||||
"expected_calls",
|
||||
),
|
||||
[
|
||||
(
|
||||
True,
|
||||
EngineShutdownState.SHUTTING_DOWN,
|
||||
False,
|
||||
0,
|
||||
None,
|
||||
["shutdown", "freeze"],
|
||||
),
|
||||
(False, EngineShutdownState.SHUTTING_DOWN, False, 0, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.RUNNING, False, 0, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.SHUTTING_DOWN, True, 0, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.SHUTTING_DOWN, False, 7, None, ["shutdown"]),
|
||||
(True, EngineShutdownState.SHUTTING_DOWN, False, 0, 1, ["shutdown"]),
|
||||
],
|
||||
)
|
||||
def test_freeze_gc_after_clean_rocm_engine_core_shutdown(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
is_rocm: bool,
|
||||
shutdown_state: EngineShutdownState,
|
||||
has_work: bool,
|
||||
shutdown_timeout: int,
|
||||
exit_code: int | None,
|
||||
expected_calls: list[str],
|
||||
):
|
||||
calls: list[str] = []
|
||||
vllm_config = SimpleNamespace(shutdown_timeout=shutdown_timeout)
|
||||
proc = SimpleNamespace(
|
||||
shutdown_state=EngineShutdownState.RUNNING,
|
||||
has_work=lambda: has_work,
|
||||
vllm_config=vllm_config,
|
||||
)
|
||||
|
||||
def run_busy_loop():
|
||||
proc.shutdown_state = shutdown_state
|
||||
raise SystemExit(exit_code)
|
||||
|
||||
proc.run_busy_loop = run_busy_loop
|
||||
proc.shutdown = lambda: calls.append("shutdown")
|
||||
parallel_config = SimpleNamespace(
|
||||
data_parallel_size=1,
|
||||
numa_bind=False,
|
||||
reconfigure_for_independent_dp_rank=lambda: None,
|
||||
)
|
||||
vllm_config.parallel_config = parallel_config
|
||||
|
||||
for name in (
|
||||
"maybe_register_config_serialize_by_value",
|
||||
"set_process_title",
|
||||
"maybe_init_worker_tracer",
|
||||
"decorate_logs",
|
||||
):
|
||||
monkeypatch.setattr(core_module, name, lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(core_module, "EngineCoreProc", lambda *args, **kwargs: proc)
|
||||
monkeypatch.setattr(
|
||||
core_module,
|
||||
"SignalCallback",
|
||||
lambda callback: SimpleNamespace(trigger=lambda: None, stop=lambda: None),
|
||||
)
|
||||
monkeypatch.setattr(core_module.signal, "signal", lambda *args: None)
|
||||
monkeypatch.setattr(
|
||||
platforms, "current_platform", SimpleNamespace(is_rocm=lambda: is_rocm)
|
||||
)
|
||||
monkeypatch.setattr(core_module.gc, "freeze", lambda: calls.append("freeze"))
|
||||
|
||||
with pytest.raises(SystemExit):
|
||||
EngineCoreProc.run_engine_core(vllm_config=vllm_config)
|
||||
|
||||
assert calls == expected_calls
|
||||
|
||||
|
||||
class _FinishedProcess:
|
||||
name = "RustFrontend"
|
||||
|
||||
def __init__(self, sentinel):
|
||||
self.sentinel = sentinel
|
||||
|
||||
@property
|
||||
def exitcode(self):
|
||||
return 1
|
||||
|
||||
|
||||
def test_wait_for_engine_startup_reports_watched_process_exit():
|
||||
"""Update the startup test argument so it reaches frontend failure handling."""
|
||||
ctx = zmq.Context()
|
||||
handshake_socket = ctx.socket(zmq.ROUTER)
|
||||
recv, send = connection.Pipe(duplex=False)
|
||||
send.close()
|
||||
|
||||
parallel_config = SimpleNamespace(
|
||||
data_parallel_size_local=1,
|
||||
data_parallel_hybrid_lb=False,
|
||||
data_parallel_external_lb=False,
|
||||
)
|
||||
|
||||
try:
|
||||
launch = CoreEngineLaunch(
|
||||
engine_manager=None,
|
||||
coordinator=None,
|
||||
addresses=EngineZmqAddresses(inputs=[], outputs=[]),
|
||||
tensor_queue=None,
|
||||
)
|
||||
launch.watched_frontend_processes = [_FinishedProcess(recv)]
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
wait_for_engine_startup(
|
||||
handshake_socket,
|
||||
[CoreEngine()],
|
||||
parallel_config,
|
||||
coordinated_dp=False,
|
||||
cache_config=None,
|
||||
launch=launch,
|
||||
)
|
||||
finally:
|
||||
recv.close()
|
||||
handshake_socket.close(linger=0)
|
||||
ctx.term()
|
||||
|
||||
assert "Frontend process failed during engine core initialization" in str(
|
||||
exc_info.value
|
||||
)
|
||||
assert "Failed frontend proc(s): {'RustFrontend': 1}" in str(exc_info.value)
|
||||
Reference in New Issue
Block a user