Enable Diffusion Image models asynchronous output (#4981)
Signed-off-by: zzh <943967662@qq.com> Co-authored-by: dengyunyang <584797741@qq.com>
This commit is contained in:
1 parent
f2d9eb1630
commit
dba05c3517
22 files changed
+1440
-72
No files matched your search
+59
-24
@@ -21,23 +21,43 @@ _SHM_TENSOR_THRESHOLD = 1_000_000 # 1 MB
|
||||
DIFFUSION_RPC_RESULT_ENVELOPE = "diffusion_rpc_result"
|
||||
|
||||
|
||||
def _tensor_to_shm(tensor: torch.Tensor) -> dict[str, Any]:
|
||||
def _tensor_to_shm(
|
||||
tensor: torch.Tensor,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Copy a tensor into POSIX shared memory and return a metadata handle.
|
||||
|
||||
The shared memory segment remains alive after this call (the local fd is
|
||||
closed, but the segment persists until ``_tensor_from_shm`` unlinks it).
|
||||
|
||||
If *d2h_stream* is provided, the D2H copy uses ``copy_()`` with
|
||||
``pin_memory=True`` on that stream instead of the synchronous ``.cpu()``
|
||||
path. The caller must synchronize *d2h_stream* after all tensors are
|
||||
packed.
|
||||
"""
|
||||
from multiprocessing import shared_memory
|
||||
|
||||
import numpy as np
|
||||
|
||||
tensor = tensor.detach().cpu().contiguous()
|
||||
original_dtype = tensor.dtype
|
||||
# NumPy does not support bfloat16; promote to float32 for the SHM
|
||||
# transfer and record the original dtype so _tensor_from_shm can
|
||||
# convert back. The round-trip is lossless for bfloat16 values.
|
||||
if original_dtype == torch.bfloat16:
|
||||
tensor = tensor.to(torch.float32)
|
||||
if d2h_stream is not None:
|
||||
# Non-blocking D2H: copy on side stream to pinned CPU memory.
|
||||
old_stream = torch.accelerator.current_stream()
|
||||
torch.accelerator.set_stream(d2h_stream)
|
||||
try:
|
||||
t = tensor.detach()
|
||||
if original_dtype == torch.bfloat16:
|
||||
t = t.to(torch.float32)
|
||||
cpu = torch.empty(t.shape, dtype=t.dtype, pin_memory=True)
|
||||
cpu.copy_(t, non_blocking=True)
|
||||
finally:
|
||||
torch.accelerator.set_stream(old_stream)
|
||||
d2h_stream.synchronize()
|
||||
tensor = cpu
|
||||
else:
|
||||
tensor = tensor.detach().cpu().contiguous()
|
||||
if original_dtype == torch.bfloat16:
|
||||
tensor = tensor.to(torch.float32)
|
||||
arr = tensor.numpy()
|
||||
nbytes = arr.nbytes
|
||||
shm = shared_memory.SharedMemory(create=True, size=nbytes)
|
||||
@@ -79,14 +99,20 @@ def _tensor_from_shm(handle: dict[str, Any]) -> torch.Tensor:
|
||||
return tensor
|
||||
|
||||
|
||||
def _pack_tensor_if_large(val: torch.Tensor) -> torch.Tensor | dict:
|
||||
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:
|
||||
return _tensor_to_shm(val)
|
||||
return _tensor_to_shm(val, d2h_stream=d2h_stream)
|
||||
return val
|
||||
|
||||
|
||||
def _pack_value_if_large(val: object) -> object:
|
||||
def _pack_value_if_large(
|
||||
val: object,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
) -> object:
|
||||
"""Recursively replace large tensors with SHM handles.
|
||||
|
||||
Walks the container shapes pipelines return as ``DiffusionOutput.output``:
|
||||
@@ -96,13 +122,13 @@ def _pack_value_if_large(val: object) -> object:
|
||||
the two in sync.
|
||||
"""
|
||||
if isinstance(val, torch.Tensor):
|
||||
return _pack_tensor_if_large(val)
|
||||
return _pack_tensor_if_large(val, d2h_stream=d2h_stream)
|
||||
if isinstance(val, dict):
|
||||
return {key: _pack_value_if_large(value) for key, value in val.items()}
|
||||
return {key: _pack_value_if_large(value, d2h_stream=d2h_stream) for key, value in val.items()}
|
||||
if isinstance(val, list):
|
||||
return [_pack_value_if_large(item) for item in val]
|
||||
return [_pack_value_if_large(item, d2h_stream=d2h_stream) for item in val]
|
||||
if isinstance(val, tuple):
|
||||
return tuple(_pack_value_if_large(item) for item in val)
|
||||
return tuple(_pack_value_if_large(item, d2h_stream=d2h_stream) for item in val)
|
||||
return val
|
||||
|
||||
|
||||
@@ -119,15 +145,18 @@ def _unpack_if_shm_handle(val: object) -> object:
|
||||
return val
|
||||
|
||||
|
||||
def _pack_diffusion_fields(output: DiffusionOutput) -> DiffusionOutput:
|
||||
def _pack_diffusion_fields(
|
||||
output: DiffusionOutput,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
) -> DiffusionOutput:
|
||||
if output.output is not None:
|
||||
output.output = _pack_value_if_large(output.output)
|
||||
output.output = _pack_value_if_large(output.output, d2h_stream=d2h_stream)
|
||||
if output.trajectory_latents is not None and isinstance(output.trajectory_latents, torch.Tensor):
|
||||
output.trajectory_latents = _pack_tensor_if_large(output.trajectory_latents)
|
||||
output.trajectory_latents = _pack_tensor_if_large(output.trajectory_latents, d2h_stream=d2h_stream)
|
||||
if output.trajectory_timesteps is not None and isinstance(output.trajectory_timesteps, torch.Tensor):
|
||||
output.trajectory_timesteps = _pack_tensor_if_large(output.trajectory_timesteps)
|
||||
output.trajectory_timesteps = _pack_tensor_if_large(output.trajectory_timesteps, d2h_stream=d2h_stream)
|
||||
if output.trajectory_log_probs is not None and isinstance(output.trajectory_log_probs, torch.Tensor):
|
||||
output.trajectory_log_probs = _pack_tensor_if_large(output.trajectory_log_probs)
|
||||
output.trajectory_log_probs = _pack_tensor_if_large(output.trajectory_log_probs, d2h_stream=d2h_stream)
|
||||
return output
|
||||
|
||||
|
||||
@@ -135,31 +164,37 @@ def _is_rpc_result_envelope(output: object) -> bool:
|
||||
return isinstance(output, dict) and output.get("type") == DIFFUSION_RPC_RESULT_ENVELOPE
|
||||
|
||||
|
||||
def pack_diffusion_output_shm(output: object) -> object:
|
||||
def pack_diffusion_output_shm(
|
||||
output: object,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
) -> object:
|
||||
"""Replace large tensors in diffusion worker outputs with SHM handles.
|
||||
|
||||
Supports a bare ``DiffusionOutput``, a wrapper object carrying one in
|
||||
``.result`` (for example ``RunnerOutput``), an RPC result envelope carrying
|
||||
the diffusion output in ``["result"]``, or a batch wrapper carrying
|
||||
``RunnerOutput`` objects in ``.runner_outputs``.
|
||||
|
||||
If *d2h_stream* is provided, D2H copies use that stream (non-blocking on
|
||||
the default stream). The caller must synchronize *d2h_stream* afterward.
|
||||
"""
|
||||
if isinstance(output, DiffusionOutput):
|
||||
return _pack_diffusion_fields(output)
|
||||
return _pack_diffusion_fields(output, d2h_stream=d2h_stream)
|
||||
|
||||
if _is_rpc_result_envelope(output):
|
||||
result = output.get("result")
|
||||
if isinstance(result, DiffusionOutput):
|
||||
output["result"] = _pack_diffusion_fields(result)
|
||||
output["result"] = _pack_diffusion_fields(result, d2h_stream=d2h_stream)
|
||||
return output
|
||||
|
||||
result = getattr(output, "result", None)
|
||||
if isinstance(result, DiffusionOutput):
|
||||
output.result = _pack_diffusion_fields(result)
|
||||
output.result = _pack_diffusion_fields(result, d2h_stream=d2h_stream)
|
||||
|
||||
runner_outputs = getattr(output, "runner_outputs", None)
|
||||
if isinstance(runner_outputs, list):
|
||||
for runner_output in runner_outputs:
|
||||
pack_diffusion_output_shm(runner_output)
|
||||
pack_diffusion_output_shm(runner_output, d2h_stream=d2h_stream)
|
||||
return output
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user