Merge remote-tracking branch 'origin/main' into qwen-image-2.1

# Conflicts:
#	tests/entrypoints/openai_api/test_image_server.py
#	vllm_omni/entrypoints/openai/api_server.py
This commit is contained in:
Isotr0py committed 2026-09-22 01:23:45 +00:00
commit 3e274a0024
220 files changed
+22342 -1079

No files matched your search

+82 -26
View File
@@ -228,9 +228,10 @@ class DiffusionEngine:
#: remains a pure explicit user override (never mutated by engines).
default_diffusion_model_runner_cls: str | None = None
# Class-level default so tests using object.__new__ (without __init__)
# don't hit AttributeError when _busy_loop accesses self.dp_concurrent.
# Class-level defaults so tests using object.__new__ (without __init__)
# don't hit AttributeError when _busy_loop accesses them.
dp_concurrent: bool = False
_scheduling_paused: bool = False
def __init__(
self,
@@ -387,6 +388,8 @@ class DiffusionEngine:
self._shutdown_complete = False
self.abort_queue: queue.Queue[str] = queue.Queue()
self._rpc_queue: queue.Queue[_RpcTask] = queue.Queue()
# pause_scheduler(mode="keep"): no new batch is scheduled while set.
self._scheduling_paused = False
# Copied onto the existing output metrics payload so queue monitoring
# reuses the normal diffusion result path without additional IPC.
self._scheduler_num_waiting_reqs = 0
@@ -584,10 +587,16 @@ class DiffusionEngine:
while not self.stop_event.is_set():
self._process_aborts_queue()
self._process_rpc_queue()
if self._scheduling_paused:
# No wave runs while paused, so requests finished by an abort
# would otherwise wait for the resume to surface.
with self._cv:
pending_finished = self.scheduler.pending_finished_request_ids()
self._emit_finished_outputs(pending_finished, None)
with self._cv:
while (
not self.scheduler.has_requests()
(self._scheduling_paused or not self.scheduler.has_requests())
and self._rpc_queue.empty()
and self.abort_queue.empty()
and not self.stop_event.is_set()
@@ -597,11 +606,14 @@ class DiffusionEngine:
if self.stop_event.is_set():
break
if not self.scheduler.has_requests():
if self._scheduling_paused or not self.scheduler.has_requests():
# Only RPC / abort work pending; loop back to drain it.
continue
self._wait_for_admission_if_needed_locked()
if self._scheduling_paused:
# The gate closed while the batching wait released the lock.
continue
try:
sched_output = self.scheduler.schedule()
@@ -693,7 +705,7 @@ class DiffusionEngine:
last_waiting = -1
stable_since = start
while not self.stop_event.is_set():
while not self.stop_event.is_set() and not self._scheduling_paused:
waiting = self.scheduler.num_waiting_requests()
now = time.monotonic()
@@ -733,19 +745,34 @@ class DiffusionEngine:
except queue.Empty:
return
fut = task.future
if fut.cancelled() or fut.done():
continue
self._run_rpc_task(task)
remaining: float | None = None
if task.deadline is not None:
remaining = task.deadline - time.monotonic()
if remaining <= 0:
if not fut.done():
fut.set_exception(TimeoutError(f"RPC call to {task.method} timed out before execution."))
continue
if task.method == "pause_scheduler":
# A dequeued pause ends this drain whatever became of it, so
# the batch that just ran is delivered before anything the
# caller queued behind the pause. The rest of the queue is
# picked up on the next pass of the busy loop.
return
try:
def _run_rpc_task(self, task: _RpcTask) -> None:
fut = task.future
if fut.cancelled() or fut.done():
return
remaining: float | None = None
if task.deadline is not None:
remaining = task.deadline - time.monotonic()
if remaining <= 0:
if not fut.done():
fut.set_exception(TimeoutError(f"RPC call to {task.method} timed out before execution."))
return
try:
if task.method == "pause_scheduler":
result = self._run_pause_barrier(remaining)
elif task.method == "resume_scheduler":
result = self._open_scheduling_gate()
else:
result = self.executor.collective_rpc(
method=task.method,
timeout=remaining,
@@ -753,16 +780,16 @@ class DiffusionEngine:
kwargs=task.kwargs,
unique_reply_rank=task.unique_reply_rank,
)
except BaseException as exc: # noqa: BLE001 - propagate to caller
# The future may have been cancelled (e.g. by a sync timeout
# or asyncio cancellation) while the executor call was
# running. Setting state on a cancelled/done future raises
# InvalidStateError, which would kill the busy loop.
if not fut.done():
fut.set_exception(exc)
else:
if not fut.done():
fut.set_result(result)
except BaseException as exc: # noqa: BLE001 - propagate to caller
# The future may have been cancelled (e.g. by a sync timeout
# or asyncio cancellation) while the executor call was
# running. Setting state on a cancelled/done future raises
# InvalidStateError, which would kill the busy loop.
if not fut.done():
fut.set_exception(exc)
else:
if not fut.done():
fut.set_result(result)
def _fail_pending_rpcs(self, exc: BaseException) -> None:
while True:
@@ -773,6 +800,30 @@ class DiffusionEngine:
if not task.future.done():
task.future.set_exception(exc)
def _check_pause_request(self, kwargs: dict | None) -> None:
mode = (kwargs or {}).get("mode")
if mode != "keep":
raise ValueError(f"DiffusionEngine pause supports mode='keep' only, got {mode!r}.")
if self.execution_mode != DiffusionExecutionMode.REQUEST_BATCH:
raise NotImplementedError("DiffusionEngine pause supports request-level execution only.")
def _run_pause_barrier(self, timeout: float | None) -> None:
"""Return once every worker has finished the device work of the batch that ran."""
self.executor.collective_rpc("synchronize_device", timeout=timeout, kwargs={"timeout": timeout})
def _open_scheduling_gate(self) -> None:
with self._cv:
self._scheduling_paused = False
self._cv.notify_all()
def _run_engine_control(self, method: str, timeout: float | None, kwargs: dict | None) -> None:
"""Bootstrap-path dispatch for engine-local control methods."""
if method == "pause_scheduler":
self._check_pause_request(kwargs)
self._scheduling_paused = True
return self._run_pause_barrier(timeout)
return self._open_scheduling_gate()
def _remove_diffusion_kv_requests(self, request_ids: Iterable[str]) -> None:
"""Clear terminal Worker rows while Scheduler owns the allocations."""
@@ -1309,6 +1360,9 @@ class DiffusionEngine:
unique_reply_rank=unique_reply_rank,
)
with self._cv:
if method == "pause_scheduler":
self._check_pause_request(kwargs)
self._scheduling_paused = True
self._rpc_queue.put(task)
self._cv.notify_all()
return task
@@ -1351,6 +1405,8 @@ class DiffusionEngine:
# between the outer check and acquiring the lock, in which
# case we should use the queued path for proper ordering.
if not self._loop_started:
if method in ("pause_scheduler", "resume_scheduler"):
return self._run_engine_control(method, timeout, kwargs)
return self.executor.collective_rpc(
method=method,
timeout=timeout,
@@ -781,22 +781,34 @@ def _decoder_upsample_count(decoder: nn.Module) -> int:
return count
def install_wan_spatial_shard_decode(vae: Any, group: dist.ProcessGroup, split_dim: str = "height") -> None:
def install_wan_spatial_shard_decode(
vae: Any,
group: dist.ProcessGroup,
split_dim: str = "height",
*,
dst: int | None = 0,
) -> None:
"""Patch ``vae.decoder`` once for spatially-sharded decode.
This mutates the already-loaded decoder in place by swapping its spatial
convolutions/padding for halo-exchanging variants and wrapping
``decoder.forward``. The patch is permanent for the lifetime of the VAE
instance and is applied only once (subsequent calls are no-ops). A given
instance is bound to a single ``split_dim``; switching between
``"height"`` and ``"width"`` requires a fresh VAE instance and raises here
otherwise.
instance is bound to a single ``split_dim`` and ``dst``; switching either
requires a fresh VAE instance and raises here otherwise.
Only group-relative rank 0 assembles the final decoded frame, mirroring the
distributed tiled-decode ``broadcast_result=False`` contract; the other ranks
take part in the collectives but return an empty placeholder.
With ``dst=0`` (the default) only group-relative rank 0 assembles the
final decoded frame, mirroring the distributed tiled-decode
``broadcast_result=False`` contract; the other ranks take part in the
collectives but return an empty placeholder. ``dst=None`` lets every rank
keep the assembled frame, for a caller whose every rank goes on to
consume the decoded pixels; the gather is an all-gather either way, so
this costs no extra communication.
"""
_spatial_dim(split_dim)
_, world_size = _rank_world(group)
if dst is not None and (not isinstance(dst, int) or not 0 <= dst < world_size):
raise ValueError(f"Wan spatial-shard dst must be None or an integer in [0, {world_size}), got {dst!r}.")
if getattr(vae, "_vllm_omni_wan_spatial_shard_installed", False):
installed_split_dim = getattr(vae, "_vllm_omni_wan_spatial_shard_split_dim", "height")
if installed_split_dim != split_dim:
@@ -804,6 +816,12 @@ def install_wan_spatial_shard_decode(vae: Any, group: dist.ProcessGroup, split_d
"Wan spatial-shard VAE decoder was already patched for "
f"{installed_split_dim!r} split; create a fresh VAE instance to use {split_dim!r} split."
)
installed_dst = getattr(vae, "_vllm_omni_wan_spatial_shard_dst", 0)
if installed_dst != dst:
raise ValueError(
"Wan spatial-shard VAE decoder was already patched to assemble on "
f"{installed_dst!r}; create a fresh VAE instance to assemble on {dst!r}."
)
return
decoder = getattr(vae, "decoder", None)
if decoder is None:
@@ -844,11 +862,12 @@ def install_wan_spatial_shard_decode(vae: Any, group: dist.ProcessGroup, split_d
out = orig_forward(x, feat_cache=feat_cache, feat_idx=feat_idx, first_chunk=first_chunk)
finally:
_SPATIAL_SHARD_CONTEXT.reset(token)
return gather_and_trim_extent(out, expected_extent=expected_extent, split_dim=split_dim, group=group, dst=0)
return gather_and_trim_extent(out, expected_extent=expected_extent, split_dim=split_dim, group=group, dst=dst)
decoder.forward = MethodType(_forward, decoder)
vae._vllm_omni_wan_spatial_shard_installed = True
vae._vllm_omni_wan_spatial_shard_split_dim = split_dim
vae._vllm_omni_wan_spatial_shard_dst = dst
logger.info("Installed Wan VAE %s-sharded decode.", split_dim)
@@ -24,18 +24,6 @@ def _launch_row_chunks(kernel, rows: int, device_type: str, *args, **kwargs) ->
kernel[(chunk_rows,)](*args, row_offset, **kwargs)
def _use_hopper_bf16_affine_semantics(x: torch.Tensor) -> bool:
"""Use the unfused AdaLN dtype boundaries on Hopper.
The fused FP32 modulation path is stable on Blackwell, but the SM90
kernel can accumulate enough extra precision in the repeated RMSNorm and
AdaLN operations to move the 50-step I2VA result below its CI threshold.
Keep the existing path on other architectures until their numerical
baselines are independently validated.
"""
return x.device.type == "cuda" and torch.cuda.get_device_capability(x.device)[0] == 9
@triton.jit
def _indexed_scale_shift_kernel(
output_ptr,
@@ -114,7 +102,6 @@ def _rms_norm_indexed_scale_shift_kernel(
stride_scale_row,
stride_indices,
row_offset,
use_bf16_affine: tl.constexpr,
block_n: tl.constexpr,
):
row = tl.program_id(0) + row_offset
@@ -125,17 +112,13 @@ def _rms_norm_indexed_scale_shift_kernel(
x = tl.load(x_ptr + row * stride_x_row + columns, mask=mask, other=0.0).to(tl.float32)
weight = tl.load(weight_ptr + columns, mask=mask, other=0.0).to(tl.float32)
variance = tl.sum(x * x, axis=0) / hidden_size
if use_bf16_affine:
# Match the unfused RMSNorm output consumed by AdaLN on Hopper.
normalized = (x * tl.rsqrt(variance + eps) * weight).to(tl.bfloat16)
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0)
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0)
output = normalized * (scale + 1.0) + shift
else:
normalized = x * tl.rsqrt(variance + eps) * weight
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
output = normalized * (1.0 + scale) + shift
# Keep RMSNorm and AdaLN intermediates in FP32 on every architecture.
# Rounding the normalized value to BF16 before the affine transform
# changes the fused computation, including values at rounding boundaries.
normalized = x * tl.rsqrt(variance + eps) * weight
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
output = normalized * (1.0 + scale) + shift
tl.store(
output_ptr + row * hidden_size + columns,
output,
@@ -163,7 +146,6 @@ def _indexed_gate_rms_norm_scale_shift_kernel(
stride_scale_row,
stride_indices,
row_offset,
use_bf16_affine: tl.constexpr,
block_n: tl.constexpr,
):
row = tl.program_id(0) + row_offset
@@ -180,17 +162,10 @@ def _indexed_gate_rms_norm_scale_shift_kernel(
weight = tl.load(weight_ptr + columns, mask=mask, other=0.0).to(tl.float32)
variance = tl.sum(updated * updated, axis=0) / hidden_size
if use_bf16_affine:
# Match the unfused RMSNorm output consumed by AdaLN on Hopper.
normalized = (updated * tl.rsqrt(variance + eps) * weight).to(tl.bfloat16)
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0)
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0)
output = normalized * (scale + 1.0) + shift
else:
normalized = updated * tl.rsqrt(variance + eps) * weight
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
output = normalized * (1.0 + scale) + shift
normalized = updated * tl.rsqrt(variance + eps) * weight
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
output = normalized * (1.0 + scale) + shift
tl.store(
modulated_out_ptr + row * hidden_size + columns,
output,
@@ -300,7 +275,6 @@ def rms_norm_indexed_scale_shift(
shift.stride(0),
scale.stride(0),
indices.stride(0),
use_bf16_affine=_use_hopper_bf16_affine_semantics(x),
block_n=triton.next_power_of_2(hidden_size),
num_warps=8,
)
@@ -354,7 +328,6 @@ def indexed_gate_rms_norm_scale_shift(
shift.stride(0),
scale.stride(0),
indices.stride(0),
use_bf16_affine=_use_hopper_bf16_affine_semantics(residual),
block_n=triton.next_power_of_2(hidden_size),
num_warps=8,
)
@@ -25,7 +25,6 @@ from vllm.model_executor.model_loader.weight_utils import (
pt_weights_iterator,
safetensors_weights_iterator,
)
from vllm.transformers_utils.repo_utils import hf_api
from vllm.utils.import_utils import resolve_obj_by_qualname
from vllm.utils.torch_utils import set_default_torch_dtype
@@ -54,6 +53,7 @@ from vllm_omni.diffusion.offloader.module_collector import ModuleDiscovery
from vllm_omni.diffusion.offloader.offload_plan import get_offload_plan
from vllm_omni.diffusion.registry import initialize_model
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from vllm_omni.transformers_utils.repo_utils import hf_api
# download_gguf was removed from upstream vLLM (commit 6635279d8).
@@ -35,6 +35,7 @@ from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
from vllm_omni.errors import OmniClientError
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
from .autoencoder import AutoEncoder, AutoEncoderParams, DistributedAutoEncoder
@@ -184,6 +185,45 @@ def _bagel_effective_image_size(
return min(resized_height, max_image_size), min(resized_width, max_image_size)
def _bagel_canvas_requested(sampling: OmniDiffusionSamplingParams) -> bool:
return (sampling.height is not None and not sampling.height_not_provided) or (
sampling.width is not None and not sampling.width_not_provided
)
def _bagel_align_requested_canvas(
sampling: OmniDiffusionSamplingParams,
*,
latent_downsample: int,
max_latent_size: int,
) -> None:
"""Floor an explicitly requested canvas to the latent stride; reject sides over the checkpoint limit."""
max_image_size = int(max_latent_size * latent_downsample)
resized: list[str] = []
for name in ("width", "height"):
value = getattr(sampling, name)
if value is None or getattr(sampling, f"{name}_not_provided"):
continue
value = int(value)
if value > max_image_size:
raise OmniClientError(
f"Requested {name}={value} exceeds the BAGEL checkpoint limit of {max_image_size} "
f"(max_latent_size={max_latent_size}, latent_downsample={latent_downsample})."
)
aligned = max(latent_downsample, (value // latent_downsample) * latent_downsample)
if aligned != value:
setattr(sampling, name, aligned)
resized.append(f"{name} {value}->{aligned}")
if resized:
logger.warning(
"BAGEL: requested canvas is not a multiple of the latent stride %d and cannot be "
"generated as-is; resizing %s.",
latent_downsample,
", ".join(resized),
)
def get_bagel_pre_process_func(od_config: OmniDiffusionConfig):
"""Resolve BAGEL execution mode and step-batch compatibility."""
@@ -194,12 +234,23 @@ def get_bagel_pre_process_func(od_config: OmniDiffusionConfig):
nonlocal image_geometry
sampling = request.sampling_params
modalities = (request.prompt.get("modalities") or []) if isinstance(request.prompt, dict) else []
kv_metadata = getattr(sampling, "kv_metadata", None) or {}
image_shape = kv_metadata.get("image_shape")
if image_shape is not None:
if _bagel_canvas_requested(sampling) and "text" not in modalities:
if image_geometry is None:
image_geometry = _resolve_bagel_image_geometry(od_config)
latent_downsample, max_latent_size = image_geometry
_bagel_align_requested_canvas(
sampling,
latent_downsample=latent_downsample,
max_latent_size=max_latent_size,
)
elif image_shape is not None:
sampling.height, sampling.width = (int(value) for value in image_shape)
sampling.height_not_provided = False
sampling.width_not_provided = False
elif isinstance(request.prompt, dict):
modalities = request.prompt.get("modalities") or []
multi_modal_data = request.prompt.get("multi_modal_data") or {}
image_input = multi_modal_data.get("img2img")
if image_input is None and "text" not in modalities:
@@ -220,6 +271,8 @@ def get_bagel_pre_process_func(od_config: OmniDiffusionConfig):
latent_downsample=latent_downsample,
max_latent_size=max_latent_size,
)
sampling.height_not_provided = True
sampling.width_not_provided = True
extra_args = request.sampling_params.extra_args or {}
cfg_interval = tuple(extra_args.get("cfg_interval", (0.4, 1.0)))
@@ -528,6 +581,7 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
f"latent_downsample={self.bagel.latent_downsample})."
)
image_shape = (height, width)
image_shape_requested = _bagel_canvas_requested(sampling)
extra_args = getattr(sampling, "extra_args", {}) or {}
cfg_text_scale = extra_args.get("cfg_text_scale", 4.0)
@@ -568,7 +622,15 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
gen_context["ropes"] = [seq_len]
if sampling.kv_metadata and "image_shape" in sampling.kv_metadata:
image_shape = tuple(sampling.kv_metadata["image_shape"])
if not image_shape_requested:
image_shape = tuple(sampling.kv_metadata["image_shape"])
elif tuple(sampling.kv_metadata["image_shape"]) != image_shape:
logger.info(
"Generating at requested %dx%d instead of KV image shape %s",
image_shape[1],
image_shape[0],
sampling.kv_metadata["image_shape"],
)
branch_kvs = getattr(sampling, "cfg_branch_past_key_values", None) or {}
branch_metadata = getattr(sampling, "cfg_branch_kv_metadata", None) or {}
@@ -673,8 +735,15 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
image_input = [_resize_to_stride(img) for img in image_input]
resized_w, resized_h = image_input[0].size
image_shape = (resized_h, resized_w)
logger.info(f"img2img: resized image to {resized_w}x{resized_h}")
if not image_shape_requested:
image_shape = (resized_h, resized_w)
logger.info(
"img2img: resized source to %dx%d, generating at %dx%d",
resized_w,
resized_h,
image_shape[1],
image_shape[0],
)
def vae_transforms(img):
if img.mode != "RGB":
@@ -7,9 +7,10 @@ over every block, stepwise execution calls ``probe_step`` / ``apply_transition``
one denoise step at a time and ``commit_block_kv`` from ``post_decode`` -- so the
math lives here once and cannot drift between the two modes.
A block is four probes that must not touch KV, then one clean-x0 commit that
does. Whether a call sees paged (session-bound) or request-local KV is decided
by the ``ar`` argument, so this class never reaches back into the pipeline.
By default a block is four probes followed by one clean-x0 KV commit.
The experimental last-step reuse mode instead commits the fourth noisy probe.
Whether a call sees paged (session-bound) or request-local KV is decided by
the ``ar`` argument, so this class never reaches back into the pipeline.
"""
from __future__ import annotations
@@ -19,6 +20,7 @@ from typing import TYPE_CHECKING, Any, cast
import torch
from diffusers.utils.torch_utils import randn_tensor
from vllm.logger import init_logger
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.models.lingbot_world.transformer import (
@@ -33,6 +35,9 @@ if TYPE_CHECKING:
from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVState
logger = init_logger(__name__)
@dataclass(frozen=True)
class ARBlockContext:
"""The bound AR-Diffusion session one block runs against.
@@ -55,10 +60,14 @@ class LingBotDMDBlockRunner:
*,
device: torch.device,
enforce_eager: bool,
reuse_last_step_kv: bool = False,
) -> None:
self.transformer = transformer
self.device = device
self.enforce_eager = enforce_eager
# Experimental approximation: cache x_t/t_last features instead of x0/t=0.
self.reuse_last_step_kv = reuse_last_step_kv
logger.info("LingBot experimental last-step KV reuse: %s", self.reuse_last_step_kv)
# ── cache selection ──────────────────────────────────────────────────
@@ -114,8 +123,8 @@ class LingBotDMDBlockRunner:
) -> torch.Tensor:
"""Predict flow for one denoise step.
A probe never writes KV: only the clean x0 of a finished block may
enter the cache, which is ``commit_block_kv``'s job.
Normally only clean x0 enters KV. The experimental reuse mode commits
the final noisy probe instead; the fixed DMD schedule has four probes.
``camera_cache`` is the block's camera-modulation cache when the caller
holds it across separate calls (the stepwise path); ``generate_block``
@@ -128,14 +137,15 @@ class LingBotDMDBlockRunner:
# Checkpoint channel contract:
# [noise/x_t(16), temporal_mask(4), image_latent(16)] -> 36.
model_input = torch.cat((current_latents.to(dtype=condition.dtype), condition), dim=1)
commit_probe = self.reuse_last_step_kv and step_index == 3
flow_prediction = self.transformer(
hidden_states=model_input,
timestep=timestep,
encoder_hidden_states=prompt_embeds,
camera_hidden_states=camera,
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=False),
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=commit_probe),
start_frame=start_frame,
update_cache=False,
update_cache=commit_probe,
camera_modulation_cache=camera_cache,
)
if flow_prediction.shape != current_latents.shape:
@@ -183,10 +193,15 @@ class LingBotDMDBlockRunner:
) -> None:
"""Write the finished block's clean x0 into KV and commit its pages.
The fifth transformer call of a block, deliberately not a denoise step:
on the stepwise path it belongs to ``post_decode()``. ``camera_cache``
is as in ``probe_step``.
By default this is the fifth transformer call, at t=0. Experimental
reuse only finalizes the pages written by the fourth probe. On the
stepwise path both modes finalize from ``post_decode()``.
``camera_cache`` is as in ``probe_step``.
"""
if self.reuse_last_step_kv:
if ar is not None:
ar.state.commit_paged_context(ar.branch)
return
# Commit K/V only for the final clean block, never for noisy probes.
cache_input = torch.cat((latents.to(dtype=condition.dtype), condition), dim=1)
if not self.enforce_eager:
@@ -26,6 +26,7 @@ from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
from vllm_omni.diffusion.distributed.autoencoders.wan_spatial_shard import install_wan_spatial_shard_decode
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.interaction.mixin import InteractionMixin
from vllm_omni.diffusion.interaction.modality_handlers.camera import CameraSession
@@ -92,6 +93,10 @@ logger = init_logger(__name__)
# measured to hold.
_STREAMING_DECODE_BYTES_PER_PIXEL_FP32 = 37832 * 1024 / (64 * 64)
# The frame dimension the decoder is sharded along when the pipeline runs on
# more than one Ulysses rank; see ``_install_sharded_vae_decode``.
_VAE_SHARD_SPLIT_DIM = "width"
if TYPE_CHECKING:
from tqdm.std import tqdm as TqdmProgressBar
@@ -236,8 +241,6 @@ def _validate_scheduler_config(config: dict[str, Any]) -> None:
def _validate_parallel_config(od_config: OmniDiffusionConfig) -> None:
if getattr(od_config, "quantization_config", None) is not None:
raise NotImplementedError("LingBot World v1 does not support quantization.")
parallel_config = getattr(od_config, "parallel_config", None)
if parallel_config is None:
return
@@ -580,7 +583,13 @@ class LingBotWorldCausalDMDPipeline(
super().__init__()
del prefix
_validate_parallel_config(od_config)
parallel_config = getattr(od_config, "parallel_config", None)
self.od_config = od_config
model_config = getattr(od_config, "model_config", None) or {}
reuse_last_step_kv = model_config.get("lingbot_reuse_last_step_kv", False)
if not isinstance(reuse_last_step_kv, bool):
raise ValueError("model_config.lingbot_reuse_last_step_kv must be a bool.")
self._reuse_last_step_kv = reuse_last_step_kv
self.device = get_local_device()
dtype = getattr(od_config, "dtype", torch.bfloat16)
model = od_config.model
@@ -666,7 +675,6 @@ class LingBotWorldCausalDMDPipeline(
self.vae_scale_factor_temporal = int(getattr(self.vae.config, "scale_factor_temporal", 4))
self.vae_scale_factor_spatial = int(getattr(self.vae.config, "scale_factor_spatial", 8))
model_config = getattr(od_config, "model_config", None) or {}
self._ar_height = int(model_config.get("ar_diffusion_height", 480))
self._ar_width = int(model_config.get("ar_diffusion_width", 832))
self._ar_diffusion_kv_state: ARDiffusionKVState | None = None
@@ -679,6 +687,14 @@ class LingBotWorldCausalDMDPipeline(
self._streaming_decode_states: dict[str, StreamingDecodeState] = {}
self._cached_streaming_decoder: WanStreamingDecoder | None = None
self._streaming_decode_unsupported = False
self._vae_shard_split_dim: str | None = None
self._vae_shard_world_size = 1
vae_sharding = model_config.get("lingbot_vae_spatial_sharding", True)
if not isinstance(vae_sharding, bool):
raise ValueError("lingbot_vae_spatial_sharding must be a boolean.")
sequence_parallel_size = int(getattr(parallel_config, "sequence_parallel_size", 1) or 1)
if sequence_parallel_size > 1 and vae_sharding:
self._install_sharded_vae_decode(sequence_parallel_size)
self.setup_diffusion_pipeline_profiler(
profiler_targets=[
"vae.encode",
@@ -799,9 +815,24 @@ class LingBotWorldCausalDMDPipeline(
decoder = self._streaming_decoder()
if decoder is None:
return 0
height, width = self._ar_height, self._ar_width
if self._vae_shard_split_dim is not None:
# The decoder pads the latent extent to a multiple of the group
# size before splitting. Account for that padding on every rank,
# including ranks whose final pixels are trimmed after gathering.
scale = self.vae_scale_factor_spatial
extent = width if self._vae_shard_split_dim == "width" else height
latent_extent = (extent + scale - 1) // scale
local_extent = (latent_extent + self._vae_shard_world_size - 1) // self._vae_shard_world_size
if self._vae_shard_split_dim == "width":
width = local_extent * scale
else:
height = local_extent * scale
# Temporal caches retain local inputs, before spatial halo exchange.
# Halo receive buffers belong to the decoder, not to each session.
return decoder.declared_state_bytes(
height=self._ar_height,
width=self._ar_width,
height=height,
width=width,
dtype=self.vae.dtype,
)
@@ -1337,6 +1368,7 @@ class LingBotWorldCausalDMDPipeline(
self.transformer,
device=self.device,
enforce_eager=bool(self.od_config.enforce_eager),
reuse_last_step_kv=self._reuse_last_step_kv,
)
self._dmd_block_runner = runner
return runner
@@ -1654,6 +1686,51 @@ class LingBotWorldCausalDMDPipeline(
tile_latent_min_width = int(getattr(self.vae, "tile_sample_min_width", None) or 0) // compression
return bool(latents.shape[-2] > tile_latent_min_height or latents.shape[-1] > tile_latent_min_width)
def _vae_shard_group(self) -> tuple[Any, int]:
"""The Ulysses ranks the decoder is sharded across, and how many there are."""
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
group = get_sp_group().device_group
return group, torch.distributed.get_world_size(group=group)
def _install_sharded_vae_decode(self, sequence_parallel_size: int) -> None:
"""Shard the Wan decoder across the Ulysses ranks along the width.
The DiT runs on ``sequence_parallel_size`` ranks, and the decode of
one AR block used to run on every one of them in full: each rank
decoded the whole frame so that its own ``post_decode`` could carry
on. Splitting the frame across those same ranks with halo exchange at
the convolution borders makes each decode a quarter of the work at
four ranks; every rank still ends the block with the assembled frame
because the gather is an all-gather, so nothing downstream changes.
The streaming decoder is unaffected: ``feat_cache``, ``feat_idx`` and
``first_chunk`` pass straight through to the patched decoder, and the
per-session temporal cache shrinks by the same factor.
This is the default for multi-rank deployments; setting
``model_config.lingbot_vae_spatial_sharding=False`` keeps full-frame
decode on each rank without changing DiT parallelism.
``vae_patch_parallel_size`` stays rejected because it would make the
registry set up the tiled distributed executor and force
tiling on a decoder that is already sharded. Width rather than height
because at 480x832 it is the longer side, so each rank keeps a
208-pixel shard against the same halo, and it is the split this was
measured on: 269.9 -> 98.7 ms per block on 4xH200. Numerically it is
not bit-exact against a single-rank decode: the halo-exchanged
convolutions accumulate in a different order at the shard borders
(max abs diff 0.0195 on [-1, 1] at 480x832).
"""
group, world_size = self._vae_shard_group()
if world_size != sequence_parallel_size:
raise RuntimeError(
f"LingBot World sequence_parallel_size={sequence_parallel_size} but the Ulysses group has "
f"{world_size} ranks."
)
install_wan_spatial_shard_decode(self.vae, group, split_dim=_VAE_SHARD_SPLIT_DIM, dst=None)
self._vae_shard_split_dim = _VAE_SHARD_SPLIT_DIM
self._vae_shard_world_size = world_size
logger.info("LingBot World VAE decode sharded along %s across %d ranks.", _VAE_SHARD_SPLIT_DIM, world_size)
def _streaming_decoder(self) -> WanStreamingDecoder | None:
"""The session-owned streaming decoder, or ``None`` on a VAE that cannot stream.
@@ -8,7 +8,7 @@ import math
from collections.abc import Iterable
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Any, Self, cast
from typing import TYPE_CHECKING, Any, Self, cast
import torch
import torch.nn as nn
@@ -36,6 +36,9 @@ from vllm_omni.experimental.ar_diffusion.kv_cache.paged_attention import (
paged_write_attn,
)
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
@dataclass
class LingBotAttentionCache:
@@ -170,6 +173,7 @@ class LingBotSelfAttention(nn.Module):
num_heads: int,
*,
eps: float = 1e-6,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> None:
super().__init__()
@@ -188,6 +192,7 @@ class LingBotSelfAttention(nn.Module):
head_size=self.head_dim,
total_num_heads=num_heads,
bias=True,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "qkv"),
)
self.num_local_heads = self.qkv.num_heads
@@ -205,6 +210,7 @@ class LingBotSelfAttention(nn.Module):
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "o"),
)
self.norm_q = _LingBotRMSNorm(self.tp_inner_dim, eps)
@@ -416,6 +422,7 @@ class LingBotCrossAttention(nn.Module):
num_heads: int,
*,
eps: float = 1e-6,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> None:
super().__init__()
@@ -443,6 +450,7 @@ class LingBotCrossAttention(nn.Module):
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "q"),
)
self.k = ColumnParallelLinear(
@@ -451,6 +459,7 @@ class LingBotCrossAttention(nn.Module):
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "k"),
)
self.v = ColumnParallelLinear(
@@ -459,6 +468,7 @@ class LingBotCrossAttention(nn.Module):
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "v"),
)
self.o = RowParallelLinear(
@@ -467,6 +477,7 @@ class LingBotCrossAttention(nn.Module):
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "o"),
)
self.norm_q = _LingBotRMSNorm(self.tp_inner_dim, eps)
@@ -528,6 +539,7 @@ class LingBotAttentionBlock(nn.Module):
ffn_dim: int | None = None,
cross_attn_norm: bool = True,
eps: float = 1e-6,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> None:
super().__init__()
@@ -538,12 +550,14 @@ class LingBotAttentionBlock(nn.Module):
dim,
num_heads,
eps=eps,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "self_attn"),
)
self.cross_attn = LingBotCrossAttention(
dim,
num_heads,
eps=eps,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "cross_attn"),
)
self.norm2 = LayerNorm(dim, eps=eps, elementwise_affine=False)
@@ -555,6 +569,7 @@ class LingBotAttentionBlock(nn.Module):
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "ffn.0"),
),
nn.GELU(approximate="tanh"),
@@ -564,6 +579,7 @@ class LingBotAttentionBlock(nn.Module):
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "ffn.2"),
),
)
@@ -574,6 +590,7 @@ class LingBotAttentionBlock(nn.Module):
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "cam_injector_layer1"),
)
self.cam_injector_layer2 = RowParallelLinear(
@@ -582,6 +599,7 @@ class LingBotAttentionBlock(nn.Module):
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "cam_injector_layer2"),
)
self.cam_scale_layer = nn.Linear(dim, dim)
@@ -823,7 +841,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
num_frames_per_block: int = 3,
sliding_window_num_frames: int = 18,
local_attn_size: int = -1,
quant_config: object | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> None:
super().__init__()
@@ -853,11 +871,6 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
):
if field_value is not None:
raise ValueError(f"{field_name} must be None because LingBot World v2 has no image embedding path.")
if quant_config is not None:
raise RuntimeError(
"quant_config is not supported by the LingBot World transformer; construct the unquantized model."
)
dim = num_attention_heads * attention_head_dim
self.dim = dim
self.config = SimpleNamespace(
@@ -898,6 +911,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
bias=True,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "c2ws_hidden_states_layer1"),
)
self.c2ws_hidden_states_layer2 = RowParallelLinear(
@@ -906,6 +920,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
bias=True,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=_projection_prefix(prefix, "c2ws_hidden_states_layer2"),
)
self.text_embedding = nn.Sequential(
@@ -930,6 +945,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
ffn_dim=ffn_dim,
cross_attn_norm=cross_attn_norm,
eps=eps,
quant_config=quant_config,
prefix=_projection_prefix(prefix, f"blocks.{index}"),
)
for index in range(num_layers)
@@ -976,7 +992,7 @@ class CausalLingBotWorldTransformer3DModel(nn.Module):
cls,
config: dict[str, Any],
*,
quant_config: Any | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> Self:
checkpoint_contract = {
@@ -225,7 +225,7 @@ def _resolve_checkpoint_root(model: str, revision: str | None) -> str:
"MAGI-2 expects a local checkpoint directory or the official "
f"model ID {MAGI2_MODEL_ID!r}; got {model!r}."
)
from vllm.transformers_utils.repo_utils import hf_api
from vllm_omni.transformers_utils.repo_utils import hf_api
pinned_revision = revision or MAGI2_MODEL_REVISION
logger.warning(
+10 -5
View File
@@ -31,6 +31,7 @@ from vllm_omni.diffusion.offloader.module_residency import (
BoundedAllocatorCache,
PinnedModuleStager,
)
from vllm_omni.platforms import current_omni_platform
from .chunked_decode import decode_h3_chunks
from .ops import install_h3_vae_optimizations
@@ -56,15 +57,19 @@ def _minimax_h3_keyframe_encode_context(
yield
return
# The official keyframe latent uses cuDNN's TF32 convolution path. The
# default non-deterministic algorithm can select numerically different
# reductions on H100s, and the difference is amplified by the denoiser.
# Pin both the algorithm and math mode for this sensitive encode only.
# Deterministic cuDNN algorithms can still use reduced-precision TF32.
# On Hopper, TF32 can shift the keyframe latent enough to push I2VA below
# the reference accuracy thresholds. Use FP32 convolutions for this
# sensitive encode only; preserve the existing math mode elsewhere.
allow_tf32 = True
if current_omni_platform.is_cuda():
capability = current_omni_platform.get_device_capability(device.index or 0)
allow_tf32 = capability is None or capability.major != 9
with torch.backends.cudnn.flags(
enabled=True,
benchmark=False,
deterministic=True,
allow_tf32=True,
allow_tf32=allow_tf32,
):
yield
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
# Adapted from NextStep-1.1 (https://huggingface.co/stepfun-ai/NextStep-1.1)
import os
@@ -704,7 +704,7 @@ class NextStep11Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelin
)
# Unpatchify
latents = self.model.unpatchify(tokens)
latents = self.model.unpatchify(tokens, h=height // self.down_factor, w=width // self.down_factor)
latents = (latents / self.scaling_factor) + self.shift_factor
# Decode latents
@@ -343,6 +343,10 @@ class BaseScheduler(ABC):
def num_running_requests(self) -> int:
return len(self._running)
def pending_finished_request_ids(self) -> set[str]:
"""Finished requests whose state the engine has not consumed yet."""
return {request_id for request_id in self._finished_req_ids if request_id in self._request_states}
def get_admission_wait_decision(
self,
*,
+18 -1
View File
@@ -877,6 +877,19 @@ class DiffusionWorker:
logger.info(f"[Worker {self.rank}] Wake-up complete.")
return True
def synchronize_device(self, timeout: float | None = None) -> None:
"""Wait until this rank has no device work left.
A KV prefetch still receiving on its background thread has queued no
device work yet, so it is joined first. ``timeout`` bounds that join
(and the multi-process worker's output drain before this call); the
device wait itself is unbounded.
"""
manager = getattr(self.model_runner, "kv_transfer_manager", None)
if manager is not None and not manager.wait_prefetch(timeout=timeout):
raise TimeoutError("Diffusion KV prefetch did not finish before pause")
current_omni_platform.synchronize()
def handle_sleep_task(self, task: OmniSleepTask | dict) -> OmniACK | None:
from vllm_omni.platforms import current_omni_platform
@@ -1214,11 +1227,13 @@ class WorkerProc:
self._async_output_pending = max(0, self._async_output_pending - 1)
self._async_output_done.notify_all()
def drain_async_outputs(self, timeout: float = _ASYNC_OUTPUT_DRAIN_TIMEOUT_S) -> bool:
def drain_async_outputs(self, timeout: float | None = None) -> bool:
"""Block until background D2H/SHM packing has no work left.
Returns False if outputs are still in flight when ``timeout`` expires.
"""
if timeout is None:
timeout = _ASYNC_OUTPUT_DRAIN_TIMEOUT_S
with self._async_output_done:
if self._async_output_pending == 0:
return True
@@ -1334,6 +1349,8 @@ class WorkerProc:
}
try:
if method == "synchronize_device" and not self.drain_async_outputs(timeout=kwargs.get("timeout")):
raise TimeoutError("Diffusion async outputs did not drain before pause")
if method in _MEMORY_RELEASING_METHODS:
self.drain_async_outputs()
# Use execute_method from WorkerWrapperBase for consistent method resolution