[feat] Streaming diffusion video generation output (#3737)

Signed-off-by: Huang, Zeyu <11222265+fhfuih@users.noreply.github.com>
Signed-off-by: Zeyu Huang | 黃澤宇 <11222265+fhfuih@users.noreply.github.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
authored and GitHub committed 2026-06-23 09:57:53 +00:00
1 parent b84c99c122
commit 3901ad8165
42 files changed
+4322 -65

No files matched your search

+8
View File
@@ -689,6 +689,9 @@ class OmniDiffusionConfig:
# Step mode settings
step_execution: bool = False
# Streaming mode settings
streaming_output: bool = False # Start (video) generation with initial prompt, but streaming output in chunks
# Maximum number of sequences to generate in a batch
max_num_seqs: int = 1
@@ -1164,6 +1167,11 @@ class DiffusionOutput:
# logged timings info, directly from Req.timings
# timings: Optional["RequestTimings"] = None
# Streaming info (the defaults should make sense for non-streaming mode)
finished: bool = True
chunk_index: int = 0
total_chunks: int = 1
# logged duration of stages
stage_durations: dict[str, float] = field(default_factory=dict)
+169 -13
View File
@@ -9,7 +9,7 @@ import inspect
import queue
import threading
import time
from collections.abc import Iterable
from collections.abc import AsyncGenerator, Iterable
from dataclasses import dataclass, field, replace
from typing import TYPE_CHECKING, Any
@@ -126,9 +126,14 @@ class DiffusionEngine:
self.action_post_process_func, "custom_output"
)
self.step_execution = bool(getattr(od_config, "step_execution", False))
if self.od_config.streaming_output and not self.step_execution:
logger.warning("streaming_output=True requires step_execution=True; enabling step execution.")
self.od_config.step_execution = True
self.step_execution = True
executor_class = DiffusionExecutor.get_class(od_config)
self.executor = executor_class(od_config)
self.step_execution = bool(getattr(od_config, "step_execution", False))
self.scheduler: SchedulerInterface = scheduler or (
StepScheduler() if self.step_execution else RequestScheduler()
)
@@ -149,11 +154,15 @@ class DiffusionEngine:
self._rpc_lock = threading.RLock()
self._cv = threading.Condition(self._rpc_lock)
self._out_queue: dict[str, asyncio.Future] = {}
self._out_queue_streaming: dict[str, asyncio.Queue[DiffusionOutput]] = {}
self._closed = False
self._shutdown_complete = False
self.abort_queue: queue.Queue[str] = queue.Queue()
self._rpc_queue: queue.Queue[_RpcTask] = queue.Queue()
self.execute_fn = self.executor.execute_step if self.step_execution else self.executor.execute_request
if self.step_execution:
self.execute_fn = self.executor.execute_step
else:
self.execute_fn = self.executor.execute_request
try:
self._dummy_run()
@@ -197,7 +206,37 @@ class DiffusionEngine:
exec_start_time = time.perf_counter()
output = await self.async_add_req_and_wait_for_response(request)
exec_total_time = time.perf_counter() - exec_start_time
return self.postprocess_output(request, output, diffusion_engine_start_time, preprocess_time, exec_total_time)
async def step_streaming(self, request: OmniDiffusionRequest) -> AsyncGenerator[list[OmniRequestOutput], None]:
await self._check_and_start_background_loop()
diffusion_engine_start_time = time.perf_counter()
preprocess_time = 0.0
if self.pre_process_func is not None:
preprocess_start_time = time.perf_counter()
request = self.pre_process_func(request)
preprocess_time = time.perf_counter() - preprocess_start_time
logger.debug("Pre-processing completed in %.4f seconds", preprocess_time)
exec_start_time = time.perf_counter()
generator = self.async_add_req_and_stream_response(request)
async for output in generator:
exec_total_time = time.perf_counter() - exec_start_time
yield self.postprocess_output(
request, output, diffusion_engine_start_time, preprocess_time, exec_total_time
)
def postprocess_output(
self,
request: OmniDiffusionRequest,
output: DiffusionOutput,
diffusion_engine_start_time: float,
preprocess_time: float,
exec_total_time: float,
) -> list[OmniRequestOutput]:
"""Convert a DiffusionOutput to a list of OmniRequestOutput, attaching profiling metrics."""
if output.aborted:
raise DiffusionRequestAbortedError(output.abort_message or "Diffusion request aborted.")
if output.error:
@@ -212,7 +251,7 @@ class DiffusionEngine:
if output.output is None:
logger.warning("Output is None, returning empty OmniRequestOutput")
return format_empty_diffusion_outputs(request)
return format_empty_diffusion_outputs(request, finished=output.finished)
# When CPU offload is enabled, move output to CPU before
# post-processing to avoid device OOM — model weights may still
@@ -312,11 +351,14 @@ class DiffusionEngine:
sched_output = self.scheduler.schedule()
if sched_output.is_empty:
self._handle_finished_requests(sched_output.finished_req_ids, None)
if self.od_config.streaming_output:
self._handle_empty_streaming_requests(sched_output.finished_req_ids)
else:
self._handle_finished_requests(sched_output.finished_req_ids, None)
continue
try:
runner_output = self.execute_fn(sched_output)
runner_output: BaseRunnerOutput = self.execute_fn(sched_output) # pyright: ignore[reportAssignmentType]
except Exception as exc:
logger.error(
"Execution failed for diffusion requests %s", sched_output.scheduled_request_ids, exc_info=True
@@ -336,7 +378,14 @@ class DiffusionEngine:
self._process_aborts_queue()
self._process_rpc_queue()
finished_req_ids = self.scheduler.update_from_output(sched_output, runner_output)
self._handle_finished_requests(finished_req_ids, runner_output)
if self.od_config.streaming_output:
self._handle_step_streaming_runner_output(
finished_req_ids,
sched_output.scheduled_request_ids,
runner_output,
)
else:
self._handle_finished_requests(finished_req_ids, runner_output)
# Engine is stopping: fail any RPCs still queued so callers don't hang.
self._fail_pending_rpcs(RuntimeError("DiffusionEngine is shutting down."))
@@ -411,6 +460,57 @@ class DiffusionEngine:
out = self._finalize_finished_request(rid, _output, missing_result_error)
self._complete_future(fut, out)
def _handle_empty_streaming_requests(
self,
finished_ids: set[str],
missing_result_error: str = "Diffusion streaming request finished without execution output.",
) -> None:
"""Mirrors `_handle_finished_requests()` in non-streaming mode when used for empty scheduler output."""
for rid in finished_ids:
out = self._finalize_finished_request(rid, None, missing_result_error=missing_result_error)
self._put_streaming_output_with_cv(rid, out)
def _handle_step_streaming_runner_output(
self,
finished_req_ids: set[str],
scheduled_request_ids: list[str],
runner_output: BaseRunnerOutput,
) -> None:
"""
Deliver partial step-execution outputs in streaming mode.
Step execution returns one ``RunnerOutput`` per scheduled request per
engine tick. Most denoise steps have ``result=None``; chunk boundaries
return a ``DiffusionOutput`` that must be delivered even before the
scheduler marks the request finished.
"""
delivered_finished_req_ids: set[str] = set()
# finished_ids may have some requests that are not scheduler in this round.
# First handle this-round requests.
for request_id in scheduled_request_ids:
req_output = runner_output.get_request_output(request_id)
if request_id in finished_req_ids:
# This entire request is finished (this is the last chunk)
out = self._finalize_finished_request(
request_id,
req_output,
missing_result_error="Diffusion streaming execution finished without a final output.",
)
self._put_streaming_output_with_cv(request_id, out)
delivered_finished_req_ids.add(request_id)
elif req_output is not None and req_output.result is not None:
# This is a non-terminal chunk. So it is not in scheduler's finished_req_ids, but still need delivering.
self._put_streaming_output_with_cv(request_id, req_output.result)
# Then handle other requests that are finished in this round.
for request_id in finished_req_ids - delivered_finished_req_ids:
out = self._finalize_finished_request(
request_id,
missing_result_error="Diffusion streaming request finished without execution output.",
)
self._put_streaming_output_with_cv(request_id, out)
@staticmethod
def make_engine(
config: OmniDiffusionConfig,
@@ -430,9 +530,14 @@ class DiffusionEngine:
with self._cv:
if self._closed:
raise RuntimeError("DiffusionEngine is closed.")
fut = self.main_loop.create_future()
request_id = self.scheduler.add_request(request)
self._out_queue[request_id] = fut
if not self.od_config.streaming_output:
fut = self.main_loop.create_future()
request_id = self.scheduler.add_request(request)
self._out_queue[request_id] = fut
else:
queue: asyncio.Queue[DiffusionOutput] = asyncio.Queue()
request_id = self.scheduler.add_request(request)
self._out_queue_streaming[request_id] = queue
self._cv.notify_all()
return request_id
@@ -448,12 +553,39 @@ class DiffusionEngine:
logger.error(f"Wait for response failed: {e}")
raise
async def get_streaming_result(self, request_id: str) -> AsyncGenerator[DiffusionOutput, None]:
"""Mirrors `get_result()` in non-streaming mode."""
with self._cv:
queue = self._out_queue_streaming.get(request_id)
if queue is None:
raise RuntimeError(f"Request {request_id} not found in output queue.")
try:
while True:
output: DiffusionOutput = await queue.get()
yield output
if output.finished:
break
except Exception as e:
logger.error(f"Wait for response failed: {e}")
raise
finally:
# In streaming mode, an output queue is maintained until the terminal chunk is met.
# So unlike the non-streaming mode where output Future is popped in `_handle_finished_requests` (immediately
# after the request is returned), the streaming mode needs to pop the output queue here (one layer above).
with self._cv:
if self._out_queue_streaming.get(request_id) is queue:
self._out_queue_streaming.pop(request_id, None)
async def async_add_req_and_wait_for_response(self, request: OmniDiffusionRequest) -> DiffusionOutput:
# No lock needed: add_request is already protected by self._cv, and
# all executor calls are serialized inside the busy loop.
request_id = self.add_request(request)
return await self.get_result(request_id)
def async_add_req_and_stream_response(self, request: OmniDiffusionRequest) -> AsyncGenerator[DiffusionOutput, None]:
request_id = self.add_request(request)
return self.get_streaming_result(request_id)
def add_req_and_wait_for_response(self, request: OmniDiffusionRequest) -> DiffusionOutput:
with self._rpc_lock:
if self._closed:
@@ -475,7 +607,7 @@ class DiffusionEngine:
# within _dummy_run, only one request will be scheduled
request_id = sched_output.scheduled_request_ids[0]
try:
runner_output = self.execute_fn(sched_output)
runner_output: BaseRunnerOutput = self.execute_fn(sched_output) # pyright: ignore[reportAssignmentType]
except EngineDeadError:
raise
except Exception as exc:
@@ -495,10 +627,10 @@ class DiffusionEngine:
if not isinstance(runner_output, RunnerOutput) and not len(runner_output) == 1:
raise ValueError("Sync func should receive one result at one time")
if target_request_id in finished_req_ids:
runner_output = runner_output.get_request_output(target_request_id)
req_output = runner_output.get_request_output(target_request_id)
return self._finalize_finished_request(
target_request_id,
runner_output=runner_output,
runner_output=req_output,
missing_result_error="Diffusion execution finished without a final output.",
)
@@ -693,8 +825,28 @@ class DiffusionEngine:
else:
_set_result()
def _put_streaming_queue_output(
self,
queue: asyncio.Queue[DiffusionOutput],
output: DiffusionOutput,
) -> None:
"""Append to streaming output queue in a safe event loop. Mirrors `_complete_future()` in non-streaming mode."""
loop = self.main_loop
if loop is not None and loop.is_running():
loop.call_soon_threadsafe(queue.put_nowait, output)
else:
queue.put_nowait(output)
def _put_streaming_output_with_cv(self, request_id: str, output: DiffusionOutput) -> None:
with self._cv:
queue = self._out_queue_streaming.get(request_id)
if queue is None:
return
self._put_streaming_queue_output(queue, output)
def close(self) -> None:
pending_futures: list[asyncio.Future] = []
pending_streaming_queues: list[asyncio.Queue[DiffusionOutput]] = []
with self._cv:
if self._closed and self._shutdown_complete:
return
@@ -703,12 +855,16 @@ class DiffusionEngine:
if self.stop_event is not None:
self.stop_event.set()
pending_futures = list(self._out_queue.values())
pending_streaming_queues = list(self._out_queue_streaming.values())
self._out_queue.clear()
self._out_queue_streaming.clear()
self._cv.notify_all()
closed_output = DiffusionOutput(error="DiffusionEngine is closed.")
for fut in pending_futures:
self._complete_future(fut, closed_output)
for streaming_queue in pending_streaming_queues:
self._put_streaming_queue_output(streaming_queue, closed_output)
worker_thread = self.worker_thread
if worker_thread is not None:
@@ -134,12 +134,18 @@ class InlineStageDiffusionClient(StageClientBase):
kv_sender_info=kv_sender_info,
)
results = await self._engine.step(request)
result = results[0]
if not result.request_id:
result.request_id = request_id
self._output_queue.put_nowait(result)
if self.od_config.streaming_output:
async for results in self._engine.step_streaming(request):
result = results[0]
if not result.request_id:
result.request_id = request_id
self._output_queue.put_nowait(result)
else:
results = await self._engine.step(request)
result = results[0]
if not result.request_id:
result.request_id = request_id
self._output_queue.put_nowait(result)
except DiffusionRequestAbortedError as e:
logger.info("request_id: %s aborted: %s", request_id, str(e))
except Exception as e:
@@ -8,7 +8,7 @@ import json
import logging
import math
import os
from collections.abc import Iterable
from collections.abc import Iterable, Sequence
from typing import TYPE_CHECKING, Any, ClassVar
import numpy as np
@@ -33,9 +33,10 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.platforms import current_omni_platform
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
)
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm_omni.diffusion.worker.input_batch import InputBatch
from vllm_omni.diffusion.worker.utils import DiffusionRequestState
logger = logging.getLogger(__name__)
@@ -161,6 +162,7 @@ class HeliosPipeline(
Implements chunked video generation with multi-term memory history context.
"""
supports_step_execution: ClassVar[bool] = True
_dit_modules: ClassVar[list[str]] = ["transformer"]
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
_vae_modules: ClassVar[list[str]] = ["vae"]
@@ -267,6 +269,640 @@ class HeliosPipeline(
def current_timestep(self):
return self._current_timestep
def _stage1_sigmas(self, num_steps: int) -> np.ndarray:
# DMD drops the last timestep in set_timesteps(). Only compensate for
# the one-step dummy-run edge case; otherwise preserve the historical
# stage-1 schedule used by request-level forward().
sigma_count = num_steps + 2 if self.is_distilled and num_steps == 1 else num_steps + 1
return np.linspace(0.999, 0.0, sigma_count)[:-1]
def prepare_encode(
self,
state: DiffusionRequestState,
**kwargs: Any,
) -> DiffusionRequestState:
"""Initialize Helios request state for chunk-wise step execution."""
del kwargs
req = OmniDiffusionRequest(
prompts=state.prompts or [],
sampling_params=state.sampling,
request_id=state.request_id,
)
extra = getattr(state.sampling, "extra_args", {}) or {}
history_sizes = sorted(extra.get("history_sizes", [16, 2, 1]), reverse=True)
num_latent_frames_per_chunk = int(extra.get("num_latent_frames_per_chunk", 9))
keep_first_frame = bool(extra.get("keep_first_frame", True))
frame_num = int(extra.get("frame_num", 132))
height = (int(state.sampling.height or extra.get("height", 384)) // 16) * 16
width = (int(state.sampling.width or extra.get("width", 640)) // 16) * 16
num_frames = max(int(state.sampling.num_frames or frame_num), 1)
num_steps = int(state.sampling.num_inference_steps or extra.get("num_inference_steps", 50))
output_type = extra.get("output_type", "np")
image = extra.get("image")
video = extra.get("video")
if image is not None and video is not None:
raise ValueError("image and video cannot be provided simultaneously")
if len(req.prompts) > 1:
raise ValueError("Helios step execution supports a single prompt, not a batched request.")
prompt = None
negative_prompt = None
if len(req.prompts) == 1:
prompt = req.prompts[0] if isinstance(req.prompts[0], str) else req.prompts[0].get("prompt")
negative_prompt = None if isinstance(req.prompts[0], str) else req.prompts[0].get("negative_prompt")
if prompt is None:
raise ValueError("Prompt is required for Helios generation.")
guidance_scale = float(extra.get("guidance_scale", 5.0))
if state.sampling.guidance_scale_provided:
guidance_scale = state.sampling.guidance_scale
self._guidance_scale = guidance_scale
device = self.device
dtype = self.transformer.dtype
generator = state.sampling.generator
if generator is None and state.sampling.seed is not None:
generator = torch.Generator(device=device).manual_seed(state.sampling.seed)
state.sampling.generator = generator
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
prompt=prompt,
negative_prompt=negative_prompt,
do_classifier_free_guidance=self.do_classifier_free_guidance,
num_videos_per_prompt=state.sampling.num_outputs_per_prompt or 1,
max_sequence_length=state.sampling.max_sequence_length or 226,
device=device,
dtype=dtype,
)
batch_size = prompt_embeds.shape[0]
latents_mean = (
torch.tensor(self.vae.config.latents_mean)
.view(1, self.vae.config.z_dim, 1, 1, 1)
.to(self.vae.device, self.vae.dtype)
)
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
self.vae.device, self.vae.dtype
)
add_noise_to_image_latents = bool(extra.get("add_noise_to_image_latents", True))
image_noise_sigma_min = float(extra.get("image_noise_sigma_min", 0.111))
image_noise_sigma_max = float(extra.get("image_noise_sigma_max", 0.135))
add_noise_to_video_latents = bool(extra.get("add_noise_to_video_latents", True))
video_noise_sigma_min = float(extra.get("video_noise_sigma_min", 0.111))
video_noise_sigma_max = float(extra.get("video_noise_sigma_max", 0.135))
fake_image_latents = None
image_latents = None
if image is not None:
image_latents, fake_image_latents = self.prepare_image_latents(
image,
latents_mean=latents_mean,
latents_std=latents_std,
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
dtype=torch.float32,
device=device,
generator=generator,
)
if image_latents is not None and add_noise_to_image_latents:
image_noise_sigma = (
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
+ image_noise_sigma_min
)
image_latents = (
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
+ (1 - image_noise_sigma) * image_latents
)
fake_image_noise_sigma = (
torch.rand(1, device=device, generator=generator) * (video_noise_sigma_max - video_noise_sigma_min)
+ video_noise_sigma_min
)
fake_image_latents = (
fake_image_noise_sigma * randn_tensor(fake_image_latents.shape, generator=generator, device=device)
+ (1 - fake_image_noise_sigma) * fake_image_latents
)
video_latents = None
if video is not None:
image_latents, video_latents = self.prepare_video_latents(
video,
latents_mean=latents_mean,
latents_std=latents_std,
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
dtype=torch.float32,
device=device,
generator=generator,
)
if video_latents is not None and add_noise_to_video_latents:
image_noise_sigma = (
torch.rand(1, device=device, generator=generator) * (image_noise_sigma_max - image_noise_sigma_min)
+ image_noise_sigma_min
)
image_latents = (
image_noise_sigma * randn_tensor(image_latents.shape, generator=generator, device=device)
+ (1 - image_noise_sigma) * image_latents
)
noisy_latents_chunks = []
num_latent_chunks = video_latents.shape[2] // num_latent_frames_per_chunk
for i in range(num_latent_chunks):
chunk_start = i * num_latent_frames_per_chunk
chunk_end = chunk_start + num_latent_frames_per_chunk
latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :]
chunk_frames = latent_chunk.shape[2]
frame_sigmas = (
torch.rand(chunk_frames, device=device, generator=generator)
* (video_noise_sigma_max - video_noise_sigma_min)
+ video_noise_sigma_min
)
frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1)
noisy_chunk = (
frame_sigmas * randn_tensor(latent_chunk.shape, generator=generator, device=device)
+ (1 - frame_sigmas) * latent_chunk
)
noisy_latents_chunks.append(noisy_chunk)
video_latents = torch.cat(noisy_latents_chunks, dim=2)
num_channels_latents = self.transformer.config.in_channels
window_num_frames = (num_latent_frames_per_chunk - 1) * self.vae_scale_factor_temporal + 1
num_latent_chunk = max(1, (num_frames + window_num_frames - 1) // window_num_frames)
num_history_latent_frames = sum(history_sizes)
total_generated_latent_frames = 0
if not keep_first_frame:
history_sizes[-1] = history_sizes[-1] + 1
history_latents = torch.zeros(
batch_size,
num_channels_latents,
num_history_latent_frames,
height // self.vae_scale_factor_spatial,
width // self.vae_scale_factor_spatial,
device=device,
dtype=torch.float32,
)
if fake_image_latents is not None:
history_latents = torch.cat([history_latents[:, :, :-1, :, :], fake_image_latents], dim=2)
total_generated_latent_frames += 1
if video_latents is not None:
history_frames = history_latents.shape[2]
video_frames = video_latents.shape[2]
if video_frames < history_frames:
keep_frames = history_frames - video_frames
history_latents = torch.cat([history_latents[:, :, :keep_frames, :, :], video_latents], dim=2)
else:
history_latents = video_latents
total_generated_latent_frames += video_latents.shape[2]
if keep_first_frame:
indices = torch.arange(0, sum([1, *history_sizes, num_latent_frames_per_chunk]))
(
indices_prefix,
indices_latents_history_long,
indices_latents_history_mid,
indices_latents_history_1x,
indices_hidden_states,
) = indices.split([1, *history_sizes, num_latent_frames_per_chunk], dim=0)
indices_latents_history_short = torch.cat([indices_prefix, indices_latents_history_1x], dim=0)
else:
indices = torch.arange(0, sum([*history_sizes, num_latent_frames_per_chunk]))
(
indices_latents_history_long,
indices_latents_history_mid,
indices_latents_history_short,
indices_hidden_states,
) = indices.split([*history_sizes, num_latent_frames_per_chunk], dim=0)
state.prompt_embeds = prompt_embeds
state.negative_prompt_embeds = negative_prompt_embeds
state.do_true_cfg = self.do_classifier_free_guidance
state.chunk_index = 0
state.step_in_chunk = 0
state.total_chunks = num_latent_chunk
state.extra.update(
{
"attention_kwargs": extra.get("attention_kwargs", {}) or {},
"batch_size": batch_size,
"dtype": dtype,
"generator": generator,
"guidance_scale": guidance_scale,
"height": height,
"history_latents": history_latents,
"history_sizes": history_sizes,
"history_video": None,
"image_latents": image_latents,
"indices_hidden_states": indices_hidden_states.unsqueeze(0),
"indices_latents_history_long": indices_latents_history_long.unsqueeze(0),
"indices_latents_history_mid": indices_latents_history_mid.unsqueeze(0),
"indices_latents_history_short": indices_latents_history_short.unsqueeze(0),
"is_amplify_first_chunk": bool(extra.get("is_amplify_first_chunk", False)),
"is_enable_stage2": bool(extra.get("is_enable_stage2", False)),
"is_skip_first_chunk": bool(extra.get("is_skip_first_chunk", False)),
"keep_first_frame": keep_first_frame,
"latents_mean": latents_mean,
"latents_std": latents_std,
"num_channels_latents": num_channels_latents,
"num_history_latent_frames": num_history_latent_frames,
"num_latent_frames_per_chunk": num_latent_frames_per_chunk,
"num_steps": num_steps,
"output_type": output_type,
"pyramid_num_inference_steps_list": extra.get("pyramid_num_inference_steps_list", [10, 10, 10]),
"pyramid_num_stages": int(extra.get("pyramid_num_stages", 3)),
"total_generated_latent_frames": total_generated_latent_frames,
"use_cfg_zero_star": bool(extra.get("use_cfg_zero_star", False)),
"use_zero_init": bool(extra.get("use_zero_init", True)),
"vae_dtype": self.vae.dtype,
"width": width,
"window_num_frames": window_num_frames,
"zero_steps": int(extra.get("zero_steps", 1)),
}
)
self._prepare_next_chunk(state)
return state
def _prepare_next_chunk(self, state: DiffusionRequestState) -> None:
extra = state.extra
k = state.chunk_index
is_first_chunk = k == 0
is_second_chunk = k == 1
history_sizes = extra["history_sizes"]
history_latents = extra["history_latents"]
keep_first_frame = extra["keep_first_frame"]
image_latents = extra["image_latents"]
num_history_latent_frames = extra["num_history_latent_frames"]
if keep_first_frame:
latents_history_long, latents_history_mid, latents_history_1x = history_latents[
:, :, -num_history_latent_frames:
].split(history_sizes, dim=2)
if image_latents is None and is_first_chunk:
latents_prefix = torch.zeros(
(
extra["batch_size"],
extra["num_channels_latents"],
1,
latents_history_1x.shape[-2],
latents_history_1x.shape[-1],
),
device=latents_history_1x.device,
dtype=latents_history_1x.dtype,
)
else:
latents_prefix = image_latents
latents_history_short = torch.cat([latents_prefix, latents_history_1x], dim=2)
else:
latents_history_long, latents_history_mid, latents_history_short = history_latents[
:, :, -num_history_latent_frames:
].split(history_sizes, dim=2)
state.latents = self.prepare_latents(
extra["batch_size"],
extra["num_channels_latents"],
extra["height"],
extra["width"],
extra["window_num_frames"],
dtype=torch.float32,
device=self.device,
generator=extra["generator"],
latents=None,
)
extra["stage1_start_latents"] = state.latents
extra.update(
{
"is_first_chunk": is_first_chunk,
"is_second_chunk": is_second_chunk,
"latents_history_long": latents_history_long,
"latents_history_mid": latents_history_mid,
"latents_history_short": latents_history_short,
}
)
if not extra["is_enable_stage2"]:
patch_size = self.transformer.config.patch_size
image_seq_len = (state.latents.shape[-1] * state.latents.shape[-2] * state.latents.shape[-3]) // (
patch_size[0] * patch_size[1] * patch_size[2]
)
sigmas = self._stage1_sigmas(extra["num_steps"])
mu = calculate_shift(image_seq_len)
self.scheduler.set_timesteps(extra["num_steps"], device=self.device, sigmas=sigmas, mu=mu)
state.timesteps = self.scheduler.timesteps
state.chunk_num_steps = len(state.timesteps)
else:
self._prepare_stage2_chunk(state)
state.step_in_chunk = 0
state.step_index = 0
self._num_timesteps = state.chunk_num_steps
def _prepare_stage2_chunk(self, state: DiffusionRequestState) -> None:
extra = state.extra
batch_size, num_channel, num_frames_lat, height, width = state.latents.shape
latents_flat = state.latents.permute(0, 2, 1, 3, 4).reshape(
batch_size * num_frames_lat, num_channel, height, width
)
for _ in range(extra["pyramid_num_stages"] - 1):
height //= 2
width //= 2
latents_flat = F.interpolate(latents_flat, size=(height, width), mode="bilinear") * 2
state.latents = latents_flat.reshape(batch_size, num_frames_lat, num_channel, height, width).permute(
0, 2, 1, 3, 4
)
extra["stage2_height"] = height
extra["stage2_width"] = width
extra["stage2_start_point_list"] = [state.latents] if self.is_distilled else None
extra["stage_index"] = 0
extra["stage_step_index"] = 0
amplify_first_chunk = extra["is_amplify_first_chunk"] and extra["is_first_chunk"]
state.chunk_num_steps = sum(
self._stage2_effective_num_steps(int(num_steps), amplify_first_chunk)
for num_steps in extra["pyramid_num_inference_steps_list"]
)
self._set_stage2_timesteps(state)
def _stage2_effective_num_steps(self, num_steps: int, is_amplify_first_chunk: bool) -> int:
if self.is_distilled and is_amplify_first_chunk:
return num_steps * 2
return num_steps
def _set_stage2_timesteps(self, state: DiffusionRequestState) -> None:
extra = state.extra
patch_size = self.transformer.config.patch_size
image_seq_len = (state.latents.shape[-1] * state.latents.shape[-2] * state.latents.shape[-3]) // (
patch_size[0] * patch_size[1] * patch_size[2]
)
mu = calculate_shift(image_seq_len)
stage_index = extra["stage_index"]
self.scheduler.set_timesteps(
extra["pyramid_num_inference_steps_list"][stage_index],
stage_index=stage_index,
device=self.device,
mu=mu,
is_amplify_first_chunk=extra["is_amplify_first_chunk"] and extra["is_first_chunk"],
)
state.timesteps = self.scheduler.timesteps
state.step_index = extra["stage_step_index"]
def denoise_step(
self,
input_batch: InputBatch,
states: Sequence[DiffusionRequestState],
**kwargs: Any,
) -> torch.Tensor | None:
del kwargs
if len(states) != 1:
raise ValueError("Helios step execution supports a single request, not a batched request.")
state = states[0]
if state.extra["is_enable_stage2"]:
return self._denoise_stage2_step(state)
return self._denoise_stage1_step(state, input_batch.latents, input_batch.timesteps)
def _denoise_stage1_step(
self,
state: DiffusionRequestState,
latents: torch.Tensor,
timesteps: torch.Tensor,
) -> torch.Tensor:
extra = state.extra
batch_size = latents.shape[0]
t = timesteps
self._current_timestep = t
timestep = t.expand(batch_size)
transformer_kwargs = {
"hidden_states": latents.to(extra["dtype"]),
"timestep": timestep,
"indices_hidden_states": extra["indices_hidden_states"],
"indices_latents_history_short": extra["indices_latents_history_short"],
"indices_latents_history_mid": extra["indices_latents_history_mid"],
"indices_latents_history_long": extra["indices_latents_history_long"],
"latents_history_short": extra["latents_history_short"].to(extra["dtype"]),
"latents_history_mid": extra["latents_history_mid"].to(extra["dtype"]),
"latents_history_long": extra["latents_history_long"].to(extra["dtype"]),
"attention_kwargs": extra["attention_kwargs"],
"return_dict": False,
}
if extra["use_cfg_zero_star"] and state.do_true_cfg:
noise_pred = self.transformer(
encoder_hidden_states=state.prompt_embeds,
**transformer_kwargs,
)[0]
noise_uncond = self.transformer(
encoder_hidden_states=state.negative_prompt_embeds,
**transformer_kwargs,
)[0]
positive_flat = noise_pred.view(batch_size, -1)
negative_flat = noise_uncond.view(batch_size, -1)
alpha_cfg = optimized_scale(positive_flat, negative_flat)
alpha_cfg = alpha_cfg.view(batch_size, *([1] * (len(noise_pred.shape) - 1))).to(noise_pred.dtype)
if (state.step_in_chunk <= extra["zero_steps"]) and extra["use_zero_init"]:
return noise_pred * 0.0
return noise_uncond * alpha_cfg + extra["guidance_scale"] * (noise_pred - noise_uncond * alpha_cfg)
positive_kwargs = {
"encoder_hidden_states": state.prompt_embeds,
**transformer_kwargs,
}
negative_kwargs = (
{
"encoder_hidden_states": state.negative_prompt_embeds,
**transformer_kwargs,
}
if state.do_true_cfg
else None
)
return self.predict_noise_maybe_with_cfg(
do_true_cfg=state.do_true_cfg,
true_cfg_scale=extra["guidance_scale"],
positive_kwargs=positive_kwargs,
negative_kwargs=negative_kwargs,
cfg_normalize=False,
)
def _denoise_stage2_step(self, state: DiffusionRequestState) -> torch.Tensor:
extra = state.extra
latents = state.latents
assert latents is not None
batch_size = latents.shape[0]
t = state.current_timestep
assert t is not None
self._current_timestep = t
timestep = t.expand(batch_size).to(torch.int64)
transformer_kwargs = {
"hidden_states": latents.to(extra["dtype"]),
"timestep": timestep,
"indices_hidden_states": extra["indices_hidden_states"],
"indices_latents_history_short": extra["indices_latents_history_short"],
"indices_latents_history_mid": extra["indices_latents_history_mid"],
"indices_latents_history_long": extra["indices_latents_history_long"],
"latents_history_short": extra["latents_history_short"].to(extra["dtype"]),
"latents_history_mid": extra["latents_history_mid"].to(extra["dtype"]),
"latents_history_long": extra["latents_history_long"].to(extra["dtype"]),
"attention_kwargs": extra["attention_kwargs"],
"return_dict": False,
}
noise_pred = self.transformer(encoder_hidden_states=state.prompt_embeds, **transformer_kwargs)[0]
if state.do_true_cfg:
noise_uncond = self.transformer(encoder_hidden_states=state.negative_prompt_embeds, **transformer_kwargs)[0]
if extra["use_cfg_zero_star"]:
positive_flat = noise_pred.view(batch_size, -1)
negative_flat = noise_uncond.view(batch_size, -1)
alpha_cfg = optimized_scale(positive_flat, negative_flat)
alpha_cfg = alpha_cfg.view(batch_size, *([1] * (len(noise_pred.shape) - 1))).to(noise_pred.dtype)
if (
extra["stage_index"] == 0
and extra["stage_step_index"] <= extra["zero_steps"]
and extra["use_zero_init"]
):
noise_pred = noise_pred * 0.0
else:
noise_pred = noise_uncond * alpha_cfg + extra["guidance_scale"] * (
noise_pred - noise_uncond * alpha_cfg
)
else:
noise_pred = noise_uncond + extra["guidance_scale"] * (noise_pred - noise_uncond)
return noise_pred
def step_scheduler(
self,
state: DiffusionRequestState,
noise_pred: torch.Tensor,
**kwargs: Any,
) -> None:
del kwargs
if state.extra["is_enable_stage2"]:
self._step_scheduler_stage2(state, noise_pred)
else:
t = state.current_timestep
assert t is not None
if self.is_distilled:
state.latents = self.scheduler.step(
noise_pred,
t,
state.latents,
return_dict=False,
cur_sampling_step=state.step_in_chunk,
dmd_noisy_tensor=state.extra["stage1_start_latents"],
dmd_sigmas=self.scheduler.sigmas,
dmd_timesteps=self.scheduler.timesteps,
all_timesteps=state.timesteps,
)[0]
else:
state.latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, state.latents, state.do_true_cfg)
state.step_in_chunk += 1
state.step_index = state.step_in_chunk
def _step_scheduler_stage2(self, state: DiffusionRequestState, noise_pred: torch.Tensor) -> None:
extra = state.extra
t = state.current_timestep
assert t is not None and state.latents is not None
start_points = extra["stage2_start_point_list"]
state.latents = self.scheduler.step(
noise_pred,
t,
state.latents,
return_dict=False,
cur_sampling_step=extra["stage_step_index"],
dmd_noisy_tensor=start_points[extra["stage_index"]] if start_points is not None else None,
dmd_sigmas=self.scheduler.sigmas,
dmd_timesteps=self.scheduler.timesteps,
all_timesteps=state.timesteps,
)[0]
extra["stage_step_index"] += 1
state.step_in_chunk += 1
state.step_index = extra["stage_step_index"]
if extra["stage_step_index"] < len(state.timesteps):
return
if extra["stage_index"] >= extra["pyramid_num_stages"] - 1:
return
extra["stage_index"] += 1
extra["stage_step_index"] = 0
extra["stage2_height"] *= 2
extra["stage2_width"] *= 2
batch_size, num_channel, num_frames_cur = state.latents.shape[:3]
latents_flat = state.latents.permute(0, 2, 1, 3, 4).reshape(
batch_size * num_frames_cur,
num_channel,
extra["stage2_height"] // 2,
extra["stage2_width"] // 2,
)
latents_flat = F.interpolate(latents_flat, size=(extra["stage2_height"], extra["stage2_width"]), mode="nearest")
state.latents = latents_flat.reshape(
batch_size,
num_frames_cur,
num_channel,
extra["stage2_height"],
extra["stage2_width"],
).permute(0, 2, 1, 3, 4)
ori_sigma = 1 - self.scheduler.ori_start_sigmas[extra["stage_index"]]
gamma = self.scheduler.config.gamma
alpha = 1 / (math.sqrt(1 + (1 / gamma)) * (1 - ori_sigma) + ori_sigma)
beta = alpha * (1 - ori_sigma) / math.sqrt(gamma)
patch_size = self.transformer.config.patch_size
noise = self.sample_block_noise(
batch_size,
num_channel,
state.latents.shape[2],
extra["stage2_height"],
extra["stage2_width"],
patch_size,
generator=extra["generator"],
).to(device=self.device, dtype=extra["dtype"])
state.latents = alpha * state.latents + beta * noise
if self.is_distilled and extra["stage2_start_point_list"] is not None:
extra["stage2_start_point_list"].append(state.latents)
self._set_stage2_timesteps(state)
def post_decode(
self,
state: DiffusionRequestState,
**kwargs: Any,
) -> DiffusionOutput:
del kwargs
extra = state.extra
is_first_chunk = extra["is_first_chunk"]
is_second_chunk = extra["is_second_chunk"]
if extra["keep_first_frame"] and (
(is_first_chunk and extra["image_latents"] is None) or (extra["is_skip_first_chunk"] and is_second_chunk)
):
extra["image_latents"] = state.latents[:, :, 0:1, :, :]
extra["total_generated_latent_frames"] += state.latents.shape[2]
extra["history_latents"] = torch.cat([extra["history_latents"], state.latents], dim=2)
real_history_latents = extra["history_latents"][:, :, -extra["total_generated_latent_frames"] :]
current_latents = (
real_history_latents[:, :, -extra["num_latent_frames_per_chunk"] :].to(extra["vae_dtype"])
/ extra["latents_std"]
+ extra["latents_mean"]
)
current_video = self.vae.decode(current_latents, return_dict=False)[0]
if extra["history_video"] is None:
extra["history_video"] = current_video
else:
extra["history_video"] = torch.cat([extra["history_video"], current_video], dim=2)
output = current_latents if extra["output_type"] == "latent" else current_video
completed_chunk_index = state.chunk_index
state.chunk_index += 1
finished = state.request_denoise_completed
if not finished:
self._prepare_next_chunk(state)
else:
self._current_timestep = None
if current_omni_platform.is_available():
current_omni_platform.empty_cache()
return DiffusionOutput(
output=output,
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else {},
chunk_index=completed_chunk_index,
total_chunks=state.total_chunks,
finished=finished,
)
def forward(
self,
req: OmniDiffusionRequest,
+5 -1
View File
@@ -56,15 +56,19 @@ class SupportsStepExecution(Protocol):
def prepare_encode(self, state: DiffusionRequestState, **kwargs: Any) -> DiffusionRequestState:
"""Prepare request-level inputs and return initialized state."""
...
def denoise_step(self, input_batch: InputBatch, **kwargs: Any) -> torch.Tensor | None:
"""Run one denoise forward on the runner-assembled batch."""
...
def step_scheduler(self, state: DiffusionRequestState, noise_pred: torch.Tensor, **kwargs: Any) -> None:
"""Run one scheduler step."""
...
def post_decode(self, state: DiffusionRequestState, **kwargs: Any) -> DiffusionOutput:
"""Decode output after denoise loop."""
"""Decode output after denoise loop or at a partial chunk boundary."""
...
@runtime_checkable
+15 -1
View File
@@ -70,7 +70,11 @@ def normalize_diffusion_postprocess_output(
)
def format_empty_diffusion_outputs(request: OmniDiffusionRequest) -> list[OmniRequestOutput]:
def format_empty_diffusion_outputs(
request: OmniDiffusionRequest,
*,
finished: bool = True,
) -> list[OmniRequestOutput]:
return [
OmniRequestOutput.from_diffusion(
request_id=request.request_id,
@@ -78,6 +82,7 @@ def format_empty_diffusion_outputs(request: OmniDiffusionRequest) -> list[OmniRe
prompt=prompt,
metrics={},
latents=None,
finished=finished,
)
for prompt in request.prompts
]
@@ -125,6 +130,7 @@ def format_diffusion_outputs(
is_text_output=is_text_output,
is_audio_output=is_audio_output,
audio_sample_rate=audio_sample_rate,
finished=diffusion_output.finished,
)
return _format_multi_prompt_outputs(
@@ -135,6 +141,7 @@ def format_diffusion_outputs(
postprocess_output=postprocess_output,
is_audio_output=is_audio_output,
audio_sample_rate=audio_sample_rate,
finished=diffusion_output.finished,
)
@@ -185,6 +192,7 @@ def _format_single_prompt_output(
is_text_output: bool,
is_audio_output: bool,
audio_sample_rate: int | None,
finished: bool = True,
) -> list[OmniRequestOutput]:
prompt = request.prompts[0]
request_id = request.request_id
@@ -202,6 +210,7 @@ def _format_single_prompt_output(
final_output_type="text",
stage_durations=diffusion_output.stage_durations,
peak_memory_mb=diffusion_output.peak_memory_mb,
finished=finished,
),
]
@@ -227,6 +236,7 @@ def _format_single_prompt_output(
final_output_type="audio",
stage_durations=diffusion_output.stage_durations,
peak_memory_mb=diffusion_output.peak_memory_mb,
finished=finished,
),
]
@@ -245,6 +255,7 @@ def _format_single_prompt_output(
multimodal_output=mm_output,
stage_durations=diffusion_output.stage_durations,
peak_memory_mb=diffusion_output.peak_memory_mb,
finished=finished,
),
]
@@ -258,6 +269,7 @@ def _format_multi_prompt_outputs(
postprocess_output: DiffusionPostprocessOutput,
is_audio_output: bool,
audio_sample_rate: int | None,
finished: bool = True,
) -> list[OmniRequestOutput]:
results = []
output_idx = 0
@@ -298,6 +310,7 @@ def _format_multi_prompt_outputs(
final_output_type="audio",
stage_durations=diffusion_output.stage_durations,
peak_memory_mb=diffusion_output.peak_memory_mb,
finished=finished,
),
)
continue
@@ -337,6 +350,7 @@ def _format_multi_prompt_outputs(
multimodal_output=mm_output,
stage_durations=diffusion_output.stage_durations,
peak_memory_mb=diffusion_output.peak_memory_mb,
finished=finished,
),
)
@@ -81,7 +81,9 @@ class DiffusionPipelineProfilerMixin:
_PROFILER_TARGETS = ["vae.encode", "vae.decode", "diffuse", "text_encoder.forward", "tokenizer.forward"]
def setup_diffusion_pipeline_profiler(
self, profiler_targets: list[str] | None = None, enable_diffusion_pipeline_profiler: bool = False
self,
profiler_targets: list[str] | None = None,
enable_diffusion_pipeline_profiler: bool = False,
) -> None:
self.enable_diffusion_pipeline_profiler = enable_diffusion_pipeline_profiler
if not enable_diffusion_pipeline_profiler:
+43 -7
View File
@@ -10,6 +10,7 @@ import asyncio
import contextlib
import multiprocessing.connection
import signal
from collections.abc import AsyncGenerator
from concurrent.futures import ThreadPoolExecutor
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
@@ -172,6 +173,29 @@ class StageDiffusionProc:
result.request_id = request_id
return result
async def _process_streaming_request(
self,
request_id: str,
prompt: Any,
sampling_params_dict: dict,
kv_sender_info: dict[str, Any] | None = None,
) -> AsyncGenerator[OmniRequestOutput, None]:
"""Process a streaming diffusion request and yield the results from DiffusionEngine.step_streaming()."""
sampling_params = self._reconstruct_sampling_params(sampling_params_dict)
request = OmniDiffusionRequest(
prompts=[prompt],
sampling_params=sampling_params,
request_id=request_id,
kv_sender_info=kv_sender_info,
)
async for results in self._engine.step_streaming(request): # pyright: ignore[reportOptionalMemberAccess]
result = results[0]
if not result.request_id:
result.request_id = request_id
yield result
async def _process_batch_request(
self,
request_id: str,
@@ -186,6 +210,9 @@ class StageDiffusionProc:
``images`` list contains every generated image, matching the
contract expected by the orchestrator and tests.
"""
if self._od_config.streaming_output:
raise NotImplementedError("Streaming output is not supported for batched requests")
sampling_params = self._reconstruct_sampling_params(sampling_params_dict)
request = OmniDiffusionRequest(
@@ -388,13 +415,22 @@ class StageDiffusionProc:
) -> None:
"""Process a single diffusion request and send the response."""
try:
result = await self._process_request(
request_id,
prompt,
sampling_params_dict,
kv_sender_info=kv_sender_info,
)
await response_socket.send(encoder.encode({"type": "result", "output": result}))
if not self._od_config.streaming_output:
result = await self._process_request(
request_id,
prompt,
sampling_params_dict,
kv_sender_info=kv_sender_info,
)
await response_socket.send(encoder.encode({"type": "result", "output": result}))
else:
async for result in self._process_streaming_request(
request_id,
prompt,
sampling_params_dict,
kv_sender_info=kv_sender_info,
):
await response_socket.send(encoder.encode({"type": "result", "output": result}))
except DiffusionRequestAbortedError as e:
logger.info(
"request_id: %s aborted: %s",
+121 -4
View File
@@ -6,11 +6,124 @@ from __future__ import annotations
import io
from fractions import Fraction
from typing import Any, cast
import av
import numpy as np
class FragmentedMP4Muxer:
"""Incrementally mux video frames into one fragmented MP4 byte stream."""
def __init__(
self,
*,
width: int,
height: int,
fps: float = 25.0,
video_codec: str = "h264",
crf: str = "18",
video_codec_options: dict[str, str] | None = None,
) -> None:
self._buf = io.BytesIO()
self._closed = False
self._container = av.open(
self._buf,
mode="w",
format="mp4",
options={"movflags": "+frag_every_frame+empty_moov+default_base_moof"},
)
self._stream: av.VideoStream = cast(
av.VideoStream,
self._container.add_stream(video_codec, rate=Fraction(fps).limit_denominator(10000)),
)
self._stream.width = width
self._stream.height = height
self._stream.pix_fmt = "yuv420p"
options: dict[str, object] = {"crf": str(crf)}
if video_codec_options:
options.update(video_codec_options)
self._stream.options = options
try:
self._stream.codec_context.max_b_frames = 0
except AttributeError:
pass
def mux_video_frames(self, video_frames: np.ndarray) -> bytes:
"""Mux a batch of ``uint8`` RGB frames and return newly written MP4 bytes."""
if self._closed:
raise RuntimeError("Cannot mux frames after FragmentedMP4Muxer.close().")
if video_frames.ndim != 4 or video_frames.shape[-1] != 3:
raise ValueError("video_frames must have shape (T, H, W, 3).")
if video_frames.dtype != np.uint8:
raise ValueError("video_frames must be uint8.")
if video_frames.shape[1] != self._stream.height or video_frames.shape[2] != self._stream.width:
raise ValueError("All fragmented MP4 chunks in a session must use the same frame size.")
for frame_data in video_frames:
frame = av.VideoFrame.from_ndarray(frame_data, format="rgb24")
for packet in self._stream.encode(frame):
self._container.mux(packet)
return self._read_new_bytes()
def close(self) -> bytes:
"""Flush delayed encoder packets, close the container, and return final bytes."""
if self._closed:
return b""
for packet in self._stream.encode():
self._container.mux(packet)
self._container.close()
self._closed = True
return self._read_new_bytes()
def _read_new_bytes(self) -> bytes:
"""Return newly muxed bytes in the current video container,
then clear the buffer to prepare for the next chunk."""
chunk = self._buf.getvalue()
self._buf.seek(0)
self._buf.truncate()
return chunk
def finalize_streaming_video_bytes(
video_bytes: bytes,
*,
input_format: str,
fps: float = 25.0,
video_codec_options: dict[str, str] | None = None,
) -> bytes:
"""Convert streamed video bytes into a progressive MP4 for local playback."""
if not video_bytes:
return video_bytes
normalized_format = input_format.lower()
if normalized_format == "m4s":
demux_format = "mp4"
else:
raise ValueError(f"Unsupported streaming video format: {input_format}")
try:
with cast(Any, av.open(io.BytesIO(video_bytes), format=demux_format)) as container:
stream = container.streams.video[0]
frame_arrays = [frame.to_ndarray(format="rgb24") for frame in container.decode(stream)]
except Exception:
return video_bytes
if not frame_arrays:
return video_bytes
frames_u8 = np.ascontiguousarray(np.stack(frame_arrays, axis=0), dtype=np.uint8)
return mux_video_audio_bytes(
frames_u8,
None,
fps=float(fps),
video_codec_options=video_codec_options,
)
def mux_video_audio_bytes(
video_frames: np.ndarray,
audio_waveform: np.ndarray | None = None,
@@ -39,17 +152,19 @@ def mux_video_audio_bytes(
buf = io.BytesIO()
container = av.open(buf, mode="w", format="mp4")
v_stream = container.add_stream(video_codec, rate=Fraction(fps).limit_denominator(10000))
v_stream = cast(av.VideoStream, container.add_stream(video_codec, rate=Fraction(fps).limit_denominator(10000)))
v_stream.width = video_frames.shape[2]
v_stream.height = video_frames.shape[1]
v_stream.pix_fmt = "yuv420p"
options = {"crf": str(crf)}
options: dict[str, object] = {"crf": str(crf)}
if video_codec_options:
options.update(video_codec_options)
v_stream.options = options
a_stream = None
a_stream: av.AudioStream | None = None
samples: np.ndarray | None = None
layout: str | None = None
if audio_waveform is not None:
samples = audio_waveform.astype(np.float32)
if samples.ndim == 1:
@@ -58,7 +173,7 @@ def mux_video_audio_bytes(
samples = np.ascontiguousarray(samples.T)
num_channels = samples.shape[0]
layout = "stereo" if num_channels >= 2 else "mono"
a_stream = container.add_stream(audio_codec, rate=audio_sample_rate)
a_stream = cast(av.AudioStream, container.add_stream(audio_codec, rate=audio_sample_rate))
a_stream.layout = layout
for frame_data in video_frames:
@@ -69,6 +184,8 @@ def mux_video_audio_bytes(
container.mux(packet)
if a_stream is not None and audio_waveform is not None:
if samples is None or layout is None:
raise ValueError("Audio samples were not prepared for muxing.")
audio_frame = av.AudioFrame.from_ndarray(samples, format="fltp", layout=layout)
audio_frame.sample_rate = audio_sample_rate
for packet in a_stream.encode(audio_frame):
@@ -152,12 +152,21 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
)
logger.info("Model runner: Model loaded successfully.")
if self.od_config.streaming_output and not getattr(self.od_config, "step_execution", False):
logger.warning("streaming_output=True requires step_execution=True; enabling step execution.")
self.od_config.step_execution = True
if getattr(self.od_config, "step_execution", False) and not self.supports_step_mode():
raise ValueError(
"step_execution=True requires a pipeline implementing "
"prepare_encode(), denoise_step(), step_scheduler(), and post_decode(); "
f"{self.od_config.model_class_name} does not support that contract."
)
if self.od_config.streaming_output and not self.supports_step_mode():
raise ValueError(
"streaming_output=True requires step execution support; "
f"{self.od_config.model_class_name} does not support that contract."
)
# Apply CPU offloading
self.offload_backend = get_offload_backend(self.od_config, device=self.device)
@@ -357,7 +366,6 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
and self.od_config.enable_cache_dit_summary
):
cache_summary(self.pipeline, details=True)
return output
# ------------------------------------------------------------------
@@ -457,7 +465,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
scatter_latents(states, input_batch)
for state in states:
if interrupted or state.denoise_completed:
if interrupted or state.request_denoise_completed:
self.state_cache.pop(state.request_id, None)
def _prepare_attn_metadata(self, input_batch: InputBatch) -> Any:
@@ -492,7 +500,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
omni_diffusion_config=self.od_config,
attn_metadata=attn_metadata,
):
noise_pred = self.pipeline.denoise_step(input_batch)
noise_pred = self.pipeline.denoise_step(input_batch, states=states)
runner_output_list = []
pipeline_interrupted = getattr(self.pipeline, "interrupt", False)
@@ -515,15 +523,24 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
req, noise_pred[offset : offset + row_num] if noise_pred is not None else None
)
offset = offset + row_num
if req.denoise_completed:
if self.od_config.streaming_output:
should_decode = req.chunk_denoise_completed
else:
should_decode = req.denoise_completed
if should_decode:
result = self.pipeline.post_decode(req)
else:
result = None
# finished should be computed after post_decode() advanced chunk_index
finished = (
req.request_denoise_completed if self.od_config.streaming_output else req.denoise_completed
)
runner_output_list.append(
RunnerOutput(
request_id=req.request_id,
step_index=req.step_index,
finished=req.denoise_completed,
finished=finished,
result=result,
)
)
+18
View File
@@ -55,6 +55,12 @@ class DiffusionRequestState:
timesteps: torch.Tensor | list[torch.Tensor] | None = None
step_index: int = 0
# ── Optional chunked streaming progress ──
chunk_index: int = 0
step_in_chunk: int = 0
total_chunks: int = 1
chunk_num_steps: int | None = None
# ── Per-request scheduler instance (set once by prepare_encode) ──
scheduler: Any | None = None
@@ -103,6 +109,18 @@ class DiffusionRequestState:
return False
return self.step_index >= total_steps
@property
def chunk_denoise_completed(self) -> bool:
if self.chunk_num_steps is None:
return False
return self.step_in_chunk >= self.chunk_num_steps
@property
def request_denoise_completed(self) -> bool:
if self.chunk_num_steps is None:
return self.denoise_completed
return self.chunk_index >= self.total_chunks
@property
def new_request(self) -> bool:
# TODO: this is only an approximation for current stepwise mode.