[Bugfix] Fix lost async diffusion outputs in request-level batching (#6023)

Signed-off-by: samithuang <285365963@qq.com>
This commit is contained in:
Samit authored and GitHub committed 2026-08-15 18:27:51 +08:00
1 parent ce6ab0ca46
commit 136cb27b05
9 files changed
+475 -55

No files matched your search

+10 -1
View File
@@ -339,7 +339,16 @@ class DiffusionEngine:
# Async mode: wait for background D2H/SHM to complete.
if output.async_output_id:
fut = self.executor.wait_output_ready(output.async_output_id)
output = await asyncio.wait_for(asyncio.wrap_future(fut), timeout=_ASYNC_OUTPUT_TIMEOUT)
try:
output = await asyncio.wait_for(asyncio.wrap_future(fut), timeout=_ASYNC_OUTPUT_TIMEOUT)
except (TimeoutError, asyncio.TimeoutError):
describe = getattr(self.executor, "describe_pending_state", None)
logger.error(
"Timed out after %.0fs waiting for async output; executor state: %s",
_ASYNC_OUTPUT_TIMEOUT,
describe(output.async_output_id) if describe else "unavailable",
)
raise
postprocess_start_time = time.perf_counter()
formatted_outputs = self.postprocess_output(request, output)
postprocess_time = time.perf_counter() - postprocess_start_time
@@ -641,8 +641,23 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
async_output_id=per_req_id,
)
)
# The worker's background D2H/SHM thread can publish OUTPUT_READY
# before this call returns. In that case the pump found no split
# map and cached the whole batch output under batch_id, so adopt it
# here instead of registering a map nothing will ever consume.
with self._futures_lock:
self._batch_split_map[batch_id] = per_req_map
early = self._completed_outputs.pop(batch_id, None)
if early is None:
self._batch_split_map[batch_id] = per_req_map
if early is not None:
logger.debug("Batch %s output arrived before split map; splitting now", batch_id)
try:
batch_output = early.result()
error = None
except Exception as exc:
batch_output = None
error = str(exc)
self._deliver_batch_split(per_req_map, batch_output, error)
return BatchRunnerOutput.from_list(runner_outputs)
if not isinstance(result, BatchRunnerOutput):
raise RuntimeError(f"Unexpected response type for execute_batch: {type(result)!r}")
@@ -868,52 +883,76 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
unpack_diffusion_output_shm(msg.output)
except Exception:
logger.exception("SHM unpack failed for batch %s", batch_id)
batch_output = msg.output
for per_req_id, req_id in per_req_map.items():
req_output = batch_output.get_request_output(req_id)
per_req_result: DiffusionOutput
if req_output is not None and req_output.result is not None:
per_req_result = req_output.result
elif msg.error:
per_req_result = DiffusionOutput(error=msg.error)
else:
per_req_result = DiffusionOutput(error="No output result for batch request")
fut: concurrent.futures.Future = concurrent.futures.Future()
fut.set_result(per_req_result)
with self._futures_lock:
pending = self._output_futures.pop(per_req_id, None)
if pending is not None and not pending.done():
pending.set_result(per_req_result)
else:
self._completed_outputs[per_req_id] = fut
self._deliver_batch_split(per_req_map, msg.output, msg.error)
else:
with self._futures_lock:
fut = self._output_futures.pop(batch_id, None) if batch_id else None
if fut is not None and not fut.done():
if msg.error:
fut.set_exception(RuntimeError(msg.error))
else:
try:
unpack_diffusion_output_shm(msg.output)
except Exception as e:
logger.exception("SHM unpack failed in result pump")
fut.set_exception(e)
continue
fut.set_result(msg.output)
elif batch_id:
fut = concurrent.futures.Future()
if msg.error:
fut.set_exception(RuntimeError(msg.error))
else:
try:
unpack_diffusion_output_shm(msg.output)
except Exception as e:
logger.exception("SHM unpack failed in result pump (cached)")
fut.set_exception(e)
else:
fut.set_result(msg.output)
# Single-request result: unpack SHM first, then resolve or cache atomically.
output_result: DiffusionOutput | None = None
exc: Exception | None = None
if msg.error:
exc = RuntimeError(msg.error)
else:
try:
unpack_diffusion_output_shm(msg.output)
output_result = msg.output
except Exception as e:
logger.exception("SHM unpack failed in result pump")
exc = e
if batch_id:
with self._futures_lock:
self._completed_outputs[batch_id] = fut
pending = self._output_futures.pop(batch_id, None)
if pending is not None and not pending.done():
if exc is not None:
pending.set_exception(exc)
else:
pending.set_result(output_result)
else:
fut = concurrent.futures.Future()
if exc is not None:
fut.set_exception(exc)
else:
fut.set_result(output_result)
self._completed_outputs[batch_id] = fut
def _deliver_batch_split(
self,
per_req_map: dict[str, str],
batch_output: Any,
error: str | None = None,
) -> None:
"""Resolve per-request futures from one batch-level output."""
for per_req_id, req_id in per_req_map.items():
req_output = batch_output.get_request_output(req_id) if batch_output is not None else None
per_req_result: DiffusionOutput
if req_output is not None and req_output.result is not None:
per_req_result = req_output.result
elif error:
per_req_result = DiffusionOutput(error=error)
else:
per_req_result = DiffusionOutput(error="No output result for batch request")
with self._futures_lock:
pending = self._output_futures.pop(per_req_id, None)
if pending is not None and not pending.done():
pending.set_result(per_req_result)
else:
fut: concurrent.futures.Future = concurrent.futures.Future()
fut.set_result(per_req_result)
self._completed_outputs[per_req_id] = fut
def describe_pending_state(self, async_output_id: str | None = None) -> str:
"""Summarize async-output bookkeeping for diagnosing stuck waits."""
with self._futures_lock:
waiting = list(self._output_futures)
cached = list(self._completed_outputs)
batches = list(self._batch_split_map)
rpcs = list(self._rpc_futures)
return (
f"async_output_id={async_output_id} "
f"waiting={len(waiting)}{waiting[:5]} "
f"cached={len(cached)}{cached[:5]} "
f"unsplit_batches={len(batches)}{batches[:5]} "
f"pending_rpcs={len(rpcs)}{rpcs[:5]}"
)
def _next_rpc_id(self) -> str:
with self._rpc_id_lock:
+13 -2
View File
@@ -121,8 +121,19 @@ def _pack_tensor_if_large(
val: torch.Tensor,
d2h_stream: torch.Stream | None = None,
) -> torch.Tensor | dict:
"""Replace a tensor with an SHM handle if it exceeds the threshold."""
if val.nelement() * val.element_size() > _SHM_TENSOR_THRESHOLD:
"""Replace a tensor with an SHM handle if it exceeds the threshold.
Batch outputs are split into per-request views that share one storage.
Pickle serializes a view's whole storage, so a batch of small views costs
the full batch tensor once per request. Size the decision on the storage
to keep those views off the wire; packing copies just the view.
"""
view_bytes = val.nelement() * val.element_size()
try:
storage_bytes = val.untyped_storage().nbytes()
except Exception:
storage_bytes = view_bytes
if max(view_bytes, storage_bytes) > _SHM_TENSOR_THRESHOLD:
return _tensor_to_shm(val, d2h_stream=d2h_stream)
return val
+57 -6
View File
@@ -65,6 +65,15 @@ from vllm_omni.worker.gpu_memory_utils import get_process_gpu_memory
logger = init_logger(__name__)
_ASYNC_OUTPUT_THREAD_JOIN_TIMEOUT_S = 10.0
# Maximum time (in seconds) to wait for pending background D2H / SHM packing
# to drain before the worker executes memory-releasing lifecycle tasks
# (e.g. during sleep/wake transitions). This barrier prevents device tensors
# from being freed while the side CUDA stream is still actively reading them.
_ASYNC_OUTPUT_DRAIN_TIMEOUT_S = 10.0
# Worker entry points that release device memory. Background D2H/SHM packing
# still reads model output tensors, so it must finish before these run.
_MEMORY_RELEASING_METHODS = frozenset({"sleep", "handle_sleep_task"})
@dataclass
@@ -850,6 +859,13 @@ class WorkerProc:
self._async_output_queue: queue.Queue | None = None
self._async_output_thread: threading.Thread | None = None
self._async_output_done = threading.Condition()
self._async_output_pending = 0
# MessageQueue.acquire_write() is single-writer: it reads current_idx,
# writes that block, then advances the index. The async output thread
# enqueues OUTPUT_READY while the main loop enqueues COMPUTE_DONE, so
# unsynchronized writers can target the same block and drop a message.
self._result_mq_lock = threading.Lock()
if not self.od_config.step_execution:
self._async_output_queue = queue.Queue()
self._async_output_thread = threading.Thread(
@@ -882,25 +898,32 @@ class WorkerProc:
)
return wrapper
def _enqueue_result(self, msg: Any) -> None:
"""Serialize writes to the single-writer result queue."""
with self._result_mq_lock:
self.result_mq.enqueue(msg)
def _return_result(self, output: Any, rpc_id: str | None = None) -> None:
"""Reply to client, only on rank 0."""
if self.result_mq is None:
return
if isinstance(output, OmniACK):
self.result_mq.enqueue(output)
self._enqueue_result(output)
return
# Async path: enqueue compute_done immediately, bg thread does D2H+SHM.
if not self.od_config.step_execution and isinstance(output, (DiffusionOutput, BatchRunnerOutput)):
async_output_id = WorkerProc._generate_async_output_id()
gpu_event = current_omni_platform.record_device_event()
with self._async_output_done:
self._async_output_pending += 1
self._async_output_queue.put((output, async_output_id, gpu_event))
msg = AsyncDiffusionOutput(
kind=AsyncOutputKind.COMPUTE_DONE,
rpc_id=rpc_id,
async_output_id=async_output_id,
)
self.result_mq.enqueue(msg)
self._enqueue_result(msg)
return
# Sync path (original, or async fallback).
@@ -909,7 +932,7 @@ class WorkerProc:
except Exception as e:
if hasattr(output, "output"):
logger.warning("SHM pack failed for model output: %s", e)
self.result_mq.enqueue(output)
self._enqueue_result(output)
def _async_output_loop(self):
"""Background thread: D2H + SHM packing for async diffusion output.
@@ -932,7 +955,7 @@ class WorkerProc:
pack_diffusion_output_shm(output, d2h_stream=d2h_stream)
d2h_stream.synchronize()
self.result_mq.enqueue(
self._enqueue_result(
AsyncDiffusionOutput(
kind=AsyncOutputKind.OUTPUT_READY,
async_output_id=async_output_id,
@@ -944,13 +967,38 @@ class WorkerProc:
"Async output packing failed for id '%s'; sending error",
async_output_id,
)
self.result_mq.enqueue(
self._enqueue_result(
AsyncDiffusionOutput(
kind=AsyncOutputKind.OUTPUT_READY,
async_output_id=async_output_id,
error="Background D2H/SHM packing failed",
)
)
finally:
with self._async_output_done:
# Clamped: only items enqueued by _return_result are counted.
self._async_output_pending = max(0, self._async_output_pending - 1)
self._async_output_done.notify_all()
def drain_async_outputs(self, timeout: float = _ASYNC_OUTPUT_DRAIN_TIMEOUT_S) -> bool:
"""Block until background D2H/SHM packing has no work left.
Returns False if outputs are still in flight when ``timeout`` expires.
"""
with self._async_output_done:
if self._async_output_pending == 0:
return True
drained = self._async_output_done.wait_for(lambda: self._async_output_pending == 0, timeout=timeout)
pending = self._async_output_pending
if not drained:
logger.warning(
"Worker %d: %d async output(s) still in flight after %.1fs; "
"releasing device memory now may drop OUTPUT_READY messages",
self.gpu_id,
pending,
timeout,
)
return drained
def shutdown(self) -> None:
"""Stop background work and release worker-owned IPC resources."""
@@ -1049,6 +1097,8 @@ class WorkerProc:
}
try:
if method in _MEMORY_RELEASING_METHODS:
self.drain_async_outputs()
# Use execute_method from WorkerWrapperBase for consistent method resolution
result = self.worker.execute_method(method, *args, **kwargs)
except Exception as e:
@@ -1114,6 +1164,7 @@ class WorkerProc:
continue
if isinstance(msg, dict) and msg.get("type") == "sleep":
self.drain_async_outputs()
task = OmniSleepTask(level=msg.get("level", 2), task_id=msg.get("task_id", "local"))
ack = self.worker.handle_sleep_task(task)
self._return_result(ack)
@@ -1140,7 +1191,7 @@ class WorkerProc:
if rpc_id is not None:
# Async RPC: must complete the executor's pending
# future so collective_rpc() doesn't hang.
self.result_mq.enqueue(
self._enqueue_result(
AsyncDiffusionOutput(
kind=AsyncOutputKind.RPC_RESULT,
rpc_id=rpc_id,