diff --git a/docs/docs/sglang-diffusion/api/cli.mdx b/docs/docs/sglang-diffusion/api/cli.mdx
index 56a61d2768..b547bdb395 100644
--- a/docs/docs/sglang-diffusion/api/cli.mdx
+++ b/docs/docs/sglang-diffusion/api/cli.mdx
@@ -424,6 +424,13 @@ sglang serve \
--port 30010
```
+### Asynchronous output saving
+
+Use `--async-output-save` to overlap output saving with the next request during
+native NVIDIA CUDA serving. It is disabled by default. See
+[Asynchronous output saving](/docs/sglang-diffusion/performance-optimization#asynchronous-output-saving)
+for an example, eligible requests, and the response latency and memory tradeoffs.
+
### Health endpoints
SGLang Diffusion separates process liveness from inference readiness:
diff --git a/docs/docs/sglang-diffusion/performance-optimization.mdx b/docs/docs/sglang-diffusion/performance-optimization.mdx
index 78dcc4ed3a..d8e04247e8 100644
--- a/docs/docs/sglang-diffusion/performance-optimization.mdx
+++ b/docs/docs/sglang-diffusion/performance-optimization.mdx
@@ -93,9 +93,67 @@ These settings should preserve model behavior while changing residency, parallel
Serving many compatible requests concurrently. |
Inference Batching |
+
+ --async-output-save |
+ Image/video encoding and disk writes leave the GPU idle between queued requests. |
+ Asynchronous output saving |
+
+## Asynchronous output saving
+
+Enable `--async-output-save` to overlap output saving with the next request's GPU
+work during serving. Frame materialization, image/video encoding, and disk writes
+run on a background thread. The flag is disabled by default and does not change
+the model's generation settings or the requested output format.
+
+Use it when you have concurrent requests and saving takes a noticeable share of
+each request, such as PNG images or large videos from a fast model. A client that
+waits for each response before sending the next request has no work to overlap.
+
+### Enable
+
+The feature requires NVIDIA CUDA and the native SGLang backend in monolithic
+serving mode. After following [Installation](/docs/sglang-diffusion/installation),
+you can start this example on one GPU with the public Hugging Face model
+`Tongyi-MAI/Z-Image-Turbo`:
+
+```bash Command
+sglang serve \
+ --model-path Tongyi-MAI/Z-Image-Turbo \
+ --backend sglang \
+ --num-gpus 1 \
+ --batching-max-size 1 \
+ --async-output-save
+```
+
+Send concurrent requests using the [OpenAI-compatible API](/docs/sglang-diffusion/api/openai_api).
+`--batching-max-size 1` keeps each forward separate while allowing requests to
+queue. Grouped and dynamically batched forwards currently keep synchronous output
+saving.
+
+### Scope and tradeoffs
+
+- Only the output rank performs asynchronous saving, and only for requests that
+ save files and return their paths (`save_output=true` and
+ `return_file_paths_only=true` in the sampling parameters).
+- Warmup requests, raw-frame responses, requests with `save_output=false`, and
+ requests with `perf_dump_path` set or `SGLANG_DIFFUSION_STAGE_LOGGING=1` keep the
+ synchronous path. This includes the frame-return path used by `/rollout/generate`.
+- Each reply is sent from the saving thread as soon as its output is saved,
+ even while the next request's forward is running. Measure both throughput and
+ response latency against the flag disabled.
+- Up to two pending finalizations retain request outputs in GPU memory. The
+ scheduler waits for capacity before starting another forward; leave memory
+ headroom for the pending outputs as well as inference.
+- Per-request peak memory metrics can include allocations from the next request.
+ Asynchronous finalization skips the usual per-request allocator cache release.
+
+Compare the flag on and off with the same model, output shape, format, and client
+concurrency. Keep it disabled when the reply latency or extra memory outweighs
+the throughput gain.
+
## Quality-Tradeoff / Lossy Or Approximate Levers
These techniques can change the denoising path, numerical representation, or generated output. They are useful after you have a baseline and an acceptance criterion for quality.
diff --git a/python/sglang/multimodal_gen/runtime/managers/gpu_worker.py b/python/sglang/multimodal_gen/runtime/managers/gpu_worker.py
index 901d475b6e..5f98bef67e 100644
--- a/python/sglang/multimodal_gen/runtime/managers/gpu_worker.py
+++ b/python/sglang/multimodal_gen/runtime/managers/gpu_worker.py
@@ -9,6 +9,7 @@ import tempfile
import time
from contextlib import ExitStack
from dataclasses import dataclass, field, replace
+from functools import partial
from typing import Any, Callable, Iterator, List, Union
import numpy as np
@@ -274,6 +275,13 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
self.cfg_cpu_group = self.cfg_group.cpu_group
self._realtime_sessions = RealtimeSessionCache(max_sessions=1)
self.memory_occupation: MemoryOccupationController | None = None
+ self._async_output_save = (
+ server_args.async_output_save
+ and self.is_output_rank
+ and current_platform.is_cuda()
+ )
+ self._deferred_finalize: Callable[[], None] | None = None
+ self._deferred_save_stream = None
# per-rank memory measurements of server warmup forwards; consumed by
# the auto-residency placement decision before the server turns ready
self._auto_residency_warmup_records: list[WarmupMemoryRecord] = []
@@ -506,7 +514,7 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
)
def execute_forward(
- self, batch: List[Req], return_req: bool = False
+ self, batch: List[Req], return_req: bool = False, defer_finalize: bool = False
) -> OutputBatch | Req:
"""
Execute a forward pass.
@@ -515,6 +523,9 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
batch: List of requests to process.
return_req: If True, return the raw Req instead of OutputBatch.
Used by disaggregated pipelines to access intermediate tensors.
+ defer_finalize: If True and the request is eligible, skip output
+ materialization and stash it as a closure for the caller to
+ retrieve via take_deferred_finalize() and run off the event loop.
"""
assert self.pipeline is not None
# request boundary: the IPC watchdog flag is a device read, illegal
@@ -541,6 +552,7 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
req, output_batch
),
error_context=f"request {req.request_id}",
+ defer_finalize=defer_finalize,
)
def execute_forward_sequentially(self, batch: list[Req]) -> Iterator[OutputBatch]:
@@ -618,6 +630,7 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
error_context: str,
execution_start_time: float | None = None,
propagate_forward_errors: bool = False,
+ defer_finalize: bool = False,
) -> OutputBatch | Req:
"""
Args:
@@ -625,6 +638,9 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
"""
output_batch = None
forward_failed = False
+ # A closure left behind by an aborted dispatch must not pair with this
+ # request's output.
+ self._deferred_finalize = None
# Prewarm reqs (is_warmup=False) run a different offload layout and
# must not contaminate the calibration records. Pipelines that cannot
# apply a residency plan also skip the temporary per-layer hooks.
@@ -727,38 +743,25 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
for metrics in output_metrics:
metrics.total_duration_ms = duration_ms
- req_label = req.request_id[:8] if req.request_id else "unnamed"
- with maybe_record_function(f"SAVE_OUTPUTS {req_label}"):
- self._materialize_output_transport(output_batch, req, save_output_paths)
- self._record_output_peak_memory(output_batch, is_warmup=req.is_warmup)
-
- collect_perf = (
- req.perf_dump_path is not None or envs.SGLANG_DIFFUSION_STAGE_LOGGING
- )
- if collect_perf and not req.is_warmup:
- self._record_replica_peak_memory(output_metrics)
-
- if (
- self.is_output_rank
- and not req.suppress_logs
- and not current_platform.is_cpu()
- and logger.isEnabledFor(logging.DEBUG)
- ):
- self.do_mem_analysis(output_batch)
-
- if (
- not current_platform.is_cpu()
- and output_batch.output is None
- and not req.return_raw_frames
- ):
- with maybe_record_function("EMPTY_CACHE"):
- torch.get_device_module().empty_cache()
-
- if req.perf_dump_path is not None or envs.SGLANG_DIFFUSION_STAGE_LOGGING:
- if not req.is_warmup:
- PerformanceLogger.log_request_summary(metrics=output_batch.metrics)
-
- self._dump_perf_report(req, output_batch)
+ if defer_finalize and self._can_defer_finalize(req):
+ done_event = torch.get_device_module().Event()
+ done_event.record()
+ self._deferred_finalize = partial(
+ self._finalize_deferred,
+ output_batch=output_batch,
+ req=req,
+ save_output_paths=save_output_paths,
+ output_metrics=output_metrics,
+ done_event=done_event,
+ )
+ else:
+ self._finalize_output_batch(
+ output_batch=output_batch,
+ req=req,
+ save_output_paths=save_output_paths,
+ output_metrics=output_metrics,
+ deferred=False,
+ )
except Exception as e:
if propagate_forward_errors and forward_failed:
if isinstance(e, StopIteration):
@@ -802,6 +805,99 @@ class GPUWorker(GPUWorkerPostTrainingMixin):
)
return output_batch
+ def _finalize_output_batch(
+ self,
+ *,
+ output_batch: OutputBatch,
+ req: Req,
+ save_output_paths: Callable[[OutputBatch], None],
+ output_metrics: list[Any],
+ deferred: bool,
+ ) -> None:
+ req_label = req.request_id[:8] if req.request_id else "unnamed"
+ with maybe_record_function(f"SAVE_OUTPUTS {req_label}"):
+ self._materialize_output_transport(output_batch, req, save_output_paths)
+ self._record_output_peak_memory(output_batch, is_warmup=req.is_warmup)
+
+ collect_perf = (
+ req.perf_dump_path is not None or envs.SGLANG_DIFFUSION_STAGE_LOGGING
+ )
+ if collect_perf and not req.is_warmup:
+ self._record_replica_peak_memory(output_metrics)
+
+ if (
+ self.is_output_rank
+ and not req.suppress_logs
+ and not current_platform.is_cpu()
+ and logger.isEnabledFor(logging.DEBUG)
+ ):
+ self.do_mem_analysis(output_batch)
+
+ # Deferred finalize keeps the allocator cache: releasing it while the
+ # next request is mid-forward causes cudaFree/cudaMalloc churn.
+ if (
+ not deferred
+ and not current_platform.is_cpu()
+ and output_batch.output is None
+ and not req.return_raw_frames
+ ):
+ with maybe_record_function("EMPTY_CACHE"):
+ torch.get_device_module().empty_cache()
+
+ if req.perf_dump_path is not None or envs.SGLANG_DIFFUSION_STAGE_LOGGING:
+ if not req.is_warmup:
+ PerformanceLogger.log_request_summary(metrics=output_batch.metrics)
+
+ self._dump_perf_report(req, output_batch)
+
+ def _can_defer_finalize(self, req: Req) -> bool:
+ # Perf-instrumented requests stay synchronous: their finalize runs a
+ # replica-wide all_reduce that must not fire from a second thread.
+ return (
+ self._async_output_save
+ and not req.is_warmup
+ and not req.return_raw_frames
+ and bool(req.save_output and req.return_file_paths_only)
+ and req.perf_dump_path is None
+ and not envs.SGLANG_DIFFUSION_STAGE_LOGGING
+ )
+
+ def _finalize_deferred(
+ self,
+ *,
+ output_batch: OutputBatch,
+ req: Req,
+ save_output_paths: Callable[[OutputBatch], None],
+ output_metrics: list[Any],
+ done_event: Any,
+ ) -> None:
+ """Runs on the scheduler's finalize thread, never on the event loop."""
+ # A dedicated stream, ordered after the producing forward via done_event,
+ # keeps the D2H copies and uint8 conversions off the next request's
+ # compute stream.
+ device_module = torch.get_device_module()
+ # CUDA's current device is thread-local; executor threads do not inherit
+ # the worker's device selection.
+ with device_module.device(self.local_rank):
+ if self._deferred_save_stream is None:
+ self._deferred_save_stream = device_module.Stream()
+ stream = self._deferred_save_stream
+ stream.wait_event(done_event)
+ with device_module.stream(stream):
+ self._finalize_output_batch(
+ output_batch=output_batch,
+ req=req,
+ save_output_paths=save_output_paths,
+ output_metrics=output_metrics,
+ deferred=True,
+ )
+ stream.synchronize()
+
+ def take_deferred_finalize(self) -> Callable[[], None] | None:
+ deferred = self._deferred_finalize
+ self._deferred_finalize = None
+ return deferred
+
def _record_server_warmup_memory(
self,
*,
diff --git a/python/sglang/multimodal_gen/runtime/managers/scheduler.py b/python/sglang/multimodal_gen/runtime/managers/scheduler.py
index 73906d9557..8d739221ed 100644
--- a/python/sglang/multimodal_gen/runtime/managers/scheduler.py
+++ b/python/sglang/multimodal_gen/runtime/managers/scheduler.py
@@ -3,13 +3,16 @@
# SPDX-License-Identifier: Apache-2.0
import dataclasses
import pickle
+import threading
import time
from collections import deque
+from concurrent.futures import Future, ThreadPoolExecutor
from contextlib import contextmanager
from copy import deepcopy
from enum import Enum
-from typing import Any, Iterator, List
+from typing import Any, Callable, Iterator, List
+import msgspec
import zmq
from sglang.multimodal_gen.runtime.disaggregation.roles import RoleType
@@ -80,6 +83,20 @@ logger = init_logger(__name__)
_MAX_RECV_REQS_PER_POLL = 1024
_BATCH_METRICS_LOG_INTERVAL = 5
+# Each pending finalize pins one request's output tensor on the GPU; arbitrary,
+# picked to bound that memory while still hiding one save behind one forward.
+_MAX_INFLIGHT_FINALIZES = 2
+
+
+class _DeferredOutput(msgspec.Struct):
+ """Forward result whose materialization and reply run off the event loop.
+
+ Never crosses the IPC boundary: the finalize thread runs finalize() and
+ then replies with the inner OutputBatch itself.
+ """
+
+ output_batch: OutputBatch
+ finalize: Callable[[], None]
@dataclasses.dataclass(frozen=True)
@@ -94,6 +111,9 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
This class does NOT manage worker processes.
"""
+ # instances built without __init__ (tests) still get a lock for the socket
+ _socket_lock = threading.Lock()
+
metrics: DiffusionMetrics | None = None
def __init__(
@@ -189,6 +209,19 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
self._max_consecutive_errors = 3
self._consecutive_error_count = 0
+ self._async_output_save = server_args.async_output_save and isinstance(
+ self.worker, GPUWorker
+ )
+ self._finalize_executor: ThreadPoolExecutor | None = None
+ self._inflight_finalizes: deque[Future] = deque()
+ # The finalize thread replies on the event loop's ROUTER socket, and a
+ # zmq socket must never be used by two threads at once.
+ self._socket_lock = threading.Lock()
+ if self._async_output_save:
+ self._finalize_executor = ThreadPoolExecutor(
+ max_workers=1, thread_name_prefix="sgl-diffusion-finalize"
+ )
+
self._init_disagg_state(server_args, local_rank)
if self._batch_metrics_enabled:
@@ -286,6 +319,12 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
):
"""Dispatch generation requests, merging compatible requests when allowed."""
reqs = self._normalize_generation_reqs(reqs)
+ if self._async_output_save:
+ # Reserve capacity before any forward allocates another output.
+ # The single finalize worker completes futures in FIFO order.
+ while len(self._inflight_finalizes) >= _MAX_INFLIGHT_FINALIZES:
+ self._inflight_finalizes.popleft().result()
+ self._reap_finalizes()
if self.worker.is_sleeping():
raise RuntimeError(
"Server is sleeping. Call resume_memory_occupation first."
@@ -312,6 +351,8 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
)
if len(reqs) == 1 or not allow_dynamic_batching:
+ if self._async_output_save and len(reqs) == 1:
+ return self._execute_forward_with_deferred_save(reqs)
return self.worker.execute_forward(reqs)
if self.server_args.pipeline_config.supports_native_grouped_requests():
@@ -788,8 +829,11 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
):
payload = pickle.dumps(output_batch)
- with self._record_return_stage(
- output_batch, "Scheduler.return_result.send"
+ with (
+ self._record_return_stage(
+ output_batch, "Scheduler.return_result.send"
+ ),
+ self._socket_lock,
):
self.receiver.send_multipart([identity, b"", payload])
@@ -826,6 +870,66 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
else:
self.return_result(output_batch, identity, should_not_return=is_warmup)
+ def _execute_forward_with_deferred_save(
+ self, reqs: list[Req]
+ ) -> OutputBatch | _DeferredOutput:
+ output = self.worker.execute_forward(reqs, defer_finalize=True)
+ finalize = self.worker.take_deferred_finalize()
+ if finalize is None:
+ return output
+ assert isinstance(output, OutputBatch)
+ return _DeferredOutput(output_batch=output, finalize=finalize)
+
+ def _submit_deferred_reply(
+ self,
+ *,
+ item: tuple[bytes | None, Any],
+ deferred: _DeferredOutput,
+ ) -> None:
+ assert self._finalize_executor is not None
+ future = self._finalize_executor.submit(
+ self._finalize_and_reply, item=item, deferred=deferred
+ )
+ self._inflight_finalizes.append(future)
+
+ def _finalize_and_reply(
+ self,
+ *,
+ item: tuple[bytes | None, Any],
+ deferred: _DeferredOutput,
+ ) -> None:
+ """Runs on the finalize thread; must never raise.
+
+ Replies as soon as the output is saved instead of waiting for the event
+ loop, which may be inside the next request's forward for its whole length.
+ """
+ try:
+ deferred.finalize()
+ except Exception as e:
+ logger.error("Deferred output finalize failed: %s", e, exc_info=True)
+ deferred.output_batch.error = f"Deferred output finalize failed: {e}"
+ # never ship device tensors through the reply path
+ deferred.output_batch.output = None
+ deferred.output_batch.audio = None
+ try:
+ self._return_item_result(item, deferred.output_batch)
+ except zmq.ZMQError as e:
+ logger.error(f"ZMQ error sending deferred reply: {e}")
+ except Exception as e:
+ logger.error("Deferred reply failed: %s", e, exc_info=True)
+
+ def _reap_finalizes(self) -> None:
+ while self._inflight_finalizes and self._inflight_finalizes[0].done():
+ self._inflight_finalizes.popleft()
+
+ def _drain_deferred_replies(self) -> None:
+ if not self._async_output_save:
+ return
+ while self._inflight_finalizes:
+ self._inflight_finalizes.popleft().result()
+ if self._finalize_executor is not None:
+ self._finalize_executor.shutdown(wait=True)
+
def _return_results_sequentially(
self,
items: list[tuple[bytes | None, Any]],
@@ -1206,13 +1310,15 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
if self.receiver is not None:
try:
recv_reqs: list[tuple[bytes, Any]] = []
- while len(recv_reqs) < _MAX_RECV_REQS_PER_POLL:
- try:
- # Accept valid REQ envelopes only, ignore malformed/probe frames.
- parts = self.receiver.recv_multipart(zmq.NOBLOCK)
- except zmq.Again:
- break
-
+ received: list[list[bytes]] = []
+ with self._socket_lock:
+ while len(received) < _MAX_RECV_REQS_PER_POLL:
+ try:
+ received.append(self.receiver.recv_multipart(zmq.NOBLOCK))
+ except zmq.Again:
+ break
+ for parts in received:
+ # Accept valid REQ envelopes only, ignore malformed/probe frames.
try:
identity, payload = parts[0], parts[-1]
reqs = pickle.loads(payload) if len(parts) > 2 else []
@@ -1276,6 +1382,8 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
logger.debug("Driver scheduler of dp replica %d listening", self.dp_replica)
while self._running:
+ self._reap_finalizes()
+
# Update queue depth for metrics
if self._disagg_metrics:
self._disagg_metrics.update_queue_depth(len(self.waiting_queue))
@@ -1323,9 +1431,19 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
elapsed_ms = (time.monotonic() - oldest_ts) * 1000.0
remaining_ms = max(0, self._batching_delay_s * 1000.0 - elapsed_ms)
if remaining_ms > 0 and self.receiver is not None:
- self._poller.poll(timeout=remaining_ms)
+ with self._socket_lock:
+ self._poller.poll(timeout=remaining_ms)
elif remaining_ms > 0:
time.sleep(remaining_ms / 1000.0)
+ elif self._inflight_finalizes:
+ # An idle hot spin convoys the finalize thread: each of its
+ # short GIL-holding ops waits a full switch interval, which
+ # turns a sub-second save into minutes. Yield instead.
+ if self.receiver is not None:
+ with self._socket_lock:
+ self._poller.poll(timeout=1)
+ else:
+ time.sleep(0.001)
continue
if self.metrics is not None:
@@ -1383,7 +1501,10 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
# 3. return results
try:
for item, output_batch in zip(items, output_batches, strict=True):
- self._return_item_result(item, output_batch)
+ if isinstance(output_batch, _DeferredOutput):
+ self._submit_deferred_reply(item=item, deferred=output_batch)
+ else:
+ self._return_item_result(item, output_batch)
except zmq.ZMQError as e:
# Reply failed; log and keep loop alive to accept future requests
logger.error(f"ZMQ error sending reply: {e}")
@@ -1393,6 +1514,7 @@ class Scheduler(SchedulerWarmupMixin, SchedulerPostTrainingMixin, SchedulerDisag
for _, req in items:
self.metrics.finish(id(req), error=True)
+ self._drain_deferred_replies()
self._log_batch_metrics_summary()
if self.receiver is not None:
diff --git a/python/sglang/multimodal_gen/runtime/server_args/server_args.py b/python/sglang/multimodal_gen/runtime/server_args/server_args.py
index c0cdcf0534..4217d08c79 100644
--- a/python/sglang/multimodal_gen/runtime/server_args/server_args.py
+++ b/python/sglang/multimodal_gen/runtime/server_args/server_args.py
@@ -547,6 +547,7 @@ class ServerArgs(DisaggServerArgsMixin):
batching_delay_ms: float = 0.0
batching_config: str | None = None
enable_batching_metrics: bool = False
+ async_output_save: bool = False
# Strict port mode: fail if requested port is unavailable instead of auto-selecting
strict_ports: bool = False
@@ -2871,6 +2872,18 @@ class ServerArgs(DisaggServerArgsMixin):
default=ServerArgs.enable_batching_metrics,
help="Log periodic batch efficiency metrics such as realized batch size and queue wait time.",
)
+ parser.add_argument(
+ "--async-output-save",
+ action="store_true",
+ default=ServerArgs.async_output_save,
+ help="Finalize outputs (frame materialization, image/video encoding, disk "
+ "write, reply) on a background thread so the scheduler can start the next "
+ "request's GPU work immediately. Applies to save-to-file requests on the "
+ "output rank; requests carrying perf instrumentation keep the synchronous "
+ "path. Memory metrics reported for a request may include the next "
+ "request's allocations, and the per-request allocator cache release is "
+ "skipped.",
+ )
parser.add_argument(
"--host",
type=str,
diff --git a/python/sglang/multimodal_gen/test/unit/test_async_output_save.py b/python/sglang/multimodal_gen/test/unit/test_async_output_save.py
new file mode 100644
index 0000000000..d8b42237bc
--- /dev/null
+++ b/python/sglang/multimodal_gen/test/unit/test_async_output_save.py
@@ -0,0 +1,260 @@
+# SPDX-License-Identifier: Apache-2.0
+
+import threading
+from collections import deque
+from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
+from contextlib import contextmanager
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import numpy as np
+import pytest
+import torch
+
+from sglang.multimodal_gen.configs.sample.sampling_params import SamplingParams
+from sglang.multimodal_gen.runtime.entrypoints.utils import _sample_to_uint8_frames
+from sglang.multimodal_gen.runtime.managers.gpu_worker import GPUWorker
+from sglang.multimodal_gen.runtime.managers.scheduler import Scheduler, _DeferredOutput
+from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import OutputBatch, Req
+
+
+def _req():
+ return Req(sampling_params=SamplingParams(prompt="test"))
+
+
+@pytest.mark.parametrize("fail", [False, True])
+def test_finalize_selects_worker_device_and_restores_thread_device(monkeypatch, fail):
+ current_device = 0
+ stream = Mock()
+
+ @contextmanager
+ def device(index):
+ nonlocal current_device
+ previous = current_device
+ current_device = index
+ try:
+ yield
+ finally:
+ current_device = previous
+
+ def make_stream():
+ assert current_device == 1
+ return stream
+
+ @contextmanager
+ def use_stream(selected):
+ assert selected is stream
+ assert current_device == 1
+ yield
+
+ device_module = SimpleNamespace(
+ device=device, Stream=Mock(side_effect=make_stream), stream=use_stream
+ )
+ monkeypatch.setattr(torch, "get_device_module", lambda: device_module)
+ worker = GPUWorker.__new__(GPUWorker)
+ worker.local_rank = 1
+ worker._deferred_save_stream = None
+ done_event = object()
+
+ def finalize(**kwargs):
+ assert current_device == 1
+ stream.wait_event.assert_called_with(done_event)
+ if fail:
+ raise OSError("save failed")
+
+ worker._finalize_output_batch = finalize
+ for _ in range(2):
+ try:
+ worker._finalize_deferred(
+ output_batch=OutputBatch(),
+ req=_req(),
+ save_output_paths=lambda _: None,
+ output_metrics=[],
+ done_event=done_event,
+ )
+ except OSError:
+ assert fail
+ else:
+ assert not fail
+ assert current_device == 0
+ device_module.Stream.assert_called_once()
+
+
+@pytest.mark.skipif(
+ not torch.cuda.is_available() or torch.cuda.device_count() < 2,
+ reason="requires two CUDA devices",
+)
+def test_finalize_materializes_pixels_on_nonzero_worker_device():
+ worker = GPUWorker.__new__(GPUWorker)
+ worker.local_rank = 1
+ worker._deferred_save_stream = None
+ observed = []
+
+ def finalize(**kwargs):
+ observed.append(
+ (
+ torch.cuda.current_device(),
+ torch.cuda.current_stream().device,
+ _sample_to_uint8_frames(kwargs["output_batch"].output[0]),
+ )
+ )
+
+ worker._finalize_output_batch = finalize
+
+ def run_finalize(output, done_event):
+ torch.cuda.set_device(0)
+ worker._finalize_deferred(
+ output_batch=OutputBatch(output=output),
+ req=_req(),
+ save_output_paths=lambda _: None,
+ output_metrics=[],
+ done_event=done_event,
+ )
+ assert torch.cuda.current_device() == 0
+
+ with torch.cuda.device(1), ThreadPoolExecutor(max_workers=1) as executor:
+ producer = torch.cuda.Stream()
+ for value in (0.0, 1.0):
+ with torch.cuda.stream(producer):
+ output = torch.full((1, 3, 1, 2, 2), value, device="cuda:1")
+ done_event = torch.cuda.Event()
+ done_event.record()
+ executor.submit(run_finalize, output, done_event).result(timeout=30)
+ device, stream_device, frames = observed[-1]
+ assert device == 1
+ assert stream_device == torch.device("cuda:1")
+ np.testing.assert_array_equal(frames[0], np.full((2, 2, 3), value * 255))
+
+
+@pytest.mark.parametrize("grouped", [False, True])
+def test_generation_waits_for_capacity_before_forward(grouped):
+ waiting = Future()
+
+ class ObservedFuture(Future):
+ def result(self, timeout=None):
+ waiting.set_result(None)
+ return super().result(timeout)
+
+ first, second = ObservedFuture(), Future()
+ scheduler = Scheduler.__new__(Scheduler)
+ scheduler._async_output_save = True
+ scheduler._inflight_finalizes = deque([first, second])
+ scheduler.server_args = SimpleNamespace(
+ pipeline_config=SimpleNamespace(
+ supports_sequential_multi_output_inference=lambda: False
+ )
+ )
+ reqs = [_req() for _ in range(2 if grouped else 1)]
+
+ def forward(*args, **kwargs):
+ assert first.done()
+ assert not second.done()
+ return OutputBatch()
+
+ scheduler.worker = SimpleNamespace(
+ is_sleeping=lambda: False,
+ execute_forward=Mock(side_effect=forward),
+ take_deferred_finalize=lambda: lambda: None,
+ )
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ dispatch = executor.submit(
+ scheduler._handle_generation, reqs, allow_dynamic_batching=False
+ )
+ try:
+ done, _ = wait([waiting, dispatch], timeout=10, return_when=FIRST_COMPLETED)
+ assert waiting in done
+ assert not dispatch.done()
+ scheduler.worker.execute_forward.assert_not_called()
+ first.set_result(None)
+ result = dispatch.result(timeout=10)
+ assert isinstance(result, OutputBatch if grouped else _DeferredOutput)
+ scheduler.worker.execute_forward.assert_called_once()
+ finally:
+ if not first.done():
+ first.set_result(None)
+ second.set_result(None)
+
+
+def test_generation_with_one_pending_finalize_still_overlaps():
+ scheduler = Scheduler.__new__(Scheduler)
+ scheduler._async_output_save = True
+ pending = Future()
+ scheduler._inflight_finalizes = deque([pending])
+ scheduler.server_args = SimpleNamespace(
+ pipeline_config=SimpleNamespace(
+ supports_sequential_multi_output_inference=lambda: False
+ )
+ )
+ scheduler.worker = SimpleNamespace(
+ is_sleeping=lambda: False,
+ execute_forward=Mock(return_value=OutputBatch()),
+ take_deferred_finalize=lambda: lambda: None,
+ )
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ dispatch = executor.submit(scheduler._handle_generation, [_req()])
+ try:
+ assert isinstance(dispatch.result(timeout=10), _DeferredOutput)
+ assert not pending.done()
+ scheduler.worker.execute_forward.assert_called_once()
+ finally:
+ pending.set_result(None)
+
+
+def _finalize_scheduler(replies):
+ scheduler = Scheduler.__new__(Scheduler)
+ scheduler._async_output_save = True
+ scheduler._inflight_finalizes = deque()
+ scheduler._finalize_executor = ThreadPoolExecutor(
+ max_workers=1, thread_name_prefix="sgl-diffusion-finalize"
+ )
+ scheduler._return_item_result = lambda item, batch: replies.append(
+ (threading.current_thread().name, item, batch)
+ )
+ return scheduler
+
+
+@pytest.mark.parametrize("fail", [False, True])
+def test_deferred_reply_leaves_as_soon_as_finalize_finishes(fail):
+ # The event loop never runs here: the reply must not wait for it, since in
+ # serving it is busy with the next request's forward.
+ replies = []
+ scheduler = _finalize_scheduler(replies)
+ output = OutputBatch(output=torch.zeros(1))
+
+ def finalize():
+ if fail:
+ raise OSError("disk full")
+
+ item = (b"client", _req())
+ try:
+ scheduler._submit_deferred_reply(
+ item=item, deferred=_DeferredOutput(output_batch=output, finalize=finalize)
+ )
+ scheduler._inflight_finalizes[0].result(timeout=10)
+ finally:
+ scheduler._finalize_executor.shutdown(wait=True)
+
+ assert len(replies) == 1
+ thread_name, replied_item, batch = replies[0]
+ assert thread_name.startswith("sgl-diffusion-finalize")
+ assert replied_item is item and batch is output
+ if fail:
+ assert "disk full" in batch.error
+ assert batch.output is None
+ else:
+ assert batch.error is None
+
+
+def test_reply_send_holds_the_socket_lock():
+ scheduler = Scheduler.__new__(Scheduler)
+ scheduler._socket_lock = threading.Lock()
+ scheduler.server_args = SimpleNamespace(scheduler_endpoint="tcp://10.0.0.1:5555")
+ held = []
+ scheduler.receiver = SimpleNamespace(
+ send_multipart=lambda frames: held.append(scheduler._socket_lock.locked())
+ )
+
+ scheduler.return_result(OutputBatch(), identity=b"client")
+
+ assert held == [True]
+ assert not scheduler._socket_lock.locked()
diff --git a/python/sglang/multimodal_gen/test/unit/test_diffusion_metrics.py b/python/sglang/multimodal_gen/test/unit/test_diffusion_metrics.py
index 9addb21a84..523b3ce945 100644
--- a/python/sglang/multimodal_gen/test/unit/test_diffusion_metrics.py
+++ b/python/sglang/multimodal_gen/test/unit/test_diffusion_metrics.py
@@ -65,6 +65,8 @@ def test_scheduler_counts_original_requests_and_cleans_up(
):
collector, registry = metrics
scheduler = Scheduler.__new__(Scheduler)
+ scheduler._async_output_save = False
+ scheduler._inflight_finalizes = deque()
scheduler.metrics = collector if enabled else None
scheduler._disagg_role = RoleType.MONOLITHIC
scheduler._disagg_metrics = None
diff --git a/python/sglang/multimodal_gen/test/unit/test_perf_dump_write.py b/python/sglang/multimodal_gen/test/unit/test_perf_dump_write.py
index d7b2e62cb5..76b7012ac8 100644
--- a/python/sglang/multimodal_gen/test/unit/test_perf_dump_write.py
+++ b/python/sglang/multimodal_gen/test/unit/test_perf_dump_write.py
@@ -1,11 +1,16 @@
import json
from types import SimpleNamespace
+from unittest.mock import Mock
import pytest
from sglang.multimodal_gen.runtime.managers.gpu_worker import GPUWorker
+from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import OutputBatch
from sglang.multimodal_gen.runtime.utils import perf_logger as perf_logger_module
-from sglang.multimodal_gen.runtime.utils.perf_logger import PerformanceLogger
+from sglang.multimodal_gen.runtime.utils.perf_logger import (
+ PerformanceLogger,
+ RequestMetrics,
+)
def _metrics(request_id: str) -> SimpleNamespace:
@@ -53,3 +58,37 @@ def test_only_the_output_rank_writes_the_report(tmp_path, monkeypatch, is_output
)
assert path.exists() == is_output_rank
+
+
+@pytest.mark.parametrize("is_output_rank", [True, False])
+def test_finalize_preserves_the_output_rank_report_guard(
+ tmp_path, monkeypatch, is_output_rank
+):
+ monkeypatch.setattr(perf_logger_module, "get_git_commit_hash", lambda: "test")
+ worker = GPUWorker.__new__(GPUWorker)
+ worker.is_output_rank = is_output_rank
+ worker.server_args = SimpleNamespace(model_path="model")
+ worker._materialize_output_transport = Mock()
+ worker._record_output_peak_memory = Mock()
+ worker._record_replica_peak_memory = Mock()
+ path = tmp_path / "perf.json"
+ metrics = RequestMetrics("request")
+
+ worker._finalize_output_batch(
+ output_batch=OutputBatch(metrics=metrics),
+ req=SimpleNamespace(
+ request_id="request",
+ perf_dump_path=str(path),
+ is_warmup=False,
+ suppress_logs=True,
+ return_raw_frames=True,
+ ),
+ save_output_paths=Mock(),
+ output_metrics=[metrics],
+ deferred=False,
+ )
+
+ worker._record_replica_peak_memory.assert_called_once_with([metrics])
+ assert path.exists() == is_output_rank
+ if is_output_rank:
+ assert json.loads(path.read_text())["request_id"] == "request"