Merge branch 'main' into codex-diffusion-shutdown-escalation
This commit is contained in:
621 files changed
+44129
-12315
No files matched your search
@@ -121,6 +121,13 @@ class AttentionBackend(ABC):
|
||||
when it unifies cache layouts across layers. Dense diffusion backends
|
||||
conservatively keep the default ``False``; a paged backend should
|
||||
override this only when its kernel actually follows that layout.
|
||||
|
||||
Since vLLM 0.29 this no longer rides on ``AttentionSpec``. It selects
|
||||
the block-outermost physical layout pinned on
|
||||
``CacheConfig.kv_cache_layout`` -- see
|
||||
``vllm_omni.diffusion.diffusion_kv.layout`` -- whose
|
||||
``is_block_outermost`` is what upstream reads when it sizes
|
||||
``KVCacheTensor`` regions.
|
||||
"""
|
||||
|
||||
return False
|
||||
|
||||
@@ -28,11 +28,9 @@ def _load_hub_module(repo_id: str):
|
||||
|
||||
logger.info("Loading %s kernel from HuggingFace Hub...", repo_id)
|
||||
last_error = None
|
||||
for version in (1, 2, None):
|
||||
for version in (1, 2):
|
||||
try:
|
||||
if version is not None:
|
||||
return get_kernel(repo_id, version=version)
|
||||
return get_kernel(repo_id)
|
||||
return get_kernel(repo_id, version=version)
|
||||
except Exception as exc:
|
||||
logger.info("Failed to load %s version %s: %s", repo_id, version, exc)
|
||||
last_error = exc
|
||||
|
||||
@@ -24,6 +24,7 @@ from vllm_omni.diffusion.attention.parallel.ring import RingParallelAttention
|
||||
from vllm_omni.diffusion.attention.selector import get_attn_backend_for_role
|
||||
from vllm_omni.diffusion.config import get_current_diffusion_config_or_none
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
from vllm_omni.diffusion.diffusion_kv.layout import assert_backend_layout_supported
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
get_forward_context,
|
||||
@@ -261,15 +262,19 @@ class Attention(nn.Module):
|
||||
return None
|
||||
dtype = self.paged_kv_cache_dtype or vllm_config.model_config.dtype
|
||||
# Keep backend layout discovery under the same config context used by
|
||||
# upstream vLLM's attention-spec collector.
|
||||
# upstream vLLM's attention-spec collector. vLLM 0.29 moved the
|
||||
# block-stride decision off the spec and onto the single physical
|
||||
# ``CacheConfig.kv_cache_layout`` resolved before the cache is built,
|
||||
# so the backend's preference is enforced there (see
|
||||
# ``vllm_omni.diffusion.diffusion_kv.initialization``) rather than
|
||||
# carried per layer.
|
||||
with set_current_vllm_config(vllm_config):
|
||||
indexes_kv_by_block_stride = self.attn_backend.indexes_kv_by_block_stride()
|
||||
assert_backend_layout_supported(vllm_config, self.attn_backend)
|
||||
return FullAttentionSpec(
|
||||
block_size=vllm_config.cache_config.block_size,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
head_size=self.head_size,
|
||||
dtype=dtype,
|
||||
indexes_kv_by_block_stride=indexes_kv_by_block_stride,
|
||||
non_causal=not self.causal,
|
||||
)
|
||||
|
||||
|
||||
@@ -7,6 +7,22 @@ from __future__ import annotations
|
||||
import torch
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
# Ascend CANN limits the launch coreDim to uint16.
|
||||
_MAX_1D_GRID_SIZE = 65535
|
||||
|
||||
|
||||
def _iter_row_chunks(rows: int):
|
||||
for row_offset in range(0, rows, _MAX_1D_GRID_SIZE):
|
||||
yield row_offset, min(rows - row_offset, _MAX_1D_GRID_SIZE)
|
||||
|
||||
|
||||
def _launch_row_chunks(kernel, rows: int, device_type: str, *args, **kwargs) -> None:
|
||||
if device_type != "npu":
|
||||
kernel[(rows,)](*args, 0, **kwargs)
|
||||
return
|
||||
for row_offset, chunk_rows in _iter_row_chunks(rows):
|
||||
kernel[(chunk_rows,)](*args, row_offset, **kwargs)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexed_scale_shift_kernel(
|
||||
@@ -20,9 +36,10 @@ def _indexed_scale_shift_kernel(
|
||||
stride_shift_row,
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0)
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
@@ -51,9 +68,10 @@ def _indexed_gate_kernel(
|
||||
stride_gate_row,
|
||||
stride_other_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0)
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
@@ -83,9 +101,10 @@ def _rms_norm_indexed_scale_shift_kernel(
|
||||
stride_shift_row,
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0)
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
@@ -123,9 +142,10 @@ def _indexed_gate_rms_norm_scale_shift_kernel(
|
||||
stride_shift_row,
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0)
|
||||
row = tl.program_id(0) + row_offset
|
||||
columns = tl.arange(0, block_n)
|
||||
mask = columns < hidden_size
|
||||
index = tl.load(indices_ptr + row * stride_indices)
|
||||
@@ -162,7 +182,10 @@ def indexed_scale_shift_(
|
||||
rows, hidden_size = x.shape
|
||||
if rows == 0:
|
||||
return x
|
||||
_indexed_scale_shift_kernel[(rows,)](
|
||||
_launch_row_chunks(
|
||||
_indexed_scale_shift_kernel,
|
||||
rows,
|
||||
x.device.type,
|
||||
x,
|
||||
x,
|
||||
shift,
|
||||
@@ -192,7 +215,10 @@ def indexed_gate(
|
||||
rows, hidden_size = x.shape
|
||||
if rows == 0:
|
||||
return output
|
||||
_indexed_gate_kernel[(rows,)](
|
||||
_launch_row_chunks(
|
||||
_indexed_gate_kernel,
|
||||
rows,
|
||||
x.device.type,
|
||||
output,
|
||||
x,
|
||||
gate,
|
||||
@@ -229,7 +255,10 @@ def rms_norm_indexed_scale_shift(
|
||||
output = torch.empty_like(x)
|
||||
rows, hidden_size = x.shape
|
||||
if rows:
|
||||
_rms_norm_indexed_scale_shift_kernel[(rows,)](
|
||||
_launch_row_chunks(
|
||||
_rms_norm_indexed_scale_shift_kernel,
|
||||
rows,
|
||||
x.device.type,
|
||||
output,
|
||||
x,
|
||||
weight,
|
||||
@@ -274,7 +303,10 @@ def indexed_gate_rms_norm_scale_shift(
|
||||
modulated_out = torch.empty_like(residual)
|
||||
rows, hidden_size = residual.shape
|
||||
if rows:
|
||||
_indexed_gate_rms_norm_scale_shift_kernel[(rows,)](
|
||||
_launch_row_chunks(
|
||||
_indexed_gate_rms_norm_scale_shift_kernel,
|
||||
rows,
|
||||
residual.device.type,
|
||||
residual_out,
|
||||
modulated_out,
|
||||
residual,
|
||||
|
||||
@@ -14,7 +14,11 @@ from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.parallel.base import ParallelAttentionContext
|
||||
from vllm_omni.diffusion.distributed.comm import SeqAllToAll4D
|
||||
from vllm_omni.diffusion.distributed.group_coordinator import SequenceParallelGroupCoordinator
|
||||
from vllm_omni.diffusion.forward_context import get_ulysses_mode
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
get_forward_context,
|
||||
get_ulysses_mode,
|
||||
is_forward_context_available,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -142,7 +146,7 @@ def _ulysses_all_to_all_any_qkv(
|
||||
|
||||
input_split_sizes = [s_local] * world_size
|
||||
output_split_sizes = seq_lens
|
||||
s_global = int(sum(output_split_sizes))
|
||||
s_global = sum(output_split_sizes)
|
||||
|
||||
out = torch.empty((s_global, bsz, head_cnt_local, head_dim), device=x.device, dtype=x.dtype)
|
||||
dist.all_to_all_single(
|
||||
@@ -177,7 +181,7 @@ def _ulysses_all_to_all_any_o(
|
||||
return x
|
||||
|
||||
bsz, s_global, head_cnt_local, head_dim = x.shape
|
||||
s_local = int(local_seq_len)
|
||||
s_local = local_seq_len
|
||||
|
||||
# (B, S_global, H_local, D) -> (S_global, B, H_local, D)
|
||||
x_t = x.permute(1, 0, 2, 3).contiguous()
|
||||
@@ -411,9 +415,22 @@ class UlyssesParallelAttention:
|
||||
f"(got scatter_idx={self._scatter_idx}, gather_idx={self._gather_idx})."
|
||||
)
|
||||
|
||||
local_seq_len = int(query.shape[1])
|
||||
seq_lens = _all_gather_int(self._ulysses_pg, local_seq_len, device=query.device)
|
||||
s_global = int(sum(seq_lens))
|
||||
if is_forward_context_available() and get_forward_context().sp_rank_local_seq_lens_equal:
|
||||
# auto_pad already made every rank's shard the same length, so
|
||||
# the lengths are known without a collective. Keep local_seq_len
|
||||
# as a SymInt (no int()) so torch.compile(dynamic=True) does not
|
||||
# specialize on it, and skip the host sync + graph break that
|
||||
# _all_gather_int would introduce in every attention call.
|
||||
local_seq_len = query.shape[1]
|
||||
seq_lens = [local_seq_len] * ulysses_world_size
|
||||
else:
|
||||
local_seq_len = int(query.shape[1])
|
||||
seq_lens = _all_gather_int(
|
||||
self._ulysses_pg,
|
||||
local_seq_len,
|
||||
device=query.device,
|
||||
)
|
||||
s_global = sum(seq_lens)
|
||||
|
||||
# In hybrid Ulysses+Ring, Ring attention uses P2P send/recv with fixed-shape
|
||||
# buffers. This requires all ring ranks to have the same seq_len after the
|
||||
@@ -571,8 +588,8 @@ class UlyssesParallelAttention:
|
||||
joint_len=joint_len,
|
||||
joint_strategy=joint_strategy,
|
||||
use_uaa=(mode == "advanced_uaa"),
|
||||
uaa_seq_lens=tuple(int(x) for x in seq_lens) if mode == "advanced_uaa" else (),
|
||||
uaa_local_seq_len=int(local_seq_len) if mode == "advanced_uaa" else 0,
|
||||
uaa_seq_lens=tuple(seq_lens) if mode == "advanced_uaa" else (),
|
||||
uaa_local_seq_len=local_seq_len if mode == "advanced_uaa" else 0,
|
||||
orig_head_cnt=int(orig_head_cnt) if mode == "advanced_uaa" else 0,
|
||||
joint_orig_head_cnt=int(joint_orig_head_cnt) if mode == "advanced_uaa" else 0,
|
||||
)
|
||||
@@ -591,15 +608,15 @@ class UlyssesParallelAttention:
|
||||
if attn_metadata.attn_mask is None:
|
||||
assert attn_metadata.joint_attn_mask is not None
|
||||
attn_metadata.attn_mask = torch.ones(
|
||||
[query.shape[0], query.shape[1] - attn_metadata.joint_attn_mask.shape[1]],
|
||||
[key.shape[0], key.shape[1] - attn_metadata.joint_attn_mask.shape[1]],
|
||||
dtype=torch.bool,
|
||||
device=query.device,
|
||||
device=key.device,
|
||||
)
|
||||
elif attn_metadata.joint_attn_mask is None:
|
||||
attn_metadata.joint_attn_mask = torch.ones(
|
||||
[query.shape[0], query.shape[1] - attn_metadata.attn_mask.shape[1]],
|
||||
[key.shape[0], key.shape[1] - attn_metadata.attn_mask.shape[1]],
|
||||
dtype=torch.bool,
|
||||
device=query.device,
|
||||
device=key.device,
|
||||
)
|
||||
attn_metadata.attn_mask = (
|
||||
torch.cat([attn_metadata.joint_attn_mask, attn_metadata.attn_mask], dim=1)
|
||||
@@ -608,9 +625,10 @@ class UlyssesParallelAttention:
|
||||
)
|
||||
|
||||
if attn_metadata.attn_mask is not None:
|
||||
# the final attn_mask is ready, the length should be aligedn with query length
|
||||
assert attn_metadata.attn_mask.shape[1] == query.shape[1], (
|
||||
f"attn_mask length: {attn_metadata.attn_mask.shape[1]} != query length: {query.shape[1]}"
|
||||
# A 2D mask describes keys. Joint attention may provide K/V-only
|
||||
# context, so key and query lengths are not necessarily equal.
|
||||
assert attn_metadata.attn_mask.shape[1] == key.shape[1], (
|
||||
f"attn_mask length: {attn_metadata.attn_mask.shape[1]} != key length: {key.shape[1]}"
|
||||
)
|
||||
attn_metadata.attn_mask = attn_metadata.attn_mask.bool().contiguous()
|
||||
return query, key, value, attn_metadata, ctx
|
||||
|
||||
+88
-34
@@ -2,6 +2,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
import copy
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
@@ -42,45 +43,57 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def normalize_omni_diffusion_kwargs(kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
||||
def normalize_omni_diffusion_kwargs(raw_kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize legacy diffusion kwargs before config construction."""
|
||||
normalized = dict(kwargs)
|
||||
config_kwargs = dict(raw_kwargs)
|
||||
|
||||
dtype = config_kwargs.get("dtype")
|
||||
if dtype is None:
|
||||
config_kwargs["dtype"] = "auto"
|
||||
elif isinstance(dtype, torch.dtype):
|
||||
config_kwargs["dtype"] = str(dtype).removeprefix("torch.")
|
||||
elif not isinstance(dtype, str):
|
||||
raise TypeError(f"Provided dtype must be a string or torch.dtype, got {type(dtype).__name__}")
|
||||
|
||||
# Backwards-compatibility: older callers may use a diffusion-specific
|
||||
# "static_lora_scale" kwarg. Normalize it to the canonical "lora_scale".
|
||||
if "static_lora_scale" in normalized:
|
||||
if "lora_scale" not in normalized:
|
||||
normalized["lora_scale"] = normalized["static_lora_scale"]
|
||||
normalized.pop("static_lora_scale", None)
|
||||
if "static_lora_scale" in config_kwargs:
|
||||
if "lora_scale" not in config_kwargs:
|
||||
config_kwargs["lora_scale"] = config_kwargs["static_lora_scale"]
|
||||
config_kwargs.pop("static_lora_scale", None)
|
||||
|
||||
diffusion_quantization = config_kwargs.pop("diffusion_quantization_config", None)
|
||||
if config_kwargs.get("quantization_config") is None and diffusion_quantization is not None:
|
||||
config_kwargs["quantization_config"] = diffusion_quantization
|
||||
|
||||
# Backwards-compatibility: map "quantization" to "quantization_config"
|
||||
# so callers using the old field name still work.
|
||||
if "quantization" in normalized and normalized.get("quantization_config", None) is None:
|
||||
normalized["quantization_config"] = normalized.pop("quantization")
|
||||
if "quantization" in config_kwargs and config_kwargs.get("quantization_config", None) is None:
|
||||
config_kwargs["quantization_config"] = config_kwargs.pop("quantization")
|
||||
else:
|
||||
normalized.pop("quantization", None)
|
||||
config_kwargs.pop("quantization", None)
|
||||
|
||||
# Renamed from kv_cache_* to avoid clashing with vLLM's --kv-cache-dtype.
|
||||
if normalized.get("diffusion_kv_cache_dtype") is None and "kv_cache_dtype" in normalized:
|
||||
normalized["diffusion_kv_cache_dtype"] = normalized.pop("kv_cache_dtype")
|
||||
if config_kwargs.get("diffusion_kv_cache_dtype") is None and "kv_cache_dtype" in config_kwargs:
|
||||
config_kwargs["diffusion_kv_cache_dtype"] = config_kwargs.pop("kv_cache_dtype")
|
||||
else:
|
||||
normalized.pop("kv_cache_dtype", None)
|
||||
if normalized.get("diffusion_kv_cache_skip_steps") is None and "kv_cache_skip_steps" in normalized:
|
||||
normalized["diffusion_kv_cache_skip_steps"] = normalized.pop("kv_cache_skip_steps")
|
||||
config_kwargs.pop("kv_cache_dtype", None)
|
||||
if config_kwargs.get("diffusion_kv_cache_skip_steps") is None and "kv_cache_skip_steps" in config_kwargs:
|
||||
config_kwargs["diffusion_kv_cache_skip_steps"] = config_kwargs.pop("kv_cache_skip_steps")
|
||||
else:
|
||||
normalized.pop("kv_cache_skip_steps", None)
|
||||
if normalized.get("diffusion_kv_cache_skip_layers") is None and "kv_cache_skip_layers" in normalized:
|
||||
normalized["diffusion_kv_cache_skip_layers"] = normalized.pop("kv_cache_skip_layers")
|
||||
config_kwargs.pop("kv_cache_skip_steps", None)
|
||||
if config_kwargs.get("diffusion_kv_cache_skip_layers") is None and "kv_cache_skip_layers" in config_kwargs:
|
||||
config_kwargs["diffusion_kv_cache_skip_layers"] = config_kwargs.pop("kv_cache_skip_layers")
|
||||
else:
|
||||
normalized.pop("kv_cache_skip_layers", None)
|
||||
config_kwargs.pop("kv_cache_skip_layers", None)
|
||||
|
||||
# Handle "diffusion_attention_backend" shorthand: merge into
|
||||
# diffusion_attention_config before field filtering.
|
||||
diffusion_attn_backend = normalized.pop("diffusion_attention_backend", None)
|
||||
fastvideo_vsa_topk = normalized.pop("fastvideo_vsa_topk", None)
|
||||
diffusion_attn_backend = config_kwargs.pop("diffusion_attention_backend", None)
|
||||
fastvideo_vsa_topk = config_kwargs.pop("fastvideo_vsa_topk", None)
|
||||
if diffusion_attn_backend is not None or fastvideo_vsa_topk is not None:
|
||||
existing = normalized.get("diffusion_attention_config")
|
||||
normalized["diffusion_attention_config"] = parse_attention_config(
|
||||
existing = config_kwargs.get("diffusion_attention_config")
|
||||
config_kwargs["diffusion_attention_config"] = parse_attention_config(
|
||||
existing,
|
||||
attention_backend=diffusion_attn_backend,
|
||||
fastvideo_vsa_topk=fastvideo_vsa_topk,
|
||||
@@ -88,16 +101,33 @@ def normalize_omni_diffusion_kwargs(kwargs: Mapping[str, Any]) -> dict[str, Any]
|
||||
|
||||
# Check environment variable as fallback for cache_backend.
|
||||
# Support both old DIFFUSION_CACHE_ADAPTER and new DIFFUSION_CACHE_BACKEND.
|
||||
if "cache_backend" not in normalized:
|
||||
if "cache_backend" not in config_kwargs:
|
||||
cache_backend = os.environ.get("DIFFUSION_CACHE_BACKEND") or os.environ.get("DIFFUSION_CACHE_ADAPTER")
|
||||
normalized["cache_backend"] = cache_backend.lower() if cache_backend else "none"
|
||||
config_kwargs["cache_backend"] = cache_backend.lower() if cache_backend else "none"
|
||||
elif config_kwargs["cache_backend"] is None:
|
||||
# Callers (e.g. example CLIs with `default=None`) pass an explicit
|
||||
# None for "no cache"; canonicalize it so every consumer sees the
|
||||
# declared `str` value instead of relying on per-model None handling.
|
||||
config_kwargs["cache_backend"] = "none"
|
||||
|
||||
cache_config = config_kwargs.get("cache_config")
|
||||
if isinstance(cache_config, str):
|
||||
try:
|
||||
config_kwargs["cache_config"] = json.loads(cache_config)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Invalid cache_config JSON, using backend defaults.")
|
||||
config_kwargs.pop("cache_config", None)
|
||||
|
||||
if config_kwargs.get("streaming_output") is None and config_kwargs.get("diffusion_streaming_output") is not None:
|
||||
config_kwargs["streaming_output"] = config_kwargs["diffusion_streaming_output"]
|
||||
config_kwargs.pop("diffusion_streaming_output", None)
|
||||
|
||||
# Convert optional YAML null values to empty containers.
|
||||
for key in ("diffusers_load_kwargs", "diffusers_call_kwargs"):
|
||||
if key in normalized and normalized[key] is None:
|
||||
normalized[key] = {}
|
||||
if key in config_kwargs and config_kwargs[key] is None:
|
||||
config_kwargs[key] = {}
|
||||
|
||||
return normalized
|
||||
return config_kwargs
|
||||
|
||||
|
||||
def validate_host_weight_runtime_options(*, mode: object, root: object) -> None:
|
||||
@@ -434,6 +464,27 @@ class DiffusionParallelConfig:
|
||||
raise TypeError(f"Expected parallel config dict, got {type(data)!r}")
|
||||
return cls(**data)
|
||||
|
||||
@classmethod
|
||||
def from_stage_overrides(cls, kwargs: Mapping[str, Any]) -> "DiffusionParallelConfig":
|
||||
"""Resolve nested or flat stage inputs through the config's own defaults."""
|
||||
parallel_config = kwargs.get("parallel_config")
|
||||
if isinstance(parallel_config, cls):
|
||||
return parallel_config
|
||||
|
||||
valid_fields = {item.name for item in fields(cls) if item.init}
|
||||
if isinstance(parallel_config, Mapping):
|
||||
return cls.from_dict(dict(parallel_config))
|
||||
elif parallel_config is not None and hasattr(parallel_config, "__dict__"):
|
||||
return cls.from_dict(dict(vars(parallel_config)))
|
||||
elif parallel_config is not None:
|
||||
raise TypeError(
|
||||
f"parallel_config must be a mapping or DiffusionParallelConfig, got {type(parallel_config).__name__}"
|
||||
)
|
||||
else:
|
||||
values = {key: value for key, value in kwargs.items() if key in valid_fields}
|
||||
|
||||
return cls(**{key: value for key, value in values.items() if value is not None})
|
||||
|
||||
|
||||
@dataclass
|
||||
class TransformerConfig:
|
||||
@@ -1545,15 +1596,18 @@ class OmniDiffusionConfig:
|
||||
raise
|
||||
|
||||
@classmethod
|
||||
def from_kwargs(cls, **kwargs: Any) -> "OmniDiffusionConfig":
|
||||
kwargs = normalize_omni_diffusion_kwargs(kwargs)
|
||||
|
||||
# Filter kwargs to only include valid fields
|
||||
def normalize_init_kwargs(cls, raw_kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
||||
config_kwargs = normalize_omni_diffusion_kwargs(raw_kwargs)
|
||||
valid_fields = {f.name for f in fields(cls)}
|
||||
filtered_kwargs = {k: v for k, v in kwargs.items() if k in valid_fields}
|
||||
# Remaining ``None`` values mean "unset" at the CLI/deploy boundary.
|
||||
# Drop them so non-optional dataclass defaults are not overwritten.
|
||||
# Fields where ``None`` has normalization semantics (for example dtype
|
||||
# and nullable container inputs) are handled above before this filter.
|
||||
return {key: value for key, value in config_kwargs.items() if key in valid_fields and value is not None}
|
||||
|
||||
instance = cls(**filtered_kwargs)
|
||||
return instance
|
||||
@classmethod
|
||||
def from_kwargs(cls, **kwargs: Any) -> "OmniDiffusionConfig":
|
||||
return cls(**cls.normalize_init_kwargs(kwargs))
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -439,8 +439,10 @@ class DiffusionEngine:
|
||||
generator = self.get_output_stream(request_id)
|
||||
async for output in generator:
|
||||
exec_total_time = time.perf_counter() - exec_start_time
|
||||
output_ready_wait_time = 0.0
|
||||
# Async mode: wait for background D2H/SHM to complete.
|
||||
if output.async_output_id:
|
||||
output_ready_wait_start_time = time.perf_counter()
|
||||
fut = self.executor.wait_output_ready(output.async_output_id)
|
||||
timeout = _async_output_timeout()
|
||||
try:
|
||||
@@ -455,6 +457,7 @@ class DiffusionEngine:
|
||||
describe(output.async_output_id) if describe else "unavailable",
|
||||
)
|
||||
raise
|
||||
output_ready_wait_time = time.perf_counter() - output_ready_wait_start_time
|
||||
postprocess_start_time = time.perf_counter()
|
||||
scheduler_metrics = diffusion_scheduler_waiting_metrics(getattr(self, "_scheduler_num_waiting_reqs", 0))
|
||||
try:
|
||||
@@ -468,9 +471,11 @@ class DiffusionEngine:
|
||||
step_total_ms = (time.perf_counter() - diffusion_engine_start_time) * 1000
|
||||
logger.debug(
|
||||
"DiffusionEngine.step_streaming breakdown: preprocess=%.2f ms, "
|
||||
"add_req_and_wait=%.2f ms, postprocess=%.2f ms, total=%.2f ms",
|
||||
"add_req_and_wait=%.2f ms, output_ready_wait=%.2f ms, "
|
||||
"postprocess=%.2f ms, total=%.2f ms",
|
||||
preprocess_time * 1000,
|
||||
exec_total_time * 1000,
|
||||
output_ready_wait_time * 1000,
|
||||
postprocess_time * 1000,
|
||||
step_total_ms,
|
||||
)
|
||||
@@ -478,6 +483,7 @@ class DiffusionEngine:
|
||||
metrics_update = {
|
||||
"preprocess_time_ms": preprocess_time * 1000,
|
||||
"diffusion_engine_exec_time_ms": exec_total_time * 1000,
|
||||
"output_ready_wait_time_ms": output_ready_wait_time * 1000,
|
||||
"postprocess_time_ms": postprocess_time * 1000,
|
||||
**scheduler_metrics,
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -16,6 +16,7 @@ from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheSpec
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
from vllm_omni.diffusion.diffusion_kv.layout import resolve_diffusion_kv_cache_layout
|
||||
from vllm_omni.diffusion.vllm_config import create_diffusion_vllm_config
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
@@ -28,14 +29,35 @@ def build_native_kv_cache_configs(
|
||||
vllm_config: VllmConfig,
|
||||
worker_specs: list[dict[str, KVCacheSpec]],
|
||||
available_memory: list[int],
|
||||
*,
|
||||
indexes_kv_by_block_stride: bool = False,
|
||||
) -> tuple[list[KVCacheConfig], KVCacheConfig]:
|
||||
"""Build rank-local and Scheduler-native configs using vLLM utilities."""
|
||||
"""Build rank-local and Scheduler-native configs using vLLM utilities.
|
||||
|
||||
``indexes_kv_by_block_stride`` carries the native backend requirement that
|
||||
0.29 removed from ``AttentionSpec``. Every diffusion backend in tree
|
||||
declares ``False``, so the default reproduces current behaviour; a caller
|
||||
that learns otherwise from its workers passes ``True`` here and the
|
||||
block-outermost layout propagates to every rank-local config.
|
||||
"""
|
||||
|
||||
from vllm.v1.core import single_type_kv_cache_manager
|
||||
|
||||
# 0.29 sizes every KVCacheTensor region from the resolved physical layout,
|
||||
# so it must be pinned before get_kv_cache_configs. Idempotent, so callers
|
||||
# that already resolved it (the control plane) are unaffected.
|
||||
layout = resolve_diffusion_kv_cache_layout(
|
||||
vllm_config,
|
||||
indexes_kv_by_block_stride=indexes_kv_by_block_stride,
|
||||
)
|
||||
single_type_kv_cache_manager.register_all_kvcache_specs(vllm_config)
|
||||
worker_configs = get_kv_cache_configs(vllm_config, worker_specs, available_memory)
|
||||
return worker_configs, generate_scheduler_kv_cache_config(worker_configs)
|
||||
scheduler_config = generate_scheduler_kv_cache_config(worker_configs)
|
||||
# Workers only receive a KVCacheConfig, so the resolved layout travels on it
|
||||
# and is adopted into each worker's own CacheConfig before allocation.
|
||||
for config in (*worker_configs, scheduler_config):
|
||||
config.kv_cache_layout = layout.name
|
||||
return worker_configs, scheduler_config
|
||||
|
||||
|
||||
def initialize_diffusion_kv_control_plane(
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Physical KV cache layout selection for the native Diffusion paged cache.
|
||||
|
||||
vLLM 0.29 removed ``AttentionSpec.indexes_kv_by_block_stride`` and replaced it
|
||||
with a single physical layout per model, resolved once and recorded on
|
||||
``CacheConfig.kv_cache_layout``. ``KVCacheLayout.is_block_outermost`` is the
|
||||
direct successor of the old per-spec flag: upstream derives
|
||||
``interleaved_block_stride`` from it when it lays out ``KVCacheTensor`` regions
|
||||
(``vllm/v1/core/kv_cache_utils.py``).
|
||||
|
||||
Diffusion never reaches vLLM's engine-core resolution. Its backends subclass
|
||||
Omni's own ``AttentionBackend`` ABC, which upstream's
|
||||
``get_supported_kv_cache_layouts`` never sees, so the layout is pinned here
|
||||
before ``get_kv_cache_configs`` runs.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm.v1.kv_cache_interface import KVCacheSpec, KVCacheTensor, compute_layout_strides
|
||||
from vllm.v1.kv_cache_layout import KVCacheLayout
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
# Layer-outermost, matching the head of upstream's ``_DEFAULT_LAYOUT_PREFERENCE``
|
||||
# and reproducing the ``indexes_kv_by_block_stride=False`` that every dense
|
||||
# diffusion backend declared before 0.29.
|
||||
DEFAULT_DIFFUSION_KV_CACHE_LAYOUT = KVCacheLayout.LBNHC
|
||||
# Block-outermost counterpart, for a paged backend whose kernel really does read
|
||||
# K/V pages by the runtime block stride.
|
||||
BLOCK_STRIDE_DIFFUSION_KV_CACHE_LAYOUT = KVCacheLayout.BLNHC
|
||||
|
||||
|
||||
def resolve_diffusion_kv_cache_layout(
|
||||
vllm_config: VllmConfig,
|
||||
*,
|
||||
indexes_kv_by_block_stride: bool = False,
|
||||
) -> KVCacheLayout:
|
||||
"""Pin the physical KV layout for the Diffusion cache and return it.
|
||||
|
||||
A layout already present on the config wins, mirroring upstream's
|
||||
``resolve_kv_cache_layout``; it is validated against the requirement rather
|
||||
than silently overwritten, because an inconsistent layout reads K/V
|
||||
from the wrong offsets instead of raising.
|
||||
"""
|
||||
|
||||
required_block_outermost = bool(indexes_kv_by_block_stride)
|
||||
cache_config = getattr(vllm_config, "cache_config", None)
|
||||
if cache_config is None:
|
||||
# A config double with nowhere to record the choice; report what the
|
||||
# requirement implies without pretending it was pinned.
|
||||
return BLOCK_STRIDE_DIFFUSION_KV_CACHE_LAYOUT if required_block_outermost else DEFAULT_DIFFUSION_KV_CACHE_LAYOUT
|
||||
|
||||
current = getattr(cache_config, "kv_cache_layout", None)
|
||||
if current is not None:
|
||||
layout = KVCacheLayout[current]
|
||||
if layout.is_block_outermost != required_block_outermost:
|
||||
raise ValueError(
|
||||
"Diffusion KV cache layout "
|
||||
f"{layout.name} (is_block_outermost="
|
||||
f"{layout.is_block_outermost}) contradicts the attention "
|
||||
"backend, which requires is_block_outermost="
|
||||
f"{required_block_outermost}."
|
||||
)
|
||||
return layout
|
||||
|
||||
layout = BLOCK_STRIDE_DIFFUSION_KV_CACHE_LAYOUT if required_block_outermost else DEFAULT_DIFFUSION_KV_CACHE_LAYOUT
|
||||
cache_config.kv_cache_layout = layout.name
|
||||
return layout
|
||||
|
||||
|
||||
def adopt_kv_cache_layout(vllm_config: VllmConfig, kv_cache_config) -> KVCacheLayout:
|
||||
"""Adopt the control plane's resolved layout inside a worker.
|
||||
|
||||
The engine core resolves the layout once and every worker adopts it before
|
||||
allocating (``CacheConfig.kv_cache_layout``). Diffusion workers receive only
|
||||
a ``KVCacheConfig``, so the name rides along on ``kv_cache_config`` and is
|
||||
copied onto the worker's own config here. Without this, anything calling
|
||||
``get_resolved_kv_cache_layout`` in a worker -- ``init_kv_cache`` does --
|
||||
raises.
|
||||
"""
|
||||
|
||||
name = getattr(kv_cache_config, "kv_cache_layout", None)
|
||||
if name is None:
|
||||
# Older configs, or a standalone harness: fall back to the same default
|
||||
# the control plane pins so both sides still agree.
|
||||
return resolve_diffusion_kv_cache_layout(vllm_config)
|
||||
|
||||
cache_config = getattr(vllm_config, "cache_config", None)
|
||||
if cache_config is None:
|
||||
return KVCacheLayout[name]
|
||||
|
||||
current = getattr(cache_config, "kv_cache_layout", None)
|
||||
if current is None:
|
||||
cache_config.kv_cache_layout = name
|
||||
elif current != name:
|
||||
raise ValueError(
|
||||
f"Worker KV cache layout {current!r} disagrees with the layout resolved by the control plane ({name!r})."
|
||||
)
|
||||
return KVCacheLayout[name]
|
||||
|
||||
|
||||
def build_kv_cache_tensor(
|
||||
spec: KVCacheSpec,
|
||||
num_blocks: int,
|
||||
layers: Sequence[str],
|
||||
*,
|
||||
layout: KVCacheLayout | None = None,
|
||||
offset: int = 0,
|
||||
) -> KVCacheTensor:
|
||||
"""A ``KVCacheTensor`` covering ``layers`` for ``num_blocks`` blocks.
|
||||
|
||||
Before 0.29 a tensor named the layers sharing it
|
||||
(``KVCacheTensor(size=..., shared_by=[...])``); 0.29 replaced that with an
|
||||
explicit layout, so layer ``l``'s block ``b`` starts at
|
||||
``offset + l * layer_stride + b * block_stride``. Note this lays the layers
|
||||
out at distinct offsets rather than aliasing them, which is what upstream
|
||||
now does for a single cache group.
|
||||
|
||||
The strides come from upstream's own ``compute_layout_strides``, called the
|
||||
way ``vllm.v1.core.kv_cache_utils`` calls it, because hand-computed strides
|
||||
read K/V from the wrong offsets silently instead of raising.
|
||||
"""
|
||||
|
||||
layout = layout or DEFAULT_DIFFUSION_KV_CACHE_LAYOUT
|
||||
layer_names = list(layers)
|
||||
# Mirrors kv_cache_utils: the block stride is pinned up front only for
|
||||
# block-outermost layouts, where every block repeats the same packing.
|
||||
bytes_per_block = spec.page_size_bytes * len(layer_names)
|
||||
interleaved_block_stride = bytes_per_block if layout.is_block_outermost else None
|
||||
layer_stride, block_stride, _, _, _ = compute_layout_strides(
|
||||
spec,
|
||||
num_blocks,
|
||||
len(layer_names),
|
||||
layout,
|
||||
fixed_strides=(None, interleaved_block_stride, None, None, None),
|
||||
)
|
||||
return KVCacheTensor(
|
||||
size=bytes_per_block * num_blocks,
|
||||
layers=layer_names,
|
||||
layer_stride=layer_stride,
|
||||
block_stride=block_stride,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
|
||||
def assert_backend_layout_supported(vllm_config: VllmConfig, attn_backend: type | None) -> None:
|
||||
"""Fail loudly when a backend's block-stride need contradicts the layout.
|
||||
|
||||
Skipped while the layout is still unresolved -- worker processes collect
|
||||
specs before the control plane hands them the resolved name -- so this
|
||||
enforces the contract wherever it is knowable and never crashes a rank that
|
||||
has simply not been told yet.
|
||||
"""
|
||||
|
||||
if attn_backend is None:
|
||||
return
|
||||
# Spec discovery runs against lightweight config doubles in tests and against
|
||||
# worker configs that have not been handed the resolved name yet; in both
|
||||
# cases there is simply nothing to check.
|
||||
cache_config = getattr(vllm_config, "cache_config", None)
|
||||
if cache_config is None or getattr(cache_config, "kv_cache_layout", None) is None:
|
||||
return
|
||||
indexes_by_block_stride = getattr(attn_backend, "indexes_kv_by_block_stride", None)
|
||||
if indexes_by_block_stride is None:
|
||||
return
|
||||
resolve_diffusion_kv_cache_layout(
|
||||
vllm_config,
|
||||
indexes_kv_by_block_stride=indexes_by_block_stride(),
|
||||
)
|
||||
@@ -18,6 +18,10 @@ from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode, is_scheduler_paged_kv_mode
|
||||
from vllm_omni.diffusion.diffusion_kv.layout import (
|
||||
adopt_kv_cache_layout,
|
||||
assert_backend_layout_supported,
|
||||
)
|
||||
from vllm_omni.diffusion.diffusion_kv.metadata import DiffusionKVMetadata
|
||||
from vllm_omni.diffusion.diffusion_kv.paged_attention_adapter import (
|
||||
DiffusionPagedAttentionAdapter,
|
||||
@@ -285,13 +289,16 @@ class DiffusionKVModelRunnerBackend:
|
||||
layers=self._kv_cache_layer_adapters,
|
||||
resolve_row=self._resolve_paged_attention_row,
|
||||
)
|
||||
# vLLM 0.29 reads the resolved physical layout when allocating,
|
||||
# and dropped attn_groups/cache_dtype from the signature.
|
||||
adopt_kv_cache_layout(self.vllm_config, kv_cache_config)
|
||||
for layer_adapter in self._kv_cache_layer_adapters.values():
|
||||
assert_backend_layout_supported(self.vllm_config, getattr(layer_adapter, "attn_backend", None))
|
||||
init_kv_cache(
|
||||
kv_caches,
|
||||
self.vllm_config.compilation_config.static_forward_context,
|
||||
kv_cache_config,
|
||||
attn_groups,
|
||||
self.device,
|
||||
self.vllm_config.cache_config.cache_dtype,
|
||||
kernel_block_sizes,
|
||||
self.vllm_config,
|
||||
)
|
||||
|
||||
@@ -105,10 +105,12 @@ class DiffusionPagedAttentionLayerAdapter(AttentionLayerBase):
|
||||
attn_backend,
|
||||
ulysses_degree=ulysses_degree,
|
||||
)
|
||||
# vLLM 0.29 carries the block-stride decision on the resolved physical
|
||||
# ``CacheConfig.kv_cache_layout`` instead of the spec; the backend's
|
||||
# requirement is enforced against that layout rather than copied here.
|
||||
canonical_spec = replace(
|
||||
spec,
|
||||
num_kv_heads=num_kv_heads,
|
||||
indexes_kv_by_block_stride=attn_backend.indexes_kv_by_block_stride(),
|
||||
)
|
||||
self.layer_name = layer_name
|
||||
self.spec = canonical_spec
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from contextlib import nullcontext
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
from diffusers.models.autoencoders import AutoencoderKLWan
|
||||
from diffusers.models.autoencoders.autoencoder_kl_wan import unpatchify
|
||||
from diffusers.models.autoencoders.vae import DecoderOutput
|
||||
from diffusers.utils.accelerate_utils import apply_forward_hook
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.distributed.autoencoders import wan_spatial_shard
|
||||
@@ -18,6 +19,7 @@ from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor impor
|
||||
GridSpec,
|
||||
TileTask,
|
||||
)
|
||||
from vllm_omni.diffusion.models.interface import DecodedChunkConsumer
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -45,9 +47,137 @@ class OmniAutoencoderKLWan(AutoencoderKLWan):
|
||||
return super().encode(x, return_dict=return_dict)
|
||||
|
||||
def decode(self, z: torch.Tensor, return_dict: bool = True):
|
||||
"""Decode a Wan latent using the Diffusers-compatible full-tensor API."""
|
||||
with self._execution_context():
|
||||
return super().decode(z, return_dict=return_dict)
|
||||
|
||||
def _decode(self, z: torch.Tensor, return_dict: bool = True):
|
||||
"""Decode one latent batch, preserving the parent Diffusers contract."""
|
||||
_, _, _, height, width = z.shape
|
||||
tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio
|
||||
tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio
|
||||
|
||||
if getattr(self, "use_tiling", False) and (width > tile_latent_min_width or height > tile_latent_min_height):
|
||||
return self.tiled_decode(z, return_dict=return_dict)
|
||||
|
||||
return self._decode_temporal(z, return_dict=return_dict)
|
||||
|
||||
# Chunks are published straight from the decoder, clamped to the
|
||||
# checkpoint's output range.
|
||||
chunk_value_range: ClassVar[tuple[float, float]] = (-1.0, 1.0)
|
||||
|
||||
@apply_forward_hook
|
||||
def decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
|
||||
"""Decode ``z`` while synchronously delivering temporal chunks.
|
||||
|
||||
The ordinary :meth:`decode` contract remains the Diffusers contract.
|
||||
Chunk callbacks deliberately reject a sliced batch: Diffusers slices
|
||||
each sample before decoding, while a streaming consumer needs a stable
|
||||
batch ownership contract. Callers can disable ``use_slicing`` or
|
||||
invoke this capability once per sample.
|
||||
|
||||
Every rank participating in distributed VAE execution must invoke this
|
||||
method. Spatial-sharded execution invokes ``on_chunk`` only on the
|
||||
output-owning rank. Chunks have shape ``(B, C, T, H, W)`` and
|
||||
values clamped to ``[-1, 1]``. After a callback failure, remaining
|
||||
chunks are decoded and discarded before the exception is re-raised.
|
||||
"""
|
||||
if not callable(on_chunk):
|
||||
raise TypeError("on_chunk must be callable")
|
||||
if getattr(self, "use_slicing", False) and z.shape[0] > 1:
|
||||
raise ValueError(
|
||||
"Wan chunked decode does not support use_slicing for batch size > 1; "
|
||||
"disable VAE slicing or decode one sample at a time"
|
||||
)
|
||||
|
||||
with self._execution_context():
|
||||
self._decode_with_chunks(z, on_chunk=on_chunk)
|
||||
|
||||
def _decode_temporal(
|
||||
self,
|
||||
z: torch.Tensor,
|
||||
*,
|
||||
on_chunk: DecodedChunkConsumer | None = None,
|
||||
return_dict: bool = True,
|
||||
):
|
||||
"""Decode the non-tiled temporal path, optionally streaming chunks."""
|
||||
self.clear_cache()
|
||||
callback_error: BaseException | None = None
|
||||
try:
|
||||
x = self.post_quant_conv(z)
|
||||
decoded_chunks: list[torch.Tensor] = []
|
||||
for i in range(z.shape[2]):
|
||||
self._conv_idx = [0]
|
||||
if i == 0:
|
||||
chunk = self.decoder(
|
||||
x[:, :, i : i + 1, :, :],
|
||||
feat_cache=self._feat_map,
|
||||
feat_idx=self._conv_idx,
|
||||
first_chunk=True,
|
||||
)
|
||||
else:
|
||||
chunk = self.decoder(
|
||||
x[:, :, i : i + 1, :, :],
|
||||
feat_cache=self._feat_map,
|
||||
feat_idx=self._conv_idx,
|
||||
)
|
||||
|
||||
if on_chunk is None:
|
||||
decoded_chunks.append(chunk)
|
||||
continue
|
||||
|
||||
if callback_error is None:
|
||||
try:
|
||||
if self.config.patch_size is not None:
|
||||
chunk = unpatchify(chunk, patch_size=self.config.patch_size)
|
||||
on_chunk(torch.clamp(chunk, min=-1.0, max=1.0))
|
||||
except BaseException as exc:
|
||||
# A previously installed spatial-shard decoder still
|
||||
# runs collectives, even for latents below the tiling
|
||||
# threshold. Drain before surfacing consumer failures.
|
||||
callback_error = exc
|
||||
del chunk
|
||||
|
||||
if callback_error is not None:
|
||||
raise callback_error
|
||||
if on_chunk is not None:
|
||||
return None
|
||||
|
||||
out = torch.cat(decoded_chunks, dim=2)
|
||||
if self.config.patch_size is not None:
|
||||
out = unpatchify(out, patch_size=self.config.patch_size)
|
||||
out = torch.clamp(out, min=-1.0, max=1.0)
|
||||
if not return_dict:
|
||||
return (out,)
|
||||
return DecoderOutput(sample=out)
|
||||
finally:
|
||||
self.clear_cache()
|
||||
|
||||
@staticmethod
|
||||
def _discard_decoded_chunk(_chunk: torch.Tensor) -> None:
|
||||
"""Consume a non-owner rank's chunk without retaining its tensor."""
|
||||
|
||||
def _decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
|
||||
"""Run the temporal streaming primitive without API or hook handling."""
|
||||
distributed_enabled = False
|
||||
if hasattr(self, "is_distributed_enabled"):
|
||||
distributed_enabled = self.is_distributed_enabled()
|
||||
|
||||
if getattr(self, "use_tiling", False):
|
||||
tile_latent_min_height = self.tile_sample_min_height // self.spatial_compression_ratio
|
||||
tile_latent_min_width = self.tile_sample_min_width // self.spatial_compression_ratio
|
||||
exceeds_tile = z.shape[-1] > tile_latent_min_width or z.shape[-2] > tile_latent_min_height
|
||||
if exceeds_tile:
|
||||
if distributed_enabled:
|
||||
self._tiled_decode_with_chunks(z, on_chunk=on_chunk)
|
||||
return
|
||||
raise ValueError("Wan chunk callbacks are unsupported for spatial tiling")
|
||||
|
||||
callback = on_chunk
|
||||
if distributed_enabled and dist.get_rank(group=self.distributed_executor.group) != 0:
|
||||
callback = self._discard_decoded_chunk
|
||||
self._decode_temporal(z, on_chunk=callback)
|
||||
|
||||
|
||||
class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
|
||||
@classmethod
|
||||
@@ -78,7 +208,7 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
|
||||
blend_height = self.tile_sample_min_height - tile_sample_stride_height
|
||||
blend_width = self.tile_sample_min_width - tile_sample_stride_width
|
||||
|
||||
tiletask_list = []
|
||||
tiletask_list: list[TileTask] = []
|
||||
for i in range(0, height, tile_latent_stride_height):
|
||||
for j in range(0, width, tile_latent_stride_width):
|
||||
time_list = []
|
||||
@@ -151,7 +281,7 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
|
||||
blend_height = tile_latent_min_height - tile_latent_stride_height
|
||||
blend_width = tile_latent_min_width - tile_latent_stride_width
|
||||
|
||||
tiletask_list = []
|
||||
tiletask_list: list[TileTask] = []
|
||||
temporal_compression = self.config.scale_factor_temporal
|
||||
for i in range(0, height, tile_sample_stride_height):
|
||||
for j in range(0, width, tile_sample_stride_width):
|
||||
@@ -307,8 +437,10 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
|
||||
if not self.is_distributed_enabled():
|
||||
return super().tiled_decode(z, return_dict=return_dict)
|
||||
|
||||
if self._spatial_shard_decode_enabled(z):
|
||||
spatial_shard_enabled = self._spatial_shard_decode_enabled(z)
|
||||
if spatial_shard_enabled:
|
||||
split_dim = self._spatial_shard_decode_split_dim()
|
||||
assert split_dim is not None
|
||||
logger.debug("Decode running with Wan VAE spatial_shard_%s mode", split_dim)
|
||||
return wan_spatial_shard.spatial_shard_decode(
|
||||
self,
|
||||
@@ -329,6 +461,27 @@ class DistributedAutoencoderKLWan(OmniAutoencoderKLWan, DistributedVaeMixin):
|
||||
|
||||
return DecoderOutput(sample=result)
|
||||
|
||||
def _tiled_decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
|
||||
"""Decode tiled latents and deliver temporal chunks to ``on_chunk``."""
|
||||
if not self.is_distributed_enabled():
|
||||
raise ValueError("Wan chunk callbacks are unsupported for spatial tiling")
|
||||
|
||||
spatial_shard_enabled = self._spatial_shard_decode_enabled(z)
|
||||
if not spatial_shard_enabled:
|
||||
raise ValueError("Wan chunk callbacks require spatial-shard decode when tiling is enabled")
|
||||
|
||||
split_dim = self._spatial_shard_decode_split_dim()
|
||||
assert split_dim is not None
|
||||
logger.debug("Decode running with Wan VAE spatial_shard_%s mode", split_dim)
|
||||
wan_spatial_shard.spatial_shard_decode(
|
||||
self,
|
||||
z,
|
||||
group=self.distributed_executor.group,
|
||||
return_dict=True,
|
||||
split_dim=split_dim,
|
||||
on_chunk=on_chunk,
|
||||
)
|
||||
|
||||
def tiled_encode(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
Encode using distributed VAE executor.
|
||||
|
||||
@@ -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
|
||||
#
|
||||
# The halo-exchange spatial-parallel decode here is adapted from SGLang's
|
||||
# spatial-parallel VAE decode
|
||||
@@ -24,7 +24,7 @@ from contextlib import nullcontext
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
from types import MethodType
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -34,6 +34,8 @@ from diffusers.models.autoencoders.autoencoder_kl_wan import unpatchify
|
||||
from diffusers.models.autoencoders.vae import DecoderOutput
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.models.interface import DecodedChunkConsumer
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -644,7 +646,7 @@ def _replace_child(
|
||||
)
|
||||
return
|
||||
if isinstance(child, nn.ZeroPad2d):
|
||||
padding = tuple(int(p) for p in child.padding)
|
||||
padding = cast(tuple[int, int, int, int], tuple(int(p) for p in child.padding))
|
||||
module_padding = padding
|
||||
if parent.__class__.__name__ == "Sequential":
|
||||
# Let the following WanDistConv2d account for global after-edge
|
||||
@@ -794,7 +796,8 @@ def spatial_shard_decode(
|
||||
group: dist.ProcessGroup,
|
||||
return_dict: bool = True,
|
||||
split_dim: str = "height",
|
||||
) -> DecoderOutput | tuple[torch.Tensor]:
|
||||
on_chunk: DecodedChunkConsumer | None = None,
|
||||
) -> DecoderOutput | tuple[torch.Tensor] | None:
|
||||
install_wan_spatial_shard_decode(vae, group, split_dim=split_dim)
|
||||
|
||||
if z.shape[2] == 0:
|
||||
@@ -806,6 +809,7 @@ def spatial_shard_decode(
|
||||
produce_output = world_size <= 1 or rank == 0
|
||||
|
||||
vae.clear_cache()
|
||||
callback_error: BaseException | None = None
|
||||
try:
|
||||
context = vae._execution_context() if hasattr(vae, "_execution_context") else nullcontext()
|
||||
with context:
|
||||
@@ -820,18 +824,33 @@ def spatial_shard_decode(
|
||||
first_chunk=(i == 0),
|
||||
)
|
||||
if produce_output:
|
||||
decoded_chunks.append(chunk)
|
||||
if on_chunk is not None and callback_error is None:
|
||||
try:
|
||||
if vae.config.patch_size is not None:
|
||||
chunk = unpatchify(chunk, patch_size=vae.config.patch_size)
|
||||
on_chunk(torch.clamp(chunk, min=-1.0, max=1.0))
|
||||
except BaseException as exc:
|
||||
# Keep all ranks in the temporal collective loop;
|
||||
# surface the callback failure only after decode.
|
||||
callback_error = exc
|
||||
elif on_chunk is None:
|
||||
decoded_chunks.append(chunk)
|
||||
del chunk
|
||||
|
||||
if produce_output:
|
||||
if produce_output and on_chunk is None:
|
||||
out = torch.cat(decoded_chunks, dim=2)
|
||||
if vae.config.patch_size is not None:
|
||||
out = unpatchify(out, patch_size=vae.config.patch_size)
|
||||
out = torch.clamp(out, min=-1.0, max=1.0)
|
||||
else:
|
||||
out = z.new_zeros(0)
|
||||
finally:
|
||||
vae.clear_cache()
|
||||
|
||||
if callback_error is not None:
|
||||
raise callback_error
|
||||
if on_chunk is not None:
|
||||
return None
|
||||
if not produce_output:
|
||||
out = z.new_zeros(0)
|
||||
if not return_dict:
|
||||
return (out,)
|
||||
return DecoderOutput(sample=out)
|
||||
@@ -4,7 +4,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
@@ -66,6 +66,10 @@ class ForwardContext:
|
||||
# Tracks the depth of SP sharding - incremented on shard, decremented on gather
|
||||
# Used by attention layers to determine if SP communication should be enabled
|
||||
_sp_shard_depth: int = 0
|
||||
# One entry per active SP split boundary: whether it auto-pads, which makes
|
||||
# every rank's shard the same length and lets attention collectives skip a
|
||||
# runtime length all-gather. Pushed on split, popped on gather.
|
||||
_sp_equal_pad_stack: list[bool] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def sp_active(self) -> bool:
|
||||
@@ -88,6 +92,15 @@ class ForwardContext:
|
||||
sp_size = self.omni_diffusion_config.parallel_config.sequence_parallel_size
|
||||
return sp_size is not None and sp_size > 1
|
||||
|
||||
@property
|
||||
def sp_rank_local_seq_lens_equal(self) -> bool:
|
||||
"""Whether every active SP boundary guarantees equal local shard sizes.
|
||||
|
||||
Only framework-managed auto_pad boundaries provide this contract; a
|
||||
region that also shards manually keeps the dynamic length exchange.
|
||||
"""
|
||||
return bool(self._sp_equal_pad_stack) and all(self._sp_equal_pad_stack)
|
||||
|
||||
def __post_init__(self):
|
||||
pass
|
||||
|
||||
|
||||
@@ -264,6 +264,7 @@ class SequenceParallelSplitHook(ModelHook):
|
||||
|
||||
output_list = [output] if is_tensor else list(output)
|
||||
actually_sharded = False
|
||||
equal_rank_seq_lens = True
|
||||
|
||||
for index, spm in self.metadata.items():
|
||||
if not isinstance(index, int):
|
||||
@@ -277,10 +278,13 @@ class SequenceParallelSplitHook(ModelHook):
|
||||
output_list[index] = self._prepare_sp_input(original, spm, self._last_args, self._last_kwargs)
|
||||
if output_list[index] is not original:
|
||||
actually_sharded = True
|
||||
equal_rank_seq_lens &= isinstance(spm, SequenceParallelInput) and spm.auto_pad
|
||||
|
||||
# Mark SP as active only if at least one tensor was actually sharded
|
||||
if actually_sharded and is_forward_context_available():
|
||||
get_forward_context()._sp_shard_depth += 1
|
||||
ctx = get_forward_context()
|
||||
ctx._sp_shard_depth += 1
|
||||
ctx._sp_equal_pad_stack.append(equal_rank_seq_lens)
|
||||
|
||||
return output_list[0] if is_tensor else type(output)(output_list)
|
||||
|
||||
@@ -553,6 +557,8 @@ class SequenceParallelGatherHook(ModelHook):
|
||||
if actually_gathered and is_forward_context_available():
|
||||
ctx = get_forward_context()
|
||||
ctx._sp_shard_depth = max(0, ctx._sp_shard_depth - 1)
|
||||
if ctx._sp_equal_pad_stack:
|
||||
ctx._sp_equal_pad_stack.pop()
|
||||
|
||||
return output[0] if is_tensor else type(output)(output)
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,124 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Interaction coordinator to be co-owned by a pipeline and a runner."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm_omni.diffusion.interaction.registry import STRUCTURED_HANDLER_REGISTRY
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionPayload,
|
||||
merge_interaction_metadata,
|
||||
)
|
||||
from vllm_omni.diffusion.models.interface import supports_interaction_apply
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.base import InteractionHandler
|
||||
|
||||
|
||||
class InteractionCoordinator:
|
||||
"""Handles mid-way interaction inputs for one loaded pipeline.
|
||||
|
||||
Request-local session state lives on ``StepRequestState.interaction_sessions``;
|
||||
this object is request-agnostic.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
handlers: dict[str, InteractionHandler],
|
||||
*,
|
||||
model_class_name: str | None = None,
|
||||
) -> None:
|
||||
self._handlers = handlers
|
||||
self.model_class_name = model_class_name
|
||||
|
||||
@classmethod
|
||||
def build(cls, pipeline: object, od_config: OmniDiffusionConfig) -> InteractionCoordinator:
|
||||
model_class_name = od_config.model_class_name
|
||||
handlers: dict[str, InteractionHandler] = {}
|
||||
|
||||
if supports_interaction_apply(pipeline):
|
||||
for modality, handler_cls in STRUCTURED_HANDLER_REGISTRY.get(model_class_name or "", {}).items():
|
||||
handlers[modality] = handler_cls.from_pipeline(pipeline)
|
||||
|
||||
return cls(handlers, model_class_name=model_class_name)
|
||||
|
||||
def has_modality(self, modality: str) -> bool:
|
||||
return modality in self._handlers
|
||||
|
||||
@property
|
||||
def needs_chunk_media(self) -> bool:
|
||||
"""Whether any registered handler needs chunk ``num_frames``/``fps``."""
|
||||
return any(handler.needs_chunk_media for handler in self._handlers.values())
|
||||
|
||||
def get_handler(self, modality: str) -> InteractionHandler:
|
||||
handler = self._handlers.get(modality)
|
||||
if handler is None:
|
||||
raise ValueError(
|
||||
f"interaction modality {modality!r} is not supported by pipeline {self.model_class_name!r}"
|
||||
)
|
||||
return handler
|
||||
|
||||
def enqueue(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
modality: str,
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Fan out enqueue to handlers in stable order (prompt first)."""
|
||||
handler = self.get_handler(modality)
|
||||
handler.enqueue(
|
||||
state,
|
||||
event_id=event_id,
|
||||
received_at=received_at,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
|
||||
def apply_at_chunk_boundary(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
) -> InteractionChunkMetadata:
|
||||
"""Fan out chunk-boundary apply to handlers in stable order (prompt first)."""
|
||||
if chunk_index is None:
|
||||
chunk_index = state.chunk_index
|
||||
metas: list[InteractionChunkMetadata] = []
|
||||
for handler in self._handlers_in_apply_order():
|
||||
if handler.modality not in state.interaction_sessions:
|
||||
# This function is always called at chunk boundary without knowing if an interaction is really enqueued.
|
||||
# `state.interaction_sessions[this modality]` is lazy-populated after the first interaction is enqueued.
|
||||
# So, check here and skip a modality handler if this modality's session is not yet created.
|
||||
continue
|
||||
meta = handler.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=boundary_at,
|
||||
chunk_index=chunk_index,
|
||||
num_frames=num_frames,
|
||||
fps=fps,
|
||||
)
|
||||
if meta is not None:
|
||||
metas.append(meta)
|
||||
return merge_interaction_metadata(metas)
|
||||
|
||||
def _handlers_in_apply_order(self) -> list[InteractionHandler]:
|
||||
ordered: list[InteractionHandler] = []
|
||||
if "prompt" in self._handlers:
|
||||
ordered.append(self._handlers["prompt"])
|
||||
for modality, handler in self._handlers.items():
|
||||
if modality == "prompt":
|
||||
continue
|
||||
ordered.append(handler)
|
||||
return ordered
|
||||
@@ -0,0 +1,58 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Interaction-handling mixin for diffusion pipelines. Process interactions at chunk boundaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from vllm_omni.diffusion.models.interface import SupportsInteractionApply
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.interaction.coordinator import InteractionCoordinator
|
||||
|
||||
|
||||
class InteractionMixin:
|
||||
"""Unified chunk-boundary interaction hook.
|
||||
|
||||
Pipelines inherit this mixin and implement ``peek_chunk_media`` to offer playback information about the next chunk.
|
||||
Diffusion runner calls ``apply_interaction_at_chunk_boundary`` without knowing which modality is being applied.
|
||||
|
||||
Per-modality session state lives on ``StepRequestState.interaction_sessions``;
|
||||
handler strategy objects live on the pipeline/runner ``InteractionCoordinator``.
|
||||
"""
|
||||
|
||||
_interaction_coordinator: InteractionCoordinator | None = None
|
||||
|
||||
def apply_interaction_at_chunk_boundary(self, state: StepRequestState) -> None:
|
||||
"""Advance all active interaction tracks before the next chunk."""
|
||||
if self._interaction_coordinator is None:
|
||||
raise RuntimeError(
|
||||
"interaction coordinator is not initialized; "
|
||||
"DiffusionModelRunner.load_model must wire InteractionCoordinator "
|
||||
"onto the pipeline before chunked generation"
|
||||
)
|
||||
|
||||
num_frames: int | None = None
|
||||
fps: float | None = None
|
||||
if self._interaction_coordinator.needs_chunk_media:
|
||||
media = cast(SupportsInteractionApply, self).peek_chunk_media(state)
|
||||
num_frames = media.num_frames
|
||||
fps = media.fps
|
||||
|
||||
merged = self._interaction_coordinator.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=time.monotonic(),
|
||||
num_frames=num_frames,
|
||||
fps=fps,
|
||||
)
|
||||
state.interaction_chunk_metadata = merged
|
||||
|
||||
def prepare_next_chunk(self, state: StepRequestState) -> None:
|
||||
"""Set up pipeline state for the next chunk after interaction apply.
|
||||
|
||||
Default no-op. Pipelines may override this if needed.
|
||||
"""
|
||||
pass
|
||||
@@ -0,0 +1,62 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Base interaction handler interface."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import ClassVar, Self
|
||||
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionPayload,
|
||||
)
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
|
||||
class InteractionHandler(ABC):
|
||||
"""Strategy object for one interaction modality.
|
||||
|
||||
Handler instances are pipeline/runner-owned and request-agnostic. Per-request
|
||||
session state lives on ``StepRequestState.interaction_sessions``.
|
||||
Each concrete modality handler decides how to handle timing from ``received_at``.
|
||||
"""
|
||||
|
||||
modality: ClassVar[str]
|
||||
# When True, chunk-boundary apply needs ``ChunkMediaSpec`` (num_frames/fps)
|
||||
# Those information are useful when interaction handler needs interpolation/integration on a frame-by-frame basis
|
||||
needs_chunk_media: ClassVar[bool] = False
|
||||
|
||||
@classmethod
|
||||
def from_pipeline(cls, pipeline: object) -> Self:
|
||||
"""Bind a request-agnostic handler to ``pipeline`` when construction needs it.
|
||||
|
||||
Default construction ignores the pipeline. Prompt handlers override this to
|
||||
capture ``encode_prompt`` / device / dtype.
|
||||
"""
|
||||
del pipeline
|
||||
return cls()
|
||||
|
||||
@abstractmethod
|
||||
def enqueue(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Validate and queue this track on request-local state."""
|
||||
|
||||
@abstractmethod
|
||||
def apply_at_chunk_boundary(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None, # defaults to state.chunk_index when omitted
|
||||
num_frames: int | None = None, # only set when at least one interaction handler needs it
|
||||
fps: float | None = None, # only set when at least one interaction handler needs it
|
||||
) -> InteractionChunkMetadata | None:
|
||||
"""Advance request-local state and materialize this chunk's effects."""
|
||||
@@ -0,0 +1,266 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Prompt-track interaction handler (midway prompt updates)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
from typing_extensions import override
|
||||
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.base import InteractionHandler
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionEvent,
|
||||
InteractionMode,
|
||||
InteractionPayload,
|
||||
InteractionSession,
|
||||
)
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
DEFAULT_TRANSITION_CHUNKS = 3
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class QueuedPromptEvent(InteractionEvent):
|
||||
"""Last-write-wins prompt update waiting for / active at a chunk boundary.
|
||||
|
||||
``source_prompt_embeds`` is the lerp start endpoint, staged when this event
|
||||
is activated (not at enqueue). Live blended embeds live on
|
||||
``StepRequestState.prompt_embeds``.
|
||||
"""
|
||||
|
||||
mode: InteractionMode = "target"
|
||||
prompt: str
|
||||
target_prompt_embeds: torch.Tensor
|
||||
source_prompt_embeds: torch.Tensor | None = None
|
||||
|
||||
def blended_prompt_embeds(self) -> torch.Tensor:
|
||||
assert self.source_prompt_embeds is not None
|
||||
alpha = self._current_alpha()
|
||||
if alpha >= 1.0:
|
||||
return self.target_prompt_embeds
|
||||
return (1.0 - alpha) * self.source_prompt_embeds + alpha * self.target_prompt_embeds
|
||||
|
||||
def advance_transition(self) -> None:
|
||||
assert self.source_prompt_embeds is not None
|
||||
if self.transition_chunks <= 0:
|
||||
self.source_prompt_embeds = self.target_prompt_embeds
|
||||
return
|
||||
self.elapsed_transition_chunks += 1
|
||||
if self.elapsed_transition_chunks >= self.transition_chunks:
|
||||
self.source_prompt_embeds = self.target_prompt_embeds
|
||||
self.elapsed_transition_chunks = float(self.transition_chunks)
|
||||
|
||||
def _current_alpha(self) -> float:
|
||||
if self.transition_chunks <= 0:
|
||||
return 1.0
|
||||
return min(1.0, self.elapsed_transition_chunks / self.transition_chunks)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PromptSession(InteractionSession):
|
||||
"""Request-local prompt-update session under ``state.interaction_sessions['prompt']``."""
|
||||
|
||||
pending_event: QueuedPromptEvent | None = None
|
||||
active_event: QueuedPromptEvent | None = None
|
||||
version: int = 0
|
||||
|
||||
|
||||
def prompt_update_versions(states: Sequence[StepRequestState]) -> tuple[int, ...]:
|
||||
"""Return per-request prompt-update versions for batch cache comparison."""
|
||||
versions: list[int] = []
|
||||
for state in states:
|
||||
session = state.interaction_sessions.get("prompt")
|
||||
versions.append(session.version if isinstance(session, PromptSession) else 0)
|
||||
return tuple(versions)
|
||||
|
||||
|
||||
class PromptInteractionHandler(InteractionHandler):
|
||||
"""Encode-and-queue prompt updates; lerp embeds at chunk boundaries.
|
||||
|
||||
Mirrors the former ``PromptUpdateMixin`` behavior. Encoding happens at
|
||||
enqueue time via an injected ``encode_prompt`` callable.
|
||||
"""
|
||||
|
||||
modality: ClassVar[str] = "prompt"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
encode_prompt: Callable[..., tuple[torch.Tensor, ...]],
|
||||
device: torch.device | str,
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
self._encode_prompt = encode_prompt
|
||||
self._device = device
|
||||
self._dtype = dtype
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_pipeline(cls, pipeline: Any) -> PromptInteractionHandler:
|
||||
"""Build a handler from a diffusion pipeline that exposes ``encode_prompt``."""
|
||||
return cls(
|
||||
encode_prompt=pipeline.encode_prompt,
|
||||
device=pipeline.device,
|
||||
dtype=pipeline.transformer.dtype,
|
||||
)
|
||||
|
||||
@override
|
||||
def enqueue(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Prompt updates are last-write-win and unbuffered at chunk boundary."""
|
||||
prompt = payload.get("prompt")
|
||||
if not isinstance(prompt, str) or not prompt:
|
||||
raise ValueError("prompt must be non-empty")
|
||||
if not event_id:
|
||||
raise ValueError("event_id must be non-empty")
|
||||
if state.prompt_embeds is None:
|
||||
raise ValueError(
|
||||
f"prompt_update is not allowed before initial generation has started (request_id={state.request_id!r})"
|
||||
)
|
||||
duration = DEFAULT_TRANSITION_CHUNKS if transition_chunks is None else transition_chunks
|
||||
if duration < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
|
||||
target_prompt_embeds, _ = self._encode_prompt(
|
||||
prompt=prompt,
|
||||
negative_prompt=None,
|
||||
do_classifier_free_guidance=False,
|
||||
num_videos_per_prompt=state.sampling.num_outputs_per_prompt,
|
||||
max_sequence_length=state.sampling.max_sequence_length,
|
||||
device=self._device,
|
||||
dtype=self._dtype,
|
||||
)
|
||||
session = state.interaction_sessions.setdefault("prompt", PromptSession())
|
||||
assert isinstance(session, PromptSession)
|
||||
with session.lock:
|
||||
# Chunk-level LWW: replace any prior pending event.
|
||||
session.pending_event = QueuedPromptEvent(
|
||||
event_id=event_id,
|
||||
received_at=received_at,
|
||||
transition_chunks=duration,
|
||||
prompt=prompt,
|
||||
target_prompt_embeds=target_prompt_embeds,
|
||||
)
|
||||
|
||||
@override
|
||||
def apply_at_chunk_boundary(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
) -> InteractionChunkMetadata | None:
|
||||
"""Advance or start prompt interpolation before the next chunk."""
|
||||
# Prompt lerp is chunk-LWW; media timeline and caller chunk_index unused.
|
||||
del chunk_index, num_frames, fps
|
||||
session = state.interaction_sessions.get("prompt")
|
||||
assert isinstance(session, PromptSession)
|
||||
|
||||
embeds_changed = False
|
||||
next_chunk_index = state.chunk_index
|
||||
started_event_ids: list[str] = []
|
||||
active_event_ids: list[str] = []
|
||||
completed_event_ids: list[str] = []
|
||||
|
||||
with session.lock:
|
||||
# Prompt ignores frame scheduling but still records the boundary clock.
|
||||
session.last_boundary_at = boundary_at
|
||||
pending_event = session.pending_event
|
||||
session.pending_event = None
|
||||
active_event = session.active_event
|
||||
|
||||
# If current transition is not complete, advance it.
|
||||
# After completion, leave active_event in place (so a later pending
|
||||
# update can abort/overwrite), but do not keep bumping the version.
|
||||
if active_event is not None:
|
||||
in_transition = (
|
||||
active_event.transition_chunks > 0
|
||||
and active_event.elapsed_transition_chunks < active_event.transition_chunks
|
||||
)
|
||||
if in_transition:
|
||||
active_event.advance_transition()
|
||||
state.prompt_embeds = active_event.blended_prompt_embeds()
|
||||
embeds_changed = True
|
||||
active_event_ids.append(active_event.event_id)
|
||||
if active_event.elapsed_transition_chunks >= active_event.transition_chunks:
|
||||
state.prompt_embeds = active_event.target_prompt_embeds
|
||||
active_event.source_prompt_embeds = active_event.target_prompt_embeds
|
||||
completed_event_ids.append(active_event.event_id)
|
||||
logger.debug(
|
||||
"prompt_update transition complete request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
active_event.prompt,
|
||||
)
|
||||
|
||||
# If a new prompt update is pending, start a new transition.
|
||||
if pending_event is not None:
|
||||
if state.prompt_embeds is None:
|
||||
raise RuntimeError(
|
||||
"internal error: trying to apply a pending prompt update but "
|
||||
f"current prompt_embeds is None (request_id={state.request_id!r})"
|
||||
)
|
||||
# Stage lerp-start embeds at activation (after any same-boundary advance).
|
||||
pending_event.source_prompt_embeds = state.prompt_embeds.detach().clone()
|
||||
pending_event.elapsed_transition_chunks = 0.0
|
||||
session.active_event = pending_event
|
||||
active_event = pending_event
|
||||
event_id = pending_event.event_id
|
||||
duration = pending_event.transition_chunks
|
||||
prompt = pending_event.prompt
|
||||
target = pending_event.target_prompt_embeds
|
||||
started_event_ids.append(event_id)
|
||||
active_event_ids.append(event_id)
|
||||
if duration <= 0:
|
||||
# A hard/immediate transition
|
||||
state.prompt_embeds = target
|
||||
pending_event.source_prompt_embeds = target
|
||||
completed_event_ids.append(event_id)
|
||||
logger.debug(
|
||||
"prompt_update sharp transition request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
prompt,
|
||||
)
|
||||
else:
|
||||
# A transition that really takes some time
|
||||
active_event.advance_transition()
|
||||
state.prompt_embeds = active_event.blended_prompt_embeds()
|
||||
if active_event.elapsed_transition_chunks >= active_event.transition_chunks:
|
||||
state.prompt_embeds = active_event.target_prompt_embeds
|
||||
active_event.source_prompt_embeds = active_event.target_prompt_embeds
|
||||
completed_event_ids.append(event_id)
|
||||
logger.debug(
|
||||
"prompt_update transition start request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
prompt,
|
||||
)
|
||||
embeds_changed = True
|
||||
|
||||
# Indicate that prompt embeddings have changed---clear input batch cache.
|
||||
if embeds_changed:
|
||||
session.version += 1
|
||||
|
||||
return InteractionChunkMetadata(
|
||||
started_event_ids=started_event_ids,
|
||||
active_event_ids=active_event_ids,
|
||||
completed_event_ids=completed_event_ids,
|
||||
)
|
||||
@@ -0,0 +1,24 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Registry of mid-way interaction handlers during a diffusion generation.
|
||||
A pipeline only declares the modalities that it supports.
|
||||
And a pipeline can choose which handler for each modality (there can be more than one handler for a modality).
|
||||
|
||||
Outer key: pipeline architecture name (``od_config.model_class_name``).
|
||||
Inner key: modality name (e.g. ``\"prompt\"``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.base import InteractionHandler
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.prompt import PromptInteractionHandler
|
||||
|
||||
STRUCTURED_HANDLER_REGISTRY: dict[str, dict[str, type[InteractionHandler]]] = {
|
||||
# Pipeline class name -> modality -> handler class.
|
||||
"HeliosPipeline": {
|
||||
"prompt": PromptInteractionHandler,
|
||||
},
|
||||
"HeliosPyramidPipeline": {
|
||||
"prompt": PromptInteractionHandler,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Shared types for midway interaction handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
from typing import Literal
|
||||
|
||||
# Wire payload for one modality track. Handlers validate keys they need.
|
||||
InteractionPayload = Mapping[str, object]
|
||||
|
||||
# Shared command semantics across modalities that support them.
|
||||
# Prompt specialization uses ``"target"`` only.
|
||||
InteractionMode = Literal["target"]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ChunkMediaSpec:
|
||||
"""Media extent of one generation chunk, for interaction timeline mapping."""
|
||||
|
||||
num_frames: int
|
||||
fps: float
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.num_frames <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.num_frames must be > 0, got {self.num_frames}")
|
||||
if self.fps <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.fps must be > 0, got {self.fps}")
|
||||
|
||||
@property
|
||||
def duration_s(self) -> float:
|
||||
return float(self.num_frames) / float(self.fps)
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class InteractionEvent:
|
||||
"""Shared envelope for one queued or in-flight interaction command. **Intended to be subclassed**.
|
||||
|
||||
Example:
|
||||
- ``QueuedPromptEvent`` in ``vllm_omni.diffusion.interaction.modality_handlers.prompt``
|
||||
"""
|
||||
|
||||
event_id: str
|
||||
received_at: float
|
||||
mode: InteractionMode
|
||||
transition_chunks: int
|
||||
elapsed_transition_chunks: float = 0.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class InteractionSession:
|
||||
"""Request-local session base for one interaction modality. **Intended to be subclassed**.
|
||||
|
||||
Concrete modalities subclass this and store their own pending/active state.
|
||||
``last_boundary_at`` is available for frame-scheduled modalities; chunk-LWW
|
||||
modalities may ignore it.
|
||||
|
||||
Example:
|
||||
- ``PromptSession`` in ``vllm_omni.diffusion.interaction.modality_handlers.prompt``
|
||||
"""
|
||||
|
||||
lock: Lock = field(default_factory=Lock, repr=False)
|
||||
last_boundary_at: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class InteractionChunkMetadata:
|
||||
"""Per-modality (or merged) event-id bookkeeping for one chunk boundary."""
|
||||
|
||||
started_event_ids: list[str] = field(default_factory=list)
|
||||
active_event_ids: list[str] = field(default_factory=list)
|
||||
completed_event_ids: list[str] = field(default_factory=list)
|
||||
|
||||
def as_dict(self) -> dict[str, list[str]]:
|
||||
return {
|
||||
"started_event_ids": list(self.started_event_ids),
|
||||
"active_event_ids": list(self.active_event_ids),
|
||||
"completed_event_ids": list(self.completed_event_ids),
|
||||
}
|
||||
|
||||
|
||||
def merge_interaction_metadata(
|
||||
metas: list[InteractionChunkMetadata],
|
||||
) -> InteractionChunkMetadata:
|
||||
"""Merge per-handler metadata while preserving order and de-duplicating ids."""
|
||||
started: list[str] = []
|
||||
active: list[str] = []
|
||||
completed: list[str] = []
|
||||
seen_started: set[str] = set()
|
||||
seen_active: set[str] = set()
|
||||
seen_completed: set[str] = set()
|
||||
for meta in metas:
|
||||
for event_id in meta.started_event_ids:
|
||||
if event_id not in seen_started:
|
||||
seen_started.add(event_id)
|
||||
started.append(event_id)
|
||||
for event_id in meta.active_event_ids:
|
||||
if event_id not in seen_active:
|
||||
seen_active.add(event_id)
|
||||
active.append(event_id)
|
||||
for event_id in meta.completed_event_ids:
|
||||
if event_id not in seen_completed:
|
||||
seen_completed.add(event_id)
|
||||
completed.append(event_id)
|
||||
return InteractionChunkMetadata(
|
||||
started_event_ids=started,
|
||||
active_event_ids=active,
|
||||
completed_event_ids=completed,
|
||||
)
|
||||
@@ -1,3 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from importlib import import_module
|
||||
from importlib.util import find_spec
|
||||
|
||||
import torch
|
||||
@@ -98,6 +102,7 @@ class RotaryEmbedding(CustomOp):
|
||||
self.interleaved = not is_neox_style
|
||||
self.half_head_dim = half_head_dim
|
||||
self.apply_rotary_emb_flash_attn = None
|
||||
self.apply_rotary_emb_vllm_flash_attn = None
|
||||
self.has_mindie = False
|
||||
# ``find_spec("flash_attn")`` is True as long as *any* package publishes
|
||||
# the ``flash_attn`` namespace — including ``flash-attn-4``, which ships
|
||||
@@ -111,6 +116,17 @@ class RotaryEmbedding(CustomOp):
|
||||
self.apply_rotary_emb_flash_attn = apply_rotary
|
||||
except ImportError:
|
||||
pass
|
||||
# CUDA wheels vendor this kernel under vllm_flash_attn, while source
|
||||
# and CPU-only installations may not contain the generated package.
|
||||
# Resolve it lazily and retain the native implementation as a portable
|
||||
# fallback for those environments.
|
||||
if current_omni_platform.is_cuda():
|
||||
try:
|
||||
self.apply_rotary_emb_vllm_flash_attn = import_module(
|
||||
"vllm.vllm_flash_attn.layers.rotary"
|
||||
).apply_rotary_emb
|
||||
except ImportError:
|
||||
pass
|
||||
if find_spec("mindiesd") is not None:
|
||||
self.has_mindie = True
|
||||
|
||||
@@ -135,12 +151,18 @@ class RotaryEmbedding(CustomOp):
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
from vllm.vllm_flash_attn.layers.rotary import apply_rotary_emb
|
||||
|
||||
cos, sin = self._prepare_half_head_dim_cos_sin(cos, sin)
|
||||
|
||||
if self.apply_rotary_emb_vllm_flash_attn is None:
|
||||
return apply_rotary_emb_torch(
|
||||
x,
|
||||
cos,
|
||||
sin,
|
||||
interleaved=self.interleaved,
|
||||
)
|
||||
|
||||
x, squeezed = _ensure_batch_dim(x)
|
||||
output = apply_rotary_emb(
|
||||
output = self.apply_rotary_emb_vllm_flash_attn(
|
||||
x,
|
||||
cos,
|
||||
sin,
|
||||
@@ -231,13 +253,14 @@ class RotaryEmbeddingWan(RotaryEmbedding):
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
from vllm.vllm_flash_attn.layers.rotary import apply_rotary_emb
|
||||
if self.apply_rotary_emb_vllm_flash_attn is None:
|
||||
return self.forward_native(x, cos, sin)
|
||||
|
||||
if cos.dim() > 2:
|
||||
cos = cos.reshape(-1, cos.shape[-1])
|
||||
sin = sin.reshape(-1, sin.shape[-1])
|
||||
|
||||
return apply_rotary_emb(
|
||||
return self.apply_rotary_emb_vllm_flash_attn(
|
||||
x,
|
||||
cos,
|
||||
sin,
|
||||
|
||||
@@ -25,6 +25,9 @@ class DiffusionBaseLinearLayerWithLoRA(BaseLinearLayerWithLoRA):
|
||||
lora_a_stacked: tuple[torch.Tensor, ...]
|
||||
lora_b_stacked: tuple[torch.Tensor, ...]
|
||||
|
||||
# Mask saved while the adapter is suspended; None means "not suspended".
|
||||
_diffusion_lora_suspended_slices: tuple[bool, ...] | None = None
|
||||
|
||||
def _move_lora_buffers(self, device: torch.device) -> None:
|
||||
self.lora_a_stacked = tuple(tensor.to(device=device) for tensor in self.lora_a_stacked)
|
||||
self.lora_b_stacked = tuple(tensor.to(device=device) for tensor in self.lora_b_stacked)
|
||||
@@ -54,11 +57,14 @@ class DiffusionBaseLinearLayerWithLoRA(BaseLinearLayerWithLoRA):
|
||||
object.__setattr__(self, "_diffusion_base_layer_ref", base_layer)
|
||||
n_slices = getattr(self, "n_slices", 1)
|
||||
self._diffusion_lora_active_slices = (False,) * int(n_slices)
|
||||
self._diffusion_lora_suspended_slices = None
|
||||
|
||||
def reset_lora(self, index: int):
|
||||
super().reset_lora(index)
|
||||
n_slices = getattr(self, "n_slices", 1)
|
||||
self._diffusion_lora_active_slices = (False,) * int(n_slices)
|
||||
# The upload is gone, so a saved mask no longer describes the buffers.
|
||||
self._diffusion_lora_suspended_slices = None
|
||||
|
||||
def set_lora(
|
||||
self,
|
||||
@@ -82,6 +88,30 @@ class DiffusionBaseLinearLayerWithLoRA(BaseLinearLayerWithLoRA):
|
||||
# Single-slice layer.
|
||||
self._diffusion_lora_active_slices = (True,)
|
||||
|
||||
def suspend_lora(self) -> None:
|
||||
"""Gate every slice off without dropping the uploaded weights.
|
||||
|
||||
`apply()` reads the stacked buffers only for slices this mask marks
|
||||
active, so a suspended adapter costs nothing while staying resident.
|
||||
A saved mask means the layer is already suspended; keep the original
|
||||
rather than overwriting it with the all-False mask now in place.
|
||||
"""
|
||||
if self._diffusion_lora_suspended_slices is not None:
|
||||
return
|
||||
self._diffusion_lora_suspended_slices = self._diffusion_lora_active_slices
|
||||
self._diffusion_lora_active_slices = (False,) * len(self._diffusion_lora_active_slices)
|
||||
|
||||
def resume_lora(self) -> None:
|
||||
"""Restore the mask captured by `suspend_lora()`.
|
||||
|
||||
A layer registered after the suspend, or one whose buffers were torn
|
||||
down meanwhile, has no mask to restore and keeps its own inactive one.
|
||||
"""
|
||||
saved = self._diffusion_lora_suspended_slices
|
||||
if saved is not None:
|
||||
self._diffusion_lora_active_slices = saved
|
||||
self._diffusion_lora_suspended_slices = None
|
||||
|
||||
def apply(self, x: torch.Tensor, bias: torch.Tensor | None = None) -> torch.Tensor:
|
||||
"""
|
||||
override: Use simple matmul instead of punica_wrapper.add_lora_linear().
|
||||
|
||||
@@ -10,11 +10,11 @@ from diffusers.loaders.lora_conversion_utils import (
|
||||
_convert_non_diffusers_qwen_lora_to_diffusers,
|
||||
_convert_non_diffusers_wan_lora_to_diffusers,
|
||||
)
|
||||
from huggingface_hub import hf_hub_download
|
||||
from safetensors.torch import load_file
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.utils.tf_utils import get_transformer_from_pipeline
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -131,7 +131,7 @@ def _load_lora_state_dict(
|
||||
|
||||
# finally, we try to load it from the internet
|
||||
try:
|
||||
model_file = hf_hub_download(
|
||||
model_file = hf_api().hf_hub_download(
|
||||
pretrained_model_name_or_path,
|
||||
filename=weights_name,
|
||||
subfolder=subfolder,
|
||||
|
||||
@@ -48,6 +48,11 @@ class DiffusionLoRAManager:
|
||||
# Valid max allowed ranks for LoRA in vLLM
|
||||
_VALID_MAX_RANKS: list[int] = sorted(get_args(MaxLoRARanks))
|
||||
|
||||
# Adapter whose weights are still uploaded while gated off. Class-level so
|
||||
# a manager built without __init__ (some tests use object.__new__) reads as
|
||||
# "nothing suspended" instead of raising.
|
||||
_suspended_adapter_id: int | None = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pipeline: nn.Module,
|
||||
@@ -493,9 +498,11 @@ class DiffusionLoRAManager:
|
||||
fully_sharded_loras=False,
|
||||
)
|
||||
|
||||
# Recreate per-layer buffers with the new maximum rank.
|
||||
# Recreate per-layer buffers with the new maximum rank. The previous
|
||||
# upload is gone, so nothing may be re-armed afterwards.
|
||||
for lora_layer in self._lora_modules.values():
|
||||
lora_layer.create_lora_weights(max_loras=1, lora_config=lora_config, model_config=None)
|
||||
self._suspended_adapter_id = None
|
||||
|
||||
# Re-apply active adapter if needed (buffers were reset).
|
||||
if self._active_adapter_id is not None:
|
||||
@@ -679,18 +686,32 @@ class DiffusionLoRAManager:
|
||||
def _reset_lora_layers(self) -> None:
|
||||
for lora_layer in self._lora_modules.values():
|
||||
lora_layer.reset_lora(0)
|
||||
self._suspended_adapter_id = None
|
||||
|
||||
def _activate_adapter(self, adapter_id: int, scale: float) -> None:
|
||||
if self._is_active_at_scale(adapter_id, scale):
|
||||
logger.debug("Adapter %d already active at scale %.3f skipping", adapter_id, scale)
|
||||
return
|
||||
|
||||
if self._suspended_adapter_id == adapter_id and self._adapter_scales.get(
|
||||
adapter_id
|
||||
) == DiffusionLoRAManager._get_rounded_scale(scale):
|
||||
# Weights are still uploaded from an earlier activation; re-arming
|
||||
# the masks avoids rebuilding and re-uploading every layer.
|
||||
for lora_layer in self._lora_modules.values():
|
||||
lora_layer.resume_lora()
|
||||
self._suspended_adapter_id = None
|
||||
self._active_adapter_id = adapter_id
|
||||
logger.debug("Re-armed suspended adapter %d", adapter_id)
|
||||
return
|
||||
|
||||
logger.info("Activating adapter: id=%d", adapter_id)
|
||||
lora_model = self._registered_adapters[adapter_id]
|
||||
# Binding overwrites slot 0 incrementally. Invalidate the fast-path
|
||||
# state before the first mutation and leave every wrapper inactive if
|
||||
# any set_lora() call or model validator fails.
|
||||
self._active_adapter_id = None
|
||||
self._suspended_adapter_id = None
|
||||
try:
|
||||
self._bind_adapter_weights(lora_model, scale)
|
||||
except Exception:
|
||||
@@ -704,8 +725,10 @@ class DiffusionLoRAManager:
|
||||
if self._active_adapter_id is None:
|
||||
logger.debug("All adapters already inactive")
|
||||
return
|
||||
logger.info("Deactivating all adapters: %d layers", len(self._lora_modules))
|
||||
self._reset_lora_layers()
|
||||
logger.info("Suspending all adapters: %d layers", len(self._lora_modules))
|
||||
for lora_layer in self._lora_modules.values():
|
||||
lora_layer.suspend_lora()
|
||||
self._suspended_adapter_id = self._active_adapter_id
|
||||
self._active_adapter_id = None
|
||||
logger.debug("All adapters deactivated")
|
||||
|
||||
@@ -772,6 +795,11 @@ class DiffusionLoRAManager:
|
||||
if self._active_adapter_id == adapter_id:
|
||||
self._deactivate_all_adapters()
|
||||
|
||||
if self._suspended_adapter_id == adapter_id:
|
||||
# The adapter is going away, so the upload can never be resumed.
|
||||
# Tear it down instead of leaving it in the stacked buffers.
|
||||
self._reset_lora_layers()
|
||||
|
||||
del self._registered_adapters[adapter_id]
|
||||
self._adapter_scales.pop(adapter_id, None)
|
||||
self._adapter_access_order.pop(adapter_id, None)
|
||||
|
||||
@@ -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
|
||||
|
||||
"""Best-effort HuggingFace Hub prefetch for multi-subfolder pipelines.
|
||||
|
||||
@@ -297,7 +297,7 @@ def prefetch_subfolders(
|
||||
logger.info("Prefetching %s subfolders: %s", model, subfolders)
|
||||
|
||||
try:
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
except ImportError: # pragma: no cover - huggingface_hub is a hard dep
|
||||
logger.debug("huggingface_hub unavailable; skipping prefetch of %s", model)
|
||||
return
|
||||
@@ -334,7 +334,7 @@ def prefetch_subfolders(
|
||||
for attempt in range(1, _PREFETCH_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
with _repo_prefetch_lock(model):
|
||||
snapshot_download(
|
||||
hf_api().snapshot_download(
|
||||
repo_id=model,
|
||||
revision=revision,
|
||||
allow_patterns=allow_patterns,
|
||||
|
||||
@@ -11,6 +11,10 @@ class DiffusionModelMetadata:
|
||||
supports_multimodal_inputs: bool = False
|
||||
max_multimodal_image_inputs: int | None = None
|
||||
supports_mixed_reference_inputs: bool = False
|
||||
# Multipart controls are exposed as ``control_reference`` plus
|
||||
# ``control_type`` by the video API. A pipeline that opts in receives the
|
||||
# persisted upload through ``extra_args[control_type]["control_path"]``.
|
||||
supported_control_upload_types: tuple[str, ...] = ()
|
||||
attention_mask_free: bool = False
|
||||
final_output_type: str | None = None
|
||||
|
||||
@@ -48,12 +52,16 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
attention_mask_free=True,
|
||||
),
|
||||
# The modular alias is served by MiniMaxH3Pipeline and has the same
|
||||
# Ref2VA request contract. Keep admission limits in sync with it.
|
||||
# Ref2VA request contract and packed-sequence layout. Every field must stay
|
||||
# in sync with it: the repository root ``model_index.json`` declares this
|
||||
# alias, so serving the checkpoint by repo id resolves here rather than to
|
||||
# ``MiniMaxH3Pipeline``.
|
||||
"MiniMaxH3ModularPipeline": DiffusionModelMetadata(
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=9,
|
||||
supports_mixed_reference_inputs=True,
|
||||
final_output_type="video",
|
||||
attention_mask_free=True,
|
||||
),
|
||||
"Magi2Pipeline": DiffusionModelMetadata(
|
||||
supports_multimodal_inputs=True,
|
||||
@@ -90,8 +98,14 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
"LongCatVideoAvatarPipeline": DiffusionModelMetadata(final_output_type="video"),
|
||||
"MagiHumanPipeline": DiffusionModelMetadata(final_output_type="video"),
|
||||
"DreamIDOmniPipeline": DiffusionModelMetadata(final_output_type="video"),
|
||||
"Cosmos3OmniDiffusersPipeline": DiffusionModelMetadata(final_output_type="video"),
|
||||
"Cosmos3OmniPipeline": DiffusionModelMetadata(final_output_type="video"),
|
||||
"Cosmos3OmniDiffusersPipeline": DiffusionModelMetadata(
|
||||
supported_control_upload_types=("edge", "blur", "depth", "seg", "wsm"),
|
||||
final_output_type="video",
|
||||
),
|
||||
"Cosmos3OmniPipeline": DiffusionModelMetadata(
|
||||
supported_control_upload_types=("edge", "blur", "depth", "seg", "wsm"),
|
||||
final_output_type="video",
|
||||
),
|
||||
"SanaVideoPipeline": DiffusionModelMetadata(final_output_type="video"),
|
||||
"SanaImageToVideoPipeline": DiffusionModelMetadata(final_output_type="video"),
|
||||
"SanaWmPipeline": DiffusionModelMetadata(
|
||||
@@ -107,6 +121,7 @@ _DIFFUSION_MODEL_METADATA_ALIASES = {
|
||||
"LTX2DistilledOneStagePipeline": "LTX2DistilledPipeline",
|
||||
"LTX2DistilledTwoStagePipeline": "LTX2DistilledPipeline",
|
||||
"LingBotWorldCausalDMDPipeline": "LingBotVideoPipeline",
|
||||
"BooguImageTurboPipeline": "BooguImagePipeline",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.models.utils import make_attention_mask
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -1554,17 +1555,11 @@ class BooguImageTransformer2DModel(nn.Module):
|
||||
img_hidden_states = combined_img_hidden_states
|
||||
|
||||
# Joint mask for [instruct + image].
|
||||
max_seq_len = max(seq_lengths)
|
||||
joint_attention_mask = hidden_states.new_zeros(batch_size, max_seq_len, dtype=torch.bool)
|
||||
for i, seq_len in enumerate(seq_lengths):
|
||||
joint_attention_mask[i, :seq_len] = True
|
||||
joint_attention_mask = make_attention_mask(hidden_states, seq_lengths)
|
||||
|
||||
# Dual-stream (double-stream) stage.
|
||||
if self.num_double_stream_layers > 0:
|
||||
max_img_len = max(combined_img_seq_lengths)
|
||||
img_attention_mask = hidden_states.new_zeros(batch_size, max_img_len, dtype=torch.bool)
|
||||
for i, img_seq_len in enumerate(combined_img_seq_lengths):
|
||||
img_attention_mask[i, :img_seq_len] = True
|
||||
img_attention_mask = make_attention_mask(hidden_states, combined_img_seq_lengths)
|
||||
|
||||
for layer in self.double_stream_layers:
|
||||
img_hidden_states, instruct_hidden_states = layer(
|
||||
|
||||
@@ -3522,7 +3522,12 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
control_chunks_per_hint[key].append(control[:, :, current_conditional_frames:])
|
||||
|
||||
if not is_output_rank:
|
||||
return DiffusionOutput(output={"video": output_video}, custom_output={"fps": frame_rate})
|
||||
return DiffusionOutput(
|
||||
output={
|
||||
"payload": {"video": output_video},
|
||||
"metadata": {"video": {"fps": frame_rate}},
|
||||
},
|
||||
)
|
||||
|
||||
full_output = torch.cat(output_chunks, dim=2)[:, :, :total_frames]
|
||||
full_controls = {
|
||||
|
||||
@@ -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
|
||||
"""Cosmos3 sound tokenizer integration.
|
||||
|
||||
The tokenizer decodes model-generated sound latents for video+audio output. It
|
||||
@@ -338,9 +338,9 @@ class Cosmos3SoundTokenizer:
|
||||
|
||||
model_root = str(model_path) if model_path and os.path.isdir(model_path) else None
|
||||
if model_root is None and model_path and not explicit_avae_path:
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
model_root = snapshot_download(
|
||||
model_root = hf_api().snapshot_download(
|
||||
repo_id=str(model_path),
|
||||
revision=getattr(od_config, "revision", None),
|
||||
allow_patterns=[
|
||||
|
||||
@@ -439,9 +439,9 @@ def uint8_cthw_to_normalized_5d(frames: torch.Tensor, *, dtype: torch.dtype) ->
|
||||
|
||||
def _pil_to_uint8_rgb(value: Any) -> np.ndarray:
|
||||
if isinstance(value, PIL.Image.Image):
|
||||
return np.asarray(value.convert("RGB"), dtype=np.uint8)
|
||||
return np.array(value.convert("RGB"), dtype=np.uint8, copy=True)
|
||||
if isinstance(value, str | Path):
|
||||
return np.asarray(PIL.Image.open(value).convert("RGB"), dtype=np.uint8)
|
||||
return np.array(PIL.Image.open(value).convert("RGB"), dtype=np.uint8, copy=True)
|
||||
if isinstance(value, torch.Tensor):
|
||||
tensor = value.detach().cpu()
|
||||
if tensor.ndim == 3 and tensor.shape[0] in (3, 4):
|
||||
|
||||
@@ -705,7 +705,21 @@ class Cosmos3CrossAttention(nn.Module):
|
||||
# standard reverse-all-to-all path (no joint-output splitting).
|
||||
joint_q = q.new_empty(B, 0, self.num_heads_local, self.head_dim)
|
||||
|
||||
gen_mask = None
|
||||
joint_mask = None
|
||||
if is_forward_context_available():
|
||||
ctx = get_forward_context()
|
||||
if ctx.sp_original_seq_len is not None and ctx.sp_padding_size > 0:
|
||||
padded_seq_len = ctx.sp_original_seq_len + ctx.sp_padding_size
|
||||
gen_mask = torch.ones(B, padded_seq_len, dtype=torch.bool, device=q.device)
|
||||
gen_mask[:, ctx.sp_original_seq_len :] = False
|
||||
# UND K/V are trimmed to the common real text length before GEN
|
||||
# attention, so every remaining joint key is valid.
|
||||
joint_mask = torch.ones(B, k_und.shape[1], dtype=torch.bool, device=q.device)
|
||||
|
||||
attn_metadata = AttentionMetadata(
|
||||
attn_mask=gen_mask,
|
||||
joint_attn_mask=joint_mask,
|
||||
joint_query=joint_q,
|
||||
joint_key=k_und,
|
||||
joint_value=v_und,
|
||||
@@ -1055,6 +1069,13 @@ class Cosmos3GenSPPrepare(nn.Module):
|
||||
freqs_cos: torch.Tensor,
|
||||
freqs_sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
# A transfer denoising step may run a full-control branch followed by a
|
||||
# shorter no-control branch in one ForwardContext. Auto-padding metadata
|
||||
# belongs to one branch only and must not truncate a later gather.
|
||||
if is_forward_context_available():
|
||||
ctx = get_forward_context()
|
||||
ctx.sp_padding_size = 0
|
||||
ctx.sp_original_seq_len = None
|
||||
return hidden_gen, freqs_cos, freqs_sin
|
||||
|
||||
|
||||
@@ -1112,9 +1133,9 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
|
||||
_sp_plan = {
|
||||
"gen_sp_prepare": {
|
||||
0: SequenceParallelInput(split_dim=1, expected_dims=3, split_output=True),
|
||||
1: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True),
|
||||
2: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True),
|
||||
0: SequenceParallelInput(split_dim=1, expected_dims=3, split_output=True, auto_pad=True),
|
||||
1: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True, auto_pad=True),
|
||||
2: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True, auto_pad=True),
|
||||
},
|
||||
"gen_sp_gather": SequenceParallelOutput(gather_dim=1, expected_dims=3),
|
||||
}
|
||||
@@ -1586,47 +1607,6 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
self.cached_kv = None
|
||||
self.cached_freqs_gen = None
|
||||
|
||||
@staticmethod
|
||||
def _validate_gen_sequence_parallel(
|
||||
*,
|
||||
s_gen: int,
|
||||
s_video: int,
|
||||
s_control: int,
|
||||
s_action: int,
|
||||
s_sound: int,
|
||||
has_action: bool,
|
||||
has_sound: bool,
|
||||
has_control: bool,
|
||||
ulysses_size: int,
|
||||
) -> None:
|
||||
if ulysses_size <= 1 or s_gen % ulysses_size == 0:
|
||||
return
|
||||
|
||||
detail_parts = []
|
||||
if has_control:
|
||||
detail_parts.append(f"control tokens {s_control}")
|
||||
detail_parts.append(f"video tokens {s_video}")
|
||||
if has_action:
|
||||
detail_parts.append(f"action tokens {s_action}")
|
||||
if has_sound:
|
||||
detail_parts.append(f"sound tokens {s_sound}")
|
||||
detail = " = " + " + ".join(detail_parts) if len(detail_parts) > 1 else ""
|
||||
adjust_detail = (
|
||||
"Adjust the spatial resolution, frame count, action chunk size, "
|
||||
"sound duration, or sound latent FPS so the combined media sequence is a "
|
||||
"multiple of ulysses_degree."
|
||||
if has_control or has_action or has_sound
|
||||
else (
|
||||
"Adjust the spatial resolution so that "
|
||||
"t * ceil(h/patch) * ceil(w/patch) is a multiple "
|
||||
"of ulysses_degree."
|
||||
)
|
||||
)
|
||||
raise ValueError(
|
||||
f"GEN sequence length ({s_gen}{detail}) must be divisible by "
|
||||
f"ulysses_degree ({ulysses_size}). {adjust_detail}"
|
||||
)
|
||||
|
||||
def sound_latent_frames_for_sequence_parallel(
|
||||
self,
|
||||
*,
|
||||
@@ -1907,17 +1887,6 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
# framework Attention handles the Ulysses head-slicing internally.
|
||||
if self.cached_kv is None or self.cached_freqs_gen is None:
|
||||
raise RuntimeError("Cosmos3 GEN cache was not initialized before running GEN layers.")
|
||||
self._validate_gen_sequence_parallel(
|
||||
s_gen=hidden_gen.shape[1],
|
||||
s_video=s_video,
|
||||
s_control=s_control,
|
||||
s_action=s_action,
|
||||
s_sound=s_sound,
|
||||
has_action=has_action,
|
||||
has_sound=has_sound,
|
||||
has_control=has_control,
|
||||
ulysses_size=1 if use_multi_control_attention else ulysses_size,
|
||||
)
|
||||
freqs_cos, freqs_sin = self.cached_freqs_gen
|
||||
if not use_multi_control_attention:
|
||||
hidden_gen, freqs_cos, freqs_sin = self.gen_sp_prepare(hidden_gen, freqs_cos, freqs_sin)
|
||||
|
||||
@@ -21,7 +21,6 @@ from contextlib import contextmanager
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from huggingface_hub import hf_hub_download
|
||||
from transformers import AutoTokenizer, UMT5Config, UMT5EncoderModel
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
@@ -67,6 +66,7 @@ from vllm_omni.experimental.world_models.session_state import (
|
||||
resolve_session_state_config,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
MAX_DREAMZERO_SESSIONS = 64
|
||||
@@ -581,7 +581,7 @@ class DreamZeroPipeline(nn.Module, CFGParallelMixin):
|
||||
return json.load(f)
|
||||
|
||||
try:
|
||||
json_path = hf_hub_download(model_path, relative_path)
|
||||
json_path = hf_api().hf_hub_download(model_path, relative_path)
|
||||
with open(json_path) as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import logging
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
@@ -138,26 +137,22 @@ class Gr00tN1d7ActionHead(nn.Module):
|
||||
state_features: [B, state_horizon, input_embedding_dim]
|
||||
embodiment_id: [B] (embodiment IDs)
|
||||
backbone_output: Output from the backbone model
|
||||
options: ``generator`` (a ``torch.Generator`` on the model device) draws
|
||||
the initial action noise; ``None`` leaves ``torch.randn`` on the
|
||||
global RNG, as upstream Isaac-GR00T does. The ``rtc_*`` keys drive
|
||||
real-time chunking when ``action_input`` carries a previous chunk.
|
||||
"""
|
||||
vl_embeds = backbone_features
|
||||
|
||||
batch_size = vl_embeds.shape[0]
|
||||
device = vl_embeds.device
|
||||
_seed_env = os.environ.get("GR00T_NOISE_SEED")
|
||||
if _seed_env is not None:
|
||||
_gen = torch.Generator(device=device).manual_seed(int(_seed_env))
|
||||
actions = torch.randn(
|
||||
size=(batch_size, self.config.action_horizon, self.action_dim),
|
||||
dtype=vl_embeds.dtype,
|
||||
device=device,
|
||||
generator=_gen,
|
||||
)
|
||||
else:
|
||||
actions = torch.randn(
|
||||
size=(batch_size, self.config.action_horizon, self.action_dim),
|
||||
dtype=vl_embeds.dtype,
|
||||
device=device,
|
||||
)
|
||||
generator = options.get("generator") if options else None
|
||||
actions = torch.randn(
|
||||
size=(batch_size, self.config.action_horizon, self.action_dim),
|
||||
dtype=vl_embeds.dtype,
|
||||
device=device,
|
||||
generator=generator,
|
||||
)
|
||||
|
||||
dt = 1.0 / self.num_inference_timesteps
|
||||
vel_strength = torch.ones_like(actions)
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -46,20 +47,119 @@ class LetterBoxTransform:
|
||||
return transforms.functional.pad(img, padding=[pad_left, pad_top, pad_right, pad_bottom], fill=0)
|
||||
|
||||
|
||||
def _smallest_edge_resize(image: np.ndarray, max_size: int) -> np.ndarray:
|
||||
"""albumentations 1.4.18 ``SmallestMaxSize(max_size, interpolation=cv2.INTER_AREA)``.
|
||||
|
||||
Scale off the shortest edge, skip entirely at scale 1.0, round each dimension
|
||||
independently; ``cv2.resize`` takes ``dsize`` as ``(width, height)``.
|
||||
"""
|
||||
import cv2
|
||||
|
||||
height, width = image.shape[:2]
|
||||
scale = max_size / float(min(height, width))
|
||||
if scale == 1.0:
|
||||
return image
|
||||
new_height, new_width = (round(dim * scale) for dim in (height, width))
|
||||
if (new_height, new_width) == (height, width):
|
||||
return image
|
||||
return cv2.resize(image, dsize=(new_width, new_height), interpolation=cv2.INTER_AREA)
|
||||
|
||||
|
||||
def _fractional_center_crop(image: np.ndarray, fraction: float) -> np.ndarray:
|
||||
"""Isaac-GR00T ``FractionalCenterCrop``: ``int()`` truncation (not rounding), floor 1, centred."""
|
||||
height, width = image.shape[:2]
|
||||
crop_height = max(1, int(height * fraction))
|
||||
crop_width = max(1, int(width * fraction))
|
||||
y_min = (height - crop_height) // 2
|
||||
x_min = (width - crop_width) // 2
|
||||
return image[y_min : y_min + crop_height, x_min : x_min + crop_width]
|
||||
|
||||
|
||||
def _letter_box_pad(image: np.ndarray) -> np.ndarray:
|
||||
"""Isaac-GR00T ``LetterBoxPad``: zero-pad to square, centred, remainder on the far side."""
|
||||
import cv2
|
||||
|
||||
height, width = image.shape[:2]
|
||||
if height == width:
|
||||
return image
|
||||
longest = max(height, width)
|
||||
pad_h, pad_w = longest - height, longest - width
|
||||
top, left = pad_h // 2, pad_w // 2
|
||||
return cv2.copyMakeBorder(image, top, pad_h - top, left, pad_w - left, cv2.BORDER_CONSTANT, value=0)
|
||||
|
||||
|
||||
class AlbumentationsEvalImageTransform:
|
||||
"""Eval transform of the Isaac-GR00T ``use_albumentations=True`` recipe, without albumentations.
|
||||
|
||||
``[LetterBoxPad] -> SmallestMaxSize(INTER_AREA) -> FractionalCenterCrop -> SmallestMaxSize(INTER_AREA)``,
|
||||
transcribed from the eval branch of Isaac-GR00T ``build_image_transformations_albumentations`` and
|
||||
albumentations 1.4.18, so a checkpoint trained with that recipe sees the same pixels at inference.
|
||||
Per frame: HWC uint8 RGB array in, ``(C, H, W)`` uint8 tensor out (the ``_get_vlm_inputs`` contract).
|
||||
"""
|
||||
|
||||
def __init__(self, max_size: int, fraction: float, letter_box_transform: bool):
|
||||
self.max_size = int(max_size)
|
||||
self.fraction = float(fraction)
|
||||
self.letter_box_transform = letter_box_transform
|
||||
|
||||
def __call__(self, image: np.ndarray) -> torch.Tensor:
|
||||
array = np.asarray(image)
|
||||
if array.dtype != np.uint8 or array.ndim != 3 or array.shape[2] != 3:
|
||||
raise ValueError(
|
||||
"GR00T eval image transform expects an HWC uint8 RGB frame, "
|
||||
f"got shape={tuple(array.shape)} dtype={array.dtype}"
|
||||
)
|
||||
if self.letter_box_transform:
|
||||
array = _letter_box_pad(array)
|
||||
array = _smallest_edge_resize(array, self.max_size)
|
||||
array = _fractional_center_crop(array, self.fraction)
|
||||
array = _smallest_edge_resize(array, self.max_size)
|
||||
# The crop is a non-contiguous view; the caller stacks frames right after this.
|
||||
return torch.from_numpy(np.ascontiguousarray(array)).permute(2, 0, 1)
|
||||
|
||||
|
||||
def _build_eval_image_transform(
|
||||
image_target_size: list[int],
|
||||
image_crop_size: list[int],
|
||||
) -> transforms.Compose:
|
||||
"""Deterministic eval/inference image transform (letterbox → resize → centercrop → resize)."""
|
||||
return transforms.Compose(
|
||||
*,
|
||||
shortest_image_edge: int | None = None,
|
||||
crop_fraction: float | None = None,
|
||||
use_albumentations: bool = False,
|
||||
letter_box_transform: bool = False,
|
||||
) -> Callable[[np.ndarray], torch.Tensor]:
|
||||
"""Deterministic eval/inference image transform, selected the way Isaac-GR00T's processor does.
|
||||
|
||||
``use_albumentations=True``: ``[letterbox] -> resize (shortest edge) -> fractional centre crop -> resize``
|
||||
(:class:`AlbumentationsEvalImageTransform`). Otherwise the torchvision recipe
|
||||
``[letterbox] -> resize -> centre crop -> resize``. Letterboxing is gated by ``letter_box_transform``
|
||||
on both paths.
|
||||
"""
|
||||
if use_albumentations:
|
||||
if crop_fraction is None:
|
||||
if image_crop_size is None or image_target_size is None:
|
||||
raise ValueError("image_crop_size and image_target_size are required when crop_fraction is None")
|
||||
fraction = image_crop_size[0] / image_target_size[0]
|
||||
else:
|
||||
fraction = crop_fraction
|
||||
if shortest_image_edge is None:
|
||||
if image_target_size is None:
|
||||
raise ValueError("image_target_size is required when shortest_image_edge is None")
|
||||
max_size = image_target_size[0]
|
||||
else:
|
||||
max_size = shortest_image_edge
|
||||
return AlbumentationsEvalImageTransform(max_size, fraction, letter_box_transform)
|
||||
|
||||
steps: list[Callable[..., torch.Tensor]] = [transforms.ToImage()]
|
||||
if letter_box_transform:
|
||||
steps.append(LetterBoxTransform())
|
||||
steps.extend(
|
||||
[
|
||||
transforms.ToImage(),
|
||||
LetterBoxTransform(),
|
||||
transforms.Resize(size=image_target_size),
|
||||
transforms.CenterCrop(size=image_crop_size),
|
||||
transforms.Resize(size=image_target_size),
|
||||
]
|
||||
)
|
||||
return transforms.Compose(steps)
|
||||
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -191,6 +291,9 @@ class Gr00tN1d7Processor(ProcessorMixin):
|
||||
exclude_state: bool = False,
|
||||
# Normalization
|
||||
use_mean_std: bool = False,
|
||||
# Image pipeline selection; must match the recipe the checkpoint was trained with
|
||||
use_albumentations: bool = False,
|
||||
letter_box_transform: bool = False,
|
||||
**kwargs, # absorb deprecated training-only keys from saved processor_config.json
|
||||
):
|
||||
if transformers_loading_kwargs is None:
|
||||
@@ -237,6 +340,8 @@ class Gr00tN1d7Processor(ProcessorMixin):
|
||||
self.embodiment_id_mapping[k] = v
|
||||
self.shortest_image_edge = shortest_image_edge
|
||||
self.crop_fraction = crop_fraction
|
||||
self.use_albumentations = use_albumentations
|
||||
self.letter_box_transform = letter_box_transform
|
||||
|
||||
self.statistics: dict[str, dict[str, dict[str, dict[str, list[float]]]]] = {}
|
||||
|
||||
@@ -244,6 +349,10 @@ class Gr00tN1d7Processor(ProcessorMixin):
|
||||
self.eval_image_transform = _build_eval_image_transform(
|
||||
image_target_size,
|
||||
image_crop_size,
|
||||
shortest_image_edge=shortest_image_edge,
|
||||
crop_fraction=crop_fraction,
|
||||
use_albumentations=use_albumentations,
|
||||
letter_box_transform=letter_box_transform,
|
||||
)
|
||||
self._collator = self.data_collator_class(
|
||||
model_name=model_name,
|
||||
@@ -428,7 +537,7 @@ class Gr00tN1d7Processor(ProcessorMixin):
|
||||
image_keys: list[str],
|
||||
images: list[Image.Image],
|
||||
masks: dict[str, list[np.ndarray]] | None,
|
||||
image_transform: transforms.Compose,
|
||||
image_transform: Callable[[np.ndarray], torch.Tensor],
|
||||
language: str,
|
||||
):
|
||||
temporal_stacked_images = {}
|
||||
@@ -470,6 +579,8 @@ class Gr00tN1d7Processor(ProcessorMixin):
|
||||
"color_jitter_params": self.color_jitter_params,
|
||||
"shortest_image_edge": self.shortest_image_edge,
|
||||
"crop_fraction": self.crop_fraction,
|
||||
"use_albumentations": self.use_albumentations,
|
||||
"letter_box_transform": self.letter_box_transform,
|
||||
"model_name": self.model_name,
|
||||
"model_type": self.model_type,
|
||||
"formalize_language": self.formalize_language,
|
||||
|
||||
@@ -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
|
||||
|
||||
from collections.abc import Iterable, Mapping
|
||||
from typing import Any
|
||||
@@ -13,6 +13,7 @@ from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.models.gr00t.policy import Gr00tPolicy
|
||||
from vllm_omni.diffusion.request import DUMMY_DIFFUSION_REQUEST_ID
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -30,6 +31,10 @@ class Gr00tN1d7Pipeline(nn.Module):
|
||||
vLLM-Omni owns the serving integration: OpenPI observations arrive through
|
||||
`sampling_params.extra_args["robot_obs"]`, this pipeline runs GR00T policy
|
||||
inference, and actions are returned through `DiffusionOutput.output["actions"]`.
|
||||
|
||||
The request's `seed` (materialised by the runner into `sampling_params.generator`)
|
||||
draws the flow-matching noise, so repeating a request with the same seed reproduces
|
||||
its action chunk.
|
||||
"""
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = "") -> None:
|
||||
@@ -123,7 +128,8 @@ class Gr00tN1d7Pipeline(nn.Module):
|
||||
self.reset()
|
||||
|
||||
policy_obs = _normalize_observation(robot_obs, language_key=self.policy.language_key)
|
||||
result = self.policy.get_action(policy_obs)
|
||||
generator = _noise_generator(req.sampling_params, self.device)
|
||||
result = self.policy.get_action(policy_obs, {"generator": generator} if generator is not None else None)
|
||||
actions = result[0] if isinstance(result, tuple) else result
|
||||
if not isinstance(actions, Mapping):
|
||||
return DiffusionOutput(error=f"GR00T policy returned {type(actions).__name__}; expected dict actions.")
|
||||
@@ -132,6 +138,35 @@ class Gr00tN1d7Pipeline(nn.Module):
|
||||
return DiffusionOutput(output={"actions": _to_float32_action_dict(actions)})
|
||||
|
||||
|
||||
def _noise_generator(sampling_params: OmniDiffusionSamplingParams, device: str) -> torch.Generator | None:
|
||||
"""Pick the generator that draws the action head's initial noise.
|
||||
|
||||
The runner materialises ``sampling_params.seed`` into ``sampling_params.generator`` on
|
||||
the model device before every forward, and ``OmniDiffusionRequest`` assigns a random
|
||||
seed when the caller omits one, so in serving the generator is always present. The
|
||||
seed fallback serves callers that bypass the runner (direct use, unit tests). ``None``
|
||||
leaves the action head on the global RNG, as upstream Isaac-GR00T runs. GR00T draws one
|
||||
noise tensor per request, so a generator in any other form (for example a list of several
|
||||
generators) is ignored with a warning and the seed fallback applies.
|
||||
"""
|
||||
generator = sampling_params.generator
|
||||
if isinstance(generator, list) and len(generator) == 1:
|
||||
generator = generator[0]
|
||||
if isinstance(generator, torch.Generator):
|
||||
return generator
|
||||
if generator is not None:
|
||||
received = f"a list of {len(generator)} generators" if isinstance(generator, list) else type(generator).__name__
|
||||
logger.warning(
|
||||
"GR00T expects a single torch.Generator per request but got %s; ignoring it. The initial noise "
|
||||
"falls back to sampling_params.seed=%s, or to the global RNG when that is None.",
|
||||
received,
|
||||
sampling_params.seed,
|
||||
)
|
||||
if sampling_params.seed is not None:
|
||||
return torch.Generator(device=device).manual_seed(int(sampling_params.seed))
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_observation(robot_obs: Mapping[str, Any], *, language_key: str) -> dict[str, Any]:
|
||||
obs: dict[str, Any] = {}
|
||||
if "video" in robot_obs:
|
||||
|
||||
@@ -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
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -328,7 +328,8 @@ class Gr00tPolicy:
|
||||
|
||||
Args:
|
||||
observation: Batched observation dictionary
|
||||
options: Optional parameters (currently unused)
|
||||
options: Optional per-request model parameters, forwarded verbatim to
|
||||
the action head (e.g. ``generator``)
|
||||
|
||||
Returns:
|
||||
Tuple of (actions_dict, info_dict)
|
||||
@@ -351,7 +352,7 @@ class Gr00tPolicy:
|
||||
|
||||
# Step 4: Run model inference to predict actions
|
||||
with torch.inference_mode():
|
||||
model_pred = self.model.get_action(**collated_inputs)
|
||||
model_pred = self.model.get_action(**collated_inputs, options=options)
|
||||
normalized_action = model_pred["action_pred"].float()
|
||||
|
||||
# Step 5: Decode actions from normalized space back to physical units
|
||||
|
||||
@@ -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 Helios (https://github.com/BestWishYsh/Helios)
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,18 +18,20 @@ from diffusers import AutoencoderKLWan
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from torch import nn
|
||||
from transformers import AutoConfig, AutoTokenizer, UMT5EncoderModel
|
||||
from typing_extensions import override
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.interaction.mixin import InteractionMixin
|
||||
from vllm_omni.diffusion.interaction.types import ChunkMediaSpec
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.helios.helios_transformer import HeliosTransformer3DModel
|
||||
from vllm_omni.diffusion.models.helios.scheduling_helios import HeliosScheduler
|
||||
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.prompt_update import PromptUpdateMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -74,9 +76,9 @@ def load_json_config(model_path: str, subfolder: str, filename: str, local_files
|
||||
return json.load(f)
|
||||
else:
|
||||
try:
|
||||
from huggingface_hub import hf_hub_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
config_path = hf_hub_download(
|
||||
config_path = hf_api().hf_hub_download(
|
||||
repo_id=model_path,
|
||||
filename=f"{subfolder}/{filename}",
|
||||
)
|
||||
@@ -160,7 +162,7 @@ class HeliosPipeline(
|
||||
CFGParallelMixin,
|
||||
ProgressBarMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
PromptUpdateMixin,
|
||||
InteractionMixin,
|
||||
SupportsComponentDiscovery,
|
||||
):
|
||||
"""Helios text-to-video / image-to-video / video-to-video pipeline for vllm-omni.
|
||||
@@ -533,10 +535,22 @@ class HeliosPipeline(
|
||||
"zero_steps": int(extra.get("zero_steps", 1)),
|
||||
}
|
||||
)
|
||||
self._prepare_next_chunk(state)
|
||||
self.prepare_next_chunk(state)
|
||||
return state
|
||||
|
||||
def _prepare_next_chunk(self, state: StepRequestState) -> None:
|
||||
def peek_chunk_media(self, state: StepRequestState) -> ChunkMediaSpec:
|
||||
"""Expose this chunk's decoded media extent for interaction timelines."""
|
||||
num_frames = int(state.extra["window_num_frames"])
|
||||
fps = state.sampling.fps
|
||||
if fps is None or float(fps) <= 0:
|
||||
raise ValueError(
|
||||
"sampling.fps is required and must be > 0 for interaction modalities that use the "
|
||||
f"chunk media timeline, got {fps!r} (request_id={state.request_id!r})"
|
||||
)
|
||||
return ChunkMediaSpec(num_frames=num_frames, fps=float(fps))
|
||||
|
||||
@override
|
||||
def prepare_next_chunk(self, state: StepRequestState) -> None:
|
||||
extra = state.extra
|
||||
k = state.chunk_index
|
||||
is_first_chunk = k == 0
|
||||
@@ -900,14 +914,9 @@ class HeliosPipeline(
|
||||
|
||||
output = current_latents if extra["output_type"] == "latent" else current_video
|
||||
completed_chunk_index = state.chunk_index
|
||||
prompt_update_metadata = state.extra.pop("prompt_update_chunk_metadata", {})
|
||||
state.chunk_index += 1
|
||||
finished = state.request_denoise_completed
|
||||
if not finished:
|
||||
# Apply queued/advancing prompt updates before preparing the next chunk.
|
||||
self._apply_prompt_update_at_chunk_boundary(state)
|
||||
self._prepare_next_chunk(state)
|
||||
else:
|
||||
if finished:
|
||||
self._current_timestep = None
|
||||
if current_omni_platform.is_available():
|
||||
current_omni_platform.empty_cache()
|
||||
@@ -917,9 +926,6 @@ class HeliosPipeline(
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else {},
|
||||
chunk_index=completed_chunk_index,
|
||||
total_chunks=state.total_chunks,
|
||||
started_event_ids=prompt_update_metadata.get("started_event_ids", []),
|
||||
active_event_ids=prompt_update_metadata.get("active_event_ids", []),
|
||||
completed_event_ids=prompt_update_metadata.get("completed_event_ids", []),
|
||||
finished=finished,
|
||||
)
|
||||
|
||||
@@ -1352,6 +1358,8 @@ class HeliosPipeline(
|
||||
"""Single-stage denoising loop for one chunk."""
|
||||
batch_size = latents.shape[0]
|
||||
do_true_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
# Distilled (DMD) needs the chunk-start noise for renoise; mirror step_scheduler.
|
||||
stage1_start_latents = latents
|
||||
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for i, t in enumerate(timesteps):
|
||||
@@ -1414,7 +1422,20 @@ class HeliosPipeline(
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
if self.is_distilled:
|
||||
latents = self.scheduler.step(
|
||||
noise_pred,
|
||||
t,
|
||||
latents,
|
||||
return_dict=False,
|
||||
cur_sampling_step=i,
|
||||
dmd_noisy_tensor=stage1_start_latents,
|
||||
dmd_sigmas=self.scheduler.sigmas,
|
||||
dmd_timesteps=self.scheduler.timesteps,
|
||||
all_timesteps=timesteps,
|
||||
)[0]
|
||||
else:
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
|
||||
pbar.update()
|
||||
|
||||
|
||||
@@ -2190,24 +2190,28 @@ class HunyuanImage3Model(nn.Module):
|
||||
return torch.concat((q, k, v))
|
||||
|
||||
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
|
||||
if _is_moe(self.config):
|
||||
# Params for weights, fp8 weight scales, fp8 activation scales
|
||||
# (param_name, weight_name, expert_id, shard_id)
|
||||
fused_moe_expert_mapping = FusedMoE.make_expert_params_mapping(
|
||||
self,
|
||||
ckpt_gate_proj_name="gate_proj",
|
||||
ckpt_down_proj_name="down_proj",
|
||||
ckpt_up_proj_name="up_proj",
|
||||
num_experts=self.config.num_experts,
|
||||
num_redundant_experts=self.num_redundant_experts,
|
||||
)
|
||||
expert_weights_remapping = {
|
||||
"gate_proj": ("gate_and_up_proj", 1, 2),
|
||||
"up_proj": ("gate_and_up_proj", 0, 2),
|
||||
}
|
||||
return fused_moe_expert_mapping, expert_weights_remapping
|
||||
else:
|
||||
return [], {}
|
||||
if not _is_moe(self.config):
|
||||
return []
|
||||
|
||||
# Params for weights, fp8 weight scales, fp8 activation scales
|
||||
# (param_name, weight_name, expert_id, shard_id)
|
||||
return FusedMoE.make_expert_params_mapping(
|
||||
self,
|
||||
ckpt_gate_proj_name="gate_proj",
|
||||
ckpt_down_proj_name="down_proj",
|
||||
ckpt_up_proj_name="up_proj",
|
||||
num_experts=self.config.num_experts,
|
||||
num_redundant_experts=self.num_redundant_experts,
|
||||
)
|
||||
|
||||
def _get_expert_weights_remapping(self) -> dict[str, tuple[str, int, int]]:
|
||||
"""Return the vLLM-Omni-local remapping for Hunyuan checkpoint weights."""
|
||||
if not _is_moe(self.config):
|
||||
return {}
|
||||
return {
|
||||
"gate_proj": ("gate_and_up_proj", 1, 2),
|
||||
"up_proj": ("gate_and_up_proj", 0, 2),
|
||||
}
|
||||
|
||||
# rename for delay load
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
|
||||
@@ -2243,7 +2247,8 @@ class HunyuanImage3Model(nn.Module):
|
||||
|
||||
params_dict = dict(self.named_parameters())
|
||||
loaded_params: set[str] = set()
|
||||
expert_params_mapping, expert_weights_remapping = self.get_expert_mapping()
|
||||
expert_params_mapping = self.get_expert_mapping()
|
||||
expert_weights_remapping = self._get_expert_weights_remapping()
|
||||
|
||||
# List of unexpected keywords in weight names
|
||||
unexpected_keywords = [
|
||||
|
||||
@@ -454,11 +454,10 @@ class HunyuanImage3Pipeline(
|
||||
|
||||
# Note: guidance_emb and timestep_r_emb are no longer skipped
|
||||
# to support HunyuanImage-3.0-Distil and MeanFlow distilled models
|
||||
loader = AutoWeightsLoader(
|
||||
self,
|
||||
skip_prefixes=skip_prefixes,
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(
|
||||
weights, mapper=WeightsMapper(orig_to_new_prefix={name: None for name in (skip_prefixes or ())})
|
||||
)
|
||||
return loader.load_weights(weights)
|
||||
|
||||
def prepare_seed(self, seed=None, batch_size=1):
|
||||
# random seed
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
@@ -9,6 +10,7 @@ from typing import (
|
||||
ClassVar,
|
||||
Literal,
|
||||
Protocol,
|
||||
TypeGuard,
|
||||
runtime_checkable,
|
||||
)
|
||||
|
||||
@@ -19,6 +21,7 @@ if TYPE_CHECKING:
|
||||
|
||||
from vllm_omni.diffusion.cache.cachedit import CacheDiTBackend
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.interaction.types import ChunkMediaSpec
|
||||
from vllm_omni.diffusion.worker.input_batch import InputBatch
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
@@ -45,6 +48,42 @@ class SupportAudioOutput(Protocol):
|
||||
support_audio_output: ClassVar[bool] = True
|
||||
|
||||
|
||||
DecodedChunkConsumer = Callable[["torch.Tensor"], None]
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SupportsChunkedVAEDecode(Protocol):
|
||||
"""Optional capability for VAEs that stream decoded temporal chunks.
|
||||
|
||||
Implementations must drain decoding before surfacing callback errors. In a
|
||||
distributed VAE, every rank invokes the method so collectives stay in
|
||||
lockstep, while ``on_chunk`` is called only on the rank that owns output.
|
||||
|
||||
``chunk_value_range`` is the closed interval the delivered floats occupy,
|
||||
which differs per checkpoint: a Wan VAE emits ``(-1.0, 1.0)`` while a
|
||||
MiniMax-H3 VAE reverts through its processor to ``(0.0, 1.0)``. A consumer
|
||||
cannot quantize chunks to pixels without it, so it is part of the
|
||||
capability rather than knowledge each consumer hard-codes per model.
|
||||
"""
|
||||
|
||||
chunk_value_range: ClassVar[tuple[float, float]]
|
||||
|
||||
def decode_with_chunks(
|
||||
self,
|
||||
z: torch.Tensor,
|
||||
*,
|
||||
on_chunk: DecodedChunkConsumer,
|
||||
) -> None:
|
||||
"""Decode ``z`` and synchronously deliver committed chunks in order."""
|
||||
...
|
||||
|
||||
|
||||
def supports_chunked_vae_decode(vae: object) -> TypeGuard[SupportsChunkedVAEDecode]:
|
||||
"""Return whether ``vae`` exposes the optional chunked decode capability."""
|
||||
|
||||
return isinstance(vae, SupportsChunkedVAEDecode)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SupportsStepExecution(Protocol):
|
||||
"""State-driven step-level execution protocol for diffusion pipelines.
|
||||
@@ -108,30 +147,34 @@ def supports_step_execution(pipeline: object) -> bool:
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class SupportsPromptUpdate(Protocol):
|
||||
"""Optional protocol for pipelines that support midway prompt updates.
|
||||
class SupportsInteractionApply(Protocol):
|
||||
"""Optional protocol for pipelines with unified mid-generation, chunk-boundary hooks."""
|
||||
|
||||
Pipelines typically implement this via
|
||||
:class:`~vllm_omni.diffusion.prompt_update.PromptUpdateMixin`.
|
||||
"""
|
||||
def peek_chunk_media(self, state: StepRequestState) -> ChunkMediaSpec:
|
||||
"""Return the media timeline represented by the upcoming/current chunk.
|
||||
|
||||
supports_prompt_update: ClassVar[bool] = True
|
||||
Useful when interaction handler needs interpolation/integration on a frame-by-frame basis,
|
||||
or for backpressure/pacing.
|
||||
"""
|
||||
...
|
||||
|
||||
def prepare_prompt_update(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
prompt: str,
|
||||
event_id: str,
|
||||
transition_chunks: int | None = None,
|
||||
) -> None:
|
||||
"""Encode and queue a prompt update on request-local state."""
|
||||
def apply_interaction_at_chunk_boundary(self, state: StepRequestState) -> None:
|
||||
"""Advance queued interactions before the next generation chunk."""
|
||||
...
|
||||
|
||||
def prepare_next_chunk(self, state: StepRequestState) -> None:
|
||||
"""Set up pipeline state for the next chunk after interaction apply.
|
||||
|
||||
Default implementations is a no-op; model-specific pipelines override
|
||||
when chunk transitions require latent/history bookkeeping.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
def supports_prompt_update(pipeline: object) -> bool:
|
||||
"""Return whether ``pipeline`` implements :class:`SupportsPromptUpdate`."""
|
||||
def supports_interaction_apply(pipeline: object) -> bool:
|
||||
"""Return whether ``pipeline`` implements :class:`SupportsInteractionApply`."""
|
||||
|
||||
return isinstance(pipeline, SupportsPromptUpdate)
|
||||
return isinstance(pipeline, SupportsInteractionApply)
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Realtime keyboard controls for LingBot World 2.0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from collections.abc import Iterable, Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from typing import Any, TypeAlias
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -42,7 +42,31 @@ def _normalize_actions(value: object, *, field: str) -> tuple[str, ...]:
|
||||
return tuple(action for action in _ACTION_ORDER if action in actions)
|
||||
|
||||
|
||||
def _normalize_frames(value: object, *, field: str) -> tuple[tuple[str, ...], ...]:
|
||||
#: Key states for one latent frame each, e.g. ``(("w",), ("w", "j"), ())`` for
|
||||
#: the three latent frames of one AR block.
|
||||
LingBotCameraActionFrames: TypeAlias = tuple[tuple[str, ...], ...]
|
||||
|
||||
#: One :data:`LingBotCameraActionFrames` per generated chunk, carried on the
|
||||
#: request for the whole rollout.
|
||||
LingBotCameraActionScript: TypeAlias = tuple[LingBotCameraActionFrames, ...]
|
||||
|
||||
|
||||
def as_camera_action_frames(value: Iterable[Iterable[str]]) -> LingBotCameraActionFrames:
|
||||
"""Restore the tuple form of one chunk's per-latent-frame key states."""
|
||||
return tuple(tuple(frame) for frame in value)
|
||||
|
||||
|
||||
def as_camera_action_script(value: Iterable[Iterable[Iterable[str]]]) -> LingBotCameraActionScript:
|
||||
"""Restore the tuple form of a whole request's script.
|
||||
|
||||
``sampling_params.extra_args`` round-trips through JSON, so an already
|
||||
validated script comes back as lists; this rebuilds the hashable tuple form
|
||||
without re-running validation.
|
||||
"""
|
||||
return tuple(as_camera_action_frames(chunk) for chunk in value)
|
||||
|
||||
|
||||
def _normalize_frames(value: object, *, field: str) -> LingBotCameraActionFrames:
|
||||
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)):
|
||||
raise ValueError(f"{field} must be a sequence of per-frame action lists.")
|
||||
return tuple(_normalize_actions(actions, field=f"{field}[{index}]") for index, actions in enumerate(value))
|
||||
@@ -52,7 +76,7 @@ def parse_lingbot_camera_action_frames(
|
||||
data: Mapping[str, Any],
|
||||
*,
|
||||
expected_frames: int,
|
||||
) -> tuple[tuple[str, ...], ...]:
|
||||
) -> LingBotCameraActionFrames:
|
||||
"""Validate the chunk-sized payload emitted by the session reducer."""
|
||||
|
||||
if data.get("mode") != "frames":
|
||||
@@ -66,6 +90,30 @@ def parse_lingbot_camera_action_frames(
|
||||
return frames
|
||||
|
||||
|
||||
def parse_lingbot_camera_action_script(
|
||||
script: object,
|
||||
*,
|
||||
frames_per_chunk: int,
|
||||
) -> LingBotCameraActionScript:
|
||||
"""Validate a request-scoped list of per-chunk camera action frames."""
|
||||
|
||||
if not isinstance(script, Sequence) or isinstance(script, (str, bytes)):
|
||||
raise ValueError("camera_action_script must be a sequence of per-chunk action lists.")
|
||||
if not script:
|
||||
raise ValueError("camera_action_script must contain at least one chunk.")
|
||||
chunks: list[LingBotCameraActionFrames] = []
|
||||
for index, chunk in enumerate(script):
|
||||
frames = _normalize_frames(chunk, field=f"camera_action_script[{index}]")
|
||||
if len(frames) != frames_per_chunk:
|
||||
raise ValueError(
|
||||
"camera_action_script chunks must contain exactly "
|
||||
f"{frames_per_chunk} per-latent-frame action lists; "
|
||||
f"chunk {index} has {len(frames)}."
|
||||
)
|
||||
chunks.append(frames)
|
||||
return tuple(chunks)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _LingBotCameraReducerState:
|
||||
mode: str | None = None
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""One AR block of LingBot World's causal DMD sampler.
|
||||
|
||||
The pipeline drives this in two ways -- request mode loops ``generate_block``
|
||||
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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.models.lingbot_world.transformer import (
|
||||
LingBotAttentionCache,
|
||||
LingBotTransformerCache,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.models.lingbot_world.transformer import CausalLingBotWorldTransformer3DModel
|
||||
from vllm_omni.diffusion.models.progress_bar import TqdmProgressBar
|
||||
from vllm_omni.experimental.ar_diffusion.kv_cache.state import ARDiffusionKVState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ARBlockContext:
|
||||
"""The bound AR-Diffusion session one block runs against.
|
||||
|
||||
Built by the pipeline from the state the runner bound for this invocation;
|
||||
``None`` in place of a context means request-local contiguous KV.
|
||||
"""
|
||||
|
||||
state: ARDiffusionKVState
|
||||
cross_attention: list[LingBotAttentionCache]
|
||||
branch: str
|
||||
|
||||
|
||||
class LingBotDMDBlockRunner:
|
||||
"""Runs the DMD probes and the KV commit for one latent-frame block."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
transformer: CausalLingBotWorldTransformer3DModel,
|
||||
*,
|
||||
device: torch.device,
|
||||
enforce_eager: bool,
|
||||
) -> None:
|
||||
self.transformer = transformer
|
||||
self.device = device
|
||||
self.enforce_eager = enforce_eager
|
||||
|
||||
# ── cache selection ──────────────────────────────────────────────────
|
||||
|
||||
def _paged_cache(
|
||||
self,
|
||||
*,
|
||||
condition: torch.Tensor,
|
||||
ar: ARBlockContext,
|
||||
commit_current: bool,
|
||||
) -> LingBotTransformerCache:
|
||||
patch_frames, patch_height, patch_width = self.transformer.config.patch_size
|
||||
frames = condition.shape[2] // patch_frames
|
||||
height = condition.shape[3] // patch_height
|
||||
width = condition.shape[4] // patch_width
|
||||
return LingBotTransformerCache(
|
||||
self_attention=ar.state.get_kv_caches(
|
||||
ar.branch,
|
||||
seq_len=frames * height * width,
|
||||
commit_current=commit_current,
|
||||
),
|
||||
cross_attention=ar.cross_attention,
|
||||
)
|
||||
|
||||
def _block_cache(
|
||||
self,
|
||||
*,
|
||||
condition: torch.Tensor,
|
||||
cache: LingBotTransformerCache | None,
|
||||
ar: ARBlockContext | None,
|
||||
commit_current: bool,
|
||||
) -> LingBotTransformerCache:
|
||||
"""Pick the cache one transformer call sees: paged when a session is
|
||||
bound, else the caller's request-local cache."""
|
||||
if ar is not None:
|
||||
return self._paged_cache(condition=condition, ar=ar, commit_current=commit_current)
|
||||
return cast(LingBotTransformerCache, cache)
|
||||
|
||||
# ── one block ────────────────────────────────────────────────────────
|
||||
|
||||
def probe_step(
|
||||
self,
|
||||
*,
|
||||
current_latents: torch.Tensor,
|
||||
condition: torch.Tensor,
|
||||
camera: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
cache: LingBotTransformerCache | None,
|
||||
ar: ARBlockContext | None,
|
||||
start_frame: int,
|
||||
timestep_value: float,
|
||||
step_index: int,
|
||||
) -> 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.
|
||||
"""
|
||||
if not self.enforce_eager:
|
||||
torch.compiler.cudagraph_mark_step_begin()
|
||||
set_forward_context_denoise_step_idx(step_index)
|
||||
timestep = torch.full((1,), float(timestep_value), device=self.device, dtype=torch.float32)
|
||||
# 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)
|
||||
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),
|
||||
start_frame=start_frame,
|
||||
update_cache=False,
|
||||
)
|
||||
if flow_prediction.shape != current_latents.shape:
|
||||
raise RuntimeError(
|
||||
"transformer flow prediction shape must match the 16-channel noise latent, "
|
||||
f"got {tuple(flow_prediction.shape)} and {tuple(current_latents.shape)}."
|
||||
)
|
||||
return flow_prediction
|
||||
|
||||
def apply_transition(
|
||||
self,
|
||||
current_latents: torch.Tensor,
|
||||
flow_prediction: torch.Tensor,
|
||||
sigma: float,
|
||||
*,
|
||||
next_sigma: float | None,
|
||||
generator: torch.Generator,
|
||||
) -> torch.Tensor:
|
||||
"""Invert the flow to x0, then re-noise at ``next_sigma``.
|
||||
|
||||
``next_sigma=None`` marks the final step, so where the caller sits in
|
||||
its own loop stays out of this function.
|
||||
"""
|
||||
# The checkpoint's flow parameterization is inverted by
|
||||
# x0 = x_t - sigma * flow. Intermediate steps re-noise that x0
|
||||
# estimate at the next sigma; the final step keeps x0 as this
|
||||
# block's generated latent.
|
||||
x0 = current_latents - sigma * flow_prediction.float()
|
||||
if next_sigma is None:
|
||||
return x0
|
||||
noise = randn_tensor(current_latents.shape, generator=generator, device=self.device, dtype=torch.float32)
|
||||
return (1.0 - next_sigma) * x0 + next_sigma * noise
|
||||
|
||||
def commit_block_kv(
|
||||
self,
|
||||
*,
|
||||
latents: torch.Tensor,
|
||||
condition: torch.Tensor,
|
||||
camera: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
cache: LingBotTransformerCache | None,
|
||||
ar: ARBlockContext | None,
|
||||
start_frame: int,
|
||||
) -> 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()``.
|
||||
"""
|
||||
# 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:
|
||||
torch.compiler.cudagraph_mark_step_begin()
|
||||
self.transformer(
|
||||
hidden_states=cache_input,
|
||||
timestep=torch.zeros(1, device=self.device, dtype=torch.float32),
|
||||
encoder_hidden_states=prompt_embeds,
|
||||
camera_hidden_states=camera,
|
||||
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=True),
|
||||
start_frame=start_frame,
|
||||
update_cache=True,
|
||||
)
|
||||
if ar is not None:
|
||||
ar.state.commit_paged_context(ar.branch)
|
||||
|
||||
def generate_block(
|
||||
self,
|
||||
*,
|
||||
condition: torch.Tensor,
|
||||
camera: torch.Tensor,
|
||||
prompt_embeds: torch.Tensor,
|
||||
cache: LingBotTransformerCache | None,
|
||||
ar: ARBlockContext | None,
|
||||
start_frame: int,
|
||||
schedule: tuple[tuple[float, float], ...],
|
||||
generator: torch.Generator,
|
||||
progress_bar: TqdmProgressBar[Any],
|
||||
) -> torch.Tensor:
|
||||
"""Request mode: all probes of one block, then its commit."""
|
||||
block_shape = (1, self.transformer.config.out_channels, *condition.shape[2:5])
|
||||
current_latents = randn_tensor(block_shape, generator=generator, device=self.device, dtype=torch.float32)
|
||||
for step_index, (timestep_value, sigma) in enumerate(schedule):
|
||||
flow_prediction = self.probe_step(
|
||||
current_latents=current_latents,
|
||||
condition=condition,
|
||||
camera=camera,
|
||||
prompt_embeds=prompt_embeds,
|
||||
cache=cache,
|
||||
ar=ar,
|
||||
start_frame=start_frame,
|
||||
timestep_value=timestep_value,
|
||||
step_index=step_index,
|
||||
)
|
||||
next_sigma = schedule[step_index + 1][1] if step_index + 1 < len(schedule) else None
|
||||
current_latents = self.apply_transition(
|
||||
current_latents, flow_prediction, sigma, next_sigma=next_sigma, generator=generator
|
||||
)
|
||||
progress_bar.update()
|
||||
self.commit_block_kv(
|
||||
latents=current_latents,
|
||||
condition=condition,
|
||||
camera=camera,
|
||||
prompt_embeds=prompt_embeds,
|
||||
cache=cache,
|
||||
ar=ar,
|
||||
start_frame=start_frame,
|
||||
)
|
||||
return current_latents
|
||||
@@ -1,12 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Request-scoped LingBot-World v2 causal DMD pipeline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from collections.abc import Callable, Iterable, Iterator, Sequence
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import TYPE_CHECKING, Any, ClassVar, cast
|
||||
@@ -24,15 +24,19 @@ 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.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput, SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput, SupportsComponentDiscovery, SupportsStepExecution
|
||||
from vllm_omni.diffusion.models.lingbot_world.actions import (
|
||||
LINGBOT_CAMERA_ACTION_SCHEMA,
|
||||
LINGBOT_CAMERA_TRAJECTORY_SCHEMA,
|
||||
LingBotCameraActionFrames,
|
||||
LingBotCameraActionScript,
|
||||
as_camera_action_frames,
|
||||
as_camera_action_script,
|
||||
integrate_lingbot_camera_actions,
|
||||
parse_lingbot_camera_action_frames,
|
||||
parse_lingbot_camera_action_script,
|
||||
)
|
||||
from vllm_omni.diffusion.models.lingbot_world.camera import (
|
||||
CameraTrajectory,
|
||||
@@ -41,6 +45,7 @@ from vllm_omni.diffusion.models.lingbot_world.camera import (
|
||||
load_camera_trajectory,
|
||||
resolve_trusted_action_directory,
|
||||
)
|
||||
from vllm_omni.diffusion.models.lingbot_world.dmd_block import ARBlockContext, LingBotDMDBlockRunner
|
||||
from vllm_omni.diffusion.models.lingbot_world.transformer import (
|
||||
CausalLingBotWorldTransformer3DModel,
|
||||
LingBotAttentionCache,
|
||||
@@ -64,8 +69,11 @@ from vllm_omni.experimental.ar_diffusion.tick_protocol import (
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
from tqdm.std import tqdm as TqdmProgressBar
|
||||
|
||||
from vllm_omni.diffusion.worker.input_batch import InputBatch
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
from vllm_omni.experimental.ar_diffusion.kv_cache.state import (
|
||||
ARDiffusionKVState,
|
||||
)
|
||||
@@ -79,6 +87,7 @@ _MAX_SEQUENCE_LENGTH = 512
|
||||
_ACTION_ROOT_ENV = "VLLM_OMNI_LINGBOT_ACTION_ROOT"
|
||||
_PREPROCESSED_CAMERA_KEY = "_lingbot_camera_trajectory"
|
||||
_PREPROCESSED_CAMERA_ACTIONS_KEY = "_lingbot_camera_actions"
|
||||
_PREPROCESSED_CAMERA_ACTION_SCRIPT_KEY = "_lingbot_camera_action_script"
|
||||
_SOURCE_IMAGE_ERROR = (
|
||||
"Unable to load multi_modal_data.image; expected a decodable image within 4096 * 4096 source pixels."
|
||||
)
|
||||
@@ -86,12 +95,34 @@ _SOURCE_IMAGE_ERROR = (
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _LingBotRequestInputs:
|
||||
"""Validated model-specific request boundary."""
|
||||
"""Validated model-specific request boundary.
|
||||
|
||||
Pre-processing materializes exactly one of the three camera fields, chosen
|
||||
from the shape of the incoming control. They are not alternative spellings
|
||||
of one input: ``camera_action_script`` is a *container* whose element is a
|
||||
``camera_actions``, and the two are live at once during step execution.
|
||||
|
||||
- ``camera_trajectory`` is explicit per-frame poses and intrinsics. Offline
|
||||
replay loads it from ``extra_args["action_path"]``; the tick entry point
|
||||
receives the same content as a ``lingbot.camera_trajectory.v1`` control.
|
||||
Integrating WASD actions also produces one, written back onto this field.
|
||||
- ``camera_actions`` is WASD key state for *one* three-latent-frame block:
|
||||
the unit every path reduces to before the camera is embedded. The tick
|
||||
entry point fills it directly, because one of its requests is one block;
|
||||
step execution derives it per block by slicing ``camera_action_script``.
|
||||
``_prepare_camera`` also reads it as the signal that the trajectory it
|
||||
was handed is already latent-aligned.
|
||||
- ``camera_action_script`` holds one such action list *per generated chunk*
|
||||
for the whole rollout, which only step execution needs, because only it
|
||||
runs every block inside a single ``generate()``. The tick entry point has
|
||||
no use for it and ``forward()`` rejects a request that carries it.
|
||||
"""
|
||||
|
||||
prompt: str
|
||||
image: PIL.Image.Image | torch.Tensor
|
||||
camera_trajectory: CameraTrajectory | None
|
||||
camera_actions: tuple[tuple[str, ...], ...] | None
|
||||
camera_actions: LingBotCameraActionFrames | None
|
||||
camera_action_script: LingBotCameraActionScript | None
|
||||
height: int
|
||||
width: int
|
||||
num_frames: int
|
||||
@@ -303,6 +334,16 @@ def get_lingbot_world_pre_process_func(
|
||||
"LingBot realtime camera controls require schema "
|
||||
"'lingbot.camera_trajectory.v1' or 'lingbot.camera_actions.v1'."
|
||||
)
|
||||
camera_action_script = None
|
||||
elif extra_args.get("camera_action_script") is not None:
|
||||
if extra_args.get("action_path"):
|
||||
raise ValueError("camera_action_script cannot be combined with action_path.")
|
||||
camera_action_script = parse_lingbot_camera_action_script(
|
||||
extra_args.get("camera_action_script"),
|
||||
frames_per_chunk=3,
|
||||
)
|
||||
trajectory = None
|
||||
camera_actions = None
|
||||
else:
|
||||
action_path = extra_args.get("action_path")
|
||||
if not isinstance(action_path, (str, os.PathLike)) or not str(action_path):
|
||||
@@ -323,6 +364,7 @@ def get_lingbot_world_pre_process_func(
|
||||
"Unable to load camera trajectory from action_path; expected poses.npy and intrinsics.npy."
|
||||
) from None
|
||||
camera_actions = None
|
||||
camera_action_script = None
|
||||
|
||||
updated_prompt = dict(prompt)
|
||||
updated_multi_modal_data = dict(multi_modal_data)
|
||||
@@ -333,6 +375,7 @@ def get_lingbot_world_pre_process_func(
|
||||
**extra_args,
|
||||
_PREPROCESSED_CAMERA_KEY: trajectory,
|
||||
_PREPROCESSED_CAMERA_ACTIONS_KEY: camera_actions,
|
||||
_PREPROCESSED_CAMERA_ACTION_SCRIPT_KEY: camera_action_script,
|
||||
}
|
||||
return request
|
||||
|
||||
@@ -377,11 +420,13 @@ class LingBotWorldCausalDMDPipeline(
|
||||
nn.Module,
|
||||
SupportImageInput,
|
||||
SupportsComponentDiscovery,
|
||||
SupportsStepExecution,
|
||||
ProgressBarMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
):
|
||||
"""LingBot-World v2 I2V generation with a request-local causal cache."""
|
||||
|
||||
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"]
|
||||
@@ -617,11 +662,17 @@ class LingBotWorldCausalDMDPipeline(
|
||||
raise ValueError("sampling_params.extra_args must be a mapping.")
|
||||
camera_trajectory = extra_args.get(_PREPROCESSED_CAMERA_KEY)
|
||||
camera_actions = extra_args.get(_PREPROCESSED_CAMERA_ACTIONS_KEY)
|
||||
camera_action_script = extra_args.get(_PREPROCESSED_CAMERA_ACTION_SCRIPT_KEY)
|
||||
if camera_trajectory is not None and not isinstance(camera_trajectory, CameraTrajectory):
|
||||
raise ValueError("LingBot camera trajectory must be materialized by the pre-process function.")
|
||||
if camera_actions is not None:
|
||||
camera_actions = tuple(tuple(actions) for actions in camera_actions)
|
||||
if (camera_trajectory is None) == (camera_actions is None):
|
||||
camera_actions = as_camera_action_frames(camera_actions)
|
||||
if camera_action_script is not None:
|
||||
camera_action_script = as_camera_action_script(camera_action_script)
|
||||
camera_sources = (
|
||||
int(camera_trajectory is not None) + int(camera_actions is not None) + int(camera_action_script is not None)
|
||||
)
|
||||
if camera_sources != 1:
|
||||
raise ValueError("LingBot pre-processing must materialize exactly one camera input.")
|
||||
|
||||
request_flow_shift = (
|
||||
@@ -720,6 +771,7 @@ class LingBotWorldCausalDMDPipeline(
|
||||
image=image,
|
||||
camera_trajectory=camera_trajectory,
|
||||
camera_actions=camera_actions,
|
||||
camera_action_script=camera_action_script,
|
||||
height=height,
|
||||
width=width,
|
||||
num_frames=num_frames,
|
||||
@@ -818,6 +870,7 @@ class LingBotWorldCausalDMDPipeline(
|
||||
*,
|
||||
dtype: torch.dtype,
|
||||
previous: CameraTrajectory | None = None,
|
||||
latent_aligned: bool = False,
|
||||
) -> tuple[torch.Tensor, CameraTrajectory]:
|
||||
"""Convert raw camera frames to a latent-aligned ray tensor."""
|
||||
|
||||
@@ -825,7 +878,7 @@ class LingBotWorldCausalDMDPipeline(
|
||||
if trajectory is None:
|
||||
raise RuntimeError("LingBot camera trajectory was not prepared before camera embedding.")
|
||||
available_frames = int(trajectory.poses.shape[0])
|
||||
if inputs.camera_actions is not None:
|
||||
if inputs.camera_actions is not None or latent_aligned:
|
||||
if available_frames != inputs.num_latent_frames:
|
||||
raise ValueError(
|
||||
"camera actions must produce exactly one pose per latent frame; "
|
||||
@@ -942,29 +995,38 @@ class LingBotWorldCausalDMDPipeline(
|
||||
)
|
||||
]
|
||||
|
||||
def _ar_transformer_cache(
|
||||
# ── DMD block helpers ─────────────────────────────────────────────────
|
||||
#
|
||||
# The DMD math for one AR block lives in ``LingBotDMDBlockRunner`` so that
|
||||
# request mode (``_generate_block`` in a loop) and stepwise execution
|
||||
# (``denoise_step`` / ``step_scheduler`` / ``post_decode``) share one copy.
|
||||
# The pipeline's only jobs here are building the runner and translating
|
||||
# the bound AR session into an ``ARBlockContext``.
|
||||
|
||||
@property
|
||||
def _dmd_blocks(self) -> LingBotDMDBlockRunner:
|
||||
runner = getattr(self, "_dmd_block_runner", None)
|
||||
if runner is None:
|
||||
runner = LingBotDMDBlockRunner(
|
||||
self.transformer,
|
||||
device=self.device,
|
||||
enforce_eager=bool(self.od_config.enforce_eager),
|
||||
)
|
||||
self._dmd_block_runner = runner
|
||||
return runner
|
||||
|
||||
def _ar_block_context(
|
||||
self,
|
||||
*,
|
||||
condition: torch.Tensor,
|
||||
cross_attention: list[LingBotAttentionCache],
|
||||
commit_current: bool,
|
||||
) -> LingBotTransformerCache:
|
||||
cross_attention: list[LingBotAttentionCache] | None,
|
||||
) -> ARBlockContext | None:
|
||||
"""Wrap the bound session for the block runner; ``None`` keeps
|
||||
request-local KV."""
|
||||
if cross_attention is None:
|
||||
return None
|
||||
state = self._ar_diffusion_kv_state
|
||||
if state is None:
|
||||
raise RuntimeError("LingBot AR cache requested without a bound state.")
|
||||
patch_frames, patch_height, patch_width = self.transformer.config.patch_size
|
||||
frames = condition.shape[2] // patch_frames
|
||||
height = condition.shape[3] // patch_height
|
||||
width = condition.shape[4] // patch_width
|
||||
seq_len = frames * height * width
|
||||
return LingBotTransformerCache(
|
||||
self_attention=state.get_kv_caches(
|
||||
self._AR_BRANCH,
|
||||
seq_len=seq_len,
|
||||
commit_current=commit_current,
|
||||
),
|
||||
cross_attention=cross_attention,
|
||||
)
|
||||
return ARBlockContext(state=state, cross_attention=cross_attention, branch=self._AR_BRANCH)
|
||||
|
||||
def _generate_block(
|
||||
self,
|
||||
@@ -979,102 +1041,17 @@ class LingBotWorldCausalDMDPipeline(
|
||||
generator: torch.Generator,
|
||||
progress_bar: TqdmProgressBar[Any],
|
||||
) -> torch.Tensor:
|
||||
block_shape = (
|
||||
1,
|
||||
self.transformer.config.out_channels,
|
||||
condition.shape[2],
|
||||
condition.shape[3],
|
||||
condition.shape[4],
|
||||
)
|
||||
current_latents = randn_tensor(
|
||||
block_shape,
|
||||
generator=generator,
|
||||
device=self.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
for step_index, (timestep_value, sigma) in enumerate(schedule):
|
||||
if not self.od_config.enforce_eager:
|
||||
torch.compiler.cudagraph_mark_step_begin()
|
||||
set_forward_context_denoise_step_idx(step_index)
|
||||
timestep = torch.full((1,), float(timestep_value), device=self.device, dtype=torch.float32)
|
||||
# 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)
|
||||
current_cache = (
|
||||
self._ar_transformer_cache(
|
||||
condition=condition,
|
||||
cross_attention=cast(
|
||||
list[LingBotAttentionCache],
|
||||
ar_cross_attention,
|
||||
),
|
||||
commit_current=False,
|
||||
)
|
||||
if ar_cross_attention is not None
|
||||
else cast(LingBotTransformerCache, cache)
|
||||
)
|
||||
flow_prediction = self.transformer(
|
||||
hidden_states=model_input,
|
||||
timestep=timestep,
|
||||
encoder_hidden_states=prompt_embeds,
|
||||
camera_hidden_states=camera,
|
||||
cache=current_cache,
|
||||
start_frame=start_frame,
|
||||
update_cache=False,
|
||||
)
|
||||
if flow_prediction.shape != current_latents.shape:
|
||||
raise RuntimeError(
|
||||
"transformer flow prediction shape must match the 16-channel noise latent, "
|
||||
f"got {tuple(flow_prediction.shape)} and {tuple(current_latents.shape)}."
|
||||
)
|
||||
# The checkpoint's flow parameterization is inverted by
|
||||
# x0 = x_t - sigma * flow. Intermediate steps re-noise that x0
|
||||
# estimate at the next sigma; the final step keeps x0 as this
|
||||
# block's generated latent.
|
||||
x0 = current_latents - sigma * flow_prediction.float()
|
||||
if step_index + 1 < len(schedule):
|
||||
next_sigma = schedule[step_index + 1][1]
|
||||
noise = randn_tensor(
|
||||
current_latents.shape,
|
||||
generator=generator,
|
||||
device=self.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
current_latents = (1.0 - next_sigma) * x0 + next_sigma * noise
|
||||
else:
|
||||
current_latents = x0
|
||||
progress_bar.update()
|
||||
|
||||
# Commit K/V only for the final clean block, never for noisy probes.
|
||||
cache_input = torch.cat((current_latents.to(dtype=condition.dtype), condition), dim=1)
|
||||
commit_cache = (
|
||||
self._ar_transformer_cache(
|
||||
condition=condition,
|
||||
cross_attention=cast(
|
||||
list[LingBotAttentionCache],
|
||||
ar_cross_attention,
|
||||
),
|
||||
commit_current=True,
|
||||
)
|
||||
if ar_cross_attention is not None
|
||||
else cast(LingBotTransformerCache, cache)
|
||||
)
|
||||
if not self.od_config.enforce_eager:
|
||||
torch.compiler.cudagraph_mark_step_begin()
|
||||
self.transformer(
|
||||
hidden_states=cache_input,
|
||||
timestep=torch.zeros(1, device=self.device, dtype=torch.float32),
|
||||
encoder_hidden_states=prompt_embeds,
|
||||
camera_hidden_states=camera,
|
||||
cache=commit_cache,
|
||||
return self._dmd_blocks.generate_block(
|
||||
condition=condition,
|
||||
camera=camera,
|
||||
prompt_embeds=prompt_embeds,
|
||||
cache=cache,
|
||||
ar=self._ar_block_context(ar_cross_attention),
|
||||
start_frame=start_frame,
|
||||
update_cache=True,
|
||||
schedule=schedule,
|
||||
generator=generator,
|
||||
progress_bar=progress_bar,
|
||||
)
|
||||
if ar_cross_attention is not None:
|
||||
state = self._ar_diffusion_kv_state
|
||||
if state is None:
|
||||
raise RuntimeError("LingBot AR state disappeared before KV commit.")
|
||||
state.commit_paged_context(self._AR_BRANCH)
|
||||
return current_latents
|
||||
|
||||
def encode_prompt(
|
||||
self,
|
||||
@@ -1100,6 +1077,15 @@ class LingBotWorldCausalDMDPipeline(
|
||||
|
||||
def forward(self, req: DiffusionRequestBatch) -> DiffusionOutput:
|
||||
inputs = self._parse_request(req)
|
||||
if inputs.camera_action_script is not None:
|
||||
# Only step execution walks a whole rollout inside one request, so
|
||||
# a per-chunk script here would be silently dropped rather than
|
||||
# steering the camera.
|
||||
raise ValueError(
|
||||
"camera_action_script is read only by LingBot step execution; "
|
||||
"request mode takes one three-frame camera_actions control per "
|
||||
"block, or a camera_trajectory for the request."
|
||||
)
|
||||
tick = ARDiffusionTickRequest.from_extra_args(req.sampling_params.extra_args)
|
||||
if tick is not None and self._ar_diffusion_kv_state is None:
|
||||
raise RuntimeError("LingBot typed ticks require ARDiffusionEngine session binding.")
|
||||
@@ -1287,6 +1273,317 @@ class LingBotWorldCausalDMDPipeline(
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
def _decode_chunk_to_pixels(
|
||||
self, latents: torch.Tensor, *, output_type: str
|
||||
) -> torch.Tensor | np.ndarray | list[list[PIL.Image.Image]]:
|
||||
"""Decode one AR block so streaming consumers receive pixels, not latents.
|
||||
|
||||
Blocks are decoded independently, which keeps the shared VAE stateless
|
||||
and lets a rollout be served without a per-session temporal cache. That
|
||||
is the same shape Helios streams today; cross-block ``feat_cache``
|
||||
continuity is a separate decision and is not made here.
|
||||
|
||||
The registered post-process hook returns a ``{"payload", "metadata"}``
|
||||
envelope untouched, so the pixel conversion it would do for a bare
|
||||
tensor has to happen here instead.
|
||||
"""
|
||||
latent_mean, latent_std = self._vae_latent_stats(latents)
|
||||
vae_latents = (latents * latent_std + latent_mean).to(dtype=self.vae.dtype)
|
||||
video = self.vae.decode(vae_latents, return_dict=False)[0]
|
||||
return self._video_processor().postprocess_video(video, output_type=output_type)
|
||||
|
||||
def _video_processor(self) -> VideoProcessor:
|
||||
processor = getattr(self, "_cached_video_processor", None)
|
||||
if processor is None:
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
|
||||
processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
||||
self._cached_video_processor = processor
|
||||
return processor
|
||||
|
||||
def _horizon_latent_frames(self) -> int:
|
||||
return (_MAX_RAW_FRAMES - 1) // self.vae_scale_factor_temporal + 1
|
||||
|
||||
def _max_realtime_chunks(self) -> int:
|
||||
return self._horizon_latent_frames() // int(self.transformer.config.num_frames_per_block)
|
||||
|
||||
def _require_bound_ar_state(self) -> None:
|
||||
if self._ar_diffusion_kv_state is None:
|
||||
raise RuntimeError("LingBot step execution requires AR-Diffusion session binding.")
|
||||
|
||||
def prepare_encode(self, state: StepRequestState, **kwargs: Any) -> StepRequestState:
|
||||
del kwargs
|
||||
self._require_bound_ar_state()
|
||||
req = DiffusionRequestBatch(
|
||||
requests=[
|
||||
OmniDiffusionRequest(
|
||||
prompt=state.prompt,
|
||||
sampling_params=state.sampling,
|
||||
request_id=state.request_id,
|
||||
)
|
||||
]
|
||||
)
|
||||
inputs = self._parse_request(req)
|
||||
if ARDiffusionTickRequest.from_extra_args(state.sampling.extra_args) is not None:
|
||||
raise ValueError("LingBot step execution does not accept AR-Diffusion ticks.")
|
||||
if (inputs.height, inputs.width) != (self._ar_height, self._ar_width):
|
||||
raise ValueError(
|
||||
"LingBot AR-Diffusion request resolution must match the "
|
||||
f"fixed cache geometry {self._ar_height}x{self._ar_width}."
|
||||
)
|
||||
block_frames = int(self.transformer.config.num_frames_per_block)
|
||||
total_chunks = inputs.num_latent_frames // block_frames
|
||||
max_chunks = self._max_realtime_chunks()
|
||||
if total_chunks > max_chunks:
|
||||
raise ValueError(
|
||||
"LingBot step execution currently supports at most "
|
||||
f"{max_chunks} chunks because the image-condition horizon is "
|
||||
f"{_MAX_RAW_FRAMES} pixel frames."
|
||||
)
|
||||
if inputs.camera_action_script is not None and len(inputs.camera_action_script) != total_chunks:
|
||||
raise ValueError(
|
||||
"camera_action_script must contain one action list per generated chunk; "
|
||||
f"got {len(inputs.camera_action_script)} chunks for {total_chunks} requested chunks."
|
||||
)
|
||||
dtype = self.transformer.dtype
|
||||
prompt_embeds = self.encode_prompt(
|
||||
inputs.prompt,
|
||||
max_sequence_length=inputs.max_sequence_length,
|
||||
dtype=dtype,
|
||||
)
|
||||
image_condition = self._prepare_condition(
|
||||
replace(
|
||||
inputs,
|
||||
num_frames=_MAX_RAW_FRAMES,
|
||||
num_latent_frames=self._horizon_latent_frames(),
|
||||
),
|
||||
dtype=dtype,
|
||||
)
|
||||
camera_trajectory_cache = None
|
||||
camera_embedding_cache = None
|
||||
if inputs.camera_trajectory is not None:
|
||||
available_frames = int(inputs.camera_trajectory.poses.shape[0])
|
||||
if available_frames < inputs.num_frames:
|
||||
raise ValueError(
|
||||
"camera trajectory frames must be at least num_frames; "
|
||||
f"got camera_frames={available_frames}, num_frames={inputs.num_frames}."
|
||||
)
|
||||
truncated = CameraTrajectory(
|
||||
poses=inputs.camera_trajectory.poses[: inputs.num_frames],
|
||||
intrinsics=inputs.camera_trajectory.intrinsics[: inputs.num_frames],
|
||||
)
|
||||
camera_trajectory_cache = interpolate_camera_trajectory(truncated, inputs.num_latent_frames)
|
||||
# Embed the whole trajectory once, exactly as request mode does, and
|
||||
# slice it per block in ``_prepare_next_chunk``. Embedding each chunk
|
||||
# on its own would normalize that block's framewise translations by
|
||||
# its own largest step, so a slow block would be conditioned as
|
||||
# full-speed motion and drift from offline replay of the same path.
|
||||
camera_embedding_cache, _ = self._prepare_camera(inputs, dtype=dtype)
|
||||
state.prompt_embeds = prompt_embeds
|
||||
state.chunk_index = 0
|
||||
state.step_index = 0
|
||||
state.step_in_chunk = 0
|
||||
state.total_chunks = total_chunks
|
||||
state.chunk_num_steps = len(LINGBOT_DMD_TIMESTEPS)
|
||||
state.extra = {
|
||||
"inputs": inputs,
|
||||
"image_condition": image_condition,
|
||||
"schedule": _build_shifted_flow_schedule(flow_shift=inputs.flow_shift),
|
||||
"dtype": dtype,
|
||||
"block_frames": block_frames,
|
||||
"camera_pitch": 0.0,
|
||||
"camera_tail": None,
|
||||
"camera_action_script": inputs.camera_action_script,
|
||||
"camera_trajectory_cache": camera_trajectory_cache,
|
||||
"camera_embedding_cache": camera_embedding_cache,
|
||||
}
|
||||
self._ar_text_caches(prompt_embeds, invalidate=False)
|
||||
self._prepare_next_chunk(state)
|
||||
return state
|
||||
|
||||
def _prepare_next_chunk(self, state: StepRequestState) -> None:
|
||||
extra = state.extra
|
||||
inputs: _LingBotRequestInputs = extra["inputs"]
|
||||
block_frames = int(extra["block_frames"])
|
||||
start_frame = state.chunk_index * block_frames
|
||||
stop_frame = start_frame + block_frames
|
||||
image_condition = extra["image_condition"]
|
||||
if stop_frame > image_condition.shape[2]:
|
||||
raise ValueError("LingBot chunk_index exceeds the configured causal image condition horizon.")
|
||||
condition = image_condition[:, :, start_frame:stop_frame]
|
||||
previous = extra.get("camera_tail")
|
||||
if extra.get("camera_action_script") is not None:
|
||||
chunk_actions = extra["camera_action_script"][state.chunk_index]
|
||||
action_trajectory, camera_pitch = integrate_lingbot_camera_actions(
|
||||
chunk_actions,
|
||||
width=inputs.width,
|
||||
height=inputs.height,
|
||||
initial_pose=(previous.poses[-1] if previous is not None else None),
|
||||
initial_pitch=float(extra.get("camera_pitch", 0.0)),
|
||||
)
|
||||
extra["camera_pitch"] = camera_pitch
|
||||
chunk_inputs = replace(
|
||||
inputs,
|
||||
camera_trajectory=action_trajectory,
|
||||
camera_actions=chunk_actions,
|
||||
num_frames=(block_frames - 1) * self.vae_scale_factor_temporal + 1,
|
||||
num_latent_frames=block_frames,
|
||||
)
|
||||
camera, camera_tail = self._prepare_camera(
|
||||
chunk_inputs,
|
||||
dtype=extra["dtype"],
|
||||
previous=previous,
|
||||
)
|
||||
elif extra.get("camera_embedding_cache") is not None:
|
||||
# Same slice request mode takes from its one full-trajectory
|
||||
# embedding, so both paths condition a block identically.
|
||||
trajectory = extra["camera_trajectory_cache"]
|
||||
camera = extra["camera_embedding_cache"][:, :, start_frame:stop_frame]
|
||||
camera_tail = CameraTrajectory(
|
||||
poses=trajectory.poses[stop_frame - 1 : stop_frame].clone(),
|
||||
intrinsics=trajectory.intrinsics[stop_frame - 1 : stop_frame].clone(),
|
||||
)
|
||||
else:
|
||||
raise RuntimeError("LingBot step execution is missing a camera trajectory or action script.")
|
||||
if camera.shape[2:] != condition.shape[2:]:
|
||||
raise RuntimeError(
|
||||
"folded camera and image condition must share latent frame/height/width geometry; "
|
||||
f"got camera={tuple(camera.shape)}, condition={tuple(condition.shape)}."
|
||||
)
|
||||
generator = getattr(state.sampling, "generator", None)
|
||||
if not isinstance(generator, torch.Generator):
|
||||
raise ValueError("LingBot World requires the runner-provided torch.Generator.")
|
||||
extra["condition"] = condition
|
||||
extra["camera"] = camera
|
||||
extra["camera_tail"] = camera_tail
|
||||
extra["start_frame"] = start_frame
|
||||
extra["ar_cross_attention"] = self._ar_text_caches(
|
||||
cast(torch.Tensor, state.prompt_embeds),
|
||||
invalidate=False,
|
||||
)
|
||||
state.latents = randn_tensor(
|
||||
(
|
||||
1,
|
||||
self.transformer.config.out_channels,
|
||||
condition.shape[2],
|
||||
condition.shape[3],
|
||||
condition.shape[4],
|
||||
),
|
||||
generator=generator,
|
||||
device=self.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
state.timesteps = torch.tensor(
|
||||
[timestep for timestep, _ in extra["schedule"]],
|
||||
device=self.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
state.step_in_chunk = 0
|
||||
state.step_index = 0
|
||||
|
||||
def denoise_step(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
*,
|
||||
states: Sequence[StepRequestState] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> torch.Tensor | None:
|
||||
del input_batch, kwargs
|
||||
if states is None or len(states) != 1:
|
||||
raise ValueError("LingBot step execution supports a single request, not a batched request.")
|
||||
self._require_bound_ar_state()
|
||||
state = states[0]
|
||||
extra = state.extra
|
||||
latents = state.latents
|
||||
if latents is None:
|
||||
raise RuntimeError("LingBot step execution requires latents before denoise_step.")
|
||||
timestep = state.current_timestep
|
||||
if timestep is None:
|
||||
raise RuntimeError("LingBot step execution requires a current timestep before denoise_step.")
|
||||
schedule = extra["schedule"]
|
||||
step_in_chunk = state.step_in_chunk
|
||||
return self._dmd_blocks.probe_step(
|
||||
current_latents=latents,
|
||||
condition=extra["condition"],
|
||||
camera=extra["camera"],
|
||||
prompt_embeds=cast(torch.Tensor, state.prompt_embeds),
|
||||
cache=None,
|
||||
ar=self._ar_block_context(extra["ar_cross_attention"]),
|
||||
start_frame=int(extra["start_frame"]),
|
||||
timestep_value=float(schedule[step_in_chunk][0]),
|
||||
step_index=step_in_chunk,
|
||||
)
|
||||
|
||||
def step_scheduler(self, state: StepRequestState, noise_pred: torch.Tensor, **kwargs: Any) -> None:
|
||||
del kwargs
|
||||
extra = state.extra
|
||||
latents = state.latents
|
||||
if latents is None:
|
||||
raise RuntimeError("LingBot step execution requires latents before step_scheduler.")
|
||||
generator = getattr(state.sampling, "generator", None)
|
||||
if not isinstance(generator, torch.Generator):
|
||||
raise ValueError("LingBot World requires the runner-provided torch.Generator.")
|
||||
schedule = extra["schedule"]
|
||||
step_in_chunk = state.step_in_chunk
|
||||
next_sigma = schedule[step_in_chunk + 1][1] if step_in_chunk + 1 < len(schedule) else None
|
||||
state.latents = self._dmd_blocks.apply_transition(
|
||||
latents,
|
||||
noise_pred,
|
||||
schedule[step_in_chunk][1],
|
||||
next_sigma=next_sigma,
|
||||
generator=generator,
|
||||
)
|
||||
state.step_in_chunk += 1
|
||||
state.step_index = state.step_in_chunk
|
||||
|
||||
def post_decode(self, state: StepRequestState, **kwargs: Any) -> DiffusionOutput:
|
||||
del kwargs
|
||||
self._require_bound_ar_state()
|
||||
extra = state.extra
|
||||
latents = state.latents
|
||||
if latents is None:
|
||||
raise RuntimeError("LingBot step execution requires latents before post_decode.")
|
||||
self._dmd_blocks.commit_block_kv(
|
||||
latents=latents,
|
||||
condition=extra["condition"],
|
||||
camera=extra["camera"],
|
||||
prompt_embeds=cast(torch.Tensor, state.prompt_embeds),
|
||||
cache=None,
|
||||
ar=self._ar_block_context(extra["ar_cross_attention"]),
|
||||
start_frame=int(extra["start_frame"]),
|
||||
)
|
||||
completed_chunk_index = state.chunk_index
|
||||
inputs: _LingBotRequestInputs = extra["inputs"]
|
||||
# "video" is the payload key the output formatter treats as primary, so
|
||||
# a streaming client receives frames on ``images`` like any other video
|
||||
# pipeline; latent mode keeps the tensor for offline consumers.
|
||||
if inputs.output_type == "latent":
|
||||
payload: dict[str, Any] = {"latents": latents}
|
||||
else:
|
||||
payload = {"video": self._decode_chunk_to_pixels(latents, output_type=inputs.output_type)}
|
||||
output = {
|
||||
"payload": payload,
|
||||
"metadata": {
|
||||
"ar_diffusion": ARDiffusionChunkMetadata(
|
||||
session_id=state.request_id,
|
||||
request_id=state.request_id,
|
||||
chunk_index=completed_chunk_index,
|
||||
applied_event_ids=(),
|
||||
).to_dict()
|
||||
},
|
||||
}
|
||||
state.chunk_index += 1
|
||||
finished = state.request_denoise_completed
|
||||
if not finished:
|
||||
self._prepare_next_chunk(state)
|
||||
return DiffusionOutput(
|
||||
output=output,
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
chunk_index=completed_chunk_index,
|
||||
total_chunks=state.total_chunks,
|
||||
finished=finished,
|
||||
)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loader = AutoWeightsLoader(self)
|
||||
return cast(set[str], loader.load_weights(weights))
|
||||
@@ -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
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -376,9 +376,9 @@ def _ensure_local_dir(model: str | os.PathLike[str], allow_patterns: list[str] |
|
||||
model_path = Path(model)
|
||||
if model_path.exists():
|
||||
return model_path
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
return Path(snapshot_download(str(model), allow_patterns=allow_patterns))
|
||||
return Path(hf_api().snapshot_download(str(model), allow_patterns=allow_patterns))
|
||||
|
||||
|
||||
def _ensure_avatar_model_index(model_dir: Path, use_int8: bool) -> None:
|
||||
|
||||
@@ -15,12 +15,10 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
from diffusers import AutoencoderKLLTX2Audio, AutoencoderKLLTX2Video, FlowMatchEulerDiscreteScheduler
|
||||
from diffusers.models.autoencoders.ltx2_diffusion_decoder import LTX2VideoVaeNeighborhoodNattenProcessor
|
||||
from diffusers.pipelines.ltx2 import LTX2TextConnectors
|
||||
from diffusers.pipelines.ltx2.latent_upsampler import LTX2LatentUpsamplerModel
|
||||
from diffusers.pipelines.ltx2.vocoder import LTX2Vocoder
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
from huggingface_hub import hf_hub_download
|
||||
from safetensors import safe_open
|
||||
from safetensors.torch import load_file
|
||||
from transformers import AutoModelForImageTextToText, AutoTokenizer, Gemma3ForConditionalGeneration
|
||||
@@ -32,16 +30,11 @@ from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.offloader.module_collector import ModuleDiscovery
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
|
||||
from .ltx2_diffusion_decoder import (
|
||||
LTX25_NATIVE_ARTIFACT_REVISION,
|
||||
LTX25_NATIVE_DIFFUSION_DECODER_FILENAME,
|
||||
LTX25_NATIVE_DIFFUSION_DECODER_REPO_ID,
|
||||
)
|
||||
from .ltx2_diffusion_decoder_distributed import DistributedLTX2VideoDiffusionDecoderModel
|
||||
from .ltx2_request import LTXCheckpointKind, validate_ltx_checkpoint
|
||||
from .ltx2_transformer import (
|
||||
LTX2VideoTransformer3DModel,
|
||||
@@ -49,6 +42,13 @@ from .ltx2_transformer import (
|
||||
apply_split_rotary_emb,
|
||||
to_ltx_padding_mask,
|
||||
)
|
||||
from .vae.decoder import (
|
||||
LTX25_NATIVE_ARTIFACT_REVISION,
|
||||
LTX25_NATIVE_DIFFUSION_DECODER_FILENAME,
|
||||
LTX25_NATIVE_DIFFUSION_DECODER_REPO_ID,
|
||||
LTX2VideoVaeNeighborhoodNattenProcessor,
|
||||
)
|
||||
from .vae.distributed import DistributedLTX2VideoDiffusionDecoderModel
|
||||
|
||||
try:
|
||||
from diffusers.pipelines.ltx2.vocoder import LTX2VocoderWithBWE
|
||||
@@ -279,7 +279,7 @@ def resolve_ltx_artifact(
|
||||
# independently pinned artifact revision.
|
||||
revision = model_revision if model == repo_id else artifact_revision
|
||||
try:
|
||||
return hf_hub_download(
|
||||
return hf_api().hf_hub_download(
|
||||
repo_id=repo_id,
|
||||
filename=filename,
|
||||
revision=revision,
|
||||
@@ -298,7 +298,7 @@ def _create_ltx25_natten_processor() -> LTX2VideoVaeNeighborhoodNattenProcessor:
|
||||
except (ImportError, OSError, RuntimeError, ValueError) as exc:
|
||||
raise RuntimeError(
|
||||
"LTX-2.5 DiffVAE requires the shi-labs/natten Hub kernel. "
|
||||
"Install kernels==0.15.2, use a supported GPU, leave "
|
||||
"Install kernels==0.16.1, use a supported GPU, leave "
|
||||
"DIFFUSERS_DISABLE_REMOTE_CODE unset, and allow Hub access during kernel initialization."
|
||||
) from exc
|
||||
|
||||
@@ -351,7 +351,7 @@ def _load_ltx_metadata_json(model: str, filename: str, revision: str | None = No
|
||||
return {}
|
||||
else:
|
||||
try:
|
||||
path = hf_hub_download(repo_id=model, filename=filename, revision=revision)
|
||||
path = hf_api().hf_hub_download(repo_id=model, filename=filename, revision=revision)
|
||||
except Exception:
|
||||
return {}
|
||||
try:
|
||||
@@ -529,7 +529,7 @@ def _detect_vocoder_output_sample_rate(model: str, revision: str | None = None)
|
||||
vocoder_config_path = os.path.join(model, "vocoder", "config.json")
|
||||
if not os.path.exists(vocoder_config_path):
|
||||
try:
|
||||
vocoder_config_path = hf_hub_download(model, "vocoder/config.json", revision=revision)
|
||||
vocoder_config_path = hf_api().hf_hub_download(model, "vocoder/config.json", revision=revision)
|
||||
except Exception:
|
||||
return None
|
||||
try:
|
||||
@@ -662,7 +662,7 @@ def initialize_pipeline_components(pipeline: Any, od_config: Any) -> None:
|
||||
revision=revision,
|
||||
)
|
||||
if profile.text_encoder_cls is None:
|
||||
raise ImportError("LTX-2.5 requires Gemma4UnifiedForConditionalGeneration; install transformers>=5.10.1,<5.15.")
|
||||
raise ImportError("LTX-2.5 requires Gemma4UnifiedForConditionalGeneration; install transformers>=5.13.0,<5.15.")
|
||||
with torch.device("cpu"):
|
||||
pipeline.text_encoder = _load_component(
|
||||
profile.text_encoder_cls,
|
||||
@@ -839,7 +839,7 @@ def load_transformer_config(
|
||||
if not os.path.exists(config_path):
|
||||
raise FileNotFoundError(f"LTX transformer config not found: {config_path}")
|
||||
else:
|
||||
config_path = hf_hub_download(
|
||||
config_path = hf_api().hf_hub_download(
|
||||
repo_id=model_path,
|
||||
filename=f"{subfolder}/config.json",
|
||||
revision=revision,
|
||||
|
||||
@@ -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
|
||||
|
||||
"""Shared denoise execution primitives for LTX pipelines."""
|
||||
|
||||
@@ -578,12 +578,6 @@ class LTXPhaseExecutor:
|
||||
video_audio_step_adapter=video_audio_step_adapter,
|
||||
)
|
||||
video_coords, audio_coords = prepare_rope_coords_stage(pipeline, forward_ctx, latents, audio_latents)
|
||||
ring_degree = getattr(pipeline.od_config.parallel_config, "ring_degree", 1) or 1
|
||||
if padded_audio_num_frames > original_audio_num_frames and ring_degree > 1:
|
||||
raise ValueError(
|
||||
"LTX audio padding requires an attention mask, which Ring sequence parallelism does not support. "
|
||||
"Use Ulysses-only SP or choose a request whose audio latent length is divisible by the SP size."
|
||||
)
|
||||
denoise_ctx = LTXDenoiseContext(
|
||||
latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
|
||||
@@ -24,7 +24,7 @@ from vllm.distributed import (
|
||||
tensor_model_parallel_all_reduce,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.batch_invariant import linear_batch_invariant
|
||||
from vllm.model_executor.determinism.batch_invariant import linear_batch_invariant
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
|
||||
@@ -497,7 +497,6 @@ class LTXRequestMixin:
|
||||
image_crf = _normalize_image_crf(first_image_crf if first_image_crf is not None else image_crf)
|
||||
|
||||
sampling = sampling_params_list[0]
|
||||
is_dummy_run = req.is_dummy_run()
|
||||
prompt = [item if isinstance(item, str) else (item.get("prompt") or "") for item in req.prompts] or prompt
|
||||
negative_prompt = _resolve_negative_prompts(
|
||||
req.prompts,
|
||||
@@ -511,8 +510,6 @@ class LTXRequestMixin:
|
||||
num_inference_steps = (
|
||||
sampling.num_inference_steps or num_inference_steps or self.pipeline_recipe.num_inference_steps
|
||||
)
|
||||
if is_dummy_run and self.pipeline_recipe.fixed_num_inference_steps:
|
||||
num_inference_steps = self.pipeline_recipe.num_inference_steps
|
||||
num_inference_steps = max(int(num_inference_steps), 2)
|
||||
|
||||
num_videos_per_prompt = (
|
||||
@@ -528,8 +525,6 @@ class LTXRequestMixin:
|
||||
for item in sampling_params_list
|
||||
]
|
||||
guidance = guidance_specs[0]
|
||||
if is_dummy_run and not self.pipeline_recipe.phases[0].allow_guidance_override:
|
||||
guidance = self.pipeline_recipe.request_guidance
|
||||
if any(item != guidance for item in guidance_specs[1:]):
|
||||
raise ValueError("Batched LTX requests must use identical video/audio guidance parameters.")
|
||||
|
||||
|
||||
@@ -5,14 +5,16 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from contextlib import nullcontext
|
||||
import time
|
||||
from collections.abc import Iterable, Iterator
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from dataclasses import replace
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
@@ -60,28 +62,42 @@ from .ltx2_request import (
|
||||
validate_pipeline_request,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _deterministic_ltx_vocoder():
|
||||
previous = torch.backends.cudnn.deterministic
|
||||
try:
|
||||
torch.backends.cudnn.deterministic = True
|
||||
yield
|
||||
finally:
|
||||
torch.backends.cudnn.deterministic = previous
|
||||
|
||||
|
||||
def _run_ltx_vocoder(vocoder: nn.Module, generated_mel: torch.Tensor) -> torch.Tensor:
|
||||
"""Run the BWE vocoder in FP32, matching the official LTX pipeline."""
|
||||
if not hasattr(vocoder, "bwe_generator"):
|
||||
return vocoder(generated_mel)
|
||||
|
||||
input_dtype = generated_mel.dtype
|
||||
device_type = generated_mel.device.type
|
||||
module_dtype = next(vocoder.parameters()).dtype
|
||||
if device_type == "mps":
|
||||
if module_dtype != torch.float32:
|
||||
vocoder.float()
|
||||
try:
|
||||
return vocoder(generated_mel.float()).to(input_dtype)
|
||||
finally:
|
||||
if module_dtype != torch.float32:
|
||||
vocoder.to(module_dtype)
|
||||
cudnn_context = _deterministic_ltx_vocoder() if device_type == "cuda" else nullcontext()
|
||||
with cudnn_context:
|
||||
if not hasattr(vocoder, "bwe_generator"):
|
||||
return vocoder(generated_mel)
|
||||
|
||||
# BF16 errors compound through the BWE model's long convolution stack.
|
||||
# FP32 autocast upcasts each op without materializing a second FP32 model.
|
||||
with torch.autocast(device_type=device_type, dtype=torch.float32):
|
||||
return vocoder(generated_mel.float()).to(input_dtype)
|
||||
input_dtype = generated_mel.dtype
|
||||
module_dtype = next(vocoder.parameters()).dtype
|
||||
if device_type == "mps":
|
||||
if module_dtype != torch.float32:
|
||||
vocoder.float()
|
||||
try:
|
||||
return vocoder(generated_mel.float()).to(input_dtype)
|
||||
finally:
|
||||
if module_dtype != torch.float32:
|
||||
vocoder.to(module_dtype)
|
||||
|
||||
# BF16 errors compound through the BWE model's long convolution stack.
|
||||
# FP32 autocast upcasts each op without materializing a second FP32 model.
|
||||
with torch.autocast(device_type=device_type, dtype=torch.float32):
|
||||
return vocoder(generated_mel.float()).to(input_dtype)
|
||||
|
||||
|
||||
def _prepare_ltx2_video_output(
|
||||
@@ -195,7 +211,7 @@ class LTXRuntime(
|
||||
connector_batches_cfg = False
|
||||
distributed_video_decode = True
|
||||
support_image_input = False
|
||||
dummy_run_num_frames = 1
|
||||
dummy_run_num_frames: ClassVar[int] = 0
|
||||
preserve_sp_padded_audio_duration = False
|
||||
reports_stage_durations = False
|
||||
|
||||
@@ -207,6 +223,14 @@ class LTXRuntime(
|
||||
f"{self.__class__.__name__} does not support ulysses_mode='advanced_uaa'. "
|
||||
"Use the default ulysses_mode='strict' for LTX sequence parallelism."
|
||||
)
|
||||
ring_degree = getattr(parallel_config, "ring_degree", 1)
|
||||
allgather_degree = getattr(parallel_config, "allgather_degree", 1)
|
||||
if ring_degree != 1 or allgather_degree != 1:
|
||||
raise ValueError(
|
||||
f"{self.__class__.__name__} supports pure Ulysses sequence parallelism only. "
|
||||
"Set ring_degree=1 and allgather_degree=1; "
|
||||
f"got {ring_degree=} and {allgather_degree=}."
|
||||
)
|
||||
self.model_version = detect_ltx_model_version(od_config.model, revision=getattr(od_config, "revision", None))
|
||||
self.use_diffusion_decoder = _ltx2_use_diffusion_decoder(od_config, self.model_version)
|
||||
self.component_profile = resolve_ltx_component_profile(self.pipeline_kind, self.model_version)
|
||||
@@ -354,27 +378,29 @@ class LTXRuntime(
|
||||
)
|
||||
)
|
||||
self._enter_phase(phase_recipe)
|
||||
phase_inputs = self._build_phase_inputs(
|
||||
request_inputs,
|
||||
phase_recipe,
|
||||
phase_results[-1] if phase_results else None,
|
||||
)
|
||||
with self._profile_phase_method("_build_phase_inputs", phase_recipe.name):
|
||||
phase_inputs = self._build_phase_inputs(
|
||||
request_inputs,
|
||||
phase_recipe,
|
||||
phase_results[-1] if phase_results else None,
|
||||
)
|
||||
if phase_sigmas is not None:
|
||||
phase_inputs = replace(phase_inputs, num_inference_steps=len(phase_sigmas) - 1)
|
||||
noise_scale = phase_recipe.noise_scale
|
||||
if override_sigmas is not None and phase_recipe.input_transform == "spatial_upsample":
|
||||
noise_scale = float(override_sigmas[0])
|
||||
phase_result = self.run_phase(
|
||||
req,
|
||||
phase_inputs,
|
||||
noise_scale=noise_scale,
|
||||
sigmas=phase_sigmas,
|
||||
timesteps=None,
|
||||
attention_kwargs=None,
|
||||
phase_recipe=phase_recipe,
|
||||
image=image,
|
||||
prompt_context=prompt_context,
|
||||
)
|
||||
with self._profile_phase_method("run_phase", phase_recipe.name):
|
||||
phase_result = self.run_phase(
|
||||
req,
|
||||
phase_inputs,
|
||||
noise_scale=noise_scale,
|
||||
sigmas=phase_sigmas,
|
||||
timesteps=None,
|
||||
attention_kwargs=None,
|
||||
phase_recipe=phase_recipe,
|
||||
image=image,
|
||||
prompt_context=prompt_context,
|
||||
)
|
||||
phase_results.append(phase_result)
|
||||
prompt_context = phase_result.forward_context.prompt_context
|
||||
|
||||
@@ -384,7 +410,45 @@ class LTXRuntime(
|
||||
video=phase_results[self.pipeline_recipe.video_output_phase].video,
|
||||
audio=phase_results[self.pipeline_recipe.audio_output_phase].audio,
|
||||
)
|
||||
return self.decode_phase(output_phase)
|
||||
with self._profile_phase_method("decode_phase"):
|
||||
output = self.decode_phase(output_phase)
|
||||
return self._attach_profiled_stage_durations(output)
|
||||
|
||||
@contextmanager
|
||||
def _profile_phase_method(self, method_name: str, phase_name: str | None = None) -> Iterator[None]:
|
||||
if not getattr(self, "enable_diffusion_pipeline_profiler", False):
|
||||
yield
|
||||
return
|
||||
|
||||
metric_parts = [self.__class__.__name__]
|
||||
if phase_name is not None:
|
||||
metric_parts.append(phase_name)
|
||||
metric_parts.append(method_name)
|
||||
metric_name = ".".join(metric_parts)
|
||||
|
||||
if current_omni_platform.is_available():
|
||||
current_omni_platform.synchronize()
|
||||
start_time = time.perf_counter()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if current_omni_platform.is_available():
|
||||
current_omni_platform.synchronize()
|
||||
duration = time.perf_counter() - start_time
|
||||
logger.info("[DiffusionPipelineProfiler] %s took %.6fs", metric_name, duration)
|
||||
with self._profiler_lock:
|
||||
self._stage_durations[metric_name] = self._stage_durations.get(metric_name, 0.0) + duration
|
||||
|
||||
def _attach_profiled_stage_durations(
|
||||
self, output: DiffusionOutput | list[DiffusionOutput]
|
||||
) -> DiffusionOutput | list[DiffusionOutput]:
|
||||
if not getattr(self, "enable_diffusion_pipeline_profiler", False):
|
||||
return output
|
||||
stage_durations = self.stage_durations
|
||||
outputs = output if isinstance(output, list) else [output]
|
||||
for item in outputs:
|
||||
item.stage_durations = dict(stage_durations)
|
||||
return output
|
||||
|
||||
def _enter_phase(self, phase: LTXPhaseRecipe) -> None:
|
||||
self._active_phase_name = phase.name
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.parallel.base import (
|
||||
ParallelAttentionContext,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.comm import SeqAllToAll4D
|
||||
from vllm_omni.diffusion.distributed.group_coordinator import (
|
||||
SequenceParallelGroupCoordinator,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _VideoToAudioContext(ParallelAttentionContext):
|
||||
ulysses_pg: dist.ProcessGroup
|
||||
use_sync: bool
|
||||
|
||||
|
||||
class LTX2VideoToAudioParallelAttention:
|
||||
"""LTX video-to-audio SP with replicated audio queries.
|
||||
|
||||
Video K/V arrive sequence-sharded, while the much shorter audio query is
|
||||
replicated. Redistribute only K/V across sequence/head dimensions, slice
|
||||
audio query heads locally, then gather output heads. This uses three
|
||||
collectives instead of standard Ulysses' four and keeps audio replicated.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sp_group: SequenceParallelGroupCoordinator,
|
||||
*,
|
||||
use_sync: bool = False,
|
||||
) -> None:
|
||||
if sp_group.ring_world_size != 1:
|
||||
raise NotImplementedError(
|
||||
"LTX video-to-audio sequence parallelism currently supports pure Ulysses only (ring_degree must be 1)."
|
||||
)
|
||||
self._sp_group = sp_group
|
||||
self._ulysses_pg = sp_group.ulysses_group
|
||||
self._use_sync = use_sync
|
||||
|
||||
@property
|
||||
def enabled(self) -> bool:
|
||||
return True
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "ltx2_video_to_audio"
|
||||
|
||||
def pre_attention(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
):
|
||||
if query.ndim != 4 or key.ndim != 4 or value.ndim != 4:
|
||||
raise ValueError(
|
||||
"LTX video-to-audio SP expects Q/K/V in (B, S, H, D) layout, "
|
||||
f"got {query.shape=}, {key.shape=}, {value.shape=}."
|
||||
)
|
||||
if key.shape != value.shape:
|
||||
raise ValueError(
|
||||
"LTX video-to-audio SP requires matching K/V shapes, "
|
||||
f"got key={tuple(key.shape)} and value={tuple(value.shape)}."
|
||||
)
|
||||
|
||||
world_size = self._sp_group.ulysses_world_size
|
||||
rank = self._sp_group.ulysses_rank
|
||||
query_heads = int(query.shape[2])
|
||||
if query_heads % world_size != 0:
|
||||
raise ValueError(
|
||||
"LTX video-to-audio SP requires query heads divisible by "
|
||||
f"ulysses_degree, got heads={query_heads}, ulysses_degree={world_size}."
|
||||
)
|
||||
if int(key.shape[2]) % world_size != 0:
|
||||
raise ValueError(
|
||||
"LTX video-to-audio SP requires K/V heads divisible by "
|
||||
f"ulysses_degree, got heads={key.shape[2]}, ulysses_degree={world_size}."
|
||||
)
|
||||
|
||||
heads_per_rank = query_heads // world_size
|
||||
head_start = rank * heads_per_rank
|
||||
query = query[:, :, head_start : head_start + heads_per_rank, :].contiguous()
|
||||
key = SeqAllToAll4D.apply(self._ulysses_pg, key, 2, 1, self._use_sync)
|
||||
value = SeqAllToAll4D.apply(self._ulysses_pg, value, 2, 1, self._use_sync)
|
||||
|
||||
ctx = _VideoToAudioContext(
|
||||
name=self.name,
|
||||
ulysses_pg=self._ulysses_pg,
|
||||
use_sync=self._use_sync,
|
||||
)
|
||||
return query, key, value, attn_metadata, ctx
|
||||
|
||||
def post_attention(
|
||||
self,
|
||||
attn_output: torch.Tensor,
|
||||
ctx: ParallelAttentionContext | None,
|
||||
) -> torch.Tensor:
|
||||
if not isinstance(ctx, _VideoToAudioContext):
|
||||
raise TypeError(f"Unexpected LTX video-to-audio context: {type(ctx)!r}.")
|
||||
|
||||
# Gather along heads by moving H to the leading dimension required by
|
||||
# all_gather_into_tensor, then restore the backend's (B, S, H, D) layout.
|
||||
local_heads_first = attn_output.permute(2, 0, 1, 3).contiguous()
|
||||
world_size = dist.get_world_size(ctx.ulysses_pg)
|
||||
gathered = torch.empty(
|
||||
(local_heads_first.shape[0] * world_size, *local_heads_first.shape[1:]),
|
||||
dtype=attn_output.dtype,
|
||||
device=attn_output.device,
|
||||
)
|
||||
dist.all_gather_into_tensor(gathered, local_heads_first, group=ctx.ulysses_pg)
|
||||
if ctx.use_sync:
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
return gathered.permute(1, 2, 0, 3).contiguous()
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
# Copyright 2025 The Lightricks team and The HuggingFace Team.
|
||||
# All rights reserved.
|
||||
#
|
||||
@@ -47,9 +50,12 @@ from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.cache.cachedit import CacheDiTAdapterConfig
|
||||
from vllm_omni.diffusion.distributed.hsdp_utils import is_transformer_block_module
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelInput, SequenceParallelOutput
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
|
||||
from .ltx2_sequence_parallel import LTX2VideoToAudioParallelAttention
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_RMSNORM_INIT_PARAMS = inspect.signature(RMSNorm.__init__).parameters
|
||||
@@ -359,6 +365,34 @@ def to_ltx_padding_mask(attention_mask: torch.Tensor) -> torch.Tensor:
|
||||
class _LTX2ParallelAttention(Attention):
|
||||
"""Preserve LTX SP collectives while applying model-specific padding masks."""
|
||||
|
||||
_SP_MODES = frozenset({"local", "video_self", "video_to_audio"})
|
||||
|
||||
def __init__(self, *args, ltx_sp_mode: str = "local", **kwargs):
|
||||
if ltx_sp_mode not in self._SP_MODES:
|
||||
raise ValueError(
|
||||
f"Unsupported LTX sequence-parallel mode {ltx_sp_mode!r}; expected one of {sorted(self._SP_MODES)}."
|
||||
)
|
||||
super().__init__(*args, **kwargs)
|
||||
self.ltx_sp_mode = ltx_sp_mode
|
||||
self._video_to_audio_strategy = None
|
||||
|
||||
def _get_active_parallel_strategy(self):
|
||||
base_strategy = super()._get_active_parallel_strategy()
|
||||
if self.ltx_sp_mode == "local" or not base_strategy.enabled:
|
||||
return self._no_parallel_strategy
|
||||
if self.ltx_sp_mode == "video_self":
|
||||
return base_strategy
|
||||
if base_strategy.name != "ulysses":
|
||||
raise NotImplementedError(
|
||||
f"LTX video-to-audio sequence parallelism requires pure Ulysses; got strategy={base_strategy.name!r}."
|
||||
)
|
||||
if self._video_to_audio_strategy is None:
|
||||
self._video_to_audio_strategy = LTX2VideoToAudioParallelAttention(
|
||||
get_sp_group(),
|
||||
use_sync=self.use_sync,
|
||||
)
|
||||
return self._video_to_audio_strategy
|
||||
|
||||
def _run_local_attention(self, query, key, value, attn_metadata):
|
||||
attention_mask = attn_metadata.attn_mask if attn_metadata is not None else None
|
||||
if attention_mask is not None:
|
||||
@@ -597,6 +631,7 @@ class LTX2Attention(torch.nn.Module):
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
disable_kv_quant: bool = False,
|
||||
sequence_parallel_mode: str = "local",
|
||||
):
|
||||
super().__init__()
|
||||
# LTX-2 uses "rms_norm_across_heads", LTX-2.3 uses "rms_norm" -- both
|
||||
@@ -721,6 +756,7 @@ class LTX2Attention(torch.nn.Module):
|
||||
causal=False,
|
||||
prefix=prefix,
|
||||
disable_kv_quant=disable_kv_quant,
|
||||
ltx_sp_mode=sequence_parallel_mode,
|
||||
)
|
||||
|
||||
# LTX-2.3: per-head gated attention
|
||||
@@ -876,6 +912,7 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
apply_gated_attention=video_gated_attn,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.attn1" if prefix else "attn1",
|
||||
sequence_parallel_mode="video_self",
|
||||
)
|
||||
|
||||
self.audio_norm1 = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine)
|
||||
@@ -965,6 +1002,7 @@ class LTX2VideoTransformerBlock(nn.Module):
|
||||
apply_gated_attention=audio_gated_attn,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.video_to_audio_attn" if prefix else "video_to_audio_attn",
|
||||
sequence_parallel_mode="video_to_audio",
|
||||
)
|
||||
|
||||
# 4. Feedforward layers
|
||||
@@ -1568,38 +1606,25 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
|
||||
return {
|
||||
"": {
|
||||
# Shard video/audio latents across sequence
|
||||
# Keep only the long video stream sequence-sharded. Audio and
|
||||
# prompt streams remain replicated on every SP rank.
|
||||
"hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
||||
"audio_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
||||
"keyframes_mask": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
||||
# Shard prompt embeds across sequence
|
||||
"encoder_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
||||
"audio_encoder_hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, split_output=False),
|
||||
# Keep per-token video/audio timestep embeddings aligned with
|
||||
# their corresponding latent sequence shards. Official LTX
|
||||
# multi-guidance supplies both tensors as (B, seq_len).
|
||||
# Keep per-token video timestep embeddings aligned with the
|
||||
# video latent shard. LTX guidance supplies a separate,
|
||||
# replicated audio_timestep under SP.
|
||||
"timestep": SequenceParallelInput(split_dim=1, expected_dims=2, split_output=False),
|
||||
"audio_timestep": SequenceParallelInput(split_dim=1, expected_dims=2, split_output=False),
|
||||
},
|
||||
"rope": {
|
||||
0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
},
|
||||
"audio_rope": {
|
||||
0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
},
|
||||
"cross_attn_rope": {
|
||||
0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
},
|
||||
"cross_attn_audio_rope": {
|
||||
0: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
1: SequenceParallelInput(split_dim=rope_split_dim, expected_dims=rope_expected_dims, split_output=True),
|
||||
},
|
||||
# Gather outputs before returning
|
||||
# Video output is sharded; audio output is already replicated.
|
||||
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
|
||||
"audio_proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Shared operator selection for LTX-2 eager kernels and their tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
|
||||
import torch
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
from vllm.utils.import_utils import has_tilelang
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
# Pointwise fusions are launch/memory-traffic reductions whose first execution
|
||||
# for every runtime key is checked bit-for-bit; failures use the ordinary model
|
||||
# math. The FNA schedule is performance-tuned for SM90 and has no silent
|
||||
# fallback, so qualify the two paths independently.
|
||||
_FUSION_CUDA_COMPUTE_CAPABILITIES = frozenset({90, 100, 103})
|
||||
_FNA_CUDA_COMPUTE_CAPABILITIES = frozenset({90})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LTX2VAEOperatorSet:
|
||||
qk_norm_rope: Callable[..., tuple[torch.Tensor, torch.Tensor] | None]
|
||||
residual_norm: Callable[..., torch.Tensor | None]
|
||||
residual_add: Callable[..., torch.Tensor | None]
|
||||
swiglu: Callable[..., torch.Tensor | None]
|
||||
fna: Callable[..., torch.Tensor] | None
|
||||
|
||||
|
||||
def _fna3d_tilelang(*args, **kwargs):
|
||||
# Selecting an operator set must not import the optional compiler backend.
|
||||
from .fna import fna3d_tilelang
|
||||
|
||||
return fna3d_tilelang(*args, **kwargs)
|
||||
|
||||
|
||||
@cache
|
||||
def _operator_set(with_fna: bool) -> LTX2VAEOperatorSet:
|
||||
from .qk_rms_norm import try_qk_rms_norm_scale_rope_3d_exact
|
||||
from .residual_adaln import try_residual_add3_exact, try_residual_rms_norm_modulate_exact
|
||||
from .swiglu import try_swiglu_tiled_exact
|
||||
|
||||
return LTX2VAEOperatorSet(
|
||||
qk_norm_rope=try_qk_rms_norm_scale_rope_3d_exact,
|
||||
residual_norm=try_residual_rms_norm_modulate_exact,
|
||||
residual_add=try_residual_add3_exact,
|
||||
swiglu=try_swiglu_tiled_exact,
|
||||
fna=_fna3d_tilelang if with_fna else None,
|
||||
)
|
||||
|
||||
|
||||
@cache
|
||||
def _cuda_compute_capability(device_index: int) -> int | None:
|
||||
if not HAS_TRITON or not current_omni_platform.is_cuda() or not current_omni_platform.is_available():
|
||||
return None
|
||||
capability = current_omni_platform.get_device_capability(device_id=device_index)
|
||||
return capability.to_int() if capability is not None else None
|
||||
|
||||
|
||||
def resolve_ltx2_vae_operators(device: torch.device) -> LTX2VAEOperatorSet | None:
|
||||
"""Select the production operators, or return None for unsupported devices."""
|
||||
if device.type != "cuda" or not current_omni_platform.is_cuda() or not current_omni_platform.is_available():
|
||||
return None
|
||||
device_index = device.index if device.index is not None else torch.accelerator.current_device_index()
|
||||
capability = _cuda_compute_capability(int(device_index))
|
||||
if capability not in _FUSION_CUDA_COMPUTE_CAPABILITIES:
|
||||
return None
|
||||
return _operator_set(capability in _FNA_CUDA_COMPUTE_CAPABILITIES and has_tilelang())
|
||||
|
||||
|
||||
def _eligible_operators(tensor: torch.Tensor) -> LTX2VAEOperatorSet | None:
|
||||
if not tensor.is_cuda or torch.compiler.is_compiling() or torch.is_grad_enabled():
|
||||
return None
|
||||
return resolve_ltx2_vae_operators(tensor.device)
|
||||
|
||||
|
||||
def is_ltx2_fusion_eligible(tensor: torch.Tensor) -> bool:
|
||||
"""Allow self-verifying pointwise fusions on qualified CUDA devices."""
|
||||
|
||||
return _eligible_operators(tensor) is not None
|
||||
|
||||
|
||||
def is_ltx2_fna_eligible(tensor: torch.Tensor) -> bool:
|
||||
"""Keep the strict, Hopper-tuned TileLang FNA schedule on SM90."""
|
||||
|
||||
operators = _eligible_operators(tensor)
|
||||
return operators is not None and operators.fna is not None
|
||||
|
||||
|
||||
__all__ = ["LTX2VAEOperatorSet", "resolve_ltx2_vae_operators", "is_ltx2_fna_eligible", "is_ltx2_fusion_eligible"]
|
||||
@@ -0,0 +1,86 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Numerical primitives shared by exact LTX-2 Triton kernels."""
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def round_bf16_to_fp32(value):
|
||||
"""RNE-round FP32 to BF16 precision while retaining an FP32 register."""
|
||||
|
||||
bits = value.to(tl.int32, bitcast=True)
|
||||
rounding_bias = 0x7FFF + ((bits >> 16) & 1)
|
||||
rounded_bits = (bits + rounding_bias) & -65536
|
||||
return rounded_bits.to(tl.float32, bitcast=True)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def add_rn_f32(x, y):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="add.rn.f32 $0, $1, $2;",
|
||||
constraints="=f,f,f",
|
||||
args=[x, y],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def mul_rn_f32(x, y):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="mul.rn.f32 $0, $1, $2;",
|
||||
constraints="=f,f,f",
|
||||
args=[x, y],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def fma_rn_f32(x, y, accumulator):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="fma.rn.f32 $0, $1, $2, $3;",
|
||||
constraints="=f,f,f,f",
|
||||
args=[x, y, accumulator],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def rsqrt_approx_f32(x):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="rsqrt.approx.f32 $0, $1;",
|
||||
constraints="=f,f",
|
||||
args=[x],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def shfl_down_f32(value, delta: tl.constexpr):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="shfl.sync.down.b32 $0, $1, $2, 0x1f, 0xffffffff;",
|
||||
constraints="=f,f,n",
|
||||
args=[value, delta],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"add_rn_f32",
|
||||
"fma_rn_f32",
|
||||
"mul_rn_f32",
|
||||
"round_bf16_to_fp32",
|
||||
"rsqrt_approx_f32",
|
||||
"shfl_down_f32",
|
||||
]
|
||||
@@ -0,0 +1,525 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""TileLang FNA for the LTX-2.5 DiffVAE stage-5 schedule.
|
||||
|
||||
This intentionally reuses NATTEN's token permutation. It only replaces the
|
||||
middle BF16 attention kernel for Q tiles (4, 4, 4), KV tiles (4, 4, 8),
|
||||
head_dim=64, stride=dilation=1, and scale=1.0.
|
||||
"""
|
||||
|
||||
import functools
|
||||
import math
|
||||
from collections import OrderedDict
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
from vllm.tilelang_utils import T, tilelang
|
||||
|
||||
Q_TILE = (4, 4, 4)
|
||||
KV_TILE = (4, 4, 8)
|
||||
Q_TOKENS = math.prod(Q_TILE)
|
||||
KV_TOKENS = math.prod(KV_TILE)
|
||||
HEAD_DIM = 64
|
||||
HEADS = 4
|
||||
LOG2_E = 1.4426950408889634
|
||||
KV_BUCKET_LIMITS = (32, 48, 60, 75)
|
||||
PATTERN_TABLE_SIZE = 16
|
||||
KV_TILE_ID_BITS = 15
|
||||
SHAPE_CACHE_SIZE = 16
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Problem:
|
||||
frames: int
|
||||
height: int
|
||||
width: int
|
||||
window: tuple[int, int, int]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if min(self.frames, self.height, self.width) <= 0:
|
||||
raise ValueError(f"invalid FNA problem: {self}")
|
||||
if len(self.window) != 3 or any(x <= 0 for x in self.window):
|
||||
raise ValueError(f"invalid FNA window: {self.window}")
|
||||
if any(w > n for w, n in zip(self.window, self.shape)):
|
||||
raise ValueError(f"window {self.window} exceeds shape {self.shape}")
|
||||
if math.prod(self.kv_grid) > 1 << KV_TILE_ID_BITS:
|
||||
raise ValueError(f"KV tile grid exceeds {KV_TILE_ID_BITS}-bit metadata encoding: {self.kv_grid}")
|
||||
|
||||
@property
|
||||
def shape(self) -> tuple[int, int, int]:
|
||||
return self.frames, self.height, self.width
|
||||
|
||||
@property
|
||||
def q_padded(self) -> tuple[int, int, int]:
|
||||
return tuple(_round_up(n, tile) for n, tile in zip(self.shape, Q_TILE))
|
||||
|
||||
@property
|
||||
def kv_padded(self) -> tuple[int, int, int]:
|
||||
return tuple(_round_up(n, tile) for n, tile in zip(self.shape, KV_TILE))
|
||||
|
||||
@property
|
||||
def q_grid(self) -> tuple[int, int, int]:
|
||||
return tuple(n // tile for n, tile in zip(self.q_padded, Q_TILE))
|
||||
|
||||
@property
|
||||
def kv_grid(self) -> tuple[int, int, int]:
|
||||
return tuple(n // tile for n, tile in zip(self.kv_padded, KV_TILE))
|
||||
|
||||
@property
|
||||
def q_length(self) -> int:
|
||||
return math.prod(self.q_padded)
|
||||
|
||||
@property
|
||||
def kv_length(self) -> int:
|
||||
return math.prod(self.kv_padded)
|
||||
|
||||
|
||||
def _round_up(value: int, multiple: int) -> int:
|
||||
return (value + multiple - 1) // multiple * multiple
|
||||
|
||||
|
||||
def _window_start(index: int, window: int, length: int) -> int:
|
||||
return min(max(index - window // 2, 0), length - window)
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=32)
|
||||
def _dimension_pattern_table(
|
||||
length: int,
|
||||
q_tile_size: int,
|
||||
kv_tile_size: int,
|
||||
window: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Map (Q tile, KV tile) pairs to a small table of packed 1D masks."""
|
||||
q_tiles = _round_up(length, q_tile_size) // q_tile_size
|
||||
kv_tiles = _round_up(length, kv_tile_size) // kv_tile_size
|
||||
zero = (0,) * q_tile_size
|
||||
patterns: list[tuple[int, ...]] = [zero]
|
||||
pattern_ids = {zero: 0}
|
||||
ids = torch.zeros((q_tiles, kv_tiles), dtype=torch.int64)
|
||||
|
||||
for q_tile in range(q_tiles):
|
||||
for kv_tile in range(kv_tiles):
|
||||
rows: list[int] = []
|
||||
for q_inner in range(q_tile_size):
|
||||
q = q_tile * q_tile_size + q_inner
|
||||
bits = 0
|
||||
if q < length:
|
||||
start = _window_start(q, window, length)
|
||||
for kv_inner in range(kv_tile_size):
|
||||
kv = kv_tile * kv_tile_size + kv_inner
|
||||
if kv < length and start <= kv < start + window:
|
||||
bits |= 1 << kv_inner
|
||||
rows.append(bits)
|
||||
signature = tuple(rows)
|
||||
pattern_id = pattern_ids.get(signature)
|
||||
if pattern_id is None:
|
||||
pattern_id = len(patterns)
|
||||
pattern_ids[signature] = pattern_id
|
||||
patterns.append(signature)
|
||||
ids[q_tile, kv_tile] = pattern_id
|
||||
|
||||
if len(patterns) > PATTERN_TABLE_SIZE:
|
||||
raise AssertionError(f"4-bit pattern id overflow for length={length}: {len(patterns)}")
|
||||
packed = []
|
||||
for pattern in patterns:
|
||||
value = sum(bits << (q * kv_tile_size) for q, bits in enumerate(pattern))
|
||||
# Store uint32 bit patterns in an int32 tensor. Arithmetic right shift
|
||||
# followed by `& 1` still extracts the desired bit when bit 31 is set.
|
||||
packed.append(value if value < (1 << 31) else value - (1 << 32))
|
||||
# The four-bit pattern ids address at most 16 entries. Pad to that fixed
|
||||
# size so T/H/W-specific table lengths cannot specialize the GPU kernel.
|
||||
packed.extend([0] * (PATTERN_TABLE_SIZE - len(packed)))
|
||||
return ids, torch.tensor(packed, dtype=torch.int32)
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=SHAPE_CACHE_SIZE)
|
||||
def build_kv_tile_map(problem: Problem) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Return packed KV tile ids and valid counts for each permuted Q tile."""
|
||||
q_grid_t, q_grid_h, q_grid_w = problem.q_grid
|
||||
kv_grid_t, kv_grid_h, _ = problem.kv_grid
|
||||
rows: list[list[int]] = []
|
||||
|
||||
# Token permutation flattens outer tile modes as (W, H, T), with T
|
||||
# changing fastest. Keep KV tiles in the same increasing linear order.
|
||||
for q_w_tile in range(q_grid_w):
|
||||
for q_h_tile in range(q_grid_h):
|
||||
for q_t_tile in range(q_grid_t):
|
||||
ranges: list[range] = []
|
||||
for q_tile_idx, q_tile_size, kv_tile_size, window, length in zip(
|
||||
(q_t_tile, q_h_tile, q_w_tile),
|
||||
Q_TILE,
|
||||
KV_TILE,
|
||||
problem.window,
|
||||
problem.shape,
|
||||
):
|
||||
first_q = q_tile_idx * q_tile_size
|
||||
last_q = min(first_q + q_tile_size, length) - 1
|
||||
first_k = _window_start(first_q, window, length)
|
||||
last_k = _window_start(last_q, window, length) + window - 1
|
||||
ranges.append(range(first_k // kv_tile_size, last_k // kv_tile_size + 1))
|
||||
|
||||
t_tiles, h_tiles, w_tiles = ranges
|
||||
row = [
|
||||
(kv_w * kv_grid_h + kv_h) * kv_grid_t + kv_t
|
||||
for kv_w in w_tiles
|
||||
for kv_h in h_tiles
|
||||
for kv_t in t_tiles
|
||||
]
|
||||
if not row:
|
||||
raise AssertionError("every Q tile must overlap at least one KV tile")
|
||||
rows.append(row)
|
||||
|
||||
max_tiles = max(map(len, rows))
|
||||
# Duplicate a valid tile in padding slots. The kernel masks those slots
|
||||
# with `counts`; avoiding -1 keeps every indirect global load in bounds.
|
||||
indices = torch.tensor(
|
||||
[row + [row[0]] * (max_tiles - len(row)) for row in rows],
|
||||
dtype=torch.int32,
|
||||
)
|
||||
counts = torch.tensor([len(row) for row in rows], dtype=torch.int32)
|
||||
return indices, counts
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=SHAPE_CACHE_SIZE)
|
||||
def build_kv_tile_metadata(
|
||||
problem: Problem,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Pack KV tile id and three separable mask pattern ids into int32."""
|
||||
indices, counts = build_kv_tile_map(problem)
|
||||
q_grid_t, q_grid_h, _ = problem.q_grid
|
||||
kv_grid_t, kv_grid_h, _ = problem.kv_grid
|
||||
t_ids, t_patterns = _dimension_pattern_table(problem.frames, Q_TILE[0], KV_TILE[0], problem.window[0])
|
||||
h_ids, h_patterns = _dimension_pattern_table(problem.height, Q_TILE[1], KV_TILE[1], problem.window[1])
|
||||
w_ids, w_patterns = _dimension_pattern_table(problem.width, Q_TILE[2], KV_TILE[2], problem.window[2])
|
||||
|
||||
q_blocks = torch.arange(indices.shape[0], dtype=torch.int64)[:, None]
|
||||
q_t = q_blocks % q_grid_t
|
||||
q_h = (q_blocks // q_grid_t) % q_grid_h
|
||||
q_w = q_blocks // (q_grid_t * q_grid_h)
|
||||
kv = indices.to(torch.int64)
|
||||
kv_t = kv % kv_grid_t
|
||||
kv_h = (kv // kv_grid_t) % kv_grid_h
|
||||
kv_w = kv // (kv_grid_t * kv_grid_h)
|
||||
t_pattern_id = t_ids[q_t, kv_t]
|
||||
h_pattern_id = h_ids[q_h, kv_h]
|
||||
w_pattern_id = w_ids[q_w, kv_w]
|
||||
metadata = kv | (t_pattern_id << 15) | (h_pattern_id << 19) | (w_pattern_id << 23)
|
||||
active = torch.arange(indices.shape[1])[None, :] < counts[:, None]
|
||||
metadata = torch.where(active, metadata, 0).to(torch.int32)
|
||||
return metadata, t_patterns, h_patterns, w_patterns
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=SHAPE_CACHE_SIZE)
|
||||
def build_kv_tile_buckets(
|
||||
problem: Problem,
|
||||
) -> tuple[tuple[torch.Tensor, torch.Tensor, int], ...]:
|
||||
"""Group Q tiles by an upper bound on their useful KV tile count."""
|
||||
metadata, *_ = build_kv_tile_metadata(problem)
|
||||
_, counts = build_kv_tile_map(problem)
|
||||
maximum = int(counts.max())
|
||||
if maximum > KV_BUCKET_LIMITS[-1]:
|
||||
raise ValueError(
|
||||
f"FNA neighborhood needs {maximum} KV tiles, exceeding the supported ceiling {KV_BUCKET_LIMITS[-1]}"
|
||||
)
|
||||
buckets = []
|
||||
lower = 0
|
||||
for limit in KV_BUCKET_LIMITS:
|
||||
q_tile_ids = torch.nonzero((counts > lower) & (counts <= limit), as_tuple=False).flatten()
|
||||
if q_tile_ids.numel():
|
||||
# Small grids can have fewer columns than the first bucket limit.
|
||||
# Zero metadata encodes an all-masked tile, preserving the fixed ABI.
|
||||
bucket_metadata = torch.zeros((q_tile_ids.numel(), limit), dtype=torch.int32)
|
||||
columns = min(limit, metadata.shape[1])
|
||||
bucket_metadata[:, :columns] = metadata[q_tile_ids, :columns]
|
||||
buckets.append(
|
||||
(
|
||||
q_tile_ids.to(torch.int32),
|
||||
bucket_metadata,
|
||||
limit,
|
||||
)
|
||||
)
|
||||
lower = limit
|
||||
if limit >= maximum:
|
||||
break
|
||||
return tuple(buckets)
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=32)
|
||||
def compile_kernel(
|
||||
max_kv_tiles: int,
|
||||
*,
|
||||
target: str = "auto",
|
||||
):
|
||||
"""Compile one T/H/W-dynamic kernel for a fixed KV-count ceiling."""
|
||||
if max_kv_tiles not in KV_BUCKET_LIMITS:
|
||||
raise ValueError(f"unsupported KV bucket ceiling: {max_kv_tiles}")
|
||||
|
||||
q_length = T.dynamic("q_length")
|
||||
kv_length = T.dynamic("kv_length")
|
||||
q_tile_count = T.dynamic("q_tile_count")
|
||||
|
||||
# Batch is fixed to one by the public guard. Excluding it from the
|
||||
# kernel ABI keeps every physical stride static even when token lengths
|
||||
# vary, preserving vectorized global/shared-memory copies.
|
||||
q_shape = [q_length, HEADS, HEAD_DIM]
|
||||
kv_shape = [kv_length, HEADS, HEAD_DIM]
|
||||
q_tile_id_shape = [q_tile_count]
|
||||
map_shape = [q_tile_count, max_kv_tiles]
|
||||
pattern_shape = [PATTERN_TABLE_SIZE]
|
||||
dtype = T.bfloat16
|
||||
accum_dtype = T.float32
|
||||
|
||||
@T.prim_func
|
||||
def main(
|
||||
query: T.Tensor(q_shape, dtype),
|
||||
key: T.Tensor(kv_shape, dtype),
|
||||
value: T.Tensor(kv_shape, dtype),
|
||||
q_tile_ids: T.Tensor(q_tile_id_shape, T.int32),
|
||||
kv_tile_metadata: T.Tensor(map_shape, T.int32),
|
||||
t_mask_patterns: T.Tensor(pattern_shape, T.int32),
|
||||
h_mask_patterns: T.Tensor(pattern_shape, T.int32),
|
||||
w_mask_patterns: T.Tensor(pattern_shape, T.int32),
|
||||
output: T.Tensor(q_shape, dtype),
|
||||
):
|
||||
with T.Kernel(q_tile_count, HEADS, threads=128) as (bx, by):
|
||||
q_shared = T.alloc_shared([Q_TOKENS, HEAD_DIM], dtype)
|
||||
k_shared = T.alloc_shared([KV_TOKENS, HEAD_DIM], dtype)
|
||||
v_shared = T.alloc_shared([KV_TOKENS, HEAD_DIM], dtype)
|
||||
o_shared = T.alloc_shared([Q_TOKENS, HEAD_DIM], dtype)
|
||||
scores = T.alloc_fragment([Q_TOKENS, KV_TOKENS], accum_dtype)
|
||||
probs = T.alloc_fragment([Q_TOKENS, KV_TOKENS], dtype)
|
||||
acc_o = T.alloc_fragment([Q_TOKENS, HEAD_DIM], accum_dtype)
|
||||
row_max = T.alloc_fragment([Q_TOKENS], accum_dtype)
|
||||
row_max_prev = T.alloc_fragment([Q_TOKENS], accum_dtype)
|
||||
row_scale = T.alloc_fragment([Q_TOKENS], accum_dtype)
|
||||
row_sum = T.alloc_fragment([Q_TOKENS], accum_dtype)
|
||||
row_denom = T.alloc_fragment([Q_TOKENS], accum_dtype)
|
||||
|
||||
q_block = q_tile_ids[bx]
|
||||
# CPU metadata only emits padded Q/KV tiles that are fully backed
|
||||
# by the permuted tensors. Expose those invariants so dynamic
|
||||
# lengths do not add per-copy boundary predicates.
|
||||
T.assume(q_block >= 0)
|
||||
T.assume((q_block + 1) * Q_TOKENS <= q_length)
|
||||
T.copy(
|
||||
query[
|
||||
q_block * Q_TOKENS : (q_block + 1) * Q_TOKENS,
|
||||
by,
|
||||
:,
|
||||
],
|
||||
q_shared,
|
||||
)
|
||||
T.fill(acc_o, 0)
|
||||
T.fill(row_denom, 0)
|
||||
T.fill(row_max, -T.infinity(accum_dtype))
|
||||
|
||||
for block_iter in T.Pipelined(max_kv_tiles, num_stages=1):
|
||||
metadata = kv_tile_metadata[bx, block_iter]
|
||||
kv_block = metadata & 0x7FFF
|
||||
T.assume((kv_block + 1) * KV_TOKENS <= kv_length)
|
||||
t_mask = t_mask_patterns[(metadata >> 15) & 0xF]
|
||||
h_mask = h_mask_patterns[(metadata >> 19) & 0xF]
|
||||
w_mask = w_mask_patterns[(metadata >> 23) & 0xF]
|
||||
T.copy(
|
||||
key[
|
||||
kv_block * KV_TOKENS : (kv_block + 1) * KV_TOKENS,
|
||||
by,
|
||||
:,
|
||||
],
|
||||
k_shared,
|
||||
prefer_instruction="cp_async",
|
||||
)
|
||||
|
||||
for i, j in T.Parallel(Q_TOKENS, KV_TOKENS):
|
||||
q_t = i % Q_TILE[0]
|
||||
q_h = (i // Q_TILE[0]) % Q_TILE[1]
|
||||
q_w = i // (Q_TILE[0] * Q_TILE[1])
|
||||
k_t = j % KV_TILE[0]
|
||||
k_h = (j // KV_TILE[0]) % KV_TILE[1]
|
||||
k_w = j // (KV_TILE[0] * KV_TILE[1])
|
||||
valid = (
|
||||
(((t_mask >> (q_t * KV_TILE[0] + k_t)) & 1) != 0)
|
||||
& (((h_mask >> (q_h * KV_TILE[1] + k_h)) & 1) != 0)
|
||||
& (((w_mask >> (q_w * KV_TILE[2] + k_w)) & 1) != 0)
|
||||
)
|
||||
scores[i, j] = T.if_then_else(valid, 0, -T.infinity(accum_dtype))
|
||||
|
||||
T.gemm(
|
||||
q_shared,
|
||||
k_shared,
|
||||
scores,
|
||||
transpose_B=True,
|
||||
policy=T.GemmWarpPolicy.FullRow,
|
||||
)
|
||||
T.copy(row_max, row_max_prev)
|
||||
T.fill(row_max, -T.infinity(accum_dtype))
|
||||
T.reduce_max(scores, row_max, dim=1, clear=False)
|
||||
# A KV tile is selected for the union of all 64 queries in
|
||||
# this Q tile. It can therefore be fully masked for one
|
||||
# individual query. Preserve that row's previous online
|
||||
# softmax state instead of evaluating (-inf) - (-inf).
|
||||
T.copy(row_max, row_sum)
|
||||
for i in T.Parallel(Q_TOKENS):
|
||||
has_score = row_sum[i] > -T.infinity(accum_dtype)
|
||||
merged_max = T.max(row_sum[i], row_max_prev[i])
|
||||
row_max[i] = T.if_then_else(has_score, merged_max, row_max_prev[i])
|
||||
row_scale[i] = T.if_then_else(
|
||||
has_score,
|
||||
T.exp2((row_max_prev[i] - merged_max) * LOG2_E),
|
||||
1,
|
||||
)
|
||||
# Match Hopper NATTEN's two separately rounded FP32
|
||||
# products before exp2.
|
||||
row_sum[i] = T.if_then_else(
|
||||
has_score,
|
||||
merged_max * LOG2_E,
|
||||
-T.infinity(accum_dtype),
|
||||
)
|
||||
for i, j in T.Parallel(Q_TOKENS, KV_TOKENS):
|
||||
scores[i, j] = T.if_then_else(
|
||||
row_sum[i] > -T.infinity(accum_dtype),
|
||||
T.exp2(scores[i, j] * LOG2_E - row_sum[i]),
|
||||
0,
|
||||
)
|
||||
T.reduce_sum(scores, row_sum, dim=1)
|
||||
for i in T.Parallel(Q_TOKENS):
|
||||
row_denom[i] = row_denom[i] * row_scale[i] + row_sum[i]
|
||||
T.copy(scores, probs)
|
||||
for i, j in T.Parallel(Q_TOKENS, HEAD_DIM):
|
||||
acc_o[i, j] *= row_scale[i]
|
||||
|
||||
T.copy(
|
||||
value[
|
||||
kv_block * KV_TOKENS : (kv_block + 1) * KV_TOKENS,
|
||||
by,
|
||||
:,
|
||||
],
|
||||
v_shared,
|
||||
prefer_instruction="cp_async",
|
||||
)
|
||||
T.gemm(probs, v_shared, acc_o, policy=T.GemmWarpPolicy.FullRow)
|
||||
|
||||
# Match NATTEN's epilogue: compute one reciprocal per query row,
|
||||
# then multiply every output accumulator by that shared alpha.
|
||||
for i in T.Parallel(Q_TOKENS):
|
||||
row_scale[i] = T.if_then_else(
|
||||
row_denom[i] > 0,
|
||||
T.call_extern("float32", "__frcp_rn", row_denom[i]),
|
||||
0,
|
||||
)
|
||||
for i, j in T.Parallel(Q_TOKENS, HEAD_DIM):
|
||||
acc_o[i, j] *= row_scale[i]
|
||||
T.copy(acc_o, o_shared)
|
||||
T.copy(
|
||||
o_shared,
|
||||
output[
|
||||
q_block * Q_TOKENS : (q_block + 1) * Q_TOKENS,
|
||||
by,
|
||||
:,
|
||||
],
|
||||
)
|
||||
|
||||
return tilelang.compile(
|
||||
main,
|
||||
out_idx=None,
|
||||
target="auto" if target == "auto" else {"kind": "cuda", "arch": target},
|
||||
pass_configs={
|
||||
tilelang.PassConfigKey.TL_ENABLE_FAST_MATH: True,
|
||||
# Keeping all work in the 128-thread consumer warpgroup avoids a
|
||||
# separate producer warpgroup. The generated 240-register
|
||||
# consumer can then admit two CTAs per SM instead of one.
|
||||
tilelang.PassConfigKey.TL_DISABLE_WARP_SPECIALIZED: True,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
_DEVICE_MAP_CACHE: OrderedDict[tuple[Problem, torch.device], tuple[object, ...]] = OrderedDict()
|
||||
|
||||
|
||||
def _fna3d_tilelang(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
*,
|
||||
shape: tuple[int, int, int],
|
||||
window: tuple[int, int, int],
|
||||
) -> torch.Tensor:
|
||||
problem = Problem(*shape, window=window)
|
||||
if query.shape[1] != problem.q_length or key.shape[1] != problem.kv_length:
|
||||
raise ValueError(f"permuted lengths do not match {problem}: Q={query.shape[1]}, KV={key.shape[1]}")
|
||||
cache_key = (problem, query.device)
|
||||
device_inputs = _DEVICE_MAP_CACHE.get(cache_key)
|
||||
if device_inputs is None:
|
||||
_, t_patterns, h_patterns, w_patterns = build_kv_tile_metadata(problem)
|
||||
pattern_tables = tuple(
|
||||
tensor.to(query.device, non_blocking=True) for tensor in (t_patterns, h_patterns, w_patterns)
|
||||
)
|
||||
buckets = tuple(
|
||||
(
|
||||
q_tile_ids.to(query.device, non_blocking=True),
|
||||
metadata.to(query.device, non_blocking=True),
|
||||
limit,
|
||||
)
|
||||
for q_tile_ids, metadata, limit in build_kv_tile_buckets(problem)
|
||||
)
|
||||
device_inputs = (pattern_tables, buckets)
|
||||
_DEVICE_MAP_CACHE[cache_key] = device_inputs
|
||||
if len(_DEVICE_MAP_CACHE) > SHAPE_CACHE_SIZE:
|
||||
_DEVICE_MAP_CACHE.popitem(last=False)
|
||||
else:
|
||||
_DEVICE_MAP_CACHE.move_to_end(cache_key)
|
||||
|
||||
pattern_tables, buckets = device_inputs
|
||||
output = torch.empty_like(query)
|
||||
for q_tile_ids, metadata, limit in buckets:
|
||||
from tilelang.backend.target import determine_target
|
||||
|
||||
target = str(determine_target("auto", return_object=True).attrs["arch"])
|
||||
kernel = compile_kernel(limit, target=target)
|
||||
for batch in range(query.shape[0]):
|
||||
kernel(query[batch], key[batch], value[batch], q_tile_ids, metadata, *pattern_tables, output[batch])
|
||||
return output
|
||||
|
||||
|
||||
def fna3d_tilelang(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
*,
|
||||
shape: tuple[int, int, int],
|
||||
window: tuple[int, int, int],
|
||||
) -> torch.Tensor:
|
||||
"""Run native stage-5 FNA, or raise for unsupported inputs/launch failures.
|
||||
|
||||
Q and KV use the documented token-tiled layout. Batch members share spatial
|
||||
metadata; compilation is cached by target architecture and KV-count bucket.
|
||||
"""
|
||||
if not (
|
||||
query.is_cuda
|
||||
and query.dtype is torch.bfloat16
|
||||
and query.ndim == key.ndim == value.ndim == 4
|
||||
and query.shape[0] > 0
|
||||
and query.shape[-2:] == (HEADS, HEAD_DIM)
|
||||
and query.numel() > 0
|
||||
and query.is_contiguous()
|
||||
and key.device == value.device == query.device
|
||||
and key.dtype is value.dtype is query.dtype
|
||||
and key.is_contiguous()
|
||||
and value.is_contiguous()
|
||||
and value.shape == key.shape
|
||||
and key.shape[0] == query.shape[0]
|
||||
and key.shape[-2:] == query.shape[-2:]
|
||||
and len(shape) == 3
|
||||
and tuple(window) == (11, 11, 11)
|
||||
):
|
||||
raise ValueError(
|
||||
"LTX DiffVAE FNA requires contiguous CUDA BF16 [B, tokens, 4, 64] Q/K/V and an 11x11x11 window."
|
||||
)
|
||||
if torch.is_grad_enabled() and any(x.requires_grad for x in (query, key, value)):
|
||||
raise RuntimeError("LTX DiffVAE FNA is inference-only.")
|
||||
with torch.accelerator.device_index(query.device.index):
|
||||
return _fna3d_tilelang(query, key, value, shape=tuple(shape), window=tuple(window))
|
||||
|
||||
|
||||
__all__ = ["fna3d_tilelang"]
|
||||
@@ -0,0 +1,377 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Bit-exact multi-row Q/K RMSNorm for the LTX diffusion VAE decoder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from . import is_ltx2_fusion_eligible
|
||||
from ._numerics import (
|
||||
add_rn_f32,
|
||||
fma_rn_f32,
|
||||
mul_rn_f32,
|
||||
round_bf16_to_fp32,
|
||||
rsqrt_approx_f32,
|
||||
shfl_down_f32,
|
||||
)
|
||||
from .rope_tables import get_rope_tables
|
||||
|
||||
_HEAD_DIM = 64
|
||||
_ROWS_PER_PROGRAM = 2
|
||||
_VERIFY_ROWS = 256
|
||||
_FAILED_ROPE_KEYS: set[tuple[int | None, float, float, tuple[int, int, int], float]] = set()
|
||||
_VERIFIED_ROPE_KEYS: set[tuple[int | None, float, float, tuple[int, int, int], float]] = set()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _shuffle_lane_zero(value):
|
||||
return tl.inline_asm_elementwise(
|
||||
asm="shfl.sync.idx.b32 $0, $1, 0, 0x1f, 0xffffffff;",
|
||||
constraints="=f,f",
|
||||
args=[value],
|
||||
dtype=tl.float32,
|
||||
is_pure=True,
|
||||
pack=1,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _warp_sum(value):
|
||||
value = add_rn_f32(value, shfl_down_f32(value, 16))
|
||||
value = add_rn_f32(value, shfl_down_f32(value, 8))
|
||||
value = add_rn_f32(value, shfl_down_f32(value, 4))
|
||||
value = add_rn_f32(value, shfl_down_f32(value, 2))
|
||||
value = add_rn_f32(value, shfl_down_f32(value, 1))
|
||||
return _shuffle_lane_zero(value)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _qk_rms_norm_scale_rope_3d_kernel(
|
||||
query_output_ptr,
|
||||
key_output_ptr,
|
||||
query_ptr,
|
||||
key_ptr,
|
||||
query_weight_ptr,
|
||||
key_weight_ptr,
|
||||
cos_t_ptr,
|
||||
sin_t_ptr,
|
||||
cos_h_ptr,
|
||||
sin_h_ptr,
|
||||
cos_w_ptr,
|
||||
sin_w_ptr,
|
||||
rows,
|
||||
tokens_per_batch,
|
||||
height,
|
||||
width,
|
||||
heads,
|
||||
eps,
|
||||
query_scale,
|
||||
rows_per_program: tl.constexpr,
|
||||
head_dim: tl.constexpr,
|
||||
pairs_t: tl.constexpr,
|
||||
pairs_h: tl.constexpr,
|
||||
):
|
||||
threads = tl.arange(0, rows_per_program * 32)
|
||||
local_row = threads // 32
|
||||
lane = threads % 32
|
||||
row = tl.program_id(0).to(tl.int64) * rows_per_program + local_row
|
||||
valid_row = row < rows
|
||||
reduction_valid = valid_row & (lane < 16)
|
||||
reduction_base = row * head_dim + lane * 4
|
||||
|
||||
query_accumulator = tl.zeros((rows_per_program * 32,), dtype=tl.float32)
|
||||
key_accumulator = tl.zeros((rows_per_program * 32,), dtype=tl.float32)
|
||||
for element in tl.static_range(4):
|
||||
query = tl.load(query_ptr + reduction_base + element, mask=reduction_valid, other=0.0).to(tl.float32)
|
||||
key = tl.load(key_ptr + reduction_base + element, mask=reduction_valid, other=0.0).to(tl.float32)
|
||||
query_accumulator = fma_rn_f32(query, query, query_accumulator)
|
||||
key_accumulator = fma_rn_f32(key, key, key_accumulator)
|
||||
query_rstd = rsqrt_approx_f32(_warp_sum(query_accumulator) / head_dim + eps)
|
||||
key_rstd = rsqrt_approx_f32(_warp_sum(key_accumulator) / head_dim + eps)
|
||||
|
||||
tokens = (row // heads) % tokens_per_batch
|
||||
pos_w = tokens % width
|
||||
pos_h = (tokens // width) % height
|
||||
pos_t = tokens // (height * width)
|
||||
pairs_per_head: tl.constexpr = head_dim // 2
|
||||
pairs_w: tl.constexpr = pairs_per_head - pairs_t - pairs_h
|
||||
is_t = lane < pairs_t
|
||||
is_h = (lane >= pairs_t) & (lane < pairs_t + pairs_h)
|
||||
is_w = ~(is_t | is_h)
|
||||
pair_t = lane
|
||||
pair_h = lane - pairs_t
|
||||
pair_w = lane - pairs_t - pairs_h
|
||||
cos_t = tl.load(cos_t_ptr + pos_t * pairs_t + pair_t, mask=valid_row & is_t, other=0.0)
|
||||
sin_t = tl.load(sin_t_ptr + pos_t * pairs_t + pair_t, mask=valid_row & is_t, other=0.0)
|
||||
cos_h = tl.load(cos_h_ptr + pos_h * pairs_h + pair_h, mask=valid_row & is_h, other=0.0)
|
||||
sin_h = tl.load(sin_h_ptr + pos_h * pairs_h + pair_h, mask=valid_row & is_h, other=0.0)
|
||||
cos_w = tl.load(cos_w_ptr + pos_w * pairs_w + pair_w, mask=valid_row & is_w, other=0.0)
|
||||
sin_w = tl.load(sin_w_ptr + pos_w * pairs_w + pair_w, mask=valid_row & is_w, other=0.0)
|
||||
cos = cos_t + cos_h + cos_w
|
||||
sin = sin_t + sin_h + sin_w
|
||||
|
||||
even_column = lane * 2
|
||||
odd_column = even_column + 1
|
||||
even_offset = row * head_dim + even_column
|
||||
odd_offset = row * head_dim + odd_column
|
||||
query_even = tl.load(query_ptr + even_offset, mask=valid_row).to(tl.float32)
|
||||
query_odd = tl.load(query_ptr + odd_offset, mask=valid_row).to(tl.float32)
|
||||
key_even = tl.load(key_ptr + even_offset, mask=valid_row).to(tl.float32)
|
||||
key_odd = tl.load(key_ptr + odd_offset, mask=valid_row).to(tl.float32)
|
||||
query_even_weight = tl.load(query_weight_ptr + even_column).to(tl.float32)
|
||||
query_odd_weight = tl.load(query_weight_ptr + odd_column).to(tl.float32)
|
||||
key_even_weight = tl.load(key_weight_ptr + even_column).to(tl.float32)
|
||||
key_odd_weight = tl.load(key_weight_ptr + odd_column).to(tl.float32)
|
||||
|
||||
query_even = round_bf16_to_fp32(mul_rn_f32(query_even_weight, mul_rn_f32(query_rstd, query_even)))
|
||||
query_odd = round_bf16_to_fp32(mul_rn_f32(query_odd_weight, mul_rn_f32(query_rstd, query_odd)))
|
||||
query_even = round_bf16_to_fp32(mul_rn_f32(query_even, query_scale))
|
||||
query_odd = round_bf16_to_fp32(mul_rn_f32(query_odd, query_scale))
|
||||
key_even = round_bf16_to_fp32(mul_rn_f32(key_even_weight, mul_rn_f32(key_rstd, key_even)))
|
||||
key_odd = round_bf16_to_fp32(mul_rn_f32(key_odd_weight, mul_rn_f32(key_rstd, key_odd)))
|
||||
|
||||
tl.store(
|
||||
query_output_ptr + even_offset,
|
||||
add_rn_f32(mul_rn_f32(query_even, cos), -mul_rn_f32(query_odd, sin)),
|
||||
mask=valid_row,
|
||||
)
|
||||
tl.store(
|
||||
query_output_ptr + odd_offset,
|
||||
add_rn_f32(mul_rn_f32(query_even, sin), mul_rn_f32(query_odd, cos)),
|
||||
mask=valid_row,
|
||||
)
|
||||
tl.store(
|
||||
key_output_ptr + even_offset,
|
||||
add_rn_f32(mul_rn_f32(key_even, cos), -mul_rn_f32(key_odd, sin)),
|
||||
mask=valid_row,
|
||||
)
|
||||
tl.store(
|
||||
key_output_ptr + odd_offset,
|
||||
add_rn_f32(mul_rn_f32(key_even, sin), mul_rn_f32(key_odd, cos)),
|
||||
mask=valid_row,
|
||||
)
|
||||
|
||||
|
||||
def _weight_matches(value: torch.Tensor, weight: torch.Tensor) -> bool:
|
||||
return (
|
||||
weight.is_cuda
|
||||
and weight.device == value.device
|
||||
and weight.dtype is torch.bfloat16
|
||||
and weight.shape == (_HEAD_DIM,)
|
||||
and weight.is_contiguous()
|
||||
)
|
||||
|
||||
|
||||
def _supported_inputs(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
query_weight: torch.Tensor,
|
||||
key_weight: torch.Tensor,
|
||||
eps: float,
|
||||
query_scale: float,
|
||||
) -> bool:
|
||||
return (
|
||||
is_ltx2_fusion_eligible(query)
|
||||
and query.dtype is torch.bfloat16
|
||||
and query.ndim == 6
|
||||
and query.shape[-1] == _HEAD_DIM
|
||||
and query.numel() > 0
|
||||
and query.is_contiguous()
|
||||
and key.is_cuda
|
||||
and key.device == query.device
|
||||
and key.dtype is query.dtype
|
||||
and key.shape == query.shape
|
||||
and key.is_contiguous()
|
||||
and _weight_matches(query, query_weight)
|
||||
and _weight_matches(query, key_weight)
|
||||
and math.isfinite(eps)
|
||||
and eps > 0
|
||||
and math.isfinite(query_scale)
|
||||
)
|
||||
|
||||
|
||||
def _combined_supported_inputs(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
query_weight: torch.Tensor,
|
||||
key_weight: torch.Tensor,
|
||||
eps: float,
|
||||
query_scale: float,
|
||||
dim_split: tuple[int, int, int],
|
||||
base: float,
|
||||
) -> bool:
|
||||
return (
|
||||
_supported_inputs(query, key, query_weight, key_weight, eps, query_scale)
|
||||
and len(dim_split) == 3
|
||||
and sum(dim_split) == _HEAD_DIM
|
||||
and all(dim > 0 and dim % 2 == 0 for dim in dim_split)
|
||||
and math.isfinite(base)
|
||||
and base > 0
|
||||
)
|
||||
|
||||
|
||||
def _launch_combined(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
query_weight: torch.Tensor,
|
||||
key_weight: torch.Tensor,
|
||||
eps: float,
|
||||
query_scale: float,
|
||||
dim_split: tuple[int, int, int],
|
||||
base: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
query_output = torch.empty_like(query)
|
||||
key_output = torch.empty_like(key)
|
||||
rows = query.numel() // _HEAD_DIM
|
||||
tables = get_rope_tables(query, dim_split, base)
|
||||
cos_t, sin_t = tables[0]
|
||||
cos_h, sin_h = tables[1]
|
||||
cos_w, sin_w = tables[2]
|
||||
with torch.accelerator.device_index(query.device.index):
|
||||
_qk_rms_norm_scale_rope_3d_kernel[(triton.cdiv(rows, _ROWS_PER_PROGRAM),)](
|
||||
query_output,
|
||||
key_output,
|
||||
query,
|
||||
key,
|
||||
query_weight,
|
||||
key_weight,
|
||||
cos_t,
|
||||
sin_t,
|
||||
cos_h,
|
||||
sin_h,
|
||||
cos_w,
|
||||
sin_w,
|
||||
rows,
|
||||
query.shape[1] * query.shape[2] * query.shape[3],
|
||||
query.shape[2],
|
||||
query.shape[3],
|
||||
query.shape[4],
|
||||
eps,
|
||||
query_scale,
|
||||
rows_per_program=_ROWS_PER_PROGRAM,
|
||||
head_dim=_HEAD_DIM,
|
||||
pairs_t=dim_split[0] // 2,
|
||||
pairs_h=dim_split[1] // 2,
|
||||
num_warps=_ROWS_PER_PROGRAM,
|
||||
)
|
||||
return query_output, key_output
|
||||
|
||||
|
||||
def _verify_combined_prefix(
|
||||
output: tuple[torch.Tensor, torch.Tensor],
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
query_weight: torch.Tensor,
|
||||
key_weight: torch.Tensor,
|
||||
eps: float,
|
||||
query_scale: float,
|
||||
dim_split: tuple[int, int, int],
|
||||
base: float,
|
||||
) -> bool:
|
||||
rows = min(query.numel() // _HEAD_DIM, _VERIFY_ROWS)
|
||||
query_rows = query.reshape(-1, _HEAD_DIM)[:rows]
|
||||
key_rows = key.reshape(-1, _HEAD_DIM)[:rows]
|
||||
query_rows = F.rms_norm(query_rows, (_HEAD_DIM,), query_weight, eps) * query_scale
|
||||
key_rows = F.rms_norm(key_rows, (_HEAD_DIM,), key_weight, eps)
|
||||
tables = get_rope_tables(query, dim_split, base)
|
||||
row_indices = torch.arange(rows, device=query.device)
|
||||
tokens_per_batch = query.shape[1] * query.shape[2] * query.shape[3]
|
||||
tokens = (row_indices // query.shape[4]) % tokens_per_batch
|
||||
positions = (
|
||||
tokens // (query.shape[2] * query.shape[3]),
|
||||
(tokens // query.shape[3]) % query.shape[2],
|
||||
tokens % query.shape[3],
|
||||
)
|
||||
cos = torch.cat([axis_tables[0][position] for axis_tables, position in zip(tables, positions, strict=True)], -1)
|
||||
sin = torch.cat([axis_tables[1][position] for axis_tables, position in zip(tables, positions, strict=True)], -1)
|
||||
|
||||
def rotate(value: torch.Tensor) -> torch.Tensor:
|
||||
pairs = value.reshape(rows, _HEAD_DIM // 2, 2)
|
||||
even = pairs[..., 0].float()
|
||||
odd = pairs[..., 1].float()
|
||||
return (
|
||||
torch.stack((even * cos - odd * sin, even * sin + odd * cos), -1).reshape(rows, _HEAD_DIM).to(value.dtype)
|
||||
)
|
||||
|
||||
reference = rotate(query_rows), rotate(key_rows)
|
||||
actual = tuple(value.reshape(-1, _HEAD_DIM)[:rows] for value in output)
|
||||
return all(torch.equal(a, b) for a, b in zip(actual, reference, strict=True))
|
||||
|
||||
|
||||
def try_qk_rms_norm_scale_rope_3d_exact(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
query_weight: torch.Tensor,
|
||||
key_weight: torch.Tensor,
|
||||
eps: float,
|
||||
query_scale: float,
|
||||
dim_split: tuple[int, int, int],
|
||||
base: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor] | None:
|
||||
"""Normalize Q/K, scale Q, and apply paired 3D RoPE in one kernel."""
|
||||
|
||||
if not _combined_supported_inputs(
|
||||
query,
|
||||
key,
|
||||
query_weight,
|
||||
key_weight,
|
||||
eps,
|
||||
query_scale,
|
||||
dim_split,
|
||||
base,
|
||||
):
|
||||
return None
|
||||
runtime_key = (query.device.index, float(eps), float(query_scale), dim_split, float(base))
|
||||
if runtime_key in _FAILED_ROPE_KEYS:
|
||||
return None
|
||||
try:
|
||||
output = _launch_combined(
|
||||
query,
|
||||
key,
|
||||
query_weight,
|
||||
key_weight,
|
||||
eps,
|
||||
query_scale,
|
||||
dim_split,
|
||||
base,
|
||||
)
|
||||
if runtime_key not in _VERIFIED_ROPE_KEYS:
|
||||
if not _verify_combined_prefix(
|
||||
output,
|
||||
query,
|
||||
key,
|
||||
query_weight,
|
||||
key_weight,
|
||||
eps,
|
||||
query_scale,
|
||||
dim_split,
|
||||
base,
|
||||
):
|
||||
_FAILED_ROPE_KEYS.add(runtime_key)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE Q/K RMSNorm+3D RoPE fusion on %s after a bit-exactness mismatch",
|
||||
query.device,
|
||||
)
|
||||
return None
|
||||
_VERIFIED_ROPE_KEYS.add(runtime_key)
|
||||
except Exception as exc: # noqa: BLE001 - fail closed after optimized-path failure
|
||||
_FAILED_ROPE_KEYS.add(runtime_key)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE Q/K RMSNorm+3D RoPE fusion on %s after failure: %s",
|
||||
query.device,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
return output
|
||||
|
||||
|
||||
__all__ = ["try_qk_rms_norm_scale_rope_3d_exact"]
|
||||
@@ -0,0 +1,489 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Exact LTX DiffVAE residual, RMSNorm, and AdaLN Triton fusions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from . import is_ltx2_fusion_eligible
|
||||
from ._numerics import (
|
||||
add_rn_f32,
|
||||
fma_rn_f32,
|
||||
mul_rn_f32,
|
||||
round_bf16_to_fp32,
|
||||
rsqrt_approx_f32,
|
||||
shfl_down_f32,
|
||||
)
|
||||
|
||||
_HIDDEN_SIZE = 256
|
||||
_POINTWISE_BLOCK = 1024
|
||||
_VERIFY_ROWS = 256
|
||||
_VERIFY_ELEMENTS = 1 << 20
|
||||
_FAILED_ADALN_KEYS: set[tuple[int | None, int, float]] = set()
|
||||
_VERIFIED_ADALN_KEYS: set[tuple[int | None, int, float]] = set()
|
||||
_FAILED_ADD_DEVICES: set[int | None] = set()
|
||||
_VERIFIED_ADD_DEVICES: set[int | None] = set()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _two_warp_sum(values):
|
||||
values = add_rn_f32(values, shfl_down_f32(values, 16))
|
||||
values = add_rn_f32(values, shfl_down_f32(values, 8))
|
||||
values = add_rn_f32(values, shfl_down_f32(values, 4))
|
||||
values = add_rn_f32(values, shfl_down_f32(values, 2))
|
||||
values = add_rn_f32(values, shfl_down_f32(values, 1))
|
||||
threads = tl.arange(0, 64)
|
||||
warp_0 = tl.sum(tl.where(threads == 0, values, 0.0))
|
||||
warp_1 = tl.sum(tl.where(threads == 32, values, 0.0))
|
||||
return add_rn_f32(warp_0, warp_1)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _load_ordered_residual(
|
||||
x_ptr,
|
||||
residual_a_ptr,
|
||||
residual_b_ptr,
|
||||
offset,
|
||||
valid,
|
||||
residual_count: tl.constexpr,
|
||||
):
|
||||
value = add_rn_f32(
|
||||
tl.load(x_ptr + offset, mask=valid, other=0.0).to(tl.float32),
|
||||
tl.load(residual_a_ptr + offset, mask=valid, other=0.0).to(tl.float32),
|
||||
)
|
||||
value = round_bf16_to_fp32(value)
|
||||
if residual_count == 2:
|
||||
value = add_rn_f32(
|
||||
value,
|
||||
tl.load(residual_b_ptr + offset, mask=valid, other=0.0).to(tl.float32),
|
||||
)
|
||||
value = round_bf16_to_fp32(value)
|
||||
return value
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _store_modulated(
|
||||
output_ptr,
|
||||
norm_weight_ptr,
|
||||
scale_ptr,
|
||||
shift_ptr,
|
||||
value,
|
||||
offset,
|
||||
column,
|
||||
modulation_base,
|
||||
reciprocal_rms,
|
||||
valid,
|
||||
):
|
||||
normalized = mul_rn_f32(value, reciprocal_rms)
|
||||
norm_weight = tl.load(norm_weight_ptr + column, mask=valid, other=0.0).to(tl.float32)
|
||||
normalized = round_bf16_to_fp32(mul_rn_f32(normalized, norm_weight))
|
||||
scale = tl.load(scale_ptr + modulation_base + column, mask=valid, other=0.0).to(tl.float32)
|
||||
shift = tl.load(shift_ptr + modulation_base + column, mask=valid, other=0.0).to(tl.float32)
|
||||
one_plus_scale = round_bf16_to_fp32(add_rn_f32(1.0, scale))
|
||||
product = round_bf16_to_fp32(mul_rn_f32(normalized, one_plus_scale))
|
||||
tl.store(output_ptr + offset, add_rn_f32(product, shift), mask=valid)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _residual_rms_norm_modulate_kernel(
|
||||
output_ptr,
|
||||
x_ptr,
|
||||
residual_a_ptr,
|
||||
residual_b_ptr,
|
||||
norm_weight_ptr,
|
||||
scale_ptr,
|
||||
shift_ptr,
|
||||
rows_per_batch,
|
||||
eps,
|
||||
residual_count: tl.constexpr,
|
||||
hidden_size: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
batch = row // rows_per_batch
|
||||
threads = tl.arange(0, 64)
|
||||
row_base = row * hidden_size
|
||||
|
||||
# PyTorch's BF16 RMSNorm kernel uses four contiguous values per thread for
|
||||
# hidden=256. Keep the four ordered BF16 residual values in registers so
|
||||
# the output pass does not read the large activations a second time.
|
||||
column_0 = threads * 4
|
||||
column_1 = column_0 + 1
|
||||
column_2 = column_0 + 2
|
||||
column_3 = column_0 + 3
|
||||
valid_0 = column_0 < hidden_size
|
||||
valid_1 = column_1 < hidden_size
|
||||
valid_2 = column_2 < hidden_size
|
||||
valid_3 = column_3 < hidden_size
|
||||
offset_0 = row_base + column_0
|
||||
offset_1 = row_base + column_1
|
||||
offset_2 = row_base + column_2
|
||||
offset_3 = row_base + column_3
|
||||
value_0 = _load_ordered_residual(x_ptr, residual_a_ptr, residual_b_ptr, offset_0, valid_0, residual_count)
|
||||
value_1 = _load_ordered_residual(x_ptr, residual_a_ptr, residual_b_ptr, offset_1, valid_1, residual_count)
|
||||
value_2 = _load_ordered_residual(x_ptr, residual_a_ptr, residual_b_ptr, offset_2, valid_2, residual_count)
|
||||
value_3 = _load_ordered_residual(x_ptr, residual_a_ptr, residual_b_ptr, offset_3, valid_3, residual_count)
|
||||
accumulator = fma_rn_f32(value_0, value_0, tl.zeros((64,), dtype=tl.float32))
|
||||
accumulator = fma_rn_f32(value_1, value_1, accumulator)
|
||||
accumulator = fma_rn_f32(value_2, value_2, accumulator)
|
||||
accumulator = fma_rn_f32(value_3, value_3, accumulator)
|
||||
|
||||
total = _two_warp_sum(accumulator)
|
||||
reciprocal_rms = rsqrt_approx_f32(total / hidden_size + eps)
|
||||
modulation_base = batch * hidden_size
|
||||
_store_modulated(
|
||||
output_ptr,
|
||||
norm_weight_ptr,
|
||||
scale_ptr,
|
||||
shift_ptr,
|
||||
value_0,
|
||||
offset_0,
|
||||
column_0,
|
||||
modulation_base,
|
||||
reciprocal_rms,
|
||||
valid_0,
|
||||
)
|
||||
_store_modulated(
|
||||
output_ptr,
|
||||
norm_weight_ptr,
|
||||
scale_ptr,
|
||||
shift_ptr,
|
||||
value_1,
|
||||
offset_1,
|
||||
column_1,
|
||||
modulation_base,
|
||||
reciprocal_rms,
|
||||
valid_1,
|
||||
)
|
||||
_store_modulated(
|
||||
output_ptr,
|
||||
norm_weight_ptr,
|
||||
scale_ptr,
|
||||
shift_ptr,
|
||||
value_2,
|
||||
offset_2,
|
||||
column_2,
|
||||
modulation_base,
|
||||
reciprocal_rms,
|
||||
valid_2,
|
||||
)
|
||||
_store_modulated(
|
||||
output_ptr,
|
||||
norm_weight_ptr,
|
||||
scale_ptr,
|
||||
shift_ptr,
|
||||
value_3,
|
||||
offset_3,
|
||||
column_3,
|
||||
modulation_base,
|
||||
reciprocal_rms,
|
||||
valid_3,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _residual_add3_kernel(
|
||||
output_ptr,
|
||||
x_ptr,
|
||||
residual_a_ptr,
|
||||
residual_b_ptr,
|
||||
residual_c_ptr,
|
||||
elements,
|
||||
block: tl.constexpr,
|
||||
):
|
||||
offsets = tl.program_id(0).to(tl.int64) * block + tl.arange(0, block)
|
||||
valid = offsets < elements
|
||||
value = add_rn_f32(
|
||||
tl.load(x_ptr + offsets, mask=valid, other=0.0).to(tl.float32),
|
||||
tl.load(residual_a_ptr + offsets, mask=valid, other=0.0).to(tl.float32),
|
||||
)
|
||||
value = round_bf16_to_fp32(value)
|
||||
value = add_rn_f32(
|
||||
value,
|
||||
tl.load(residual_b_ptr + offsets, mask=valid, other=0.0).to(tl.float32),
|
||||
)
|
||||
value = round_bf16_to_fp32(value)
|
||||
value = add_rn_f32(
|
||||
value,
|
||||
tl.load(residual_c_ptr + offsets, mask=valid, other=0.0).to(tl.float32),
|
||||
)
|
||||
tl.store(output_ptr + offsets, value, mask=valid)
|
||||
|
||||
|
||||
def _same_activation(x: torch.Tensor, residual: torch.Tensor) -> bool:
|
||||
return (
|
||||
residual.dtype is torch.bfloat16
|
||||
and residual.is_cuda
|
||||
and residual.device == x.device
|
||||
and residual.shape == x.shape
|
||||
and residual.is_contiguous()
|
||||
)
|
||||
|
||||
|
||||
def _modulation_matches(x: torch.Tensor, value: torch.Tensor) -> bool:
|
||||
return (
|
||||
value.dtype is torch.bfloat16
|
||||
and value.is_cuda
|
||||
and value.device == x.device
|
||||
and value.shape[-1] == _HIDDEN_SIZE
|
||||
and value.numel() == x.shape[0] * _HIDDEN_SIZE
|
||||
and value.is_contiguous()
|
||||
)
|
||||
|
||||
|
||||
def _norm_weight_matches(x: torch.Tensor, weight: torch.Tensor) -> bool:
|
||||
return (
|
||||
weight.dtype is torch.bfloat16
|
||||
and weight.is_cuda
|
||||
and weight.device == x.device
|
||||
and weight.shape == (_HIDDEN_SIZE,)
|
||||
and weight.is_contiguous()
|
||||
)
|
||||
|
||||
|
||||
def _adaln_inputs_supported(
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor | None,
|
||||
norm_weight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
eps: float,
|
||||
) -> bool:
|
||||
return (
|
||||
is_ltx2_fusion_eligible(x)
|
||||
and x.dtype is torch.bfloat16
|
||||
and x.ndim >= 2
|
||||
and x.shape[-1] == _HIDDEN_SIZE
|
||||
and x.numel() > 0
|
||||
and x.is_contiguous()
|
||||
and _same_activation(x, residual_a)
|
||||
and (residual_b is None or _same_activation(x, residual_b))
|
||||
and _norm_weight_matches(x, norm_weight)
|
||||
and _modulation_matches(x, scale)
|
||||
and _modulation_matches(x, shift)
|
||||
and math.isfinite(eps)
|
||||
and eps > 0
|
||||
)
|
||||
|
||||
|
||||
def _residual_reference(
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
hidden_states = x + residual_a
|
||||
if residual_b is not None:
|
||||
hidden_states = hidden_states + residual_b
|
||||
return hidden_states
|
||||
|
||||
|
||||
def _adaln_reference(
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor | None,
|
||||
norm_weight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
hidden_states = _residual_reference(x, residual_a, residual_b)
|
||||
normalized = F.rms_norm(hidden_states, (_HIDDEN_SIZE,), weight=norm_weight, eps=eps)
|
||||
return normalized * (1 + scale) + shift
|
||||
|
||||
|
||||
def _launch_adaln(
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor | None,
|
||||
norm_weight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
output = torch.empty_like(x)
|
||||
rows = x.numel() // _HIDDEN_SIZE
|
||||
rows_per_batch = rows // x.shape[0]
|
||||
with torch.accelerator.device_index(x.device.index):
|
||||
_residual_rms_norm_modulate_kernel[(rows,)](
|
||||
output,
|
||||
x,
|
||||
residual_a,
|
||||
x if residual_b is None else residual_b,
|
||||
norm_weight,
|
||||
scale,
|
||||
shift,
|
||||
rows_per_batch,
|
||||
eps,
|
||||
residual_count=1 if residual_b is None else 2,
|
||||
hidden_size=_HIDDEN_SIZE,
|
||||
num_warps=2,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def _verify_adaln_prefix(
|
||||
output: torch.Tensor,
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor | None,
|
||||
norm_weight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
eps: float,
|
||||
) -> bool:
|
||||
rows_per_batch = x.numel() // (x.shape[0] * _HIDDEN_SIZE)
|
||||
rows = min(rows_per_batch, _VERIFY_ROWS)
|
||||
x_rows = x.reshape(x.shape[0], rows_per_batch, _HIDDEN_SIZE)[0, :rows]
|
||||
residual_a_rows = residual_a.reshape(x.shape[0], rows_per_batch, _HIDDEN_SIZE)[0, :rows]
|
||||
residual_b_rows = (
|
||||
None if residual_b is None else residual_b.reshape(x.shape[0], rows_per_batch, _HIDDEN_SIZE)[0, :rows]
|
||||
)
|
||||
scale_row = scale.reshape(x.shape[0], 1, _HIDDEN_SIZE)[0]
|
||||
shift_row = shift.reshape(x.shape[0], 1, _HIDDEN_SIZE)[0]
|
||||
reference = _adaln_reference(
|
||||
x_rows,
|
||||
residual_a_rows,
|
||||
residual_b_rows,
|
||||
norm_weight,
|
||||
scale_row,
|
||||
shift_row,
|
||||
eps,
|
||||
)
|
||||
actual = output.reshape(x.shape[0], rows_per_batch, _HIDDEN_SIZE)[0, :rows]
|
||||
return torch.equal(actual, reference)
|
||||
|
||||
|
||||
def try_residual_rms_norm_modulate_exact(
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor | None,
|
||||
norm_weight: torch.Tensor,
|
||||
scale: torch.Tensor,
|
||||
shift: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor | None:
|
||||
"""Fuse one or two ordered BF16 residuals with RMSNorm and AdaLN."""
|
||||
|
||||
if not _adaln_inputs_supported(x, residual_a, residual_b, norm_weight, scale, shift, eps):
|
||||
return None
|
||||
residual_count = 1 if residual_b is None else 2
|
||||
runtime_key = (x.device.index, residual_count, float(eps))
|
||||
if runtime_key in _FAILED_ADALN_KEYS:
|
||||
return None
|
||||
try:
|
||||
output = _launch_adaln(x, residual_a, residual_b, norm_weight, scale, shift, eps)
|
||||
if runtime_key not in _VERIFIED_ADALN_KEYS:
|
||||
if not _verify_adaln_prefix(
|
||||
output,
|
||||
x,
|
||||
residual_a,
|
||||
residual_b,
|
||||
norm_weight,
|
||||
scale,
|
||||
shift,
|
||||
eps,
|
||||
):
|
||||
_FAILED_ADALN_KEYS.add(runtime_key)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE residual-AdaLN fusion on %s after a bit-exactness mismatch",
|
||||
x.device,
|
||||
)
|
||||
return None
|
||||
_VERIFIED_ADALN_KEYS.add(runtime_key)
|
||||
except Exception as exc: # noqa: BLE001 - fail closed after optimized-path failure
|
||||
_FAILED_ADALN_KEYS.add(runtime_key)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE residual-AdaLN fusion on %s after failure: %s",
|
||||
x.device,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
return output
|
||||
|
||||
|
||||
def _add_inputs_supported(x: torch.Tensor, residuals: tuple[torch.Tensor, ...]) -> bool:
|
||||
return (
|
||||
is_ltx2_fusion_eligible(x)
|
||||
and x.dtype is torch.bfloat16
|
||||
and x.numel() > 0
|
||||
and x.is_contiguous()
|
||||
and all(_same_activation(x, residual) for residual in residuals)
|
||||
)
|
||||
|
||||
|
||||
def _launch_add3(
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor,
|
||||
residual_c: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
output = torch.empty_like(x)
|
||||
with torch.accelerator.device_index(x.device.index):
|
||||
_residual_add3_kernel[(triton.cdiv(x.numel(), _POINTWISE_BLOCK),)](
|
||||
output,
|
||||
x,
|
||||
residual_a,
|
||||
residual_b,
|
||||
residual_c,
|
||||
x.numel(),
|
||||
block=_POINTWISE_BLOCK,
|
||||
num_warps=4,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def try_residual_add3_exact(
|
||||
x: torch.Tensor,
|
||||
residual_a: torch.Tensor,
|
||||
residual_b: torch.Tensor,
|
||||
residual_c: torch.Tensor,
|
||||
) -> torch.Tensor | None:
|
||||
"""Fuse three ordered BF16 residual additions into one pointwise pass."""
|
||||
|
||||
residuals = (residual_a, residual_b, residual_c)
|
||||
if not _add_inputs_supported(x, residuals) or x.device.index in _FAILED_ADD_DEVICES:
|
||||
return None
|
||||
try:
|
||||
output = _launch_add3(x, *residuals)
|
||||
if x.device.index not in _VERIFIED_ADD_DEVICES:
|
||||
elements = min(x.numel(), _VERIFY_ELEMENTS)
|
||||
reference = (
|
||||
_residual_reference(
|
||||
x.reshape(-1)[:elements],
|
||||
residual_a.reshape(-1)[:elements],
|
||||
residual_b.reshape(-1)[:elements],
|
||||
)
|
||||
+ residual_c.reshape(-1)[:elements]
|
||||
)
|
||||
if not torch.equal(output.reshape(-1)[:elements], reference):
|
||||
_FAILED_ADD_DEVICES.add(x.device.index)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE residual-add fusion on %s after a bit-exactness mismatch",
|
||||
x.device,
|
||||
)
|
||||
return None
|
||||
_VERIFIED_ADD_DEVICES.add(x.device.index)
|
||||
except Exception as exc: # noqa: BLE001 - fail closed after optimized-path failure
|
||||
_FAILED_ADD_DEVICES.add(x.device.index)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE residual-add fusion on %s after failure: %s",
|
||||
x.device,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
return output
|
||||
|
||||
|
||||
__all__ = [
|
||||
"try_residual_add3_exact",
|
||||
"try_residual_rms_norm_modulate_exact",
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Cached 3D RoPE tables for LTX DiffVAE kernels."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
_TABLE_CACHE_MAX = 16
|
||||
_TABLE_CACHE: dict[
|
||||
tuple[torch.device, int, int, int, tuple[int, int, int], float],
|
||||
tuple[tuple[torch.Tensor, torch.Tensor], ...],
|
||||
] = {}
|
||||
|
||||
|
||||
def _axis_tables(
|
||||
length: int,
|
||||
dim: int,
|
||||
device: torch.device,
|
||||
base: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
exponents = torch.arange(0, dim, 2, dtype=torch.float64, device=device) / dim
|
||||
inv_freqs = (1.0 / base**exponents).to(torch.float32)
|
||||
positions = torch.arange(length, dtype=torch.float32, device=device)
|
||||
angles = positions[:, None] * inv_freqs[None, :]
|
||||
return angles.cos().contiguous(), angles.sin().contiguous()
|
||||
|
||||
|
||||
def get_rope_tables(
|
||||
query: torch.Tensor,
|
||||
dim_split: tuple[int, int, int],
|
||||
base: float,
|
||||
) -> tuple[tuple[torch.Tensor, torch.Tensor], ...]:
|
||||
num_frames, height, width = query.shape[1:4]
|
||||
cache_key = (query.device, num_frames, height, width, dim_split, base)
|
||||
cached = _TABLE_CACHE.get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
tables = tuple(
|
||||
_axis_tables(length, dim, query.device, base)
|
||||
for length, dim in zip((num_frames, height, width), dim_split, strict=True)
|
||||
)
|
||||
if len(_TABLE_CACHE) >= _TABLE_CACHE_MAX:
|
||||
_TABLE_CACHE.pop(next(iter(_TABLE_CACHE)))
|
||||
_TABLE_CACHE[cache_key] = tables
|
||||
return tables
|
||||
|
||||
|
||||
__all__ = ["get_rope_tables"]
|
||||
@@ -0,0 +1,206 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Bit-exact workspace-reusing SwiGLU for the LTX diffusion VAE decoder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
from . import is_ltx2_fusion_eligible
|
||||
from ._numerics import mul_rn_f32, round_bf16_to_fp32
|
||||
|
||||
_POINTWISE_BLOCK = 1024
|
||||
_BASE_TILE_ROWS = 16384
|
||||
_MAX_TILE_HIDDEN_ELEMENTS = _BASE_TILE_ROWS * 4 * 2048
|
||||
_FAILED_KEYS: set[tuple[int | None, int, int, int, int]] = set()
|
||||
_VERIFIED_KEYS: set[tuple[int | None, int, int, int, int]] = set()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _tile_rows(rows: int, hidden: int) -> int:
|
||||
"""Bound projection storage while giving narrow MLPs larger GEMMs."""
|
||||
|
||||
budget_rows = _MAX_TILE_HIDDEN_ELEMENTS // hidden
|
||||
aligned_rows = max(_BASE_TILE_ROWS, budget_rows // _BASE_TILE_ROWS * _BASE_TILE_ROWS)
|
||||
return min(rows, aligned_rows)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _silu_mul_kernel(
|
||||
gate_ptr,
|
||||
up_ptr,
|
||||
elements,
|
||||
block: tl.constexpr,
|
||||
):
|
||||
offsets = tl.program_id(0).to(tl.int64) * block + tl.arange(0, block)
|
||||
valid = offsets < elements
|
||||
gate = tl.load(gate_ptr + offsets, mask=valid).to(tl.float32)
|
||||
up = tl.load(up_ptr + offsets, mask=valid).to(tl.float32)
|
||||
# Eager rounds SiLU to BF16 before the separate BF16 multiply.
|
||||
silu = round_bf16_to_fp32(mul_rn_f32(gate, tl.sigmoid(gate)))
|
||||
tl.store(gate_ptr + offsets, mul_rn_f32(silu, up), mask=valid)
|
||||
|
||||
|
||||
def _weight_matches(
|
||||
hidden_states: torch.Tensor,
|
||||
weight: torch.Tensor,
|
||||
shape: tuple[int, int],
|
||||
) -> bool:
|
||||
return (
|
||||
weight.is_cuda
|
||||
and weight.device == hidden_states.device
|
||||
and weight.dtype is torch.bfloat16
|
||||
and weight.shape == shape
|
||||
and weight.is_contiguous()
|
||||
)
|
||||
|
||||
|
||||
def _supported_inputs(
|
||||
hidden_states: torch.Tensor,
|
||||
gate_weight: torch.Tensor,
|
||||
up_weight: torch.Tensor,
|
||||
down_weight: torch.Tensor,
|
||||
) -> bool:
|
||||
if hidden_states.ndim < 3:
|
||||
return False
|
||||
dim = hidden_states.shape[-1]
|
||||
hidden = gate_weight.shape[0] if gate_weight.ndim == 2 else 0
|
||||
return (
|
||||
is_ltx2_fusion_eligible(hidden_states)
|
||||
and hidden_states.dtype is torch.bfloat16
|
||||
and hidden_states.shape[0] == 1
|
||||
and hidden_states.numel() > 0
|
||||
and hidden_states.is_contiguous()
|
||||
and 256 <= dim <= 2048
|
||||
and hidden == 4 * dim
|
||||
and _weight_matches(hidden_states, gate_weight, (hidden, dim))
|
||||
and _weight_matches(hidden_states, up_weight, (hidden, dim))
|
||||
and _weight_matches(hidden_states, down_weight, (dim, hidden))
|
||||
)
|
||||
|
||||
|
||||
def _silu_mul_inplace(gate: torch.Tensor, up: torch.Tensor) -> None:
|
||||
with torch.accelerator.device_index(gate.device.index):
|
||||
_silu_mul_kernel[(triton.cdiv(gate.numel(), _POINTWISE_BLOCK),)](
|
||||
gate,
|
||||
up,
|
||||
gate.numel(),
|
||||
block=_POINTWISE_BLOCK,
|
||||
num_warps=4,
|
||||
)
|
||||
|
||||
|
||||
def _reference_tile(
|
||||
hidden_states: torch.Tensor,
|
||||
gate_weight: torch.Tensor,
|
||||
up_weight: torch.Tensor,
|
||||
down_weight: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return F.linear(
|
||||
F.silu(F.linear(hidden_states, gate_weight)) * F.linear(hidden_states, up_weight),
|
||||
down_weight,
|
||||
)
|
||||
|
||||
|
||||
def _launch(
|
||||
hidden_states: torch.Tensor,
|
||||
gate_weight: torch.Tensor,
|
||||
up_weight: torch.Tensor,
|
||||
down_weight: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
dim = hidden_states.shape[-1]
|
||||
hidden = gate_weight.shape[0]
|
||||
flat = hidden_states.reshape(-1, dim)
|
||||
tile_rows = _tile_rows(flat.shape[0], hidden)
|
||||
output = torch.empty_like(flat)
|
||||
workspace_gate = torch.empty((tile_rows, hidden), device=flat.device, dtype=flat.dtype)
|
||||
for start in range(0, flat.shape[0], tile_rows):
|
||||
end = min(start + tile_rows, flat.shape[0])
|
||||
tokens = end - start
|
||||
tile = flat[start:end]
|
||||
gate = workspace_gate[:tokens]
|
||||
torch.mm(tile, gate_weight.t(), out=gate)
|
||||
up = torch.mm(tile, up_weight.t())
|
||||
_silu_mul_inplace(gate, up)
|
||||
torch.mm(gate, down_weight.t(), out=output[start:end])
|
||||
return output.reshape(hidden_states.shape)
|
||||
|
||||
|
||||
def _verify_edge_tiles(
|
||||
output: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
gate_weight: torch.Tensor,
|
||||
up_weight: torch.Tensor,
|
||||
down_weight: torch.Tensor,
|
||||
) -> bool:
|
||||
from diffusers.models.autoencoders.ltx2_diffusion_decoder import _SWIGLU_TILE_SIZE
|
||||
|
||||
dim = hidden_states.shape[-1]
|
||||
flat = hidden_states.reshape(-1, dim)
|
||||
actual = output.reshape(-1, dim)
|
||||
tile_rows = _tile_rows(flat.shape[0], gate_weight.shape[0])
|
||||
starts = {0, ((flat.shape[0] - 1) // tile_rows) * tile_rows}
|
||||
for start in starts:
|
||||
end = min(start + tile_rows, flat.shape[0])
|
||||
# Match upstream's token tiling, not the optimized GEMM shape: changing
|
||||
# the matmul row count can change its reduction order and BF16 output.
|
||||
for reference_start in range(start, end, _SWIGLU_TILE_SIZE):
|
||||
reference_end = min(reference_start + _SWIGLU_TILE_SIZE, end)
|
||||
if not torch.equal(
|
||||
actual[reference_start:reference_end],
|
||||
_reference_tile(flat[reference_start:reference_end], gate_weight, up_weight, down_weight),
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def try_swiglu_tiled_exact(
|
||||
hidden_states: torch.Tensor,
|
||||
gate_weight: torch.Tensor,
|
||||
up_weight: torch.Tensor,
|
||||
down_weight: torch.Tensor,
|
||||
) -> torch.Tensor | None:
|
||||
"""Run workspace-reusing tiled SwiGLU, or expose the original module."""
|
||||
|
||||
if not _supported_inputs(hidden_states, gate_weight, up_weight, down_weight):
|
||||
return None
|
||||
rows = hidden_states.numel() // hidden_states.shape[-1]
|
||||
tile_rows = _tile_rows(rows, gate_weight.shape[0])
|
||||
runtime_key = (
|
||||
hidden_states.device.index,
|
||||
hidden_states.shape[-1],
|
||||
gate_weight.shape[0],
|
||||
tile_rows,
|
||||
(rows - 1) % tile_rows + 1,
|
||||
)
|
||||
if runtime_key in _FAILED_KEYS:
|
||||
return None
|
||||
try:
|
||||
output = _launch(hidden_states, gate_weight, up_weight, down_weight)
|
||||
if runtime_key not in _VERIFIED_KEYS:
|
||||
if not _verify_edge_tiles(output, hidden_states, gate_weight, up_weight, down_weight):
|
||||
_FAILED_KEYS.add(runtime_key)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE tiled SwiGLU fusion on %s after a bit-exactness mismatch",
|
||||
hidden_states.device,
|
||||
)
|
||||
return None
|
||||
_VERIFIED_KEYS.add(runtime_key)
|
||||
except Exception as exc: # noqa: BLE001 - fail closed after optimized-path failure
|
||||
_FAILED_KEYS.add(runtime_key)
|
||||
logger.warning(
|
||||
"Disabling LTX DiffVAE tiled SwiGLU fusion on %s after failure: %s",
|
||||
hidden_states.device,
|
||||
exc,
|
||||
)
|
||||
return None
|
||||
return output
|
||||
|
||||
|
||||
__all__ = ["try_swiglu_tiled_exact"]
|
||||
@@ -0,0 +1,4 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Ordinary LTX-2.5 DiffVAE, tiled decoding and acceleration operators."""
|
||||
+185
@@ -7,19 +7,24 @@
|
||||
|
||||
"""LTX-2.5 Native-weight adapter for Diffusers' diffusion VAE decoder."""
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping
|
||||
from functools import cache
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from diffusers.models.autoencoders import (
|
||||
LTX2VideoDiffusionDecoderModel as DiffusersLTX2VideoDiffusionDecoderModel,
|
||||
)
|
||||
from diffusers.models.autoencoders import ltx2_diffusion_decoder as diffusers_decoder
|
||||
from diffusers.models.autoencoders.ltx2_diffusion_decoder import (
|
||||
LTX2VideoDiffusionDecoder3d as DiffusersLTX2VideoDiffusionDecoder3d,
|
||||
)
|
||||
from diffusers.models.autoencoders.vae import DecoderOutput
|
||||
from safetensors import safe_open
|
||||
|
||||
from ..ops import is_ltx2_fna_eligible, is_ltx2_fusion_eligible, resolve_ltx2_vae_operators
|
||||
|
||||
LTX25_NATIVE_DIFFUSION_DECODER_REPO_ID = "Lightricks/LTX-2.5"
|
||||
LTX25_NATIVE_ARTIFACT_REVISION = "8a4ff96f581e72bedc1b44367581c49d544a05f1"
|
||||
LTX25_NATIVE_DIFFUSION_DECODER_FILENAME = "vae/ltx-2.5-video-vae-bf16.safetensors"
|
||||
@@ -131,6 +136,177 @@ def load_ltx25_native_diffusion_decoder_state_dict(path: str) -> dict[str, torch
|
||||
return convert_ltx25_native_diffusion_decoder_state_dict(native_state_dict)
|
||||
|
||||
|
||||
@cache
|
||||
def _load_natten_token_permutation():
|
||||
from kernels import get_kernel
|
||||
|
||||
natten = get_kernel("shi-labs/natten", version=1)
|
||||
return natten.token_permute.token_permute_operation, natten.token_permute.token_unpermute_operation
|
||||
|
||||
|
||||
class LTX2VideoVaeNeighborhoodNattenProcessor(diffusers_decoder.LTX2VideoVaeNeighborhoodNattenProcessor):
|
||||
"""NATTEN dispatch with Omni FNA for eligible stage-5 grids."""
|
||||
|
||||
def __call__(
|
||||
self, attn: "LTX2VideoVaeNeighborhoodAttention", hidden_states: torch.Tensor, block_mask=None
|
||||
) -> torch.Tensor:
|
||||
batch_size, num_frames, height, width, channels = hidden_states.shape
|
||||
query, key, value = attn.project_qkv(hidden_states)
|
||||
# NATTEN's CUTLASS kernels silently produce wrong output for non-contiguous inputs.
|
||||
query, key, value = query.contiguous(), key.contiguous(), value.contiguous()
|
||||
operators = resolve_ltx2_vae_operators(hidden_states.device) if is_ltx2_fna_eligible(hidden_states) else None
|
||||
# `scale=1.0`: the query is already scaled in `project_qkv`, as in the reference.
|
||||
if (
|
||||
tuple(attn.kernel_size) == (11, 11, 11)
|
||||
and hidden_states.dtype == torch.bfloat16
|
||||
and channels == 256
|
||||
and attn.head_dim == 64
|
||||
and operators is not None
|
||||
and operators.fna is not None
|
||||
# The native metadata encodes KV tile indices in 15 bits.
|
||||
and math.prod((n + tile - 1) // tile for n, tile in zip((num_frames, height, width), (4, 4, 8))) <= 1 << 15
|
||||
):
|
||||
token_permute, token_unpermute = _load_natten_token_permutation()
|
||||
query_permuted, token_shape, _ = token_permute(query, (4, 4, 4), flip_tiled_dims=True)
|
||||
key_permuted, _, _ = token_permute(key, (4, 4, 8), flip_tiled_dims=True)
|
||||
value_permuted, _, _ = token_permute(value, (4, 4, 8), flip_tiled_dims=True)
|
||||
output = operators.fna(
|
||||
query_permuted,
|
||||
key_permuted,
|
||||
value_permuted,
|
||||
shape=(num_frames, height, width),
|
||||
window=tuple(attn.kernel_size),
|
||||
)
|
||||
hidden_states = token_unpermute(
|
||||
output,
|
||||
token_layout_shape=token_shape,
|
||||
tile_shape=(4, 4, 4),
|
||||
flip_tiled_dims=True,
|
||||
)
|
||||
else:
|
||||
hidden_states = self._na3d(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
kernel_size=attn.kernel_size,
|
||||
scale=1.0,
|
||||
backend=self.backend,
|
||||
)
|
||||
hidden_states = hidden_states.reshape(batch_size, num_frames, height, width, channels)
|
||||
return attn.to_out[0](hidden_states)
|
||||
|
||||
|
||||
class LTX2VideoVaeNeighborhoodAttention(diffusers_decoder.LTX2VideoVaeNeighborhoodAttention):
|
||||
_available_processors = [
|
||||
*diffusers_decoder.LTX2VideoVaeNeighborhoodAttention._available_processors,
|
||||
LTX2VideoVaeNeighborhoodNattenProcessor,
|
||||
]
|
||||
|
||||
def project_qkv(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
batch_size, num_frames, height, width, _ = hidden_states.shape
|
||||
shape = (batch_size, num_frames, height, width, self.heads, self.head_dim)
|
||||
query = self.to_q(hidden_states).view(shape)
|
||||
key = self.to_k(hidden_states).view(shape)
|
||||
value = self.to_v(hidden_states).view(shape)
|
||||
|
||||
operators = resolve_ltx2_vae_operators(query.device) if is_ltx2_fusion_eligible(query) else None
|
||||
optimized = (
|
||||
None
|
||||
if operators is None
|
||||
else operators.qk_norm_rope(
|
||||
query,
|
||||
key,
|
||||
self.norm_q.weight,
|
||||
self.norm_k.weight,
|
||||
self.norm_q.eps,
|
||||
self.scale,
|
||||
self.rope.rope_dim_split,
|
||||
self.rope.base,
|
||||
)
|
||||
)
|
||||
if optimized is not None:
|
||||
query, key = optimized
|
||||
return query, key, value
|
||||
|
||||
query = self.norm_q(query)
|
||||
key = self.norm_k(key)
|
||||
query = query * self.scale
|
||||
return self.rope(query), self.rope(key), value
|
||||
|
||||
|
||||
class LTX2VideoVaeSwiGLU(diffusers_decoder.LTX2VideoVaeSwiGLU):
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
operators = resolve_ltx2_vae_operators(hidden_states.device) if is_ltx2_fusion_eligible(hidden_states) else None
|
||||
optimized = (
|
||||
None
|
||||
if operators is None
|
||||
else operators.swiglu(hidden_states, self.w_gate.weight, self.w_up.weight, self.w_down.weight)
|
||||
)
|
||||
return super().forward(hidden_states) if optimized is None else optimized
|
||||
|
||||
|
||||
class LTX2VideoVaeDiffusionNABlock(diffusers_decoder.LTX2VideoVaeDiffusionNABlock):
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
latent_context: torch.Tensor,
|
||||
modulation: tuple[torch.Tensor, ...],
|
||||
block_mask=None,
|
||||
) -> torch.Tensor:
|
||||
if hidden_states.dtype is not torch.bfloat16 or not is_ltx2_fusion_eligible(hidden_states):
|
||||
return super().forward(hidden_states, latent_context, modulation, block_mask)
|
||||
operators = resolve_ltx2_vae_operators(hidden_states.device)
|
||||
assert operators is not None
|
||||
|
||||
scale_msa, shift_msa, _, scale_mlp, shift_mlp, _, _ = [
|
||||
modulation[i] + self.scale_shift_table[i].view(1, 1, 1, 1, -1) for i in range(self.num_mod_params)
|
||||
]
|
||||
context_output = self.context_proj(latent_context)
|
||||
attention_input = operators.residual_norm(
|
||||
hidden_states,
|
||||
context_output,
|
||||
None,
|
||||
self.norm1.weight,
|
||||
scale_msa,
|
||||
shift_msa,
|
||||
self.norm1.eps,
|
||||
)
|
||||
if attention_input is None:
|
||||
hidden_states = hidden_states + context_output
|
||||
hidden_states = hidden_states + self.attn(
|
||||
self.norm1(hidden_states) * (1 + scale_msa) + shift_msa, block_mask
|
||||
)
|
||||
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states) * (1 + scale_mlp) + shift_mlp)
|
||||
return hidden_states
|
||||
|
||||
attention_output = self.attn(attention_input, block_mask)
|
||||
mlp_input = operators.residual_norm(
|
||||
hidden_states,
|
||||
context_output,
|
||||
attention_output,
|
||||
self.norm2.weight,
|
||||
scale_mlp,
|
||||
shift_mlp,
|
||||
self.norm2.eps,
|
||||
)
|
||||
if mlp_input is None:
|
||||
residual = hidden_states + context_output
|
||||
residual = residual + attention_output
|
||||
mlp_input = self.norm2(residual) * (1 + scale_mlp) + shift_mlp
|
||||
mlp_output = self.mlp(mlp_input)
|
||||
output = operators.residual_add(
|
||||
hidden_states,
|
||||
context_output,
|
||||
attention_output,
|
||||
mlp_output,
|
||||
)
|
||||
if output is not None:
|
||||
return output
|
||||
residual = hidden_states + context_output
|
||||
residual = residual + attention_output
|
||||
return residual + mlp_output
|
||||
|
||||
|
||||
class LTX2VideoDiffusionDecoder3d(DiffusersLTX2VideoDiffusionDecoder3d):
|
||||
"""Diffusers decoder core with the short-clip NATTEN context fix."""
|
||||
|
||||
@@ -200,6 +376,15 @@ class LTX2VideoDiffusionDecoderModel(DiffusersLTX2VideoDiffusionDecoderModel):
|
||||
# to this behavior-only subclass preserves parameters and state-dict keys.
|
||||
self.decoder.__class__ = LTX2VideoDiffusionDecoder3d
|
||||
self.decoder.stage5_kernel = tuple(decoder_stage5_kernel)
|
||||
overrides = {
|
||||
diffusers_decoder.LTX2VideoVaeNeighborhoodAttention: LTX2VideoVaeNeighborhoodAttention,
|
||||
diffusers_decoder.LTX2VideoVaeSwiGLU: LTX2VideoVaeSwiGLU,
|
||||
diffusers_decoder.LTX2VideoVaeDiffusionNABlock: LTX2VideoVaeDiffusionNABlock,
|
||||
}
|
||||
# Preserve every module and parameter object; only execution methods change.
|
||||
for module in self.decoder.modules():
|
||||
if replacement := overrides.get(type(module)):
|
||||
module.__class__ = replacement
|
||||
|
||||
@classmethod
|
||||
def from_ltx25_native_checkpoint(
|
||||
+1
-1
@@ -25,7 +25,7 @@ from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor impor
|
||||
TileTask,
|
||||
)
|
||||
|
||||
from .ltx2_diffusion_decoder import LTX2VideoDiffusionDecoderModel
|
||||
from .decoder import LTX2VideoDiffusionDecoderModel
|
||||
|
||||
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
||||
|
||||
@@ -21,7 +21,7 @@ from typing import Literal
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
@@ -133,9 +133,10 @@ def torch_mh_moe_forward(
|
||||
return output
|
||||
|
||||
|
||||
_SWIGLU7_ALPHA = tl.constexpr(1.702)
|
||||
_SWIGLU7_LIMIT = tl.constexpr(7.0)
|
||||
_SWIGLU7_BIAS = tl.constexpr(1.0)
|
||||
# vLLM's no-Triton placeholder exposes ``tl.constexpr`` as ``None``.
|
||||
_SWIGLU7_ALPHA = tl.constexpr(1.702) if HAS_TRITON else 1.702
|
||||
_SWIGLU7_LIMIT = tl.constexpr(7.0) if HAS_TRITON else 7.0
|
||||
_SWIGLU7_BIAS = tl.constexpr(1.0) if HAS_TRITON else 1.0
|
||||
|
||||
|
||||
@triton.jit
|
||||
@@ -198,7 +199,7 @@ def _mh_moe_kernel(
|
||||
block_t: tl.constexpr,
|
||||
block_dh: tl.constexpr,
|
||||
block_de: tl.constexpr,
|
||||
acc_dtype: tl.constexpr = tl.float32,
|
||||
acc_dtype: tl.constexpr,
|
||||
deterministic: tl.constexpr = False,
|
||||
):
|
||||
tile_id = tl.program_id(0)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Frames-only callback coordination for MiniMax-H3 VAE decoding."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
from .temporal_chunks import decode_temporal_chunks
|
||||
|
||||
MiniMaxH3VideoChunkCallback = Callable[[torch.Tensor], None]
|
||||
|
||||
|
||||
def decode_h3_chunks(
|
||||
host,
|
||||
latent: torch.Tensor,
|
||||
callback: MiniMaxH3VideoChunkCallback | None,
|
||||
*,
|
||||
group: dist.ProcessGroup | None,
|
||||
) -> torch.Tensor:
|
||||
"""Run the local temporal loop, synchronizing callback errors across ranks."""
|
||||
streaming = callback is not None
|
||||
owner = streaming
|
||||
if group is not None:
|
||||
rank = dist.get_rank(group)
|
||||
world_size = dist.get_world_size(group)
|
||||
# Ownership is positional: every rank supplies the callback and rank 0
|
||||
# publishes. Reduce only whether the ranks agree that this decode
|
||||
# streams, so the verdict is identical everywhere -- a rank-local
|
||||
# verdict would let a peer fall through and enter the decoder
|
||||
# collectives alone, hanging the stage instead of failing it.
|
||||
census = torch.tensor([int(streaming)], dtype=torch.int64, device=latent.device)
|
||||
dist.all_reduce(census, group=group)
|
||||
supplied = int(census.item())
|
||||
if supplied not in (0, world_size):
|
||||
raise ValueError(
|
||||
"MiniMax-H3 chunk callback must be supplied on every rank of the VAE "
|
||||
f"group or on none of them; got {supplied} of {world_size}"
|
||||
)
|
||||
# No rank supplied a callback: every rank runs a plain full decode.
|
||||
streaming = supplied == world_size
|
||||
owner = streaming and rank == 0
|
||||
|
||||
error: BaseException | None = None
|
||||
|
||||
def publish(raw: torch.Tensor) -> None:
|
||||
nonlocal error
|
||||
if not owner or error is not None:
|
||||
return
|
||||
try:
|
||||
processor = getattr(host.model, "processor", None)
|
||||
decoded = raw if processor is None else processor.revert_tensor(raw)
|
||||
frames = host._normalize_decoded_frames(decoded).contiguous()
|
||||
assert callback is not None
|
||||
callback(frames)
|
||||
except BaseException as exc: # noqa: BLE001
|
||||
error = exc
|
||||
|
||||
# Peer ranks run the temporal loop without materializing a second video.
|
||||
sink = publish if owner else ((lambda _frames: None) if streaming else None)
|
||||
result = decode_temporal_chunks(
|
||||
host.model,
|
||||
host._denormalize_latent(latent),
|
||||
sink,
|
||||
)
|
||||
|
||||
if group is not None:
|
||||
failed = torch.tensor([int(rank == 0 and error is not None)], dtype=torch.int32, device=latent.device)
|
||||
dist.broadcast(failed, src=dist.get_global_rank(group, 0), group=group)
|
||||
if int(failed.item()):
|
||||
if rank == 0:
|
||||
assert error is not None
|
||||
raise error
|
||||
raise RuntimeError("MiniMax-H3 video chunk callback failed on rank zero")
|
||||
elif error is not None:
|
||||
raise error
|
||||
|
||||
if not result.numel():
|
||||
return result
|
||||
processor = getattr(host.model, "processor", None)
|
||||
decoded = result if processor is None else processor.revert_tensor(result)
|
||||
return host._normalize_decoded_frames(decoded)
|
||||
@@ -1,20 +1,25 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Loader for the LightX2V Turbo MiniMax-H3 LoRA.
|
||||
"""Loader for the LightX2V Turbo MiniMax-H3 LoRA family.
|
||||
|
||||
Keyed by ``key_format=minimax-h3-diffusers``. The native FlashGen contract lives
|
||||
in ``.npu.lora``; the two artifacts differ in rank, target naming and QKV
|
||||
layout, so each owns its own parsing and packing.
|
||||
The published artifacts differ in task family, step count, training resolution
|
||||
and LoRA alpha, so :class:`TurboSpec` carries the contract of the file actually
|
||||
loaded and the pipeline validates each request against it. Only the
|
||||
Diffusers-PEFT exports are served. The native FlashGen contract lives in
|
||||
``.npu.lora``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass, replace
|
||||
from pathlib import Path
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
from safetensors import safe_open
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.lora_model import LoRAModel
|
||||
from vllm.lora.lora_weights import PackedLoRALayerWeights
|
||||
from vllm.lora.peft_helper import PEFTHelper
|
||||
@@ -22,12 +27,79 @@ from vllm.model_executor.models.utils import WeightsMapper
|
||||
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_TURBO_RANK = 128
|
||||
_TURBO_ALPHA = 128
|
||||
_TURBO_HIDDEN_SIZE = 5376
|
||||
_TURBO_ATTENTION_INNER_SIZE = 7168
|
||||
_TURBO_FFN_HIDDEN_SIZE = 14336
|
||||
_TURBO_FILENAME = "minimax_h3_fl2v_turbo_4step_v1.0_768p_bf16.safetensors"
|
||||
# ``minimax_h3_<task>_turbo_<n>step_v<major.minor>[_768p][_bf16]``. The name is
|
||||
# the only place the sampler contract is recorded.
|
||||
_TURBO_NAME_RE = re.compile(
|
||||
r"^minimax_h3_(?P<task>fl2v|ref2v)_turbo_(?P<steps>\d+)step"
|
||||
r"_v\d+\.\d+(?P<res>_768p)?(?:_bf16)?\.safetensors$"
|
||||
)
|
||||
# The 768p retrains moved to a shorter video flow shift; the 544p artifacts keep
|
||||
# the base model's.
|
||||
_TURBO_VIDEO_SHIFT_768P = 6.0
|
||||
_TURBO_VIDEO_SHIFT_544P = 12.0
|
||||
_TURBO_AUDIO_SHIFT = 3.0
|
||||
# Only ``4step_v0.1`` declares no alpha. LightX2V's reference script never reads
|
||||
# the metadata: it applies ``scale * alpha / rank`` with ``--lora-alpha``
|
||||
# defaulting to 8, and its documented v0.1 command does not override that. So an
|
||||
# artifact that declares nothing is driven at 8, not at its rank.
|
||||
_TURBO_DEFAULT_ALPHA = 8.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TurboSpec:
|
||||
"""The sampler contract one Turbo artifact was distilled for."""
|
||||
|
||||
filename: str
|
||||
task_family: str
|
||||
"""``fl2v`` (serves t2va and fl2va) or ``ref2v`` (serves ref2va)."""
|
||||
denoise_steps: int
|
||||
video_shift: float
|
||||
audio_shift: float
|
||||
rank: int
|
||||
alpha: float
|
||||
|
||||
@property
|
||||
def sigma_points(self) -> int:
|
||||
"""Sigma points the API contract expects: one more than the forwards."""
|
||||
return self.denoise_steps + 1
|
||||
|
||||
@property
|
||||
def supported_tasks(self) -> frozenset[str]:
|
||||
if self.task_family == "ref2v":
|
||||
return frozenset({"ref2va"})
|
||||
return frozenset({"t2va", "fl2va"})
|
||||
|
||||
|
||||
def parse_turbo_filename(name: str) -> TurboSpec | None:
|
||||
"""Return the contract a Turbo filename encodes, or ``None``.
|
||||
|
||||
``alpha`` is the rank-matched default; the loader replaces it with the
|
||||
artifact's declared value.
|
||||
"""
|
||||
|
||||
match = _TURBO_NAME_RE.match(name)
|
||||
if match is None:
|
||||
return None
|
||||
steps = int(match.group("steps"))
|
||||
if steps <= 0:
|
||||
return None
|
||||
return TurboSpec(
|
||||
filename=name,
|
||||
task_family=match.group("task"),
|
||||
denoise_steps=steps,
|
||||
video_shift=_TURBO_VIDEO_SHIFT_768P if match.group("res") else _TURBO_VIDEO_SHIFT_544P,
|
||||
audio_shift=_TURBO_AUDIO_SHIFT,
|
||||
rank=_TURBO_RANK,
|
||||
alpha=_TURBO_DEFAULT_ALPHA,
|
||||
)
|
||||
|
||||
|
||||
_LORA_A_SUFFIX = ".lora_A.default.weight"
|
||||
_LORA_B_SUFFIX = ".lora_B.default.weight"
|
||||
_TURBO_TARGETS = frozenset({"to_q", "to_k", "to_v", "out_proj", "fc1", "fc2"})
|
||||
@@ -81,11 +153,20 @@ def _select_turbo_file(artifact_path: str | Path) -> Path | None:
|
||||
if not path.is_dir():
|
||||
return None
|
||||
|
||||
candidate = path / _TURBO_FILENAME
|
||||
return candidate if candidate.is_file() else None
|
||||
candidates = sorted(child for child in path.glob("*.safetensors") if parse_turbo_filename(child.name))
|
||||
if len(candidates) == 1:
|
||||
return candidates[0]
|
||||
if len(candidates) > 1:
|
||||
raise ValueError(
|
||||
f"{path} holds {len(candidates)} MiniMax-H3 Turbo artifacts "
|
||||
f"({[c.name for c in candidates[:4]]}); point --lora-path at one file."
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _validate_and_convert_tensors(checkpoint) -> dict[str, torch.Tensor]:
|
||||
"""Validate a Diffusers-layout Turbo tensor set and pack it for the manager."""
|
||||
|
||||
tensors: dict[str, torch.Tensor] = {}
|
||||
pairs: dict[str, set[str]] = {}
|
||||
raw_targets: set[str] = set()
|
||||
@@ -134,7 +215,7 @@ def _validate_and_convert_tensors(checkpoint) -> dict[str, torch.Tensor]:
|
||||
unexpected = sorted(raw_targets - _TURBO_EXPECTED_RAW_TARGETS)
|
||||
if missing or unexpected:
|
||||
raise ValueError(
|
||||
"MiniMax-H3 Turbo target set does not match the supported v1.0 artifact: "
|
||||
"MiniMax-H3 Turbo target set does not match the published artifact layout: "
|
||||
f"missing={len(missing)} {missing[:5]}, unexpected={len(unexpected)} {unexpected[:5]}"
|
||||
)
|
||||
return tensors
|
||||
@@ -164,39 +245,61 @@ def load_minimax_h3_turbo_lora(
|
||||
lora_path: str | Path,
|
||||
dtype: torch.dtype,
|
||||
unsupported_offload_mode: str | None = None,
|
||||
) -> tuple[LoRAModel, PEFTHelper] | None:
|
||||
"""Load the published LightX2V Turbo v1.0 through the legacy manager."""
|
||||
) -> tuple[LoRAModel, PEFTHelper, TurboSpec] | None:
|
||||
"""Load any published LightX2V Turbo artifact through the legacy manager."""
|
||||
|
||||
lora_file = _select_turbo_file(lora_path)
|
||||
if lora_file is None:
|
||||
return None
|
||||
spec = parse_turbo_filename(lora_file.name)
|
||||
if spec is None:
|
||||
# Not a Turbo artifact by name; leave it to the next loader.
|
||||
return None
|
||||
with safe_open(lora_file, framework="pt", device="cpu") as checkpoint:
|
||||
# Three published artifacts declare no key_format, so absence is not an
|
||||
# error; a declaration naming a different format is.
|
||||
metadata = checkpoint.metadata() or {}
|
||||
if metadata.get("key_format") != "minimax-h3-diffusers":
|
||||
if lora_file.name == _TURBO_FILENAME:
|
||||
raise ValueError(
|
||||
"MiniMax-H3 Turbo v1.0 requires safetensors metadata key_format='minimax-h3-diffusers'"
|
||||
)
|
||||
return None
|
||||
if lora_file.name != _TURBO_FILENAME:
|
||||
raise ValueError(f"MiniMax-H3 Turbo supports only {_TURBO_FILENAME!r}, got {lora_file.name!r}")
|
||||
declared_format = metadata.get("key_format")
|
||||
if declared_format not in (None, "minimax-h3-diffusers"):
|
||||
raise ValueError(
|
||||
f"{lora_file.name} declares key_format={declared_format!r}, expected 'minimax-h3-diffusers'"
|
||||
)
|
||||
raw_alpha = metadata.get("alpha")
|
||||
try:
|
||||
alpha = float(raw_alpha) if raw_alpha is not None else math.nan
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"MiniMax-H3 Turbo alpha must be numeric, got {raw_alpha!r}") from exc
|
||||
if alpha != _TURBO_ALPHA:
|
||||
raise ValueError(f"MiniMax-H3 Turbo v1.0 requires alpha={_TURBO_ALPHA}, got {raw_alpha!r}")
|
||||
if partition == "ref2va":
|
||||
raise ValueError("MiniMax-H3 Turbo LoRA supports FL2VA/T2VA only")
|
||||
if raw_alpha is None:
|
||||
logger.warning(
|
||||
"MiniMax-H3 Turbo artifact %s declares no alpha; using the LightX2V reference "
|
||||
"default alpha=%g (scale %g). Override with the request-level LoRA scale.",
|
||||
spec.filename,
|
||||
spec.alpha,
|
||||
spec.alpha / spec.rank,
|
||||
)
|
||||
else:
|
||||
try:
|
||||
spec = replace(spec, alpha=float(raw_alpha))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValueError(f"MiniMax-H3 Turbo alpha must be numeric, got {raw_alpha!r}") from exc
|
||||
if not math.isfinite(spec.alpha) or spec.alpha <= 0:
|
||||
raise ValueError(f"MiniMax-H3 Turbo alpha must be a positive number, got {raw_alpha!r}")
|
||||
|
||||
if partition == "ref2va" and spec.task_family == "fl2v":
|
||||
raise ValueError(f"{spec.filename} is an FL2VA/T2VA Turbo artifact; a Ref2VA-only server cannot serve it.")
|
||||
# ``combined`` serves ref2va from ``transformers_ref``, but the LoRA
|
||||
# target pattern only injects into ``transformer``: the adapter would
|
||||
# bind to the stack that never runs.
|
||||
if spec.task_family == "ref2v" and partition != "ref2va":
|
||||
raise ValueError(
|
||||
f"{spec.filename} is a Ref2VA Turbo artifact; start the server with --task-type ref2va "
|
||||
f"(task_type={partition!r} serves ref2va from a DiT the adapter cannot bind to)"
|
||||
)
|
||||
if unsupported_offload_mode is not None:
|
||||
raise ValueError(f"MiniMax-H3 Turbo dynamic LoRA does not support {unsupported_offload_mode}")
|
||||
|
||||
tensors = _validate_and_convert_tensors(checkpoint)
|
||||
|
||||
peft_helper = PEFTHelper.from_dict(
|
||||
{
|
||||
"r": _TURBO_RANK,
|
||||
"lora_alpha": _TURBO_ALPHA,
|
||||
"r": spec.rank,
|
||||
"lora_alpha": spec.alpha,
|
||||
"target_modules": _TURBO_TARGET_PATTERN,
|
||||
}
|
||||
)
|
||||
@@ -209,4 +312,16 @@ def load_minimax_h3_turbo_lora(
|
||||
weights_mapper=_TURBO_WEIGHTS_MAPPER,
|
||||
)
|
||||
_pack_h3_turbo_fc1(lora_model)
|
||||
return lora_model, peft_helper
|
||||
logger.info(
|
||||
"MiniMax-H3 Turbo adapter %s: task=%s, %d denoiser forwards (%d sigma points), "
|
||||
"rank=%d alpha=%g, flow_shift=%g/%g",
|
||||
spec.filename,
|
||||
spec.task_family,
|
||||
spec.denoise_steps,
|
||||
spec.sigma_points,
|
||||
spec.rank,
|
||||
spec.alpha,
|
||||
spec.video_shift,
|
||||
spec.audio_shift,
|
||||
)
|
||||
return lora_model, peft_helper, spec
|
||||
@@ -125,7 +125,7 @@ from .denoise_loop import (
|
||||
)
|
||||
from .encoder import MiniMaxH3Qwen3VLEncoder
|
||||
from .fasth3 import FastH3WeightFusion, resolve_fasth3_fusion
|
||||
from .lora import load_minimax_h3_turbo_lora
|
||||
from .lora import TurboSpec, load_minimax_h3_turbo_lora
|
||||
from .minimax_h3_transformer import (
|
||||
MiniMaxH3Attention,
|
||||
MiniMaxH3DiTModel,
|
||||
@@ -188,9 +188,6 @@ MINIMAX_H3_MAX_REFERENCE_IMAGE_BYTES = 30 * 1024 * 1024
|
||||
MINIMAX_H3_REFERENCE_IMAGE_FORMATS = frozenset({"jpeg", "png", "webp", "heic", "heif"})
|
||||
MINIMAX_H3_MIN_OUTPUT_SECONDS = 4.0
|
||||
MINIMAX_H3_MAX_OUTPUT_SECONDS = 15.0
|
||||
MINIMAX_H3_TURBO_SIGMA_POINTS = 5
|
||||
MINIMAX_H3_TURBO_VIDEO_SHIFT = 6.0
|
||||
MINIMAX_H3_TURBO_AUDIO_SHIFT = 3.0
|
||||
MINIMAX_H3_DOWNLOAD_PATTERNS = [
|
||||
"FL2VA/**",
|
||||
"Ref2VA/model_index.json",
|
||||
@@ -686,6 +683,8 @@ class MiniMaxH3Pipeline(
|
||||
"_encode_reference_audio_conditions",
|
||||
"diffuse",
|
||||
"decode",
|
||||
"video_vae.decode_latent",
|
||||
"audio_vae.decode_latent",
|
||||
"prepare_encode",
|
||||
"denoise_step",
|
||||
"post_decode",
|
||||
@@ -706,7 +705,7 @@ class MiniMaxH3Pipeline(
|
||||
) -> tuple[LoRAModel, PEFTHelper] | None:
|
||||
# A cache eviction may be followed by a different adapter reusing the
|
||||
# same client-supplied ID. Every real load replaces the classification.
|
||||
self._turbo_lora_adapter_ids.discard(lora_request.lora_int_id)
|
||||
self._turbo_lora_specs.pop(lora_request.lora_int_id, None)
|
||||
self._native_lora_adapter_ids.discard(lora_request.lora_int_id)
|
||||
self._lora_sigma_schedules.pop(lora_request.lora_int_id, None)
|
||||
od_config = getattr(self, "od_config", None)
|
||||
@@ -726,8 +725,9 @@ class MiniMaxH3Pipeline(
|
||||
unsupported_offload_mode=" or ".join(offload_modes) or None,
|
||||
)
|
||||
if loaded is not None:
|
||||
self._turbo_lora_adapter_ids.add(lora_request.lora_int_id)
|
||||
return loaded
|
||||
lora_model, peft_helper, turbo_spec = loaded
|
||||
self._turbo_lora_specs[lora_request.lora_int_id] = turbo_spec
|
||||
return lora_model, peft_helper
|
||||
|
||||
# Selection is by the artifact's safetensors ``key_format``, not by the
|
||||
# running platform: the native loader is checkpoint-format parsing with
|
||||
@@ -753,7 +753,7 @@ class MiniMaxH3Pipeline(
|
||||
lora_model: LoRAModel,
|
||||
bound_lora_names: frozenset[str],
|
||||
) -> None:
|
||||
if lora_model.id in self._turbo_lora_adapter_ids:
|
||||
if lora_model.id in self._turbo_lora_specs:
|
||||
missing = sorted(set(lora_model.loras) - bound_lora_names)
|
||||
if missing:
|
||||
raise ValueError(
|
||||
@@ -770,14 +770,6 @@ class MiniMaxH3Pipeline(
|
||||
f"bound={len(bound_lora_names)}/{len(lora_model.loras)}, missing={missing[:5]}"
|
||||
)
|
||||
|
||||
def _has_active_turbo_lora(self, sampling: Any) -> bool:
|
||||
lora_request = sampling.lora_request
|
||||
return (
|
||||
lora_request is not None
|
||||
and not math.isclose(0.0, float(sampling.lora_scale))
|
||||
and lora_request.lora_int_id in self._turbo_lora_adapter_ids
|
||||
)
|
||||
|
||||
def _has_active_native_lora(self, sampling: Any) -> bool:
|
||||
lora_request = sampling.lora_request
|
||||
return (
|
||||
@@ -837,27 +829,46 @@ class MiniMaxH3Pipeline(
|
||||
return adapter_schedule
|
||||
return self._base_schedule_for_task(task)
|
||||
|
||||
def _validate_turbo_sampling(self, sampling: Any) -> None:
|
||||
def _active_turbo_spec(self, sampling: Any) -> TurboSpec | None:
|
||||
"""Return the spec of the Turbo adapter this request actually applies.
|
||||
|
||||
A recognized adapter at scale 0 contributes nothing, so it neither
|
||||
constrains the task nor imposes its sampler contract.
|
||||
"""
|
||||
|
||||
lora_request = sampling.lora_request
|
||||
if lora_request is None or math.isclose(0.0, float(sampling.lora_scale)):
|
||||
return None
|
||||
return self._turbo_lora_specs.get(lora_request.lora_int_id)
|
||||
|
||||
def _validate_turbo_sampling(self, sampling: Any, spec: TurboSpec) -> None:
|
||||
"""Hold a request to the contract of the artifact that is loaded.
|
||||
|
||||
Sigma-point count and both flow shifts vary across the Turbo family, so
|
||||
each is checked against the adapter's own spec rather than a single
|
||||
published configuration.
|
||||
"""
|
||||
|
||||
extra = sampling.extra_args or {}
|
||||
sigma_points = sampling.num_inference_steps
|
||||
if sigma_points != MINIMAX_H3_TURBO_SIGMA_POINTS:
|
||||
if sigma_points != spec.sigma_points:
|
||||
raise OmniClientError(
|
||||
"MiniMax-H3 Turbo requires num_inference_steps=5 (five sigma points produce four denoiser evaluations)"
|
||||
f"{spec.filename} is a {spec.denoise_steps}-step artifact and requires "
|
||||
f"num_inference_steps={spec.sigma_points} "
|
||||
f"({spec.sigma_points} sigma points produce {spec.denoise_steps} denoiser evaluations)"
|
||||
)
|
||||
try:
|
||||
video_shift = float(extra.get("flow_shift", self.default_video_shift))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OmniClientError(f"MiniMax-H3 Turbo requires flow_shift={MINIMAX_H3_TURBO_VIDEO_SHIFT:g}") from exc
|
||||
if not math.isclose(video_shift, MINIMAX_H3_TURBO_VIDEO_SHIFT):
|
||||
raise OmniClientError(f"MiniMax-H3 Turbo requires flow_shift={MINIMAX_H3_TURBO_VIDEO_SHIFT:g}")
|
||||
raise OmniClientError(f"{spec.filename} requires flow_shift={spec.video_shift:g}") from exc
|
||||
if not math.isclose(video_shift, spec.video_shift):
|
||||
raise OmniClientError(f"{spec.filename} requires flow_shift={spec.video_shift:g}")
|
||||
try:
|
||||
audio_shift = float(extra.get("audio_flow_shift", self.default_audio_shift))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OmniClientError(
|
||||
f"MiniMax-H3 Turbo requires audio_flow_shift={MINIMAX_H3_TURBO_AUDIO_SHIFT:g}"
|
||||
) from exc
|
||||
if not math.isclose(audio_shift, MINIMAX_H3_TURBO_AUDIO_SHIFT):
|
||||
raise OmniClientError(f"MiniMax-H3 Turbo requires audio_flow_shift={MINIMAX_H3_TURBO_AUDIO_SHIFT:g}")
|
||||
raise OmniClientError(f"{spec.filename} requires audio_flow_shift={spec.audio_shift:g}") from exc
|
||||
if not math.isclose(audio_shift, spec.audio_shift):
|
||||
raise OmniClientError(f"{spec.filename} requires audio_flow_shift={spec.audio_shift:g}")
|
||||
|
||||
def adopt_cache_dit_backend(self, backend: CacheDiTBackend) -> None:
|
||||
"""Adopt runner-installed generic Cache-DiT for request transitions."""
|
||||
@@ -890,7 +901,7 @@ class MiniMaxH3Pipeline(
|
||||
getattr(od_config, "task_type", None),
|
||||
str(od_config.model),
|
||||
)
|
||||
self._turbo_lora_adapter_ids: set[int] = set()
|
||||
self._turbo_lora_specs: dict[int, TurboSpec] = {}
|
||||
self._native_lora_adapter_ids: set[int] = set()
|
||||
self._lora_sigma_schedules: dict[int, DMD2SigmaSchedule] = {}
|
||||
model_root = _resolve_minimax_h3_model_root(
|
||||
@@ -1177,7 +1188,7 @@ class MiniMaxH3Pipeline(
|
||||
requested: str | None,
|
||||
multi_modal_data: dict[str, Any],
|
||||
*,
|
||||
has_turbo_lora: bool = False,
|
||||
turbo_spec: TurboSpec | None = None,
|
||||
has_native_lora: bool = False,
|
||||
) -> str:
|
||||
if requested is None:
|
||||
@@ -1196,8 +1207,11 @@ class MiniMaxH3Pipeline(
|
||||
raise OmniClientError(
|
||||
f"checkpoint partition {self.partition!r} supports {sorted(self.supported_tasks)}, got task={task!r}"
|
||||
)
|
||||
if task == "ref2va" and has_turbo_lora:
|
||||
raise OmniClientError("MiniMax-H3 Turbo LoRA supports T2VA/FL2VA requests only")
|
||||
if turbo_spec is not None and task not in turbo_spec.supported_tasks:
|
||||
raise OmniClientError(
|
||||
f"{turbo_spec.filename} is a {turbo_spec.task_family} Turbo artifact and serves "
|
||||
f"{sorted(turbo_spec.supported_tasks)}, got task={task!r}"
|
||||
)
|
||||
if has_native_lora and task != "t2va":
|
||||
raise OmniClientError("MiniMax-H3 native LoRA supports T2VA requests only")
|
||||
if self._fasth3 is not None:
|
||||
@@ -2216,16 +2230,16 @@ class MiniMaxH3Pipeline(
|
||||
quality = sampling.quality
|
||||
logger.debug("MiniMax H3 request quality=%s", quality)
|
||||
extra = sampling.extra_args or {}
|
||||
has_turbo_lora = self._has_active_turbo_lora(sampling)
|
||||
turbo_spec = self._active_turbo_spec(sampling)
|
||||
has_native_lora = self._has_active_native_lora(sampling)
|
||||
task = self._resolve_task(
|
||||
extra.get("task"),
|
||||
multi_modal_data,
|
||||
has_turbo_lora=has_turbo_lora,
|
||||
turbo_spec=turbo_spec,
|
||||
has_native_lora=has_native_lora,
|
||||
)
|
||||
if has_turbo_lora:
|
||||
self._validate_turbo_sampling(sampling)
|
||||
if turbo_spec is not None:
|
||||
self._validate_turbo_sampling(sampling, turbo_spec)
|
||||
if has_native_lora:
|
||||
self._validate_native_sampling(sampling, task=task)
|
||||
if self._fasth3 is not None:
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Small compatibility loop for the released MiniMax-H3 temporal decoder."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
|
||||
def decode_temporal_chunks(
|
||||
model: nn.Module,
|
||||
latent: torch.Tensor,
|
||||
callback: Callable[[torch.Tensor], None] | None,
|
||||
) -> torch.Tensor:
|
||||
"""Decode H3 temporal clips and synchronously publish committed frames.
|
||||
|
||||
The released VAE exposes the temporal clip primitives but materializes the
|
||||
final tensor. This is the same loop with the write point replaced by a
|
||||
frames-only callback. ``callback=None`` retains the complete-output path.
|
||||
"""
|
||||
if latent.ndim != 5 or not bool(getattr(model, "use_3d_conv", False)):
|
||||
raise ValueError("MiniMax-H3 temporal chunk decode requires a rank-5 3D latent")
|
||||
|
||||
token_drop = int(model.token_drop)
|
||||
chunk_size = int(model.tokens_chunk_size)
|
||||
overlap_tokens = int(model.token_overlap)
|
||||
ratio_t = int(model.vae_ratio_t)
|
||||
pre_padding = int(model.frame_pre_padding)
|
||||
|
||||
isolated_first = bool(model.isolated_first_frame and pre_padding == 0)
|
||||
isolated_last = bool(model.isolated_last_frame)
|
||||
z_head = latent[:, :, :1] if isolated_first else None
|
||||
z_tail = latent[:, :, -1:] if isolated_last else None
|
||||
start = int(isolated_first)
|
||||
stop = int(latent.shape[2]) - int(isolated_last)
|
||||
latent = latent[:, :, start:stop]
|
||||
|
||||
pseudo_tokens = int(latent.shape[2]) + token_drop
|
||||
pad_tokens = (-pseudo_tokens) % chunk_size
|
||||
if pad_tokens:
|
||||
latent = torch.cat((latent, latent[:, :, -1:].repeat(1, 1, pad_tokens, 1, 1)), dim=2)
|
||||
num_chunks = (pseudo_tokens + pad_tokens) // chunk_size - int(token_drop > 0)
|
||||
if num_chunks <= 0:
|
||||
raise ValueError("MiniMax-H3 temporal chunk plan is empty")
|
||||
|
||||
total_frames, pad_frames, output_frames = model._decode_temporal_output_frame_plan(
|
||||
latent, z_head, z_tail, num_chunks, pad_tokens
|
||||
)
|
||||
output_frames = int(output_frames)
|
||||
if output_frames <= 0:
|
||||
raise ValueError("MiniMax-H3 temporal chunk plan has no output frames")
|
||||
|
||||
collected: list[torch.Tensor] = []
|
||||
overlap: torch.Tensor | None = None
|
||||
written = 0
|
||||
|
||||
def emit(part: torch.Tensor) -> None:
|
||||
nonlocal written
|
||||
frames = int(part.shape[2])
|
||||
if frames <= 0 or written >= output_frames:
|
||||
return
|
||||
frames = min(frames, output_frames - written)
|
||||
part = part[:, :, :frames]
|
||||
if callback is None:
|
||||
collected.append(part)
|
||||
else:
|
||||
callback(part)
|
||||
written += frames
|
||||
|
||||
chunk_frames = chunk_size * ratio_t
|
||||
split_count = int(token_drop > 0) + 1
|
||||
for index in range(num_chunks):
|
||||
begin = index * chunk_size
|
||||
end = begin + chunk_size + overlap_tokens
|
||||
clip = latent[:, :, begin:end]
|
||||
if index == 0 and z_head is not None:
|
||||
clip = torch.cat((z_head, clip), dim=2)
|
||||
if index == num_chunks - 1 and z_tail is not None:
|
||||
clip = torch.cat((clip, z_tail), dim=2)
|
||||
|
||||
decoded = model._adaptive_decode(clip)
|
||||
|
||||
# The isolated boundary latents were prepended/appended to the clip, so
|
||||
# the decoder returns their frames inside this clip's block. Publish
|
||||
# them the way the released loop does and drop their temporal block
|
||||
# before splitting, or every later frame shifts by one block.
|
||||
decoded_tail = None
|
||||
if index == 0 and z_head is not None:
|
||||
emit(decoded[:, :, ratio_t - 1 : ratio_t])
|
||||
decoded = decoded[:, :, ratio_t:]
|
||||
if index == num_chunks - 1 and z_tail is not None:
|
||||
decoded_tail = decoded[:, :, -1:]
|
||||
decoded = decoded[:, :, :-ratio_t]
|
||||
|
||||
for split in range(split_count):
|
||||
begin = split * chunk_frames
|
||||
end = min(begin + chunk_frames, int(decoded.shape[2]))
|
||||
part = decoded[:, :, begin:end]
|
||||
part = part[:, :, pre_padding:]
|
||||
if split == 0:
|
||||
if overlap is not None:
|
||||
part = model.blend(overlap, part, int(model.frame_overlap), dim=-3)
|
||||
overlap = None
|
||||
emit(part)
|
||||
else:
|
||||
overlap = part.contiguous()
|
||||
|
||||
if index == num_chunks - 1:
|
||||
if overlap is not None:
|
||||
emit(overlap)
|
||||
overlap = None
|
||||
if decoded_tail is not None:
|
||||
emit(decoded_tail)
|
||||
|
||||
if written != output_frames:
|
||||
raise RuntimeError(f"MiniMax-H3 temporal decode emitted {written}/{output_frames} frames")
|
||||
if callback is not None:
|
||||
return latent.new_empty((0,))
|
||||
return torch.cat(collected, dim=2) if collected else latent.new_empty((0,))
|
||||
@@ -9,7 +9,7 @@ import json
|
||||
from collections.abc import Iterator
|
||||
from contextlib import AbstractContextManager, contextmanager, nullcontext
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -22,11 +22,13 @@ from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor impor
|
||||
DistributedVaeMixin,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_world_group
|
||||
from vllm_omni.diffusion.models.interface import DecodedChunkConsumer
|
||||
from vllm_omni.diffusion.offloader.module_residency import (
|
||||
BoundedAllocatorCache,
|
||||
PinnedModuleStager,
|
||||
)
|
||||
|
||||
from .chunked_decode import decode_h3_chunks
|
||||
from .ops import install_h3_vae_optimizations
|
||||
from .packed_tokens import minimax_h3_patchify_video_latent
|
||||
|
||||
@@ -38,6 +40,27 @@ MINIMAX_H3_AUDIO_CHANNELS = 2
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _minimax_h3_keyframe_encode_context(
|
||||
device: torch.device,
|
||||
) -> Iterator[None]:
|
||||
if device.type != "cuda":
|
||||
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.
|
||||
with torch.backends.cudnn.flags(
|
||||
enabled=True,
|
||||
benchmark=False,
|
||||
deterministic=True,
|
||||
allow_tf32=True,
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
def _load_component_config(component_path: str) -> dict[str, Any]:
|
||||
config_path = Path(component_path) / "config.json"
|
||||
config = json.loads(config_path.read_text(encoding="utf-8"))
|
||||
@@ -280,10 +303,11 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
for device in devices:
|
||||
with self.device_module.device(device):
|
||||
self.device_module.manual_seed(MINIMAX_H3_KEYFRAME_ENCODE_SEED)
|
||||
latent = self.model.encode_images(
|
||||
image,
|
||||
use_fp16_latent=True,
|
||||
)[0]
|
||||
with _minimax_h3_keyframe_encode_context(parameter.device):
|
||||
latent = self.model.encode_images(
|
||||
image,
|
||||
use_fp16_latent=True,
|
||||
)[0]
|
||||
finally:
|
||||
self.model.parallel_tiling = previous_parallel
|
||||
if previous_dtype != torch.float32:
|
||||
@@ -355,25 +379,16 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
).float()
|
||||
return rows, shape
|
||||
|
||||
@torch.inference_mode()
|
||||
def decode_latent(self, latent: torch.Tensor) -> torch.Tensor:
|
||||
channels = int(self.config_dict["latent_channels"])
|
||||
mean = torch.tensor(
|
||||
self.config_dict["latents_mean"],
|
||||
device=latent.device,
|
||||
dtype=latent.dtype,
|
||||
).view(1, channels, 1, 1, 1)
|
||||
std = torch.tensor(
|
||||
self.config_dict["latents_std"],
|
||||
device=latent.device,
|
||||
dtype=latent.dtype,
|
||||
).view(1, channels, 1, 1, 1)
|
||||
# The checkpoint hands rank r the tiles ``range(r, num_tiles, sp_size)``
|
||||
# and then rejects an empty share inside the gather. A rank with no
|
||||
# tiles raises and leaves the collective while the others block in it
|
||||
# forever, so too few tiles hangs the whole stage rather than failing
|
||||
# it. Tile count depends only on the latent shape, so every rank takes
|
||||
# this branch together.
|
||||
def _decode_tiling_context(self, latent: torch.Tensor) -> AbstractContextManager:
|
||||
"""Pick the tiling mode a decode of ``latent`` can safely use.
|
||||
|
||||
The checkpoint hands rank r the tiles ``range(r, num_tiles, sp_size)``
|
||||
and then rejects an empty share inside the gather. A rank with no
|
||||
tiles raises and leaves the collective while the others block in it
|
||||
forever, so too few tiles hangs the whole stage rather than failing
|
||||
it. Tile count depends only on the latent shape, so every rank takes
|
||||
this branch together.
|
||||
"""
|
||||
num_tiles = self._decoder_tile_count(latent)
|
||||
if self.parallel_size > 1 and num_tiles < self.parallel_size:
|
||||
logger.warning_once(
|
||||
@@ -383,19 +398,64 @@ class MiniMaxH3VideoVAE(nn.Module, DistributedVaeMixin):
|
||||
num_tiles,
|
||||
self.parallel_size,
|
||||
)
|
||||
tiling_context: AbstractContextManager = self._rank_local_tiling()
|
||||
else:
|
||||
tiling_context = nullcontext()
|
||||
return self._rank_local_tiling()
|
||||
return nullcontext()
|
||||
|
||||
with tiling_context:
|
||||
decoded = self.model.decode_base(latent * std + mean)
|
||||
frames = self.model.processor.revert_tensor(decoded)
|
||||
@torch.inference_mode()
|
||||
def decode_latent(self, latent: torch.Tensor) -> torch.Tensor:
|
||||
with self._decode_tiling_context(latent):
|
||||
decoded = self.model.decode_base(self._denormalize_latent(latent))
|
||||
return self._normalize_decoded_frames(self.model.processor.revert_tensor(decoded))
|
||||
|
||||
def _denormalize_latent(self, latent: torch.Tensor) -> torch.Tensor:
|
||||
channels = int(self.config_dict["latent_channels"])
|
||||
mean = torch.tensor(self.config_dict["latents_mean"], device=latent.device, dtype=latent.dtype)
|
||||
std = torch.tensor(self.config_dict["latents_std"], device=latent.device, dtype=latent.dtype)
|
||||
shape = (1, channels, 1, 1, 1)
|
||||
return latent * std.view(shape) + mean.view(shape)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_decoded_frames(decoded: torch.Tensor) -> torch.Tensor:
|
||||
"""Canonicalize remote H3 decoder output to [B,C,T,H,W]."""
|
||||
frames = decoded
|
||||
if frames.ndim == 4:
|
||||
frames = frames.unsqueeze(0).transpose(1, 2)
|
||||
if frames.ndim != 5:
|
||||
raise ValueError(f"unexpected decoded video shape {tuple(frames.shape)}")
|
||||
return frames.float()
|
||||
|
||||
# Chunks are reverted through the checkpoint's processor, which
|
||||
# denormalizes and clamps into the unit interval.
|
||||
chunk_value_range: ClassVar[tuple[float, float]] = (0.0, 1.0)
|
||||
|
||||
@torch.inference_mode()
|
||||
def decode_with_chunks(self, z: torch.Tensor, *, on_chunk: DecodedChunkConsumer) -> None:
|
||||
"""Decode temporal clips and synchronously publish frames-only chunks.
|
||||
|
||||
Implements :class:`SupportsChunkedVAEDecode`. Every rank participating
|
||||
in distributed VAE execution must invoke this method with a callback so
|
||||
the temporal collectives stay in lockstep; ``on_chunk`` is called only
|
||||
on the rank that owns output. Chunks arrive as ``[B, C, T, H, W]``
|
||||
float frames, normalized through the checkpoint's processor to match
|
||||
the complete decode path. After a callback failure, the remaining
|
||||
chunks are decoded and discarded before the exception is re-raised.
|
||||
"""
|
||||
if not callable(on_chunk):
|
||||
raise TypeError("on_chunk must be callable")
|
||||
if not callable(getattr(self.model, "_adaptive_decode", None)):
|
||||
raise RuntimeError("Loaded MiniMax-H3 VAE does not expose temporal decode primitives")
|
||||
group = None
|
||||
if self.is_distributed_enabled():
|
||||
group = self._native_parallel_state().get("sp_process_group")
|
||||
if group is None or dist.get_world_size(group) != self.parallel_size:
|
||||
raise RuntimeError("MiniMax-H3 VAE chunk decode has an invalid spatial-parallel group")
|
||||
# Native H3 tiling performs its own collectives for every temporal clip,
|
||||
# so this path needs the same too-few-tiles fallback as the complete
|
||||
# decode: without it a shape that leaves some ranks tileless hangs the
|
||||
# gather instead of decoding rank-locally.
|
||||
with self._decode_tiling_context(z):
|
||||
decode_h3_chunks(self, z, on_chunk, group=group)
|
||||
|
||||
|
||||
class MiniMaxH3AudioVAE(nn.Module):
|
||||
def __init__(
|
||||
|
||||
@@ -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
|
||||
"""
|
||||
OmniVoice TTS Pipeline for vLLM-Omni diffusion engine.
|
||||
|
||||
@@ -12,10 +12,13 @@ Uses request-mode execution (all steps in one forward() call).
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from typing import ClassVar
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -26,10 +29,17 @@ from vllm.logger import init_logger
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.models.interface import SupportAudioOutput
|
||||
from vllm_omni.diffusion.worker.input_batch import InputBatch
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
from vllm_omni.errors import OmniClientError
|
||||
from vllm_omni.model_executor.models.omnivoice.duration import RuleDurationEstimator
|
||||
from vllm_omni.model_executor.models.omnivoice.omnivoice_decoder import OmniVoiceDecoder
|
||||
from vllm_omni.model_executor.models.omnivoice.omnivoice_generator import OmniVoiceGenerator
|
||||
from vllm_omni.model_executor.models.omnivoice.omnivoice_generator import (
|
||||
OmniVoiceGenerator,
|
||||
_build_cu_seqs,
|
||||
_get_time_steps,
|
||||
)
|
||||
from vllm_omni.transformers_utils.configs.omnivoice import OmniVoiceConfig
|
||||
from vllm_omni.utils.speaker_cache import get_speaker_cache
|
||||
|
||||
@@ -43,6 +53,15 @@ import torchaudio
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PreparedOmniVoiceRequest:
|
||||
input_ids: torch.Tensor
|
||||
audio_mask: torch.Tensor
|
||||
cond_len: int
|
||||
target_len: int
|
||||
seed: int | None
|
||||
|
||||
|
||||
def get_omnivoice_post_process_func(od_config: OmniDiffusionConfig):
|
||||
"""Post-processing: convert audio tensor to numpy for WAV encoding."""
|
||||
|
||||
@@ -132,6 +151,8 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
"""
|
||||
|
||||
support_audio_output: ClassVar[bool] = True
|
||||
supports_request_batch: ClassVar[bool] = True
|
||||
supports_step_execution: ClassVar[bool] = True
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
@@ -141,9 +162,9 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
|
||||
# Resolve model path (HF hub ID → local cache)
|
||||
if not os.path.isdir(self.model_path):
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
self.model_path = snapshot_download(self.model_path)
|
||||
self.model_path = hf_api().snapshot_download(self.model_path)
|
||||
|
||||
# Load OmniVoice config
|
||||
config_path = os.path.join(self.model_path, "config.json")
|
||||
@@ -152,7 +173,7 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
self.config = OmniVoiceConfig(**hf_config)
|
||||
|
||||
# Build generator and decoder
|
||||
self.generator = OmniVoiceGenerator(self.config)
|
||||
self.generator = OmniVoiceGenerator(self.config, od_config)
|
||||
self.decoder = OmniVoiceDecoder(self.config)
|
||||
|
||||
# Tokenizer (low-level, avoids HF tokenizer extra_special_tokens issue)
|
||||
@@ -205,50 +226,36 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
tokens = tokens.squeeze(0) # [8, T_ref]
|
||||
return tokens
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, req: DiffusionRequestBatch) -> DiffusionOutput:
|
||||
"""Generate speech audio from text, optionally with voice cloning.
|
||||
|
||||
Accepts either a plain text prompt or a structured dict:
|
||||
{"text": "...", "ref_audio": (samples, sr), "ref_text": "...",
|
||||
"lang": "...", "instruct": "..."}
|
||||
"""
|
||||
prompt = req.prompts[0] if req.prompts else ""
|
||||
def _prepare_request_input(
|
||||
self,
|
||||
prompt: Any,
|
||||
extra: dict[str, Any],
|
||||
) -> _PreparedOmniVoiceRequest | DiffusionOutput:
|
||||
"""Build one request's conditional/unconditional model inputs."""
|
||||
ref_audio = None
|
||||
ref_text = None
|
||||
lang = "None"
|
||||
instruct = "None"
|
||||
extra = req.sampling_params.extra_args or {}
|
||||
voice_name = None
|
||||
seed = extra.get("seed", None)
|
||||
|
||||
voice_name = None
|
||||
if isinstance(prompt, dict):
|
||||
# Top-level keys (used by serving_speech.py /v1/audio/speech path)
|
||||
text = prompt.get("input") or prompt.get("text") or prompt.get("prompt")
|
||||
ref_audio = prompt.get("ref_audio")
|
||||
ref_text = prompt.get("ref_text")
|
||||
voice_name = prompt.get("voice_name")
|
||||
lang = prompt.get("lang")
|
||||
instruct = prompt.get("instruct")
|
||||
# OmniTextPrompt format (used by offline Omni.generate path):
|
||||
# ref_audio comes via multi_modal_data["audio"] and the rest via
|
||||
# mm_processor_kwargs. Fall back to those when top-level keys are
|
||||
# absent so both invocation styles work.
|
||||
mm_data = prompt.get("multi_modal_data") or {}
|
||||
mm_kwargs = prompt.get("mm_processor_kwargs") or {}
|
||||
if ref_audio is None:
|
||||
audio_field = mm_data.get("audio")
|
||||
# Standard multimodal shape allows a list of audios; OmniVoice
|
||||
# voice cloning conditions on a single reference clip, so
|
||||
# unwrap a length-1 list and reject multi-reference prompts up
|
||||
# front (otherwise a list would later crash inside
|
||||
# ``_encode_ref_audio`` when it calls ``audio.dim()``).
|
||||
if isinstance(audio_field, list):
|
||||
if len(audio_field) == 1:
|
||||
audio_field = audio_field[0]
|
||||
elif len(audio_field) > 1:
|
||||
return DiffusionOutput(
|
||||
error=f"OmniVoice voice cloning supports a single reference audio; got {len(audio_field)}" # noqa: E501
|
||||
error=f"OmniVoice voice cloning supports a single reference audio; got {len(audio_field)}"
|
||||
)
|
||||
else:
|
||||
audio_field = None
|
||||
@@ -264,7 +271,6 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
lang = mm_kwargs.get("lang")
|
||||
if instruct is None:
|
||||
instruct = mm_kwargs.get("instruct")
|
||||
|
||||
if not text:
|
||||
return DiffusionOutput(error="Empty text prompt")
|
||||
lang = lang or "None"
|
||||
@@ -274,105 +280,325 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
if not text:
|
||||
return DiffusionOutput(error="Empty text prompt")
|
||||
|
||||
device = self.device
|
||||
num_cb = self.config.num_audio_codebook
|
||||
mask_id = self.config.audio_mask_id
|
||||
|
||||
# Estimate target duration
|
||||
target_len = self.duration_estimator.estimate_duration(text, "Nice to meet you.", 25)
|
||||
target_len = max(1, int(target_len))
|
||||
|
||||
# Build text prompt with control tokens
|
||||
style_text = f"<|denoise|><|lang_start|>{lang}<|lang_end|><|instruct_start|>{instruct}<|instruct_end|>"
|
||||
full_text = _combine_text(ref_text=ref_text, text=text)
|
||||
wrapped_text = f"<|text_start|>{full_text}<|text_end|>"
|
||||
style_tokens = self.tokenizer.encode(style_text).ids
|
||||
text_tokens = _tokenize_with_nonverbal_tags(wrapped_text, self.tokenizer)
|
||||
encoding_ids = style_tokens + text_tokens
|
||||
text_tokens = torch.tensor(encoding_ids, dtype=torch.long, device=device)
|
||||
text_len = text_tokens.shape[0]
|
||||
text_tokens_tensor = torch.tensor(encoding_ids, dtype=torch.long, device=self.device)
|
||||
text_len = text_tokens_tensor.shape[0]
|
||||
|
||||
# Encode reference audio tokens if provided (with voice caching)
|
||||
ref_audio_tokens = None
|
||||
if ref_audio is not None:
|
||||
if self.audio_tokenizer is None:
|
||||
raise RuntimeError(
|
||||
"Voice cloning requires transformers>=5.3.0. Try: uv pip install 'transformers>=5.3.0'"
|
||||
)
|
||||
# Check speaker cache first
|
||||
_cache_key = None
|
||||
cache_key = None
|
||||
if voice_name:
|
||||
_cache_key = self._speaker_cache.make_cache_key(
|
||||
cache_key = self._speaker_cache.make_cache_key(
|
||||
voice_name,
|
||||
model_type="omnivoice",
|
||||
created_at=int(prompt.get("voice_created_at") or 0),
|
||||
)
|
||||
cached = self._speaker_cache.get(_cache_key)
|
||||
cached = self._speaker_cache.get(cache_key)
|
||||
if cached is not None:
|
||||
ref_audio_tokens = cached["ref_audio_tokens"].to(device)
|
||||
_cache_key = None # hit → don't store again
|
||||
ref_audio_tokens = cached["ref_audio_tokens"].to(self.device)
|
||||
cache_key = None
|
||||
logger.debug("Speaker cache HIT for OmniVoice speaker '%s'", voice_name)
|
||||
|
||||
if ref_audio_tokens is None:
|
||||
audio_signal, sr = ref_audio
|
||||
if isinstance(audio_signal, np.ndarray):
|
||||
audio_signal = torch.from_numpy(audio_signal).float()
|
||||
ref_audio_tokens = self._encode_ref_audio(audio_signal, int(sr)).to(device)
|
||||
|
||||
# Store in cache for next request
|
||||
if _cache_key is not None:
|
||||
self._speaker_cache.put(_cache_key, {"ref_audio_tokens": ref_audio_tokens.cpu()})
|
||||
ref_audio_tokens = self._encode_ref_audio(audio_signal, int(sr)).to(self.device)
|
||||
if cache_key is not None:
|
||||
self._speaker_cache.put(cache_key, {"ref_audio_tokens": ref_audio_tokens.cpu()})
|
||||
logger.debug("Speaker cache STORE for OmniVoice speaker '%s'", voice_name)
|
||||
|
||||
# Build conditional + unconditional batches [2, 8, max_len]
|
||||
text_ids = text_tokens.unsqueeze(0).repeat(num_cb, 1)
|
||||
target_ids = torch.full((num_cb, target_len), mask_id, dtype=torch.long, device=device)
|
||||
|
||||
if ref_audio_tokens is not None:
|
||||
cond_ids = torch.cat([text_ids, ref_audio_tokens, target_ids], dim=1)
|
||||
else:
|
||||
cond_ids = torch.cat([text_ids, target_ids], dim=1)
|
||||
num_cb = self.config.num_audio_codebook
|
||||
mask_id = self.config.audio_mask_id
|
||||
text_ids = text_tokens_tensor.unsqueeze(0).repeat(num_cb, 1)
|
||||
target_ids = torch.full((num_cb, target_len), mask_id, dtype=torch.long, device=self.device)
|
||||
cond_ids = (
|
||||
torch.cat([text_ids, ref_audio_tokens, target_ids], dim=1)
|
||||
if ref_audio_tokens is not None
|
||||
else torch.cat([text_ids, target_ids], dim=1)
|
||||
)
|
||||
cond_len = cond_ids.shape[1]
|
||||
uncond_ids = target_ids.clone()
|
||||
uncond_len = target_len
|
||||
max_len = max(cond_len, uncond_len)
|
||||
if uncond_len < max_len:
|
||||
pad = torch.full(
|
||||
(num_cb, max_len - uncond_len),
|
||||
mask_id,
|
||||
dtype=torch.long,
|
||||
device=device,
|
||||
input_ids = torch.cat([cond_ids, uncond_ids], dim=1).transpose(0, 1).contiguous()
|
||||
|
||||
max_len = input_ids.shape[0]
|
||||
audio_mask = torch.zeros(max_len, dtype=torch.bool, device=self.device)
|
||||
audio_mask[text_len:] = True
|
||||
|
||||
return _PreparedOmniVoiceRequest(
|
||||
input_ids=input_ids,
|
||||
audio_mask=audio_mask,
|
||||
cond_len=cond_len,
|
||||
target_len=target_len,
|
||||
seed=seed,
|
||||
)
|
||||
|
||||
def _collate_request_inputs(
|
||||
self,
|
||||
prepared_requests: Sequence[_PreparedOmniVoiceRequest],
|
||||
) -> tuple[torch.Tensor, torch.Tensor, list[int]]:
|
||||
"""Pack request-major [cond, uncond] token sequences."""
|
||||
input_ids: list[torch.Tensor] = []
|
||||
audio_masks: list[torch.Tensor] = []
|
||||
cond_lens: list[int] = []
|
||||
|
||||
for request in prepared_requests:
|
||||
input_id = request.input_ids
|
||||
audio_mask = request.audio_mask
|
||||
cond_len = request.cond_len
|
||||
input_ids.append(input_id)
|
||||
audio_masks.append(audio_mask)
|
||||
cond_lens.append(cond_len)
|
||||
|
||||
input_ids = torch.cat(input_ids, dim=0)
|
||||
audio_masks = torch.cat(audio_masks, dim=0)
|
||||
|
||||
return input_ids, audio_masks, cond_lens
|
||||
|
||||
def prepare_encode(self, state: StepRequestState) -> StepRequestState:
|
||||
prompt = state.prompt if state.prompt else ""
|
||||
extra = state.sampling.extra_args or {}
|
||||
prepared = self._prepare_request_input(prompt, extra)
|
||||
if isinstance(prepared, DiffusionOutput):
|
||||
raise OmniClientError(prepared.error or "OmniVoice request preparation failed")
|
||||
|
||||
prepared_request = prepared
|
||||
cond_len = prepared_request.cond_len
|
||||
target_len = prepared_request.target_len
|
||||
input_ids = prepared_request.input_ids
|
||||
audio_mask = prepared_request.audio_mask
|
||||
seed = prepared_request.seed
|
||||
device = self.device
|
||||
mask_id = self.config.audio_mask_id
|
||||
num_codebooks = self.config.num_audio_codebook
|
||||
if seed is None:
|
||||
seed = random.randint(0, 2**63 - 1)
|
||||
num_step = (
|
||||
state.sampling.num_inference_steps if state.sampling.num_inference_steps is not None else self.num_step
|
||||
)
|
||||
|
||||
t_shift = self.t_shift
|
||||
|
||||
# Initialize all target tokens as [MASK]
|
||||
tokens = torch.full((1, num_codebooks, target_len), mask_id, dtype=torch.long, device=device)
|
||||
|
||||
timesteps = _get_time_steps(0.0, 1.0, num_step + 1, t_shift)
|
||||
|
||||
# Compute unmasking schedule
|
||||
schedules = []
|
||||
total_mask = target_len * num_codebooks
|
||||
rem = total_mask
|
||||
sched = []
|
||||
for step in range(num_step):
|
||||
num = (
|
||||
rem
|
||||
if step == num_step - 1
|
||||
else min(
|
||||
math.ceil(total_mask * (timesteps[step + 1] - timesteps[step])),
|
||||
rem,
|
||||
)
|
||||
)
|
||||
uncond_ids = torch.cat([uncond_ids, pad], dim=1)
|
||||
sched.append(int(num))
|
||||
rem -= int(num)
|
||||
schedules = torch.tensor(sched, dtype=torch.long, device=device)
|
||||
|
||||
batch_input_ids = torch.stack([cond_ids, uncond_ids])
|
||||
layer_ids = torch.arange(num_codebooks, device=device).view(1, -1, 1)
|
||||
generator = torch.Generator(device=device).manual_seed(seed)
|
||||
|
||||
batch_audio_mask = torch.zeros(2, max_len, dtype=torch.bool, device=device)
|
||||
batch_audio_mask[0, text_len:cond_len] = True
|
||||
batch_audio_mask[1, :uncond_len] = True
|
||||
guidance_scale = (
|
||||
state.sampling.guidance_scale if state.sampling.guidance_scale is not None else self.guidance_scale
|
||||
)
|
||||
state.latents = input_ids
|
||||
state.timesteps = schedules
|
||||
state.guidance = guidance_scale
|
||||
state.extra["schedules"] = schedules
|
||||
state.extra["layer_ids"] = layer_ids
|
||||
state.extra["generator"] = generator
|
||||
state.extra["t_shift"] = t_shift
|
||||
state.extra["cond_len"] = cond_len
|
||||
state.extra["target_len"] = target_len
|
||||
state.extra["audio_mask"] = audio_mask
|
||||
state.extra["tokens"] = tokens
|
||||
return state
|
||||
|
||||
batch_attn_mask = torch.zeros(2, 1, max_len, max_len, dtype=torch.bool, device=device)
|
||||
batch_attn_mask[0, :, :cond_len, :cond_len] = True
|
||||
batch_attn_mask[1, :, :uncond_len, :uncond_len] = True
|
||||
def denoise_step(self, input_batch: InputBatch, *, states: Sequence[StepRequestState] | None = None, **kwargs: Any):
|
||||
input_ids = input_batch.latents
|
||||
use_cuda_graph = self.generator._cuda_graph_fwd is not None and input_ids.is_cuda
|
||||
layer_ids = states[0].extra["layer_ids"]
|
||||
|
||||
audio_masks: list[torch.Tensor] = []
|
||||
target_lens: list[int] = []
|
||||
batch_tokens: list[torch.Tensor] = []
|
||||
cond_lens: list[int] = []
|
||||
|
||||
steps: list[int] = []
|
||||
schedules: list[torch.Tensor] = []
|
||||
generators: list[torch.Generator] = []
|
||||
guidance_scales: list[float] = []
|
||||
|
||||
for state in states:
|
||||
audio_masks.append(state.extra.get("audio_mask", None))
|
||||
cond_lens.append(state.extra["cond_len"])
|
||||
target_lens.append(state.extra["target_len"])
|
||||
batch_tokens.append(state.extra["tokens"])
|
||||
guidance_scales.append(state.guidance)
|
||||
generators.append(state.extra.get("generator", None))
|
||||
schedules.append(state.extra["schedules"])
|
||||
steps.append(state.step_index)
|
||||
|
||||
audio_masks = torch.cat(audio_masks, dim=0)
|
||||
|
||||
B = len(target_lens)
|
||||
cu_seqs = _build_cu_seqs(cond_lens, target_lens, input_ids.device)
|
||||
|
||||
position_temperature = self.position_temperature
|
||||
class_temperature = self.class_temperature
|
||||
layer_penalty_factor = self.layer_penalty_factor
|
||||
if use_cuda_graph:
|
||||
# Replay a fixed packed-token bucket with dynamic varlen metadata.
|
||||
batch_logits = self.generator._cuda_graph_fwd(input_ids, audio_masks, cu_seqs, B)
|
||||
else:
|
||||
# Run packed eager attention for the current active requests.
|
||||
inputs_embeds = self.generator._prepare_embeddings(input_ids, audio_masks)
|
||||
hidden_states = self.generator._transformer_forward(
|
||||
inputs_embeds,
|
||||
cu_seqs,
|
||||
max_seqlen=max(cond_lens),
|
||||
)
|
||||
# fp32 cast deferred to the per-item slices below.
|
||||
batch_logits = self.generator._get_logits(hidden_states)
|
||||
# batch_logits: [8, total_seq_len, 1025]
|
||||
|
||||
target_offsets: list[int] = []
|
||||
target_offset = 0
|
||||
for target_len in target_lens:
|
||||
target_offsets.append(target_offset)
|
||||
target_offset += target_len
|
||||
|
||||
sequence_offsets: list[int] = []
|
||||
sequence_offset = 0
|
||||
for cond_len, target_len in zip(cond_lens, target_lens):
|
||||
sequence_offsets.append(sequence_offset)
|
||||
sequence_offset += cond_len + target_len
|
||||
|
||||
for i in range(B):
|
||||
k = schedules[i][steps[i]]
|
||||
if k <= 0:
|
||||
continue
|
||||
|
||||
c_len = cond_lens[i]
|
||||
t_len = target_lens[i]
|
||||
|
||||
# Extract logits for target region; upcast only the slices we actually consume.
|
||||
request_start = sequence_offsets[i]
|
||||
cond_end = request_start + c_len
|
||||
uncond_start = cond_end
|
||||
|
||||
# Extract logits for target region; upcast only the slices we actually consume.
|
||||
c_logits = batch_logits[:, cond_end - t_len : cond_end, :].unsqueeze(0).to(torch.float32)
|
||||
u_logits = batch_logits[:, uncond_start : uncond_start + t_len, :].unsqueeze(0).to(torch.float32)
|
||||
sample = batch_tokens[i]
|
||||
sample_tokens = sample[..., :t_len]
|
||||
self.generator._unmask_one_request(
|
||||
c_logits,
|
||||
u_logits,
|
||||
sample_tokens,
|
||||
num_to_unmask=k,
|
||||
guidance_scale=guidance_scales[i],
|
||||
generator=generators[i],
|
||||
class_temperature=class_temperature,
|
||||
position_temperature=position_temperature,
|
||||
layer_penalty_factor=layer_penalty_factor,
|
||||
layer_ids=layer_ids,
|
||||
)
|
||||
|
||||
# Mirror update into both cond and uncond input_ids halves for the next step.
|
||||
packed_sample_tokens = sample_tokens.squeeze(0).transpose(0, 1)
|
||||
input_ids[cond_end - t_len : cond_end] = packed_sample_tokens
|
||||
input_ids[uncond_start : uncond_start + t_len] = packed_sample_tokens
|
||||
states[i].extra["tokens"] = sample_tokens
|
||||
|
||||
# InputBatch reuses its latents buffer across steps. Returning that
|
||||
# same storage would make the Runner persist per-request views into the
|
||||
# cached destination; the next make_batch() would then copy overlapping
|
||||
# source/destination slices. Break the alias at the lifecycle boundary.
|
||||
return input_ids.clone()
|
||||
|
||||
def step_scheduler(self, state: StepRequestState, noise_pred: torch.Tensor, **kwargs: Any):
|
||||
state.latents = noise_pred
|
||||
state.step_index += 1
|
||||
|
||||
def post_decode(self, state: StepRequestState, **kwargs: Any):
|
||||
tokens = state.extra["tokens"]
|
||||
if tokens.dim() == 2:
|
||||
tokens = tokens.unsqueeze(0)
|
||||
audio = self.decoder(tokens)
|
||||
return DiffusionOutput(output=audio)
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, req: DiffusionRequestBatch) -> list[DiffusionOutput]:
|
||||
"""Generate speech audio from text, optionally with voice cloning.
|
||||
|
||||
Accepts either a plain text prompt or a structured dict:
|
||||
{"text": "...", "ref_audio": (samples, sr), "ref_text": "...",
|
||||
"lang": "...", "instruct": "..."}
|
||||
"""
|
||||
prepared_requests: list[_PreparedOmniVoiceRequest] = []
|
||||
outputs = [None] * len(req.requests)
|
||||
prepared_indices: list[int] = []
|
||||
for i, request in enumerate(req.requests):
|
||||
prompt = request.prompt if request.prompt else ""
|
||||
extra = request.sampling_params.extra_args or {}
|
||||
prepared = self._prepare_request_input(prompt, extra)
|
||||
if isinstance(prepared, DiffusionOutput):
|
||||
outputs[i] = prepared
|
||||
continue
|
||||
prepared_indices.append(i)
|
||||
prepared_requests.append(prepared)
|
||||
|
||||
if not prepared_requests:
|
||||
return outputs
|
||||
|
||||
batch_target_len = [request.target_len for request in prepared_requests]
|
||||
batch_seeds = [request.seed for request in prepared_requests]
|
||||
batch_input_ids, batch_audio_mask, batch_cond_lens = self._collate_request_inputs(prepared_requests)
|
||||
# Run 32-step iterative unmasking
|
||||
sampling = req.requests[0].sampling_params
|
||||
num_step = sampling.num_inference_steps if sampling.num_inference_steps is not None else self.num_step
|
||||
guidance_scale = sampling.guidance_scale if sampling.guidance_scale is not None else self.guidance_scale
|
||||
tokens = self.generator(
|
||||
input_ids=batch_input_ids,
|
||||
audio_mask=batch_audio_mask,
|
||||
attention_mask=batch_attn_mask,
|
||||
target_lens=[target_len],
|
||||
num_step=self.num_step,
|
||||
guidance_scale=self.guidance_scale,
|
||||
cond_lens=batch_cond_lens,
|
||||
target_lens=batch_target_len,
|
||||
num_step=num_step,
|
||||
guidance_scale=guidance_scale,
|
||||
t_shift=self.t_shift,
|
||||
layer_penalty_factor=self.layer_penalty_factor,
|
||||
position_temperature=self.position_temperature,
|
||||
class_temperature=self.class_temperature,
|
||||
seed=seed,
|
||||
seed=batch_seeds,
|
||||
)
|
||||
# Decode tokens to audio
|
||||
audio = self.decoder(tokens) # [1, 1, samples]
|
||||
|
||||
return DiffusionOutput(output=audio)
|
||||
target_offset = 0
|
||||
for i, target_len in enumerate(batch_target_len):
|
||||
request_tokens = tokens[:, :, target_offset : target_offset + target_len]
|
||||
audio = self.decoder(request_tokens)
|
||||
outputs[prepared_indices[i]] = DiffusionOutput(output=audio)
|
||||
target_offset += target_len
|
||||
return outputs
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load weights from model directory (not from the iterator).
|
||||
|
||||
@@ -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
|
||||
"""π0 (Pi-Zero) VLA pipeline for vllm-omni.
|
||||
|
||||
Entry point for ``DiffusionEngine.step() → pipeline.forward(req)``. Mirrors the
|
||||
@@ -94,9 +94,9 @@ class Pi0Pipeline(nn.Module):
|
||||
return None
|
||||
if os.path.isdir(model):
|
||||
return model
|
||||
from huggingface_hub import snapshot_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
return snapshot_download(
|
||||
return hf_api().snapshot_download(
|
||||
repo_id=model,
|
||||
allow_patterns=["*.json", "*.safetensors", "*.model", "tokenizer*"],
|
||||
)
|
||||
|
||||
@@ -36,6 +36,7 @@ from vllm_omni.diffusion.models.qwen_image.pipeline_qwen_image import calculate_
|
||||
from vllm_omni.diffusion.models.qwen_image.qwen_image_transformer import (
|
||||
QwenImageTransformer2DModel,
|
||||
)
|
||||
from vllm_omni.diffusion.models.qwen_image.rope_utils import txt_seq_lens_from_embeds
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.utils.prompt_utils import (
|
||||
@@ -815,10 +816,8 @@ class QwenImageEditPipeline(
|
||||
if self.attention_kwargs is None:
|
||||
self._attention_kwargs = {}
|
||||
|
||||
txt_seq_lens = prompt_embeds_mask.sum(dim=1).tolist() if prompt_embeds_mask is not None else None
|
||||
negative_txt_seq_lens = (
|
||||
negative_prompt_embeds_mask.sum(dim=1).tolist() if negative_prompt_embeds_mask is not None else None
|
||||
)
|
||||
txt_seq_lens = txt_seq_lens_from_embeds(prompt_embeds)
|
||||
negative_txt_seq_lens = txt_seq_lens_from_embeds(negative_prompt_embeds)
|
||||
|
||||
latents = self.diffuse(
|
||||
prompt_embeds,
|
||||
|
||||
@@ -50,6 +50,17 @@ from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _apply_qwen_image_rotary_emb(x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
||||
"""Rotate interleaved pairs before rounding back to the activation dtype.
|
||||
|
||||
Qwen-Image's reference uses complex FP32 multiplication. Rounding the
|
||||
frequencies to BF16 before rotation loses positional precision; those
|
||||
errors accumulate across the denoising steps.
|
||||
"""
|
||||
paired = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
|
||||
return torch.view_as_real(paired * freqs.unsqueeze(1)).flatten(3).to(x.dtype)
|
||||
|
||||
|
||||
def _normalize_qwen_image_weight_name(name: str) -> str:
|
||||
name = name.removeprefix("transformer.")
|
||||
if ".to_out.0." in name:
|
||||
@@ -642,15 +653,23 @@ class QwenImageCrossAttention(nn.Module):
|
||||
txt_query = self.norm_added_q(txt_query)
|
||||
txt_key = self.norm_added_k(txt_key)
|
||||
|
||||
img_cos = torch.real(vid_freqs).to(img_query.dtype)
|
||||
img_sin = torch.imag(vid_freqs).to(img_query.dtype)
|
||||
txt_cos = torch.real(txt_freqs).to(txt_query.dtype)
|
||||
txt_sin = torch.imag(txt_freqs).to(txt_query.dtype)
|
||||
if img_query.device.type == "cuda":
|
||||
img_query = _apply_qwen_image_rotary_emb(img_query, vid_freqs)
|
||||
img_key = _apply_qwen_image_rotary_emb(img_key, vid_freqs)
|
||||
txt_query = _apply_qwen_image_rotary_emb(txt_query, txt_freqs)
|
||||
txt_key = _apply_qwen_image_rotary_emb(txt_key, txt_freqs)
|
||||
else:
|
||||
# Retain the platform-specific kernels on other accelerators,
|
||||
# which may not support complex tensors.
|
||||
img_cos = torch.real(vid_freqs).to(img_query.dtype)
|
||||
img_sin = torch.imag(vid_freqs).to(img_query.dtype)
|
||||
txt_cos = torch.real(txt_freqs).to(txt_query.dtype)
|
||||
txt_sin = torch.imag(txt_freqs).to(txt_query.dtype)
|
||||
|
||||
img_query = self.rope(img_query, img_cos, img_sin)
|
||||
img_key = self.rope(img_key, img_cos, img_sin)
|
||||
txt_query = self.rope(txt_query, txt_cos, txt_sin)
|
||||
txt_key = self.rope(txt_key, txt_cos, txt_sin)
|
||||
img_query = self.rope(img_query, img_cos, img_sin)
|
||||
img_key = self.rope(img_key, img_cos, img_sin)
|
||||
txt_query = self.rope(txt_query, txt_cos, txt_sin)
|
||||
txt_key = self.rope(txt_key, txt_cos, txt_sin)
|
||||
|
||||
seq_len_txt = encoder_hidden_states.shape[1]
|
||||
joint_query = torch.cat([txt_query, img_query], dim=1)
|
||||
|
||||
@@ -273,7 +273,8 @@ def retrieve_timesteps(
|
||||
|
||||
|
||||
def _validate_cache_offload_parallelism(od_config: OmniDiffusionConfig) -> None:
|
||||
cache_backend = od_config.cache_backend
|
||||
# Treat None like "none", matching the other pipelines' cache checks.
|
||||
cache_backend = od_config.cache_backend or "none"
|
||||
if cache_backend not in ("none", "cache_dit"):
|
||||
raise NotImplementedError(
|
||||
f"Cache backend {cache_backend!r} is not supported by the native SANA-Video pipeline; "
|
||||
|
||||
@@ -27,7 +27,6 @@ import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torchvision.transforms as T
|
||||
from huggingface_hub import snapshot_download
|
||||
from PIL import Image
|
||||
from transformers import AutoTokenizer
|
||||
from vllm.logger import init_logger
|
||||
@@ -109,7 +108,9 @@ def _resolve_model_path(model_path: str) -> str:
|
||||
"""Resolve a HuggingFace model ID or local path to a local directory."""
|
||||
if os.path.isdir(model_path):
|
||||
return model_path
|
||||
return snapshot_download(model_path)
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
return hf_api().snapshot_download(model_path)
|
||||
|
||||
|
||||
def _round_by_factor(number: float, factor: int) -> int:
|
||||
|
||||
@@ -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
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -31,6 +31,34 @@ if TYPE_CHECKING:
|
||||
Style = Literal["colwise", "colwise_rep", "rowwise", "rowwise_rep", "replicate"]
|
||||
|
||||
|
||||
def make_attention_mask(
|
||||
hidden_states: torch.Tensor,
|
||||
seq_lengths: list[int],
|
||||
) -> torch.Tensor | None:
|
||||
"""Build a padding mask only when the batch contains padding.
|
||||
|
||||
``seq_lengths`` must be non-empty and contain valid sequence lengths.
|
||||
Returns a boolean mask of shape ``(len(seq_lengths), max(seq_lengths))``
|
||||
on the device of ``hidden_states``, with True marking valid tokens,
|
||||
or None when all sequence lengths are equal.
|
||||
|
||||
Passing an all-true CUDA mask makes attention backends inspect a device
|
||||
scalar to select the dense path, which introduces a host-device sync.
|
||||
"""
|
||||
max_seq_len = max(seq_lengths)
|
||||
if all(seq_len == max_seq_len for seq_len in seq_lengths):
|
||||
return None
|
||||
|
||||
attention_mask = hidden_states.new_zeros(
|
||||
len(seq_lengths),
|
||||
max_seq_len,
|
||||
dtype=torch.bool,
|
||||
)
|
||||
for i, seq_len in enumerate(seq_lengths):
|
||||
attention_mask[i, :seq_len] = True
|
||||
return attention_mask
|
||||
|
||||
|
||||
def replace_linear_class(
|
||||
linear: nn.Linear,
|
||||
style: Style = "replicate",
|
||||
@@ -140,8 +168,8 @@ def _load_json(model_path: str, filename: str, local_files_only: bool = True) ->
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
from huggingface_hub import hf_hub_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
cached = hf_hub_download(repo_id=model_path, filename=filename)
|
||||
cached = hf_api().hf_hub_download(repo_id=model_path, filename=filename)
|
||||
with open(cached) as f:
|
||||
return json.load(f)
|
||||
@@ -156,9 +156,9 @@ def load_transformer_config(model_path: str, subfolder: str = "transformer", loc
|
||||
else:
|
||||
# Try to download config from HF Hub
|
||||
try:
|
||||
from huggingface_hub import hf_hub_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
config_path = hf_hub_download(
|
||||
config_path = hf_api().hf_hub_download(
|
||||
repo_id=model_path,
|
||||
filename=f"{subfolder}/config.json",
|
||||
)
|
||||
@@ -364,9 +364,9 @@ class Wan22Pipeline(
|
||||
else:
|
||||
# For remote models, download and read model_index.json
|
||||
try:
|
||||
from huggingface_hub import hf_hub_download
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
model_index_path = hf_hub_download(repo_id=model, filename="model_index.json")
|
||||
model_index_path = hf_api().hf_hub_download(repo_id=model, filename="model_index.json")
|
||||
with open(model_index_path) as f:
|
||||
model_index = json.load(f)
|
||||
self.expand_timesteps = model_index.get("expand_timesteps", False)
|
||||
|
||||
@@ -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
|
||||
"""
|
||||
Wan2.2 Speech-to-Video (S2V) Transformer using vllm-omni ops.
|
||||
|
||||
@@ -1359,11 +1359,9 @@ class WanS2VTransformer3DModel(nn.Module):
|
||||
return flatten_mot, mot_remb
|
||||
|
||||
def process_motion_frame_pack(self, motion_latents, drop_motion_frames=False, add_last_motion=2):
|
||||
flatten_mot, mot_remb = self.frame_packer(motion_latents, add_last_motion)
|
||||
if drop_motion_frames:
|
||||
return [m[:, :0] for m in flatten_mot], [m[:, :0] for m in mot_remb]
|
||||
else:
|
||||
return flatten_mot, mot_remb
|
||||
return [], []
|
||||
return self.frame_packer(motion_latents, add_last_motion)
|
||||
|
||||
def process_motion_transformer_motioner(self, motion_latents, drop_motion_frames=False, add_last_motion=True):
|
||||
batch_size = motion_latents.shape[0]
|
||||
|
||||
@@ -20,6 +20,12 @@ from .distributed_layerwise_backend import (
|
||||
from .layerwise_backend import LayerWiseOffloadBackend
|
||||
from .module_residency import BoundedAllocatorCache, PinnedModuleStager
|
||||
from .offload_plan import OffloadPlan, get_offload_plan
|
||||
from .plan_resolver import (
|
||||
BlockStack,
|
||||
ResolvedComponent,
|
||||
ResolvedOffloadPlan,
|
||||
resolve_offload_plan,
|
||||
)
|
||||
from .sequential_backend import (
|
||||
ModelLevelOffloadBackend,
|
||||
apply_sequential_offload,
|
||||
@@ -42,6 +48,10 @@ __all__ = [
|
||||
"OffloadConfig",
|
||||
"OffloadPlan",
|
||||
"OffloadStrategy",
|
||||
"BlockStack",
|
||||
"ResolvedComponent",
|
||||
"ResolvedOffloadPlan",
|
||||
"resolve_offload_plan",
|
||||
"SupportsModelCpuOffload",
|
||||
"LayerWiseOffloadBackend",
|
||||
"DistributedLayerwiseOffloadBackend",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterator
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from itertools import chain
|
||||
from operator import attrgetter
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -14,14 +14,12 @@ from torch import nn
|
||||
from torch.distributed.tensor import DTensor
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .block_discovery import get_blocks_from_dit
|
||||
from .config import DIT_COMPONENT, TEXT_ENCODER_COMPONENT
|
||||
from .config import TEXT_ENCODER_COMPONENT
|
||||
from .offload_plan import OffloadPlan
|
||||
from .tensor_utils import set_tensor_storage
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .base import OffloadConfig
|
||||
from .module_collector import PipelineModules
|
||||
from .plan_resolver import BlockStack, ResolvedComponent, ResolvedOffloadPlan
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -76,30 +74,25 @@ def get_encoder_block_groups(
|
||||
|
||||
|
||||
def iter_streamable_dits(
|
||||
modules: PipelineModules,
|
||||
config: OffloadConfig,
|
||||
resolved: ResolvedOffloadPlan,
|
||||
device: torch.device,
|
||||
plan: OffloadPlan | None,
|
||||
) -> Iterator[tuple[str, nn.Module, list[str], list[nn.Module]]]:
|
||||
"""Yield selected DiTs whose block metadata resolves successfully."""
|
||||
if not config.offloads(DIT_COMPONENT):
|
||||
return
|
||||
for name, module in zip(modules.dit_names, modules.dits):
|
||||
logger.info("Applying hooks on %s (%s)", name, module.__class__.__name__)
|
||||
planned_attrs = None if plan is None else plan.block_attrs.get(name)
|
||||
block_attrs, blocks = get_blocks_from_dit(module, planned_attrs)
|
||||
if blocks:
|
||||
yield name, module, block_attrs, blocks
|
||||
) -> Iterator[tuple[ResolvedComponent, BlockStack]]:
|
||||
"""Yield selected DiTs that resolved to a streamable block stack."""
|
||||
for component in resolved.dits:
|
||||
if not component.selected:
|
||||
continue
|
||||
if config.components is not None:
|
||||
raise ValueError(f"Selected DiT {name!r} has no streamable layerwise-offload blocks")
|
||||
logger.warning("Target layers (blocks) not found. Skipping offloading on %s (%s)", name, type(module).__name__)
|
||||
module.to(device)
|
||||
logger.info("Applying hooks on %s (%s)", component.path, component.module.__class__.__name__)
|
||||
if not component.stacks:
|
||||
# The resolver already warned; a legacy selection keeps the
|
||||
# unstreamable DiT resident instead of failing the run.
|
||||
component.module.to(device)
|
||||
continue
|
||||
yield component, component.stacks[0]
|
||||
|
||||
|
||||
def move_non_block_state_to_device(
|
||||
module: nn.Module,
|
||||
block_groups: list[nn.ModuleList],
|
||||
block_groups: Sequence[Sequence[nn.Module]],
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
"""Keep component state outside streamed block lists resident on device."""
|
||||
@@ -120,7 +113,7 @@ def move_non_block_state_to_device(
|
||||
def set_encoder_layerwise_state(
|
||||
module: nn.Module,
|
||||
hooks: list[Any],
|
||||
block_groups: list[nn.ModuleList],
|
||||
block_groups: Sequence[Sequence[nn.Module]],
|
||||
) -> None:
|
||||
"""Publish the backend-neutral state used by encoder stage lifecycles."""
|
||||
module._omni_layerwise_hooks = hooks
|
||||
@@ -163,59 +156,38 @@ def prepare_component(
|
||||
|
||||
|
||||
def prepare_pipeline_components(
|
||||
modules: PipelineModules,
|
||||
config: OffloadConfig,
|
||||
plan: OffloadPlan | None,
|
||||
resolved: ResolvedOffloadPlan,
|
||||
*,
|
||||
device: torch.device,
|
||||
staged_components: list[nn.Module],
|
||||
enable_encoder_blocks: Callable[[nn.Module, str, OffloadPlan | None, bool], bool],
|
||||
enable_encoder_blocks: Callable[[ResolvedComponent], bool],
|
||||
) -> None:
|
||||
"""Apply the shared encoder/VAE/resident placement policy."""
|
||||
if config.components is not None and config.offloads(TEXT_ENCODER_COMPONENT):
|
||||
selected_encoder_names = [name for name in modules.encoder_names if config.offloads_encoder(name, plan)]
|
||||
if not selected_encoder_names:
|
||||
raise ValueError("No text encoder modules found for selected text_encoder offload")
|
||||
|
||||
if plan is not None:
|
||||
for encoder, name in zip(modules.encoders, modules.encoder_names):
|
||||
if config.should_offload_encoder(name, plan) and name in plan.on_demand_component_paths:
|
||||
validate_on_demand_component(encoder, name)
|
||||
|
||||
for encoder, name in zip(modules.encoders, modules.encoder_names):
|
||||
selected = config.should_offload_encoder(name, plan)
|
||||
stage_on_demand = bool(selected and plan is not None and name in plan.on_demand_component_paths)
|
||||
blockwise = selected and enable_encoder_blocks(encoder, name, plan, stage_on_demand)
|
||||
if stage_on_demand and not blockwise and config.uses_allgather(TEXT_ENCODER_COMPONENT):
|
||||
raise ValueError(
|
||||
f"Text encoder {name!r} cannot use AllGather without a model-declared streamable block plan"
|
||||
)
|
||||
if selected and config.components is not None and not (blockwise or stage_on_demand):
|
||||
raise ValueError(f"Selected text encoder {name!r} requires a model-declared streamable or on-demand plan")
|
||||
for component in resolved.encoders:
|
||||
blockwise = bool(component.stacks) and enable_encoder_blocks(component)
|
||||
prepare_component(
|
||||
encoder,
|
||||
name,
|
||||
component.module,
|
||||
component.path,
|
||||
device=device,
|
||||
stage_on_demand=stage_on_demand,
|
||||
stage_on_demand=component.on_demand,
|
||||
blockwise=blockwise,
|
||||
staged_components=staged_components,
|
||||
)
|
||||
|
||||
for vae, name in zip(modules.vaes, modules.vae_names):
|
||||
legacy_staged = config.components is None and plan is not None and name in plan.on_demand_component_paths
|
||||
for component in resolved.vaes:
|
||||
prepare_component(
|
||||
vae,
|
||||
name,
|
||||
component.module,
|
||||
component.path,
|
||||
device=device,
|
||||
stage_on_demand=legacy_staged,
|
||||
stage_on_demand=component.on_demand,
|
||||
blockwise=False,
|
||||
staged_components=staged_components,
|
||||
)
|
||||
|
||||
for name, module in zip(modules.resident_names, modules.resident_modules):
|
||||
module.to(device)
|
||||
logger.debug("Moved resident module %s to %s", name, device)
|
||||
for component in resolved.residents:
|
||||
component.module.to(device)
|
||||
logger.debug("Moved resident module %s to %s", component.path, device)
|
||||
|
||||
if not config.offloads(DIT_COMPONENT):
|
||||
for dit in modules.dits:
|
||||
dit.to(device)
|
||||
for component in resolved.dits:
|
||||
if not component.selected:
|
||||
component.module.to(device)
|
||||
@@ -21,6 +21,7 @@ from __future__ import annotations
|
||||
import threading
|
||||
import time
|
||||
import weakref
|
||||
from collections.abc import Sequence
|
||||
from itertools import chain
|
||||
from typing import Any
|
||||
|
||||
@@ -39,7 +40,6 @@ from vllm_omni.platforms import current_omni_platform
|
||||
from .base import OffloadBackend, OffloadConfig, run_cleanup_steps
|
||||
from .component_utils import (
|
||||
clear_encoder_layerwise_state,
|
||||
get_encoder_block_groups,
|
||||
iter_streamable_dits,
|
||||
move_non_block_state_to_device,
|
||||
prepare_component,
|
||||
@@ -53,11 +53,8 @@ from .host_registration import (
|
||||
HostRegistrationError,
|
||||
register_host_mappings,
|
||||
)
|
||||
from .module_collector import ModuleDiscovery
|
||||
from .offload_plan import (
|
||||
OffloadPlan,
|
||||
get_offload_plan,
|
||||
)
|
||||
from .offload_plan import OffloadPlan
|
||||
from .plan_resolver import ResolvedComponent, resolve_offload_plan
|
||||
from .tensor_utils import (
|
||||
clear_block_storage,
|
||||
clear_tensor_storage,
|
||||
@@ -1437,7 +1434,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
|
||||
|
||||
def _install_hook_group(
|
||||
self,
|
||||
blocks: list[nn.Module] | nn.ModuleList,
|
||||
blocks: Sequence[nn.Module] | nn.ModuleList,
|
||||
component: str,
|
||||
*,
|
||||
use_dit_mmap: bool = False,
|
||||
@@ -1483,48 +1480,27 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
|
||||
hooks[1]._is_group_first = True
|
||||
return hooks
|
||||
|
||||
def _try_layerwise_offload_encoder(
|
||||
self,
|
||||
module: nn.Module,
|
||||
name: str,
|
||||
plan: OffloadPlan | None,
|
||||
stage_on_demand: bool = False,
|
||||
) -> bool:
|
||||
"""Apply DLO hooks to a plan-declared text encoder.
|
||||
def _try_layerwise_offload_encoder(self, component: ResolvedComponent) -> bool:
|
||||
"""Apply DLO hooks to a text encoder's resolved block stacks.
|
||||
|
||||
Rank-local transfer is always safe because it preserves the tensors
|
||||
produced by the model loader. Multi-rank AllGather is enabled only
|
||||
when the model declares that those tensors are replicated across the
|
||||
selected DLO group; encoder TP groups contain different shards and
|
||||
are deliberately not used for this transport.
|
||||
selected DLO group; the resolver rejects every other layout before
|
||||
this method installs anything.
|
||||
"""
|
||||
if plan is None:
|
||||
return False
|
||||
|
||||
group_size = self._component_transport(TEXT_ENCODER_COMPONENT)[1]
|
||||
if group_size > 1 and name not in plan.encoder_dlo_weight_replication:
|
||||
raise ValueError(
|
||||
f"Text encoder {name!r} cannot use DLO AllGather across the DiT offload group: "
|
||||
"its loader-produced weights are not declared replicated across that group. "
|
||||
"Set layer_options.text_encoder.weight_transfer='rank-local' in diffusion_offload_config "
|
||||
"for encoder-TP or rank-specific layouts."
|
||||
)
|
||||
block_groups = get_encoder_block_groups(
|
||||
module,
|
||||
name,
|
||||
plan,
|
||||
strict=self.config.components is not None or group_size > 1,
|
||||
)
|
||||
block_groups = [stack.blocks for stack in component.stacks]
|
||||
if not block_groups:
|
||||
return False
|
||||
|
||||
module = component.module
|
||||
encoder_hooks: list[DistributedLayerwiseOffloadHook] = []
|
||||
for blocks in block_groups:
|
||||
encoder_hooks.extend(self._install_hook_group(blocks, TEXT_ENCODER_COMPONENT))
|
||||
# Track the module before placement, which may fail, so outer rollback
|
||||
# also removes its partially-installed block hooks and marker state.
|
||||
self._encoder_modules.append(module)
|
||||
if not stage_on_demand:
|
||||
if not component.on_demand:
|
||||
move_non_block_state_to_device(module, block_groups, self.device)
|
||||
set_encoder_layerwise_state(
|
||||
module,
|
||||
@@ -1534,10 +1510,10 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
|
||||
logger.info(
|
||||
"Enabled %s DLO transfer for text encoder %s (%d blocks across %d stacks, group_size=%d)",
|
||||
self.config.transfer_for(TEXT_ENCODER_COMPONENT).value,
|
||||
name,
|
||||
component.path,
|
||||
sum(len(blocks) for blocks in block_groups),
|
||||
len(block_groups),
|
||||
group_size,
|
||||
self._component_transport(TEXT_ENCODER_COMPONENT)[1],
|
||||
)
|
||||
return True
|
||||
|
||||
@@ -1700,31 +1676,15 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
|
||||
if self.dp_group is None and self._has_multirank_allgather():
|
||||
self._init_dp_group()
|
||||
|
||||
modules = ModuleDiscovery.discover(pipeline)
|
||||
if not modules.dits and self.config.offloads(DIT_COMPONENT):
|
||||
# One resolver call validates the whole topology; an explicit selection
|
||||
# has already failed by the time any of the checks below run.
|
||||
resolved = resolve_offload_plan(pipeline, self.config)
|
||||
if not resolved.dits and self.config.offloads(DIT_COMPONENT):
|
||||
if self.host_weight_plan is not None:
|
||||
raise RuntimeError(
|
||||
"DLO received a loader-owned host-weight plan, but no DiT modules were discovered to consume it"
|
||||
)
|
||||
message = "No DiT/transformer modules found for selected DiT offload"
|
||||
if self.config.components is not None:
|
||||
raise ValueError(message)
|
||||
logger.warning(message)
|
||||
|
||||
# Retrieve optional declarative OffloadPlan from the pipeline.
|
||||
# When present, replaces heuristic block discovery.
|
||||
plan = get_offload_plan(pipeline)
|
||||
|
||||
if self.config.dlo_resident_layers:
|
||||
resident_paths = frozenset() if plan is None else plan.resident_dit_paths
|
||||
if not resident_paths.intersection(modules.dit_names):
|
||||
message = (
|
||||
f"resident_layers={self.config.dlo_resident_layers} was requested, but this model declares "
|
||||
"no matching resident_dit_paths"
|
||||
)
|
||||
if self.config.components is not None:
|
||||
raise ValueError(message)
|
||||
logger.warning("%s; all blocks will be streamed.", message)
|
||||
logger.warning("No DiT/transformer modules found for selected DiT offload")
|
||||
|
||||
# Storage selection belongs to the loader. DLO consumes the exact
|
||||
# prevalidated plan that caused the loader to skip materialization;
|
||||
@@ -1755,7 +1715,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
|
||||
elif host_weight_plan.backing_kind == "checkpoint_mmap":
|
||||
self._load_weights_via_mmap(
|
||||
pipeline,
|
||||
modules,
|
||||
resolved.modules,
|
||||
host_weight_plan,
|
||||
)
|
||||
else:
|
||||
@@ -1768,10 +1728,10 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
|
||||
else:
|
||||
remaining_meta = [
|
||||
name
|
||||
for dit_name, dit_module in zip(modules.dit_names, modules.dits)
|
||||
for component in resolved.dits
|
||||
for name, tensor in chain(
|
||||
dit_module.named_parameters(),
|
||||
dit_module.named_buffers(),
|
||||
component.module.named_parameters(),
|
||||
component.module.named_buffers(),
|
||||
)
|
||||
if getattr(tensor, "is_meta", False)
|
||||
]
|
||||
@@ -1784,66 +1744,46 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
|
||||
# Apply each selected encoder transfer while keeping explicit VAEs and
|
||||
# unselected components resident.
|
||||
prepare_pipeline_components(
|
||||
modules,
|
||||
self.config,
|
||||
plan,
|
||||
resolved,
|
||||
device=self.device,
|
||||
staged_components=self._staged_components,
|
||||
enable_encoder_blocks=self._try_layerwise_offload_encoder,
|
||||
)
|
||||
|
||||
if self.config.offloads(DIT_COMPONENT):
|
||||
logger.info("Applying distributed layer-wise offloading on %s", modules.dit_names)
|
||||
logger.info(
|
||||
"Applying distributed layer-wise offloading on %s",
|
||||
[component.path for component in resolved.dits],
|
||||
)
|
||||
|
||||
# Collect all DiT module objects to detect submodules that are
|
||||
# already handled as a separate DiT module (avoids duplicate hooks).
|
||||
all_dit_modules = set(id(m) for m in modules.dits)
|
||||
all_dit_modules = set(id(component.module) for component in resolved.dits)
|
||||
|
||||
# Apply hooks for each DiT module
|
||||
for dit_name, dit_module, blocks_attr_names, blocks in iter_streamable_dits(
|
||||
modules, self.config, self.device, plan
|
||||
):
|
||||
resident_count = 0
|
||||
if plan is not None and dit_name in plan.resident_dit_paths:
|
||||
resident_count = min(self.config.dlo_resident_layers, len(blocks))
|
||||
if resident_count:
|
||||
resident_blocks = blocks[:resident_count]
|
||||
self._resident_blocks.extend(resident_blocks)
|
||||
blocks = blocks[resident_count:]
|
||||
for component, stack in iter_streamable_dits(resolved, self.device):
|
||||
streaming = list(stack.streaming)
|
||||
if stack.resident_head:
|
||||
self._resident_blocks.extend(stack.resident)
|
||||
logger.info(
|
||||
"Keeping %d leading blocks resident on %s; streaming %d tail blocks",
|
||||
resident_count,
|
||||
dit_name,
|
||||
len(blocks),
|
||||
stack.resident_head,
|
||||
component.path,
|
||||
len(streaming),
|
||||
)
|
||||
|
||||
self._prepare_dit_non_block_modules(
|
||||
dit_module,
|
||||
blocks_attr_names,
|
||||
component.module,
|
||||
list(stack.attrs),
|
||||
all_dit_modules,
|
||||
plan,
|
||||
resolved.declaration,
|
||||
)
|
||||
|
||||
num_blocks = len(blocks)
|
||||
if num_blocks == 0:
|
||||
logger.info("All blocks for %s are resident; no streaming hooks required", dit_name)
|
||||
continue
|
||||
if num_blocks <= 1:
|
||||
if self.config.components is not None:
|
||||
raise ValueError(
|
||||
f"Selected DiT {dit_name!r} leaves only one streaming block after "
|
||||
f"resident_layers={resident_count}; choose a resident count that "
|
||||
"leaves zero or at least two streaming blocks"
|
||||
)
|
||||
logger.warning(
|
||||
"#Streaming target layers (blocks) <= 1. Keeping the final block resident on %s (%s)",
|
||||
dit_name,
|
||||
dit_module.__class__.__name__,
|
||||
)
|
||||
self._resident_blocks.extend(blocks)
|
||||
if not streaming:
|
||||
logger.info("All blocks for %s are resident; no streaming hooks required", component.path)
|
||||
continue
|
||||
|
||||
self._install_hook_group(blocks, DIT_COMPONENT, use_dit_mmap=True)
|
||||
self._install_hook_group(streaming, DIT_COMPONENT, use_dit_mmap=True)
|
||||
if self._resident_blocks:
|
||||
self._resident_layer_group = PinnedResidentLayerGroup(
|
||||
self._resident_blocks,
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from itertools import chain
|
||||
from typing import Any
|
||||
|
||||
@@ -20,15 +21,13 @@ from .block_discovery import (
|
||||
)
|
||||
from .component_utils import (
|
||||
clear_encoder_layerwise_state,
|
||||
get_encoder_block_groups,
|
||||
iter_streamable_dits,
|
||||
move_non_block_state_to_device,
|
||||
prepare_pipeline_components,
|
||||
set_encoder_layerwise_state,
|
||||
)
|
||||
from .config import DIT_COMPONENT
|
||||
from .module_collector import ModuleDiscovery
|
||||
from .offload_plan import OffloadPlan, get_offload_plan
|
||||
from .plan_resolver import ResolvedComponent, resolve_offload_plan
|
||||
from .tensor_utils import (
|
||||
clear_block_storage,
|
||||
clear_tensor_storage,
|
||||
@@ -279,7 +278,7 @@ def remove_block_hook(module: nn.Module) -> None:
|
||||
|
||||
|
||||
def _install_layerwise_hook_group(
|
||||
blocks: list[nn.Module] | nn.ModuleList,
|
||||
blocks: Sequence[nn.Module] | nn.ModuleList,
|
||||
device: torch.device,
|
||||
stream: Any,
|
||||
pin_memory: bool,
|
||||
@@ -327,36 +326,29 @@ def _install_layerwise_hook_group(
|
||||
|
||||
|
||||
def enable_plan_encoder_layerwise_offload(
|
||||
module: nn.Module,
|
||||
name: str,
|
||||
plan: OffloadPlan | None,
|
||||
component: ResolvedComponent,
|
||||
*,
|
||||
device: torch.device,
|
||||
stream: current_omni_platform.Stream,
|
||||
pin_memory: bool,
|
||||
stage_on_demand: bool = False,
|
||||
strict: bool = False,
|
||||
) -> bool:
|
||||
"""Apply rank-local layerwise hooks to plan-declared encoder stacks."""
|
||||
"""Apply rank-local layerwise hooks to the encoder's resolved stacks."""
|
||||
module = component.module
|
||||
if getattr(module, "_omni_layerwise_enabled", False):
|
||||
return True
|
||||
|
||||
hooks: list[LayerwiseOffloadHook] = []
|
||||
hooked_blocks: list[nn.Module] = []
|
||||
block_groups = get_encoder_block_groups(
|
||||
module,
|
||||
name,
|
||||
plan,
|
||||
strict=strict,
|
||||
)
|
||||
block_groups = [stack.blocks for stack in component.stacks]
|
||||
if not block_groups:
|
||||
return False
|
||||
|
||||
hooks: list[LayerwiseOffloadHook] = []
|
||||
hooked_blocks: list[nn.Module] = []
|
||||
try:
|
||||
for blocks in block_groups:
|
||||
group_hooks = _install_layerwise_hook_group(blocks, device, stream, pin_memory)
|
||||
hooks.extend(group_hooks)
|
||||
hooked_blocks.extend(blocks)
|
||||
if not stage_on_demand:
|
||||
if not component.on_demand:
|
||||
move_non_block_state_to_device(module, block_groups, device)
|
||||
except BaseException:
|
||||
run_cleanup_steps(
|
||||
@@ -376,7 +368,7 @@ def enable_plan_encoder_layerwise_offload(
|
||||
)
|
||||
logger.info(
|
||||
"Enabled rank-local layerwise offload for encoder %s (%d blocks across %d stacks)",
|
||||
name,
|
||||
component.path,
|
||||
sum(len(blocks) for blocks in block_groups),
|
||||
len(block_groups),
|
||||
)
|
||||
@@ -440,41 +432,27 @@ class LayerWiseOffloadBackend(OffloadBackend):
|
||||
logger.warning("LayerWiseOffloadBackend already enabled")
|
||||
return
|
||||
|
||||
modules = ModuleDiscovery.discover(pipeline)
|
||||
plan = get_offload_plan(pipeline)
|
||||
if not modules.dits and self.config.offloads(DIT_COMPONENT):
|
||||
message = "No DiT/transformer modules found for selected DiT layerwise offload"
|
||||
if self.config.components is not None:
|
||||
raise ValueError(message)
|
||||
logger.warning(message)
|
||||
resolved = resolve_offload_plan(pipeline, self.config)
|
||||
if not resolved.dits and self.config.offloads(DIT_COMPONENT):
|
||||
# An explicit selection already failed while resolving.
|
||||
logger.warning("No DiT/transformer modules found for selected DiT layerwise offload")
|
||||
return
|
||||
|
||||
def enable_encoder_blocks(
|
||||
module: nn.Module,
|
||||
name: str,
|
||||
component_plan: OffloadPlan | None,
|
||||
stage_on_demand: bool,
|
||||
) -> bool:
|
||||
def enable_encoder_blocks(component: ResolvedComponent) -> bool:
|
||||
enabled = enable_plan_encoder_layerwise_offload(
|
||||
module,
|
||||
name,
|
||||
component_plan,
|
||||
component,
|
||||
device=self.device,
|
||||
stream=self.copy_stream,
|
||||
pin_memory=self.config.pin_cpu_memory,
|
||||
stage_on_demand=stage_on_demand,
|
||||
strict=self.config.components is not None,
|
||||
)
|
||||
if enabled:
|
||||
# Record each successful installation immediately so a later
|
||||
# component failure can remove these hooks transactionally.
|
||||
self._encoder_modules.append(module)
|
||||
self._encoder_modules.append(component.module)
|
||||
return enabled
|
||||
|
||||
prepare_pipeline_components(
|
||||
modules,
|
||||
self.config,
|
||||
plan,
|
||||
resolved,
|
||||
device=self.device,
|
||||
staged_components=self._staged_components,
|
||||
enable_encoder_blocks=enable_encoder_blocks,
|
||||
@@ -489,30 +467,17 @@ class LayerWiseOffloadBackend(OffloadBackend):
|
||||
)
|
||||
return
|
||||
|
||||
logger.info("Applying layer-wise offloading on %s", modules.dit_names)
|
||||
logger.info("Applying layer-wise offloading on %s", [component.path for component in resolved.dits])
|
||||
|
||||
# Apply block-wise offloading hook for each of the blocks in DiT model(s)
|
||||
# Note that there might exist multiple DiT models in specific pipelines
|
||||
for dit_name, dit_module, blocks_attr_names, blocks in iter_streamable_dits(
|
||||
modules, self.config, self.device, plan
|
||||
):
|
||||
num_blocks = len(blocks)
|
||||
if num_blocks <= 1:
|
||||
if self.config.components is not None:
|
||||
raise ValueError(
|
||||
f"Selected DiT {dit_name!r} requires at least two streamable layerwise-offload blocks"
|
||||
)
|
||||
logger.warning(
|
||||
"#Target layers (blocks) <= 1. Skipping offloading on %s (%s)",
|
||||
dit_name,
|
||||
dit_module.__class__.__name__,
|
||||
)
|
||||
dit_module.to(self.device)
|
||||
continue
|
||||
for component, stack in iter_streamable_dits(resolved, self.device):
|
||||
dit_module = component.module
|
||||
blocks = list(stack.blocks)
|
||||
|
||||
# Move non-block modules to GPU (they stay resident)
|
||||
for name, m in dit_module.named_children():
|
||||
if name not in blocks_attr_names:
|
||||
if name not in stack.attrs:
|
||||
m.to(self.device)
|
||||
logger.debug(f"Moved {name} to device {self.device}")
|
||||
else:
|
||||
@@ -540,7 +505,7 @@ class LayerWiseOffloadBackend(OffloadBackend):
|
||||
# zero once; later denoising iterations prefetch it from the ring.
|
||||
block_hooks[0].prefetch_layer(non_blocking=False)
|
||||
|
||||
logger.info(f"Layer-wise offloading enabled on {num_blocks} layers (blocks)")
|
||||
logger.info(f"Layer-wise offloading enabled on {len(blocks)} layers (blocks)")
|
||||
|
||||
# Track hooked blocks for cleanup
|
||||
self._blocks.append(blocks)
|
||||
|
||||
@@ -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
|
||||
"""Declarative model capabilities for component layerwise offload.
|
||||
|
||||
Models declare an ``_offload_plan`` class attribute on the pipeline. Both the
|
||||
@@ -22,9 +22,11 @@ class OffloadPlan:
|
||||
pipeline class. When present, both layerwise backends use it instead of
|
||||
model-specific backend branches, making new integrations data-driven.
|
||||
|
||||
If not declared, the offloader falls back to:
|
||||
1. ``_layerwise_offload_blocks_attrs`` on each DiT module class.
|
||||
2. Heuristic search for ``layers`` / ``blocks`` / ``h`` attributes.
|
||||
If not declared, the offloader falls back to
|
||||
``_layerwise_offload_blocks_attrs`` on each DiT module class.
|
||||
|
||||
:func:`~vllm_omni.diffusion.offloader.plan_resolver.resolve_offload_plan`
|
||||
is the only consumer; backends read the resolved artifact it returns.
|
||||
|
||||
Attributes:
|
||||
block_attrs: Maps DiT path → tuple of block-list attribute names.
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""One topology resolver shared by every diffusion offload backend.
|
||||
|
||||
Model topology is declared through several mechanisms that grew independently:
|
||||
:class:`~vllm_omni.diffusion.models.interface.SupportsComponentDiscovery` class
|
||||
variables, the pipeline-level :class:`OffloadPlan`, per-DiT
|
||||
``_layerwise_offload_blocks_attrs``, and a leaf-name rule for encoders. This
|
||||
module runs them in one defined order and returns one backend-neutral artifact.
|
||||
|
||||
The resolver is pure: it moves no tensor, installs no hook, writes no module
|
||||
attribute, and touches no process group. Everything it can reject is rejected
|
||||
here, so plan-dependent failures happen before a backend mutates the model.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
|
||||
|
||||
from .block_discovery import get_blocks_from_dit
|
||||
from .component_utils import get_encoder_block_groups, validate_on_demand_component
|
||||
from .config import DIT_COMPONENT, TEXT_ENCODER_COMPONENT, OffloadStrategy
|
||||
from .module_collector import ModuleDiscovery, PipelineModules
|
||||
from .offload_plan import OffloadPlan, get_offload_plan
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .base import OffloadConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BlockStack:
|
||||
"""One ring of repeated blocks that a backend streams together.
|
||||
|
||||
``attrs`` names the owner attributes that contributed blocks; backends use
|
||||
it to skip those children when they place the non-streamed remainder. It is
|
||||
filled for DiT stacks only — encoder stacks are hooked as whole stacks and
|
||||
their remainder is placed by tensor identity.
|
||||
"""
|
||||
|
||||
blocks: tuple[nn.Module, ...]
|
||||
attrs: tuple[str, ...] = ()
|
||||
resident_head: int = 0
|
||||
|
||||
@property
|
||||
def resident(self) -> tuple[nn.Module, ...]:
|
||||
"""Leading blocks that stay on the device instead of streaming."""
|
||||
return self.blocks[: self.resident_head]
|
||||
|
||||
@property
|
||||
def streaming(self) -> tuple[nn.Module, ...]:
|
||||
"""Blocks a hook ring transfers on demand."""
|
||||
return self.blocks[self.resident_head :]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedComponent:
|
||||
"""One pipeline component with its resolved, validated offload topology.
|
||||
|
||||
``selected`` means the active selector covers this component. ``on_demand``
|
||||
means the pipeline owns its residency through ``load_to_device`` /
|
||||
``offload_to_cpu``; a VAE staged by a legacy model plan is ``on_demand``
|
||||
without being selectable through the public component grammar.
|
||||
"""
|
||||
|
||||
path: str
|
||||
module: nn.Module
|
||||
selected: bool
|
||||
stacks: tuple[BlockStack, ...] = ()
|
||||
on_demand: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedOffloadPlan:
|
||||
"""Backend-neutral topology for one pipeline under one offload config."""
|
||||
|
||||
dits: tuple[ResolvedComponent, ...]
|
||||
encoders: tuple[ResolvedComponent, ...]
|
||||
vaes: tuple[ResolvedComponent, ...]
|
||||
residents: tuple[ResolvedComponent, ...]
|
||||
# Raw discovery output and the model declaration remain reachable for the
|
||||
# loader-owned mmap path and for DLO's nested-submodule staging, which
|
||||
# still interpret topology themselves.
|
||||
modules: PipelineModules
|
||||
declaration: OffloadPlan | None = None
|
||||
|
||||
@property
|
||||
def components(self) -> tuple[ResolvedComponent, ...]:
|
||||
return self.dits + self.encoders + self.vaes + self.residents
|
||||
|
||||
|
||||
@cache
|
||||
def _warn_legacy_discovery(pipeline_class: str) -> None:
|
||||
"""Warn once per pipeline class that component discovery guessed.
|
||||
|
||||
The key is the fully qualified class name so two same-named pipeline
|
||||
classes in different modules each get their own warning.
|
||||
"""
|
||||
logger.warning(
|
||||
"%s does not declare SupportsComponentDiscovery; offload components were "
|
||||
"discovered by scanning well-known attribute names. Declare _dit_modules, "
|
||||
"_encoder_modules, and _vae_modules; the attribute scan is deprecated.",
|
||||
pipeline_class,
|
||||
)
|
||||
|
||||
|
||||
def _resolve_dit_stacks(
|
||||
module: nn.Module,
|
||||
path: str,
|
||||
declaration: OffloadPlan | None,
|
||||
config: OffloadConfig,
|
||||
*,
|
||||
explicit: bool,
|
||||
) -> tuple[BlockStack, ...]:
|
||||
"""Resolve one DiT's streamed blocks and its device-resident head."""
|
||||
planned_attrs = None if declaration is None else declaration.block_attrs.get(path)
|
||||
attrs, blocks = get_blocks_from_dit(module, planned_attrs)
|
||||
if not blocks:
|
||||
if explicit:
|
||||
raise ValueError(f"Selected DiT {path!r} has no streamable layerwise-offload blocks")
|
||||
logger.warning(
|
||||
"Target layers (blocks) not found. Skipping offloading on %s (%s)",
|
||||
path,
|
||||
type(module).__name__,
|
||||
)
|
||||
return ()
|
||||
|
||||
distributed = config.strategy is OffloadStrategy.DISTRIBUTED_LAYER_WISE
|
||||
resident_head = 0
|
||||
if (
|
||||
distributed
|
||||
and config.dlo_resident_layers
|
||||
and declaration is not None
|
||||
and path in declaration.resident_dit_paths
|
||||
):
|
||||
resident_head = min(config.dlo_resident_layers, len(blocks))
|
||||
|
||||
if len(blocks) - resident_head == 1:
|
||||
if explicit and distributed:
|
||||
raise ValueError(
|
||||
f"Selected DiT {path!r} leaves only one streaming block after "
|
||||
f"resident_layers={resident_head}; choose a resident count that "
|
||||
"leaves zero or at least two streaming blocks"
|
||||
)
|
||||
if explicit:
|
||||
raise ValueError(f"Selected DiT {path!r} requires at least two streamable layerwise-offload blocks")
|
||||
if distributed:
|
||||
# One streamed block cannot form a prefetch ring; keeping it
|
||||
# resident preserves the model instead of skipping placement.
|
||||
logger.warning(
|
||||
"#Streaming target layers (blocks) <= 1. Keeping the final block resident on %s (%s)",
|
||||
path,
|
||||
type(module).__name__,
|
||||
)
|
||||
resident_head = len(blocks)
|
||||
else:
|
||||
logger.warning(
|
||||
"#Target layers (blocks) <= 1. Skipping offloading on %s (%s)",
|
||||
path,
|
||||
type(module).__name__,
|
||||
)
|
||||
return ()
|
||||
|
||||
return (BlockStack(blocks=tuple(blocks), attrs=tuple(attrs), resident_head=resident_head),)
|
||||
|
||||
|
||||
def _resolve_encoder_stacks(
|
||||
module: nn.Module,
|
||||
path: str,
|
||||
declaration: OffloadPlan | None,
|
||||
config: OffloadConfig,
|
||||
*,
|
||||
explicit: bool,
|
||||
) -> tuple[BlockStack, ...]:
|
||||
"""Resolve one encoder's streamable stacks and check transfer safety."""
|
||||
if declaration is None:
|
||||
return ()
|
||||
|
||||
group_size = 1
|
||||
if config.strategy is OffloadStrategy.DISTRIBUTED_LAYER_WISE and config.uses_allgather(TEXT_ENCODER_COMPONENT):
|
||||
group_size = config.dp_size
|
||||
if group_size > 1 and path not in declaration.encoder_dlo_weight_replication:
|
||||
# Every rank must reject an unsafe group, including ranks whose local
|
||||
# encoder is an unloaded stub, so the check precedes block discovery.
|
||||
raise ValueError(
|
||||
f"Text encoder {path!r} cannot use DLO AllGather across the DiT offload group: "
|
||||
"its loader-produced weights are not declared replicated across that group. "
|
||||
"Set layer_options.text_encoder.weight_transfer='rank-local' in diffusion_offload_config "
|
||||
"for encoder-TP or rank-specific layouts."
|
||||
)
|
||||
|
||||
groups = get_encoder_block_groups(module, path, declaration, strict=explicit or group_size > 1)
|
||||
return tuple(BlockStack(blocks=tuple(blocks)) for blocks in groups)
|
||||
|
||||
|
||||
def resolve_offload_plan(pipeline: nn.Module, config: OffloadConfig) -> ResolvedOffloadPlan:
|
||||
"""Resolve and validate one pipeline's offload topology.
|
||||
|
||||
Raises ``ValueError`` for every topology that the requested configuration
|
||||
cannot serve, before the caller places a module or installs a hook.
|
||||
"""
|
||||
modules = ModuleDiscovery.discover(pipeline)
|
||||
declaration = get_offload_plan(pipeline)
|
||||
if not isinstance(pipeline, SupportsComponentDiscovery) and (modules.dits or modules.encoders or modules.vaes):
|
||||
pipeline_class = type(pipeline)
|
||||
_warn_legacy_discovery(f"{pipeline_class.__module__}.{pipeline_class.__qualname__}")
|
||||
|
||||
explicit = config.components is not None
|
||||
layerwise = config.strategy in (OffloadStrategy.LAYER_WISE, OffloadStrategy.DISTRIBUTED_LAYER_WISE)
|
||||
dit_selected = config.offloads(DIT_COMPONENT)
|
||||
|
||||
if explicit:
|
||||
if config.strategy is OffloadStrategy.MODEL_LEVEL:
|
||||
# Model-level offload swaps the DiT against an encoder stage, so
|
||||
# both sides must exist regardless of which side was selected.
|
||||
if not modules.dits:
|
||||
raise ValueError("Component-selective model offload requires a DiT/transformer module")
|
||||
if not modules.encoders:
|
||||
raise ValueError("Component-selective model offload requires an encoder execution stage")
|
||||
elif dit_selected and not modules.dits:
|
||||
raise ValueError("No DiT/transformer modules found for selected DiT offload")
|
||||
if config.offloads(TEXT_ENCODER_COMPONENT) and not any(
|
||||
config.offloads_encoder(path, declaration) for path in modules.encoder_names
|
||||
):
|
||||
raise ValueError("No text encoder modules found for selected text_encoder offload")
|
||||
|
||||
if config.strategy is OffloadStrategy.DISTRIBUTED_LAYER_WISE and config.dlo_resident_layers:
|
||||
resident_paths = frozenset() if declaration is None else declaration.resident_dit_paths
|
||||
if not resident_paths.intersection(modules.dit_names):
|
||||
message = (
|
||||
f"resident_layers={config.dlo_resident_layers} was requested, but this model declares "
|
||||
"no matching resident_dit_paths"
|
||||
)
|
||||
if explicit:
|
||||
raise ValueError(message)
|
||||
logger.warning("%s; all blocks will be streamed.", message)
|
||||
|
||||
dits: list[ResolvedComponent] = []
|
||||
encoders: list[ResolvedComponent] = []
|
||||
vaes: list[ResolvedComponent] = []
|
||||
residents: list[ResolvedComponent] = []
|
||||
|
||||
for path, module in zip(modules.dit_names, modules.dits):
|
||||
stacks: tuple[BlockStack, ...] = ()
|
||||
if dit_selected and layerwise:
|
||||
stacks = _resolve_dit_stacks(module, path, declaration, config, explicit=explicit)
|
||||
dits.append(ResolvedComponent(path=path, module=module, selected=dit_selected, stacks=stacks))
|
||||
|
||||
for path, module in zip(modules.encoder_names, modules.encoders):
|
||||
selected = config.should_offload_encoder(path, declaration)
|
||||
# Staged residency belongs to the layer backends; model-level offload
|
||||
# swaps whole modules through its own hooks.
|
||||
on_demand = bool(
|
||||
selected and layerwise and declaration is not None and path in declaration.on_demand_component_paths
|
||||
)
|
||||
if on_demand:
|
||||
validate_on_demand_component(module, path)
|
||||
stacks = ()
|
||||
if selected and layerwise:
|
||||
stacks = _resolve_encoder_stacks(module, path, declaration, config, explicit=explicit)
|
||||
if on_demand and not stacks and config.uses_allgather(TEXT_ENCODER_COMPONENT):
|
||||
raise ValueError(
|
||||
f"Text encoder {path!r} cannot use AllGather without a model-declared streamable block plan"
|
||||
)
|
||||
if explicit and not (stacks or on_demand):
|
||||
raise ValueError(
|
||||
f"Selected text encoder {path!r} requires a model-declared streamable or on-demand plan"
|
||||
)
|
||||
encoders.append(
|
||||
ResolvedComponent(
|
||||
path=path,
|
||||
module=module,
|
||||
selected=selected,
|
||||
stacks=stacks,
|
||||
on_demand=on_demand,
|
||||
)
|
||||
)
|
||||
|
||||
for path, module in zip(modules.vae_names, modules.vaes):
|
||||
# VAEs are not part of the public selector. A model plan may still own
|
||||
# their residency, which the compatibility topology preserves.
|
||||
legacy_staged = (
|
||||
layerwise and not explicit and declaration is not None and path in declaration.on_demand_component_paths
|
||||
)
|
||||
if legacy_staged:
|
||||
validate_on_demand_component(module, path)
|
||||
vaes.append(ResolvedComponent(path=path, module=module, selected=False, on_demand=legacy_staged))
|
||||
|
||||
for path, module in zip(modules.resident_names, modules.resident_modules):
|
||||
residents.append(ResolvedComponent(path=path, module=module, selected=False))
|
||||
|
||||
resolved = ResolvedOffloadPlan(
|
||||
dits=tuple(dits),
|
||||
encoders=tuple(encoders),
|
||||
vaes=tuple(vaes),
|
||||
residents=tuple(residents),
|
||||
modules=modules,
|
||||
declaration=declaration,
|
||||
)
|
||||
_validate_unique_ownership(resolved)
|
||||
return resolved
|
||||
|
||||
|
||||
def _validate_unique_ownership(resolved: ResolvedOffloadPlan) -> None:
|
||||
"""Reject topologies where two components would hook the same blocks."""
|
||||
owner_by_block: dict[int, str] = {}
|
||||
for component in resolved.components:
|
||||
for block in (block for stack in component.stacks for block in stack.blocks):
|
||||
owner = owner_by_block.setdefault(id(block), component.path)
|
||||
if owner != component.path:
|
||||
raise ValueError(
|
||||
f"Offload block is claimed by both {owner!r} and {component.path!r}; "
|
||||
"declare one owner for each block list"
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"BlockStack",
|
||||
"ResolvedComponent",
|
||||
"ResolvedOffloadPlan",
|
||||
"resolve_offload_plan",
|
||||
]
|
||||
@@ -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
|
||||
|
||||
from collections.abc import Collection, Iterator
|
||||
from contextlib import contextmanager
|
||||
@@ -13,9 +13,8 @@ from vllm_omni.diffusion.hooks import HookRegistry, ModelHook
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .base import OffloadBackend, OffloadConfig, SupportsModelCpuOffload
|
||||
from .config import DIT_COMPONENT, TEXT_ENCODER_COMPONENT
|
||||
from .module_collector import ModuleDiscovery
|
||||
from .offload_plan import get_offload_plan
|
||||
from .config import DIT_COMPONENT
|
||||
from .plan_resolver import resolve_offload_plan
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -329,59 +328,44 @@ class ModelLevelOffloadBackend(OffloadBackend):
|
||||
)
|
||||
return
|
||||
|
||||
modules = ModuleDiscovery.discover(pipeline)
|
||||
plan = get_offload_plan(pipeline)
|
||||
selected_encoders = [
|
||||
encoder
|
||||
for encoder, name in zip(modules.encoders, modules.encoder_names)
|
||||
if self.config.should_offload_encoder(name, plan)
|
||||
]
|
||||
if self.config.components is not None:
|
||||
if not modules.dits:
|
||||
raise ValueError("Component-selective model offload requires a DiT/transformer module")
|
||||
if not modules.encoders:
|
||||
raise ValueError("Component-selective model offload requires an encoder execution stage")
|
||||
if self.config.offloads(TEXT_ENCODER_COMPONENT) and not selected_encoders:
|
||||
raise ValueError("No text encoder modules found for selected text_encoder module offload")
|
||||
resolved = resolve_offload_plan(pipeline, self.config)
|
||||
dits = [component.module for component in resolved.dits]
|
||||
encoders = [component.module for component in resolved.encoders]
|
||||
vaes = [component.module for component in resolved.vaes]
|
||||
residents = [component.module for component in resolved.residents]
|
||||
selected_encoders = [component.module for component in resolved.encoders if component.selected]
|
||||
|
||||
all_modules = [
|
||||
*modules.dits,
|
||||
*modules.encoders,
|
||||
*modules.vaes,
|
||||
*modules.resident_modules,
|
||||
]
|
||||
all_modules = [*dits, *encoders, *vaes, *residents]
|
||||
initial_devices = _capture_tensor_devices(all_modules)
|
||||
try:
|
||||
for encoder in modules.encoders:
|
||||
for encoder in encoders:
|
||||
encoder.to(self.device)
|
||||
for vae in modules.vaes:
|
||||
for vae in vaes:
|
||||
vae.to(self.device, non_blocking=True)
|
||||
for resident in modules.resident_modules:
|
||||
for resident in residents:
|
||||
resident.to(self.device)
|
||||
|
||||
if not modules.dits:
|
||||
if not dits:
|
||||
logger.warning("No DiT/transformer modules found, skipping model-level offloading")
|
||||
return
|
||||
if not modules.encoders:
|
||||
for dit in modules.dits:
|
||||
if not encoders:
|
||||
for dit in dits:
|
||||
dit.to(self.device)
|
||||
logger.warning("No encoder modules found, skipping model-level offloading")
|
||||
return
|
||||
|
||||
apply_sequential_offload(
|
||||
dit_modules=modules.dits,
|
||||
encoder_modules=modules.encoders,
|
||||
dit_modules=dits,
|
||||
encoder_modules=encoders,
|
||||
device=self.device,
|
||||
pin_memory=self.config.pin_cpu_memory,
|
||||
use_hsdp=self.config.use_hsdp,
|
||||
offload_dit_modules=(
|
||||
modules.dits if self.config.components is None or self.config.offloads(DIT_COMPONENT) else ()
|
||||
),
|
||||
offload_dit_modules=(dits if self.config.offloads(DIT_COMPONENT) else ()),
|
||||
offload_encoder_modules=selected_encoders,
|
||||
)
|
||||
except BaseException:
|
||||
try:
|
||||
remove_sequential_offload([*modules.dits, *modules.encoders])
|
||||
remove_sequential_offload([*dits, *encoders])
|
||||
except BaseException:
|
||||
logger.exception("Failed to remove every model-level hook during rollback")
|
||||
try:
|
||||
@@ -391,15 +375,19 @@ class ModelLevelOffloadBackend(OffloadBackend):
|
||||
raise
|
||||
|
||||
# Track modules for cleanup
|
||||
self._offload_modules = [*modules.dits, *modules.encoders]
|
||||
self._offload_modules = [*dits, *encoders]
|
||||
|
||||
self.enabled = True
|
||||
|
||||
logger.info(
|
||||
"Model-level offloading enabled: %s <-> %s (mutual exclusion)%s",
|
||||
", ".join(modules.dit_names),
|
||||
", ".join(modules.encoder_names),
|
||||
f"; resident on GPU: {', '.join(modules.resident_names)}" if modules.resident_names else "",
|
||||
", ".join(component.path for component in resolved.dits),
|
||||
", ".join(component.path for component in resolved.encoders),
|
||||
(
|
||||
f"; resident on GPU: {', '.join(component.path for component in resolved.residents)}"
|
||||
if resolved.residents
|
||||
else ""
|
||||
),
|
||||
)
|
||||
|
||||
def disable(self) -> None:
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Midway prompt updates for chunked diffusion step execution.
|
||||
|
||||
``PromptUpdateMixin`` exposes
|
||||
- a pipeline interface for the external to queue a prompt update,
|
||||
- a pipeline internal method to apply prompt transitions at chunk boundaries.
|
||||
|
||||
``prompt_update_versions``: a helper for ``InputBatch`` cache invalidation.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from threading import Lock
|
||||
from typing import ClassVar, TypedDict, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
DEFAULT_TRANSITION_CHUNKS = 3
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class PromptUpdateExtra(TypedDict, total=False):
|
||||
"""A "protocol" for ``StepRequestState.extra`` keys used by the prompt-update feature."""
|
||||
|
||||
pending_prompt_update: _PendingPromptUpdate
|
||||
prompt_update_state: _PromptUpdateState
|
||||
prompt_update_chunk_metadata: _PromptUpdateChunkMetadata
|
||||
prompt_update_version: int # Bumped when prompt_embeds change; invalidates InputBatch cache.
|
||||
|
||||
# The lock for storing/updating pending prompt updates.
|
||||
# Saved in state.extra to be naturally cleaned up with the request state.
|
||||
# As PromptUpdateMixin (the pipeline) currently lacks an obvious request-finish hook
|
||||
prompt_update_lock: Lock
|
||||
|
||||
|
||||
def prompt_update_versions(states: Sequence[StepRequestState]) -> tuple[int, ...]:
|
||||
"""Return per-request prompt-update versions for batch cache comparison.
|
||||
|
||||
To be used by ``InputBatch`` or other external to determine if the cached batch is still valid.
|
||||
"""
|
||||
return tuple(int(cast(PromptUpdateExtra, state.extra).get("prompt_update_version", 0)) for state in states)
|
||||
|
||||
|
||||
class PromptUpdateMixin:
|
||||
"""Mixin for chunked streaming pipelines that support midway prompt updates.
|
||||
|
||||
Implements the behavior expected by :class:`~vllm_omni.diffusion.models.interface.SupportsPromptUpdate`.
|
||||
All per-request transition state lives on ``StepRequestState.extra``; this mixin itself is stateless.
|
||||
"""
|
||||
|
||||
supports_prompt_update: ClassVar[bool] = True
|
||||
|
||||
@staticmethod
|
||||
def _prompt_update_lock(extra: PromptUpdateExtra) -> Lock:
|
||||
return extra.setdefault("prompt_update_lock", Lock())
|
||||
|
||||
def prepare_prompt_update(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
prompt: str,
|
||||
event_id: str,
|
||||
transition_chunks: int | None = None,
|
||||
) -> None:
|
||||
"""Encode and queue a prompt update to apply at the next chunk boundary.
|
||||
It does not actually apply the prompt transition.
|
||||
|
||||
This is an extended interface for the pipeline, to be called by the runner.
|
||||
"""
|
||||
if not prompt:
|
||||
raise ValueError("prompt must be non-empty")
|
||||
if not event_id:
|
||||
raise ValueError("event_id must be non-empty")
|
||||
if state.prompt_embeds is None:
|
||||
raise ValueError(
|
||||
f"prompt_update is not allowed before initial generation has started (request_id={state.request_id!r})"
|
||||
)
|
||||
duration = DEFAULT_TRANSITION_CHUNKS if transition_chunks is None else transition_chunks
|
||||
if duration < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
|
||||
target_prompt_embeds, _ = self.encode_prompt(
|
||||
prompt=prompt,
|
||||
negative_prompt=None,
|
||||
do_classifier_free_guidance=False,
|
||||
num_videos_per_prompt=state.sampling.num_outputs_per_prompt,
|
||||
max_sequence_length=state.sampling.max_sequence_length,
|
||||
device=self.device,
|
||||
dtype=self.transformer.dtype,
|
||||
)
|
||||
extra = cast(PromptUpdateExtra, state.extra)
|
||||
with self._prompt_update_lock(extra):
|
||||
extra["pending_prompt_update"] = {
|
||||
"event_id": event_id,
|
||||
"prompt": prompt,
|
||||
"target_prompt_embeds": target_prompt_embeds,
|
||||
"transition_chunks": duration,
|
||||
}
|
||||
|
||||
def _apply_prompt_update_at_chunk_boundary(self, state: StepRequestState) -> None:
|
||||
"""Advance or start prompt interpolation before the next chunk."""
|
||||
extra = cast(PromptUpdateExtra, state.extra)
|
||||
update_state: _PromptUpdateState | None = extra.get("prompt_update_state")
|
||||
with self._prompt_update_lock(extra):
|
||||
pending = extra.pop("pending_prompt_update", None)
|
||||
embeds_changed = False
|
||||
next_chunk_index = state.chunk_index
|
||||
started_event_ids: list[str] = []
|
||||
active_event_ids: list[str] = []
|
||||
completed_event_ids: list[str] = []
|
||||
|
||||
# If current transition is not complete, advance it.
|
||||
# After completion, leave prompt_update_state in place (so a later pending
|
||||
# update can abort/overwrite), but do not keep bumping the version.
|
||||
if update_state is not None:
|
||||
in_transition = (
|
||||
update_state.transition_chunks > 0
|
||||
and update_state.elapsed_transition_chunks < update_state.transition_chunks
|
||||
)
|
||||
if in_transition:
|
||||
update_state.advance_transition()
|
||||
state.prompt_embeds = update_state.blended_prompt_embeds()
|
||||
embeds_changed = True
|
||||
active_event_ids.append(update_state.event_id)
|
||||
if update_state.elapsed_transition_chunks >= update_state.transition_chunks:
|
||||
state.prompt_embeds = update_state.target_prompt_embeds
|
||||
update_state.source_prompt_embeds = update_state.target_prompt_embeds
|
||||
completed_event_ids.append(update_state.event_id)
|
||||
if update_state.target_prompt is not None:
|
||||
logger.debug(
|
||||
"prompt_update transition complete request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
update_state.target_prompt,
|
||||
)
|
||||
|
||||
# If a new prompt update is pending, start a new transition.
|
||||
if pending is not None:
|
||||
if state.prompt_embeds is None:
|
||||
raise RuntimeError(
|
||||
"internal error: trying to apply a pending prompt update but "
|
||||
f"current prompt_embeds is None (request_id={state.request_id!r})"
|
||||
)
|
||||
source = state.prompt_embeds.detach().clone()
|
||||
target = pending["target_prompt_embeds"]
|
||||
duration = int(pending["transition_chunks"])
|
||||
prompt = str(pending.get("prompt", ""))
|
||||
event_id = pending.get("event_id")
|
||||
update_state = _PromptUpdateState(
|
||||
source_prompt_embeds=source,
|
||||
target_prompt_embeds=target,
|
||||
transition_chunks=duration,
|
||||
event_id=event_id,
|
||||
target_prompt=prompt,
|
||||
)
|
||||
extra["prompt_update_state"] = update_state
|
||||
started_event_ids.append(event_id)
|
||||
active_event_ids.append(event_id)
|
||||
if duration <= 0:
|
||||
# A hard/immediate transition
|
||||
state.prompt_embeds = target
|
||||
completed_event_ids.append(event_id)
|
||||
logger.debug(
|
||||
"prompt_update sharp transition request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
prompt,
|
||||
)
|
||||
else:
|
||||
# A transition that really takes some time
|
||||
update_state.advance_transition()
|
||||
state.prompt_embeds = update_state.blended_prompt_embeds()
|
||||
if update_state.elapsed_transition_chunks >= update_state.transition_chunks:
|
||||
state.prompt_embeds = update_state.target_prompt_embeds
|
||||
update_state.source_prompt_embeds = update_state.target_prompt_embeds
|
||||
completed_event_ids.append(event_id)
|
||||
logger.debug(
|
||||
"prompt_update transition start request_id=%s next_chunk_index=%d prompt=%.20s...",
|
||||
state.request_id,
|
||||
next_chunk_index,
|
||||
prompt,
|
||||
)
|
||||
embeds_changed = True
|
||||
|
||||
# Indicate that prompt embeddings have changed---clear input batch cache.
|
||||
if embeds_changed:
|
||||
new_version = int(extra.get("prompt_update_version", 0)) + 1
|
||||
extra["prompt_update_version"] = new_version
|
||||
|
||||
extra["prompt_update_chunk_metadata"] = {
|
||||
"started_event_ids": started_event_ids,
|
||||
"active_event_ids": active_event_ids,
|
||||
"completed_event_ids": completed_event_ids,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PromptUpdateState:
|
||||
"""Per-request prompt interpolation stored in ``state.extra["prompt_update_state"]``."""
|
||||
|
||||
source_prompt_embeds: torch.Tensor
|
||||
target_prompt_embeds: torch.Tensor
|
||||
transition_chunks: int
|
||||
event_id: str
|
||||
elapsed_transition_chunks: int = 0
|
||||
target_prompt: str | None = None
|
||||
|
||||
def blended_prompt_embeds(self) -> torch.Tensor:
|
||||
alpha = self._current_alpha()
|
||||
if alpha >= 1.0:
|
||||
return self.target_prompt_embeds
|
||||
return (1.0 - alpha) * self.source_prompt_embeds + alpha * self.target_prompt_embeds
|
||||
|
||||
def advance_transition(self) -> None:
|
||||
if self.transition_chunks <= 0:
|
||||
self.source_prompt_embeds = self.target_prompt_embeds
|
||||
return
|
||||
self.elapsed_transition_chunks += 1
|
||||
if self.elapsed_transition_chunks >= self.transition_chunks:
|
||||
self.source_prompt_embeds = self.target_prompt_embeds
|
||||
self.elapsed_transition_chunks = self.transition_chunks
|
||||
|
||||
def _current_alpha(self) -> float:
|
||||
if self.transition_chunks <= 0:
|
||||
return 1.0
|
||||
return min(1.0, self.elapsed_transition_chunks / self.transition_chunks)
|
||||
|
||||
|
||||
class _PendingPromptUpdate(TypedDict):
|
||||
event_id: str
|
||||
prompt: str
|
||||
target_prompt_embeds: torch.Tensor
|
||||
transition_chunks: int
|
||||
|
||||
|
||||
class _PromptUpdateChunkMetadata(TypedDict):
|
||||
started_event_ids: list[str]
|
||||
active_event_ids: list[str]
|
||||
completed_event_ids: list[str]
|
||||
@@ -166,6 +166,11 @@ _DIFFUSION_MODELS = {
|
||||
"pipeline_boogu_image",
|
||||
"BooguImagePipeline",
|
||||
),
|
||||
"BooguImageTurboPipeline": (
|
||||
"boogu_image",
|
||||
"pipeline_boogu_image",
|
||||
"BooguImageTurboPipeline",
|
||||
),
|
||||
"LancePipeline": (
|
||||
"lance",
|
||||
"pipeline_lance",
|
||||
@@ -549,6 +554,7 @@ _DIFFUSION_POST_PROCESS_FUNCS = {
|
||||
"ZImagePipeline": "get_post_process_func",
|
||||
"OvisImagePipeline": "get_ovis_image_post_process_func",
|
||||
"BooguImagePipeline": "get_boogu_image_post_process_func",
|
||||
"BooguImageTurboPipeline": "get_boogu_image_post_process_func",
|
||||
"WanPipeline": "get_wan22_post_process_func",
|
||||
"WanDMDPipeline": "get_wan22_post_process_func",
|
||||
"WanVACEPipeline": "get_wan22_vace_post_process_func",
|
||||
@@ -620,6 +626,7 @@ _DIFFUSION_PRE_PROCESS_FUNCS = {
|
||||
"BagelPipeline": "get_bagel_pre_process_func",
|
||||
"GlmImagePipeline": "get_glm_image_pre_process_func",
|
||||
"BooguImagePipeline": "get_boogu_image_pre_process_func",
|
||||
"BooguImageTurboPipeline": "get_boogu_image_pre_process_func",
|
||||
"QwenImageEditPipeline": "get_qwen_image_edit_pre_process_func",
|
||||
"QwenImageEditPlusPipeline": "get_qwen_image_edit_plus_pre_process_func",
|
||||
"LongCatImageEditPipeline": "get_longcat_image_edit_pre_process_func",
|
||||
|
||||
@@ -119,6 +119,7 @@ class RequestBatchSamplingParamsKey:
|
||||
guidance_scale: float = 0.0
|
||||
guidance_scale_provided: bool = False
|
||||
guidance_scale_2: float | None = None
|
||||
guidance_scale_2_provided: bool = False
|
||||
guidance_rescale: float = 0.0
|
||||
true_cfg_scale: float | None = None
|
||||
cfg_normalize: bool = False
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Video/audio muxing utilities using PyAV (no ffmpeg binary dependency)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import queue
|
||||
import threading
|
||||
from collections.abc import Iterable
|
||||
from fractions import Fraction
|
||||
from typing import Any, cast
|
||||
@@ -12,6 +14,153 @@ from typing import Any, cast
|
||||
import av
|
||||
import numpy as np
|
||||
|
||||
_CHUNKED_MP4_DONE = object()
|
||||
|
||||
|
||||
def _validate_video_chunk(chunk: np.ndarray, *, width: int, height: int) -> None:
|
||||
"""Validate a ``(T, H, W, 3)`` uint8 RGB chunk against a session's frame size."""
|
||||
if chunk.ndim != 4 or chunk.shape[-1] != 3:
|
||||
raise ValueError("video chunk must have shape (T, H, W, 3)")
|
||||
if chunk.dtype != np.uint8:
|
||||
raise ValueError("video chunk must have dtype uint8")
|
||||
if chunk.shape[1] != height or chunk.shape[2] != width:
|
||||
raise ValueError("video chunks in a session must use a consistent frame size")
|
||||
|
||||
|
||||
class ChunkedMP4Encoder:
|
||||
"""Encode temporal video chunks while the producer is still decoding.
|
||||
|
||||
A bounded queue and one muxing worker provide ordered backpressure while
|
||||
keeping host memory bounded by ``max_pending`` chunks. Chunks use the same
|
||||
``(T, H, W, 3)`` uint8 contract as :func:`mux_video_audio_bytes`.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
fps: float,
|
||||
audio_waveform: np.ndarray | None = None,
|
||||
audio_sample_rate: int | None = None,
|
||||
max_pending: int = 2,
|
||||
video_codec: str = "h264",
|
||||
audio_codec: str = "aac",
|
||||
crf: str = "18",
|
||||
video_codec_options: dict[str, str] | None = None,
|
||||
) -> None:
|
||||
if max_pending <= 0:
|
||||
raise ValueError("max_pending must be positive")
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("width and height must be positive")
|
||||
self.width = int(width)
|
||||
self.height = int(height)
|
||||
self._queue: queue.Queue[object] = queue.Queue(maxsize=max_pending)
|
||||
self._result: bytes | None = None
|
||||
self._error: BaseException | None = None
|
||||
self._closed = False
|
||||
self._aborted = False
|
||||
self._input_done = False
|
||||
self._state_lock = threading.Lock()
|
||||
|
||||
def run() -> None:
|
||||
try:
|
||||
self._result = mux_av_video_audio_bytes(
|
||||
self._frames(),
|
||||
width=self.width,
|
||||
height=self.height,
|
||||
audio_waveform=audio_waveform,
|
||||
fps=fps,
|
||||
audio_sample_rate=audio_sample_rate,
|
||||
video_codec=video_codec,
|
||||
audio_codec=audio_codec,
|
||||
crf=crf,
|
||||
video_codec_options=video_codec_options,
|
||||
)
|
||||
except BaseException as exc:
|
||||
self._error = exc
|
||||
self._drain_until_done()
|
||||
|
||||
self._thread = threading.Thread(target=run, name="chunked-mp4", daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def _drain_until_done(self) -> None:
|
||||
# A flush/mux failure can occur after _frames consumed the sentinel.
|
||||
if not self._input_done:
|
||||
while self._queue.get() is not _CHUNKED_MP4_DONE:
|
||||
pass
|
||||
|
||||
def _frames(self):
|
||||
while True:
|
||||
chunk = self._queue.get()
|
||||
if chunk is _CHUNKED_MP4_DONE:
|
||||
self._input_done = True
|
||||
return
|
||||
assert isinstance(chunk, np.ndarray)
|
||||
for frame_data in chunk:
|
||||
yield av.VideoFrame.from_ndarray(frame_data, format="rgb24")
|
||||
|
||||
def _validate_chunk(self, chunk: np.ndarray) -> None:
|
||||
_validate_video_chunk(chunk, width=self.width, height=self.height)
|
||||
|
||||
def _raise_if_failed(self) -> None:
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
if self._closed:
|
||||
raise RuntimeError("ChunkedMP4Encoder is already closed")
|
||||
|
||||
def push(self, chunk: np.ndarray) -> None:
|
||||
"""Queue a chunk; asynchronous failures surface here or at finish()."""
|
||||
self._validate_chunk(chunk)
|
||||
self._raise_if_failed()
|
||||
self._queue.put(chunk)
|
||||
self._raise_if_failed()
|
||||
|
||||
def _send_done(self) -> None:
|
||||
self._queue.put(_CHUNKED_MP4_DONE)
|
||||
|
||||
def finish(self) -> bytes:
|
||||
"""Flush the muxer and return complete progressive MP4 bytes."""
|
||||
with self._state_lock:
|
||||
if not self._closed:
|
||||
self._closed = True
|
||||
self._send_done()
|
||||
self._thread.join()
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
if self._aborted:
|
||||
raise RuntimeError("ChunkedMP4Encoder was aborted")
|
||||
assert self._result is not None
|
||||
return self._result
|
||||
|
||||
def abort(self) -> None:
|
||||
"""Discard pending chunks and join the worker after cancellation.
|
||||
|
||||
Any chunk already being encoded must finish before the worker exits.
|
||||
"""
|
||||
with self._state_lock:
|
||||
if not self._closed:
|
||||
self._closed = True
|
||||
self._aborted = True
|
||||
while True:
|
||||
try:
|
||||
self._queue.get_nowait()
|
||||
except queue.Empty:
|
||||
break
|
||||
self._send_done()
|
||||
self._thread.join()
|
||||
|
||||
close = finish
|
||||
|
||||
def __enter__(self) -> ChunkedMP4Encoder:
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb) -> None:
|
||||
if exc_type is None:
|
||||
self.finish()
|
||||
else:
|
||||
self.abort()
|
||||
|
||||
|
||||
class FragmentedMP4Muxer:
|
||||
"""Incrementally mux video frames into one fragmented MP4 byte stream."""
|
||||
@@ -57,12 +206,7 @@ class FragmentedMP4Muxer:
|
||||
"""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.")
|
||||
_validate_video_chunk(video_frames, width=self._stream.width, height=self._stream.height)
|
||||
|
||||
for frame_data in video_frames:
|
||||
frame = av.VideoFrame.from_ndarray(frame_data, format="rgb24")
|
||||
|
||||
@@ -42,12 +42,13 @@ from vllm_omni.diffusion.diffusion_kv.paged_attention_adapter import (
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_classifier_free_guidance_rank
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context
|
||||
from vllm_omni.diffusion.interaction.coordinator import InteractionCoordinator
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.interface import (
|
||||
SupportsPromptUpdate,
|
||||
SupportsInteractionApply,
|
||||
adopt_request_scoped_cache_dit,
|
||||
is_request_scoped_cache_dit_enabled,
|
||||
supports_prompt_update,
|
||||
supports_interaction_apply,
|
||||
supports_step_execution,
|
||||
)
|
||||
from vllm_omni.diffusion.offloader import enable_offload_backend
|
||||
@@ -176,6 +177,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
self.offload_backend: Any | None = None
|
||||
self.prompt_embed_cache: Any | None = None
|
||||
self.input_batch: InputBatch | None = None
|
||||
self._interaction_coordinator: InteractionCoordinator | None = None
|
||||
self.model_memory_usage = 0
|
||||
self.diffusion_kv_backend = DiffusionKVModelRunnerBackend(
|
||||
vllm_config=vllm_config,
|
||||
@@ -427,6 +429,10 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
model_tag=self.od_config.model_class_name,
|
||||
)
|
||||
|
||||
self._interaction_coordinator = InteractionCoordinator.build(self.pipeline, self.od_config)
|
||||
if hasattr(self.pipeline, "_interaction_coordinator"):
|
||||
self.pipeline._interaction_coordinator = self._interaction_coordinator
|
||||
|
||||
logger.info("Model runner: Initialization complete.")
|
||||
|
||||
def get_kv_cache_spec(self) -> dict[str, KVCacheSpec]:
|
||||
@@ -789,7 +795,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
|
||||
return self._runner_output_from_outputs(reqs, outputs)
|
||||
|
||||
def _attach_stepwise_metrics(
|
||||
def _attach_stepwise_metadata(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
output: DiffusionOutput,
|
||||
@@ -800,6 +806,14 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
)
|
||||
attach_stage_durations(state, output)
|
||||
|
||||
# In streaming output mode with interaction, acknowledge which events are handled in this chunk.
|
||||
meta = state.interaction_chunk_metadata
|
||||
state.interaction_chunk_metadata = None
|
||||
if meta is not None:
|
||||
output.started_event_ids = list(meta.started_event_ids)
|
||||
output.active_event_ids = list(meta.active_event_ids)
|
||||
output.completed_event_ids = list(meta.completed_event_ids)
|
||||
|
||||
def execute_model(
|
||||
self,
|
||||
req: OmniDiffusionRequest,
|
||||
@@ -1275,10 +1289,16 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
clear_pipeline_stage_durations(self.pipeline)
|
||||
result = self.pipeline.post_decode(req)
|
||||
if result is not None:
|
||||
self._attach_stepwise_metrics(
|
||||
self._attach_stepwise_metadata(
|
||||
req,
|
||||
result,
|
||||
)
|
||||
# After consuming this chunk's interaction metadata, apply pending interactions and
|
||||
# prepare the next chunk (prepare_next_chunk may be a no-op---depending on pipeline)
|
||||
if supports_interaction_apply(self.pipeline) and not req.request_denoise_completed:
|
||||
pipe = cast(SupportsInteractionApply, self.pipeline)
|
||||
pipe.apply_interaction_at_chunk_boundary(req)
|
||||
pipe.prepare_next_chunk(req)
|
||||
else:
|
||||
result = None
|
||||
# finished should be computed after post_decode() advanced chunk_index
|
||||
@@ -1354,42 +1374,48 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Route a midway interaction to the matching active stepwise request feature."""
|
||||
"""Route a midway interaction through the pipeline interaction coordinator."""
|
||||
assert self.pipeline is not None, "Model not loaded. Call load_model() first."
|
||||
if not self.od_config.streaming_output:
|
||||
raise ValueError("submit_interaction requires streaming_output=True")
|
||||
if not self._supports_step_mode():
|
||||
raise ValueError("submit_interaction requires step execution support")
|
||||
|
||||
coordinator = self._interaction_coordinator
|
||||
if coordinator is None:
|
||||
coordinator = InteractionCoordinator.build(self.pipeline, self.od_config)
|
||||
self._interaction_coordinator = coordinator
|
||||
if hasattr(self.pipeline, "_interaction_coordinator"):
|
||||
self.pipeline._interaction_coordinator = coordinator
|
||||
|
||||
event = interaction.get("event")
|
||||
if isinstance(event, dict) and "prompt" in event and "multi_modal_data" not in event:
|
||||
# Is a prompt update interaction.
|
||||
self._submit_prompt_update_interaction(request_id, interaction)
|
||||
return
|
||||
has_mm = isinstance(event, dict) and "multi_modal_data" in event
|
||||
has_prompt = isinstance(event, dict) and "prompt" in event and event.get("prompt") is not None
|
||||
|
||||
raise NotImplementedError(
|
||||
"Only text-only prompt update interactions with 'event.prompt' and optional "
|
||||
"'transition_chunks' are supported in this release"
|
||||
)
|
||||
|
||||
def _submit_prompt_update_interaction(
|
||||
self,
|
||||
request_id: str,
|
||||
interaction: OmniInteractionPrompt,
|
||||
) -> None:
|
||||
"""Queue a prompt-update interaction for an active stepwise request."""
|
||||
if not supports_prompt_update(self.pipeline):
|
||||
# Prompt-only interactions in this release; multi_modal_data lands with camera support.
|
||||
if not isinstance(event, dict) or has_mm or not has_prompt:
|
||||
raise NotImplementedError(
|
||||
"Only text-only prompt update interactions with 'event.prompt' and optional "
|
||||
"'transition_chunks' are supported in this release"
|
||||
)
|
||||
if not coordinator.has_modality("prompt"):
|
||||
raise ValueError(f"prompt_update is not supported by pipeline {self.od_config.model_class_name!r}")
|
||||
|
||||
state = self.state_cache.get(request_id)
|
||||
if state is None:
|
||||
raise ValueError(f"No active request state for prompt_update: {request_id!r}")
|
||||
raise ValueError(f"No active request state for interaction: {request_id!r}")
|
||||
|
||||
event = cast(dict[str, Any], interaction.get("event"))
|
||||
prompt = event["prompt"]
|
||||
transition_chunks = interaction.get("transition_chunks")
|
||||
event_id = interaction.get("event_id")
|
||||
if not isinstance(event_id, str) or not event_id:
|
||||
raise ValueError("event_id must be non-empty")
|
||||
pipeline = cast(SupportsPromptUpdate, self.pipeline)
|
||||
pipeline.prepare_prompt_update(state, prompt, event_id, transition_chunks)
|
||||
prompt = event["prompt"]
|
||||
if not isinstance(prompt, str) or not prompt:
|
||||
raise ValueError("prompt must be non-empty")
|
||||
coordinator.enqueue(
|
||||
state,
|
||||
modality="prompt",
|
||||
event_id=event_id,
|
||||
received_at=time.monotonic(),
|
||||
payload={"prompt": prompt},
|
||||
transition_chunks=interaction.get("transition_chunks"),
|
||||
)
|
||||
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.prompt_update import prompt_update_versions
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.prompt import prompt_update_versions
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
"""Per-request mutable state for step-wise diffusion execution."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +12,10 @@ import torch
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionSession,
|
||||
)
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType
|
||||
|
||||
|
||||
@@ -100,6 +104,10 @@ class StepRequestState:
|
||||
total_chunks: int = 1
|
||||
chunk_num_steps: int | None = None
|
||||
|
||||
# ── Optional interaction information in streaming output mode ──
|
||||
interaction_sessions: dict[str, InteractionSession] = field(default_factory=dict) # Modality -> transition progress
|
||||
interaction_chunk_metadata: InteractionChunkMetadata | None = None # Acknowledging completion of each interaction
|
||||
|
||||
# ── Per-request scheduler instance (set once by prepare_encode) ──
|
||||
scheduler: Any | None = None
|
||||
|
||||
|
||||
Reference in new issue
Block a user