[Core] Add UniProc diffusion executor for single-GPU (#6308)

Signed-off-by: Rahul Steiger <rsteiger@nvidia.com>
Signed-off-by: Rahul Steiger <rsteiger@aws-cmh-slurm-1-vscode-04.cm.cluster>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Rahul Steiger <rsteiger@aws-cmh-slurm-1-vscode-04.cm.cluster>
This commit is contained in:
authored and GitHub committed 2026-08-22 21:58:21 +08:00
1 parent 72ee535fcd
commit b39f599b09
10 files changed
+619 -60

No files matched your search

+262
View File
@@ -0,0 +1,262 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Single-GPU (uniproc) diffusion executor: selection and RPC behaviour."""
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
import torch
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.executor.abstract import DiffusionExecutor
from vllm_omni.diffusion.executor.multiproc_executor import MultiprocDiffusionExecutor
from vllm_omni.diffusion.executor.uniproc_executor import UniProcDiffusionExecutor
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
class _FakeODConfig:
def __init__(self, num_gpus: int = 1, backend: str | None = None) -> None:
self.num_gpus = num_gpus
self.distributed_executor_backend = backend
self.worker_extension_cls = None
self.custom_pipeline_args = None
def _od_config(num_gpus: int = 1, backend: str | None = None) -> _FakeODConfig:
return _FakeODConfig(num_gpus=num_gpus, backend=backend)
def test_single_gpu_defaults_to_uniproc():
assert DiffusionExecutor.get_class(_od_config(num_gpus=1)) is UniProcDiffusionExecutor
def test_explicit_mp_is_honored_on_single_gpu():
assert DiffusionExecutor.get_class(_od_config(num_gpus=1, backend="mp")) is MultiprocDiffusionExecutor
def test_multi_gpu_defaults_to_multiproc():
assert DiffusionExecutor.get_class(_od_config(num_gpus=2)) is MultiprocDiffusionExecutor
def test_explicit_uni_backend_is_honored():
assert DiffusionExecutor.get_class(_od_config(num_gpus=1, backend="uni")) is UniProcDiffusionExecutor
@pytest.fixture
def executor(monkeypatch: pytest.MonkeyPatch):
"""A ``UniProcDiffusionExecutor`` with a mocked worker (no model load)."""
worker = MagicMock()
monkeypatch.setattr(
"vllm_omni.diffusion.executor.uniproc_executor.current_omni_platform.get_diffusion_worker_cls",
MagicMock(return_value="vllm_omni.diffusion.worker.diffusion_worker.DiffusionWorker"),
)
monkeypatch.setattr(
"vllm_omni.diffusion.executor.uniproc_executor.resolve_obj_by_qualname",
MagicMock(return_value=object),
)
monkeypatch.setattr(
"vllm_omni.diffusion.worker.diffusion_worker.WorkerWrapperBase",
MagicMock(return_value=worker),
)
return UniProcDiffusionExecutor(_od_config(num_gpus=1)), worker
def test_rejects_multi_gpu_config(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"vllm_omni.diffusion.executor.uniproc_executor.current_omni_platform.get_diffusion_worker_cls",
MagicMock(return_value="unused"),
)
with pytest.raises(ValueError, match="single GPU only"):
UniProcDiffusionExecutor(_od_config(num_gpus=4))
def test_shutdown_is_safe_on_partially_constructed_executor(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(
"vllm_omni.diffusion.executor.uniproc_executor.current_omni_platform.get_diffusion_worker_cls",
MagicMock(return_value="unused"),
)
monkeypatch.setattr(
"vllm_omni.diffusion.executor.uniproc_executor.resolve_obj_by_qualname",
MagicMock(return_value=object),
)
monkeypatch.setattr(
"vllm_omni.diffusion.worker.diffusion_worker.WorkerWrapperBase",
MagicMock(side_effect=RuntimeError("model load blew up")),
)
constructed = UniProcDiffusionExecutor.__new__(UniProcDiffusionExecutor)
with pytest.raises(RuntimeError, match="model load blew up"):
constructed.__init__(_od_config(num_gpus=1))
constructed.shutdown()
def test_collective_rpc_calls_worker_directly(executor):
exec_, worker = executor
worker.execute_method.return_value = "result"
out = exec_.collective_rpc("some_method", args=(1, 2), kwargs={"k": "v"}, unique_reply_rank=0)
assert out == "result"
worker.execute_method.assert_called_once_with("some_method", 1, 2, k="v")
def test_collective_rpc_returns_list_when_no_reply_rank(executor):
exec_, worker = executor
worker.execute_method.return_value = "result"
assert exec_.collective_rpc("some_method") == ["result"]
def test_collective_rpc_propagates_worker_exceptions(executor):
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("boom")
with pytest.raises(RuntimeError, match="boom"):
exec_.collective_rpc("some_method", unique_reply_rank=0)
def test_recoverable_worker_failure_keeps_the_executor_alive(executor, monkeypatch):
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("CUDA out of memory")
monkeypatch.setattr(exec_, "_device_is_usable", lambda: True)
died = MagicMock()
exec_.register_failure_callback(died)
with pytest.raises(RuntimeError):
exec_.collective_rpc("some_method", unique_reply_rank=0)
assert exec_.is_dead is False
died.assert_not_called()
exec_.check_health()
def test_poisoned_cuda_context_marks_the_executor_dead(executor, monkeypatch):
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("an illegal memory access was encountered")
monkeypatch.setattr(exec_, "_device_is_usable", lambda: False)
died = MagicMock()
exec_.register_failure_callback(died)
with pytest.raises(RuntimeError):
exec_.collective_rpc("some_method", unique_reply_rank=0)
assert exec_.is_dead is True
died.assert_called_once_with()
with pytest.raises(EngineDeadError):
exec_.check_health()
def test_failure_is_latched_and_callbacks_fire_once(executor, monkeypatch):
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("boom")
monkeypatch.setattr(exec_, "_device_is_usable", lambda: False)
died = MagicMock()
exec_.register_failure_callback(died)
for _ in range(3):
with pytest.raises(RuntimeError):
exec_.collective_rpc("some_method", unique_reply_rank=0)
died.assert_called_once_with()
def test_device_probe_is_skipped_when_cuda_was_never_initialized(executor):
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("boom")
with pytest.raises(RuntimeError):
exec_.collective_rpc("some_method", unique_reply_rank=0)
if not torch.cuda.is_initialized():
assert exec_.is_dead is False
def test_device_probe_skipped_when_accelerator_unavailable(executor, monkeypatch):
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("boom")
monkeypatch.setattr(torch.accelerator, "is_available", lambda: False)
sync = MagicMock()
monkeypatch.setattr(torch.accelerator, "synchronize", sync)
with pytest.raises(RuntimeError, match="boom"):
exec_.collective_rpc("some_method", unique_reply_rank=0)
sync.assert_not_called()
assert exec_.is_dead is False
def test_device_probe_skipped_when_device_not_initialized(executor, monkeypatch):
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("boom")
monkeypatch.setattr(torch.accelerator, "is_available", lambda: True)
monkeypatch.setattr(torch.accelerator, "current_accelerator", lambda: SimpleNamespace(type="npu"))
monkeypatch.setattr(torch, "npu", SimpleNamespace(is_initialized=lambda: False), raising=False)
sync = MagicMock()
monkeypatch.setattr(torch.accelerator, "synchronize", sync)
with pytest.raises(RuntimeError, match="boom"):
exec_.collective_rpc("some_method", unique_reply_rank=0)
sync.assert_not_called()
assert exec_.is_dead is False
def test_device_probe_latches_sticky_fault_on_npu(executor, monkeypatch):
"""NPU must not short-circuit the probe the way a CUDA-only guard did."""
exec_, worker = executor
worker.execute_method.side_effect = RuntimeError("boom")
monkeypatch.setattr(torch.accelerator, "is_available", lambda: True)
monkeypatch.setattr(torch.accelerator, "current_accelerator", lambda: SimpleNamespace(type="npu"))
monkeypatch.setattr(torch, "npu", SimpleNamespace(is_initialized=lambda: True), raising=False)
monkeypatch.setattr(
torch.accelerator,
"synchronize",
MagicMock(side_effect=RuntimeError("NPU context poisoned")),
)
died = MagicMock()
exec_.register_failure_callback(died)
with pytest.raises(RuntimeError, match="boom"):
exec_.collective_rpc("some_method", unique_reply_rank=0)
assert exec_.is_dead is True
died.assert_called_once_with()
def test_check_health_ok_then_dead(executor):
exec_, _ = executor
exec_.check_health()
exec_._is_failed = True
with pytest.raises(EngineDeadError):
exec_.check_health()
def test_shutdown_is_idempotent_and_closes_executor(executor, monkeypatch):
exec_, worker = executor
collect = MagicMock()
empty_cache = MagicMock()
monkeypatch.setattr("vllm_omni.diffusion.executor.uniproc_executor.gc.collect", collect)
monkeypatch.setattr(
"vllm_omni.diffusion.executor.uniproc_executor.current_omni_platform.is_available",
lambda: True,
)
monkeypatch.setattr(
"vllm_omni.diffusion.executor.uniproc_executor.current_omni_platform.empty_cache",
empty_cache,
)
exec_.register_failure_callback(MagicMock())
exec_.shutdown()
exec_.shutdown()
worker.shutdown.assert_called_once()
assert exec_.driver_worker is None
assert exec_._failure_callbacks == []
collect.assert_called_once_with()
empty_cache.assert_called_once_with()
with pytest.raises(RuntimeError, match="closed"):
exec_.collective_rpc("some_method", unique_reply_rank=0)
@@ -166,8 +166,8 @@ async def test_sleep_memory_reclaimed_custom_pipeline():
The fix moves custom_pipeline init outside the CUDA context so all weights
go through the caching allocator and are therefore fully reclaimed by
sleep(level=1). A non-zero ``CuMemAllocator.get_current_usage()`` after
sleep is the direct signal that the bypass is still occurring.
sleep(level=1). The tracked allocations must transition to the allocator's
asleep state and report physical reclamation.
"""
with ExitStack() as after:
engine = AsyncOmni(
@@ -187,62 +187,72 @@ async def test_sleep_memory_reclaimed_custom_pipeline():
free_before, total = torch.cuda.mem_get_info()
used_before_gib = (total - free_before) / 1024**3
# Measure CuMemAllocator-tracked usage before sleep. In inline mode
# the worker runs in a thread pool inside this process, so the allocator
# singleton is shared and can be read directly.
# Measure CuMemAllocator-tracked usage before sleep. In inline / uni
# mode the worker runs in this process, so the allocator singleton is
# shared and can be read directly.
allocator = None
tracked_before = 0
tracked_ptrs: set[int] = set()
try:
from vllm.device_allocator.cumem import CuMemAllocator
allocator = CuMemAllocator.get_instance()
tracked_before = allocator.get_current_usage()
tracked_ptrs = {ptr for ptr, data in allocator.pointer_to_data.items() if not data.is_asleep}
tracked_before = sum(allocator.pointer_to_data[ptr].handle[1] for ptr in tracked_ptrs)
except Exception:
pass
# Put the engine to sleep; all weights should be offloaded via the pool.
acks = await engine.sleep(level=1)
await asyncio.sleep(0.5) # allow the CUDA driver to settle
torch.accelerator.synchronize()
slept = False
try:
# Put the engine to sleep; this engine's weights should be
# offloaded via the pool.
acks = await engine.sleep(level=1)
slept = True
await asyncio.sleep(0.5) # allow the CUDA driver to settle
torch.accelerator.synchronize()
# Measure after sleep.
free_after, _ = torch.cuda.mem_get_info()
used_after_gib = (total - free_after) / 1024**3
drop_gib = used_before_gib - used_after_gib
# Measure after sleep.
free_after, _ = torch.cuda.mem_get_info()
used_after_gib = (total - free_after) / 1024**3
drop_gib = used_before_gib - used_after_gib
# --- Primary assertion: allocator reports zero tracked memory. ---
# If this fails it means weights were allocated outside the CuMem pool
# (safetensors direct-to-GPU bypass) — the exact regression this test
# is designed to catch.
if allocator is not None:
tracked_after = allocator.get_current_usage()
assert tracked_after == 0, (
f"CuMemAllocator still tracks {tracked_after / 1024**3:.3f} GiB "
f"after sleep(level=1) on custom_pipeline path "
f"(was {tracked_before / 1024**3:.3f} GiB before sleep). "
"Weights were allocated outside the CuMem pool via the "
"safetensors direct-to-GPU fast path — loader-context fix "
"may not be applied."
# get_current_usage() includes unmapped sleeping handles, so it
# does not decrease on sleep. Verify that allocations mapped
# before the call instead transitioned to the asleep state.
if allocator is not None:
assert tracked_before > 0, (
"Expected custom_pipeline weights to use the CuMem pool, "
"but no mapped allocations were tracked before sleep."
)
still_awake = [
ptr
for ptr in tracked_ptrs
if ptr in allocator.pointer_to_data and not allocator.pointer_to_data[ptr].is_asleep
]
assert not still_awake, (
f"{len(still_awake)} CuMem allocation(s) remained mapped "
"after sleep(level=1) on the custom_pipeline path."
)
# Physical VRAM or ACK freed_bytes confirms reclamation at the
# driver level.
total_freed_bytes = sum(
(ack.freed_bytes if hasattr(ack, "freed_bytes") else ack.get("freed_bytes", 0))
for ack in acks
if ack is not None
)
freed_gib = total_freed_bytes / 1024**3
assert freed_gib > 0 or drop_gib > 0, (
f"Expected GPU memory to be reclaimed after sleep(level=1) on "
f"custom_pipeline + enable_sleep_mode=True. "
f"CuMemAllocator tracked before={tracked_before / 1024**3:.3f} GiB, "
f"ACK freed={freed_gib:.3f} GiB, global VRAM drop={drop_gib:.3f} GiB."
)
# --- Secondary assertion: physical VRAM or ACK freed_bytes confirms
# reclamation at the driver level.
total_freed_bytes = sum(
(ack.freed_bytes if hasattr(ack, "freed_bytes") else ack.get("freed_bytes", 0))
for ack in acks
if ack is not None
)
freed_gib = total_freed_bytes / 1024**3
assert freed_gib > 0 or drop_gib > 0, (
f"Expected GPU memory to be reclaimed after sleep(level=1) on "
f"custom_pipeline + enable_sleep_mode=True. "
f"CuMemAllocator tracked before={tracked_before / 1024**3:.3f} GiB, "
f"ACK freed={freed_gib:.3f} GiB, global VRAM drop={drop_gib:.3f} GiB."
)
# Engine must report it is sleeping.
assert await engine.is_sleeping()
# Wake up and confirm the engine is functional again.
await engine.wake_up()
assert not await engine.is_sleeping()
assert await engine.is_sleeping()
await engine.wake_up()
slept = False
assert not await engine.is_sleeping()
finally:
if slept:
await engine.wake_up()
@@ -17,9 +17,12 @@ from functools import lru_cache
import numpy as np
import pytest
import torch.distributed as dist
from transformers import AutoTokenizer
from tests.helpers.mark import hardware_test
from vllm_omni.diffusion.executor.uniproc_executor import UniProcDiffusionExecutor
from vllm_omni.diffusion.inline_stage_diffusion_client import InlineStageDiffusionClient
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
@@ -131,6 +134,19 @@ async def _generate_once(
return last_output
def _assert_live_uniproc_worker(engine: AsyncOmni) -> None:
"""Default single-GPU path must use the in-process executor, not mp IPC."""
clients = engine.engine.stage_clients
assert len(clients) == 1
client = clients[0]
assert isinstance(client, InlineStageDiffusionClient)
executor = client._engine.executor
assert isinstance(executor, UniProcDiffusionExecutor)
assert executor.driver_worker is not None
assert dist.is_initialized()
assert dist.get_world_size() == 1
def _assert_valid_image_output(output: OmniRequestOutput) -> None:
assert output.final_output_type == "image"
assert output.images, "Expected at least one generated image"
@@ -158,6 +174,7 @@ async def test_async_omni_generate():
)
after.callback(engine.shutdown)
_assert_live_uniproc_worker(engine)
output = await _generate_once(
engine,
"a beautiful sunset over the ocean with vibrant orange and purple clouds "
@@ -225,7 +225,7 @@ def test_default_stage_config_whitelist_none_fallback():
engine_args = stage_cfg["engine_args"]
assert engine_args["trust_remote_code"] is False
assert engine_args["distributed_executor_backend"] == "mp"
assert engine_args["distributed_executor_backend"] is None
assert engine_args["dtype"] == "auto"
assert engine_args["enforce_eager"] is False