Merge remote-tracking branch 'origin/main' into qwen-image-2.1
# Conflicts: # vllm_omni/diffusion/executor/multiproc_executor.py # vllm_omni/diffusion/offloader/sequential_backend.py
This commit is contained in:
commit
9174554e40
1332 files changed
+160051
-60504
No files matched your search
@@ -215,8 +215,9 @@ class AttentionMetadata:
|
||||
# variable-length query/key sequences for FlashAttention.
|
||||
# "max_seqlen_q" / "max_seqlen_k": maximum sequence lengths paired with
|
||||
# the packed cu_seqlens tensors.
|
||||
# "valid_kv_length": int — contiguous valid K/V prefix length for a
|
||||
# backend that advertises supports_prefix_kv_slicing.
|
||||
# "valid_kv_length": int — contiguous valid K/V prefix length. Local
|
||||
# backends may slice it directly; ring backends trim each circulated
|
||||
# K/V block from the same global prefix.
|
||||
# "npu_attn_varlen": bool — model opt-in for the NPU packed varlen path
|
||||
# (TND npu_fusion_attention driven by cu_seqlens, mask never read).
|
||||
# Requires the [real, pad] two-document packing contract; see
|
||||
|
||||
@@ -6,7 +6,6 @@ from __future__ import annotations
|
||||
import functools
|
||||
import importlib.util
|
||||
import math
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
@@ -88,77 +87,6 @@ if not hasattr(torch.ops.vllm_omni, "fastvideo_vsa_bshd"):
|
||||
_fastvideo_vsa_bshd_op = torch.ops.vllm_omni.fastvideo_vsa_bshd
|
||||
|
||||
|
||||
# H3 needs an explicit per-query block map: prefix queries are dense, while
|
||||
# video queries select prefix + top-k video tiles. The generic
|
||||
# video_sparse_attn() entry point cannot express that contract.
|
||||
if not hasattr(torch.ops.vllm_omni, "fastvideo_h3_vsa_bhsd"):
|
||||
|
||||
@torch.library.custom_op("vllm_omni::fastvideo_h3_vsa_bhsd", mutates_args=())
|
||||
def _fastvideo_h3_vsa_bhsd_op(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
block_map: torch.Tensor,
|
||||
variable_block_sizes: torch.Tensor,
|
||||
logical_blocks: int,
|
||||
) -> torch.Tensor:
|
||||
q = query.transpose(1, 2).contiguous()
|
||||
k = key.transpose(1, 2).contiguous()
|
||||
v = value.transpose(1, 2).contiguous()
|
||||
|
||||
# Official FastVideo's measured FastH3 route opts into this native
|
||||
# Blackwell forward. Wheels without the extension (including SM103
|
||||
# builds today) retain the corrected explicit-mask Triton route.
|
||||
if os.environ.get("FASTVIDEO_VSA_SM100A", "0") == "1":
|
||||
try:
|
||||
from fastvideo_kernel import block_sparse_attn_sm100a
|
||||
from fastvideo_kernel.triton_kernels.index import map_to_index
|
||||
|
||||
if block_sparse_attn_sm100a.is_supported(q, variable_block_sizes):
|
||||
q2k_idx, q2k_num = map_to_index(block_map)
|
||||
out, _ = block_sparse_attn_sm100a.block_sparse_attn_sm100a(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
q2k_idx.to(torch.int32).contiguous(),
|
||||
q2k_num.to(torch.int32).contiguous(),
|
||||
variable_block_sizes.to(torch.int32).contiguous(),
|
||||
need_lse=False,
|
||||
)
|
||||
return out.transpose(1, 2).contiguous()
|
||||
except (ImportError, RuntimeError) as exc:
|
||||
# Opting in explicitly and then silently getting a different
|
||||
# numeric path is worse than the slower route it lands on.
|
||||
logger.warning_once(
|
||||
"FASTVIDEO_VSA_SM100A=1 requested but the native Blackwell forward is "
|
||||
"unavailable (%s); using the Triton block-sparse route instead.",
|
||||
exc,
|
||||
)
|
||||
|
||||
from fastvideo_kernel.block_sparse_attn import block_sparse_attn
|
||||
|
||||
logical_len = logical_blocks * 64
|
||||
out, _ = block_sparse_attn(
|
||||
q[:, :, :logical_len].contiguous(),
|
||||
k[:, :, :logical_len].contiguous(),
|
||||
v[:, :, :logical_len].contiguous(),
|
||||
block_map[..., :logical_blocks, :logical_blocks].contiguous(),
|
||||
variable_block_sizes[:logical_blocks].to(torch.int32).contiguous(),
|
||||
)
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
if out.shape[1] != query.shape[1]:
|
||||
out = torch.nn.functional.pad(out, (0, 0, 0, 0, 0, query.shape[1] - out.shape[1]))
|
||||
return out
|
||||
|
||||
@_fastvideo_h3_vsa_bhsd_op.register_fake
|
||||
def _(query, key, value, block_map, variable_block_sizes, logical_blocks):
|
||||
del key, value, block_map, variable_block_sizes, logical_blocks
|
||||
return torch.empty_like(query)
|
||||
|
||||
|
||||
_fastvideo_h3_vsa_bhsd_op = torch.ops.vllm_omni.fastvideo_h3_vsa_bhsd
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=32)
|
||||
def _get_tile_partition_indices(
|
||||
dit_seq_shape: tuple[int, int, int],
|
||||
@@ -226,81 +154,6 @@ def _get_tile_metadata(
|
||||
return tile_partition_indices, variable_block_sizes, non_pad_index, untile_combined_index
|
||||
|
||||
|
||||
@functools.lru_cache(maxsize=32)
|
||||
def _get_h3_tile_metadata(
|
||||
prefix_segments: tuple[int, ...],
|
||||
video_shape: tuple[int, int, int],
|
||||
device: torch.device,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int, int]:
|
||||
"""Official FastVideo H3 geometry: pure prefix chunks + 3-D video tiles."""
|
||||
block_size = (4, 4, 4)
|
||||
block_elements = 64
|
||||
prefix_len = sum(prefix_segments)
|
||||
prefix_sizes: list[int] = []
|
||||
for segment in prefix_segments:
|
||||
full, remainder = divmod(segment, block_elements)
|
||||
prefix_sizes.extend([block_elements] * full)
|
||||
if remainder:
|
||||
prefix_sizes.append(remainder)
|
||||
|
||||
video_indices = _get_tile_partition_indices(video_shape, block_size, device) + prefix_len
|
||||
video_sizes = _construct_variable_block_sizes(video_shape, block_size, device)
|
||||
partition = torch.cat([torch.arange(prefix_len, device=device, dtype=torch.long), video_indices])
|
||||
sizes = torch.cat([torch.tensor(prefix_sizes, device=device, dtype=torch.int32), video_sizes.to(torch.int32)])
|
||||
non_pad = _get_non_pad_index(sizes, block_elements)
|
||||
untile = non_pad[torch.argsort(partition)]
|
||||
total = prefix_len + math.prod(video_shape)
|
||||
if int(sizes.sum()) != total or untile.numel() != total:
|
||||
raise ValueError(
|
||||
f"invalid H3 VSA geometry: prefix={prefix_segments}, video={video_shape}, "
|
||||
f"sizes_sum={int(sizes.sum())}, total={total}"
|
||||
)
|
||||
return partition, sizes, non_pad, untile, len(prefix_sizes), int(video_sizes.numel())
|
||||
|
||||
|
||||
def _get_h3_layout(
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> tuple[tuple[int, ...], tuple[int, int, int], int] | None:
|
||||
if attn_metadata is None or attn_metadata.video_layout is None:
|
||||
return None
|
||||
prefix = attn_metadata.extra.get("vsa_h3_prefix_segments")
|
||||
if not isinstance(prefix, (tuple, list)):
|
||||
return None
|
||||
target = next(
|
||||
(span for span in reversed(attn_metadata.video_layout.video_spans) if span.role == "target"),
|
||||
None,
|
||||
)
|
||||
if target is None:
|
||||
return None
|
||||
return tuple(int(x) for x in prefix if int(x) > 0), target.latent_grid, target.start
|
||||
|
||||
|
||||
def _pool_h3_tiles(x: torch.Tensor, sizes: torch.Tensor) -> torch.Tensor:
|
||||
batch, seq_len, heads, dim = x.shape
|
||||
blocks = seq_len // 64
|
||||
pooled = x.view(batch, blocks, 64, heads, dim).sum(dim=2, dtype=torch.float32)
|
||||
pooled = pooled / sizes.view(1, -1, 1, 1).clamp_min(1)
|
||||
return pooled.permute(0, 2, 1, 3)
|
||||
|
||||
|
||||
def _build_h3_block_map(
|
||||
scores: torch.Tensor,
|
||||
num_prefix_blocks: int,
|
||||
num_video_blocks: int,
|
||||
topk: int,
|
||||
) -> torch.Tensor:
|
||||
"""Prefix K/V are exempt and prefix queries stay dense, as in FastVideo."""
|
||||
keep_video = min(topk, num_video_blocks)
|
||||
if keep_video == num_video_blocks:
|
||||
return torch.ones_like(scores, dtype=torch.bool)
|
||||
block_map = torch.zeros_like(scores, dtype=torch.bool)
|
||||
indices = scores[..., num_prefix_blocks:].topk(keep_video, dim=-1).indices + num_prefix_blocks
|
||||
block_map.scatter_(-1, indices, True)
|
||||
block_map[..., :num_prefix_blocks] = True
|
||||
block_map[:, :, :num_prefix_blocks, :] = True
|
||||
return block_map
|
||||
|
||||
|
||||
def _get_vsa_dit_seq_shape(attn_metadata: AttentionMetadata | None) -> tuple[int, int, int] | None:
|
||||
if attn_metadata is None:
|
||||
return None
|
||||
@@ -343,7 +196,9 @@ class FastVideoVSABackend(AttentionBackend):
|
||||
if importlib.util.find_spec("fastvideo_kernel") is None:
|
||||
raise ImportError(
|
||||
"FASTVIDEO_VSA requires the optional fastvideo-kernel package "
|
||||
"(the installation must provide the 'fastvideo_kernel' Python module)."
|
||||
"included in vllm-omni[vsa]. Install with `uv pip install 'vllm-omni[vsa]'` "
|
||||
"(from source: `uv pip install -e '.[vsa]'`). "
|
||||
"Prebuilt kernels require Linux, Python 3.12 and glibc >= 2.34."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -504,93 +359,6 @@ class FastVideoVSAImpl(AttentionImpl):
|
||||
return "sequence parallel context is active"
|
||||
return None
|
||||
|
||||
def _forward_h3(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata,
|
||||
) -> torch.Tensor:
|
||||
layout = _get_h3_layout(attn_metadata)
|
||||
if layout is None:
|
||||
raise ValueError("incomplete VSA-H3 layout metadata")
|
||||
prefix_segments, video_shape, target_start = layout
|
||||
if sum(prefix_segments) != target_start:
|
||||
raise ValueError(f"VSA-H3 prefix segments sum to {sum(prefix_segments)}, target starts at {target_start}")
|
||||
expected = target_start + math.prod(video_shape)
|
||||
if query.shape[1] != expected:
|
||||
raise ValueError(f"VSA-H3 layout has {expected} rows but attention received {query.shape[1]}")
|
||||
if query.dtype not in (torch.float16, torch.bfloat16):
|
||||
raise ValueError(f"VSA-H3 requires fp16/bf16 tensors, got {query.dtype}")
|
||||
gate = _get_gate_compress(attn_metadata)
|
||||
if gate is not None:
|
||||
# H3 pads the packed document to 64 rows, while VSA operates on
|
||||
# the valid prefix. Validate/slice before launching attention so a
|
||||
# metadata error can never trigger an unsafe dense fallback after
|
||||
# an asynchronous custom kernel.
|
||||
if gate.shape[0] != query.shape[0] or gate.shape[2:] != query.shape[2:] or gate.shape[1] < query.shape[1]:
|
||||
raise ValueError(f"gate_compress shape {gate.shape} cannot cover query shape {query.shape}")
|
||||
gate = gate[:, : query.shape[1]]
|
||||
|
||||
partition, sizes, non_pad, untile, prefix_blocks, video_blocks = _get_h3_tile_metadata(
|
||||
prefix_segments, video_shape, query.device
|
||||
)
|
||||
logical_blocks = int(sizes.numel())
|
||||
# The native sm100a kernel assigns pairs of query blocks to CTAs. Its
|
||||
# contract requires an even block count; the synthetic partner is
|
||||
# transport-only and is removed before returning.
|
||||
pair_pad = logical_blocks % 2
|
||||
kernel_blocks = logical_blocks + pair_pad
|
||||
target_shape = (query.shape[0], kernel_blocks * 64, query.shape[2], query.shape[3])
|
||||
q_tiled = torch.zeros(target_shape, device=query.device, dtype=query.dtype)
|
||||
k_tiled = torch.zeros_like(q_tiled)
|
||||
v_tiled = torch.zeros_like(q_tiled)
|
||||
q_tiled[:, non_pad] = query[:, partition]
|
||||
k_tiled[:, non_pad] = key[:, partition]
|
||||
v_tiled[:, non_pad] = value[:, partition]
|
||||
|
||||
q_pool = _pool_h3_tiles(q_tiled[:, : logical_blocks * 64], sizes)
|
||||
k_pool = _pool_h3_tiles(k_tiled[:, : logical_blocks * 64], sizes)
|
||||
scores = torch.matmul(q_pool, k_pool.transpose(-2, -1)) * self.softmax_scale
|
||||
block_map = _build_h3_block_map(scores, prefix_blocks, video_blocks, self.topk)
|
||||
kernel_sizes = sizes
|
||||
if pair_pad:
|
||||
block_map = torch.nn.functional.pad(block_map, (0, 1, 0, 1), value=False)
|
||||
kernel_sizes = torch.nn.functional.pad(sizes, (0, 1), value=0)
|
||||
|
||||
logger.info_once(
|
||||
"FASTVIDEO_VSA H3 routing: seq_len=%d, prefix_segments=%s, video_shape=%s, "
|
||||
"prefix_blocks=%d, video_blocks=%d, topk=%d, kernel_blocks=%d",
|
||||
query.shape[1],
|
||||
prefix_segments,
|
||||
video_shape,
|
||||
prefix_blocks,
|
||||
video_blocks,
|
||||
min(self.topk, video_blocks),
|
||||
kernel_blocks,
|
||||
)
|
||||
output = _fastvideo_h3_vsa_bhsd_op(
|
||||
q_tiled.contiguous(),
|
||||
k_tiled.contiguous(),
|
||||
v_tiled.contiguous(),
|
||||
block_map.contiguous(),
|
||||
kernel_sizes.contiguous(),
|
||||
logical_blocks,
|
||||
)[:, : logical_blocks * 64]
|
||||
|
||||
if gate is not None:
|
||||
gate_tiled = torch.zeros_like(q_tiled[:, : logical_blocks * 64])
|
||||
gate_tiled[:, non_pad] = gate[:, partition]
|
||||
v_pool = _pool_h3_tiles(v_tiled[:, : logical_blocks * 64], sizes)
|
||||
compressed = torch.matmul(torch.softmax(scores, dim=-1), v_pool)
|
||||
compressed = compressed.permute(0, 2, 1, 3).to(output.dtype)
|
||||
output = (
|
||||
output.view(output.shape[0], logical_blocks, 64, output.shape[2], output.shape[3])
|
||||
+ compressed.unsqueeze(2)
|
||||
* gate_tiled.view(gate_tiled.shape[0], logical_blocks, 64, gate_tiled.shape[2], gate_tiled.shape[3])
|
||||
).view_as(output)
|
||||
return output[:, untile].contiguous()
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
@@ -611,26 +379,6 @@ class FastVideoVSAImpl(AttentionImpl):
|
||||
key = key[:, :valid_seq_len]
|
||||
value = value[:, :valid_seq_len]
|
||||
|
||||
if attn_metadata is not None and _get_h3_layout(attn_metadata) is not None:
|
||||
try:
|
||||
output = self._forward_h3(query, key, value, attn_metadata)
|
||||
if valid_seq_len == original_seq_len:
|
||||
return output
|
||||
restored = torch.zeros_like(original_query)
|
||||
restored[:, :valid_seq_len] = output
|
||||
return restored
|
||||
except Exception as exc:
|
||||
# A CUDA fault poisons the process context; attempting SDPA
|
||||
# afterwards obscures the original kernel failure and cannot
|
||||
# recover the request.
|
||||
if isinstance(exc, torch.AcceleratorError):
|
||||
raise
|
||||
if not self.fallback_on_error:
|
||||
raise
|
||||
return self._fallback(
|
||||
original_query, original_key, original_value, attn_metadata, f"VSA-H3 kernel failed: {exc}"
|
||||
)
|
||||
|
||||
reason = self._fallback_reason(query, key, value, attn_metadata)
|
||||
if reason is not None:
|
||||
return self._fallback(original_query, original_key, original_value, attn_metadata, reason)
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import os
|
||||
from functools import partial
|
||||
from collections.abc import Callable
|
||||
from functools import cache, partial
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
@@ -19,6 +20,15 @@ from vllm_omni.platforms import current_omni_platform
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@cache
|
||||
def _get_npu_compressed_causal_mask(device: torch.device) -> torch.Tensor:
|
||||
"""Return the shared block mask used by NPU right-down causal attention."""
|
||||
return torch.triu(
|
||||
torch.ones((2048, 2048), dtype=torch.bool, device=device),
|
||||
diagonal=1,
|
||||
).contiguous()
|
||||
|
||||
|
||||
class FlashAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
supports_piecewise_spans: bool = True
|
||||
@@ -66,18 +76,18 @@ class FlashAttentionBackend(AttentionBackend):
|
||||
|
||||
|
||||
class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
# Per-platform FP8 KV quantization support.
|
||||
# To enable FP8 on a new platform, add its OmniPlatformEnum value here
|
||||
# Per-platform attention quantization support.
|
||||
# To enable a method on a new platform, add its OmniPlatformEnum value here
|
||||
# and handle kv_cache_dtype in the corresponding forward_{platform}().
|
||||
#
|
||||
# TODO(quant-backend): The FP8 quant path currently lives inside
|
||||
# TODO(quant-backend): The quantized path currently lives inside
|
||||
# FlashAttentionImpl gated by ``attn_metadata.extra["kv_cache_dtype"]``.
|
||||
# Eventually extract it into a dedicated FlashAttentionQuantBackend so
|
||||
# backend selection (not metadata) decides quant. Until then, model
|
||||
# authors can opt a specific Attention layer out via
|
||||
# backend selection decides quant.
|
||||
# Until then, model authors can opt a specific Attention layer out via
|
||||
# ``Attention(disable_kv_quant=True)``.
|
||||
_supported_kv_cache_dtypes = {
|
||||
"npu": {"fp8"},
|
||||
"npu": {"fp8", "mxfp8", "mxfp4"},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
@@ -301,11 +311,17 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
if native_impl is None:
|
||||
raise RuntimeError(f"Native attention implementation is not bound for diffusion layer {layer.layer_name!r}")
|
||||
prewrite_kv = current_omni_platform.requires_diffusion_paged_kv_prewrite()
|
||||
read_kv_from_cache = prewrite_kv and layer.attn_backend.forward_includes_kv_cache_update
|
||||
forward_updates_cache = layer.attn_backend.forward_includes_kv_cache_update
|
||||
# Match vLLM's split update/attention contract. Once K/V has been
|
||||
# written by do_kv_cache_update(), decoder attention consumes the
|
||||
# paged cache and does not need segment-local K/V tensors. In
|
||||
# particular, this avoids packing the same K/V projection view once
|
||||
# for every piecewise segment.
|
||||
read_kv_from_cache = not forward_updates_cache or prewrite_kv
|
||||
# The GPU/default path preserves native cache-update ownership. Ascend
|
||||
# prewrites through vLLM-Ascend's normal-layout writer so piecewise FIA
|
||||
# segments do not repeatedly scatter the same layer K/V.
|
||||
if not layer.attn_backend.forward_includes_kv_cache_update or prewrite_kv:
|
||||
if not forward_updates_cache or prewrite_kv:
|
||||
cache_update = getattr(native_impl, "do_kv_cache_update", None)
|
||||
if not callable(cache_update):
|
||||
raise RuntimeError(
|
||||
@@ -343,14 +359,11 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
)
|
||||
|
||||
if paged_kv_context.piecewise_plan is not None:
|
||||
# Ascend FIA can execute identical CFG rows as one batched call
|
||||
# per piece. Keep that batch layout through the piecewise runner
|
||||
# so it can concatenate row-major results instead of emitting an
|
||||
# indexed ScatterUpdate for every segment. The CUDA path keeps
|
||||
# its existing output-buffer contract (including graph capture).
|
||||
use_homogeneous_batch = (
|
||||
current_omni_platform.is_npu() and paged_kv_context.piecewise_plan.homogeneous_batch_shape is not None
|
||||
)
|
||||
# Identical CFG rows can execute as one batched call per piece.
|
||||
# Keep that batch layout through the piecewise runner so Q/K/V use
|
||||
# strided slices instead of indexed gathers and results can be
|
||||
# concatenated in row-major order.
|
||||
use_homogeneous_batch = paged_kv_context.piecewise_plan.homogeneous_batch_shape is not None
|
||||
output = None
|
||||
if not use_homogeneous_batch:
|
||||
output = torch.empty(
|
||||
@@ -517,11 +530,47 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
) -> torch.Tensor:
|
||||
"""NPU attention implementation using mindiesd."""
|
||||
|
||||
kv_cache_dtype = attn_metadata.extra.get("kv_cache_dtype") if attn_metadata else None
|
||||
if kv_cache_dtype is not None:
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
method = extra.get("kv_cache_dtype")
|
||||
if method not in (None, "float", "auto"):
|
||||
return self.forward_fa_quant_npu(query, key, value, attn_metadata)
|
||||
return self.forward_fa_npu(query, key, value, attn_metadata)
|
||||
|
||||
@staticmethod
|
||||
def _load_quant_runtime(method: str) -> Callable[..., torch.Tensor]:
|
||||
if method not in ("fp8", "mxfp8", "mxfp4"):
|
||||
raise ValueError(f"Unsupported NPU attention quantization method {method!r}.")
|
||||
from mindiesd import quant_attention
|
||||
|
||||
return quant_attention
|
||||
|
||||
def _validate_quant_request(
|
||||
self,
|
||||
method: str,
|
||||
query: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> None:
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
reason = None
|
||||
if self.causal:
|
||||
reason = "causal quantized FA is not supported"
|
||||
elif any(name in extra for name in ("cu_seqlens_q", "cu_seqlens_k")) or extra.get("npu_attn_varlen"):
|
||||
reason = "packed/varlen metadata requires the float attention path"
|
||||
elif attn_metadata is not None and attn_metadata.full_attn_spans is not None:
|
||||
reason = "piecewise attention requires the float attention path"
|
||||
elif attn_metadata is not None and attn_metadata.attn_mask is not None:
|
||||
reason = "caller masks require the float attention path"
|
||||
elif method in ("fp8", "mxfp8", "mxfp4") and (
|
||||
query.ndim != 4 or query.shape[-1] <= 0 or query.shape[-1] & (query.shape[-1] - 1)
|
||||
):
|
||||
reason = "generated Hadamard rotations require a four-dimensional input and power-of-two head size"
|
||||
if reason is not None:
|
||||
raise ValueError(
|
||||
f"NPU attention precision {method!r} is unavailable: {reason}. "
|
||||
"Set diffusion_kv_cache_dtype to a supported method, or set it to "
|
||||
"'auto'. Automatic precision fallback is not performed."
|
||||
)
|
||||
|
||||
def forward_fa_quant_npu(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
@@ -529,18 +578,29 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
from vllm_omni.platforms.npu.quant.kv_quant_npu import fp8_rotate_quant_fa
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
method = extra.get("kv_cache_dtype", "fp8")
|
||||
layout = self.qkv_layout or "BSND"
|
||||
self._validate_quant_request(method, query, attn_metadata)
|
||||
try:
|
||||
runtime = self._load_quant_runtime(method)
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
f"NPU attention precision {method!r} requires a compatible MindIE-SD "
|
||||
"quant Runtime. Install a compatible MindIE-SD build, select another "
|
||||
"diffusion_kv_cache_dtype, or set it to 'auto'. Automatic precision "
|
||||
"fallback is not performed."
|
||||
) from exc
|
||||
kwargs = dict(precision=method, layout=layout, scale=self.softmax_scale)
|
||||
# Apply Omni's deterministic Q/K rotation before every Dense quantized path.
|
||||
if method in ("fp8", "mxfp8", "mxfp4"):
|
||||
from vllm_omni.platforms.npu.quant.kv_quant_npu import get_quant_attention_rotation
|
||||
|
||||
layout = self.qkv_layout or "BNSD"
|
||||
# Models pass (B, S, H, D); NPU fused op expects (B, N, S, D).
|
||||
out = fp8_rotate_quant_fa(
|
||||
query.transpose(1, 2),
|
||||
key.transpose(1, 2),
|
||||
value.transpose(1, 2),
|
||||
layout=layout,
|
||||
softmax_scale=self.softmax_scale,
|
||||
)
|
||||
return out.transpose(1, 2)
|
||||
rotation = get_quant_attention_rotation(query.device, query.dtype, query.shape[-1])
|
||||
kwargs.update(q_rot=rotation, k_rot=rotation)
|
||||
logger.info_once("NPU attention uses MindIE-SD %s Runtime, layout=%s.", method, layout)
|
||||
# Execution errors propagate. Never retry with another precision.
|
||||
return runtime(query, key, value, **kwargs)
|
||||
|
||||
def forward_fa_npu(
|
||||
self,
|
||||
@@ -549,6 +609,53 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
attention_mask = attn_metadata.attn_mask if attn_metadata else None
|
||||
if self.causal:
|
||||
import torch_npu
|
||||
|
||||
if attention_mask is None:
|
||||
# The compressed upper-triangular mask with sparse_mode=3
|
||||
# applies FlashAttention's bottom-right causal alignment when
|
||||
# Sq != Skv without materializing the full attention matrix.
|
||||
npu_attention_mask = _get_npu_compressed_causal_mask(query.device)
|
||||
sparse_mode = 3
|
||||
# Explicitly enable invalid-row handling for Sq > Skv. Equal
|
||||
# and shorter query sequences have no fully causal-masked rows.
|
||||
inner_precise = 2 if query.shape[1] > key.shape[1] else 0
|
||||
else:
|
||||
# A custom keep-mask cannot be combined with the compressed
|
||||
# sparse_mode=3 mask. Materialize the composed block-mask and
|
||||
# use allMask mode instead. The explicit mask follows the
|
||||
# framework convention (True=keep), while npu_fusion_attention
|
||||
# uses True=block.
|
||||
explicit_keep_mask = _maybe_reshape_attn_mask(
|
||||
query,
|
||||
key,
|
||||
attention_mask,
|
||||
mask_mode="full_qk",
|
||||
).to(device=query.device, dtype=torch.bool)
|
||||
query_positions = torch.arange(query.shape[1], device=query.device).unsqueeze(1)
|
||||
key_positions = torch.arange(key.shape[1], device=query.device).unsqueeze(0)
|
||||
causal_block_mask = key_positions > query_positions + (key.shape[1] - query.shape[1])
|
||||
npu_attention_mask = (causal_block_mask | ~explicit_keep_mask).contiguous()
|
||||
sparse_mode = 1
|
||||
# An explicit mask can create fully masked rows regardless of
|
||||
# the Sq/Skv relationship.
|
||||
inner_precise = 2
|
||||
|
||||
return torch_npu.npu_fusion_attention(
|
||||
query.contiguous(),
|
||||
key.contiguous(),
|
||||
value.contiguous(),
|
||||
head_num=query.shape[2],
|
||||
input_layout="BSND",
|
||||
atten_mask=npu_attention_mask,
|
||||
scale=float(self.softmax_scale),
|
||||
keep_prob=1.0,
|
||||
inner_precise=inner_precise,
|
||||
sparse_mode=sparse_mode,
|
||||
)[0]
|
||||
|
||||
from mindiesd import attention_forward
|
||||
|
||||
# Opt-in mask-free paths (mirror the CUDA cu_seqlens behavior): the
|
||||
@@ -567,7 +674,6 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
|
||||
out = self._forward_varlen_packed_npu(query, key, value, extra)
|
||||
if out is not None:
|
||||
return out
|
||||
attention_mask = attn_metadata.attn_mask if attn_metadata else None
|
||||
if attention_mask is None and extra.get("npu_attn_varlen", False):
|
||||
# Models skip mask construction when this opt-in is set
|
||||
# (FlashAttentionBackend.supports_packed_mask_free). The packed
|
||||
|
||||
@@ -135,6 +135,11 @@ class RainFusionPlan:
|
||||
class RainFusionAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
supported_platforms: tuple[str, ...] = ("npu",)
|
||||
# The impl trims [real, pad] packed tensors to the valid prefix with
|
||||
# [:, :used] itself, so models may run the padded layout without
|
||||
# materializing a padding mask (a forward that carries one anyway falls
|
||||
# back dense in _resolve_plan).
|
||||
supports_prefix_kv_slicing: bool = True
|
||||
|
||||
@classmethod
|
||||
def validate_available(cls) -> None:
|
||||
@@ -146,8 +151,10 @@ class RainFusionAttentionBackend(AttentionBackend):
|
||||
from mindiesd import sparse_attention
|
||||
except ImportError as exc:
|
||||
raise ValueError(_MISSING_MINDIESD) from exc
|
||||
if not _supports_video_spans(sparse_attention):
|
||||
raise ValueError(_INCOMPATIBLE_MINDIESD)
|
||||
if not callable(sparse_attention):
|
||||
raise ValueError(_MISSING_MINDIESD)
|
||||
# Single-video Wan only needs the legacy geometry. Check video_spans
|
||||
# when a forward actually carries multiple videos.
|
||||
|
||||
@staticmethod
|
||||
def get_supported_head_sizes() -> list[int]:
|
||||
@@ -174,6 +181,8 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
irregular video tail internally, retaining it outside the sparse blocks.
|
||||
"""
|
||||
|
||||
_supported_kv_cache_dtypes = {"npu": {"fp8", "mxfp4"}}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
@@ -222,6 +231,8 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
def _validate_parallel_config(self) -> None:
|
||||
config = get_current_diffusion_config_or_none()
|
||||
parallel_config = getattr(config, "parallel_config", None)
|
||||
if getattr(parallel_config, "allgather_degree", 1) > 1:
|
||||
raise ValueError("RAINFUSION_ATTN requires full Q/K/V sequences; AllGather-KV SP is unsupported.")
|
||||
ring_degree = getattr(parallel_config, "ring_degree", 1)
|
||||
if ring_degree > 1:
|
||||
# Ring gives each rank a slice of the sequence, so block selection
|
||||
@@ -262,7 +273,9 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
plan = self._resolve_plan(attn_metadata)
|
||||
if plan is None:
|
||||
return self.dense_fallback.forward_npu(query, key, value, attn_metadata)
|
||||
return self._forward_sparse_npu(query, key, value, plan)
|
||||
if query.ndim != 4 or key.shape != query.shape or value.shape != query.shape or plan.used_len > query.shape[1]:
|
||||
raise ValueError("RainFusion video geometry must fit identical full-sequence BSND Q/K/V tensors.")
|
||||
return self._forward_sparse_npu(query, key, value, plan, attn_metadata)
|
||||
|
||||
def _resolve_plan(self, attn_metadata: AttentionMetadata | None) -> RainFusionPlan | None:
|
||||
"""Return the rf_v2 geometry, or None when this forward must stay dense."""
|
||||
@@ -271,18 +284,17 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
return None
|
||||
if self.layer_idx is not None and self.layer_idx in rf.skip_layers:
|
||||
return None
|
||||
step_idx = total_steps = None
|
||||
if is_forward_context_available():
|
||||
step_idx = get_forward_context().denoise_step_idx
|
||||
total_steps = get_forward_context().total_denoise_steps
|
||||
if step_idx is not None and step_idx < rf.start_step:
|
||||
if (rf.start_step and step_idx is None) or (rf.end_step and (step_idx is None or total_steps is None)):
|
||||
return None
|
||||
if step_idx is not None:
|
||||
if step_idx < rf.start_step:
|
||||
return None
|
||||
# Tail fallback: keep the last ``end_step`` denoise steps dense.
|
||||
if (
|
||||
rf.end_step > 0
|
||||
and step_idx is not None
|
||||
and total_steps is not None
|
||||
and step_idx >= total_steps - rf.end_step
|
||||
):
|
||||
if rf.end_step > 0 and total_steps is not None and step_idx >= total_steps - rf.end_step:
|
||||
return None
|
||||
if self.qkv_layout is None:
|
||||
# The sparse path reads the sequence off dim 1, which the tensors alone
|
||||
@@ -308,7 +320,16 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
"model must publish AttentionMetadata.video_layout for the sequence to be sparsified."
|
||||
)
|
||||
return None
|
||||
max_seqlen_q = attn_metadata.extra.get("max_seqlen_q")
|
||||
|
||||
# The sparse Runtime constructs its own block mask. It cannot preserve
|
||||
# an arbitrary caller-supplied mask or piecewise visibility constraints.
|
||||
mask = attn_metadata.attn_mask
|
||||
padding_only = layout.used_len is not None
|
||||
if attn_metadata.full_attn_spans is not None or (
|
||||
mask is not None and not (padding_only and mask.ndim == 2 and mask.dtype == torch.bool)
|
||||
):
|
||||
return None
|
||||
max_seqlen_q = attn_metadata.extra.get("max_seqlen_q", layout.used_len)
|
||||
if max_seqlen_q is None:
|
||||
logger.warning_once(
|
||||
"RAINFUSION_ATTN staying dense: attention metadata is missing max_seqlen_q, so the "
|
||||
@@ -459,31 +480,56 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
plan: RainFusionPlan,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
try:
|
||||
from mindiesd import sparse_attention
|
||||
except ImportError:
|
||||
raise ImportError(_MISSING_MINDIESD)
|
||||
if self.rainfusion.precision != "bf16" and not _mindiesd_supports_precision():
|
||||
raise RuntimeError(
|
||||
f"block_sparse.precision={self.rainfusion.precision!r} requires MindIE-SD "
|
||||
"with sparse_attention(precision=...) support; the installed mindiesd "
|
||||
"silently ignores it and would run the BF16 path. Install a compatible "
|
||||
"MindIE-SD release or use precision='bf16'."
|
||||
if plan.video_spans is not None and not _supports_video_spans(sparse_attention):
|
||||
raise ValueError(_INCOMPATIBLE_MINDIESD)
|
||||
extra = attn_metadata.extra if attn_metadata else {}
|
||||
requested = extra.get("kv_cache_dtype", self.rainfusion.precision)
|
||||
reason = None
|
||||
if requested in ("float", "bf16"):
|
||||
precision = "bf16"
|
||||
else:
|
||||
precision = requested
|
||||
if requested not in ("fp8", "mxfp4", "mix"):
|
||||
reason = f"sparse {requested} is not supported"
|
||||
elif not _mindiesd_supports_precision():
|
||||
reason = "MindIE-SD sparse_attention must explicitly support precision"
|
||||
elif plan.video_spans is not None:
|
||||
reason = "quantized multi-video RainFusion is not supported"
|
||||
elif requested in ("fp8", "mxfp4") and query.shape[0] != 1:
|
||||
reason = "quantized Wan BSA requires batch size 1"
|
||||
elif requested in ("fp8", "mxfp4") and (query.shape[-1] < 64 or query.shape[-1] & (query.shape[-1] - 1)):
|
||||
reason = "BSA Hadamard rotations require a power-of-two head dimension of at least 64"
|
||||
if reason is not None:
|
||||
raise ValueError(
|
||||
f"RainFusion precision {requested!r} is unavailable: {reason}. "
|
||||
"Set diffusion_kv_cache_dtype or block_sparse.precision to a method supported by the installed "
|
||||
"MindIE-SD, or disable attention quantization. Automatic precision fallback is not performed."
|
||||
)
|
||||
|
||||
logger.info_once("RainFusion uses MindIE-SD sparse attention, precision=%s.", precision)
|
||||
used = plan.used_len
|
||||
q, k, v = (tensor[:, :used] for tensor in (query, key, value))
|
||||
# Split query once: the valid prefix drives the kernel, the padding
|
||||
# tail is reused verbatim as the output padding below. All views,
|
||||
# zero-copy. split_with_sizes always yields both parts, including an
|
||||
# empty tail when the sequence needs no padding.
|
||||
q, q_pad = torch.split(query, [used, query.shape[1] - used], dim=1)
|
||||
k, v = key[:, :used], value[:, :used]
|
||||
# Ulysses has already gathered the full sequence onto this rank and split
|
||||
# the heads, so read the head count off the tensor rather than num_heads.
|
||||
common_kwargs: dict[str, object] = {
|
||||
"scale": self.softmax_scale,
|
||||
"head_num": query.shape[-2],
|
||||
"input_layout": _INPUT_LAYOUT,
|
||||
"inner_precise": _INNER_PRECISE,
|
||||
"inner_precise": 4 if precision != "bf16" else _INNER_PRECISE,
|
||||
"block_size": _BLOCK_SIZE,
|
||||
"sparsity": self.rainfusion.sparsity,
|
||||
"precision": self.rainfusion.precision,
|
||||
"precision": precision,
|
||||
}
|
||||
if plan.video_spans is not None:
|
||||
out = sparse_attention(
|
||||
@@ -497,7 +543,9 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
else:
|
||||
assert plan.prefix_len is not None and plan.latent_shape is not None
|
||||
common_kwargs.update(
|
||||
sparse_type="rf_v2",
|
||||
# rf_v2 ignores precision on non-A5 devices. Select the explicit
|
||||
# quantized high-level path so mask/rearrangement remain in MindIE.
|
||||
sparse_type="rf_v3" if precision != "bf16" else "rf_v2",
|
||||
txt_len=plan.prefix_len,
|
||||
latent_shape_q=plan.latent_shape,
|
||||
latent_shape_k=plan.latent_shape,
|
||||
@@ -505,6 +553,9 @@ class RainFusionAttentionImpl(AttentionImpl):
|
||||
out = sparse_attention(q, k, v, **common_kwargs)
|
||||
if used == query.shape[1]:
|
||||
return out
|
||||
padded = torch.zeros_like(query)
|
||||
padded[:, :used] = out
|
||||
return padded
|
||||
# Only the first ``used`` rows are read back downstream, so the padding
|
||||
# payload is free. Reuse the query tail split off above instead of
|
||||
# zeroing a fresh buffer: a single cat write, no extra allocation, and
|
||||
# always finite values (uninitialized memory could hold NaN bit
|
||||
# patterns).
|
||||
return torch.cat([out, q_pad], dim=1)
|
||||
@@ -1,4 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
# Copyright (c) 2024, Jiarui Fang.
|
||||
# Adapted from https://github.com/feifeibear/long-context-attention
|
||||
|
||||
@@ -9,7 +10,33 @@ import torch.nn.functional as F
|
||||
|
||||
LseLayout = Literal["bhs", "bsh"]
|
||||
|
||||
__all__ = ["update_out_and_lse", "flatten_varlen_lse", "unflatten_varlen_lse"]
|
||||
__all__ = [
|
||||
"ring_kv_block_valid_length",
|
||||
"update_out_and_lse",
|
||||
"flatten_varlen_lse",
|
||||
"unflatten_varlen_lse",
|
||||
]
|
||||
|
||||
|
||||
def ring_kv_block_valid_length(
|
||||
valid_kv_length: int | None,
|
||||
block_size: int,
|
||||
block_rank: int,
|
||||
world_size: int,
|
||||
) -> int:
|
||||
"""Return the valid prefix length in one globally ordered ring K/V block."""
|
||||
if valid_kv_length is None:
|
||||
return block_size
|
||||
if isinstance(valid_kv_length, bool) or not isinstance(valid_kv_length, int):
|
||||
raise ValueError("valid_kv_length must be a Python integer")
|
||||
total_length = block_size * world_size
|
||||
if not 0 < valid_kv_length <= total_length:
|
||||
raise ValueError(
|
||||
"valid_kv_length must be within the global ring K/V sequence, "
|
||||
f"got {valid_kv_length} for length {total_length}"
|
||||
)
|
||||
block_start = block_rank * block_size
|
||||
return max(0, min(block_size, valid_kv_length - block_start))
|
||||
|
||||
|
||||
def _normalize_lse(block_lse: torch.Tensor, block_out: torch.Tensor, lse_layout: LseLayout) -> torch.Tensor:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
# Copyright (c) 2024, Jiarui Fang.
|
||||
# Adapted from https://github.com/feifeibear/long-context-attention
|
||||
|
||||
@@ -6,7 +7,10 @@
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_selector import AttnType, select_flash_attn_impl
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_utils import update_out_and_lse
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_utils import (
|
||||
ring_kv_block_valid_length,
|
||||
update_out_and_lse,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.comm import RingComm
|
||||
|
||||
|
||||
@@ -27,6 +31,7 @@ def ring_flash_attn_forward(
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
valid_kv_length: int | None = None,
|
||||
):
|
||||
# Validate causal + joint_strategy combination
|
||||
# When causal=True and joint_strategy="rear", the causal mask would incorrectly
|
||||
@@ -42,6 +47,21 @@ def ring_flash_attn_forward(
|
||||
"from seeing the joint tokens."
|
||||
)
|
||||
|
||||
# Trimming the circulated K/V blocks changes their length while the query
|
||||
# block keeps the full padded length. Flash-Attention aligns a causal mask
|
||||
# to the bottom-right of a rectangular (seqlen_q, seqlen_k) tile, so a
|
||||
# trimmed block would shift the diagonal and let queries attend to the
|
||||
# wrong key positions -- silently, with no shape error. The two are
|
||||
# therefore an unsupported combination rather than a slow path: the caller
|
||||
# must either drop the padding before the ring or run non-causal.
|
||||
if causal and valid_kv_length is not None:
|
||||
raise ValueError(
|
||||
"valid_kv_length is not supported with causal=True in Ring Attention. "
|
||||
"Trimming a circulated K/V block shortens seqlen_k while seqlen_q keeps "
|
||||
"the padded length, and the causal diagonal is bottom-right aligned, so "
|
||||
"the mask would silently shift. Unpad before the ring, or use causal=False."
|
||||
)
|
||||
|
||||
comm = RingComm(process_group)
|
||||
|
||||
out = None
|
||||
@@ -66,8 +86,15 @@ def ring_flash_attn_forward(
|
||||
comm.commit()
|
||||
|
||||
if not causal or step <= comm.rank:
|
||||
step_k = k
|
||||
step_v = v
|
||||
block_rank = (comm.rank - step) % comm.world_size
|
||||
block_valid_length = ring_kv_block_valid_length(
|
||||
valid_kv_length,
|
||||
k.shape[1],
|
||||
block_rank,
|
||||
comm.world_size,
|
||||
)
|
||||
step_k = k[:, :block_valid_length]
|
||||
step_v = v[:, :block_valid_length]
|
||||
if step == 0 and joint_tensor_key is not None:
|
||||
if joint_strategy == "front":
|
||||
step_k = torch.cat([joint_tensor_key, step_k], dim=1)
|
||||
@@ -76,27 +103,28 @@ def ring_flash_attn_forward(
|
||||
step_k = torch.cat([step_k, joint_tensor_key], dim=1)
|
||||
step_v = torch.cat([step_v, joint_tensor_value], dim=1)
|
||||
|
||||
fn = select_flash_attn_impl(attn_type, stage="fwd-only", attn_processor=attn_processor)
|
||||
block_out, block_lse = fn(
|
||||
q,
|
||||
step_k,
|
||||
step_v,
|
||||
dropout_p=dropout_p,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal and step == 0,
|
||||
window_size=window_size,
|
||||
softcap=softcap,
|
||||
alibi_slopes=alibi_slopes,
|
||||
return_softmax=True and dropout_p > 0,
|
||||
)
|
||||
if step_k.shape[1] > 0:
|
||||
fn = select_flash_attn_impl(attn_type, stage="fwd-only", attn_processor=attn_processor)
|
||||
block_out, block_lse = fn(
|
||||
q,
|
||||
step_k,
|
||||
step_v,
|
||||
dropout_p=dropout_p,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=causal and step == 0,
|
||||
window_size=window_size,
|
||||
softcap=softcap,
|
||||
alibi_slopes=alibi_slopes,
|
||||
return_softmax=True and dropout_p > 0,
|
||||
)
|
||||
|
||||
# Ensure block_out is contiguous if needed, though usually it is from FA
|
||||
# Ensure block_out is contiguous if needed, though usually it is from FA
|
||||
|
||||
if attn_type == AttnType.SPARSE_SAGE:
|
||||
out, lse = block_out, block_lse
|
||||
else:
|
||||
# Ring kernel wrappers canonicalize LSE to (B, H, S).
|
||||
out, lse = update_out_and_lse(out, lse, block_out, block_lse, lse_layout="bhs")
|
||||
if attn_type == AttnType.SPARSE_SAGE:
|
||||
out, lse = block_out, block_lse
|
||||
else:
|
||||
# Ring kernel wrappers canonicalize LSE to (B, H, S).
|
||||
out, lse = update_out_and_lse(out, lse, block_out, block_lse, lse_layout="bhs")
|
||||
|
||||
if step + 1 != comm.world_size:
|
||||
comm.wait()
|
||||
@@ -132,6 +160,7 @@ class RingFlashAttnFunc(torch.autograd.Function):
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
valid_kv_length: int | None = None,
|
||||
):
|
||||
if softmax_scale is None:
|
||||
softmax_scale = q.shape[-1] ** (-0.5)
|
||||
@@ -158,6 +187,7 @@ class RingFlashAttnFunc(torch.autograd.Function):
|
||||
joint_tensor_key=joint_tensor_key,
|
||||
joint_tensor_value=joint_tensor_value,
|
||||
joint_strategy=joint_strategy,
|
||||
valid_kv_length=valid_kv_length,
|
||||
)
|
||||
return out if not return_softmax else (out, softmax_lse, None)
|
||||
|
||||
@@ -193,6 +223,7 @@ def ring_flash_attn_qkvpacked_func(
|
||||
None, # joint_tensor_key
|
||||
None, # joint_tensor_value
|
||||
"front", # joint_strategy
|
||||
None, # valid_kv_length
|
||||
)
|
||||
|
||||
|
||||
@@ -228,6 +259,7 @@ def ring_flash_attn_kvpacked_func(
|
||||
None, # joint_tensor_key
|
||||
None, # joint_tensor_value
|
||||
"front", # joint_strategy
|
||||
None, # valid_kv_length
|
||||
)
|
||||
|
||||
|
||||
@@ -249,6 +281,7 @@ def ring_flash_attn_func(
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
valid_kv_length: int | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor, None]:
|
||||
"""Ring Attention forward pass using Flash Attention backend.
|
||||
|
||||
@@ -290,6 +323,8 @@ def ring_flash_attn_func(
|
||||
Defaults to None.
|
||||
joint_strategy (str): Concatenation strategy ("front" or "back").
|
||||
Defaults to "front".
|
||||
valid_kv_length (int | None): Length of the contiguous valid prefix in
|
||||
the global ring K/V sequence. Defaults to the full sequence.
|
||||
|
||||
Returns:
|
||||
Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor, None]]:
|
||||
@@ -314,4 +349,5 @@ def ring_flash_attn_func(
|
||||
joint_tensor_key,
|
||||
joint_tensor_value,
|
||||
joint_strategy,
|
||||
valid_kv_length,
|
||||
)
|
||||
@@ -1,4 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
# Copyright (c) 2024, Jiarui Fang.
|
||||
# Adapted from https://github.com/feifeibear/long-context-attention
|
||||
|
||||
@@ -10,7 +11,10 @@ import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_kernels import pytorch_attn_forward
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_utils import update_out_and_lse
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_utils import (
|
||||
ring_kv_block_valid_length,
|
||||
update_out_and_lse,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.comm import RingComm
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -33,6 +37,7 @@ def ring_pytorch_attn_func(
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
valid_kv_length: int | None = None,
|
||||
):
|
||||
return RingAttentionFunc.apply(
|
||||
group,
|
||||
@@ -45,6 +50,7 @@ def ring_pytorch_attn_func(
|
||||
joint_tensor_key,
|
||||
joint_tensor_value,
|
||||
joint_strategy,
|
||||
valid_kv_length,
|
||||
)
|
||||
|
||||
|
||||
@@ -64,6 +70,7 @@ class RingAttentionFunc(torch.autograd.Function):
|
||||
joint_tensor_key=None,
|
||||
joint_tensor_value=None,
|
||||
joint_strategy="front",
|
||||
valid_kv_length: int | None = None,
|
||||
):
|
||||
# Validate causal + joint_strategy combination
|
||||
# When causal=True and joint_strategy="rear", the causal mask would incorrectly
|
||||
@@ -79,6 +86,22 @@ class RingAttentionFunc(torch.autograd.Function):
|
||||
"from seeing the joint tokens."
|
||||
)
|
||||
|
||||
# Trimming the circulated K/V blocks changes their length while the
|
||||
# query block keeps the full padded length. A causal SDPA mask over a
|
||||
# rectangular (seqlen_q, seqlen_k) tile is aligned to the bottom right,
|
||||
# so a trimmed block would shift the diagonal and let queries attend to
|
||||
# the wrong key positions -- silently, with no shape error. The two are
|
||||
# therefore an unsupported combination rather than a slow path: the
|
||||
# caller must either drop the padding before the ring or run
|
||||
# non-causal.
|
||||
if is_causal and valid_kv_length is not None:
|
||||
raise ValueError(
|
||||
"valid_kv_length is not supported with causal=True in Ring Attention. "
|
||||
"Trimming a circulated K/V block shortens seqlen_k while seqlen_q keeps "
|
||||
"the padded length, and the causal diagonal is bottom-right aligned, so "
|
||||
"the mask would silently shift. Unpad before the ring, or use causal=False."
|
||||
)
|
||||
|
||||
comm = RingComm(group)
|
||||
# Ensure tensors are contiguous for P2P communication
|
||||
q = q.contiguous()
|
||||
@@ -98,8 +121,15 @@ class RingAttentionFunc(torch.autograd.Function):
|
||||
comm.commit()
|
||||
|
||||
if not is_causal or step <= comm.rank:
|
||||
step_k = k
|
||||
step_v = v
|
||||
block_rank = (comm.rank - step) % comm.world_size
|
||||
block_valid_length = ring_kv_block_valid_length(
|
||||
valid_kv_length,
|
||||
k.shape[1],
|
||||
block_rank,
|
||||
comm.world_size,
|
||||
)
|
||||
step_k = k[:, :block_valid_length]
|
||||
step_v = v[:, :block_valid_length]
|
||||
if step == 0 and joint_tensor_key is not None:
|
||||
if joint_strategy == "front":
|
||||
step_k = torch.cat([joint_tensor_key, step_k], dim=1)
|
||||
@@ -108,15 +138,16 @@ class RingAttentionFunc(torch.autograd.Function):
|
||||
step_k = torch.cat([step_k, joint_tensor_key], dim=1)
|
||||
step_v = torch.cat([step_v, joint_tensor_value], dim=1)
|
||||
|
||||
block_out, block_lse = pytorch_attn_forward(
|
||||
q,
|
||||
step_k,
|
||||
step_v,
|
||||
softmax_scale=sm_scale,
|
||||
causal=is_causal and step == 0,
|
||||
op_type=op_type,
|
||||
)
|
||||
out, lse = update_out_and_lse(out, lse, block_out, block_lse, lse_layout="bhs")
|
||||
if step_k.shape[1] > 0:
|
||||
block_out, block_lse = pytorch_attn_forward(
|
||||
q,
|
||||
step_k,
|
||||
step_v,
|
||||
softmax_scale=sm_scale,
|
||||
causal=is_causal and step == 0,
|
||||
op_type=op_type,
|
||||
)
|
||||
out, lse = update_out_and_lse(out, lse, block_out, block_lse, lse_layout="bhs")
|
||||
|
||||
if step + 1 != comm.world_size:
|
||||
comm.wait()
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
# https://github.com/feifeibear/long-context-attention/blob/main/yunchang/attention/layer.py
|
||||
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import replace
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
@@ -16,7 +18,7 @@ from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.utils import extract_layer_index
|
||||
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheSpec
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionBackend, AttentionImpl, AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend
|
||||
from vllm_omni.diffusion.attention.parallel import build_parallel_attention_strategy
|
||||
from vllm_omni.diffusion.attention.parallel.base import NoParallelAttention
|
||||
@@ -81,6 +83,12 @@ class Attention(nn.Module):
|
||||
# varlen attention with learned sink logits). The shared Attention
|
||||
# layer still owns parallel dispatch and compile boundaries.
|
||||
custom_attention: nn.Module | None = None,
|
||||
# Preserve dense FP32 inference for models opting into CUDA auto fallback.
|
||||
allow_fp32_fallback: bool = False,
|
||||
# Model-owned implementation subclasses, keyed by backend name.
|
||||
# Keep the platform-selected backend and its capabilities unchanged.
|
||||
# Each override must preserve the selected implementation's contract.
|
||||
impl_overrides: Mapping[str, type[AttentionImpl]] | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -179,8 +187,18 @@ class Attention(nn.Module):
|
||||
self.backend_pref = attn_backend_cls.get_name()
|
||||
logger.debug("Attention(role=%s) → platform default (%s)", role, self.backend_pref)
|
||||
|
||||
self.attn_backend = attn_backend_cls
|
||||
self.attn_backend: type[AttentionBackend] | None = attn_backend_cls
|
||||
self.attn_impl_cls = self.attn_backend.get_impl_cls()
|
||||
if impl_overrides is not None:
|
||||
override = impl_overrides.get(attn_backend_cls.get_name())
|
||||
if override is not None:
|
||||
if not issubclass(override, self.attn_impl_cls):
|
||||
raise TypeError(
|
||||
f"Attention implementation override {override.__qualname__} must subclass "
|
||||
f"the selected implementation {self.attn_impl_cls.__qualname__} "
|
||||
f"for backend {attn_backend_cls.__qualname__}"
|
||||
)
|
||||
self.attn_impl_cls = override
|
||||
self.attention = self.attn_impl_cls(
|
||||
num_heads=num_heads,
|
||||
head_size=head_size,
|
||||
@@ -193,9 +211,9 @@ class Attention(nn.Module):
|
||||
role=role,
|
||||
backend_explicit=self.backend_explicit,
|
||||
)
|
||||
# Some model-specific paths call this helper directly. The main backend
|
||||
# dispatch below never switches to it implicitly.
|
||||
self.sdpa_fallback = SDPABackend.get_impl_cls()(
|
||||
# Compatibility kernels run inside shared dispatch, between the
|
||||
# parallel strategy's input preparation and output restoration.
|
||||
self.sdpa_fallback: AttentionImpl | None = SDPABackend.get_impl_cls()(
|
||||
num_heads=num_heads,
|
||||
head_size=head_size,
|
||||
softmax_scale=softmax_scale,
|
||||
@@ -221,6 +239,7 @@ class Attention(nn.Module):
|
||||
self.use_sync = use_sync
|
||||
self.causal = causal
|
||||
self.skip_sequence_parallel = skip_sequence_parallel
|
||||
self.allow_fp32_fallback = allow_fp32_fallback
|
||||
|
||||
self.use_ring = False
|
||||
self.ring_pg = None
|
||||
@@ -296,12 +315,13 @@ class Attention(nn.Module):
|
||||
def _init_kv_cache_quantization(self, config) -> None:
|
||||
if config is None or self._has_custom_attention:
|
||||
return
|
||||
assert self.attn_backend is not None
|
||||
dtype = getattr(config, "diffusion_kv_cache_dtype", None)
|
||||
if dtype == "auto":
|
||||
dtype = None
|
||||
parallel_config = getattr(config, "parallel_config", None)
|
||||
ring_degree = getattr(parallel_config, "ring_degree", 1)
|
||||
if dtype:
|
||||
if dtype and dtype != "float":
|
||||
if ring_degree > 1:
|
||||
raise ValueError(
|
||||
"KV quantization is not compatible with ring attention "
|
||||
@@ -318,13 +338,15 @@ class Attention(nn.Module):
|
||||
self._kv_cache_dtype = dtype
|
||||
self._kv_cache_skip_steps = getattr(config, "diffusion_kv_cache_skip_step_indices", None)
|
||||
self._kv_cache_skip_layers = getattr(config, "diffusion_kv_cache_skip_layer_indices", None)
|
||||
if self._kv_cache_skip_layers and self.layer_idx is None and not self._disable_kv_quant:
|
||||
raise ValueError("Attention quantization skip_layers requires a parseable transformer block index.")
|
||||
|
||||
def _should_apply_kv_cache_quant(self) -> bool:
|
||||
skip_steps = self._kv_cache_skip_steps
|
||||
skip_layers = self._kv_cache_skip_layers
|
||||
if skip_steps is not None:
|
||||
step_idx = get_forward_context().denoise_step_idx if is_forward_context_available() else None
|
||||
if step_idx is not None and step_idx in skip_steps:
|
||||
if skip_steps and (step_idx is None or step_idx in skip_steps):
|
||||
return False
|
||||
if skip_layers is not None:
|
||||
if self.layer_idx is not None and self.layer_idx in skip_layers:
|
||||
@@ -332,18 +354,21 @@ class Attention(nn.Module):
|
||||
return True
|
||||
|
||||
def _with_kv_cache_dtype(self, attn_metadata: AttentionMetadata | None) -> AttentionMetadata | None:
|
||||
kv_cache_dtype = self._kv_cache_dtype
|
||||
if kv_cache_dtype is None or self._disable_kv_quant or not self._should_apply_kv_cache_quant():
|
||||
if attn_metadata is None or "kv_cache_dtype" not in attn_metadata.extra:
|
||||
return attn_metadata
|
||||
extra = dict(attn_metadata.extra)
|
||||
extra.pop("kv_cache_dtype", None)
|
||||
return replace(attn_metadata, extra=extra)
|
||||
|
||||
disabled = self._disable_kv_quant or not self._should_apply_kv_cache_quant()
|
||||
dtype = self._kv_cache_dtype
|
||||
if dtype in (None, "float"):
|
||||
dtype = None
|
||||
elif disabled:
|
||||
dtype = "float"
|
||||
if dtype is None and (attn_metadata is None or "kv_cache_dtype" not in attn_metadata.extra):
|
||||
return attn_metadata
|
||||
extra = dict(attn_metadata.extra) if attn_metadata is not None else {}
|
||||
# Recompute per forward so shared metadata cannot retain another step's policy.
|
||||
extra.pop("kv_cache_dtype", None)
|
||||
if dtype is not None:
|
||||
extra["kv_cache_dtype"] = dtype
|
||||
if attn_metadata is None:
|
||||
return AttentionMetadata(extra={"kv_cache_dtype": kv_cache_dtype})
|
||||
extra = dict(attn_metadata.extra)
|
||||
extra["kv_cache_dtype"] = kv_cache_dtype
|
||||
return AttentionMetadata(extra=extra) if extra else None
|
||||
return replace(attn_metadata, extra=extra)
|
||||
|
||||
def forward(
|
||||
@@ -397,6 +422,7 @@ class Attention(nn.Module):
|
||||
)
|
||||
use_paged_attention = paged_adapter is not None and self.paged_kv_cache_role is not None
|
||||
if use_paged_attention and not getattr(self.attn_backend, "supports_paged_kv", False):
|
||||
assert self.attn_backend is not None
|
||||
raise NotImplementedError(
|
||||
f"Diffusion paged KV requires an Omni backend with paged support; "
|
||||
f"selected {self.attn_backend.get_name()}"
|
||||
@@ -493,29 +519,49 @@ class Attention(nn.Module):
|
||||
|
||||
def _run_local_attention(self, query, key, value, attn_metadata):
|
||||
if self._has_custom_attention:
|
||||
return self.attention(query, key, value, attn_metadata)
|
||||
return cast(nn.Module, self.attention)(query, key, value, attn_metadata)
|
||||
|
||||
self._assert_metadata_compatible(attn_metadata)
|
||||
|
||||
if (
|
||||
self.allow_fp32_fallback
|
||||
and query.is_cuda
|
||||
and query.dtype == torch.float32
|
||||
and query.ndim == 4
|
||||
and not self.backend_explicit
|
||||
and cast(type[AttentionBackend], self.attn_backend).get_name() == "FLASH_ATTN"
|
||||
and (
|
||||
attn_metadata is None
|
||||
or (
|
||||
attn_metadata.full_attn_spans is None
|
||||
and attn_metadata.query_ranges is None
|
||||
and attn_metadata.video_layout is None
|
||||
and attn_metadata.packed_padding is None
|
||||
and not attn_metadata.extra
|
||||
)
|
||||
)
|
||||
):
|
||||
logger.warning_once("Using SDPA for this layer's FP32 input with automatic CUDA FlashAttention selection.")
|
||||
return cast(AttentionImpl, self.sdpa_fallback).forward(query, key, value, attn_metadata)
|
||||
|
||||
in_kv_memory_profile = is_forward_context_available() and get_forward_context().in_diffusion_kv_memory_profile
|
||||
# The startup KV-capacity profile needs tensor shapes, not a paged
|
||||
# attention result. If dense FLASH_ATTN deps are absent (NPU MindIE-SD
|
||||
# or CUDA CuTe FA4), SDPA provides that profile forward. Formal paged
|
||||
# requests never use this branch because their Worker adapter is active.
|
||||
# Do not silently remap float32 (or other dtypes) to SDPA: a
|
||||
# user-explicit backend must run or raise.
|
||||
# A user-explicit backend must run or raise.
|
||||
if (
|
||||
self._scheduler_paged_kv
|
||||
and self.paged_kv_cache_role is not None
|
||||
and in_kv_memory_profile
|
||||
and self.attn_backend.get_name() == "FLASH_ATTN"
|
||||
and cast(type[AttentionBackend], self.attn_backend).get_name() == "FLASH_ATTN"
|
||||
and not current_omni_platform.supports_diffusion_dense_flash_attention()
|
||||
):
|
||||
logger.warning_once(
|
||||
"The startup KV memory profile is using SDPA because dense FLASH_ATTN is unavailable. "
|
||||
"Formal paged requests still use the platform-native paged attention backend."
|
||||
)
|
||||
return self.sdpa_fallback.forward(query, key, value, attn_metadata)
|
||||
return cast(AttentionImpl, self.sdpa_fallback).forward(query, key, value, attn_metadata)
|
||||
|
||||
return self.attention.forward(query, key, value, attn_metadata)
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared pooling, routing and provider calls for explicit block-sparse attention."""
|
||||
|
||||
import os
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
if not hasattr(torch.ops.vllm_omni, "fastvideo_block_sparse_attn_bshd"):
|
||||
|
||||
@torch.library.custom_op("vllm_omni::fastvideo_block_sparse_attn_bshd", mutates_args=())
|
||||
def fastvideo_block_sparse_attn_bshd(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
block_map: torch.Tensor,
|
||||
variable_block_sizes: torch.Tensor,
|
||||
logical_blocks: int,
|
||||
) -> torch.Tensor:
|
||||
"""Run explicit block-sparse attention on BSHD tensors in 64-row blocks.
|
||||
|
||||
Inputs and the block map may include transport-only blocks after
|
||||
``logical_blocks``. The Triton provider sees only logical blocks and
|
||||
the wrapper restores the original row count. Native provider selection
|
||||
and its supported-input checks remain owned by FastVideo.
|
||||
"""
|
||||
q = query.transpose(1, 2).contiguous()
|
||||
k = key.transpose(1, 2).contiguous()
|
||||
v = value.transpose(1, 2).contiguous()
|
||||
|
||||
# Prefer the explicitly selected native provider when it supports
|
||||
# these tensors; retain the existing Triton provider otherwise.
|
||||
if os.environ.get("FASTVIDEO_VSA_SM100A", "0") == "1":
|
||||
try:
|
||||
from fastvideo_kernel import block_sparse_attn_sm100a
|
||||
from fastvideo_kernel.triton_kernels.index import map_to_index
|
||||
|
||||
if block_sparse_attn_sm100a.is_supported(q, variable_block_sizes):
|
||||
q2k_idx, q2k_num = map_to_index(block_map)
|
||||
out, _ = block_sparse_attn_sm100a.block_sparse_attn_sm100a(
|
||||
q,
|
||||
k,
|
||||
v,
|
||||
q2k_idx.to(torch.int32).contiguous(),
|
||||
q2k_num.to(torch.int32).contiguous(),
|
||||
variable_block_sizes.to(torch.int32).contiguous(),
|
||||
need_lse=False,
|
||||
)
|
||||
return out.transpose(1, 2).contiguous()
|
||||
except torch.AcceleratorError:
|
||||
# A device fault can poison the context; do not launch another kernel.
|
||||
raise
|
||||
except (ImportError, RuntimeError) as exc:
|
||||
logger.warning_once(
|
||||
"FASTVIDEO_VSA_SM100A=1 requested but the native Blackwell forward is "
|
||||
"unavailable (%s); using the Triton block-sparse route instead.",
|
||||
exc,
|
||||
)
|
||||
|
||||
from fastvideo_kernel.block_sparse_attn import block_sparse_attn
|
||||
|
||||
logical_len = logical_blocks * 64
|
||||
out, _ = block_sparse_attn(
|
||||
q[:, :, :logical_len].contiguous(),
|
||||
k[:, :, :logical_len].contiguous(),
|
||||
v[:, :, :logical_len].contiguous(),
|
||||
block_map[..., :logical_blocks, :logical_blocks].contiguous(),
|
||||
variable_block_sizes[:logical_blocks].to(torch.int32).contiguous(),
|
||||
)
|
||||
out = out.transpose(1, 2).contiguous()
|
||||
if out.shape[1] != query.shape[1]:
|
||||
out = torch.nn.functional.pad(out, (0, 0, 0, 0, 0, query.shape[1] - out.shape[1]))
|
||||
return out
|
||||
|
||||
@fastvideo_block_sparse_attn_bshd.register_fake
|
||||
def _(query, key, value, block_map, variable_block_sizes, logical_blocks):
|
||||
del key, value, block_map, variable_block_sizes, logical_blocks
|
||||
return torch.empty_like(query)
|
||||
|
||||
|
||||
fastvideo_block_sparse_attn_bshd = torch.ops.vllm_omni.fastvideo_block_sparse_attn_bshd
|
||||
|
||||
|
||||
def mean_pool_tiles(x: torch.Tensor, sizes: torch.Tensor, block_size: int) -> torch.Tensor:
|
||||
"""Mean-pool zero-padded BSHD tiles with FP32 accumulation.
|
||||
|
||||
``sizes`` gives the number of valid rows in each tile.
|
||||
"""
|
||||
batch, seq_len, heads, dim = x.shape
|
||||
blocks = seq_len // block_size
|
||||
pooled = x.view(batch, blocks, block_size, heads, dim).sum(dim=2, dtype=torch.float32)
|
||||
pooled = pooled / sizes.view(1, -1, 1, 1).clamp_min(1)
|
||||
return pooled.permute(0, 2, 1, 3)
|
||||
|
||||
|
||||
def build_prefix_dense_block_map(
|
||||
scores: torch.Tensor,
|
||||
num_prefix_blocks: int,
|
||||
num_sparse_blocks: int,
|
||||
topk: int,
|
||||
) -> torch.Tensor:
|
||||
"""Keep prefix queries/keys dense and select top-k non-prefix keys per row."""
|
||||
keep_sparse = min(topk, num_sparse_blocks)
|
||||
if keep_sparse == num_sparse_blocks:
|
||||
return torch.ones_like(scores, dtype=torch.bool)
|
||||
block_map = torch.zeros_like(scores, dtype=torch.bool)
|
||||
indices = scores[..., num_prefix_blocks:].topk(keep_sparse, dim=-1).indices + num_prefix_blocks
|
||||
block_map.scatter_(-1, indices, True)
|
||||
block_map[..., :num_prefix_blocks] = True
|
||||
block_map[:, :, :num_prefix_blocks, :] = True
|
||||
return block_map
|
||||
@@ -156,9 +156,11 @@ class RingParallelAttention:
|
||||
# Extract joint tensors
|
||||
joint_key, joint_value = None, None
|
||||
joint_strategy = "front"
|
||||
valid_kv_length = None
|
||||
if attn_metadata is not None:
|
||||
joint_key = attn_metadata.joint_key
|
||||
joint_value = attn_metadata.joint_value
|
||||
valid_kv_length = attn_metadata.extra.get("valid_kv_length")
|
||||
if attn_metadata.joint_strategy is not None:
|
||||
joint_strategy = attn_metadata.joint_strategy
|
||||
|
||||
@@ -176,6 +178,7 @@ class RingParallelAttention:
|
||||
joint_tensor_key=joint_key,
|
||||
joint_tensor_value=joint_value,
|
||||
joint_strategy=joint_strategy,
|
||||
valid_kv_length=valid_kv_length,
|
||||
)
|
||||
|
||||
# Ring only implements local Flash/AITER and SDPA kernels. HuggingFace
|
||||
@@ -261,4 +264,5 @@ class RingParallelAttention:
|
||||
joint_tensor_key=joint_key,
|
||||
joint_tensor_value=joint_value,
|
||||
joint_strategy=joint_strategy,
|
||||
valid_kv_length=valid_kv_length,
|
||||
)
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from vllm_omni.diffusion.cache.seacache.backend import SeaCacheBackend
|
||||
from vllm_omni.diffusion.cache.seacache.config import SeaCacheConfig
|
||||
from vllm_omni.diffusion.cache.seacache.hook import (
|
||||
SeaCacheRootHook,
|
||||
apply_sea_cache_hook,
|
||||
)
|
||||
from vllm_omni.diffusion.cache.seacache.state import SeaCacheState
|
||||
|
||||
__all__ = [
|
||||
"SeaCacheBackend",
|
||||
"SeaCacheConfig",
|
||||
"SeaCacheRootHook",
|
||||
"SeaCacheState",
|
||||
"apply_sea_cache_hook",
|
||||
]
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.cache.base import CacheBackend
|
||||
from vllm_omni.diffusion.cache.seacache.config import SeaCacheConfig
|
||||
from vllm_omni.diffusion.cache.seacache.hook import (
|
||||
SeaCacheRootHook,
|
||||
apply_sea_cache_hook,
|
||||
)
|
||||
from vllm_omni.diffusion.data import DiffusionCacheConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def enable_cosmos3_seacache(
|
||||
pipeline: Any,
|
||||
config: DiffusionCacheConfig,
|
||||
) -> SeaCacheRootHook:
|
||||
transformer = getattr(pipeline, "transformer", None)
|
||||
if transformer is None:
|
||||
raise ValueError("SeaCache requires a pipeline with a transformer")
|
||||
|
||||
sea_config = SeaCacheConfig(
|
||||
threshold=config.sea_threshold,
|
||||
residual_order=config.sea_residual_order,
|
||||
max_consecutive_cached=config.sea_max_consecutive_cached,
|
||||
power_exp=config.sea_power_exp,
|
||||
)
|
||||
hook = apply_sea_cache_hook(
|
||||
transformer,
|
||||
sea_config,
|
||||
current_step_callback=lambda: getattr(pipeline, "current_step_index", None),
|
||||
current_sigma_callback=lambda: getattr(pipeline, "current_sigma", None),
|
||||
num_inference_steps_callback=lambda: getattr(
|
||||
pipeline,
|
||||
"num_timesteps",
|
||||
None,
|
||||
),
|
||||
)
|
||||
logger.info(
|
||||
"SeaCache enabled for %s (threshold=%s, residual_order=%d, max_consecutive_cached=%d, power_exp=%s)",
|
||||
pipeline.__class__.__name__,
|
||||
sea_config.threshold,
|
||||
sea_config.residual_order,
|
||||
sea_config.max_consecutive_cached,
|
||||
sea_config.power_exp,
|
||||
)
|
||||
return hook
|
||||
|
||||
|
||||
CUSTOM_SEACACHE_ENABLERS = {
|
||||
"Cosmos3OmniDiffusersPipeline": enable_cosmos3_seacache,
|
||||
"Cosmos3OmniPipeline": enable_cosmos3_seacache,
|
||||
}
|
||||
|
||||
|
||||
class SeaCacheBackend(CacheBackend):
|
||||
"""Backend for spectral-evolution-aware diffusion caching."""
|
||||
|
||||
def __init__(self, config: DiffusionCacheConfig):
|
||||
super().__init__(config)
|
||||
self._transformer_id: int | None = None
|
||||
|
||||
def enable(self, pipeline: Any) -> None:
|
||||
pipeline_type = pipeline.__class__.__name__
|
||||
enabler = CUSTOM_SEACACHE_ENABLERS.get(pipeline_type)
|
||||
if enabler is None:
|
||||
raise ValueError(f"SeaCache does not support pipeline type {pipeline_type}")
|
||||
hook = enabler(pipeline, self.config)
|
||||
self._transformer_id = id(pipeline.transformer)
|
||||
self.enabled = True
|
||||
pipeline._cache_context_factory = hook.cache_context
|
||||
|
||||
def refresh(
|
||||
self,
|
||||
pipeline: Any,
|
||||
num_inference_steps: int,
|
||||
verbose: bool = True,
|
||||
) -> None:
|
||||
del num_inference_steps
|
||||
transformer = getattr(pipeline, "transformer", None)
|
||||
if transformer is None:
|
||||
raise ValueError("SeaCache requires a pipeline with a transformer")
|
||||
if not self.enabled or self._transformer_id != id(transformer):
|
||||
self.enable(pipeline)
|
||||
|
||||
registry = getattr(transformer, "_hook_registry", None)
|
||||
hook = registry.get_hook(SeaCacheRootHook._HOOK_NAME) if registry is not None else None
|
||||
if not isinstance(hook, SeaCacheRootHook):
|
||||
raise RuntimeError("SeaCache hook is not installed on the pipeline transformer")
|
||||
hook.refresh(transformer)
|
||||
pipeline._cache_context_factory = hook.cache_context
|
||||
if verbose:
|
||||
logger.debug("SeaCache state refreshed")
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SeaCacheConfig:
|
||||
"""Configuration for SeaCache.
|
||||
|
||||
Defaults are tuned for Cosmos3 and may require adjustment for other models.
|
||||
"""
|
||||
|
||||
threshold: float = 0.25
|
||||
residual_order: int = 1
|
||||
max_consecutive_cached: int = 2
|
||||
power_exp: float = 3.0
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not math.isfinite(self.threshold) or self.threshold < 0:
|
||||
raise ValueError(f"threshold must be finite and non-negative, got {self.threshold}")
|
||||
if isinstance(self.residual_order, bool) or not isinstance(self.residual_order, int) or self.residual_order < 0:
|
||||
raise ValueError(f"residual_order must be a non-negative integer, got {self.residual_order!r}")
|
||||
if (
|
||||
isinstance(self.max_consecutive_cached, bool)
|
||||
or not isinstance(self.max_consecutive_cached, int)
|
||||
or self.max_consecutive_cached < 0
|
||||
):
|
||||
raise ValueError(
|
||||
f"max_consecutive_cached must be a non-negative integer, got {self.max_consecutive_cached!r}"
|
||||
)
|
||||
if not math.isfinite(self.power_exp) or self.power_exp <= 0:
|
||||
raise ValueError(f"power_exp must be finite and positive, got {self.power_exp}")
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.cache.seacache.config import SeaCacheConfig
|
||||
from vllm_omni.diffusion.cache.seacache.sea_filter import (
|
||||
apply_sea_filter,
|
||||
extrapolate_residual,
|
||||
indicator_distance,
|
||||
)
|
||||
from vllm_omni.diffusion.cache.seacache.state import SeaCacheState
|
||||
from vllm_omni.diffusion.cache.teacache.extractors import CacheContext, get_extractor
|
||||
from vllm_omni.diffusion.hooks import HookRegistry, ModelHook, StateManager
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _is_parameter_sharded(module: torch.nn.Module) -> bool:
|
||||
"""Detect parameter-sharding runtimes whose collectives cannot be skipped."""
|
||||
for submodule in module.modules():
|
||||
module_type = type(submodule)
|
||||
if callable(getattr(submodule, "_get_fsdp_state", None)):
|
||||
return True
|
||||
if module_type.__name__ == "FullyShardedDataParallel" and module_type.__module__.startswith(
|
||||
"torch.distributed.fsdp"
|
||||
):
|
||||
return True
|
||||
for parameter in submodule.parameters(recurse=False):
|
||||
parameter_type = type(parameter)
|
||||
if (
|
||||
parameter_type.__name__ == "FlatParameter"
|
||||
and parameter_type.__module__.startswith("torch.distributed.fsdp")
|
||||
) or (
|
||||
parameter_type.__name__ == "DTensor"
|
||||
and parameter_type.__module__.startswith("torch.distributed.tensor")
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class SeaCacheRootHook(ModelHook):
|
||||
"""Drive SeaCache gating and transformer forward control."""
|
||||
|
||||
_HOOK_NAME = "sea_cache"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: SeaCacheConfig,
|
||||
*,
|
||||
current_step_callback: Callable[[], int | torch.Tensor | None] | None = None,
|
||||
current_sigma_callback: Callable[[], float | torch.Tensor | None] | None = None,
|
||||
num_inference_steps_callback: Callable[[], int | torch.Tensor | None] | None = None,
|
||||
extractor_fn: Callable[..., CacheContext] | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.current_step_callback = current_step_callback
|
||||
self.current_sigma_callback = current_sigma_callback
|
||||
self.num_inference_steps_callback = num_inference_steps_callback
|
||||
self.state_manager = StateManager(SeaCacheState)
|
||||
self._warned_messages: set[str] = set()
|
||||
self.full_count = 0
|
||||
self.skip_count = 0
|
||||
self.extractor_fn = extractor_fn
|
||||
self._parameter_sharded = False
|
||||
self._collective_skip_groups: list[torch.distributed.ProcessGroup] = []
|
||||
|
||||
def initialize_hook(self, module: torch.nn.Module) -> torch.nn.Module:
|
||||
if self.extractor_fn is None:
|
||||
self.extractor_fn = get_extractor(type(module))
|
||||
self._parameter_sharded = _is_parameter_sharded(module)
|
||||
seen_groups: set[int] = set()
|
||||
for block in getattr(module, "gen_layers", ()):
|
||||
registry = getattr(block, "_hook_registry", None)
|
||||
dlo_hook = registry.get_hook("distributed_layerwise_offload") if registry is not None else None
|
||||
group = getattr(dlo_hook, "dp_group", None)
|
||||
if group is not None and int(getattr(dlo_hook, "dp_size", 1)) > 1 and id(group) not in seen_groups:
|
||||
seen_groups.add(id(group))
|
||||
self._collective_skip_groups.append(group)
|
||||
return module
|
||||
|
||||
def _warn_once(self, message: str) -> None:
|
||||
if message not in self._warned_messages:
|
||||
logger.warning(message)
|
||||
self._warned_messages.add(message)
|
||||
|
||||
@contextmanager
|
||||
def cache_context(self, name: str) -> Iterator[None]:
|
||||
previous_context = self.state_manager._context
|
||||
self.state_manager.set_context(name)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.state_manager.set_context(previous_context)
|
||||
|
||||
def _build_indicator(
|
||||
self,
|
||||
vision_items: list[torch.Tensor] | None,
|
||||
sigma: float,
|
||||
) -> list[torch.Tensor] | None:
|
||||
if not vision_items:
|
||||
return None
|
||||
hidden_states = vision_items[-1]
|
||||
if not isinstance(hidden_states, torch.Tensor) or hidden_states.ndim != 5:
|
||||
return None
|
||||
|
||||
# Controls precede the denoised target in packed vision-token order,
|
||||
# and each vision item is filtered independently.
|
||||
if any(
|
||||
not isinstance(item, torch.Tensor)
|
||||
or item.ndim != 5
|
||||
or item.shape[0] != hidden_states.shape[0]
|
||||
or item.shape[1:] != hidden_states.shape[1:]
|
||||
for item in vision_items
|
||||
):
|
||||
return None
|
||||
|
||||
indicator = []
|
||||
for batch_index in range(hidden_states.shape[0]):
|
||||
for latent in vision_items:
|
||||
thwc = latent[batch_index].movedim(0, -1)
|
||||
indicator.append(
|
||||
apply_sea_filter(
|
||||
thwc,
|
||||
sigma=sigma,
|
||||
power_exp=self.config.power_exp,
|
||||
).detach()
|
||||
)
|
||||
return indicator or None
|
||||
|
||||
def _resolve_gate(
|
||||
self,
|
||||
state: SeaCacheState,
|
||||
indicator: list[torch.Tensor] | None,
|
||||
step: int,
|
||||
num_inference_steps: int,
|
||||
) -> bool:
|
||||
if state.last_step is not None and step != state.last_step + 1:
|
||||
state.reset()
|
||||
state.last_step = step
|
||||
max_consecutive = bool(
|
||||
self.config.max_consecutive_cached and state.consecutive_cached >= self.config.max_consecutive_cached
|
||||
)
|
||||
forced_compute = (
|
||||
step < 1
|
||||
or step >= num_inference_steps - 1
|
||||
or max_consecutive
|
||||
or not state.history
|
||||
or indicator is None
|
||||
or state.previous_indicator is None
|
||||
)
|
||||
if forced_compute:
|
||||
state.accumulated_distance = 0.0
|
||||
state.previous_indicator = None if indicator is None else [value.detach() for value in indicator]
|
||||
return True
|
||||
|
||||
assert indicator is not None
|
||||
assert state.previous_indicator is not None
|
||||
distance = indicator_distance(indicator, state.previous_indicator)
|
||||
state.previous_indicator = [value.detach() for value in indicator]
|
||||
if not math.isfinite(distance):
|
||||
state.accumulated_distance = 0.0
|
||||
self._warn_once("SeaCache indicator history changed shape, device, or dtype; running full.")
|
||||
return True
|
||||
|
||||
state.accumulated_distance += distance
|
||||
if state.accumulated_distance < self.config.threshold:
|
||||
return False
|
||||
state.accumulated_distance = 0.0
|
||||
return True
|
||||
|
||||
def _synchronize_compute(self, compute: bool, device: torch.device) -> bool:
|
||||
if not torch.distributed.is_available() or not torch.distributed.is_initialized():
|
||||
return True if self._parameter_sharded else compute
|
||||
decision = torch.tensor(int(compute), dtype=torch.int32, device=device)
|
||||
if self._parameter_sharded:
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_fs_group,
|
||||
get_sequence_parallel_world_size,
|
||||
get_sp_group,
|
||||
)
|
||||
|
||||
fs_group = get_fs_group()
|
||||
if fs_group.world_size > 1:
|
||||
torch.distributed.all_reduce(
|
||||
decision,
|
||||
op=torch.distributed.ReduceOp.MAX,
|
||||
group=fs_group.device_group,
|
||||
)
|
||||
if get_sequence_parallel_world_size() > 1:
|
||||
torch.distributed.all_reduce(
|
||||
decision,
|
||||
op=torch.distributed.ReduceOp.MAX,
|
||||
group=get_sp_group().device_group,
|
||||
)
|
||||
return bool(decision.item())
|
||||
|
||||
for group in self._collective_skip_groups:
|
||||
torch.distributed.all_reduce(
|
||||
decision,
|
||||
op=torch.distributed.ReduceOp.MAX,
|
||||
group=group,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_sequence_parallel_world_size,
|
||||
get_sp_group,
|
||||
)
|
||||
|
||||
if get_sequence_parallel_world_size() > 1:
|
||||
torch.distributed.all_reduce(
|
||||
decision,
|
||||
op=torch.distributed.ReduceOp.MAX,
|
||||
group=get_sp_group().device_group,
|
||||
)
|
||||
return bool(decision.item())
|
||||
|
||||
@torch.compiler.disable
|
||||
def new_forward(
|
||||
self,
|
||||
module: torch.nn.Module,
|
||||
*args: Any,
|
||||
**kwargs: Any,
|
||||
) -> Any:
|
||||
if self.extractor_fn is None:
|
||||
raise RuntimeError("SeaCache extractor was not initialized")
|
||||
ctx = self.extractor_fn(module, *args, **kwargs)
|
||||
|
||||
if torch.is_grad_enabled():
|
||||
self._warn_once("SeaCache is inference-only; autograd-enabled calls run in full.")
|
||||
return self._run_uncached(ctx)
|
||||
if self.state_manager._current_context is None:
|
||||
self._warn_once("SeaCache requires an explicit cache context; running full.")
|
||||
return self._run_uncached(ctx)
|
||||
callbacks = (
|
||||
self.current_step_callback,
|
||||
self.current_sigma_callback,
|
||||
self.num_inference_steps_callback,
|
||||
)
|
||||
if any(callback is None for callback in callbacks):
|
||||
self._warn_once("SeaCache requires scheduler step, sigma, and step-count callbacks; running full.")
|
||||
return self._run_uncached(ctx)
|
||||
assert self.current_step_callback is not None
|
||||
assert self.current_sigma_callback is not None
|
||||
assert self.num_inference_steps_callback is not None
|
||||
|
||||
try:
|
||||
extra_states = ctx.extra_states or {}
|
||||
vision_items = extra_states.get("sea_cache_latents")
|
||||
if not isinstance(vision_items, list):
|
||||
raise ValueError("extractor did not provide SeaCache vision inputs")
|
||||
noisy_frame_mask = extra_states.get("sea_cache_noisy_frame_mask")
|
||||
conditioning_only = isinstance(noisy_frame_mask, torch.Tensor) and not bool(
|
||||
torch.any(noisy_frame_mask != 0).item()
|
||||
)
|
||||
|
||||
step = self.current_step_callback()
|
||||
sigma = self.current_sigma_callback()
|
||||
num_inference_steps = self.num_inference_steps_callback()
|
||||
if isinstance(step, torch.Tensor):
|
||||
step = step.item()
|
||||
if isinstance(sigma, torch.Tensor):
|
||||
sigma = sigma.item()
|
||||
if isinstance(num_inference_steps, torch.Tensor):
|
||||
num_inference_steps = num_inference_steps.item()
|
||||
if step is None or sigma is None or num_inference_steps is None:
|
||||
raise ValueError("scheduler metadata is unavailable")
|
||||
step = int(step)
|
||||
sigma = float(sigma)
|
||||
num_inference_steps = int(num_inference_steps)
|
||||
if (
|
||||
step < 0
|
||||
or num_inference_steps <= 0
|
||||
or step >= num_inference_steps
|
||||
or not math.isfinite(sigma)
|
||||
or not 0.0 <= sigma <= 1.0
|
||||
):
|
||||
raise ValueError("expected a valid step index and exact sigma in [0, 1]")
|
||||
except (IndexError, TypeError, ValueError, RuntimeError) as error:
|
||||
self._warn_once(f"SeaCache metadata is invalid; running full: {error}")
|
||||
return self._run_uncached(ctx)
|
||||
|
||||
if conditioning_only:
|
||||
self._warn_once("SeaCache requires noisy vision; conditioning-only calls run in full.")
|
||||
return self._run_uncached(ctx)
|
||||
|
||||
state: SeaCacheState = self.state_manager.get_state()
|
||||
try:
|
||||
indicator = self._build_indicator(vision_items, sigma)
|
||||
except (TypeError, ValueError, RuntimeError) as error:
|
||||
self._warn_once(f"SeaCache could not construct its vision indicator; running full: {error}")
|
||||
indicator = None
|
||||
|
||||
local_compute = self._resolve_gate(state, indicator, step, num_inference_steps)
|
||||
should_compute = self._synchronize_compute(local_compute, ctx.hidden_states.device)
|
||||
if should_compute and not local_compute:
|
||||
state.accumulated_distance = 0.0
|
||||
|
||||
if should_compute:
|
||||
self.full_count += 1
|
||||
output = self._run_full_stack(ctx)
|
||||
result = ctx.postprocess(output)
|
||||
self._record_execution(state, step, ctx.hidden_states, output)
|
||||
return result
|
||||
|
||||
residual = extrapolate_residual(
|
||||
state.history,
|
||||
step,
|
||||
self.config.residual_order,
|
||||
)
|
||||
if residual.device != ctx.hidden_states.device:
|
||||
residual = residual.to(ctx.hidden_states.device)
|
||||
state.consecutive_cached += 1
|
||||
self.skip_count += 1
|
||||
|
||||
can_reuse = (
|
||||
residual.shape == ctx.hidden_states.shape
|
||||
and residual.device == ctx.hidden_states.device
|
||||
and residual.dtype == ctx.hidden_states.dtype
|
||||
)
|
||||
if can_reuse:
|
||||
return ctx.postprocess(ctx.hidden_states + residual)
|
||||
|
||||
output = self._run_full_stack(ctx)
|
||||
result = ctx.postprocess(output)
|
||||
self._record_execution(state, step, ctx.hidden_states, output)
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _run_full_stack(ctx: CacheContext) -> torch.Tensor:
|
||||
outputs = ctx.run_transformer_blocks()
|
||||
if not outputs:
|
||||
raise RuntimeError("Cache extractor returned no transformer outputs")
|
||||
return outputs[0]
|
||||
|
||||
@staticmethod
|
||||
def _run_uncached(ctx: CacheContext) -> Any:
|
||||
return ctx.postprocess(SeaCacheRootHook._run_full_stack(ctx))
|
||||
|
||||
def _record_execution(
|
||||
self,
|
||||
state: SeaCacheState,
|
||||
step: int,
|
||||
execution_input: torch.Tensor,
|
||||
output: torch.Tensor,
|
||||
) -> None:
|
||||
if (
|
||||
output.shape == execution_input.shape
|
||||
and output.device == execution_input.device
|
||||
and output.dtype == execution_input.dtype
|
||||
):
|
||||
state.history.append((step, (output - execution_input).detach().clone()))
|
||||
state.history = state.history[-(self.config.residual_order + 1) :]
|
||||
state.consecutive_cached = 0
|
||||
return
|
||||
|
||||
state.history.clear()
|
||||
state.accumulated_distance = 0.0
|
||||
self._warn_once("SeaCache execution boundary returned an incompatible tensor; clearing cache history.")
|
||||
|
||||
def reset_state(self, module: torch.nn.Module) -> torch.nn.Module:
|
||||
self.state_manager.reset()
|
||||
self.full_count = 0
|
||||
self.skip_count = 0
|
||||
return module
|
||||
|
||||
def refresh(self, module: torch.nn.Module) -> None:
|
||||
self.reset_state(module)
|
||||
|
||||
|
||||
def apply_sea_cache_hook(
|
||||
module: torch.nn.Module,
|
||||
config: SeaCacheConfig,
|
||||
*,
|
||||
current_step_callback: Callable[[], int | torch.Tensor | None] | None = None,
|
||||
current_sigma_callback: Callable[[], float | torch.Tensor | None] | None = None,
|
||||
num_inference_steps_callback: Callable[[], int | torch.Tensor | None] | None = None,
|
||||
extractor_fn: Callable[..., CacheContext] | None = None,
|
||||
) -> SeaCacheRootHook:
|
||||
registry = HookRegistry.get_or_create(module)
|
||||
hook = SeaCacheRootHook(
|
||||
config,
|
||||
current_step_callback=current_step_callback,
|
||||
current_sigma_callback=current_sigma_callback,
|
||||
num_inference_steps_callback=num_inference_steps_callback,
|
||||
extractor_fn=extractor_fn,
|
||||
)
|
||||
registry.register_hook(SeaCacheRootHook._HOOK_NAME, hook)
|
||||
return hook
|
||||
@@ -0,0 +1,93 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
# SeaCache paper: "Spectral-Evolution-Aware Cache for Accelerating Diffusion Models"
|
||||
# https://arxiv.org/abs/2602.18993
|
||||
def apply_sea_filter(hidden_states: torch.Tensor, sigma: float, power_exp: float = 3.0) -> torch.Tensor:
|
||||
"""Apply the separable SEA Wiener filter over ``(T, H, W)``."""
|
||||
original_dtype = hidden_states.dtype
|
||||
hidden_states = hidden_states.contiguous().float()
|
||||
dimensions = (0, 1, 2)
|
||||
spectrum = torch.fft.fftn(hidden_states, dim=dimensions)
|
||||
|
||||
sigma = max(1e-6, min(1.0 - 1e-6, float(sigma)))
|
||||
signal_scale = 1.0 - sigma
|
||||
noise_scale = sigma
|
||||
gain: torch.Tensor | None = None
|
||||
for axis in dimensions:
|
||||
frequencies = torch.fft.fftfreq(
|
||||
hidden_states.shape[axis],
|
||||
device=hidden_states.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
clean_power = 1.0 / (frequencies.abs().pow(power_exp) + 1e-16)
|
||||
axis_gain = signal_scale * clean_power / (signal_scale**2 * clean_power + noise_scale**2 + 1e-16)
|
||||
axis_shape = [1] * hidden_states.ndim
|
||||
axis_shape[axis] = axis_gain.shape[0]
|
||||
reshaped_gain = axis_gain.reshape(axis_shape)
|
||||
gain = reshaped_gain if gain is None else gain * reshaped_gain
|
||||
|
||||
assert gain is not None
|
||||
gain = gain / gain.mean()
|
||||
return torch.fft.ifftn(spectrum * gain, dim=dimensions).real.to(original_dtype)
|
||||
|
||||
|
||||
def relative_l1_distance(current: torch.Tensor, previous: torch.Tensor, eps: float = 1e-16) -> float:
|
||||
numerator = (current.float() - previous.float()).abs().mean()
|
||||
denominator = previous.float().abs().mean() + eps
|
||||
return float((numerator / denominator).detach().cpu())
|
||||
|
||||
|
||||
def indicator_distance(
|
||||
current: list[torch.Tensor] | None,
|
||||
previous: list[torch.Tensor] | None,
|
||||
) -> float:
|
||||
"""Mean relative-L1 distance, or infinity for incompatible indicators."""
|
||||
if current is None or previous is None or not current or len(current) != len(previous):
|
||||
return float("inf")
|
||||
|
||||
total = 0.0
|
||||
for current_value, previous_value in zip(current, previous, strict=True):
|
||||
if (
|
||||
current_value.shape != previous_value.shape
|
||||
or current_value.device != previous_value.device
|
||||
or current_value.dtype != previous_value.dtype
|
||||
):
|
||||
return float("inf")
|
||||
total += relative_l1_distance(current_value, previous_value)
|
||||
distance = total / len(current)
|
||||
return distance if math.isfinite(distance) else float("inf")
|
||||
|
||||
|
||||
def extrapolate_residual(
|
||||
history: list[tuple[int, torch.Tensor]],
|
||||
step: int,
|
||||
order: int,
|
||||
) -> torch.Tensor:
|
||||
"""Evaluate a Newton residual polynomial at ``step``."""
|
||||
if not history:
|
||||
raise ValueError("SeaCache residual extrapolation requires non-empty history")
|
||||
|
||||
polynomial_order = max(0, min(order, len(history) - 1))
|
||||
window = history[-(polynomial_order + 1) :]
|
||||
steps = [history_step for history_step, _ in window]
|
||||
coefficients = [residual.clone() for _, residual in window]
|
||||
|
||||
for level in range(1, polynomial_order + 1):
|
||||
for index in range(polynomial_order, level - 1, -1):
|
||||
denominator = steps[index] - steps[index - level]
|
||||
if denominator == 0:
|
||||
return window[-1][1].clone()
|
||||
coefficients[index] = (coefficients[index] - coefficients[index - 1]) / float(denominator)
|
||||
|
||||
result = coefficients[polynomial_order]
|
||||
for index in range(polynomial_order - 1, -1, -1):
|
||||
result = result * float(step - steps[index]) + coefficients[index]
|
||||
return result
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SeaCacheState:
|
||||
"""Per-cache-context trajectory state."""
|
||||
|
||||
last_step: int | None = None
|
||||
accumulated_distance: float = 0.0
|
||||
previous_indicator: list[torch.Tensor] | None = None
|
||||
history: list[tuple[int, torch.Tensor]] = field(default_factory=list)
|
||||
consecutive_cached: int = 0
|
||||
|
||||
def reset(self) -> None:
|
||||
self.last_step = None
|
||||
self.accumulated_distance = 0.0
|
||||
self.previous_indicator = None
|
||||
self.history.clear()
|
||||
self.consecutive_cached = 0
|
||||
+9
-2
@@ -1,8 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.diffusion.cache.base import CacheBackend
|
||||
from vllm_omni.diffusion.cache.cachedit import CacheDiTBackend
|
||||
from vllm_omni.diffusion.cache.magcache import MagCacheBackend
|
||||
from vllm_omni.diffusion.cache.seacache import SeaCacheBackend
|
||||
from vllm_omni.diffusion.cache.stepcache import StepCacheBackend
|
||||
from vllm_omni.diffusion.cache.teacache import TeaCacheBackend
|
||||
from vllm_omni.diffusion.data import DiffusionCacheConfig
|
||||
@@ -15,11 +19,12 @@ def get_cache_backend(cache_backend: str | None, cache_config: Any) -> CacheBack
|
||||
- cache_dit: Uses CacheDiTBackend with enable()/refresh() interface
|
||||
- tea_cache: Uses TeaCacheBackend with enable()/refresh() interface
|
||||
- mag_cache: Uses MagCacheBackend with enable()/refresh() interface
|
||||
- sea_cache: Uses SeaCacheBackend for spectral residual caching
|
||||
- step_cache: Uses StepCacheBackend for DreamZero velocity step skip
|
||||
|
||||
Args:
|
||||
cache_backend: Cache backend name ("cache_dit", "tea_cache",
|
||||
"mag_cache", "step_cache", or None).
|
||||
"mag_cache", "sea_cache", "step_cache", or None).
|
||||
cache_config: Cache configuration (dict or DiffusionCacheConfig instance).
|
||||
|
||||
Returns:
|
||||
@@ -40,10 +45,12 @@ def get_cache_backend(cache_backend: str | None, cache_config: Any) -> CacheBack
|
||||
return TeaCacheBackend(cache_config)
|
||||
elif cache_backend == "mag_cache":
|
||||
return MagCacheBackend(cache_config)
|
||||
elif cache_backend == "sea_cache":
|
||||
return SeaCacheBackend(cache_config)
|
||||
elif cache_backend in ("step_cache", "stepcache", "step_cache_dit"):
|
||||
return StepCacheBackend(cache_config)
|
||||
else:
|
||||
raise ValueError(
|
||||
f"Unsupported cache backend: {cache_backend}. "
|
||||
"Supported: 'cache_dit', 'tea_cache', 'mag_cache', 'step_cache'"
|
||||
"Supported: 'cache_dit', 'tea_cache', 'mag_cache', 'sea_cache', 'step_cache'"
|
||||
)
|
||||
+90
-12
@@ -199,7 +199,7 @@ def extract_qwen_context(
|
||||
hidden_states, vid_freqs, txt_freqs = module.image_rope_prepare(hidden_states, img_shapes, txt_seq_lens)
|
||||
image_rotary_emb = (vid_freqs, txt_freqs)
|
||||
|
||||
timestep = timestep.to(device=hidden_states.device, dtype=hidden_states.dtype)
|
||||
timestep = torch.as_tensor(timestep, device=hidden_states.device, dtype=hidden_states.dtype)
|
||||
|
||||
# Call modulate_index_prepare instead of handling timestep directly.
|
||||
# For zero_cond_t=False: timestep unchanged, modulate_index=None.
|
||||
@@ -618,6 +618,8 @@ def extract_flux2_klein_context(
|
||||
# ============================================================================
|
||||
dtype = hidden_states.dtype
|
||||
|
||||
if encoder_hidden_states is None:
|
||||
raise ValueError("Flux2Klein requires encoder_hidden_states")
|
||||
num_txt_tokens = encoder_hidden_states.shape[1]
|
||||
|
||||
timestep = timestep.to(dtype=dtype) * 1000
|
||||
@@ -1260,7 +1262,7 @@ def extract_minimax_h3_context(
|
||||
preprocessing via ``_embed``, cacheable ``blocks`` loop, and
|
||||
``final_layer`` postprocessing with row selection and update masks.
|
||||
"""
|
||||
from vllm_omni.diffusion.attention.ops.minimax_h3_modulation import indexed_scale_shift_
|
||||
from vllm_omni.diffusion.layers.indexed_modulation import indexed_scale_shift_
|
||||
from vllm_omni.diffusion.models.minimax_h3.minimax_h3_transformer import (
|
||||
_FORWARD_SUPPORTED_KWARGS,
|
||||
MINIMAX_H3_ADALN_MODALITY_NUM,
|
||||
@@ -1466,6 +1468,77 @@ def extract_minimax_h3_context(
|
||||
)
|
||||
|
||||
|
||||
def extract_cosmos3_context(
|
||||
module: nn.Module,
|
||||
hidden_states: torch.Tensor,
|
||||
timestep: torch.Tensor,
|
||||
text_ids: torch.Tensor,
|
||||
text_mask: torch.Tensor,
|
||||
video_shape: tuple[int, int, int],
|
||||
fps: float | None = None,
|
||||
action_latents: torch.Tensor | None = None,
|
||||
action_domain_ids: torch.Tensor | None = None,
|
||||
action_noisy_mask: torch.Tensor | None = None,
|
||||
action_start_frame_offset: int = 1,
|
||||
action_fps: float | None = None,
|
||||
sound_latents: torch.Tensor | None = None,
|
||||
noisy_frame_mask: torch.Tensor | None = None,
|
||||
control_latents: list[torch.Tensor] | tuple[torch.Tensor, ...] | torch.Tensor | None = None,
|
||||
control_weights: list[float] | tuple[float, ...] | torch.Tensor | None = None,
|
||||
transfer_share_vision_temporal_positions: bool = True,
|
||||
**kwargs: Any,
|
||||
) -> CacheContext:
|
||||
"""Build the shared cache execution context for Cosmos3's GEN pathway."""
|
||||
if kwargs:
|
||||
raise TypeError(f"Unexpected Cosmos3 transformer kwargs: {sorted(kwargs)}")
|
||||
|
||||
prep = module._gen_preprocess(
|
||||
hidden_states,
|
||||
timestep,
|
||||
text_ids,
|
||||
text_mask,
|
||||
video_shape,
|
||||
fps=fps,
|
||||
action_latents=action_latents,
|
||||
action_domain_ids=action_domain_ids,
|
||||
action_noisy_mask=action_noisy_mask,
|
||||
action_start_frame_offset=action_start_frame_offset,
|
||||
action_fps=action_fps,
|
||||
sound_latents=sound_latents,
|
||||
noisy_frame_mask=noisy_frame_mask,
|
||||
control_latents=control_latents,
|
||||
control_weights=control_weights,
|
||||
transfer_share_vision_temporal_positions=transfer_share_vision_temporal_positions,
|
||||
)
|
||||
|
||||
def run_transformer_blocks() -> tuple[torch.Tensor, ...]:
|
||||
return (module._run_gen_stack(prep),)
|
||||
|
||||
def postprocess(hidden: torch.Tensor) -> Any:
|
||||
return module._gen_postprocess(hidden, prep)
|
||||
|
||||
if control_latents is None:
|
||||
controls: list[torch.Tensor] = []
|
||||
elif isinstance(control_latents, torch.Tensor):
|
||||
controls = [control_latents]
|
||||
else:
|
||||
controls = list(control_latents)
|
||||
|
||||
return CacheContext(
|
||||
# SeaCache uses the separate inputs in extra_states for its decision.
|
||||
modulated_input=prep.hidden_gen,
|
||||
hidden_states=prep.hidden_gen,
|
||||
encoder_hidden_states=None,
|
||||
temb=prep.time_embed,
|
||||
run_transformer_blocks=run_transformer_blocks,
|
||||
postprocess=postprocess,
|
||||
extra_states={
|
||||
"sea_cache_latents": [*controls, hidden_states],
|
||||
"sea_cache_noisy_frame_mask": noisy_frame_mask,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# Registry for model-specific extractors
|
||||
# Key: Transformer class name
|
||||
# Value: extractor function with signature (module, *args, **kwargs) -> CacheContext
|
||||
@@ -1475,6 +1548,8 @@ def extract_minimax_h3_context(
|
||||
EXTRACTOR_REGISTRY: dict[str, Callable] = {
|
||||
"QwenImageTransformer2DModel": extract_qwen_context,
|
||||
"Bagel": extract_bagel_context,
|
||||
"Cosmos3EdgeVFMTransformer": extract_cosmos3_context,
|
||||
"Cosmos3VFMTransformer": extract_cosmos3_context,
|
||||
"ZImageTransformer2DModel": extract_zimage_context,
|
||||
"Flux2Klein": extract_flux2_klein_context,
|
||||
"StableAudioDiTModel": extract_stable_audio_context,
|
||||
@@ -1521,16 +1596,15 @@ def register_extractor(transformer_cls_name: str, extractor_fn: Callable) -> Non
|
||||
EXTRACTOR_REGISTRY[transformer_cls_name] = extractor_fn
|
||||
|
||||
|
||||
def get_extractor(transformer_cls_name: str) -> Callable:
|
||||
def get_extractor(transformer_type: str | type) -> Callable:
|
||||
"""
|
||||
Get extractor function for given transformer class.
|
||||
|
||||
This function looks up the extractor based on the exact transformer_cls_name string,
|
||||
which should match the transformer type in the pipeline (i.e., pipeline.transformer.__class__.__name__).
|
||||
String lookups match an exact registered name. Type lookups also check base
|
||||
classes so runtime wrappers such as FSDP retain the underlying model extractor.
|
||||
|
||||
Args:
|
||||
transformer_cls_name: Transformer class name (e.g., "QwenImageTransformer2DModel")
|
||||
Must exactly match a key in EXTRACTOR_REGISTRY.
|
||||
transformer_type: Transformer class name or runtime type.
|
||||
|
||||
Returns:
|
||||
Extractor function with signature (module, *args, **kwargs) -> CacheContext
|
||||
@@ -1543,14 +1617,18 @@ def get_extractor(transformer_cls_name: str) -> Callable:
|
||||
>>> extractor = get_extractor("QwenImageTransformer2DModel")
|
||||
>>> ctx = extractor(transformer, hidden_states, encoder_hidden_states, timestep, ...)
|
||||
"""
|
||||
# Direct lookup - no substring matching
|
||||
if transformer_cls_name in EXTRACTOR_REGISTRY:
|
||||
return EXTRACTOR_REGISTRY[transformer_cls_name]
|
||||
candidate_names: tuple[str, ...]
|
||||
if isinstance(transformer_type, str):
|
||||
candidate_names = (transformer_type,)
|
||||
else:
|
||||
candidate_names = tuple(candidate.__name__ for candidate in transformer_type.__mro__)
|
||||
for candidate_name in candidate_names:
|
||||
if candidate_name in EXTRACTOR_REGISTRY:
|
||||
return EXTRACTOR_REGISTRY[candidate_name]
|
||||
|
||||
# No match found
|
||||
available_types = list(EXTRACTOR_REGISTRY.keys())
|
||||
raise ValueError(
|
||||
f"Unknown model type: '{transformer_cls_name}'. "
|
||||
f"Unknown model type: '{transformer_type}'. "
|
||||
f"Available types: {available_types}\n"
|
||||
f"To add support for a new model, use register_extractor() or add to EXTRACTOR_REGISTRY."
|
||||
)
|
||||
+159
-44
@@ -6,6 +6,7 @@ import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import warnings
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field, fields
|
||||
from enum import Enum
|
||||
@@ -29,6 +30,7 @@ from vllm_omni.diffusion.diffusion_kv.config import (
|
||||
parse_diffusion_kv_cache_mode,
|
||||
)
|
||||
from vllm_omni.diffusion.lora.manager import LoRABackend
|
||||
from vllm_omni.diffusion.media import DiffusionMediaOutput
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
from vllm_omni.diffusion.utils.network_utils import is_port_available
|
||||
from vllm_omni.errors import client_error_metadata
|
||||
@@ -43,55 +45,63 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def normalize_omni_diffusion_kwargs(raw_kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Normalize legacy diffusion kwargs before config construction."""
|
||||
def _move_diffusion_alias(
|
||||
normalized: dict[str, Any],
|
||||
legacy_name: str,
|
||||
canonical_name: str,
|
||||
) -> None:
|
||||
legacy_value = normalized.pop(legacy_name, None)
|
||||
if legacy_value is None:
|
||||
return
|
||||
if normalized.get(canonical_name) is not None:
|
||||
raise ValueError(f"Diffusion config fields {legacy_name!r} and {canonical_name!r} cannot both be provided.")
|
||||
warnings.warn(
|
||||
f"Diffusion config field {legacy_name!r} is deprecated; use {canonical_name!r}.",
|
||||
FutureWarning,
|
||||
stacklevel=3,
|
||||
)
|
||||
normalized[canonical_name] = legacy_value
|
||||
|
||||
|
||||
def normalize_omni_diffusion_kwargs(
|
||||
raw_kwargs: Mapping[str, Any],
|
||||
*,
|
||||
apply_defaults: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Normalize diffusion kwargs, deferring defaults until sources are merged."""
|
||||
config_kwargs = dict(raw_kwargs)
|
||||
|
||||
dtype = config_kwargs.get("dtype")
|
||||
if dtype is None:
|
||||
config_kwargs["dtype"] = "auto"
|
||||
if apply_defaults:
|
||||
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 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 config_kwargs and config_kwargs.get("quantization_config", None) is None:
|
||||
config_kwargs["quantization_config"] = config_kwargs.pop("quantization")
|
||||
else:
|
||||
config_kwargs.pop("quantization", None)
|
||||
|
||||
# Renamed from kv_cache_* to avoid clashing with vLLM's --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:
|
||||
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:
|
||||
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:
|
||||
config_kwargs.pop("kv_cache_skip_layers", None)
|
||||
for legacy, canonical in (
|
||||
("static_lora_scale", "lora_scale"),
|
||||
("quantization", "quantization_config"),
|
||||
("diffusion_quantization_config", "quantization_config"),
|
||||
("max_batch_size", "max_num_seqs"),
|
||||
("kv_cache_skip_steps", "diffusion_kv_cache_skip_steps"),
|
||||
("kv_cache_skip_layers", "diffusion_kv_cache_skip_layers"),
|
||||
):
|
||||
_move_diffusion_alias(config_kwargs, legacy, canonical)
|
||||
_move_diffusion_alias(config_kwargs, "kv_cache_dtype", "diffusion_kv_cache_dtype")
|
||||
|
||||
# Handle "diffusion_attention_backend" shorthand: merge into
|
||||
# diffusion_attention_config before field filtering.
|
||||
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:
|
||||
if diffusion_attn_backend is not None:
|
||||
warnings.warn(
|
||||
"Diffusion config field 'diffusion_attention_backend' is deprecated; use 'diffusion_attention_config'.",
|
||||
FutureWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
existing = config_kwargs.get("diffusion_attention_config")
|
||||
config_kwargs["diffusion_attention_config"] = parse_attention_config(
|
||||
existing,
|
||||
@@ -99,12 +109,23 @@ def normalize_omni_diffusion_kwargs(raw_kwargs: Mapping[str, Any]) -> dict[str,
|
||||
fastvideo_vsa_topk=fastvideo_vsa_topk,
|
||||
)
|
||||
|
||||
auxiliary_text_encoder = config_kwargs.pop("auxiliary_text_encoder", None)
|
||||
if auxiliary_text_encoder is not None:
|
||||
extras = dict(config_kwargs.get("extras") or {})
|
||||
if extras.get("auxiliary_text_encoder") is not None:
|
||||
raise ValueError(
|
||||
"Diffusion engine field 'auxiliary_text_encoder' cannot be provided both at the top level and in "
|
||||
"'extras'."
|
||||
)
|
||||
extras["auxiliary_text_encoder"] = auxiliary_text_encoder
|
||||
config_kwargs["extras"] = extras
|
||||
|
||||
# Check environment variable as fallback for cache_backend.
|
||||
# Support both old DIFFUSION_CACHE_ADAPTER and new DIFFUSION_CACHE_BACKEND.
|
||||
if "cache_backend" not in config_kwargs:
|
||||
if "cache_backend" not in config_kwargs and apply_defaults:
|
||||
cache_backend = os.environ.get("DIFFUSION_CACHE_BACKEND") or os.environ.get("DIFFUSION_CACHE_ADAPTER")
|
||||
config_kwargs["cache_backend"] = cache_backend.lower() if cache_backend else "none"
|
||||
elif config_kwargs["cache_backend"] is None:
|
||||
elif "cache_backend" in config_kwargs and config_kwargs["cache_backend"] is None and apply_defaults:
|
||||
# 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.
|
||||
@@ -161,6 +182,20 @@ def validate_dlo_host_registration_options(
|
||||
return value
|
||||
|
||||
|
||||
def validate_omni_diffusion_kwargs(
|
||||
kwargs: Mapping[str, Any],
|
||||
allowed_fields: set[str] | frozenset[str],
|
||||
*,
|
||||
stage_id: int | str | None = None,
|
||||
) -> None:
|
||||
"""Reject every field without an owner."""
|
||||
unknown = set(kwargs) - allowed_fields
|
||||
if unknown:
|
||||
names = ", ".join(repr(name) for name in sorted(unknown))
|
||||
suffix = "" if stage_id is None else f" for stage {stage_id}"
|
||||
raise ValueError(f"Unknown diffusion config field(s){suffix}: {names}")
|
||||
|
||||
|
||||
def parse_kv_cache_skip_selector(
|
||||
selector: str | list[int] | tuple[int, ...] | set[int] | None,
|
||||
) -> set[int] | None:
|
||||
@@ -540,6 +575,8 @@ class DiffusionCacheConfig:
|
||||
scm_steps_mask_policy, scm_steps_policy
|
||||
- MagCache: mag_threshold, mag_max_skip_steps, mag_retention_ratio,
|
||||
mag_ratios, mag_calibrate
|
||||
- SeaCache: sea_threshold, sea_residual_order,
|
||||
sea_max_consecutive_cached, sea_power_exp
|
||||
- step_cache: step_cache_dit_enabled, velocity_sim_thresholds,
|
||||
velocity_skip_countdowns, step_cache_dit_min_history
|
||||
|
||||
@@ -559,6 +596,12 @@ class DiffusionCacheConfig:
|
||||
rel_l1_thresh: float | None = None
|
||||
coefficients: list[float] | None = None # Uses model-specific defaults if None
|
||||
|
||||
# SeaCache parameters [sea_cache only]
|
||||
sea_threshold: float = 0.25
|
||||
sea_residual_order: int = 1
|
||||
sea_max_consecutive_cached: int = 2
|
||||
sea_power_exp: float = 3.0
|
||||
|
||||
# MagCache parameters [mag_cache only]
|
||||
# Default: 0.24 threshold for accumulated magnitude error
|
||||
mag_threshold: float = 0.24
|
||||
@@ -758,6 +801,15 @@ def uses_diffusers_adapter(od_config: object) -> bool:
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class VideoOutputTransportConfig:
|
||||
enable_device_postprocess: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not isinstance(self.enable_device_postprocess, bool):
|
||||
raise TypeError("enable_device_postprocess must be a bool")
|
||||
|
||||
|
||||
@dataclass
|
||||
class OmniDiffusionConfig:
|
||||
# Model and path configuration (for convenience)
|
||||
@@ -793,6 +845,7 @@ class OmniDiffusionConfig:
|
||||
# Cache backend configuration (NEW)
|
||||
cache_backend: str = "none" # "tea_cache", "deep_cache", etc.
|
||||
cache_config: DiffusionCacheConfig | dict[str, Any] = field(default_factory=dict)
|
||||
video_output_transport: VideoOutputTransportConfig = field(default_factory=VideoOutputTransportConfig)
|
||||
enable_cache_dit_summary: bool = False
|
||||
|
||||
# Prompt-embedding cache. When enabled, ``DiffusionModelRunner`` wraps the
|
||||
@@ -909,6 +962,7 @@ class OmniDiffusionConfig:
|
||||
|
||||
# Parallel weight loading (for faster diffusion model startup)
|
||||
enable_multithread_weight_load: bool = True
|
||||
enable_broadcast_weight_load: bool = False
|
||||
num_weight_load_threads: int = 4
|
||||
|
||||
# Enable sleep mode
|
||||
@@ -964,6 +1018,7 @@ class OmniDiffusionConfig:
|
||||
"transformer": True,
|
||||
"vae": True,
|
||||
"text_encoder": True,
|
||||
"vae_encoder": True,
|
||||
}
|
||||
)
|
||||
override_transformer_cls_name: str | None = None
|
||||
@@ -1000,16 +1055,15 @@ class OmniDiffusionConfig:
|
||||
# str is resolved to {"method": <str>} internally.
|
||||
# Per-component: {"transformer": {"method": "fp8"}, "vae": None}
|
||||
quantization_config: str | QuantizationConfig | dict[str, Any] | None = None
|
||||
# Internal provenance, retained across config projection and worker transport.
|
||||
quantization_config_is_auto_detected: bool = False
|
||||
# Explicit runtime override for ModelOpt FP8 diffusion checkpoints. This
|
||||
# does not enable FP8 by itself; it only selects CUTLASS once the checkpoint
|
||||
# has already resolved to vLLM's ModelOpt FP8 linear method.
|
||||
force_cutlass_fp8: bool = False
|
||||
|
||||
# Diffusion attention KV cache dtype (not vLLM's --kv-cache-dtype for AR models).
|
||||
# None = native dtype (no quantization).
|
||||
# "fp8" = dynamic FP8 (float8_e4m3fn) quantization per forward pass.
|
||||
# On Hopper+FA3: native FP8 attention (memory + compute savings).
|
||||
# On other backends: no benefit, backends skip quantization.
|
||||
# Runtime diffusion attention method (not vLLM's --kv-cache-dtype for AR models).
|
||||
# None/"auto" keeps native dtype; other values are validated by the selected backend.
|
||||
diffusion_kv_cache_dtype: str | None = None
|
||||
# Optional skip selectors for KV-cache quantization. Format: "0-9,20,25-30".
|
||||
# Listed steps/layers skip quantization; others keep quantized execution.
|
||||
@@ -1171,6 +1225,8 @@ class OmniDiffusionConfig:
|
||||
if self.diffusion_kv_mode is not DiffusionKVCacheMode.PAGED_SCHEDULER:
|
||||
raise ValueError("native kv_transfer_config requires diffusion_kv_mode='paged_scheduler'")
|
||||
self.kv_transfer_config = parse_kv_transfer_config(self.kv_transfer_config)
|
||||
if self.enable_sleep_mode:
|
||||
raise ValueError("Native KV transfer does not support sleep mode: registered pages must remain mapped")
|
||||
|
||||
self.master_port = self._resolve_master_port()
|
||||
self.request_batch_max_wait_ms = float(self.request_batch_max_wait_ms or 0.0)
|
||||
@@ -1258,6 +1314,13 @@ class OmniDiffusionConfig:
|
||||
# If it's neither dict nor DiffusionCacheConfig, convert to empty config
|
||||
self.cache_config = DiffusionCacheConfig()
|
||||
|
||||
if self.video_output_transport is None:
|
||||
self.video_output_transport = VideoOutputTransportConfig()
|
||||
elif isinstance(self.video_output_transport, Mapping):
|
||||
self.video_output_transport = VideoOutputTransportConfig(**dict(self.video_output_transport))
|
||||
elif not isinstance(self.video_output_transport, VideoOutputTransportConfig):
|
||||
raise TypeError("video_output_transport must be a VideoOutputTransportConfig or mapping")
|
||||
|
||||
# Auto-detect quantization from TransformerConfig if not explicitly set.
|
||||
# This covers the case where tf_model_config is passed at construction
|
||||
# time. For late (post-construction) assignment, callers should use
|
||||
@@ -1318,6 +1381,10 @@ class OmniDiffusionConfig:
|
||||
self.model,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_single_file(self) -> bool:
|
||||
return isinstance(self.model, str) and os.path.isfile(self.model)
|
||||
|
||||
def _propagate_quantization_from_tf_config(self, tf_config: "TransformerConfig") -> None:
|
||||
if tf_config.quant_config is None:
|
||||
return
|
||||
@@ -1330,6 +1397,8 @@ class OmniDiffusionConfig:
|
||||
or (is_checkpoint_nvfp4 and self._is_generic_nvfp4_quant_config(self.quantization_config))
|
||||
)
|
||||
if should_use_checkpoint_config:
|
||||
if self.quantization_config is None:
|
||||
self.quantization_config_is_auto_detected = True
|
||||
self.quantization_config = tf_config.quant_config
|
||||
logger.info(
|
||||
"Auto-detected quantization '%s' from model config",
|
||||
@@ -1420,12 +1489,22 @@ class OmniDiffusionConfig:
|
||||
"""
|
||||
from vllm.transformers_utils.config import get_hf_file_to_dict
|
||||
|
||||
from vllm_omni.diffusion.registry import resolve_native_single_file
|
||||
from vllm_omni.diffusion.utils.hf_utils import (
|
||||
get_diffusion_model_index,
|
||||
resolve_native_diffusion_model_class,
|
||||
)
|
||||
|
||||
assert self.model is not None
|
||||
|
||||
native_single_file_model = resolve_native_single_file(self.model_class_name)
|
||||
if self.is_single_file and native_single_file_model is not None:
|
||||
self.diffusion_load_format = "default"
|
||||
self.model_class_name = native_single_file_model
|
||||
self.diffusers_pipeline_cls = None
|
||||
self.set_tf_model_config(TransformerConfig())
|
||||
return
|
||||
|
||||
try:
|
||||
config_dict = get_diffusion_model_index(
|
||||
self.model,
|
||||
@@ -1583,6 +1662,11 @@ class OmniDiffusionConfig:
|
||||
self.model_class_name = "Pi0Pipeline"
|
||||
self.set_tf_model_config(TransformerConfig())
|
||||
self.update_multimodal_support()
|
||||
elif cfg.get("type") == "pi05":
|
||||
if self.model_class_name is None:
|
||||
self.model_class_name = "Pi05Pipeline"
|
||||
self.set_tf_model_config(TransformerConfig())
|
||||
self.update_multimodal_support()
|
||||
elif architectures and len(architectures) == 1:
|
||||
architecture = architectures[0]
|
||||
from vllm_omni.diffusion.registry import DiffusionModelRegistry
|
||||
@@ -1597,8 +1681,9 @@ class OmniDiffusionConfig:
|
||||
|
||||
@classmethod
|
||||
def normalize_init_kwargs(cls, raw_kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
||||
valid_fields = frozenset(f.name for f in fields(cls))
|
||||
config_kwargs = normalize_omni_diffusion_kwargs(raw_kwargs)
|
||||
valid_fields = {f.name for f in fields(cls)}
|
||||
validate_omni_diffusion_kwargs(config_kwargs, 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
|
||||
@@ -1610,6 +1695,18 @@ class OmniDiffusionConfig:
|
||||
return cls(**cls.normalize_init_kwargs(kwargs))
|
||||
|
||||
|
||||
DIFFUSION_REQUEST_LIFECYCLE_KEY = "_diffusion_request_lifecycle"
|
||||
DIFFUSION_REQUEST_STARTED = "started"
|
||||
|
||||
|
||||
def is_diffusion_request_started_output(output: Any) -> bool:
|
||||
custom_output = getattr(output, "custom_output", None)
|
||||
return (
|
||||
isinstance(custom_output, dict)
|
||||
and custom_output.get(DIFFUSION_REQUEST_LIFECYCLE_KEY) == DIFFUSION_REQUEST_STARTED
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DiffusionOutput:
|
||||
"""
|
||||
@@ -1618,8 +1715,8 @@ class DiffusionOutput:
|
||||
|
||||
output: torch.Tensor | tuple[Any, ...] | dict[str, Any] | None = None
|
||||
|
||||
# Legacy compatibility fields. New pipeline-specific payloads should be
|
||||
# carried by output["payload"] instead.
|
||||
# Legacy compatibility fields. Decoded video uses ``media``; other new
|
||||
# payloads should be carried by output["payload"] instead.
|
||||
trajectory_timesteps: torch.Tensor | dict[str, Any] | None = None
|
||||
trajectory_latents: torch.Tensor | dict[str, Any] | None = None
|
||||
trajectory_log_probs: torch.Tensor | dict[str, Any] | None = None
|
||||
@@ -1658,7 +1755,21 @@ class DiffusionOutput:
|
||||
# mode) and the receiving side must not initialise a stray CUDA context.
|
||||
to_cpu: bool = False
|
||||
|
||||
# Internal control-plane event emitted on first scheduler admission.
|
||||
request_started: bool = False
|
||||
|
||||
# Typed video-media contract. Declared last so the pre-existing positional
|
||||
# constructor order (output, trajectory_timesteps, ...) that out-of-tree
|
||||
# pipelines rely on is preserved. Mutually exclusive with ``output``.
|
||||
media: DiffusionMediaOutput | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.media is not None and not isinstance(self.media, DiffusionMediaOutput):
|
||||
raise TypeError(f"media must be DiffusionMediaOutput, got {type(self.media).__name__}")
|
||||
if self.media is not None and self.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
if self.media is not None and self.post_process_func is not None:
|
||||
raise ValueError("Typed diffusion media cannot carry a model-specific post_process_func")
|
||||
if not self.to_cpu:
|
||||
return
|
||||
|
||||
@@ -1674,6 +1785,10 @@ class DiffusionOutput:
|
||||
return value
|
||||
|
||||
self.output = _maybe_to_cpu(self.output)
|
||||
if self.media is not None:
|
||||
if not self.media.prepared_for_transport:
|
||||
raise ValueError("Diffusion media must be prepared before to_cpu=True")
|
||||
self.media = self.media.to_cpu()
|
||||
self.trajectory_timesteps = _maybe_to_cpu(self.trajectory_timesteps)
|
||||
self.trajectory_latents = _maybe_to_cpu(self.trajectory_latents)
|
||||
self.trajectory_log_probs = _maybe_to_cpu(self.trajectory_log_probs)
|
||||
|
||||
@@ -26,6 +26,8 @@ from vllm.v1.engine.exceptions import EngineDeadError
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
|
||||
from vllm_omni.diffusion.data import (
|
||||
DIFFUSION_REQUEST_LIFECYCLE_KEY,
|
||||
DIFFUSION_REQUEST_STARTED,
|
||||
DiffusionOutput,
|
||||
DiffusionRequestAbortedError,
|
||||
OmniDiffusionConfig,
|
||||
@@ -47,6 +49,7 @@ from vllm_omni.diffusion.output_formatter import (
|
||||
format_empty_diffusion_outputs,
|
||||
normalize_diffusion_postprocess_output,
|
||||
)
|
||||
from vllm_omni.diffusion.postprocess.media import finalize_diffusion_media
|
||||
from vllm_omni.diffusion.registry import (
|
||||
DiffusionModelRegistry,
|
||||
get_diffusion_post_process_func,
|
||||
@@ -54,7 +57,7 @@ from vllm_omni.diffusion.registry import (
|
||||
)
|
||||
from vllm_omni.diffusion.request import DUMMY_DIFFUSION_REQUEST_ID, OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.sched import BaseScheduler, RequestScheduler, StepScheduler
|
||||
from vllm_omni.diffusion.sched.interface import DiffusionRequestStatus
|
||||
from vllm_omni.diffusion.sched.interface import DiffusionRequestStatus, DiffusionSchedulerOutput
|
||||
from vllm_omni.diffusion.worker.utils import BaseRunnerOutput, BatchRunnerOutput, RunnerOutput
|
||||
from vllm_omni.errors import client_error_from_metadata, is_client_error_status
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniTextPrompt
|
||||
@@ -532,28 +535,40 @@ class DiffusionEngine:
|
||||
error_type=output.error_type,
|
||||
)
|
||||
raise RuntimeError(output.error)
|
||||
logger.debug("Generation completed successfully.")
|
||||
if output.request_started:
|
||||
return format_empty_diffusion_outputs(
|
||||
request,
|
||||
finished=False,
|
||||
custom_output={DIFFUSION_REQUEST_LIFECYCLE_KEY: DIFFUSION_REQUEST_STARTED},
|
||||
)
|
||||
|
||||
if output.output is None:
|
||||
logger.warning("Output is None, returning empty OmniRequestOutput")
|
||||
return format_empty_diffusion_outputs(request, finished=output.finished)
|
||||
|
||||
# When CPU offload is enabled, move output to CPU before
|
||||
# post-processing to avoid device OOM — model weights may still
|
||||
# reside on the device and leave no headroom for intermediates.
|
||||
output_data = output.output
|
||||
if self.od_config.enable_cpu_offload:
|
||||
output_data = _move_tensor_tree_to_cpu(output_data)
|
||||
|
||||
if self.post_process_func is not None:
|
||||
# Some video pipelines need request-level controls during
|
||||
# postprocess (for example worker-side frame interpolation).
|
||||
postprocess_kwargs: dict[str, object] = {}
|
||||
if self._post_process_accepts_sampling_params:
|
||||
postprocess_kwargs["sampling_params"] = request.sampling_params
|
||||
outputs = self.post_process_func(output_data, **postprocess_kwargs)
|
||||
if output.media is not None:
|
||||
if output.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
media = output.media.to_cpu() if self.od_config.enable_cpu_offload else output.media
|
||||
output_data = media.video.tensor
|
||||
outputs = finalize_diffusion_media(media, sampling_params=request.sampling_params)
|
||||
else:
|
||||
outputs = output_data
|
||||
if output.output is None:
|
||||
logger.warning("Output is None, returning empty OmniRequestOutput")
|
||||
return format_empty_diffusion_outputs(request, finished=output.finished)
|
||||
|
||||
# When CPU offload is enabled, move output to CPU before
|
||||
# post-processing to avoid device OOM — model weights may still
|
||||
# reside on the device and leave no headroom for intermediates.
|
||||
output_data = output.output
|
||||
if self.od_config.enable_cpu_offload:
|
||||
output_data = _move_tensor_tree_to_cpu(output_data)
|
||||
|
||||
if self.post_process_func is not None:
|
||||
# Some video pipelines need request-level controls during
|
||||
# postprocess (for example worker-side frame interpolation).
|
||||
postprocess_kwargs: dict[str, object] = {}
|
||||
if self._post_process_accepts_sampling_params:
|
||||
postprocess_kwargs["sampling_params"] = request.sampling_params
|
||||
outputs = self.post_process_func(output_data, **postprocess_kwargs)
|
||||
else:
|
||||
outputs = output_data
|
||||
|
||||
postprocess_output = normalize_diffusion_postprocess_output(outputs)
|
||||
|
||||
@@ -588,16 +603,31 @@ class DiffusionEngine:
|
||||
|
||||
self._wait_for_admission_if_needed_locked()
|
||||
|
||||
sched_output = self.scheduler.schedule()
|
||||
try:
|
||||
sched_output = self.scheduler.schedule()
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
return
|
||||
self._scheduler_num_waiting_reqs = max(int(sched_output.num_waiting_reqs), 0)
|
||||
|
||||
self._emit_request_started_outputs(sched_output)
|
||||
|
||||
if sched_output.is_empty:
|
||||
self._emit_finished_outputs(sched_output.finished_req_ids, None)
|
||||
continue
|
||||
|
||||
try:
|
||||
runner_output: BaseRunnerOutput = self.execute_fn(sched_output) # pyright: ignore[reportAssignmentType]
|
||||
self._prepare_kv_for_forward(sched_output)
|
||||
runner_output: BaseRunnerOutput = (
|
||||
self.execute_fn(sched_output)
|
||||
if sched_output.scheduled_request_ids
|
||||
else BatchRunnerOutput.from_list([])
|
||||
)
|
||||
worker_execution_completed = True
|
||||
except Exception as exc:
|
||||
if self._closed:
|
||||
return
|
||||
worker_execution_completed = False
|
||||
logger.error(
|
||||
"Execution failed for diffusion requests %s", sched_output.scheduled_request_ids, exc_info=True
|
||||
)
|
||||
@@ -615,12 +645,38 @@ class DiffusionEngine:
|
||||
|
||||
self._process_aborts_queue()
|
||||
self._process_rpc_queue()
|
||||
finished_req_ids = self.scheduler.update_from_output(sched_output, runner_output)
|
||||
self._emit_outputs(finished_req_ids, sched_output.scheduled_request_ids, runner_output)
|
||||
try:
|
||||
finished_req_ids = self.scheduler.update_from_output(sched_output, runner_output)
|
||||
self._emit_outputs(
|
||||
finished_req_ids,
|
||||
sched_output.scheduled_request_ids,
|
||||
runner_output,
|
||||
worker_execution_completed=worker_execution_completed,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
return
|
||||
|
||||
if not sched_output.scheduled_request_ids and self.scheduler._kv_draining_requests:
|
||||
# Only exceptional in-flight receives need idle polling. New
|
||||
# requests / aborts wake this wait immediately.
|
||||
with self._cv:
|
||||
self._cv.wait(timeout=0.01)
|
||||
|
||||
# Engine is stopping: fail any RPCs still queued so callers don't hang.
|
||||
self._fail_pending_rpcs(RuntimeError("DiffusionEngine is shutting down."))
|
||||
|
||||
def _emit_request_started_outputs(self, sched_output: DiffusionSchedulerOutput) -> None:
|
||||
"""Notify opted-in callers when requests leave the scheduler queue."""
|
||||
for new_req in sched_output.scheduled_new_reqs:
|
||||
request = getattr(new_req, "req", None)
|
||||
sampling_params = getattr(request, "sampling_params", None)
|
||||
if getattr(sampling_params, "emit_request_lifecycle", False):
|
||||
self._put_output(
|
||||
new_req.request_id,
|
||||
DiffusionOutput(finished=False, request_started=True),
|
||||
)
|
||||
|
||||
def _wait_for_admission_if_needed_locked(self) -> None:
|
||||
"""Apply scheduler admission policy while holding the engine condition.
|
||||
|
||||
@@ -727,15 +783,80 @@ class DiffusionEngine:
|
||||
return
|
||||
unique_request_ids = list(dict.fromkeys(request_ids))
|
||||
if unique_request_ids:
|
||||
self.executor.remove_diffusion_kv_requests(unique_request_ids)
|
||||
scheduler = getattr(self, "scheduler", None)
|
||||
target_builder = getattr(scheduler, "get_diffusion_kv_cleanup_targets", None)
|
||||
cleanup_targets = target_builder(unique_request_ids) if target_builder is not None else unique_request_ids
|
||||
try:
|
||||
if cleanup_targets:
|
||||
self.executor.remove_diffusion_kv_requests(cleanup_targets)
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
|
||||
def _prepare_kv_for_forward(self, sched_output: DiffusionSchedulerOutput) -> None:
|
||||
if getattr(sched_output, "kv_connector_metadata", None) is None:
|
||||
return
|
||||
try:
|
||||
output = self.executor.prepare_kv_for_forward(sched_output)
|
||||
assert output is not None
|
||||
self.scheduler.update_kv_connector_output(output)
|
||||
if not self.abort_queue.empty():
|
||||
self._process_aborts_queue()
|
||||
incomplete = sched_output.kv_transfer_request_ids - (output.finished_recving or set())
|
||||
sched_output.finished_req_ids.update(self.scheduler.fail_incomplete_kv_loads(incomplete))
|
||||
# Timed-out/cancelled requests must never reach model execution.
|
||||
terminal = {
|
||||
rid
|
||||
for rid in sched_output.scheduled_request_ids
|
||||
if (state := self.scheduler.get_request_state(rid)) is not None and state.is_finished()
|
||||
}
|
||||
if terminal:
|
||||
sched_output.finished_req_ids.update(terminal)
|
||||
sched_output.scheduled_new_reqs = [
|
||||
req for req in sched_output.scheduled_new_reqs if req.request_id not in terminal
|
||||
]
|
||||
sched_output.scheduled_cached_reqs.request_ids = [
|
||||
rid for rid in sched_output.scheduled_cached_reqs.request_ids if rid not in terminal
|
||||
]
|
||||
# is_empty / started-output handling may have already cached it.
|
||||
sched_output.__dict__.pop("scheduled_request_ids", None)
|
||||
drained = self.scheduler.completed_kv_drains()
|
||||
if drained:
|
||||
self._remove_diffusion_kv_requests(drained)
|
||||
self.scheduler.release_kv_drains(drained)
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
|
||||
def _fail_engine(self, exc: Exception) -> None:
|
||||
if getattr(self, "_shutdown_complete", False):
|
||||
return
|
||||
logger.error("Diffusion engine failed; stopping workers before releasing KV pages", exc_info=exc)
|
||||
with self._cv:
|
||||
self._closed = True
|
||||
if self.stop_event is not None:
|
||||
self.stop_event.set()
|
||||
streams = list(self._out_streams.values())
|
||||
self._cv.notify_all()
|
||||
for stream in streams:
|
||||
self._put_queue_output(stream, DiffusionOutput.from_exception(exc))
|
||||
self._fail_pending_rpcs(exc)
|
||||
try:
|
||||
self.executor.shutdown()
|
||||
finally:
|
||||
try:
|
||||
self.scheduler.close()
|
||||
finally:
|
||||
self._shutdown_complete = True
|
||||
|
||||
def _emit_finished_outputs(
|
||||
self,
|
||||
finished_ids: set[str],
|
||||
runner_output: BaseRunnerOutput | None = None,
|
||||
missing_result_error: str = "Diffusion execution finished without a final output",
|
||||
worker_cleaned_ids: set[str] | None = None,
|
||||
) -> None:
|
||||
self._remove_diffusion_kv_requests(finished_ids)
|
||||
self._remove_diffusion_kv_requests(finished_ids - (worker_cleaned_ids or set()))
|
||||
for rid in finished_ids:
|
||||
if runner_output is not None:
|
||||
_output = runner_output.get_request_output(rid)
|
||||
@@ -749,13 +870,21 @@ class DiffusionEngine:
|
||||
finished_ids: set[str],
|
||||
scheduled_request_ids: list[str],
|
||||
runner_output: BaseRunnerOutput,
|
||||
*,
|
||||
worker_execution_completed: bool = False,
|
||||
) -> None:
|
||||
"""Emit output chunks for every request through the unified output stream."""
|
||||
finished_ids = set(finished_ids)
|
||||
worker_cleaned_ids = finished_ids.intersection(scheduled_request_ids) if worker_execution_completed else set()
|
||||
if self.execution_mode != DiffusionExecutionMode.STEP_BATCH:
|
||||
self._emit_finished_outputs(finished_ids, runner_output)
|
||||
self._emit_finished_outputs(
|
||||
finished_ids,
|
||||
runner_output,
|
||||
worker_cleaned_ids=worker_cleaned_ids,
|
||||
)
|
||||
return
|
||||
|
||||
self._remove_diffusion_kv_requests(finished_ids)
|
||||
self._remove_diffusion_kv_requests(finished_ids - worker_cleaned_ids)
|
||||
|
||||
delivered_finished_req_ids: set[str] = set()
|
||||
|
||||
@@ -947,7 +1076,11 @@ class DiffusionEngine:
|
||||
# keep scheduling and executing until the target request is finished
|
||||
while True:
|
||||
self._process_aborts_queue()
|
||||
sched_output = self.scheduler.schedule()
|
||||
try:
|
||||
sched_output = self.scheduler.schedule()
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
if sched_output.is_empty:
|
||||
if target_request_id in sched_output.finished_req_ids:
|
||||
self._remove_diffusion_kv_requests([target_request_id])
|
||||
@@ -958,12 +1091,19 @@ class DiffusionEngine:
|
||||
|
||||
# NOTE: add_req_and_wait_for_response() is synchronous, will be only called
|
||||
# within _dummy_run, only one request will be scheduled
|
||||
request_id = sched_output.scheduled_request_ids[0]
|
||||
request_id = target_request_id
|
||||
try:
|
||||
runner_output: BaseRunnerOutput = self.execute_fn(sched_output) # pyright: ignore[reportAssignmentType]
|
||||
self._prepare_kv_for_forward(sched_output)
|
||||
runner_output: BaseRunnerOutput = (
|
||||
self.execute_fn(sched_output)
|
||||
if sched_output.scheduled_request_ids
|
||||
else BatchRunnerOutput.from_list([])
|
||||
)
|
||||
except EngineDeadError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if self._closed:
|
||||
raise
|
||||
logger.error("Execution failed for diffusion request %s", request_id, exc_info=True)
|
||||
runner_output = RunnerOutput(
|
||||
request_id=request_id,
|
||||
@@ -977,7 +1117,11 @@ class DiffusionEngine:
|
||||
finished_req_ids = self.scheduler.update_from_output(sched_output, runner_output)
|
||||
|
||||
# sync func should receive one result
|
||||
if not isinstance(runner_output, RunnerOutput) and not len(runner_output) == 1:
|
||||
if (
|
||||
sched_output.scheduled_request_ids
|
||||
and not isinstance(runner_output, RunnerOutput)
|
||||
and len(runner_output) != 1
|
||||
):
|
||||
raise ValueError("Sync func should receive one result at one time")
|
||||
if target_request_id in finished_req_ids:
|
||||
self._remove_diffusion_kv_requests([target_request_id])
|
||||
@@ -1072,7 +1216,8 @@ class DiffusionEngine:
|
||||
executes one request from the collective wave.
|
||||
|
||||
Hunyuan is currently the only model integrated with
|
||||
``paged_scheduler``; 1024x1024, enabled CFG, and the maximum advertised
|
||||
``paged_scheduler``. The stage's configured default resolution (or
|
||||
1024x1024 when absent), enabled CFG, and the maximum advertised
|
||||
reference-image count exercise its first-step activation peak.
|
||||
Admission compares each preprocessed request's CFG count and tokenized
|
||||
sequence/target shape with the resulting per-request profile envelope.
|
||||
@@ -1089,9 +1234,12 @@ class DiffusionEngine:
|
||||
model_class_name = self.od_config.model_class_name
|
||||
if model_class_name is None:
|
||||
raise RuntimeError("Diffusion KV profiling requires a resolved model_class_name")
|
||||
additional_config = getattr(self.od_config, "additional_config", {}) or {}
|
||||
profile_height = additional_config.get("diffusion_kv_profile_height", 1024)
|
||||
profile_width = additional_config.get("diffusion_kv_profile_width", 1024)
|
||||
request = self._make_dummy_request(
|
||||
height=1024,
|
||||
width=1024,
|
||||
height=profile_height,
|
||||
width=profile_width,
|
||||
guidance_scale=5.0,
|
||||
num_image_inputs=get_dummy_run_num_image_inputs(model_class_name),
|
||||
)
|
||||
@@ -1307,7 +1455,11 @@ class DiffusionEngine:
|
||||
|
||||
def _process_aborts_queue(self) -> None:
|
||||
with self._cv:
|
||||
self._drain_abort_queue()
|
||||
try:
|
||||
self._drain_abort_queue()
|
||||
except Exception as exc:
|
||||
self._fail_engine(exc)
|
||||
raise
|
||||
|
||||
def _drain_abort_queue(self) -> None:
|
||||
if self.abort_queue.empty():
|
||||
@@ -1324,11 +1476,10 @@ class DiffusionEngine:
|
||||
request_ids = [request_ids] if isinstance(request_ids, str) else list(request_ids)
|
||||
request_ids = list(dict.fromkeys(request_ids))
|
||||
|
||||
self._remove_diffusion_kv_requests(request_ids)
|
||||
|
||||
for request_id in request_ids:
|
||||
if self.scheduler.get_request_state(request_id) is not None:
|
||||
self.scheduler.finish_requests(request_id, DiffusionRequestStatus.FINISHED_ABORTED)
|
||||
self._remove_diffusion_kv_requests(request_ids)
|
||||
|
||||
def _finalize_finished_request(
|
||||
self,
|
||||
|
||||
@@ -1,35 +1,40 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Diffusion-side assembly facade built on the upstream Mooncake KV connector.
|
||||
|
||||
The configured ``kv_connector`` (currently ``MooncakeConnector``) is created
|
||||
through vLLM's native ``KVConnectorFactory``. PR0 only validates configuration
|
||||
and creates the Scheduler/Worker connector objects; it does not subclass or
|
||||
reimplement Mooncake's transfer runtime. Real page sizing, cache registration,
|
||||
admission, and remote loading belong to the follow-up landing PR.
|
||||
"""
|
||||
"""Assemble native vLLM KV connectors for Scheduler-owned diffusion pages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Mapping
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
from vllm.config import KVTransferConfig, VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorRole
|
||||
from vllm.distributed.kv_transfer.kv_transfer_state import ensure_kv_transfer_initialized, ensure_kv_transfer_shutdown
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorBase_V1
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.diffusion_kv.request import DiffusionKVRequest
|
||||
from vllm_omni.diffusion.sched.interface import DiffusionSchedulerOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class KVTransferRegistrationError(ValueError):
|
||||
"""A failed handoff whose destination pages have not been dispatched."""
|
||||
|
||||
|
||||
def mint_transfer_id(request_id: str) -> str:
|
||||
"""Return the stable ticket shared by one AR -> Diffusion handoff."""
|
||||
|
||||
@@ -110,6 +115,8 @@ def parse_kv_transfer_config(value: object | None) -> KVTransferConfig | None:
|
||||
|
||||
def create_scheduler_kv_connector(
|
||||
od_config: OmniDiffusionConfig,
|
||||
kv_cache_config: KVCacheConfig | None = None,
|
||||
vllm_config: VllmConfig | None = None,
|
||||
) -> KVConnectorBase_V1 | None:
|
||||
"""Create a Scheduler-role connector when native config is present."""
|
||||
|
||||
@@ -121,14 +128,15 @@ def create_scheduler_kv_connector(
|
||||
f"Diffusion native kv_transfer_config must be KVTransferConfig, got {type(kv_transfer_config)!r}"
|
||||
)
|
||||
|
||||
vllm_config = _build_native_vllm_config(od_config)
|
||||
if kv_cache_config is None or vllm_config is None:
|
||||
raise ValueError("KV transfer requires paged_scheduler and a native cache configuration")
|
||||
connector = KVConnectorFactory.create_connector(
|
||||
config=vllm_config,
|
||||
role=KVConnectorRole.SCHEDULER,
|
||||
kv_cache_config=_empty_kv_cache_config(),
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
logger.info(
|
||||
"Created KV connector stub (SCHEDULER role): connector=%s engine_id=%s",
|
||||
"Created KV connector (SCHEDULER role): connector=%s engine_id=%s",
|
||||
kv_transfer_config.kv_connector,
|
||||
kv_transfer_config.engine_id,
|
||||
)
|
||||
@@ -140,9 +148,27 @@ def init_worker_kv_connector(vllm_config: VllmConfig, kv_cache_config: KVCacheCo
|
||||
|
||||
if vllm_config.kv_transfer_config is None:
|
||||
return
|
||||
ensure_kv_transfer_initialized(vllm_config, kv_cache_config)
|
||||
import vllm.distributed.parallel_state as parallel_state
|
||||
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
|
||||
|
||||
# vLLM 0.29 Mooncake snapshots tp_rank/tp_size in its Worker constructor;
|
||||
# consumer receive/region mapping use those saved values, not get_tp_group.
|
||||
# Restrict this compatibility bridge to that connector and restore the
|
||||
# model's TP group even when construction fails. Never remap model TP for
|
||||
# the connector's entire lifetime (it would change model collectives).
|
||||
tp_group = parallel_state._TP
|
||||
parallel_config = getattr(vllm_config, "parallel_config", None)
|
||||
if getattr(parallel_config, "prefill_context_parallel_size", 1) > 1 and tp_group.world_size == 1:
|
||||
if vllm_config.kv_transfer_config.kv_connector != "MooncakeConnector":
|
||||
raise ValueError("Native SP KV transfer currently requires MooncakeConnector")
|
||||
parallel_state._TP = get_sp_group()
|
||||
try:
|
||||
ensure_kv_transfer_initialized(vllm_config, kv_cache_config)
|
||||
finally:
|
||||
parallel_state._TP = tp_group
|
||||
logger.info(
|
||||
"Initialized KV connector stub (WORKER role): connector=%s engine_id=%s",
|
||||
"Initialized KV connector (WORKER role): connector=%s engine_id=%s",
|
||||
vllm_config.kv_transfer_config.kv_connector,
|
||||
vllm_config.kv_transfer_config.engine_id,
|
||||
)
|
||||
@@ -156,26 +182,165 @@ def shutdown_kv_connector(*, scheduler_connector: KVConnectorBase_V1 | None = No
|
||||
ensure_kv_transfer_shutdown()
|
||||
|
||||
|
||||
def _empty_kv_cache_config() -> KVCacheConfig:
|
||||
"""Empty cache config used only for PR0 connector assembly."""
|
||||
|
||||
return KVCacheConfig(num_blocks=0, kv_cache_tensors=[], kv_cache_groups=[])
|
||||
def prepare_kv_requests(requests: tuple[DiffusionKVRequest, ...], params: Mapping[str, Any]) -> None:
|
||||
for request in requests:
|
||||
request.kv_transfer_params = dict(params)
|
||||
num_tokens = min(len(request.prompt_token_ids), params["num_transfer_tokens"])
|
||||
request.prompt_token_ids = request.prompt_token_ids[:num_tokens]
|
||||
request.num_prompt_tokens = num_tokens
|
||||
|
||||
|
||||
def _build_native_vllm_config(od_config: OmniDiffusionConfig) -> VllmConfig:
|
||||
from vllm_omni.diffusion.vllm_config import create_diffusion_vllm_config
|
||||
def install_mooncake_cfg_fanout(connector: KVConnectorBase_V1) -> None:
|
||||
"""Account for multiple CFG destinations on one native Mooncake ticket.
|
||||
|
||||
kv_transfer_config = getattr(od_config, "kv_transfer_config", None)
|
||||
assert isinstance(kv_transfer_config, KVTransferConfig)
|
||||
vllm_config = create_diffusion_vllm_config(torch.device("cpu"), od_config)
|
||||
vllm_config.kv_transfer_config = kv_transfer_config
|
||||
return vllm_config
|
||||
vLLM 0.29 initializes ``need_send`` to the paired consumer rank count,
|
||||
but increments ``sent`` per consumer request. Adapt only this producer
|
||||
instance, after KV initialization and before serving requests. Keep the
|
||||
upstream address planning, transport, timeout and completion code intact.
|
||||
"""
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import MooncakeConnector
|
||||
|
||||
if not isinstance(connector, MooncakeConnector):
|
||||
return
|
||||
worker = connector.connector_worker
|
||||
if worker is None or worker.is_kv_consumer or getattr(worker, "_omni_cfg_fanout_installed", False):
|
||||
return
|
||||
build_transfer_params = worker._build_transfer_params
|
||||
|
||||
async def build_with_fanout(ready_reqs, agent_meta, local_regions, remote_regions):
|
||||
# commit_kv_load registers all rows before build_connector_meta. Thus
|
||||
# each rank's message contains the complete row set for each ticket,
|
||||
# including empty-block notifications. Count the full message, not
|
||||
# just the subset whose producer-ready events fired in this iteration.
|
||||
rows_per_ticket = Counter(transfer_id for transfer_id, _ in agent_meta.req_blocks.values())
|
||||
tickets = {send_meta.transfer_id: send_meta for _, send_meta in ready_reqs}
|
||||
for transfer_id, send_meta in tickets.items():
|
||||
rows = rows_per_ticket[transfer_id]
|
||||
previous = getattr(send_meta, "_omni_cfg_rows", None)
|
||||
if rows < 1 or (previous is not None and previous != rows):
|
||||
# Use the upstream transfer-error path: it decrements sending
|
||||
# without incrementing sent, so a malformed rank cannot free
|
||||
# source pages still needed by another rank.
|
||||
return [], [], [], [req_id for req_id, _ in ready_reqs], "Inconsistent Mooncake CFG receive count"
|
||||
# No await between checking and updating: all handlers run on the
|
||||
# sender loop. The marker belongs to the ticket, not to a request-global
|
||||
# variable; it disappears with the upstream ticket on completion/expiry.
|
||||
for transfer_id, send_meta in tickets.items():
|
||||
if getattr(send_meta, "_omni_cfg_rows", None) is None:
|
||||
send_meta.need_send *= rows_per_ticket[transfer_id]
|
||||
send_meta._omni_cfg_rows = rows_per_ticket[transfer_id]
|
||||
return await build_transfer_params(ready_reqs, agent_meta, local_regions, remote_regions)
|
||||
|
||||
worker._build_transfer_params = build_with_fanout # type: ignore[method-assign]
|
||||
setattr(worker, "_omni_cfg_fanout_installed", True)
|
||||
|
||||
|
||||
def commit_kv_load(
|
||||
connector: KVConnectorBase_V1,
|
||||
manager: KVCacheManager,
|
||||
requests: tuple[DiffusionKVRequest, ...],
|
||||
matched_tokens: list[int],
|
||||
) -> set[str]:
|
||||
expected = set()
|
||||
allocations = []
|
||||
# All rows sharing a transfer_id must reach the same connector metadata:
|
||||
# the producer uses this complete per-rank row set for fan-out accounting.
|
||||
# Validate every CFG row before mutating any connector state.
|
||||
for request, num_tokens in zip(requests, matched_tokens, strict=True):
|
||||
blocks = manager.get_blocks(request.request_id)
|
||||
# Mooncake's producer advertises complete physical blocks. Keep every
|
||||
# CFG receiver on that same block boundary so the native connector can
|
||||
# use its normal one-to-one page mapping even when the branches have
|
||||
# different logical prefix lengths. Bytes beyond ``num_tokens`` are
|
||||
# not marked computed and are overwritten by the DiT prefill.
|
||||
transfer_tokens = num_tokens
|
||||
if num_tokens > 0 and request.kv_transfer_params is not None:
|
||||
transfer_tokens = request.kv_transfer_params["num_transfer_tokens"]
|
||||
if type(transfer_tokens) is not int or not num_tokens <= transfer_tokens <= request.num_tokens:
|
||||
raise KVTransferRegistrationError(
|
||||
"Diffusion KV transfer boundary must cover the reusable prefix "
|
||||
f"without exceeding the allocated sequence: reusable={num_tokens}, "
|
||||
f"transfer={transfer_tokens!r}, allocated={request.num_tokens}"
|
||||
)
|
||||
prefix_blocks = KVCacheBlocks(
|
||||
tuple(
|
||||
group[: (transfer_tokens + spec.kv_cache_spec.block_size - 1) // spec.kv_cache_spec.block_size]
|
||||
for group, spec in zip(blocks.blocks, manager.kv_cache_config.kv_cache_groups, strict=True)
|
||||
)
|
||||
)
|
||||
allocations.append((request, prefix_blocks, num_tokens))
|
||||
try:
|
||||
for request, prefix_blocks, num_tokens in allocations:
|
||||
connector.update_state_after_alloc(request, prefix_blocks, num_tokens)
|
||||
request.num_computed_tokens = num_tokens
|
||||
if request.kv_transfer_params is not None:
|
||||
expected.add(request.request_id)
|
||||
except Exception as exc:
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector import MooncakeConnector
|
||||
from vllm.v1.request import RequestStatus
|
||||
|
||||
if not isinstance(connector, MooncakeConnector):
|
||||
# Unknown connectors may have started I/O during registration.
|
||||
raise
|
||||
# Mooncake only queues metadata here; no Worker has seen addresses yet.
|
||||
# Re-arm its pre-scheduling abort hook to replace even partially
|
||||
# registered CFG receives with empty-block notifications to the producer.
|
||||
for request in requests:
|
||||
if request.kv_transfer_params is not None:
|
||||
request.kv_transfer_params["do_remote_prefill"] = True
|
||||
request.status = RequestStatus.FINISHED_ABORTED
|
||||
delay_free, _ = connector.request_finished(request, [])
|
||||
if delay_free:
|
||||
raise RuntimeError("Connector could not cancel an undispatched KV load") from exc
|
||||
raise KVTransferRegistrationError(f"Could not register diffusion KV receive: {exc}") from exc
|
||||
return expected
|
||||
|
||||
|
||||
def wait_for_kv_load(
|
||||
active_connector: ActiveKVConnector, scheduler_output: DiffusionSchedulerOutput, timeout: float
|
||||
) -> KVConnectorOutput:
|
||||
connector = active_connector.kv_connector
|
||||
active_connector.pre_forward(scheduler_output)
|
||||
pending = set(scheduler_output.kv_transfer_request_ids)
|
||||
finished_ids = scheduler_output.kv_finished_request_ids
|
||||
if not pending:
|
||||
output = active_connector.post_forward(finished_ids)
|
||||
if output.invalid_block_ids:
|
||||
raise RuntimeError("Diffusion KV connector reported invalid remote pages")
|
||||
return output
|
||||
|
||||
received, sent = set(), set()
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
finished_sending, finished_recving = connector.get_finished(finished_ids)
|
||||
sent.update(finished_sending or ())
|
||||
received.update(finished_recving or ())
|
||||
pending.difference_update(received)
|
||||
if connector.get_block_ids_with_load_errors():
|
||||
raise RuntimeError("Diffusion KV connector reported invalid remote pages")
|
||||
if not pending:
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
# A timeout is not a cancellation acknowledgement. Return partial
|
||||
# completion; Scheduler quarantines the remaining destination pages.
|
||||
break
|
||||
time.sleep(0.001)
|
||||
output = active_connector.post_forward(finished_ids)
|
||||
output.finished_sending = sent | (output.finished_sending or set())
|
||||
output.finished_recving = received | (output.finished_recving or set())
|
||||
if output.invalid_block_ids:
|
||||
raise RuntimeError("Diffusion KV connector reported invalid remote pages")
|
||||
return output
|
||||
|
||||
|
||||
def _validate_kv_transfer_config(config: KVTransferConfig) -> None:
|
||||
engine_id = config.engine_id
|
||||
if not isinstance(engine_id, str) or not engine_id.strip():
|
||||
raise ValueError("Diffusion native kv_transfer_config requires a non-empty engine_id")
|
||||
extra_config = config.kv_connector_extra_config or {}
|
||||
timeout = extra_config.get("transfer_timeout", 60.0)
|
||||
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ValueError("Diffusion transfer_timeout must be a positive finite number of seconds")
|
||||
if config.kv_connector is not None and config.kv_role is None:
|
||||
raise ValueError("Diffusion native kv_transfer_config requires kv_role when kv_connector is set")
|
||||
if config.kv_role not in (None, "kv_consumer", "kv_producer", "kv_both"):
|
||||
|
||||
@@ -8,6 +8,7 @@ from collections.abc import Sequence
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
|
||||
from vllm_omni.core.sched.utils import free_kv_blocks_in_physical_order
|
||||
from vllm_omni.diffusion.diffusion_kv.metadata import (
|
||||
DiffusionKVMetadata,
|
||||
DiffusionKVSequenceMetadata,
|
||||
@@ -179,7 +180,7 @@ class DiffusionKVCacheManager:
|
||||
requests = self._requests.pop(public_request_id, ())
|
||||
self._metadata.pop(public_request_id, None)
|
||||
for request in reversed(requests):
|
||||
self.native_manager.free(request)
|
||||
free_kv_blocks_in_physical_order(self.native_manager, request)
|
||||
self._internal_request_ids.discard(request.request_id)
|
||||
|
||||
def close(self) -> None:
|
||||
@@ -188,4 +189,4 @@ class DiffusionKVCacheManager:
|
||||
|
||||
def _rollback(self, requests: Sequence[DiffusionKVRequest]) -> None:
|
||||
for request in reversed(requests):
|
||||
self.native_manager.free(request)
|
||||
free_kv_blocks_in_physical_order(self.native_manager, request)
|
||||
@@ -41,6 +41,7 @@ class DiffusionKVSequenceMetadata:
|
||||
seq_len: int
|
||||
block_ids: tuple[list[int], ...]
|
||||
context_ids: tuple[str, ...] = ()
|
||||
num_computed_tokens: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -190,6 +190,10 @@ class DiffusionKVModelRunnerBackend:
|
||||
)
|
||||
return ulysses_degree
|
||||
|
||||
@property
|
||||
def kv_caches_by_layer(self) -> dict[str, torch.Tensor]:
|
||||
return {name: layer.kv_cache for name, layer in self._kv_cache_layer_adapters.items()}
|
||||
|
||||
def _get_max_rows_per_request(self) -> int:
|
||||
max_rows = getattr(self.od_config, "diffusion_kv_max_rows_per_request", None)
|
||||
if type(max_rows) is not int or max_rows <= 0:
|
||||
@@ -245,7 +249,9 @@ class DiffusionKVModelRunnerBackend:
|
||||
for capacity, block_size in zip(unaligned_max_num_blocks_per_group, block_sizes, strict=True)
|
||||
]
|
||||
|
||||
max_num_reqs = max_num_seqs * max_rows_per_request
|
||||
max_num_reqs = max_num_seqs
|
||||
if max_num_reqs % max_rows_per_request:
|
||||
raise ValueError("scheduler_config.max_num_seqs must be a multiple of diffusion_kv_max_rows_per_request")
|
||||
max_num_batched_tokens = getattr(scheduler_config, "max_num_batched_tokens", None)
|
||||
if type(max_num_batched_tokens) is not int or max_num_batched_tokens <= 0:
|
||||
raise ValueError("scheduler_config.max_num_batched_tokens must be a positive integer")
|
||||
@@ -254,9 +260,6 @@ class DiffusionKVModelRunnerBackend:
|
||||
cp_rank = get_dcp_group().rank_in_group if cp_size > 1 else 0
|
||||
cp_interleave = parallel_config.cp_kv_cache_interleave_size
|
||||
|
||||
# Native metadata builders size per-row buffers from max_num_seqs.
|
||||
# A diffusion public request can occupy several sequence/context rows.
|
||||
scheduler_config.max_num_seqs = max_num_reqs
|
||||
kv_caches: list[torch.Tensor | list[torch.Tensor]] = []
|
||||
previous_adapter_caches = {
|
||||
layer_name: adapter.kv_cache for layer_name, adapter in self._kv_cache_layer_adapters.items()
|
||||
@@ -303,7 +306,6 @@ class DiffusionKVModelRunnerBackend:
|
||||
self.vllm_config,
|
||||
)
|
||||
except Exception:
|
||||
scheduler_config.max_num_seqs = max_num_seqs
|
||||
for layer_name, previous_cache in previous_adapter_caches.items():
|
||||
self._kv_cache_layer_adapters[layer_name].kv_cache = previous_cache
|
||||
raise
|
||||
@@ -591,7 +593,7 @@ class DiffusionKVModelRunnerBackend:
|
||||
)
|
||||
raise RuntimeError(f"Diffusion KV request state is missing logical length for {identity!r}")
|
||||
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str]) -> int:
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str | tuple[str, int]]) -> int:
|
||||
"""Retire Worker rows without logically freeing Scheduler-owned blocks."""
|
||||
if (
|
||||
not is_scheduler_paged_kv_mode(
|
||||
@@ -600,11 +602,25 @@ class DiffusionKVModelRunnerBackend:
|
||||
or self.block_tables is None
|
||||
):
|
||||
return 0
|
||||
request_id_set = set(request_ids)
|
||||
request_generations = {
|
||||
request_id: generation
|
||||
for item in request_ids
|
||||
if isinstance(item, tuple)
|
||||
for request_id, generation in (item,)
|
||||
if isinstance(request_id, str) and type(generation) is int
|
||||
}
|
||||
request_id_set = {item if isinstance(item, str) else item[0] for item in request_ids}
|
||||
identities_and_rows = [
|
||||
(identity, row)
|
||||
for identity, row in self._diffusion_kv_identity_to_row.items()
|
||||
if identity[0] in request_id_set
|
||||
and (
|
||||
identity[0] not in request_generations
|
||||
or (
|
||||
(request_state := self._diffusion_kv_request_states.get(identity[0])) is not None
|
||||
and request_state.generation == request_generations[identity[0]]
|
||||
)
|
||||
)
|
||||
]
|
||||
rows = [row for _, row in identities_and_rows]
|
||||
if rows:
|
||||
@@ -620,9 +636,10 @@ class DiffusionKVModelRunnerBackend:
|
||||
]
|
||||
self._apply_rows(rows, installs)
|
||||
|
||||
removed_request_ids = {identity[0] for identity, _ in identities_and_rows}
|
||||
for identity, _ in identities_and_rows:
|
||||
del self._diffusion_kv_identity_to_row[identity]
|
||||
for request_id in request_id_set:
|
||||
for request_id in removed_request_ids:
|
||||
self._diffusion_kv_request_states.pop(request_id, None)
|
||||
self._diffusion_kv_free_rows.extend(rows)
|
||||
self._diffusion_kv_free_rows.sort(reverse=True)
|
||||
|
||||
@@ -84,12 +84,14 @@ class DiffusionPagedAttentionLayerAdapter(AttentionLayerBase):
|
||||
attention_config = vllm_config.attention_config
|
||||
previous_backend = attention_config.backend
|
||||
previous_backend_per_kind = attention_config.backend_per_kind
|
||||
previous_pcp_size = vllm_config.parallel_config.prefill_context_parallel_size
|
||||
try:
|
||||
# This is a portable vLLM backend request. The active platform
|
||||
# resolves it to its native implementation, such as FlashAttention
|
||||
# on CUDA or AscendAttentionBackend on NPU.
|
||||
attention_config.backend = AttentionBackendEnum.FLASH_ATTN
|
||||
attention_config.backend_per_kind = {}
|
||||
vllm_config.parallel_config.prefill_context_parallel_size = 1
|
||||
with set_current_vllm_config(vllm_config):
|
||||
attn_backend = get_attn_backend(
|
||||
head_size=spec.head_size,
|
||||
@@ -101,6 +103,7 @@ class DiffusionPagedAttentionLayerAdapter(AttentionLayerBase):
|
||||
finally:
|
||||
attention_config.backend = previous_backend
|
||||
attention_config.backend_per_kind = previous_backend_per_kind
|
||||
vllm_config.parallel_config.prefill_context_parallel_size = previous_pcp_size
|
||||
attn_backend = current_omni_platform.get_diffusion_paged_kv_attn_backend(
|
||||
attn_backend,
|
||||
ulysses_degree=ulysses_degree,
|
||||
@@ -758,6 +761,19 @@ class DiffusionPagedAttentionAdapter:
|
||||
slot_mappings=slot_mappings,
|
||||
causal=(row_segments[0].mode == "causal"),
|
||||
)
|
||||
# FA2's ``num_splits=0`` auto policy selects SplitKV for these
|
||||
# already-small piecewise calls. Reuse vLLM's supported metadata
|
||||
# control to select the single-pass kernel and avoid its extra
|
||||
# partial-output/reduction work. Leave newer native backends and
|
||||
# metadata without this control untouched.
|
||||
for layer_name, native_metadata in segment_metadata.items():
|
||||
layer = self.layers.get(layer_name)
|
||||
if (
|
||||
layer is not None
|
||||
and getattr(layer.impl, "vllm_flash_attn_version", None) == 2
|
||||
and hasattr(native_metadata, "max_num_splits")
|
||||
):
|
||||
native_metadata.max_num_splits = 1
|
||||
# FA3's full-CUDA-graph metadata builder reuses one persistent
|
||||
# scheduler buffer across builds. Piecewise attention prepares all
|
||||
# segments before executing any of them, so each segment needs its
|
||||
@@ -901,9 +917,17 @@ class DiffusionPagedAttentionAdapter:
|
||||
raise KeyError(
|
||||
f"No piecewise native attention metadata was built for diffusion layer {layer_name!r}"
|
||||
) from exc
|
||||
# Identical rows are sliced and packed once per segment by the
|
||||
# homogeneous piecewise runner. Keeping the projection view here
|
||||
# avoids first copying the complete Q tensor only to copy each segment
|
||||
# again immediately afterwards. Other native paths still require one
|
||||
# packed query buffer.
|
||||
query_input = query_flat
|
||||
if piecewise_plan is None or piecewise_plan.homogeneous_batch_shape is None:
|
||||
query_input = query_flat.contiguous()
|
||||
return DiffusionPagedAttentionContext(
|
||||
layer=layer,
|
||||
query=query_flat.contiguous(),
|
||||
query=query_input,
|
||||
key_write=key_flat,
|
||||
value_write=value_flat,
|
||||
slot_mapping=slot_mapping,
|
||||
|
||||
@@ -113,8 +113,6 @@ class DiffusionKVRequest:
|
||||
self.shared_prefix_boundary = 0
|
||||
# Opaque request-scoped parameters consumed by an upstream KVConnector.
|
||||
self.kv_transfer_params = kv_transfer_params
|
||||
# Mooncake derives the remote-load length from this list. PR0 carries
|
||||
# the field without creating a placeholder or starting a load.
|
||||
self.prompt_token_ids = prompt_token_ids
|
||||
|
||||
@property
|
||||
|
||||
@@ -505,22 +505,8 @@ class WanDistCausalConv3d(nn.Conv3d):
|
||||
self._trim_cache: dict[int, tuple[int, int, int]] = {}
|
||||
|
||||
def forward(self, x: torch.Tensor, cache_x: torch.Tensor | None = None) -> torch.Tensor:
|
||||
padding = list(self._padding)
|
||||
if cache_x is not None and padding[4] > 0:
|
||||
cache_x = cache_x.to(x.device)
|
||||
x = torch.cat([cache_x, x], dim=2)
|
||||
padding[4] -= cache_x.shape[2]
|
||||
|
||||
x = F.pad(x, padding)
|
||||
x_padded, self._halo_recv_top_buf, self._halo_recv_bottom_buf = halo_exchange(
|
||||
x,
|
||||
group=self.group,
|
||||
halo_size=self.halo_size,
|
||||
split_dim=self.split_dim,
|
||||
recv_top_buf=self._halo_recv_top_buf,
|
||||
recv_bottom_buf=self._halo_recv_bottom_buf,
|
||||
)
|
||||
shift, start, upper_bound = self._get_trim_params(x.shape[self.split_tensor_dim])
|
||||
x_padded, local_extent = self._assemble_input(x, cache_x)
|
||||
shift, start, upper_bound = self._get_trim_params(local_extent)
|
||||
if shift:
|
||||
x_padded = _narrow_along_dim(
|
||||
x_padded,
|
||||
@@ -532,6 +518,83 @@ class WanDistCausalConv3d(nn.Conv3d):
|
||||
out = _trim_local_conv_output(out, self.halo_size, start, upper_bound, split_dim=self.split_dim)
|
||||
return _zero_invalid_extent(out, split_dim=self.split_dim)
|
||||
|
||||
def _assemble_input(self, x: torch.Tensor, cache_x: torch.Tensor | None) -> tuple[torch.Tensor, int]:
|
||||
"""Build the conv input -- cached frames, causal/spatial zero padding and the halo columns -- in one pass.
|
||||
|
||||
The straightforward version wrote the activation three times per call: ``torch.cat`` of the cached
|
||||
frames, ``F.pad`` for the causal and spatial zeros, then another ``torch.cat`` to attach the halos the
|
||||
neighbours sent. Every causal conv of the decoder runs this on every latent frame, so at 480x832 that
|
||||
was the largest single source of memory traffic in the decode. Here the final tensor is allocated once
|
||||
and the cached frames and the new frames are copied straight into their slots; only the padding slices
|
||||
are zeroed. The halo rows are exchanged through contiguous send and receive buffers (a P2P op needs a
|
||||
contiguous tensor and the halo slot of a 5D tensor is a strided view) and copied into their slots. The
|
||||
conv sees the same tensor as before, byte for byte.
|
||||
|
||||
Returns the assembled tensor and the extent along the split dimension the trim parameters are keyed by
|
||||
(the extent before halos, as ``halo_exchange`` saw it).
|
||||
"""
|
||||
pad_w0, pad_w1, pad_h0, pad_h1, pad_t0, pad_t1 = self._padding
|
||||
cache_frames = 0
|
||||
if cache_x is not None and pad_t0 > 0:
|
||||
cache_x = cache_x.to(x.device)
|
||||
cache_frames = int(cache_x.shape[2])
|
||||
pad_t0 -= cache_frames
|
||||
assert pad_t0 >= 0, "Wan temporal cache exceeds the causal padding"
|
||||
rank, world_size = _rank_world(self.group)
|
||||
halo = self.halo_size if world_size > 1 else 0
|
||||
halo_h = halo if self.split_dim == "height" else 0
|
||||
halo_w = halo if self.split_dim == "width" else 0
|
||||
|
||||
batch, channels, frames, height, width = x.shape
|
||||
top, left = pad_h0 + halo_h, pad_w0 + halo_w
|
||||
total_frames = pad_t0 + cache_frames + frames + pad_t1
|
||||
total_height = top + height + pad_h1 + halo_h
|
||||
total_width = left + width + pad_w1 + halo_w
|
||||
buf = torch.empty((batch, channels, total_frames, total_height, total_width), dtype=x.dtype, device=x.device)
|
||||
# Zero only what the conv must read as zeros: the causal frames in
|
||||
# front (and any trailing ones) and the spatial padding rows/columns.
|
||||
# The halo columns are filled below.
|
||||
if pad_t0:
|
||||
buf[:, :, :pad_t0].zero_()
|
||||
if pad_t1:
|
||||
buf[:, :, total_frames - pad_t1 :].zero_()
|
||||
if pad_h0:
|
||||
buf[:, :, :, halo_h:top].zero_()
|
||||
if pad_h1:
|
||||
buf[:, :, :, total_height - halo_h - pad_h1 : total_height - halo_h].zero_()
|
||||
if pad_w0:
|
||||
buf[:, :, :, :, halo_w:left].zero_()
|
||||
if pad_w1:
|
||||
buf[:, :, :, :, total_width - halo_w - pad_w1 : total_width - halo_w].zero_()
|
||||
interior = buf[:, :, pad_t0 : pad_t0 + cache_frames + frames, top : top + height, left : left + width]
|
||||
if cache_frames:
|
||||
interior[:, :, :cache_frames].copy_(cache_x)
|
||||
interior[:, :, cache_frames:].copy_(x)
|
||||
else:
|
||||
interior.copy_(x)
|
||||
|
||||
dim = self.split_tensor_dim
|
||||
local_extent = buf.shape[dim] - 2 * halo
|
||||
if halo:
|
||||
# What halo_exchange sends: the padded tensor's first and last
|
||||
# ``halo`` rows along the split dimension, padding included.
|
||||
top_row_ref = _narrow_along_dim(buf, dim, halo, halo)
|
||||
bottom_row_ref = _narrow_along_dim(buf, dim, buf.shape[dim] - 2 * halo, halo)
|
||||
self._halo_recv_top_buf = _ensure_recv_buf(self._halo_recv_top_buf, top_row_ref)
|
||||
self._halo_recv_bottom_buf = _ensure_recv_buf(self._halo_recv_bottom_buf, bottom_row_ref)
|
||||
_halo_exchange_p2p(
|
||||
rank=rank,
|
||||
world_size=world_size,
|
||||
group=self.group,
|
||||
top_row_ref=top_row_ref,
|
||||
bottom_row_ref=bottom_row_ref,
|
||||
recv_top_buf=self._halo_recv_top_buf,
|
||||
recv_bottom_buf=self._halo_recv_bottom_buf,
|
||||
)
|
||||
_narrow_along_dim(buf, dim, 0, halo).copy_(self._halo_recv_top_buf)
|
||||
_narrow_along_dim(buf, dim, buf.shape[dim] - halo, halo).copy_(self._halo_recv_bottom_buf)
|
||||
return buf, local_extent
|
||||
|
||||
def _get_trim_params(self, local_extent: int) -> tuple[int, int, int]:
|
||||
trim_params = self._trim_cache.get(local_extent)
|
||||
if trim_params is None:
|
||||
|
||||
@@ -438,6 +438,17 @@ def init_distributed_environment(
|
||||
"world group already initialized with a different world size"
|
||||
)
|
||||
|
||||
# Now, initialize vLLM's distributed environment; we need to do this before initializing
|
||||
# model parallel in Omni. Otherwise, if we use vLLM's native coordinator, we may run into
|
||||
# issues with _NODE_COUNT / _WORLD (in vLLM, not the Omni _WORLD var above) being unset.
|
||||
vllm_parallel_state.init_distributed_environment(
|
||||
world_size=world_size,
|
||||
rank=rank,
|
||||
distributed_init_method=distributed_init_method,
|
||||
local_rank=local_rank,
|
||||
backend=backend,
|
||||
)
|
||||
|
||||
|
||||
def model_parallel_is_initialized():
|
||||
"""Check if tensor and pipeline parallel groups are initialized."""
|
||||
@@ -1061,8 +1072,8 @@ def destroy_distributed_environment():
|
||||
if _WORLD:
|
||||
_WORLD.destroy()
|
||||
_WORLD = None
|
||||
if torch.distributed.is_initialized():
|
||||
torch.distributed.destroy_process_group()
|
||||
# We only need to destroy / clear the Omni world; this takes care of the torch process groups
|
||||
vllm_parallel_state.destroy_distributed_environment()
|
||||
|
||||
|
||||
def destroy_distributed_env():
|
||||
|
||||
@@ -15,6 +15,7 @@ if TYPE_CHECKING:
|
||||
MASTER_PORT: int | None = None
|
||||
CUDA_HOME: str | None = None
|
||||
LOCAL_RANK: int = 0
|
||||
VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS: str | None = None
|
||||
|
||||
environment_variables: dict[str, Callable[[], Any]] = {
|
||||
# ================== Runtime Env Vars ==================
|
||||
@@ -28,6 +29,11 @@ environment_variables: dict[str, Callable[[], Any]] = {
|
||||
# local rank of the process in the distributed setting, used to determine
|
||||
# the GPU device id
|
||||
"LOCAL_RANK": lambda: int(os.environ.get("LOCAL_RANK", "0")),
|
||||
# Minimum rotary-table span (B*S positions) at which consumers of the shared
|
||||
# fused_qk_norm_rope op take the fused path instead of their eager chain;
|
||||
# "0" = always fuse; unset = each consumer's own measured default. Raw
|
||||
# string or None; validated by fused_qk_norm_rope_min_tokens().
|
||||
"VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS": lambda: os.environ.get("VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS", None),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheSpec
|
||||
from vllm.v1.outputs import KVConnectorOutput
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.sched.interface import CachedRequestData
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
@@ -159,7 +165,7 @@ class DiffusionExecutor(ABC):
|
||||
# ranks are not silently dropped.
|
||||
self.collective_rpc("set_kv_cache_configs", args=(kv_cache_configs, resolved_max_model_len))
|
||||
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str]) -> None:
|
||||
def remove_diffusion_kv_requests(self, request_ids: list[str | tuple[str, int]]) -> None:
|
||||
"""Clear request rows on every Worker after Scheduler retirement."""
|
||||
|
||||
unique_request_ids = list(dict.fromkeys(request_ids))
|
||||
@@ -170,6 +176,35 @@ class DiffusionExecutor(ABC):
|
||||
args=(unique_request_ids,),
|
||||
)
|
||||
|
||||
def prepare_kv_for_forward(self, scheduler_output: DiffusionSchedulerOutput) -> KVConnectorOutput | None:
|
||||
if scheduler_output.kv_connector_metadata is None:
|
||||
return
|
||||
transfer_output = replace(
|
||||
scheduler_output,
|
||||
scheduled_new_reqs=[],
|
||||
scheduled_cached_reqs=CachedRequestData.make_empty(),
|
||||
kv_prefetch_job=None,
|
||||
)
|
||||
outputs: list[KVConnectorOutput] = self.collective_rpc(
|
||||
"prepare_kv_for_forward",
|
||||
args=(transfer_output,),
|
||||
unique_reply_rank=0,
|
||||
exec_all_ranks=True,
|
||||
)
|
||||
if len(outputs) != self.od_config.num_gpus or any(output.invalid_block_ids for output in outputs):
|
||||
# Missing ranks / invalid pages cannot establish safe ownership.
|
||||
raise RuntimeError("Diffusion KV receive failed on one or more ranks")
|
||||
completed = getattr(self, "_kv_receive_completed_ranks", {})
|
||||
for rank, output in enumerate(outputs):
|
||||
for request_id in output.finished_recving or ():
|
||||
completed.setdefault(request_id, set()).add(rank)
|
||||
finished = {request_id for request_id, ranks in completed.items() if len(ranks) == len(outputs)}
|
||||
for request_id in finished:
|
||||
del completed[request_id]
|
||||
self._kv_receive_completed_ranks = completed
|
||||
outputs[0].finished_recving = finished
|
||||
return outputs[0]
|
||||
|
||||
@abstractmethod
|
||||
def shutdown(self) -> None:
|
||||
"""Shutdown the executor and release resources."""
|
||||
|
||||
@@ -13,7 +13,7 @@ import threading
|
||||
import time
|
||||
import weakref
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from multiprocessing.process import BaseProcess
|
||||
from multiprocessing.synchronize import Event
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
@@ -46,6 +46,7 @@ _DEQUEUE_TIMEOUT_S = 5.0
|
||||
_DLO_DP_WAVE_TIMEOUT_S = float(os.environ.get("VLLM_OMNI_DLO_DP_WAVE_TIMEOUT", 600.0))
|
||||
_WORKER_SHUTDOWN_GRACE_S = 15.0
|
||||
_WORKER_TERMINATE_GRACE_S = 5.0
|
||||
_WORKER_KILL_GRACE_S = 5.0
|
||||
_RESULT_PUMP_JOIN_TIMEOUT_S = 2.0
|
||||
|
||||
|
||||
@@ -83,34 +84,62 @@ class _ExecutorShutdownCleaner:
|
||||
|
||||
broadcast_mq: MessageQueue | None = None
|
||||
num_workers: int = 0
|
||||
processes: list[BaseProcess] | None = None
|
||||
processes: list[mp.Process] | None = None
|
||||
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
|
||||
|
||||
def __call__(self) -> None:
|
||||
"""Clean up background resources."""
|
||||
# The worker monitor and an explicit shutdown may race. A retry must
|
||||
# not signal/join the same Process objects while cleanup is in flight.
|
||||
if not self._lock.acquire(blocking=False):
|
||||
return
|
||||
try:
|
||||
self._cleanup()
|
||||
finally:
|
||||
self._lock.release()
|
||||
|
||||
def _cleanup(self) -> None:
|
||||
if self.broadcast_mq is not None:
|
||||
try:
|
||||
for _ in range(self.num_workers):
|
||||
self.broadcast_mq.enqueue(SHUTDOWN_MESSAGE, timeout=1.0)
|
||||
|
||||
self.broadcast_mq = None
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to send shutdown signal: %s", exc)
|
||||
finally:
|
||||
self.broadcast_mq = None
|
||||
|
||||
if self.processes:
|
||||
join_deadline = time.monotonic() + _WORKER_SHUTDOWN_GRACE_S
|
||||
for proc in self.processes:
|
||||
if not proc.is_alive():
|
||||
continue
|
||||
proc.join(max(0.0, join_deadline - time.monotonic()))
|
||||
|
||||
alive = [proc for proc in self.processes if proc.is_alive()]
|
||||
for proc in alive:
|
||||
logger.warning("Terminating diffusion worker %s after timeout", proc.name)
|
||||
proc.terminate()
|
||||
for action, grace in (
|
||||
(None, _WORKER_SHUTDOWN_GRACE_S),
|
||||
("terminate", _WORKER_TERMINATE_GRACE_S),
|
||||
("kill", _WORKER_KILL_GRACE_S),
|
||||
):
|
||||
if not alive:
|
||||
break
|
||||
if action is not None:
|
||||
for proc in alive:
|
||||
try:
|
||||
logger.warning("Calling %s on diffusion worker %s (pid=%s)", action, proc.name, proc.pid)
|
||||
getattr(proc, action)()
|
||||
except OSError:
|
||||
logger.exception("Failed to %s diffusion worker %s (pid=%s)", action, proc.name, proc.pid)
|
||||
|
||||
terminate_deadline = time.monotonic() + _WORKER_TERMINATE_GRACE_S
|
||||
for proc in alive:
|
||||
proc.join(max(0.0, terminate_deadline - time.monotonic()))
|
||||
deadline = time.monotonic() + grace
|
||||
for proc in alive:
|
||||
try:
|
||||
proc.join(max(0.0, deadline - time.monotonic()))
|
||||
except OSError:
|
||||
logger.exception("Failed to join diffusion worker %s (pid=%s)", proc.name, proc.pid)
|
||||
alive = [proc for proc in alive if proc.is_alive()]
|
||||
|
||||
self.processes = alive
|
||||
if alive:
|
||||
logger.error(
|
||||
"Diffusion worker cleanup incomplete after kill: %s; retaining processes for shutdown retry",
|
||||
[(proc.name, proc.pid) for proc in alive],
|
||||
)
|
||||
|
||||
|
||||
class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
@@ -1010,8 +1039,12 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
def shutdown(self) -> None:
|
||||
self._closed = True
|
||||
self._pump_stop.set()
|
||||
cleaner = self._shutdown_cleaner
|
||||
try:
|
||||
self._finalizer()
|
||||
if self._finalizer.alive:
|
||||
self._finalizer()
|
||||
elif cleaner is not None:
|
||||
cleaner()
|
||||
finally:
|
||||
pump_threads = getattr(self, "_result_pump_threads", [])
|
||||
for thread in pump_threads:
|
||||
@@ -1035,5 +1068,6 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
self._rpc_futures.clear()
|
||||
self._output_futures.clear()
|
||||
self._batch_split_map.clear()
|
||||
self._shutdown_cleaner = None
|
||||
self._processes = []
|
||||
self._processes = (cleaner.processes or []) if cleaner is not None else []
|
||||
if not self._processes:
|
||||
self._shutdown_cleaner = None
|
||||
@@ -282,6 +282,47 @@ def set_forward_context_denoise_step_idx(step_idx: int | None) -> None:
|
||||
ensure_active(step_idx)
|
||||
|
||||
|
||||
def get_paged_kv_computed_tokens() -> tuple[int, ...]:
|
||||
runtime = _forward_context.paged_kv_runtime if _forward_context is not None else None
|
||||
if runtime is None:
|
||||
return ()
|
||||
return tuple(row.kv_start_pos for row in runtime.metadata.prefill_rows)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def paged_kv_prefill(sequence_id: int, num_tokens: int):
|
||||
from dataclasses import replace
|
||||
|
||||
runtime = get_forward_context().paged_kv_runtime
|
||||
if runtime is None:
|
||||
raise RuntimeError("Paged KV prefill requires an active runtime")
|
||||
rows = runtime.metadata.prefill_rows
|
||||
matching_rows = [row for row in rows if row.sequence_id == sequence_id]
|
||||
if len(matching_rows) != 1:
|
||||
raise ValueError(
|
||||
f"Paged KV prefill requires exactly one active row for sequence {sequence_id}; found {len(matching_rows)}"
|
||||
)
|
||||
row = matching_rows[0]
|
||||
if type(num_tokens) is not int or not row.kv_start_pos < num_tokens <= row.seq_len:
|
||||
raise ValueError(
|
||||
"Paged KV prefill target must extend the active prefix without exceeding its allocation: "
|
||||
f"start={row.kv_start_pos}, target={num_tokens!r}, allocated={row.seq_len}"
|
||||
)
|
||||
prefill = replace(row, query_len=num_tokens - row.kv_start_pos, seq_len=num_tokens)
|
||||
batch = runtime.adapter.prepare_batch((prefill,))
|
||||
with runtime.adapter.activate(batch):
|
||||
yield
|
||||
runtime.metadata = replace(
|
||||
runtime.metadata,
|
||||
prefill_rows=tuple(
|
||||
replace(item, kv_start_pos=num_tokens, query_len=item.seq_len - num_tokens)
|
||||
if item.sequence_id == sequence_id
|
||||
else item
|
||||
for item in rows
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def set_forward_context_denoise_timestep(timestep: float | None) -> None:
|
||||
"""Set the normalized (descending, 1 -> 0) denoise timestep.
|
||||
|
||||
|
||||
@@ -19,7 +19,10 @@ from typing import TYPE_CHECKING, Any
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionRequestAbortedError
|
||||
from vllm_omni.diffusion.data import (
|
||||
DiffusionRequestAbortedError,
|
||||
is_diffusion_request_started_output,
|
||||
)
|
||||
from vllm_omni.diffusion.diffusion_engine import DiffusionEngine
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.engine.stage_client import StageClientBase
|
||||
@@ -158,7 +161,13 @@ class InlineStageDiffusionClient(StageClientBase):
|
||||
# only publish the final output.
|
||||
result = None
|
||||
async for results in self._engine.step_streaming(request):
|
||||
result = results[0]
|
||||
output = results[0]
|
||||
if is_diffusion_request_started_output(output):
|
||||
if not output.request_id:
|
||||
output.request_id = request_id
|
||||
self._output_queue.put_nowait(output)
|
||||
continue
|
||||
result = output
|
||||
if result is None:
|
||||
raise RuntimeError("Diffusion execution finished without output.")
|
||||
if not result.request_id:
|
||||
|
||||
@@ -11,8 +11,9 @@ from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionPayload,
|
||||
merge_interaction_metadata,
|
||||
synchronized_monotonic_time,
|
||||
)
|
||||
from vllm_omni.diffusion.models.interface import supports_interaction_apply
|
||||
from vllm_omni.diffusion.models.interface import SupportsInteractionApply, supports_interaction_apply
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -52,7 +53,7 @@ class InteractionCoordinator:
|
||||
|
||||
@property
|
||||
def needs_chunk_media(self) -> bool:
|
||||
"""Whether any registered handler needs chunk ``num_frames``/``fps``."""
|
||||
"""Whether any registered handler needs chunk media/latent counts + fps."""
|
||||
return any(handler.needs_chunk_media for handler in self._handlers.values())
|
||||
|
||||
def get_handler(self, modality: str) -> InteractionHandler:
|
||||
@@ -83,31 +84,109 @@ class InteractionCoordinator:
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
|
||||
def enqueue_parts(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
parts: list[tuple[str, InteractionPayload]],
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Ensure every modality is supported and every payload validates, then enqueue.
|
||||
|
||||
Composite events must not partially mutate queues when a later track is
|
||||
unsupported or carries an invalid payload.
|
||||
"""
|
||||
if not parts:
|
||||
raise ValueError("interaction event requires prompt and/or multi_modal_data")
|
||||
|
||||
# Reconcile rank-local samples so USP/SP shards share one arrival time.
|
||||
received_at = synchronized_monotonic_time(received_at)
|
||||
|
||||
handlers = [(self.get_handler(modality), payload) for modality, payload in parts]
|
||||
for handler, payload in handlers:
|
||||
handler.validate_payload(
|
||||
state,
|
||||
event_id=event_id,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
for (modality, payload), (handler, _) in zip(parts, handlers, strict=True):
|
||||
del handler
|
||||
self.enqueue(
|
||||
state,
|
||||
modality=modality,
|
||||
event_id=event_id,
|
||||
received_at=received_at,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
|
||||
def maybe_prepare_initial_session(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
pipeline: SupportsInteractionApply,
|
||||
) -> InteractionChunkMetadata:
|
||||
"""Materialize non-lazy modality sessions before chunk 0 denoise.
|
||||
|
||||
Handlers with ``lazy_initialize_session=False`` (e.g. camera) must exist
|
||||
before the first chunk even with no client enqueue.
|
||||
"""
|
||||
num_media_frames: int | None = None
|
||||
fps: float | None = None
|
||||
num_latent_frames: int | None = None
|
||||
if any(
|
||||
(not handler.lazy_initialize_session) and handler.needs_chunk_media for handler in self._handlers.values()
|
||||
):
|
||||
media = pipeline.peek_chunk_media(state)
|
||||
num_media_frames = media.num_media_frames
|
||||
fps = media.fps
|
||||
num_latent_frames = media.num_latent_frames
|
||||
|
||||
boundary_at = synchronized_monotonic_time()
|
||||
chunk_index = state.chunk_index
|
||||
metas: list[InteractionChunkMetadata] = []
|
||||
for handler in self._handlers_in_apply_order():
|
||||
if handler.lazy_initialize_session:
|
||||
continue
|
||||
meta = handler.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=boundary_at,
|
||||
chunk_index=chunk_index,
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
if meta is not None:
|
||||
metas.append(meta)
|
||||
return merge_interaction_metadata(metas)
|
||||
|
||||
def apply_at_chunk_boundary(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | 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.
|
||||
if handler.lazy_initialize_session and handler.modality not in state.interaction_sessions:
|
||||
# Lazy modalities skip apply until the first enqueue creates the session.
|
||||
continue
|
||||
meta = handler.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=boundary_at,
|
||||
chunk_index=chunk_index,
|
||||
num_frames=num_frames,
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
if meta is not None:
|
||||
metas.append(meta)
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from vllm_omni.diffusion.interaction.types import synchronized_monotonic_time
|
||||
from vllm_omni.diffusion.models.interface import SupportsInteractionApply
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
@@ -35,18 +35,21 @@ class InteractionMixin:
|
||||
"onto the pipeline before chunked generation"
|
||||
)
|
||||
|
||||
num_frames: int | None = None
|
||||
num_media_frames: int | None = None
|
||||
fps: float | None = None
|
||||
num_latent_frames: int | None = None
|
||||
if self._interaction_coordinator.needs_chunk_media:
|
||||
media = cast(SupportsInteractionApply, self).peek_chunk_media(state)
|
||||
num_frames = media.num_frames
|
||||
num_media_frames = media.num_media_frames
|
||||
fps = media.fps
|
||||
num_latent_frames = media.num_latent_frames
|
||||
|
||||
merged = self._interaction_coordinator.apply_at_chunk_boundary(
|
||||
state,
|
||||
boundary_at=time.monotonic(),
|
||||
num_frames=num_frames,
|
||||
boundary_at=synchronized_monotonic_time(),
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
state.interaction_chunk_metadata = merged
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import ClassVar, Self
|
||||
from typing import ClassVar
|
||||
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
@@ -23,9 +25,14 @@ class InteractionHandler(ABC):
|
||||
"""
|
||||
|
||||
modality: ClassVar[str]
|
||||
# When True, chunk-boundary apply needs ``ChunkMediaSpec`` (num_frames/fps)
|
||||
# When True, chunk-boundary apply needs ``ChunkMediaSpec`` (frame count & fps)
|
||||
# Those information are useful when interaction handler needs interpolation/integration on a frame-by-frame basis
|
||||
needs_chunk_media: ClassVar[bool] = False
|
||||
# When True, the coordinator skips ``apply_at_chunk_boundary`` until a session
|
||||
# exists (normally created on the first enqueue). When False, every chunk
|
||||
# boundary runs apply even with no prior enqueue so the handler can create
|
||||
# its session and materialize default chunk data (e.g. identity camera hold).
|
||||
lazy_initialize_session: ClassVar[bool] = True
|
||||
|
||||
@classmethod
|
||||
def from_pipeline(cls, pipeline: object) -> Self:
|
||||
@@ -37,6 +44,21 @@ class InteractionHandler(ABC):
|
||||
del pipeline
|
||||
return cls()
|
||||
|
||||
@abstractmethod
|
||||
def validate_payload(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
"""Validate a modality payload without mutating request state.
|
||||
|
||||
Used by ``InteractionCoordinator.enqueue_parts`` so composite events
|
||||
fail before any track is queued.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def enqueue(
|
||||
self,
|
||||
@@ -56,7 +78,9 @@ class InteractionHandler(ABC):
|
||||
*,
|
||||
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
|
||||
# Optional chunk media information. Only present when at least one initialized interaction handler needs it
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | None = None,
|
||||
) -> InteractionChunkMetadata | None:
|
||||
"""Advance request-local state and materialize this chunk's effects."""
|
||||
@@ -0,0 +1,490 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Camera modality interaction handlers.
|
||||
|
||||
Payload is structural SE(3): ``translation`` (xyz) + unit
|
||||
quaternion ``rotation`` (x, y, z, w). WASD-style key tokens belong in
|
||||
clients, not in the engine.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import ClassVar, cast
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self, override
|
||||
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.base import InteractionHandler
|
||||
from vllm_omni.diffusion.interaction.types import (
|
||||
InteractionChunkMetadata,
|
||||
InteractionEvent,
|
||||
InteractionMode,
|
||||
InteractionPayload,
|
||||
InteractionSession,
|
||||
resolve_event_frame_offset,
|
||||
)
|
||||
from vllm_omni.diffusion.worker.utils import StepRequestState
|
||||
|
||||
Vec3 = tuple[float, float, float]
|
||||
# Unit quaternion in ``(x, y, z, w)`` order. Identity is ``(0, 0, 0, 1)``.
|
||||
Quat = tuple[float, float, float, float]
|
||||
|
||||
_IDENTITY_QUAT: Quat = (0.0, 0.0, 0.0, 1.0)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CameraPose:
|
||||
"""Canonical absolute camera pose used by the shared timeline.
|
||||
|
||||
Coordinates follow Unity semantics: ``+X`` right, ``+Y`` up,
|
||||
``+Z`` forward. Session start is the identity transform;
|
||||
``target`` poses are relative to that origin.
|
||||
"""
|
||||
|
||||
translation: Vec3 = (0.0, 0.0, 0.0)
|
||||
rotation: Quat = _IDENTITY_QUAT
|
||||
|
||||
@classmethod
|
||||
def identity(cls) -> CameraPose:
|
||||
return cls()
|
||||
|
||||
def clone(self) -> CameraPose:
|
||||
return CameraPose(translation=self.translation, rotation=self.rotation)
|
||||
|
||||
def as_matrix(self) -> torch.Tensor:
|
||||
"""Return a 4x4 rigid transform from translation + unit quaternion."""
|
||||
mat = torch.eye(4, dtype=torch.float64)
|
||||
mat[:3, :3] = _quat_to_rotmat(self.rotation)
|
||||
mat[0, 3] = float(self.translation[0])
|
||||
mat[1, 3] = float(self.translation[1])
|
||||
mat[2, 3] = float(self.translation[2])
|
||||
return mat
|
||||
|
||||
@classmethod
|
||||
def from_matrix(cls, matrix: torch.Tensor) -> CameraPose:
|
||||
if matrix.shape != (4, 4):
|
||||
raise ValueError("camera pose matrix must be 4x4")
|
||||
rotation = _rotmat_to_quat(matrix[:3, :3].detach().cpu().double())
|
||||
translation = (
|
||||
float(matrix[0, 3]),
|
||||
float(matrix[1, 3]),
|
||||
float(matrix[2, 3]),
|
||||
)
|
||||
return cls(translation=translation, rotation=rotation)
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
class QueuedCameraEvent(InteractionEvent):
|
||||
"""Timestamped camera command waiting for the next chunk boundary."""
|
||||
|
||||
# Absolute pose for ``target``; per-frame SE3 delta for ``velocity``.
|
||||
pose: CameraPose = field(default_factory=CameraPose.identity)
|
||||
# Integer frame progress for ``target`` lerps (avoids float reciprocal drift).
|
||||
elapsed_transition_frames: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class CameraSession(InteractionSession):
|
||||
"""Request-local camera timeline under ``state.interaction_sessions['camera']``."""
|
||||
|
||||
current_pose: CameraPose = field(default_factory=CameraPose.identity)
|
||||
pending_events: list[QueuedCameraEvent] = field(default_factory=list)
|
||||
# In-flight command; ``elapsed_transition_chunks`` lives on the event.
|
||||
active_event: QueuedCameraEvent | None = None
|
||||
target_source: CameraPose | None = None
|
||||
# Absolute C2W poses ``[num_latent_frames, 4, 4]`` for the most recent chunk.
|
||||
last_absolute_poses: torch.Tensor | None = None
|
||||
# Since a camera session is not lazily initialized, use this field to mark that a client enqueue is ever received.
|
||||
has_received_input: bool = False
|
||||
|
||||
|
||||
class SE3DeltaCameraHandler(InteractionHandler):
|
||||
"""Generic camera timeline that samples absolute poses per frame.
|
||||
|
||||
* ``mode=target``: lerp toward an absolute pose (relative to session start).
|
||||
* ``mode=velocity``: hold a structural SE3 delta until replaced.
|
||||
|
||||
``received_at`` is resolved on the media grid (``num_media_frames``/``fps``), then mapped onto latent steps.
|
||||
Later integration and ``last_absolute_poses`` aligns with ``num_latent_frames``.
|
||||
"""
|
||||
|
||||
modality: ClassVar[str] = "camera"
|
||||
needs_chunk_media: ClassVar[bool] = True
|
||||
# Camera conditioning must exist every chunk; apply creates the session and
|
||||
# materializes identity/hold poses before any client enqueue.
|
||||
lazy_initialize_session: ClassVar[bool] = False
|
||||
default_transition_chunks: ClassVar[int] = 1
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_pipeline(cls, pipeline: object) -> Self:
|
||||
"""It doesn't need anything from the pipeline (e.g., `encode_prompt` method)"""
|
||||
del pipeline
|
||||
return cls()
|
||||
|
||||
@override
|
||||
def validate_payload(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
if not event_id:
|
||||
raise ValueError("event_id must be non-empty")
|
||||
|
||||
mode = payload.get("mode", "target")
|
||||
if mode not in ("target", "velocity"):
|
||||
raise ValueError("camera mode must be 'target' or 'velocity'")
|
||||
data = payload.get("data")
|
||||
if not isinstance(data, Mapping):
|
||||
raise ValueError("camera data must be an object")
|
||||
if "actions" in data:
|
||||
raise ValueError(
|
||||
"camera data.actions (WASD keys) is not accepted by the engine; "
|
||||
"send structural translation/rotation instead"
|
||||
)
|
||||
_parse_pose(data)
|
||||
if mode == "target":
|
||||
duration = self.default_transition_chunks if transition_chunks is None else int(transition_chunks)
|
||||
if duration < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
del state
|
||||
|
||||
@override
|
||||
def enqueue(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
event_id: str,
|
||||
received_at: float,
|
||||
payload: InteractionPayload,
|
||||
transition_chunks: int | None,
|
||||
) -> None:
|
||||
self.validate_payload(
|
||||
state,
|
||||
event_id=event_id,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
mode = payload.get("mode", "target")
|
||||
camera_mode = cast(InteractionMode, mode)
|
||||
data = cast(Mapping[str, object], payload.get("data"))
|
||||
pose = _parse_pose(data)
|
||||
if camera_mode == "target":
|
||||
duration = self.default_transition_chunks if transition_chunks is None else int(transition_chunks)
|
||||
else:
|
||||
duration = 0
|
||||
|
||||
session = state.interaction_sessions.setdefault("camera", CameraSession())
|
||||
assert isinstance(session, CameraSession)
|
||||
with session.lock:
|
||||
session.has_received_input = True
|
||||
session.pending_events.append(
|
||||
QueuedCameraEvent(
|
||||
event_id=event_id,
|
||||
received_at=received_at,
|
||||
mode=camera_mode,
|
||||
transition_chunks=duration,
|
||||
pose=pose,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
def apply_at_chunk_boundary(
|
||||
self,
|
||||
state: StepRequestState,
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | None = None,
|
||||
) -> InteractionChunkMetadata | None:
|
||||
"""Advance camera state for one chunk and store latent-aligned poses.
|
||||
|
||||
.. note::
|
||||
Hardcoded the following policy of per-frame alignment:
|
||||
|
||||
- Resolve ``received_at`` on the media grid, then map each media index onto a latent step.
|
||||
- Integrate one velocity step per **latent frame**, so holding speed ``0.05`` for a chunk with
|
||||
``num_latent_frames=3`` yields total travel ``0.15``.
|
||||
- ``last_absolute_poses.shape[0] == num_latent_frames``: interpolation is latent-aligned.
|
||||
|
||||
If future models need different scale/alignment policies, can refactor interaction registry
|
||||
to be able to mark a policy.
|
||||
"""
|
||||
del chunk_index
|
||||
if num_media_frames is None or fps is None:
|
||||
raise ValueError("SE3DeltaCameraHandler requires chunk num_media_frames and fps")
|
||||
if num_latent_frames is None:
|
||||
num_latent_frames = num_media_frames
|
||||
if int(num_latent_frames) <= 0:
|
||||
raise ValueError(f"num_latent_frames must be > 0, got {num_latent_frames}")
|
||||
|
||||
session = state.interaction_sessions.setdefault("camera", CameraSession())
|
||||
assert isinstance(session, CameraSession)
|
||||
with session.lock:
|
||||
poses, started, active, completed = self._step_one_chunk(
|
||||
session,
|
||||
num_media_frames=num_media_frames,
|
||||
fps=fps,
|
||||
num_latent_frames=num_latent_frames,
|
||||
boundary_at=boundary_at,
|
||||
)
|
||||
if poses:
|
||||
session.last_absolute_poses = torch.stack([p.as_matrix() for p in poses], dim=0)
|
||||
else:
|
||||
session.last_absolute_poses = torch.zeros((0, 4, 4), dtype=torch.float64)
|
||||
|
||||
return InteractionChunkMetadata(
|
||||
started_event_ids=started,
|
||||
active_event_ids=active,
|
||||
completed_event_ids=completed,
|
||||
)
|
||||
|
||||
def _step_one_chunk(
|
||||
self,
|
||||
session: CameraSession,
|
||||
*,
|
||||
num_media_frames: int,
|
||||
fps: float,
|
||||
num_latent_frames: int,
|
||||
boundary_at: float,
|
||||
) -> tuple[list[CameraPose], list[str], list[str], list[str]]:
|
||||
"""Sample absolute poses for this chunk under target/velocity semantics."""
|
||||
num_media_frames = max(int(num_media_frames), 1)
|
||||
num_latent_frames = max(int(num_latent_frames), 1)
|
||||
pending = list(session.pending_events)
|
||||
session.pending_events.clear()
|
||||
|
||||
by_latent: dict[int, list[QueuedCameraEvent]] = {}
|
||||
for event in pending:
|
||||
media_frame = resolve_event_frame_offset(
|
||||
received_at=event.received_at,
|
||||
previous_boundary_at=session.last_boundary_at,
|
||||
num_frames=num_media_frames,
|
||||
fps=fps,
|
||||
)
|
||||
latent_idx = _media_frame_to_latent(
|
||||
media_frame,
|
||||
num_media_frames=num_media_frames,
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
by_latent.setdefault(latent_idx, []).append(event)
|
||||
for events in by_latent.values():
|
||||
events.sort(key=lambda item: item.received_at)
|
||||
|
||||
started: list[str] = []
|
||||
completed: list[str] = []
|
||||
seen_completed: set[str] = set()
|
||||
poses: list[CameraPose] = []
|
||||
|
||||
def _mark_completed(event_id: str) -> None:
|
||||
if event_id not in seen_completed:
|
||||
seen_completed.add(event_id)
|
||||
completed.append(event_id)
|
||||
|
||||
for latent_idx in range(num_latent_frames):
|
||||
for event in by_latent.get(latent_idx, []):
|
||||
started.append(event.event_id)
|
||||
cancelled_id = self._activate_event(session, event)
|
||||
if cancelled_id is not None:
|
||||
_mark_completed(cancelled_id)
|
||||
just_completed = self._step_one_frame(session, num_latent_frames)
|
||||
poses.append(session.current_pose.clone())
|
||||
if just_completed is not None:
|
||||
_mark_completed(just_completed)
|
||||
|
||||
active: list[str] = []
|
||||
if session.active_event is not None:
|
||||
active.append(session.active_event.event_id)
|
||||
|
||||
session.last_boundary_at = boundary_at
|
||||
return poses, started, active, completed
|
||||
|
||||
def _activate_event(self, session: CameraSession, event: QueuedCameraEvent) -> str | None:
|
||||
"""Activate ``event``, returning the event_id cancelled by this replacement if any."""
|
||||
cancelled_id: str | None = None
|
||||
if session.active_event is not None and session.active_event.event_id != event.event_id:
|
||||
cancelled_id = session.active_event.event_id
|
||||
|
||||
event.elapsed_transition_chunks = 0.0
|
||||
event.elapsed_transition_frames = 0
|
||||
session.active_event = event
|
||||
if event.mode == "target":
|
||||
session.target_source = session.current_pose.clone()
|
||||
else:
|
||||
session.target_source = None
|
||||
return cancelled_id
|
||||
|
||||
def _clear_active_target(self, session: CameraSession) -> str:
|
||||
"""Snap to the target pose, clear the active target track, and return its event_id."""
|
||||
assert session.active_event is not None and session.active_event.mode == "target"
|
||||
event = session.active_event
|
||||
event_id = event.event_id
|
||||
session.current_pose = event.pose.clone()
|
||||
session.active_event = None
|
||||
session.target_source = None
|
||||
return event_id
|
||||
|
||||
def _step_one_frame(self, session: CameraSession, total_num_frames_this_chunk: int) -> str | None:
|
||||
"""Advance the active camera command by one frame."""
|
||||
event = session.active_event
|
||||
if event is None:
|
||||
return None
|
||||
|
||||
if event.mode == "target":
|
||||
duration = event.transition_chunks
|
||||
source = session.target_source or session.current_pose
|
||||
target = event.pose
|
||||
if duration <= 0:
|
||||
return self._clear_active_target(session)
|
||||
|
||||
total_frames = max(1, int(round(duration * float(total_num_frames_this_chunk))))
|
||||
event.elapsed_transition_frames += 1
|
||||
event.elapsed_transition_chunks = event.elapsed_transition_frames / float(total_num_frames_this_chunk)
|
||||
alpha = min(1.0, event.elapsed_transition_frames / float(total_frames))
|
||||
session.current_pose = _lerp_pose(source, target, alpha)
|
||||
if event.elapsed_transition_frames >= total_frames:
|
||||
return self._clear_active_target(session)
|
||||
return None
|
||||
|
||||
# Velocity: apply the held structural SE3 delta once per frame.
|
||||
session.current_pose = _compose_pose(session.current_pose, event.pose)
|
||||
return None
|
||||
|
||||
|
||||
def _media_frame_to_latent(
|
||||
media_frame: int,
|
||||
*,
|
||||
num_media_frames: int,
|
||||
num_latent_frames: int,
|
||||
) -> int:
|
||||
"""Map a media-timeline frame index onto the latent control grid."""
|
||||
if num_latent_frames <= 1 or num_media_frames <= 1:
|
||||
return 0
|
||||
return min(int(media_frame) * int(num_latent_frames) // int(num_media_frames), num_latent_frames - 1)
|
||||
|
||||
|
||||
def _as_xyz(value: object, *, name: str) -> Vec3:
|
||||
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)) or len(value) != 3:
|
||||
raise ValueError(f"camera {name} must be a length-3 list/tuple")
|
||||
if any(math.isnan(v) or math.isinf(v) for v in value):
|
||||
raise ValueError(f"camera {name} must be non-nan and non-inf")
|
||||
return (float(value[0]), float(value[1]), float(value[2]))
|
||||
|
||||
|
||||
def _as_quat(value: object, *, name: str) -> Quat:
|
||||
if not isinstance(value, Sequence) or isinstance(value, (str, bytes)) or len(value) != 4:
|
||||
raise ValueError(f"camera {name} must be a length-4 list/tuple (x, y, z, w)")
|
||||
if any(math.isnan(v) or math.isinf(v) for v in value):
|
||||
raise ValueError(f"camera {name} must be non-nan and non-inf")
|
||||
return _quat_normalize((float(value[0]), float(value[1]), float(value[2]), float(value[3])))
|
||||
|
||||
|
||||
def _parse_pose(data: Mapping[str, object]) -> CameraPose:
|
||||
translation = _as_xyz(data.get("translation", (0.0, 0.0, 0.0)), name="translation")
|
||||
rotation = _as_quat(data.get("rotation", _IDENTITY_QUAT), name="rotation")
|
||||
return CameraPose(translation=translation, rotation=rotation)
|
||||
|
||||
|
||||
def _lerp(a: float, b: float, alpha: float) -> float:
|
||||
return a + (b - a) * alpha
|
||||
|
||||
|
||||
def _lerp_pose(source: CameraPose, target: CameraPose, alpha: float) -> CameraPose:
|
||||
alpha = min(1.0, max(0.0, alpha))
|
||||
return CameraPose(
|
||||
translation=cast(
|
||||
Vec3,
|
||||
tuple(_lerp(s, t, alpha) for s, t in zip(source.translation, target.translation)),
|
||||
),
|
||||
rotation=_quat_nlerp(source.rotation, target.rotation, alpha),
|
||||
)
|
||||
|
||||
|
||||
def _compose_pose(base: CameraPose, delta: CameraPose) -> CameraPose:
|
||||
"""Apply ``delta`` after ``base`` in the session frame (T_new = T_base @ T_delta)."""
|
||||
return CameraPose.from_matrix(base.as_matrix() @ delta.as_matrix())
|
||||
|
||||
|
||||
def _quat_normalize(q: Quat) -> Quat:
|
||||
x, y, z, w = q
|
||||
norm = math.sqrt(x * x + y * y + z * z + w * w)
|
||||
if norm <= 0.0:
|
||||
raise ValueError("camera rotation quaternion must be non-zero")
|
||||
return (x / norm, y / norm, z / norm, w / norm)
|
||||
|
||||
|
||||
def _quat_nlerp(a: Quat, b: Quat, alpha: float) -> Quat:
|
||||
"""Normalized linear interpolation; flips ``b`` when needed for shortest path."""
|
||||
dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]
|
||||
if dot < 0.0:
|
||||
b = (-b[0], -b[1], -b[2], -b[3])
|
||||
return _quat_normalize(
|
||||
(
|
||||
_lerp(a[0], b[0], alpha),
|
||||
_lerp(a[1], b[1], alpha),
|
||||
_lerp(a[2], b[2], alpha),
|
||||
_lerp(a[3], b[3], alpha),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _quat_to_rotmat(q: Quat) -> torch.Tensor:
|
||||
x, y, z, w = q
|
||||
xx, yy, zz = x * x, y * y, z * z
|
||||
xy, xz, yz = x * y, x * z, y * z
|
||||
wx, wy, wz = w * x, w * y, w * z
|
||||
return torch.tensor(
|
||||
[
|
||||
[1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy)],
|
||||
[2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx)],
|
||||
[2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy)],
|
||||
],
|
||||
dtype=torch.float64,
|
||||
)
|
||||
|
||||
|
||||
def _rotmat_to_quat(rotation: torch.Tensor) -> Quat:
|
||||
"""Convert a 3x3 rotation matrix to a unit quaternion ``(x, y, z, w)``."""
|
||||
m = rotation
|
||||
trace = float(m[0, 0] + m[1, 1] + m[2, 2])
|
||||
if trace > 0.0:
|
||||
s = math.sqrt(trace + 1.0) * 2.0
|
||||
w = 0.25 * s
|
||||
x = (float(m[2, 1]) - float(m[1, 2])) / s
|
||||
y = (float(m[0, 2]) - float(m[2, 0])) / s
|
||||
z = (float(m[1, 0]) - float(m[0, 1])) / s
|
||||
elif float(m[0, 0]) > float(m[1, 1]) and float(m[0, 0]) > float(m[2, 2]):
|
||||
s = math.sqrt(1.0 + float(m[0, 0]) - float(m[1, 1]) - float(m[2, 2])) * 2.0
|
||||
w = (float(m[2, 1]) - float(m[1, 2])) / s
|
||||
x = 0.25 * s
|
||||
y = (float(m[0, 1]) + float(m[1, 0])) / s
|
||||
z = (float(m[0, 2]) + float(m[2, 0])) / s
|
||||
elif float(m[1, 1]) > float(m[2, 2]):
|
||||
s = math.sqrt(1.0 + float(m[1, 1]) - float(m[0, 0]) - float(m[2, 2])) * 2.0
|
||||
w = (float(m[0, 2]) - float(m[2, 0])) / s
|
||||
x = (float(m[0, 1]) + float(m[1, 0])) / s
|
||||
y = 0.25 * s
|
||||
z = (float(m[1, 2]) + float(m[2, 1])) / s
|
||||
else:
|
||||
s = math.sqrt(1.0 + float(m[2, 2]) - float(m[0, 0]) - float(m[1, 1])) * 2.0
|
||||
w = (float(m[1, 0]) - float(m[0, 1])) / s
|
||||
x = (float(m[0, 2]) + float(m[2, 0])) / s
|
||||
y = (float(m[1, 2]) + float(m[2, 1])) / s
|
||||
z = 0.25 * s
|
||||
return _quat_normalize((x, y, z, w))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CameraPose",
|
||||
"CameraSession",
|
||||
"QueuedCameraEvent",
|
||||
"SE3DeltaCameraHandler",
|
||||
]
|
||||
@@ -90,6 +90,7 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
"""
|
||||
|
||||
modality: ClassVar[str] = "prompt"
|
||||
lazy_initialize_session: ClassVar[bool] = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -113,16 +114,14 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
)
|
||||
|
||||
@override
|
||||
def enqueue(
|
||||
def validate_payload(
|
||||
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")
|
||||
@@ -136,6 +135,27 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
if duration < 0:
|
||||
raise ValueError("transition_chunks must be >= 0")
|
||||
|
||||
@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."""
|
||||
self.validate_payload(
|
||||
state,
|
||||
event_id=event_id,
|
||||
payload=payload,
|
||||
transition_chunks=transition_chunks,
|
||||
)
|
||||
prompt = payload.get("prompt")
|
||||
assert isinstance(prompt, str)
|
||||
duration = DEFAULT_TRANSITION_CHUNKS if transition_chunks is None else transition_chunks
|
||||
|
||||
target_prompt_embeds, _ = self._encode_prompt(
|
||||
prompt=prompt,
|
||||
negative_prompt=None,
|
||||
@@ -164,12 +184,13 @@ class PromptInteractionHandler(InteractionHandler):
|
||||
*,
|
||||
boundary_at: float,
|
||||
chunk_index: int | None = None,
|
||||
num_frames: int | None = None,
|
||||
num_media_frames: int | None = None,
|
||||
fps: float | None = None,
|
||||
num_latent_frames: int | 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
|
||||
del chunk_index, num_media_frames, fps, num_latent_frames
|
||||
session = state.interaction_sessions.get("prompt")
|
||||
assert isinstance(session, PromptSession)
|
||||
|
||||
|
||||
@@ -5,12 +5,13 @@ 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\"``).
|
||||
Inner key: modality name (e.g. ``\"camera\"``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.base import InteractionHandler
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.camera import SE3DeltaCameraHandler
|
||||
from vllm_omni.diffusion.interaction.modality_handlers.prompt import PromptInteractionHandler
|
||||
|
||||
STRUCTURED_HANDLER_REGISTRY: dict[str, dict[str, type[InteractionHandler]]] = {
|
||||
@@ -21,4 +22,7 @@ STRUCTURED_HANDLER_REGISTRY: dict[str, dict[str, type[InteractionHandler]]] = {
|
||||
"HeliosPyramidPipeline": {
|
||||
"prompt": PromptInteractionHandler,
|
||||
},
|
||||
"LingBotWorldCausalDMDPipeline": {
|
||||
"camera": SE3DeltaCameraHandler,
|
||||
},
|
||||
}
|
||||
@@ -1,38 +1,75 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared types for midway interaction handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
|
||||
# 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"]
|
||||
# Prompt specialization narrows this to ``"target"`` only.
|
||||
InteractionMode = Literal["target", "velocity"]
|
||||
|
||||
|
||||
def synchronized_monotonic_time(stamp: float | None = None) -> float:
|
||||
"""Return a monotonic timestamp shared across DiT ranks.
|
||||
|
||||
``submit_interaction`` and chunk-boundary apply run as collectives, but
|
||||
``time.monotonic()`` is rank-local. Under USP/SP, inter-rank skew that
|
||||
straddles a ``1/fps`` bucket edge would schedule the same event onto
|
||||
different frames per shard. Rank 0's stamp is broadcast (callers may pass
|
||||
a local sample; non-source ranks' values are ignored).
|
||||
"""
|
||||
if stamp is None:
|
||||
stamp = time.monotonic()
|
||||
if not torch.distributed.is_initialized():
|
||||
return stamp
|
||||
try:
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_world_group
|
||||
|
||||
group = get_world_group()
|
||||
except Exception:
|
||||
return stamp
|
||||
if group.world_size <= 1:
|
||||
return stamp
|
||||
return group.broadcast_object(stamp, src=0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ChunkMediaSpec:
|
||||
"""Media extent of one generation chunk, for interaction timeline mapping."""
|
||||
"""Decoded media extent and latent step count for one generation chunk.
|
||||
|
||||
num_frames: int
|
||||
Attributes:
|
||||
num_media_frames: Number of frames in this chunk when decoded into playable media.
|
||||
fps: Frames per second of the media.
|
||||
num_latent_frames: Number of latent frames in this chunk (internal DiT units).
|
||||
"""
|
||||
|
||||
num_media_frames: int
|
||||
fps: float
|
||||
num_latent_frames: int
|
||||
|
||||
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.num_media_frames <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.num_media_frames must be > 0, got {self.num_media_frames}")
|
||||
if self.num_latent_frames <= 0:
|
||||
raise ValueError(f"ChunkMediaSpec.num_latent_frames must be > 0, got {self.num_latent_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)
|
||||
return float(self.num_media_frames) / float(self.fps)
|
||||
|
||||
|
||||
@dataclass(kw_only=True)
|
||||
@@ -41,6 +78,7 @@ class InteractionEvent:
|
||||
|
||||
Example:
|
||||
- ``QueuedPromptEvent`` in ``vllm_omni.diffusion.interaction.modality_handlers.prompt``
|
||||
- ``QueuedCameraEvent`` in ``vllm_omni.diffusion.interaction.modality_handlers.camera``
|
||||
"""
|
||||
|
||||
event_id: str
|
||||
@@ -60,12 +98,37 @@ class InteractionSession:
|
||||
|
||||
Example:
|
||||
- ``PromptSession`` in ``vllm_omni.diffusion.interaction.modality_handlers.prompt``
|
||||
- ``CameraSession`` in ``vllm_omni.diffusion.interaction.modality_handlers.camera``
|
||||
"""
|
||||
|
||||
lock: Lock = field(default_factory=Lock, repr=False)
|
||||
last_boundary_at: float | None = None
|
||||
|
||||
|
||||
def resolve_event_frame_offset(
|
||||
*,
|
||||
received_at: float,
|
||||
previous_boundary_at: float | None,
|
||||
num_frames: int,
|
||||
fps: float,
|
||||
) -> int:
|
||||
"""Map an event arrival time onto ``[0, num_frames - 1]`` for this chunk.
|
||||
|
||||
* Uses ``floor((received_at - previous_boundary_at) * fps)``.
|
||||
* Events without a prior boundary (or with non-positive fps) map to frame 0.
|
||||
* Offsets past the represented media window are clamped to the final frame.
|
||||
"""
|
||||
num_frames = max(int(num_frames), 1)
|
||||
if previous_boundary_at is None or fps <= 0:
|
||||
return 0
|
||||
offset = math.floor((received_at - previous_boundary_at) * float(fps))
|
||||
if offset < 0:
|
||||
return 0
|
||||
if offset >= num_frames:
|
||||
return num_frames - 1
|
||||
return int(offset)
|
||||
|
||||
|
||||
@dataclass
|
||||
class InteractionChunkMetadata:
|
||||
"""Per-modality (or merged) event-id bookkeeping for one chunk boundary."""
|
||||
|
||||
+232
-25
@@ -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
|
||||
|
||||
"""IPC utilities for transferring large tensors via POSIX shared memory.
|
||||
|
||||
@@ -11,15 +11,32 @@ serialised through the queue.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput
|
||||
from vllm_omni.diffusion.media import (
|
||||
DiffusionMediaOutput,
|
||||
FloatVideoConsumer,
|
||||
VideoColorModel,
|
||||
VideoMediaOutput,
|
||||
VideoTensorEncoding,
|
||||
VideoTensorLayout,
|
||||
VideoTensorSpec,
|
||||
VideoTransportConstraints,
|
||||
VideoValueRange,
|
||||
)
|
||||
|
||||
_SHM_TENSOR_THRESHOLD = 1_000_000 # 1 MB
|
||||
DIFFUSION_RPC_RESULT_ENVELOPE = "diffusion_rpc_result"
|
||||
_DIFFUSION_MEDIA_WIRE_TYPE = "diffusion_media_v1"
|
||||
|
||||
# Sentinel so compute-then-assign packing can tell "field not packed" apart from
|
||||
# "field packed to None".
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
def _array_to_shm(array: np.ndarray) -> dict[str, Any]:
|
||||
@@ -61,9 +78,39 @@ def _array_from_shm(handle: dict[str, Any]) -> np.ndarray:
|
||||
return array
|
||||
|
||||
|
||||
def _unlink_shm_handle(handle: dict[str, Any]) -> None:
|
||||
"""Best-effort removal of a shared-memory segment created during packing."""
|
||||
from multiprocessing import shared_memory
|
||||
|
||||
name = handle.get("name")
|
||||
if not name:
|
||||
return
|
||||
try:
|
||||
shm = shared_memory.SharedMemory(name=name)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
try:
|
||||
shm.close()
|
||||
finally:
|
||||
try:
|
||||
shm.unlink()
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def _unlink_shm_handles(handles: list[dict[str, Any]]) -> None:
|
||||
for handle in handles:
|
||||
try:
|
||||
_unlink_shm_handle(handle)
|
||||
except Exception:
|
||||
# Cleanup is best-effort; never mask the original packing failure.
|
||||
pass
|
||||
|
||||
|
||||
def _tensor_to_shm(
|
||||
tensor: torch.Tensor,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Copy a tensor into POSIX shared memory and return a metadata handle.
|
||||
|
||||
@@ -82,14 +129,17 @@ def _tensor_to_shm(
|
||||
torch.accelerator.set_stream(d2h_stream)
|
||||
try:
|
||||
t = tensor.detach()
|
||||
if original_dtype == torch.bfloat16:
|
||||
t = t.to(torch.float32)
|
||||
cpu = torch.empty(t.shape, dtype=t.dtype, pin_memory=True)
|
||||
cpu.copy_(t, non_blocking=True)
|
||||
finally:
|
||||
torch.accelerator.set_stream(old_stream)
|
||||
d2h_stream.synchronize()
|
||||
tensor = cpu
|
||||
# numpy has no bfloat16, so widen on the host after D2H. Never widen on
|
||||
# the accelerator before the copy: a payload that already fell back after
|
||||
# an fp32 OOM would OOM again on a second device-side fp32 allocation.
|
||||
if original_dtype == torch.bfloat16:
|
||||
tensor = tensor.to(torch.float32)
|
||||
else:
|
||||
tensor = tensor.detach().cpu().contiguous()
|
||||
if original_dtype == torch.bfloat16:
|
||||
@@ -101,6 +151,8 @@ def _tensor_to_shm(
|
||||
"torch_dtype": str(original_dtype),
|
||||
}
|
||||
)
|
||||
if created is not None:
|
||||
created.append(handle)
|
||||
return handle
|
||||
|
||||
|
||||
@@ -120,6 +172,7 @@ def _tensor_from_shm(handle: dict[str, Any]) -> torch.Tensor:
|
||||
def _pack_tensor_if_large(
|
||||
val: torch.Tensor,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> torch.Tensor | dict:
|
||||
"""Replace a tensor with an SHM handle if it exceeds the threshold.
|
||||
|
||||
@@ -134,14 +187,16 @@ def _pack_tensor_if_large(
|
||||
except Exception:
|
||||
storage_bytes = view_bytes
|
||||
if max(view_bytes, storage_bytes) > _SHM_TENSOR_THRESHOLD:
|
||||
return _tensor_to_shm(val, d2h_stream=d2h_stream)
|
||||
return _tensor_to_shm(val, d2h_stream=d2h_stream, created=created)
|
||||
return val
|
||||
|
||||
|
||||
def _ndarray_to_shm(array: np.ndarray) -> dict[str, Any]:
|
||||
def _ndarray_to_shm(array: np.ndarray, created: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
"""Copy a contiguous NumPy array into POSIX shared memory."""
|
||||
handle = _array_to_shm(array)
|
||||
handle["__ndarray_shm__"] = True
|
||||
if created is not None:
|
||||
created.append(handle)
|
||||
return handle
|
||||
|
||||
|
||||
@@ -153,6 +208,7 @@ def _ndarray_from_shm(handle: dict[str, Any]) -> np.ndarray:
|
||||
def _pack_value_if_large(
|
||||
val: object,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> object:
|
||||
"""Recursively replace large tensors with SHM handles.
|
||||
|
||||
@@ -163,15 +219,19 @@ def _pack_value_if_large(
|
||||
the two in sync.
|
||||
"""
|
||||
if isinstance(val, torch.Tensor):
|
||||
return _pack_tensor_if_large(val, d2h_stream=d2h_stream)
|
||||
return _pack_tensor_if_large(val, d2h_stream=d2h_stream, created=created)
|
||||
if isinstance(val, np.ndarray):
|
||||
return _ndarray_to_shm(val) if not val.dtype.hasobject and val.nbytes > _SHM_TENSOR_THRESHOLD else val
|
||||
return (
|
||||
_ndarray_to_shm(val, created=created)
|
||||
if not val.dtype.hasobject and val.nbytes > _SHM_TENSOR_THRESHOLD
|
||||
else val
|
||||
)
|
||||
if isinstance(val, dict):
|
||||
return {key: _pack_value_if_large(value, d2h_stream=d2h_stream) for key, value in val.items()}
|
||||
return {key: _pack_value_if_large(value, d2h_stream=d2h_stream, created=created) for key, value in val.items()}
|
||||
if isinstance(val, list):
|
||||
return [_pack_value_if_large(item, d2h_stream=d2h_stream) for item in val]
|
||||
return [_pack_value_if_large(item, d2h_stream=d2h_stream, created=created) for item in val]
|
||||
if isinstance(val, tuple):
|
||||
return tuple(_pack_value_if_large(item, d2h_stream=d2h_stream) for item in val)
|
||||
return tuple(_pack_value_if_large(item, d2h_stream=d2h_stream, created=created) for item in val)
|
||||
return val
|
||||
|
||||
|
||||
@@ -190,18 +250,116 @@ def _unpack_if_shm_handle(val: object) -> object:
|
||||
return val
|
||||
|
||||
|
||||
def _pack_diffusion_media(
|
||||
media: DiffusionMediaOutput,
|
||||
*,
|
||||
d2h_stream: torch.Stream | None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
media.validate()
|
||||
if not media.prepared_for_transport:
|
||||
raise ValueError("Diffusion media must be prepared before IPC packing")
|
||||
video = media.video
|
||||
packed_tensor = _pack_tensor_if_large(video.tensor, d2h_stream=d2h_stream, created=created)
|
||||
if isinstance(packed_tensor, torch.Tensor) and packed_tensor.device.type != "cpu":
|
||||
packed_tensor = packed_tensor.detach().cpu().contiguous()
|
||||
return {
|
||||
"__type__": _DIFFUSION_MEDIA_WIRE_TYPE,
|
||||
"schema_version": video.schema_version,
|
||||
"prepared_for_transport": True,
|
||||
"video": {
|
||||
"tensor": packed_tensor,
|
||||
"layout": video.spec.layout.value,
|
||||
"encoding": video.spec.encoding.value,
|
||||
"value_range": video.spec.value_range.value,
|
||||
"color_model": video.spec.color_model.value,
|
||||
"pending_float_consumers": sorted(consumer.value for consumer in video.constraints.pending_float_consumers),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _unpack_diffusion_media(packed: dict[str, Any]) -> DiffusionMediaOutput:
|
||||
if packed.get("__type__") != _DIFFUSION_MEDIA_WIRE_TYPE:
|
||||
raise ValueError("Invalid diffusion media wire payload")
|
||||
video_payload = packed.get("video")
|
||||
if not isinstance(video_payload, dict):
|
||||
raise ValueError("Diffusion media wire payload is missing video metadata")
|
||||
tensor = _unpack_if_shm_handle(video_payload.get("tensor"))
|
||||
if not isinstance(tensor, torch.Tensor):
|
||||
raise ValueError("Diffusion media wire payload contains an invalid video tensor")
|
||||
schema_version = packed.get("schema_version")
|
||||
if schema_version != 1:
|
||||
raise ValueError(f"Unsupported video media schema version: {schema_version}")
|
||||
if packed.get("prepared_for_transport") is not True:
|
||||
raise ValueError("Diffusion media wire payload was not prepared for transport")
|
||||
media = DiffusionMediaOutput(
|
||||
video=VideoMediaOutput(
|
||||
tensor=tensor,
|
||||
spec=VideoTensorSpec(
|
||||
layout=VideoTensorLayout(video_payload["layout"]),
|
||||
encoding=VideoTensorEncoding(video_payload["encoding"]),
|
||||
value_range=VideoValueRange(video_payload["value_range"]),
|
||||
color_model=VideoColorModel(video_payload["color_model"]),
|
||||
),
|
||||
constraints=VideoTransportConstraints(
|
||||
pending_float_consumers=frozenset(
|
||||
FloatVideoConsumer(value) for value in video_payload.get("pending_float_consumers", [])
|
||||
)
|
||||
),
|
||||
schema_version=1,
|
||||
),
|
||||
prepared_for_transport=True,
|
||||
)
|
||||
media.validate()
|
||||
return media
|
||||
|
||||
|
||||
def _pack_diffusion_fields(
|
||||
output: DiffusionOutput,
|
||||
d2h_stream: torch.Stream | None = None,
|
||||
created: list[dict[str, Any]] | None = None,
|
||||
pending_updates: list[tuple[DiffusionOutput, str, object]] | None = None,
|
||||
) -> DiffusionOutput:
|
||||
if output.media is not None and output.output is not None:
|
||||
raise ValueError("DiffusionOutput cannot contain both media and legacy output")
|
||||
if output.media is not None and not isinstance(output.media, DiffusionMediaOutput):
|
||||
raise TypeError(f"DiffusionOutput.media must be DiffusionMediaOutput, got {type(output.media).__name__}")
|
||||
|
||||
# Pack into locals first so a mid-payload failure leaves ``output`` unmutated
|
||||
# (never enqueue a half-packed object); the caller unlinks any SHM segments
|
||||
# accumulated in ``created`` on failure.
|
||||
packed_output = _UNSET
|
||||
if output.output is not None:
|
||||
output.output = _pack_value_if_large(output.output, d2h_stream=d2h_stream)
|
||||
if output.trajectory_latents is not None and isinstance(output.trajectory_latents, torch.Tensor):
|
||||
output.trajectory_latents = _pack_tensor_if_large(output.trajectory_latents, d2h_stream=d2h_stream)
|
||||
if output.trajectory_timesteps is not None and isinstance(output.trajectory_timesteps, torch.Tensor):
|
||||
output.trajectory_timesteps = _pack_tensor_if_large(output.trajectory_timesteps, d2h_stream=d2h_stream)
|
||||
if output.trajectory_log_probs is not None and isinstance(output.trajectory_log_probs, torch.Tensor):
|
||||
output.trajectory_log_probs = _pack_tensor_if_large(output.trajectory_log_probs, d2h_stream=d2h_stream)
|
||||
packed_output = _pack_value_if_large(output.output, d2h_stream=d2h_stream, created=created)
|
||||
packed_media = _UNSET
|
||||
if output.media is not None:
|
||||
packed_media = _pack_diffusion_media(output.media, d2h_stream=d2h_stream, created=created)
|
||||
packed_latents = _UNSET
|
||||
if isinstance(output.trajectory_latents, torch.Tensor):
|
||||
packed_latents = _pack_tensor_if_large(output.trajectory_latents, d2h_stream=d2h_stream, created=created)
|
||||
packed_timesteps = _UNSET
|
||||
if isinstance(output.trajectory_timesteps, torch.Tensor):
|
||||
packed_timesteps = _pack_tensor_if_large(output.trajectory_timesteps, d2h_stream=d2h_stream, created=created)
|
||||
packed_log_probs = _UNSET
|
||||
if isinstance(output.trajectory_log_probs, torch.Tensor):
|
||||
packed_log_probs = _pack_tensor_if_large(output.trajectory_log_probs, d2h_stream=d2h_stream, created=created)
|
||||
|
||||
updates = [
|
||||
(output, field_name, value)
|
||||
for field_name, value in (
|
||||
("output", packed_output),
|
||||
("media", packed_media),
|
||||
("trajectory_latents", packed_latents),
|
||||
("trajectory_timesteps", packed_timesteps),
|
||||
("trajectory_log_probs", packed_log_probs),
|
||||
)
|
||||
if value is not _UNSET
|
||||
]
|
||||
if pending_updates is None:
|
||||
for target, field_name, value in updates:
|
||||
setattr(target, field_name, value)
|
||||
else:
|
||||
pending_updates.extend(updates)
|
||||
return output
|
||||
|
||||
|
||||
@@ -223,35 +381,84 @@ def pack_diffusion_output_shm(
|
||||
|
||||
If *d2h_stream* is provided, D2H copies use that stream (non-blocking on
|
||||
the default stream). The caller must synchronize *d2h_stream* afterward.
|
||||
|
||||
Packing is failure-atomic: every SHM segment created during the call is
|
||||
tracked and unlinked if any part of the payload fails to pack, and field
|
||||
mutations are committed only after the complete payload succeeds.
|
||||
"""
|
||||
created: list[dict[str, Any]] = []
|
||||
pending_updates: list[tuple[DiffusionOutput, str, object]] = []
|
||||
try:
|
||||
packed = _pack_output_shm(
|
||||
output,
|
||||
d2h_stream=d2h_stream,
|
||||
created=created,
|
||||
pending_updates=pending_updates,
|
||||
)
|
||||
except BaseException:
|
||||
_unlink_shm_handles(created)
|
||||
raise
|
||||
|
||||
# Commit mutations only after every field and batch entry packed. Until
|
||||
# this point, a failure leaves the complete caller-owned payload untouched.
|
||||
for target, field_name, value in pending_updates:
|
||||
setattr(target, field_name, value)
|
||||
return packed
|
||||
|
||||
|
||||
def _iter_diffusion_outputs(output: object) -> Iterator[DiffusionOutput]:
|
||||
"""Yield every packable ``DiffusionOutput`` leaf in a worker payload."""
|
||||
if isinstance(output, DiffusionOutput):
|
||||
return _pack_diffusion_fields(output, d2h_stream=d2h_stream)
|
||||
yield output
|
||||
return
|
||||
|
||||
# DP multi-concurrency: {"dp_rank": int, "output": DiffusionOutput}
|
||||
if isinstance(output, dict) and "dp_rank" in output and "output" in output:
|
||||
inner = output["output"]
|
||||
if isinstance(inner, DiffusionOutput):
|
||||
output["output"] = _pack_diffusion_fields(inner, d2h_stream=d2h_stream)
|
||||
return output
|
||||
yield inner
|
||||
return
|
||||
|
||||
if _is_rpc_result_envelope(output):
|
||||
result = output.get("result")
|
||||
output["result"] = pack_diffusion_output_shm(result, d2h_stream=d2h_stream)
|
||||
return output
|
||||
yield from _iter_diffusion_outputs(output.get("result"))
|
||||
return
|
||||
|
||||
result = getattr(output, "result", None)
|
||||
if isinstance(result, DiffusionOutput):
|
||||
output.result = _pack_diffusion_fields(result, d2h_stream=d2h_stream)
|
||||
yield result
|
||||
|
||||
runner_outputs = getattr(output, "runner_outputs", None)
|
||||
if isinstance(runner_outputs, list):
|
||||
for runner_output in runner_outputs:
|
||||
pack_diffusion_output_shm(runner_output, d2h_stream=d2h_stream)
|
||||
yield from _iter_diffusion_outputs(runner_output)
|
||||
|
||||
|
||||
def payload_carries_typed_media(output: object) -> bool:
|
||||
"""True if *output* carries any typed ``DiffusionOutput.media`` payload."""
|
||||
return any(item.media is not None for item in _iter_diffusion_outputs(output))
|
||||
|
||||
|
||||
def _pack_output_shm(
|
||||
output: object,
|
||||
*,
|
||||
d2h_stream: torch.Stream | None,
|
||||
created: list[dict[str, Any]],
|
||||
pending_updates: list[tuple[DiffusionOutput, str, object]],
|
||||
) -> object:
|
||||
for item in _iter_diffusion_outputs(output):
|
||||
_pack_diffusion_fields(
|
||||
item,
|
||||
d2h_stream=d2h_stream,
|
||||
created=created,
|
||||
pending_updates=pending_updates,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def _unpack_diffusion_fields(output: DiffusionOutput) -> DiffusionOutput:
|
||||
output.output = _unpack_if_shm_handle(output.output)
|
||||
if isinstance(output.media, dict):
|
||||
output.media = _unpack_diffusion_media(output.media)
|
||||
output.trajectory_latents = _unpack_if_shm_handle(output.trajectory_latents)
|
||||
output.trajectory_timesteps = _unpack_if_shm_handle(output.trajectory_timesteps)
|
||||
output.trajectory_log_probs = _unpack_if_shm_handle(output.trajectory_log_probs)
|
||||
|
||||
@@ -1,18 +1,26 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Q/K RMSNorm followed by packed non-interleaved RoPE.
|
||||
"""Q/K RMSNorm followed by packed RoPE (non-interleaved or interleaved).
|
||||
|
||||
The public contract is shared by diffusion attention implementations:
|
||||
|
||||
* ``q`` and ``k`` are ``[tokens, heads, head_dim]``;
|
||||
* norm weights are one-dimensional ``[head_dim]`` tensors;
|
||||
* ``rope_table`` is ``[tokens, rotary_dim]`` and stores
|
||||
``[cos(theta), sin(theta)]`` with ``theta`` of width ``rotary_dim // 2``.
|
||||
``[cos(theta), sin(theta)]`` with ``theta`` of width ``rotary_dim // 2``;
|
||||
its dtype is either the activation dtype or float32;
|
||||
* ``interleaved=False`` rotates half-split pairs ``(d, d + rotary_dim/2)``
|
||||
(MiniMax-H3); ``interleaved=True`` rotates adjacent pairs ``(2i, 2i + 1)``
|
||||
with ``theta_i`` (Boogu-Image, matching its ``apply_rotary_emb``).
|
||||
|
||||
The CUDA fast path fuses RMSNorm and RoPE without materializing normalized Q/K
|
||||
or rotary-product intermediates. Ascend composes its RMSNorm and rotary fused
|
||||
primitives; unsupported inputs use the eager reference.
|
||||
or rotary-product intermediates. The interleaved mode supports any even
|
||||
``rotary_dim <= head_dim <= 256`` (``tl.arange`` padding to the next power of
|
||||
two); the half-split mode keeps the pre-existing kernel and its MiniMax-H3
|
||||
geometry contract (``head_dim == 128``, ``rotary_dim == 96``). Ascend
|
||||
composes its RMSNorm and rotary fused primitives on the MiniMax-H3 geometry;
|
||||
unsupported inputs use the eager reference.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,31 +34,73 @@ from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
from vllm_omni.diffusion import envs
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
_FUSED_HEAD_DIM = 128
|
||||
_FUSED_ROTARY_DIM = 96
|
||||
# Interleaved-mode geometry bounds (any even rotary_dim <= head_dim <= this).
|
||||
_FUSED_MAX_HEAD_DIM = 256
|
||||
_HEADS_PER_PROGRAM = 8
|
||||
# The combined interleaved kernel: small tiles + one warp measured fastest
|
||||
# (latency-bound shapes; see the kernel docstring).
|
||||
_INTERLEAVED_HEADS_PER_PROGRAM = 4
|
||||
|
||||
|
||||
def _apply_rope_table(
|
||||
x: torch.Tensor,
|
||||
rope_table: torch.Tensor,
|
||||
rotary_dim: int,
|
||||
*,
|
||||
interleaved: bool = False,
|
||||
dtype: torch.dtype | None = None,
|
||||
output_dtype: torch.dtype | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Eager RoPE application: the fallback and the unit-test reference.
|
||||
|
||||
Shapes: ``x`` is the normalized ``[tokens, heads, head_dim]`` tensor;
|
||||
``rope_table`` is ``[tokens, rotary_dim]`` storing
|
||||
``[cos(theta) | sin(theta)]`` with ``theta`` of width ``rotary_dim // 2``.
|
||||
|
||||
``interleaved`` selects the pairing: half-split ``(d, d + rotary_dim/2)``
|
||||
sharing ``theta_d`` (MiniMax-H3) or adjacent pairs ``(2i, 2i + 1)``
|
||||
sharing ``theta_i`` (Boogu-Image). ``dtype`` is the precision the
|
||||
rotation arithmetic runs in and ``output_dtype`` the precision the result
|
||||
is cast to; both default to ``x``'s dtype (the historical half-split
|
||||
behaviour). The interleaved caller passes ``dtype=torch.float32`` to
|
||||
match the Triton kernel's composition — fp32 rotation of the
|
||||
bf16-rounded normalized value, one final rounding — which is also how
|
||||
vLLM's own ``fused_qk_norm_rope`` Triton kernel and Boogu's eager
|
||||
``apply_rotary_emb`` order their rounding.
|
||||
"""
|
||||
compute_dtype = x.dtype if dtype is None else dtype
|
||||
out_dtype = x.dtype if output_dtype is None else output_dtype
|
||||
half = rotary_dim // 2
|
||||
cos = rope_table[..., :half].to(x.dtype).unsqueeze(1)
|
||||
sin = rope_table[..., half:].to(x.dtype).unsqueeze(1)
|
||||
first = x[..., :half]
|
||||
second = x[..., half:rotary_dim]
|
||||
return torch.cat(
|
||||
(
|
||||
first * cos - second * sin,
|
||||
second * cos + first * sin,
|
||||
x[..., rotary_dim:],
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
x_c = x.to(compute_dtype)
|
||||
cos = rope_table[..., :half].to(compute_dtype).unsqueeze(1)
|
||||
sin = rope_table[..., half:].to(compute_dtype).unsqueeze(1)
|
||||
first = x_c[..., 0:rotary_dim:2] if interleaved else x_c[..., :half]
|
||||
second = x_c[..., 1:rotary_dim:2] if interleaved else x_c[..., half:rotary_dim]
|
||||
rotated_first = first * cos - second * sin
|
||||
rotated_second = second * cos + first * sin
|
||||
if interleaved:
|
||||
# stack(..., dim=-1) pairs (new_even_i, new_odd_i) into
|
||||
# [..., half, 2]; flatten(-2) lays the pairs back out as
|
||||
# [e0, o0, e1, o1, ...] — back to their interleaved positions.
|
||||
rotated = torch.stack(
|
||||
(rotated_first, rotated_second),
|
||||
dim=-1,
|
||||
).flatten(-2)
|
||||
return torch.cat((rotated, x_c[..., rotary_dim:]), dim=-1).to(out_dtype)
|
||||
else:
|
||||
return torch.cat(
|
||||
(
|
||||
rotated_first,
|
||||
rotated_second,
|
||||
x_c[..., rotary_dim:],
|
||||
),
|
||||
dim=-1,
|
||||
).to(out_dtype)
|
||||
|
||||
|
||||
if HAS_TRITON:
|
||||
@@ -74,7 +124,8 @@ if HAS_TRITON:
|
||||
eps: tl.constexpr,
|
||||
heads_per_program: tl.constexpr,
|
||||
):
|
||||
token = tl.program_id(0)
|
||||
# Long-video Q/K views can span more than 2**31 elements of fused QKV storage.
|
||||
token = tl.program_id(0).to(tl.int64)
|
||||
head_group = tl.program_id(1)
|
||||
heads = head_group * heads_per_program + tl.arange(0, heads_per_program)
|
||||
dims = tl.arange(0, head_dim)
|
||||
@@ -116,6 +167,136 @@ if HAS_TRITON:
|
||||
out_offsets = token * out_stride_t + heads[:, None] * out_stride_h + dims[None, :] * out_stride_d
|
||||
tl.store(out_ptr + out_offsets, output, mask=mask)
|
||||
|
||||
@triton.jit
|
||||
def _qk_norm_rope_kernel(
|
||||
q_ptr,
|
||||
k_ptr,
|
||||
q_weight_ptr,
|
||||
k_weight_ptr,
|
||||
rope_table_ptr,
|
||||
out_q_ptr,
|
||||
out_k_ptr,
|
||||
q_stride_t,
|
||||
q_stride_h,
|
||||
q_stride_d,
|
||||
k_stride_t,
|
||||
k_stride_h,
|
||||
k_stride_d,
|
||||
rope_stride_t,
|
||||
out_q_stride_t,
|
||||
out_q_stride_h,
|
||||
out_q_stride_d,
|
||||
out_k_stride_t,
|
||||
out_k_stride_h,
|
||||
out_k_stride_d,
|
||||
num_q_heads: tl.constexpr,
|
||||
num_kv_heads: tl.constexpr,
|
||||
head_dim: tl.constexpr,
|
||||
padded_dim: tl.constexpr, # next power of 2 >= head_dim (tl.arange needs a power of 2)
|
||||
rotary_half: tl.constexpr,
|
||||
eps: tl.constexpr,
|
||||
heads_per_program: tl.constexpr,
|
||||
q_head_groups: tl.constexpr,
|
||||
interleaved: tl.constexpr,
|
||||
):
|
||||
"""Fused per-head RMSNorm + RoPE for Q and K in one launch.
|
||||
|
||||
Grid axis 1 assigns the first ``q_head_groups`` programs of a token
|
||||
to Q and the rest to K, so the small K grid hides inside Q's waves
|
||||
instead of paying its own latency-bound launch. ``interleaved``
|
||||
selects the pairing, mirroring ``_apply_rope_table``:
|
||||
|
||||
* ``True`` — adjacent pairs ``(2i, 2i+1)`` sharing ``theta_i``.
|
||||
* ``False`` — half-split pairs ``(d, d + rotary_half)`` sharing
|
||||
``theta_d``. Production traffic still routes half-split inputs
|
||||
through ``_rms_norm_rope_kernel``; this mode is test-covered and
|
||||
awaits the maintainers' call before taking over that path.
|
||||
|
||||
The modes differ only in the pair/frequency/selector index
|
||||
expressions; the arithmetic is shared. Beyond the rotary width
|
||||
(partial rotary or lane padding) the output is the normalized value
|
||||
unchanged.
|
||||
"""
|
||||
# Long-video Q/K views can span more than 2**31 elements of fused QKV storage.
|
||||
token = tl.program_id(0).to(tl.int64)
|
||||
head_group = tl.program_id(1)
|
||||
dims = tl.arange(0, padded_dim)
|
||||
dim_mask = dims < head_dim
|
||||
if head_group < q_head_groups:
|
||||
heads = head_group * heads_per_program + tl.arange(0, heads_per_program)
|
||||
# Valid-domain mask: rows beyond the head count (when it is not a
|
||||
# multiple of heads_per_program) and padded lanes beyond head_dim.
|
||||
mask = (heads[:, None] < num_q_heads) & dim_mask[None, :]
|
||||
in_ptr = q_ptr
|
||||
weight_ptr = q_weight_ptr
|
||||
out_ptr = out_q_ptr
|
||||
in_stride_t, in_stride_h, in_stride_d = q_stride_t, q_stride_h, q_stride_d
|
||||
out_stride_t, out_stride_h, out_stride_d = (
|
||||
out_q_stride_t,
|
||||
out_q_stride_h,
|
||||
out_q_stride_d,
|
||||
)
|
||||
else:
|
||||
heads = (head_group - q_head_groups) * heads_per_program + tl.arange(0, heads_per_program)
|
||||
mask = (heads[:, None] < num_kv_heads) & dim_mask[None, :]
|
||||
in_ptr = k_ptr
|
||||
weight_ptr = k_weight_ptr
|
||||
out_ptr = out_k_ptr
|
||||
in_stride_t, in_stride_h, in_stride_d = k_stride_t, k_stride_h, k_stride_d
|
||||
out_stride_t, out_stride_h, out_stride_d = (
|
||||
out_k_stride_t,
|
||||
out_k_stride_h,
|
||||
out_k_stride_d,
|
||||
)
|
||||
|
||||
offsets = token * in_stride_t + heads[:, None] * in_stride_h + dims[None, :] * in_stride_d
|
||||
x = tl.load(in_ptr + offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
weight = tl.load(weight_ptr + dims, mask=dim_mask, other=0.0).to(tl.float32)
|
||||
# Padding lanes load 0 and do not perturb the sum; divide by the true
|
||||
# head_dim, not the padded width.
|
||||
inv_rms = tl.rsqrt(tl.sum(x * x, axis=1) / head_dim + eps)
|
||||
normalized = (x * inv_rms[:, None] * weight[None, :]).to(tl.bfloat16)
|
||||
|
||||
# The two pairings differ only in three index expressions; the pair
|
||||
# reload, the table gather, the rotation formulas and the write-back
|
||||
# are shared (the same structure as _apply_rope_table).
|
||||
rotary_dim = rotary_half * 2
|
||||
if interleaved:
|
||||
# Adjacent pairs (2i, 2i+1) sharing theta_i.
|
||||
pair_dims = tl.where(dims < rotary_dim, dims ^ 1, dims)
|
||||
freq_dims = tl.where(dims < rotary_dim, dims // 2, 0)
|
||||
is_first = (dims % 2) == 0
|
||||
else:
|
||||
# Half-split pairs (d, d + rotary_half) sharing theta_d.
|
||||
pair_dims = tl.where(
|
||||
dims < rotary_half,
|
||||
dims + rotary_half,
|
||||
tl.where(dims < rotary_dim, dims - rotary_half, dims),
|
||||
)
|
||||
freq_dims = tl.where(
|
||||
dims < rotary_half,
|
||||
dims,
|
||||
tl.where(dims < rotary_dim, dims - rotary_half, 0),
|
||||
)
|
||||
is_first = dims < rotary_half
|
||||
pair_offsets = token * in_stride_t + heads[:, None] * in_stride_h + pair_dims[None, :] * in_stride_d
|
||||
pair_x = tl.load(in_ptr + pair_offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
pair_weight = tl.load(weight_ptr + pair_dims, mask=pair_dims < head_dim, other=0.0).to(tl.float32)
|
||||
pair_normalized = (pair_x * inv_rms[:, None] * pair_weight[None, :]).to(tl.bfloat16)
|
||||
table_offsets = token * rope_stride_t + freq_dims
|
||||
cos = tl.load(rope_table_ptr + table_offsets).to(tl.float32)
|
||||
sin = tl.load(rope_table_ptr + table_offsets + rotary_half).to(tl.float32)
|
||||
first = normalized.to(tl.float32) * cos - pair_normalized.to(tl.float32) * sin
|
||||
second = normalized.to(tl.float32) * cos + pair_normalized.to(tl.float32) * sin
|
||||
output = tl.where(
|
||||
dims < rotary_dim,
|
||||
tl.where(is_first, first, second),
|
||||
normalized.to(tl.float32),
|
||||
)
|
||||
|
||||
out_offsets = token * out_stride_t + heads[:, None] * out_stride_h + dims[None, :] * out_stride_d
|
||||
tl.store(out_ptr + out_offsets, output, mask=mask)
|
||||
|
||||
|
||||
def _eager_qk_norm_rope(
|
||||
q: torch.Tensor,
|
||||
@@ -126,12 +307,16 @@ def _eager_qk_norm_rope(
|
||||
eps: float,
|
||||
head_dim: int,
|
||||
rotary_dim: int,
|
||||
interleaved: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
q_norm = F.rms_norm(q, (head_dim,), q_weight, eps)
|
||||
k_norm = F.rms_norm(k, (head_dim,), k_weight, eps)
|
||||
# fp32 rotation for the interleaved (Boogu) semantics; the half-split
|
||||
# (H3) reference keeps its historical x-dtype arithmetic via the defaults.
|
||||
rope_dtype = torch.float32 if interleaved else None
|
||||
return (
|
||||
_apply_rope_table(q_norm, rope_table, rotary_dim),
|
||||
_apply_rope_table(k_norm, rope_table, rotary_dim),
|
||||
_apply_rope_table(q_norm, rope_table, rotary_dim, interleaved=interleaved, dtype=rope_dtype),
|
||||
_apply_rope_table(k_norm, rope_table, rotary_dim, interleaved=interleaved, dtype=rope_dtype),
|
||||
)
|
||||
|
||||
|
||||
@@ -206,17 +391,23 @@ def _fused_cuda_supported(
|
||||
k: torch.Tensor,
|
||||
head_dim: int,
|
||||
rotary_dim: int,
|
||||
interleaved: bool = False,
|
||||
) -> bool:
|
||||
return (
|
||||
if not (
|
||||
HAS_TRITON
|
||||
and current_platform.is_cuda()
|
||||
and q.is_cuda
|
||||
and k.is_cuda
|
||||
and q.dtype == torch.bfloat16
|
||||
and k.dtype == torch.bfloat16
|
||||
and head_dim == _FUSED_HEAD_DIM
|
||||
and rotary_dim == _FUSED_ROTARY_DIM
|
||||
)
|
||||
):
|
||||
return False
|
||||
if interleaved:
|
||||
return rotary_dim % 2 == 0 and 2 <= rotary_dim <= head_dim <= _FUSED_MAX_HEAD_DIM
|
||||
# Half-split traffic keeps the pre-existing per-tensor kernel and its
|
||||
# exact MiniMax-H3 geometry contract (that kernel is untouched by the
|
||||
# interleaved extension).
|
||||
return head_dim == _FUSED_HEAD_DIM and rotary_dim == _FUSED_ROTARY_DIM
|
||||
|
||||
|
||||
def _fused_npu_supported(
|
||||
@@ -224,10 +415,12 @@ def _fused_npu_supported(
|
||||
k: torch.Tensor,
|
||||
head_dim: int,
|
||||
rotary_dim: int,
|
||||
interleaved: bool = False,
|
||||
) -> bool:
|
||||
"""Return whether the MiniMax-H3 Ascend fused-op contract is satisfied."""
|
||||
return (
|
||||
current_omni_platform.is_npu()
|
||||
not interleaved
|
||||
and current_omni_platform.is_npu()
|
||||
and q.device.type == "npu"
|
||||
and k.device.type == "npu"
|
||||
and q.dtype == torch.bfloat16
|
||||
@@ -271,6 +464,69 @@ def _launch_fused_rms_norm_rope(
|
||||
return out
|
||||
|
||||
|
||||
def _launch_fused_qk_norm_rope(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
q_weight: torch.Tensor,
|
||||
k_weight: torch.Tensor,
|
||||
rope_table: torch.Tensor,
|
||||
eps: float,
|
||||
interleaved: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
tokens, q_heads, head_dim = q.shape
|
||||
kv_heads = k.shape[1]
|
||||
rotary_half = rope_table.shape[-1] // 2
|
||||
out_q = torch.empty(q.shape, dtype=q.dtype, device=q.device)
|
||||
out_k = torch.empty(k.shape, dtype=k.dtype, device=k.device)
|
||||
if tokens == 0:
|
||||
return out_q, out_k
|
||||
if interleaved:
|
||||
heads_per_program = _INTERLEAVED_HEADS_PER_PROGRAM
|
||||
num_warps, num_stages = 1, 2
|
||||
else:
|
||||
# Match the historical per-tensor launch shape (8 heads per program,
|
||||
# 8 warps) so the half-split arithmetic keeps its reduction tree.
|
||||
heads_per_program = _HEADS_PER_PROGRAM
|
||||
num_warps, num_stages = 8, 3
|
||||
q_head_groups = triton.cdiv(q_heads, heads_per_program)
|
||||
kv_head_groups = triton.cdiv(kv_heads, heads_per_program)
|
||||
grid = (tokens, q_head_groups + kv_head_groups)
|
||||
_qk_norm_rope_kernel[grid](
|
||||
q,
|
||||
k,
|
||||
q_weight,
|
||||
k_weight,
|
||||
rope_table,
|
||||
out_q,
|
||||
out_k,
|
||||
q.stride(0),
|
||||
q.stride(1),
|
||||
q.stride(2),
|
||||
k.stride(0),
|
||||
k.stride(1),
|
||||
k.stride(2),
|
||||
rope_table.stride(0),
|
||||
out_q.stride(0),
|
||||
out_q.stride(1),
|
||||
out_q.stride(2),
|
||||
out_k.stride(0),
|
||||
out_k.stride(1),
|
||||
out_k.stride(2),
|
||||
num_q_heads=q_heads,
|
||||
num_kv_heads=kv_heads,
|
||||
head_dim=head_dim,
|
||||
padded_dim=triton.next_power_of_2(head_dim),
|
||||
rotary_half=rotary_half,
|
||||
eps=eps,
|
||||
heads_per_program=heads_per_program,
|
||||
q_head_groups=q_head_groups,
|
||||
interleaved=interleaved,
|
||||
num_warps=num_warps,
|
||||
num_stages=num_stages,
|
||||
)
|
||||
return out_q, out_k
|
||||
|
||||
|
||||
def _fused_qk_norm_rope_impl(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
@@ -280,8 +536,9 @@ def _fused_qk_norm_rope_impl(
|
||||
eps: float,
|
||||
head_dim: int,
|
||||
rotary_dim: int,
|
||||
interleaved: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if _fused_npu_supported(q, k, head_dim, rotary_dim):
|
||||
if _fused_npu_supported(q, k, head_dim, rotary_dim, interleaved):
|
||||
return _npu_qk_norm_rope(
|
||||
q,
|
||||
k,
|
||||
@@ -291,7 +548,7 @@ def _fused_qk_norm_rope_impl(
|
||||
eps,
|
||||
rotary_dim,
|
||||
)
|
||||
if not _fused_cuda_supported(q, k, head_dim, rotary_dim):
|
||||
if not _fused_cuda_supported(q, k, head_dim, rotary_dim, interleaved):
|
||||
return _eager_qk_norm_rope(
|
||||
q,
|
||||
k,
|
||||
@@ -301,7 +558,12 @@ def _fused_qk_norm_rope_impl(
|
||||
eps,
|
||||
head_dim,
|
||||
rotary_dim,
|
||||
interleaved,
|
||||
)
|
||||
if interleaved:
|
||||
return _launch_fused_qk_norm_rope(q, k, q_weight, k_weight, rope_table, eps, interleaved=True)
|
||||
# Half-split production traffic keeps the historical per-tensor kernel;
|
||||
# _qk_norm_rope_kernel's half-split mode awaits the maintainers' call.
|
||||
return (
|
||||
_launch_fused_rms_norm_rope(q, q_weight, rope_table, eps),
|
||||
_launch_fused_rms_norm_rope(k, k_weight, rope_table, eps),
|
||||
@@ -317,8 +579,9 @@ def _fused_qk_norm_rope_fake(
|
||||
eps: float,
|
||||
head_dim: int,
|
||||
rotary_dim: int,
|
||||
interleaved: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del q_weight, k_weight, rope_table, eps, head_dim, rotary_dim
|
||||
del q_weight, k_weight, rope_table, eps, head_dim, rotary_dim, interleaved
|
||||
return torch.empty_like(q), torch.empty_like(k)
|
||||
|
||||
|
||||
@@ -333,6 +596,39 @@ if not hasattr(torch.ops.vllm_omni, "fused_qk_norm_rope"):
|
||||
)
|
||||
|
||||
|
||||
_MIN_TOKENS_ENV = "VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS"
|
||||
|
||||
|
||||
def fused_qk_norm_rope_min_tokens(default: int) -> int:
|
||||
"""Token span below which a consumer should keep its eager chain.
|
||||
|
||||
Taking the fused path costs a fixed amount of host time per call (the
|
||||
custom-op dispatch into the Python impl and the Triton launcher), while the
|
||||
GPU time it saves grows with the number of tokens the call covers. Below a
|
||||
host- and stack-dependent crossover a call is host-bound and the fused path
|
||||
can cost more end-to-end than it saves; above it the fused path wins.
|
||||
Consumers pass the default they measured on their reference hardware
|
||||
(Boogu-Image: 2048 tokens on one H200) and a deployment on other hardware
|
||||
overrides it once, for every consumer, through
|
||||
``VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS`` (``0`` = always fuse).
|
||||
|
||||
Resolved at call time — consumers call this once per forward, not per
|
||||
attention site — so tests and operators can flip it without re-importing.
|
||||
Unset or blank means the caller's default; anything else that is not a
|
||||
non-negative integer raises ``ValueError``.
|
||||
"""
|
||||
raw = envs.VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS
|
||||
if raw is None or not raw.strip():
|
||||
return default
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
value = -1
|
||||
if value < 0:
|
||||
raise ValueError(f"{_MIN_TOKENS_ENV} must be a non-negative integer, got {raw!r}")
|
||||
return value
|
||||
|
||||
|
||||
def fused_qk_norm_rope(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
@@ -343,8 +639,9 @@ def fused_qk_norm_rope(
|
||||
*,
|
||||
head_dim: int | None = None,
|
||||
rotary_dim: int | None = None,
|
||||
interleaved: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Apply Q/K RMSNorm and packed non-interleaved RoPE."""
|
||||
"""Apply Q/K RMSNorm and packed RoPE (half-split or adjacent pairs)."""
|
||||
if q.ndim != 3 or k.ndim != 3:
|
||||
raise ValueError(f"q and k must be [tokens, heads, head_dim], got {q.shape} and {k.shape}")
|
||||
if q.shape[0] != k.shape[0] or q.shape[2] != k.shape[2]:
|
||||
@@ -364,15 +661,18 @@ def fused_qk_norm_rope(
|
||||
raise ValueError(f"Expected norm weights [{head_dim}], got {tuple(q_weight.shape)} and {tuple(k_weight.shape)}")
|
||||
if q_weight.device != q.device or k_weight.device != q.device:
|
||||
raise ValueError("Q/K norm weights must be on the activation device")
|
||||
if rope_table.device != q.device or rope_table.dtype != q.dtype:
|
||||
raise ValueError("rope_table must have the same dtype and device as q/k")
|
||||
if rope_table.device != q.device or rope_table.dtype not in (
|
||||
q.dtype,
|
||||
torch.float32,
|
||||
):
|
||||
raise ValueError("rope_table must be on q/k's device with their dtype or float32")
|
||||
if rope_table.shape != (q.shape[0], rotary_dim):
|
||||
raise ValueError(f"Expected rope_table [{q.shape[0]}, {rotary_dim}], got {tuple(rope_table.shape)}")
|
||||
|
||||
q_weight = q_weight.contiguous()
|
||||
k_weight = k_weight.contiguous()
|
||||
rope_table = rope_table.contiguous()
|
||||
if _fused_npu_supported(q, k, head_dim, rotary_dim):
|
||||
if _fused_npu_supported(q, k, head_dim, rotary_dim, interleaved):
|
||||
return _npu_qk_norm_rope(
|
||||
q,
|
||||
k,
|
||||
@@ -382,7 +682,7 @@ def fused_qk_norm_rope(
|
||||
eps,
|
||||
rotary_dim,
|
||||
)
|
||||
if not _fused_cuda_supported(q, k, head_dim, rotary_dim):
|
||||
if not _fused_cuda_supported(q, k, head_dim, rotary_dim, interleaved):
|
||||
return _fused_qk_norm_rope_impl(
|
||||
q,
|
||||
k,
|
||||
@@ -392,6 +692,7 @@ def fused_qk_norm_rope(
|
||||
eps,
|
||||
head_dim,
|
||||
rotary_dim,
|
||||
interleaved,
|
||||
)
|
||||
return torch.ops.vllm_omni.fused_qk_norm_rope(
|
||||
q,
|
||||
@@ -402,7 +703,8 @@ def fused_qk_norm_rope(
|
||||
eps,
|
||||
head_dim,
|
||||
rotary_dim,
|
||||
interleaved,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["fused_qk_norm_rope"]
|
||||
__all__ = ["fused_qk_norm_rope", "fused_qk_norm_rope_min_tokens"]
|
||||
@@ -0,0 +1,251 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Bit-exact paired Q/K full-width interleaved RoPE for CUDA.
|
||||
|
||||
The operator accepts already-normalized BF16 query and key tensors in BSND
|
||||
layout and full-width FP32 cosine/sine tables. It deliberately performs two
|
||||
round-to-nearest FP32 multiplies followed by one round-to-nearest FP32 add,
|
||||
then rounds only once when storing BF16 output. This matches Diffusers'
|
||||
``apply_rotary_emb`` arithmetic while combining its separate Q and K calls.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch.library import Library
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
_HEAD_DIM = 128
|
||||
_HEADS_PER_PROGRAM = 4
|
||||
|
||||
|
||||
if HAS_TRITON:
|
||||
|
||||
@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 _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 _qk_rope_exact_kernel(
|
||||
q_ptr,
|
||||
k_ptr,
|
||||
cos_ptr,
|
||||
sin_ptr,
|
||||
q_output_ptr,
|
||||
k_output_ptr,
|
||||
q_stride_token,
|
||||
q_stride_head,
|
||||
q_stride_dim,
|
||||
k_stride_token,
|
||||
k_stride_head,
|
||||
k_stride_dim,
|
||||
q_output_stride_token,
|
||||
q_output_stride_head,
|
||||
q_output_stride_dim,
|
||||
k_output_stride_token,
|
||||
k_output_stride_head,
|
||||
k_output_stride_dim,
|
||||
table_stride_sequence,
|
||||
table_stride_dim,
|
||||
sequence,
|
||||
num_heads: tl.constexpr,
|
||||
head_dim: tl.constexpr,
|
||||
heads_per_program: tl.constexpr,
|
||||
):
|
||||
token = tl.program_id(0)
|
||||
group = tl.program_id(1)
|
||||
is_key = tl.program_id(2) == 1
|
||||
heads = group * heads_per_program + tl.arange(0, heads_per_program)
|
||||
dims = tl.arange(0, head_dim)
|
||||
valid = heads[:, None] < num_heads
|
||||
|
||||
q_offsets = token * q_stride_token + heads[:, None] * q_stride_head + dims[None, :] * q_stride_dim
|
||||
k_offsets = token * k_stride_token + heads[:, None] * k_stride_head + dims[None, :] * k_stride_dim
|
||||
input_ptrs = tl.where(is_key, k_ptr + k_offsets, q_ptr + q_offsets)
|
||||
|
||||
pair_dims = dims ^ 1
|
||||
q_pair_offsets = token * q_stride_token + heads[:, None] * q_stride_head + pair_dims[None, :] * q_stride_dim
|
||||
k_pair_offsets = token * k_stride_token + heads[:, None] * k_stride_head + pair_dims[None, :] * k_stride_dim
|
||||
pair_ptrs = tl.where(is_key, k_ptr + k_pair_offsets, q_ptr + q_pair_offsets)
|
||||
values = tl.load(input_ptrs, mask=valid, other=0.0).to(tl.float32)
|
||||
pairs = tl.load(pair_ptrs, mask=valid, other=0.0).to(tl.float32)
|
||||
signed_pairs = tl.where((dims[None, :] & 1) == 0, -pairs, pairs)
|
||||
|
||||
sequence_index = token % sequence
|
||||
table_offsets = sequence_index * table_stride_sequence + dims * table_stride_dim
|
||||
cos = tl.load(cos_ptr + table_offsets).to(tl.float32)[None, :]
|
||||
sin = tl.load(sin_ptr + table_offsets).to(tl.float32)[None, :]
|
||||
|
||||
# Do not let the compiler contract this expression into an FMA. The
|
||||
# reference has two independently rounded FP32 multiplies and one
|
||||
# independently rounded FP32 add, followed by the final BF16 store.
|
||||
first = _mul_rn_f32(values, cos)
|
||||
second = _mul_rn_f32(signed_pairs, sin)
|
||||
output = _add_rn_f32(first, second)
|
||||
q_output_offsets = (
|
||||
token * q_output_stride_token + heads[:, None] * q_output_stride_head + dims[None, :] * q_output_stride_dim
|
||||
)
|
||||
k_output_offsets = (
|
||||
token * k_output_stride_token + heads[:, None] * k_output_stride_head + dims[None, :] * k_output_stride_dim
|
||||
)
|
||||
output_ptrs = tl.where(
|
||||
is_key,
|
||||
k_output_ptr + k_output_offsets,
|
||||
q_output_ptr + q_output_offsets,
|
||||
)
|
||||
tl.store(output_ptrs, output, mask=valid)
|
||||
|
||||
|
||||
def fused_qk_rope_supported(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> bool:
|
||||
"""Return whether the exact CUDA kernel can consume these tensors."""
|
||||
|
||||
if not (
|
||||
HAS_TRITON
|
||||
and torch.version.hip is None
|
||||
and current_platform.is_cuda()
|
||||
and not torch.is_grad_enabled()
|
||||
and q.is_cuda
|
||||
and k.is_cuda
|
||||
and q.device == k.device
|
||||
and q.dtype is torch.bfloat16
|
||||
and k.dtype is q.dtype
|
||||
and q.ndim == 4
|
||||
and k.shape == q.shape
|
||||
and q.numel() > 0
|
||||
and q.is_contiguous()
|
||||
and k.is_contiguous()
|
||||
):
|
||||
return False
|
||||
|
||||
batch, sequence, _heads, head_dim = q.shape
|
||||
del batch
|
||||
if head_dim != _HEAD_DIM:
|
||||
return False
|
||||
if not (
|
||||
cos.shape == (sequence, head_dim)
|
||||
and sin.shape == cos.shape
|
||||
and cos.device == q.device
|
||||
and sin.device == q.device
|
||||
and cos.dtype is torch.float32
|
||||
and sin.dtype is torch.float32
|
||||
and cos.is_contiguous()
|
||||
and sin.is_contiguous()
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _launch_fused_qk_rope(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
q_output = torch.empty_like(q)
|
||||
k_output = torch.empty_like(k)
|
||||
tokens = q.shape[0] * q.shape[1]
|
||||
head_groups = triton.cdiv(q.shape[2], _HEADS_PER_PROGRAM)
|
||||
grid = (tokens, head_groups, 2)
|
||||
with torch.accelerator.device_index(q.device.index):
|
||||
_qk_rope_exact_kernel[grid](
|
||||
q,
|
||||
k,
|
||||
cos,
|
||||
sin,
|
||||
q_output,
|
||||
k_output,
|
||||
q.stride(1),
|
||||
q.stride(2),
|
||||
q.stride(3),
|
||||
k.stride(1),
|
||||
k.stride(2),
|
||||
k.stride(3),
|
||||
q_output.stride(1),
|
||||
q_output.stride(2),
|
||||
q_output.stride(3),
|
||||
k_output.stride(1),
|
||||
k_output.stride(2),
|
||||
k_output.stride(3),
|
||||
cos.stride(0),
|
||||
cos.stride(1),
|
||||
q.shape[1],
|
||||
num_heads=q.shape[2],
|
||||
head_dim=q.shape[-1],
|
||||
heads_per_program=_HEADS_PER_PROGRAM,
|
||||
num_warps=4,
|
||||
)
|
||||
return q_output, k_output
|
||||
|
||||
|
||||
def _fused_qk_rope_impl(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if not fused_qk_rope_supported(q, k, cos, sin):
|
||||
raise ValueError("fused_qk_rope received unsupported inputs")
|
||||
return _launch_fused_qk_rope(q, k, cos, sin)
|
||||
|
||||
|
||||
def _fused_qk_rope_fake(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
del cos, sin
|
||||
return torch.empty_like(q), torch.empty_like(k)
|
||||
|
||||
|
||||
_OMNI_OP_LIB = Library("vllm_omni", "FRAGMENT")
|
||||
if not hasattr(torch.ops.vllm_omni, "fused_qk_rope"):
|
||||
direct_register_custom_op(
|
||||
op_name="fused_qk_rope",
|
||||
op_func=_fused_qk_rope_impl,
|
||||
fake_impl=_fused_qk_rope_fake,
|
||||
mutates_args=[],
|
||||
target_lib=_OMNI_OP_LIB,
|
||||
)
|
||||
|
||||
|
||||
def fused_qk_rope(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Apply paired full-width adjacent/interleaved RoPE on CUDA."""
|
||||
|
||||
if not fused_qk_rope_supported(q, k, cos, sin):
|
||||
raise ValueError("fused_qk_rope requires contiguous CUDA BF16 Q/K and contiguous full-width CUDA FP32 tables")
|
||||
return torch.ops.vllm_omni.fused_qk_rope(q, k, cos, sin)
|
||||
|
||||
|
||||
__all__ = ["fused_qk_rope", "fused_qk_rope_supported"]
|
||||
+42
-11
@@ -1,6 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Fused MiniMax H3 modulation with FP32 accumulation."""
|
||||
"""Fused indexed modulation with FP32 accumulation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,6 +24,18 @@ def _launch_row_chunks(kernel, rows: int, device_type: str, *args, **kwargs) ->
|
||||
kernel[(chunk_rows,)](*args, row_offset, **kwargs)
|
||||
|
||||
|
||||
def _use_hopper_bf16_affine_semantics(x: torch.Tensor) -> bool:
|
||||
"""Use the unfused AdaLN dtype boundaries on Hopper.
|
||||
|
||||
The fused FP32 modulation path is stable on Blackwell, but the SM90
|
||||
kernel can accumulate enough extra precision in the repeated RMSNorm and
|
||||
AdaLN operations to move the 50-step I2VA result below its CI threshold.
|
||||
Keep the existing path on other architectures until their numerical
|
||||
baselines are independently validated.
|
||||
"""
|
||||
return x.device.type == "cuda" and torch.cuda.get_device_capability(x.device)[0] == 9
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _indexed_scale_shift_kernel(
|
||||
output_ptr,
|
||||
@@ -102,6 +114,7 @@ def _rms_norm_indexed_scale_shift_kernel(
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
use_bf16_affine: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0) + row_offset
|
||||
@@ -112,13 +125,20 @@ def _rms_norm_indexed_scale_shift_kernel(
|
||||
x = tl.load(x_ptr + row * stride_x_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
weight = tl.load(weight_ptr + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
variance = tl.sum(x * x, axis=0) / hidden_size
|
||||
normalized = x * tl.rsqrt(variance + eps) * weight
|
||||
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
if use_bf16_affine:
|
||||
# Match the unfused RMSNorm output consumed by AdaLN on Hopper.
|
||||
normalized = (x * tl.rsqrt(variance + eps) * weight).to(tl.bfloat16)
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0)
|
||||
output = normalized * (scale + 1.0) + shift
|
||||
else:
|
||||
normalized = x * tl.rsqrt(variance + eps) * weight
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
output = normalized * (1.0 + scale) + shift
|
||||
tl.store(
|
||||
output_ptr + row * hidden_size + columns,
|
||||
normalized * (1.0 + scale) + shift,
|
||||
output,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
@@ -143,6 +163,7 @@ def _indexed_gate_rms_norm_scale_shift_kernel(
|
||||
stride_scale_row,
|
||||
stride_indices,
|
||||
row_offset,
|
||||
use_bf16_affine: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0) + row_offset
|
||||
@@ -159,12 +180,20 @@ def _indexed_gate_rms_norm_scale_shift_kernel(
|
||||
|
||||
weight = tl.load(weight_ptr + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
variance = tl.sum(updated * updated, axis=0) / hidden_size
|
||||
normalized = updated * tl.rsqrt(variance + eps) * weight
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
if use_bf16_affine:
|
||||
# Match the unfused RMSNorm output consumed by AdaLN on Hopper.
|
||||
normalized = (updated * tl.rsqrt(variance + eps) * weight).to(tl.bfloat16)
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0)
|
||||
output = normalized * (scale + 1.0) + shift
|
||||
else:
|
||||
normalized = updated * tl.rsqrt(variance + eps) * weight
|
||||
shift = tl.load(shift_ptr + index * stride_shift_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
scale = tl.load(scale_ptr + index * stride_scale_row + columns, mask=mask, other=0.0).to(tl.float32)
|
||||
output = normalized * (1.0 + scale) + shift
|
||||
tl.store(
|
||||
modulated_out_ptr + row * hidden_size + columns,
|
||||
normalized * (1.0 + scale) + shift,
|
||||
output,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
@@ -244,7 +273,7 @@ def rms_norm_indexed_scale_shift(
|
||||
indices: torch.Tensor,
|
||||
eps: float,
|
||||
) -> torch.Tensor:
|
||||
"""Fuse H3 RMSNorm with its indexed AdaLN affine transform."""
|
||||
"""Fuse RMSNorm with an indexed affine transform."""
|
||||
if x.is_cpu:
|
||||
input_dtype = x.dtype
|
||||
normalized = x.float()
|
||||
@@ -271,6 +300,7 @@ def rms_norm_indexed_scale_shift(
|
||||
shift.stride(0),
|
||||
scale.stride(0),
|
||||
indices.stride(0),
|
||||
use_bf16_affine=_use_hopper_bf16_affine_semantics(x),
|
||||
block_n=triton.next_power_of_2(hidden_size),
|
||||
num_warps=8,
|
||||
)
|
||||
@@ -324,6 +354,7 @@ def indexed_gate_rms_norm_scale_shift(
|
||||
shift.stride(0),
|
||||
scale.stride(0),
|
||||
indices.stride(0),
|
||||
use_bf16_affine=_use_hopper_bf16_affine_semantics(residual),
|
||||
block_n=triton.next_power_of_2(hidden_size),
|
||||
num_warps=8,
|
||||
)
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from importlib.util import find_spec
|
||||
|
||||
import torch
|
||||
@@ -163,75 +166,3 @@ class RMSNorm(CustomOp):
|
||||
out = self.weight.to(torch.float32) * out
|
||||
out = out.to(input_dtype)
|
||||
return (out, residual) if residual is not None else out
|
||||
|
||||
|
||||
class RMSNormVAE(CustomOp):
|
||||
"""Root Mean Square Layer Normalization for Channel-First or Last"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
channel_first: bool = True,
|
||||
images: bool = True,
|
||||
bias: bool = False,
|
||||
epsilon: float = 1e-6,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
broadcastable_dims = (1, 1, 1) if not images else (1, 1)
|
||||
shape = (dim, *broadcastable_dims) if channel_first else (dim,)
|
||||
|
||||
self.channel_first = channel_first
|
||||
self.scale = dim**0.5
|
||||
self.gamma = nn.Parameter(torch.ones(shape))
|
||||
self.bias = nn.Parameter(torch.zeros(shape)) if bias else None
|
||||
self.epsilon = epsilon
|
||||
|
||||
self.gamma_rmsnorm = None
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_hip(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
return self.forward_native(x)
|
||||
|
||||
def forward_npu(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
import torch_npu
|
||||
|
||||
if self.gamma_rmsnorm is None:
|
||||
self.gamma_rmsnorm = self.gamma.reshape(-1)
|
||||
|
||||
if self.channel_first:
|
||||
x = x.transpose(1, -1)
|
||||
out = torch_npu.npu_rms_norm(x, self.gamma_rmsnorm, epsilon=self.epsilon)[0].transpose(1, -1)
|
||||
else:
|
||||
out = torch_npu.npu_rms_norm(x, self.gamma_rmsnorm, epsilon=self.epsilon)[0]
|
||||
|
||||
if self.bias is not None:
|
||||
out = out + self.bias
|
||||
return out
|
||||
|
||||
def forward_native(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
out = (
|
||||
F.normalize(
|
||||
x,
|
||||
dim=(1 if self.channel_first else -1),
|
||||
eps=self.epsilon,
|
||||
)
|
||||
* self.scale
|
||||
* self.gamma
|
||||
)
|
||||
if self.bias is not None:
|
||||
out = out + self.bias
|
||||
return out
|
||||
@@ -0,0 +1,491 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _layernorm_select01_kernel(
|
||||
output_ptr,
|
||||
gate_out_ptr,
|
||||
x_ptr,
|
||||
weight_ptr,
|
||||
bias_ptr,
|
||||
scale0_ptr,
|
||||
shift0_ptr,
|
||||
gate0_ptr,
|
||||
scale1_ptr,
|
||||
shift1_ptr,
|
||||
gate1_ptr,
|
||||
index_ptr,
|
||||
inner_dim,
|
||||
seq_len,
|
||||
stride_x_row,
|
||||
stride_out_row,
|
||||
stride_gate_out_row,
|
||||
stride_w,
|
||||
stride_b,
|
||||
stride_s0_b,
|
||||
stride_s0_c,
|
||||
stride_sh0_b,
|
||||
stride_sh0_c,
|
||||
stride_g0_b,
|
||||
stride_g0_c,
|
||||
stride_s1_b,
|
||||
stride_s1_c,
|
||||
stride_sh1_b,
|
||||
stride_sh1_c,
|
||||
stride_g1_b,
|
||||
stride_g1_c,
|
||||
stride_i_b,
|
||||
stride_i_l,
|
||||
eps,
|
||||
has_weight: tl.constexpr,
|
||||
has_bias: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0)
|
||||
cols = tl.arange(0, block_n)
|
||||
mask = cols < inner_dim
|
||||
|
||||
x_row_ptr = x_ptr + row * stride_x_row
|
||||
x = tl.load(x_row_ptr + cols, mask=mask, other=0.0).to(tl.float32)
|
||||
|
||||
mean = tl.sum(x, axis=0) / inner_dim
|
||||
xbar = tl.where(mask, x - mean, 0.0)
|
||||
var = tl.sum(xbar * xbar, axis=0) / inner_dim
|
||||
x_hat = (x - mean) * tl.rsqrt(var + eps)
|
||||
|
||||
if has_weight:
|
||||
weight = tl.load(weight_ptr + cols * stride_w, mask=mask, other=1.0).to(tl.float32)
|
||||
x_hat = x_hat * weight
|
||||
if has_bias:
|
||||
bias = tl.load(bias_ptr + cols * stride_b, mask=mask, other=0.0).to(tl.float32)
|
||||
x_hat = x_hat + bias
|
||||
|
||||
batch_idx = row // seq_len
|
||||
seq_idx = row % seq_len
|
||||
idx = tl.load(index_ptr + batch_idx * stride_i_b + seq_idx * stride_i_l).to(tl.int1)
|
||||
|
||||
scale0_ptrs = scale0_ptr + batch_idx * stride_s0_b + cols * stride_s0_c
|
||||
shift0_ptrs = shift0_ptr + batch_idx * stride_sh0_b + cols * stride_sh0_c
|
||||
gate0_ptrs = gate0_ptr + batch_idx * stride_g0_b + cols * stride_g0_c
|
||||
scale1_ptrs = scale1_ptr + batch_idx * stride_s1_b + cols * stride_s1_c
|
||||
shift1_ptrs = shift1_ptr + batch_idx * stride_sh1_b + cols * stride_sh1_c
|
||||
gate1_ptrs = gate1_ptr + batch_idx * stride_g1_b + cols * stride_g1_c
|
||||
|
||||
scale_ptrs = tl.where(idx, scale1_ptrs, scale0_ptrs)
|
||||
shift_ptrs = tl.where(idx, shift1_ptrs, shift0_ptrs)
|
||||
gate_ptrs = tl.where(idx, gate1_ptrs, gate0_ptrs)
|
||||
|
||||
scale = tl.load(scale_ptrs, mask=mask, other=0.0).to(tl.float32)
|
||||
shift = tl.load(shift_ptrs, mask=mask, other=0.0).to(tl.float32)
|
||||
gate = tl.load(gate_ptrs, mask=mask, other=0.0)
|
||||
|
||||
y = x_hat * (1.0 + scale) + shift
|
||||
tl.store(output_ptr + row * stride_out_row + cols, y, mask=mask)
|
||||
tl.store(gate_out_ptr + row * stride_gate_out_row + cols, gate, mask=mask)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _residual_layernorm_select01_kernel(
|
||||
output_ptr,
|
||||
residual_out_ptr,
|
||||
gate_out_ptr,
|
||||
x_ptr,
|
||||
residual_ptr,
|
||||
residual_gate_ptr,
|
||||
weight_ptr,
|
||||
bias_ptr,
|
||||
scale0_ptr,
|
||||
shift0_ptr,
|
||||
gate0_ptr,
|
||||
scale1_ptr,
|
||||
shift1_ptr,
|
||||
gate1_ptr,
|
||||
index_ptr,
|
||||
inner_dim,
|
||||
seq_len,
|
||||
stride_x_row,
|
||||
stride_res_row,
|
||||
stride_res_gate_row,
|
||||
stride_out_row,
|
||||
stride_res_out_row,
|
||||
stride_gate_out_row,
|
||||
stride_w,
|
||||
stride_b,
|
||||
stride_s0_b,
|
||||
stride_s0_c,
|
||||
stride_sh0_b,
|
||||
stride_sh0_c,
|
||||
stride_g0_b,
|
||||
stride_g0_c,
|
||||
stride_s1_b,
|
||||
stride_s1_c,
|
||||
stride_sh1_b,
|
||||
stride_sh1_c,
|
||||
stride_g1_b,
|
||||
stride_g1_c,
|
||||
stride_i_b,
|
||||
stride_i_l,
|
||||
eps,
|
||||
has_weight: tl.constexpr,
|
||||
has_bias: tl.constexpr,
|
||||
block_n: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0)
|
||||
cols = tl.arange(0, block_n)
|
||||
mask = cols < inner_dim
|
||||
|
||||
x = tl.load(x_ptr + row * stride_x_row + cols, mask=mask, other=0.0).to(tl.float32)
|
||||
residual = tl.load(residual_ptr + row * stride_res_row + cols, mask=mask, other=0.0).to(tl.float32)
|
||||
residual_gate = tl.load(
|
||||
residual_gate_ptr + row * stride_res_gate_row + cols,
|
||||
mask=mask,
|
||||
other=0.0,
|
||||
).to(tl.float32)
|
||||
|
||||
residual_out = residual + residual_gate * x
|
||||
tl.store(residual_out_ptr + row * stride_res_out_row + cols, residual_out, mask=mask)
|
||||
|
||||
mean = tl.sum(residual_out, axis=0) / inner_dim
|
||||
xbar = tl.where(mask, residual_out - mean, 0.0)
|
||||
var = tl.sum(xbar * xbar, axis=0) / inner_dim
|
||||
x_hat = (residual_out - mean) * tl.rsqrt(var + eps)
|
||||
|
||||
if has_weight:
|
||||
weight = tl.load(weight_ptr + cols * stride_w, mask=mask, other=1.0).to(tl.float32)
|
||||
x_hat = x_hat * weight
|
||||
if has_bias:
|
||||
bias = tl.load(bias_ptr + cols * stride_b, mask=mask, other=0.0).to(tl.float32)
|
||||
x_hat = x_hat + bias
|
||||
|
||||
batch_idx = row // seq_len
|
||||
seq_idx = row % seq_len
|
||||
idx = tl.load(index_ptr + batch_idx * stride_i_b + seq_idx * stride_i_l).to(tl.int1)
|
||||
|
||||
scale0_ptrs = scale0_ptr + batch_idx * stride_s0_b + cols * stride_s0_c
|
||||
shift0_ptrs = shift0_ptr + batch_idx * stride_sh0_b + cols * stride_sh0_c
|
||||
gate0_ptrs = gate0_ptr + batch_idx * stride_g0_b + cols * stride_g0_c
|
||||
scale1_ptrs = scale1_ptr + batch_idx * stride_s1_b + cols * stride_s1_c
|
||||
shift1_ptrs = shift1_ptr + batch_idx * stride_sh1_b + cols * stride_sh1_c
|
||||
gate1_ptrs = gate1_ptr + batch_idx * stride_g1_b + cols * stride_g1_c
|
||||
|
||||
scale_ptrs = tl.where(idx, scale1_ptrs, scale0_ptrs)
|
||||
shift_ptrs = tl.where(idx, shift1_ptrs, shift0_ptrs)
|
||||
gate_ptrs = tl.where(idx, gate1_ptrs, gate0_ptrs)
|
||||
|
||||
scale = tl.load(scale_ptrs, mask=mask, other=0.0).to(tl.float32)
|
||||
shift = tl.load(shift_ptrs, mask=mask, other=0.0).to(tl.float32)
|
||||
gate = tl.load(gate_ptrs, mask=mask, other=0.0)
|
||||
|
||||
y = x_hat * (1.0 + scale) + shift
|
||||
tl.store(output_ptr + row * stride_out_row + cols, y, mask=mask)
|
||||
tl.store(gate_out_ptr + row * stride_gate_out_row + cols, gate, mask=mask)
|
||||
|
||||
|
||||
def split_select01_mod_params(mod_params: torch.Tensor) -> tuple[torch.Tensor, ...]:
|
||||
shift, scale, gate = mod_params.chunk(3, dim=-1)
|
||||
actual_batch = shift.size(0) // 2
|
||||
if actual_batch == 0 or shift.size(0) != actual_batch * 2:
|
||||
raise ValueError("select01 modulation expects mod_params batch dim to be 2 * batch")
|
||||
return (
|
||||
scale[:actual_batch],
|
||||
shift[:actual_batch],
|
||||
gate[:actual_batch],
|
||||
scale[actual_batch:],
|
||||
shift[actual_batch:],
|
||||
gate[actual_batch:],
|
||||
)
|
||||
|
||||
|
||||
def select01_modulation_native(
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
scale0, shift0, gate0, scale1, shift1, gate1 = split_select01_mod_params(mod_params)
|
||||
idx = index.to(dtype=torch.bool).unsqueeze(-1)
|
||||
scale = torch.where(idx, scale1.unsqueeze(1), scale0.unsqueeze(1))
|
||||
shift = torch.where(idx, shift1.unsqueeze(1), shift0.unsqueeze(1))
|
||||
gate = torch.where(idx, gate1.unsqueeze(1), gate0.unsqueeze(1))
|
||||
return scale, shift, gate
|
||||
|
||||
|
||||
def _validate_select01_inputs(
|
||||
x: torch.Tensor,
|
||||
index: torch.Tensor,
|
||||
tensors: tuple[torch.Tensor, ...],
|
||||
) -> None:
|
||||
if x.dim() != 3:
|
||||
raise ValueError("x must be 3D [B, L, C]")
|
||||
if index.dim() != 2 or index.shape[1] != x.shape[1] or index.shape[0] not in (1, x.shape[0]):
|
||||
raise ValueError("index must be 2D [B or 1, L] and match x batch/sequence")
|
||||
batch_size, _, hidden_size = x.shape
|
||||
for tensor in tensors:
|
||||
if tensor.dim() != 2 or tensor.shape != (batch_size, hidden_size):
|
||||
raise ValueError("scale/shift/gate tensors must be 2D [B, C]")
|
||||
|
||||
|
||||
def _maybe_contiguous(x: torch.Tensor) -> torch.Tensor:
|
||||
return x if x.is_contiguous() else x.contiguous()
|
||||
|
||||
|
||||
def _launch_layernorm_select01(
|
||||
x: torch.Tensor,
|
||||
weight: torch.Tensor | None,
|
||||
bias: torch.Tensor | None,
|
||||
scale0: torch.Tensor,
|
||||
shift0: torch.Tensor,
|
||||
gate0: torch.Tensor,
|
||||
scale1: torch.Tensor,
|
||||
shift1: torch.Tensor,
|
||||
gate1: torch.Tensor,
|
||||
index: torch.Tensor,
|
||||
eps: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
_validate_select01_inputs(x, index, (scale0, shift0, gate0, scale1, shift1, gate1))
|
||||
batch_size, seq_len, hidden_size = x.shape
|
||||
output = torch.empty_like(x)
|
||||
gate_out = torch.empty_like(x)
|
||||
|
||||
x_2d = _maybe_contiguous(x).view(batch_size * seq_len, hidden_size)
|
||||
output_2d = output.view(batch_size * seq_len, hidden_size)
|
||||
gate_out_2d = gate_out.view(batch_size * seq_len, hidden_size)
|
||||
index = _maybe_contiguous(index)
|
||||
scale0 = _maybe_contiguous(scale0)
|
||||
shift0 = _maybe_contiguous(shift0)
|
||||
gate0 = _maybe_contiguous(gate0)
|
||||
scale1 = _maybe_contiguous(scale1)
|
||||
shift1 = _maybe_contiguous(shift1)
|
||||
gate1 = _maybe_contiguous(gate1)
|
||||
|
||||
weight_arg = _maybe_contiguous(weight) if weight is not None else x_2d
|
||||
bias_arg = _maybe_contiguous(bias) if bias is not None else x_2d
|
||||
block_n = min(65536 // x_2d.element_size(), triton.next_power_of_2(hidden_size))
|
||||
if hidden_size > block_n:
|
||||
raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
|
||||
|
||||
_layernorm_select01_kernel[(batch_size * seq_len,)](
|
||||
output_2d,
|
||||
gate_out_2d,
|
||||
x_2d,
|
||||
weight_arg,
|
||||
bias_arg,
|
||||
scale0,
|
||||
shift0,
|
||||
gate0,
|
||||
scale1,
|
||||
shift1,
|
||||
gate1,
|
||||
index,
|
||||
hidden_size,
|
||||
seq_len,
|
||||
x_2d.stride(0),
|
||||
output_2d.stride(0),
|
||||
gate_out_2d.stride(0),
|
||||
weight_arg.stride(0) if weight is not None else 0,
|
||||
bias_arg.stride(0) if bias is not None else 0,
|
||||
scale0.stride(0),
|
||||
scale0.stride(1),
|
||||
shift0.stride(0),
|
||||
shift0.stride(1),
|
||||
gate0.stride(0),
|
||||
gate0.stride(1),
|
||||
scale1.stride(0),
|
||||
scale1.stride(1),
|
||||
shift1.stride(0),
|
||||
shift1.stride(1),
|
||||
gate1.stride(0),
|
||||
gate1.stride(1),
|
||||
index.stride(0) if index.shape[0] > 1 else 0,
|
||||
index.stride(1),
|
||||
eps,
|
||||
has_weight=weight is not None,
|
||||
has_bias=bias is not None,
|
||||
block_n=block_n,
|
||||
num_warps=4,
|
||||
num_stages=4,
|
||||
)
|
||||
return output, gate_out
|
||||
|
||||
|
||||
def _launch_residual_layernorm_select01(
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
residual_gate: torch.Tensor,
|
||||
weight: torch.Tensor | None,
|
||||
bias: torch.Tensor | None,
|
||||
scale0: torch.Tensor,
|
||||
shift0: torch.Tensor,
|
||||
gate0: torch.Tensor,
|
||||
scale1: torch.Tensor,
|
||||
shift1: torch.Tensor,
|
||||
gate1: torch.Tensor,
|
||||
index: torch.Tensor,
|
||||
eps: float,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
_validate_select01_inputs(x, index, (scale0, shift0, gate0, scale1, shift1, gate1))
|
||||
if residual.shape != x.shape:
|
||||
raise ValueError("residual must have the same shape as x")
|
||||
if residual_gate.shape != x.shape:
|
||||
raise ValueError("residual_gate must have the same shape as x")
|
||||
|
||||
batch_size, seq_len, hidden_size = x.shape
|
||||
output = torch.empty_like(x)
|
||||
residual_out = torch.empty_like(x)
|
||||
gate_out = torch.empty_like(x)
|
||||
|
||||
x_2d = _maybe_contiguous(x).view(batch_size * seq_len, hidden_size)
|
||||
residual_2d = _maybe_contiguous(residual).view(batch_size * seq_len, hidden_size)
|
||||
residual_gate_2d = _maybe_contiguous(residual_gate).view(batch_size * seq_len, hidden_size)
|
||||
output_2d = output.view(batch_size * seq_len, hidden_size)
|
||||
residual_out_2d = residual_out.view(batch_size * seq_len, hidden_size)
|
||||
gate_out_2d = gate_out.view(batch_size * seq_len, hidden_size)
|
||||
index = _maybe_contiguous(index)
|
||||
scale0 = _maybe_contiguous(scale0)
|
||||
shift0 = _maybe_contiguous(shift0)
|
||||
gate0 = _maybe_contiguous(gate0)
|
||||
scale1 = _maybe_contiguous(scale1)
|
||||
shift1 = _maybe_contiguous(shift1)
|
||||
gate1 = _maybe_contiguous(gate1)
|
||||
|
||||
weight_arg = _maybe_contiguous(weight) if weight is not None else x_2d
|
||||
bias_arg = _maybe_contiguous(bias) if bias is not None else x_2d
|
||||
block_n = min(65536 // x_2d.element_size(), triton.next_power_of_2(hidden_size))
|
||||
if hidden_size > block_n:
|
||||
raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
|
||||
|
||||
_residual_layernorm_select01_kernel[(batch_size * seq_len,)](
|
||||
output_2d,
|
||||
residual_out_2d,
|
||||
gate_out_2d,
|
||||
x_2d,
|
||||
residual_2d,
|
||||
residual_gate_2d,
|
||||
weight_arg,
|
||||
bias_arg,
|
||||
scale0,
|
||||
shift0,
|
||||
gate0,
|
||||
scale1,
|
||||
shift1,
|
||||
gate1,
|
||||
index,
|
||||
hidden_size,
|
||||
seq_len,
|
||||
x_2d.stride(0),
|
||||
residual_2d.stride(0),
|
||||
residual_gate_2d.stride(0),
|
||||
output_2d.stride(0),
|
||||
residual_out_2d.stride(0),
|
||||
gate_out_2d.stride(0),
|
||||
weight_arg.stride(0) if weight is not None else 0,
|
||||
bias_arg.stride(0) if bias is not None else 0,
|
||||
scale0.stride(0),
|
||||
scale0.stride(1),
|
||||
shift0.stride(0),
|
||||
shift0.stride(1),
|
||||
gate0.stride(0),
|
||||
gate0.stride(1),
|
||||
scale1.stride(0),
|
||||
scale1.stride(1),
|
||||
shift1.stride(0),
|
||||
shift1.stride(1),
|
||||
gate1.stride(0),
|
||||
gate1.stride(1),
|
||||
index.stride(0) if index.shape[0] > 1 else 0,
|
||||
index.stride(1),
|
||||
eps,
|
||||
has_weight=weight is not None,
|
||||
has_bias=bias is not None,
|
||||
block_n=block_n,
|
||||
num_warps=4,
|
||||
num_stages=4,
|
||||
)
|
||||
return output, residual_out, gate_out
|
||||
|
||||
|
||||
def can_use_qwen_select01_triton(x: torch.Tensor) -> bool:
|
||||
return HAS_TRITON and current_platform.is_cuda() and x.is_cuda
|
||||
|
||||
|
||||
def fused_layernorm_select01(
|
||||
x: torch.Tensor,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor,
|
||||
eps: float,
|
||||
weight: torch.Tensor | None = None,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
scale0, shift0, gate0, scale1, shift1, gate1 = split_select01_mod_params(mod_params)
|
||||
is_compiling = torch.compiler.is_compiling()
|
||||
if can_use_qwen_select01_triton(x) and not is_compiling:
|
||||
return _launch_layernorm_select01(
|
||||
x,
|
||||
weight,
|
||||
bias,
|
||||
scale0,
|
||||
shift0,
|
||||
gate0,
|
||||
scale1,
|
||||
shift1,
|
||||
gate1,
|
||||
index,
|
||||
eps,
|
||||
)
|
||||
|
||||
scale, shift, gate = select01_modulation_native(mod_params, index)
|
||||
out = F.layer_norm(
|
||||
x.float(),
|
||||
(x.shape[-1],),
|
||||
weight=weight.float() if weight is not None else None,
|
||||
bias=bias.float() if bias is not None else None,
|
||||
eps=eps,
|
||||
).to(x.dtype)
|
||||
return out * (1 + scale) + shift, gate
|
||||
|
||||
|
||||
def fused_residual_layernorm_select01(
|
||||
x: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
residual_gate: torch.Tensor,
|
||||
mod_params: torch.Tensor,
|
||||
index: torch.Tensor,
|
||||
eps: float,
|
||||
weight: torch.Tensor | None = None,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
scale0, shift0, gate0, scale1, shift1, gate1 = split_select01_mod_params(mod_params)
|
||||
is_compiling = torch.compiler.is_compiling()
|
||||
if can_use_qwen_select01_triton(x) and not is_compiling:
|
||||
return _launch_residual_layernorm_select01(
|
||||
x,
|
||||
residual,
|
||||
residual_gate,
|
||||
weight,
|
||||
bias,
|
||||
scale0,
|
||||
shift0,
|
||||
gate0,
|
||||
scale1,
|
||||
shift1,
|
||||
gate1,
|
||||
index,
|
||||
eps,
|
||||
)
|
||||
|
||||
scale, shift, gate = select01_modulation_native(mod_params, index)
|
||||
residual_out = residual + residual_gate * x
|
||||
out = F.layer_norm(
|
||||
residual_out.float(),
|
||||
(residual_out.shape[-1],),
|
||||
weight=weight.float() if weight is not None else None,
|
||||
bias=bias.float() if bias is not None else None,
|
||||
eps=eps,
|
||||
).to(residual_out.dtype)
|
||||
return out * (1 + scale) + shift, residual_out, gate
|
||||
@@ -344,140 +344,6 @@ def apply_rope_to_qk(
|
||||
return query, key
|
||||
|
||||
|
||||
class WanS2VRotaryPosEmbed(torch.nn.Module):
|
||||
"""Precompute complex-valued RoPE embeddings for S2V multi-grid positions.
|
||||
|
||||
Owns the base frequency buffer and provides forward() to compute position
|
||||
embeddings given hidden_states (for shape) and grid_sizes.
|
||||
"""
|
||||
|
||||
def __init__(self, num_heads: int, head_dim: int, max_seq_len: int = 1024):
|
||||
super().__init__()
|
||||
self.num_heads = num_heads
|
||||
self.head_dim = head_dim
|
||||
d = head_dim
|
||||
freqs = torch.cat(
|
||||
[
|
||||
self._rope_params(max_seq_len, d - 4 * (d // 6)),
|
||||
self._rope_params(max_seq_len, 2 * (d // 6)),
|
||||
self._rope_params(max_seq_len, 2 * (d // 6)),
|
||||
],
|
||||
dim=1,
|
||||
)
|
||||
self.register_buffer("freqs", freqs.to(torch.complex64), persistent=False)
|
||||
|
||||
@staticmethod
|
||||
@torch.amp.autocast(current_omni_platform.device_type, enabled=False)
|
||||
def _rope_params(max_seq_len, dim, theta=10000):
|
||||
if dim % 2 != 0:
|
||||
raise ValueError(f"dim ({dim}) must be even")
|
||||
freqs = torch.outer(
|
||||
torch.arange(max_seq_len), 1.0 / torch.pow(theta, torch.arange(0, dim, 2).to(torch.float64).div(dim))
|
||||
)
|
||||
return torch.polar(torch.ones_like(freqs), freqs)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
grid_sizes: list,
|
||||
trainable_freqs: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Precompute RoPE embeddings for the given grid layout.
|
||||
|
||||
Args:
|
||||
hidden_states: Tensor [B, S, ...] (used for batch/seq shape and device)
|
||||
grid_sizes: Grid specification (list of [offsets, sizes, totals])
|
||||
trainable_freqs: Optional trainable frequency overrides for t_f < 0
|
||||
|
||||
Returns:
|
||||
Complex tensor [B, S, 1, head_dim//2] of precomputed position embeddings
|
||||
"""
|
||||
b, s = hidden_states.shape[0], hidden_states.shape[1]
|
||||
c = self.head_dim // 2
|
||||
device = hidden_states.device
|
||||
|
||||
freqs = self.freqs.to(device)
|
||||
if trainable_freqs is not None:
|
||||
freqs_input = [freqs, trainable_freqs]
|
||||
else:
|
||||
freqs_input = freqs
|
||||
|
||||
if isinstance(freqs_input, list):
|
||||
trainable_f = freqs_input[1]
|
||||
freqs_split = freqs_input[0]
|
||||
else:
|
||||
trainable_f = None
|
||||
freqs_split = freqs_input
|
||||
freqs_split = freqs_split.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
|
||||
|
||||
output = torch.empty((b, s, 1, c), device=device, dtype=torch.complex64)
|
||||
seq_bucket = [0]
|
||||
if not isinstance(grid_sizes, list):
|
||||
grid_sizes = [grid_sizes]
|
||||
for g in grid_sizes:
|
||||
if not isinstance(g, list):
|
||||
g = [torch.zeros_like(g), g]
|
||||
batch_size = g[0].shape[0]
|
||||
for i in range(batch_size):
|
||||
f_o, h_o, w_o = g[0][i]
|
||||
f, h, w = g[1][i]
|
||||
t_f, t_h, t_w = g[2][i]
|
||||
seq_f, seq_h, seq_w = f - f_o, h - h_o, w - w_o
|
||||
seq_len = int(seq_f * seq_h * seq_w)
|
||||
if seq_len > 0:
|
||||
if t_f > 0:
|
||||
assert f_o * f >= 0 and h_o * h >= 0 and w_o * w >= 0
|
||||
seq_f_int = int(seq_f)
|
||||
seq_h_int = int(seq_h)
|
||||
seq_w_int = int(seq_w)
|
||||
|
||||
if f_o >= 0:
|
||||
f_sam = torch.linspace(int(f_o), int(t_f + f_o) - 1, seq_f_int, device=device).long()
|
||||
else:
|
||||
f_sam = torch.linspace(int(-f_o), int(-t_f - f_o) + 1, seq_f_int, device=device).long()
|
||||
h_sam = torch.linspace(int(h_o), int(t_h + h_o) - 1, seq_h_int, device=device).long()
|
||||
w_sam = torch.linspace(int(w_o), int(t_w + w_o) - 1, seq_w_int, device=device).long()
|
||||
|
||||
freqs_0 = torch.index_select(freqs_split[0] if f_o >= 0 else freqs_split[0].conj(), 0, f_sam)
|
||||
freqs_0 = freqs_0.view(seq_f_int, 1, 1, -1)
|
||||
|
||||
freqs_i = torch.cat(
|
||||
[
|
||||
freqs_0.expand(seq_f_int, seq_h_int, seq_w_int, -1),
|
||||
torch.index_select(freqs_split[1], 0, h_sam)
|
||||
.view(1, seq_h_int, 1, -1)
|
||||
.expand(seq_f_int, seq_h_int, seq_w_int, -1),
|
||||
torch.index_select(freqs_split[2], 0, w_sam)
|
||||
.view(1, 1, seq_w_int, -1)
|
||||
.expand(seq_f_int, seq_h_int, seq_w_int, -1),
|
||||
],
|
||||
dim=-1,
|
||||
).reshape(seq_len, 1, -1)
|
||||
elif t_f < 0:
|
||||
freqs_i = trainable_f.unsqueeze(1)
|
||||
output[i, seq_bucket[-1] : seq_bucket[-1] + seq_len] = freqs_i
|
||||
seq_bucket.append(seq_bucket[-1] + seq_len)
|
||||
return output
|
||||
|
||||
|
||||
class RotaryEmbeddingWanS2V(RotaryEmbeddingWan):
|
||||
"""Apply RoPE using precomputed complex freqs for Wan S2V main transformer.
|
||||
|
||||
Converts complex freqs (from WanS2VRotaryPosEmbed) to cos/sin and delegates
|
||||
to RotaryEmbeddingWan for platform-optimized application (float32 kernel).
|
||||
Under TP, freqs has 1 head — broadcasts automatically via cos/sin.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(is_neox_style=False, half_head_dim=True)
|
||||
|
||||
def forward(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
||||
freqs_sliced = freqs[:, : x.size(1)]
|
||||
cos = freqs_sliced.real.to(x.dtype)
|
||||
sin = freqs_sliced.imag.to(x.dtype)
|
||||
return super().forward(x, cos, sin)
|
||||
|
||||
|
||||
class RotaryEmbeddingS2VGrid(torch.nn.Module):
|
||||
"""Grid-based RoPE for S2V motioner/init attention.
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from diffusers.loaders.lora_conversion_utils import (
|
||||
from safetensors.torch import load_file
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.utils.tf_utils import get_transformer_from_pipeline
|
||||
from vllm_omni.transformers_utils.repo_utils import hf_api
|
||||
|
||||
@@ -48,6 +49,7 @@ def _prepare_lora_delta(
|
||||
lora_a_suffix: str = "lora_A.weight",
|
||||
lora_b_suffix: str = "lora_B.weight",
|
||||
lora_bias_suffix: str = "bias",
|
||||
compute_device: torch.device | None = None,
|
||||
):
|
||||
used_keys: set[str] = set()
|
||||
# stacked_params_mapping param_to_weight_names
|
||||
@@ -75,6 +77,8 @@ def _prepare_lora_delta(
|
||||
if lora_bias_key not in lora_state_dict:
|
||||
return None, used_keys
|
||||
delta = lora_state_dict[lora_bias_key]
|
||||
if compute_device is not None and compute_device.type != "cpu":
|
||||
delta = delta.to(compute_device)
|
||||
stacked_deltas.append(delta)
|
||||
used_keys.add(lora_bias_key)
|
||||
else:
|
||||
@@ -85,6 +89,9 @@ def _prepare_lora_delta(
|
||||
return None, used_keys
|
||||
a = lora_state_dict[lora_a_key]
|
||||
b = lora_state_dict[lora_b_key]
|
||||
if compute_device is not None and compute_device.type != "cpu":
|
||||
a = a.to(compute_device)
|
||||
b = b.to(compute_device)
|
||||
delta = torch.matmul(b, a)
|
||||
stacked_deltas.append(delta)
|
||||
used_keys.add(lora_a_key)
|
||||
@@ -99,7 +106,10 @@ def _prepare_lora_delta(
|
||||
if lora_bias_key not in lora_state_dict:
|
||||
return None, used_keys
|
||||
used_keys.add(lora_bias_key)
|
||||
return lora_state_dict[lora_bias_key], used_keys
|
||||
delta = lora_state_dict[lora_bias_key]
|
||||
if compute_device is not None and compute_device.type != "cpu":
|
||||
delta = delta.to(compute_device)
|
||||
return delta, used_keys
|
||||
|
||||
lora_a_key = f"{base_key}.{lora_a_suffix}"
|
||||
lora_b_key = f"{base_key}.{lora_b_suffix}"
|
||||
@@ -107,9 +117,29 @@ def _prepare_lora_delta(
|
||||
return None, used_keys
|
||||
a = lora_state_dict[lora_a_key]
|
||||
b = lora_state_dict[lora_b_key]
|
||||
if compute_device is not None and compute_device.type != "cpu":
|
||||
a = a.to(compute_device)
|
||||
b = b.to(compute_device)
|
||||
delta = torch.matmul(b, a)
|
||||
used_keys.add(lora_a_key)
|
||||
used_keys.add(lora_b_key)
|
||||
return torch.matmul(b, a), used_keys
|
||||
return delta, used_keys
|
||||
|
||||
|
||||
def _resolve_lora_compute_device() -> torch.device | None:
|
||||
"""Return the local accelerator device if actually usable, else None.
|
||||
|
||||
get_local_device() may return cuda:N/npu:N even when no physical device is
|
||||
present, so probe with a tiny allocation before trusting the lookup.
|
||||
"""
|
||||
try:
|
||||
dev = get_local_device()
|
||||
if dev.type != "cpu":
|
||||
torch.empty(1, device=dev)
|
||||
return dev
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _load_lora_state_dict(
|
||||
@@ -262,6 +292,9 @@ class LoraLoaderMixin:
|
||||
for param_name, weight_name, _ in module.stacked_params_mapping:
|
||||
param_to_weight_names[param_name].append(weight_name)
|
||||
|
||||
# Resolve the accelerator fallback once, outside the parameter loop.
|
||||
accel_dev = _resolve_lora_compute_device()
|
||||
|
||||
for name, params in module.named_parameters(prefix):
|
||||
is_bias = False
|
||||
if name.endswith(".bias"):
|
||||
@@ -272,6 +305,7 @@ class LoraLoaderMixin:
|
||||
else:
|
||||
continue
|
||||
|
||||
compute_dev = params.device if params.device.type != "cpu" else accel_dev
|
||||
delta, used_keys = _prepare_lora_delta(
|
||||
state_dict,
|
||||
base_key,
|
||||
@@ -280,6 +314,7 @@ class LoraLoaderMixin:
|
||||
lora_a_suffix,
|
||||
lora_b_suffix,
|
||||
lora_bias_suffix,
|
||||
compute_device=compute_dev,
|
||||
)
|
||||
if delta is None:
|
||||
continue
|
||||
@@ -314,6 +349,9 @@ class LoraLoaderMixin:
|
||||
for param_name, weight_name, _ in module.stacked_params_mapping:
|
||||
param_to_weight_names[param_name].append(weight_name)
|
||||
|
||||
# Resolve the accelerator fallback once, outside the parameter loop.
|
||||
accel_dev = _resolve_lora_compute_device()
|
||||
|
||||
for name, param in module.named_parameters(prefix):
|
||||
is_bias = False
|
||||
if name.endswith(".bias"):
|
||||
@@ -324,6 +362,7 @@ class LoraLoaderMixin:
|
||||
else:
|
||||
continue
|
||||
|
||||
compute_dev = param.device if param.device.type != "cpu" else accel_dev
|
||||
delta, used_keys = _prepare_lora_delta(
|
||||
state_dict,
|
||||
base_key,
|
||||
@@ -332,6 +371,7 @@ class LoraLoaderMixin:
|
||||
lora_a_suffix,
|
||||
lora_b_suffix,
|
||||
lora_bias_suffix,
|
||||
compute_device=compute_dev,
|
||||
)
|
||||
if delta is None:
|
||||
continue
|
||||
|
||||
@@ -394,17 +394,20 @@ class DiffusionLoRAManager:
|
||||
fully_sharded_loras=False,
|
||||
)
|
||||
|
||||
# Default denoising components, declared DiT components, and any a
|
||||
# pipeline opts into via ``_lora_components``.
|
||||
# Components scanned for LoRA-capable layers: framework defaults,
|
||||
# declared DiT components, and any a pipeline opts into via
|
||||
# ``_lora_components``. The defaults only cover the generic diffusers
|
||||
# naming convention: ``transformer`` (plus ``transformer_2`` for
|
||||
# dual-DiT pipelines such as Wan2.2) and ``unet`` for SDXL-style
|
||||
# pipelines. Model-specific attribute names must be declared by the
|
||||
# pipeline itself via ``_dit_modules`` or ``_lora_components``.
|
||||
#
|
||||
# NOTE: SDXL-style pipelines expose the denoiser as ``unet``.
|
||||
# Without scanning this component, adapters can load/activate while
|
||||
# effectively applying to zero layers, producing base-identical output.
|
||||
# NOTE: if the denoiser component is not scanned here, adapters can
|
||||
# load/activate while effectively applying to zero layers, producing
|
||||
# base-identical output.
|
||||
default_components = (
|
||||
"transformer",
|
||||
"transformer_2",
|
||||
"dit",
|
||||
"bagel",
|
||||
"unet",
|
||||
)
|
||||
declared_components = tuple(getattr(self.pipeline, "_dit_modules", ()) or ())
|
||||
@@ -556,9 +559,9 @@ class DiffusionLoRAManager:
|
||||
|
||||
def _bind_adapter_weights(self, lora_model: LoRAModel, scale: float) -> None:
|
||||
binding_validator = getattr(self.pipeline, "_validate_diffusion_lora_binding", None)
|
||||
lora_names_by_id = (
|
||||
{id(weights): name for name, weights in lora_model.loras.items()} if callable(binding_validator) else {}
|
||||
)
|
||||
# Track bindings unconditionally. The zero-binding guard below needs this
|
||||
# bookkeeping on every pipeline, not only the ones that supply a validator.
|
||||
lora_names_by_id = {id(weights): name for name, weights in lora_model.loras.items()}
|
||||
bound_lora_names: set[str] = set()
|
||||
|
||||
def _record_bound(weights: LoRALayerWeights | PackedLoRALayerWeights) -> None:
|
||||
@@ -677,6 +680,13 @@ class DiffusionLoRAManager:
|
||||
scale,
|
||||
)
|
||||
|
||||
if not bound_lora_names:
|
||||
raise ValueError(
|
||||
f"LoRA adapter {lora_model.id} applies to no layer: expected target modules in "
|
||||
f"{sorted(self._expected_lora_modules)} but received {sorted(lora_model.loras)}. "
|
||||
"Activating it would leave the base model unchanged."
|
||||
)
|
||||
|
||||
if callable(binding_validator):
|
||||
binding_validator(
|
||||
lora_model=lora_model,
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field, replace
|
||||
from enum import Enum
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
class VideoTensorLayout(str, Enum):
|
||||
BCTHW = "bcthw"
|
||||
BTHWC = "bthwc"
|
||||
|
||||
|
||||
class VideoTensorEncoding(str, Enum):
|
||||
NORMALIZED_FLOAT = "normalized_float"
|
||||
UINT8_FRAMES = "uint8_frames"
|
||||
|
||||
|
||||
class VideoValueRange(str, Enum):
|
||||
NEGATIVE_ONE_TO_ONE = "negative_one_to_one"
|
||||
ZERO_TO_ONE = "zero_to_one"
|
||||
ZERO_TO_255 = "zero_to_255"
|
||||
|
||||
|
||||
class VideoColorModel(str, Enum):
|
||||
RGB = "rgb"
|
||||
|
||||
|
||||
class FloatVideoConsumer(str, Enum):
|
||||
FRAME_INTERPOLATION = "frame_interpolation"
|
||||
VIDEO_GUARDRAILS = "video_guardrails"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VideoTensorSpec:
|
||||
layout: VideoTensorLayout
|
||||
encoding: VideoTensorEncoding
|
||||
value_range: VideoValueRange
|
||||
color_model: VideoColorModel = VideoColorModel.RGB
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VideoTransportConstraints:
|
||||
pending_float_consumers: frozenset[FloatVideoConsumer] = frozenset()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class VideoMediaOutput:
|
||||
tensor: torch.Tensor
|
||||
spec: VideoTensorSpec
|
||||
constraints: VideoTransportConstraints = field(default_factory=VideoTransportConstraints)
|
||||
schema_version: Literal[1] = 1
|
||||
|
||||
def validate(self) -> None:
|
||||
if self.schema_version != 1:
|
||||
raise ValueError(f"Unsupported video media schema version: {self.schema_version}")
|
||||
if not isinstance(self.spec, VideoTensorSpec):
|
||||
raise TypeError(f"Video media spec must be a VideoTensorSpec, got {type(self.spec).__name__}")
|
||||
if not isinstance(self.constraints, VideoTransportConstraints):
|
||||
raise TypeError(
|
||||
f"Video media constraints must be VideoTransportConstraints, got {type(self.constraints).__name__}"
|
||||
)
|
||||
if not isinstance(self.constraints.pending_float_consumers, frozenset):
|
||||
raise TypeError("pending_float_consumers must be a frozenset")
|
||||
if not isinstance(self.tensor, torch.Tensor):
|
||||
raise TypeError(f"Video media tensor must be a torch.Tensor, got {type(self.tensor).__name__}")
|
||||
if self.tensor.ndim != 5:
|
||||
raise ValueError(f"Video media tensor must be rank 5, got shape {tuple(self.tensor.shape)}")
|
||||
if any(size <= 0 for size in self.tensor.shape):
|
||||
raise ValueError(f"Video media dimensions must be positive, got shape {tuple(self.tensor.shape)}")
|
||||
if self.spec.color_model is not VideoColorModel.RGB:
|
||||
raise ValueError(f"Unsupported video color model: {self.spec.color_model}")
|
||||
if any(not isinstance(consumer, FloatVideoConsumer) for consumer in self.constraints.pending_float_consumers):
|
||||
raise ValueError("pending_float_consumers must contain only FloatVideoConsumer values")
|
||||
|
||||
if self.spec.encoding is VideoTensorEncoding.NORMALIZED_FLOAT:
|
||||
self._validate_normalized_float()
|
||||
return
|
||||
if self.spec.encoding is VideoTensorEncoding.UINT8_FRAMES:
|
||||
self._validate_uint8_frames()
|
||||
return
|
||||
raise ValueError(f"Unsupported video tensor encoding: {self.spec.encoding}")
|
||||
|
||||
def _validate_normalized_float(self) -> None:
|
||||
if self.spec.layout is not VideoTensorLayout.BCTHW:
|
||||
raise ValueError("NORMALIZED_FLOAT video must use BCTHW layout")
|
||||
if self.tensor.shape[1] != 3:
|
||||
raise ValueError(f"RGB BCTHW video must have 3 channels, got {self.tensor.shape[1]}")
|
||||
if self.tensor.dtype not in {torch.float16, torch.bfloat16, torch.float32}:
|
||||
raise ValueError(f"NORMALIZED_FLOAT video must use fp16, bf16, or fp32, got {self.tensor.dtype}")
|
||||
if self.spec.value_range not in {
|
||||
VideoValueRange.NEGATIVE_ONE_TO_ONE,
|
||||
VideoValueRange.ZERO_TO_ONE,
|
||||
}:
|
||||
raise ValueError(f"NORMALIZED_FLOAT video has incompatible value range: {self.spec.value_range}")
|
||||
|
||||
def _validate_uint8_frames(self) -> None:
|
||||
if self.spec.layout is not VideoTensorLayout.BTHWC:
|
||||
raise ValueError("UINT8_FRAMES video must use BTHWC layout")
|
||||
if self.tensor.shape[-1] != 3:
|
||||
raise ValueError(f"RGB BTHWC video must have 3 channels, got {self.tensor.shape[-1]}")
|
||||
if self.tensor.dtype is not torch.uint8:
|
||||
raise ValueError(f"UINT8_FRAMES video must use torch.uint8, got {self.tensor.dtype}")
|
||||
if self.spec.value_range is not VideoValueRange.ZERO_TO_255:
|
||||
raise ValueError(f"UINT8_FRAMES video has incompatible value range: {self.spec.value_range}")
|
||||
if self.constraints.pending_float_consumers:
|
||||
raise ValueError("UINT8_FRAMES video cannot have pending float consumers")
|
||||
if not self.tensor.is_contiguous():
|
||||
raise ValueError("UINT8_FRAMES video tensor must be contiguous")
|
||||
|
||||
def with_tensor(self, tensor: torch.Tensor) -> VideoMediaOutput:
|
||||
return replace(self, tensor=tensor)
|
||||
|
||||
def to_cpu(self) -> VideoMediaOutput:
|
||||
return self.with_tensor(self.tensor.detach().cpu())
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DiffusionMediaOutput:
|
||||
video: VideoMediaOutput
|
||||
# Only the model runner may set this before worker output packing.
|
||||
prepared_for_transport: bool = False
|
||||
|
||||
def validate(self) -> None:
|
||||
if not isinstance(self.video, VideoMediaOutput):
|
||||
raise TypeError(f"Diffusion media video must be a VideoMediaOutput, got {type(self.video).__name__}")
|
||||
if not isinstance(self.prepared_for_transport, bool):
|
||||
raise TypeError("prepared_for_transport must be a bool")
|
||||
self.video.validate()
|
||||
if not self.prepared_for_transport:
|
||||
return
|
||||
if not self.video.tensor.is_contiguous():
|
||||
raise ValueError("Prepared video media tensor must be contiguous")
|
||||
if not _owns_compact_storage(self.video.tensor):
|
||||
raise ValueError("Prepared video media tensor must own request-local storage")
|
||||
|
||||
def with_video(self, video: VideoMediaOutput) -> DiffusionMediaOutput:
|
||||
return replace(self, video=video)
|
||||
|
||||
def to_cpu(self) -> DiffusionMediaOutput:
|
||||
self.validate()
|
||||
moved = self.with_video(self.video.to_cpu())
|
||||
moved.validate()
|
||||
return moved
|
||||
|
||||
|
||||
def _owns_compact_storage(tensor: torch.Tensor) -> bool:
|
||||
"""True if *tensor* is contiguous and backed by exactly its own elements.
|
||||
|
||||
``tensor._base is None`` is not sufficient: ``batch[i : i + 1].detach()`` is
|
||||
contiguous with ``_base=None`` yet keeps a nonzero storage offset and the
|
||||
whole batch storage, so serializing it would leak every other request's
|
||||
pixels. Require a zero offset and a storage sized to the logical elements.
|
||||
"""
|
||||
if not tensor.is_contiguous():
|
||||
return False
|
||||
if tensor.storage_offset() != 0:
|
||||
return False
|
||||
try:
|
||||
storage_bytes = tensor.untyped_storage().nbytes()
|
||||
except Exception:
|
||||
return False
|
||||
return storage_bytes == tensor.numel() * tensor.element_size()
|
||||
|
||||
|
||||
def ensure_request_owned_tensor(tensor: torch.Tensor) -> torch.Tensor:
|
||||
if _owns_compact_storage(tensor):
|
||||
return tensor
|
||||
# A contiguous view may still retain another request's full batch storage.
|
||||
return tensor.clone(memory_format=torch.contiguous_format)
|
||||
|
||||
|
||||
def slice_diffusion_media_output(
|
||||
media: DiffusionMediaOutput,
|
||||
start: int,
|
||||
stop: int,
|
||||
) -> DiffusionMediaOutput:
|
||||
media.validate()
|
||||
source = media.video.tensor
|
||||
tensor = source if start == 0 and stop == source.shape[0] else source[start:stop]
|
||||
sliced = replace(media, video=media.video.with_tensor(tensor), prepared_for_transport=False)
|
||||
sliced.validate()
|
||||
return sliced
|
||||
@@ -17,10 +17,17 @@ MODEL_OPT_SCALE_SUFFIXES = (
|
||||
".weight_scale_2",
|
||||
".weight_scale_inv",
|
||||
)
|
||||
# Fused projections following the generic diffusers Attention naming
|
||||
# convention. ``to_q``/``to_k``/``to_v`` and the joint-attention
|
||||
# ``add_q_proj``/``add_k_proj``/``add_v_proj`` shard names are fused into
|
||||
# ``to_qkv``/``add_kv_proj`` by most vllm-omni DiT implementations, many of
|
||||
# which do not declare their own ``packed_modules_mapping``; keeping these
|
||||
# two entries here avoids repeating them in every such model. Model-specific
|
||||
# fusions (e.g. Z-Image's ``w13``) must be declared on the model class via
|
||||
# ``packed_modules_mapping``, which is merged on top of these defaults.
|
||||
DEFAULT_PACKED_MODULES_MAPPING = {
|
||||
"to_qkv": ("to_q", "to_k", "to_v"),
|
||||
"add_kv_proj": ("add_q_proj", "add_k_proj", "add_v_proj"),
|
||||
"w13": ("w1", "w3"),
|
||||
}
|
||||
FP8_DTYPES = tuple(
|
||||
dtype
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from collections.abc import Generator, Iterable, Sequence
|
||||
from collections.abc import Callable, Generator, Iterable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
|
||||
@@ -481,8 +481,14 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
)
|
||||
|
||||
def _get_expected_parameter_names(self, model: nn.Module) -> set[str]:
|
||||
"""Return parameter names that should be covered by strict load checks."""
|
||||
all_parameter_names = {name for name, _ in model.named_parameters()}
|
||||
"""Return parameter names that should be covered by strict load checks.
|
||||
|
||||
A parameter with an initialized checkpoint default can explicitly set
|
||||
``is_checkpoint_optional``. It is still loaded when present on disk.
|
||||
"""
|
||||
all_parameter_names = {
|
||||
name for name, param in model.named_parameters() if not getattr(param, "is_checkpoint_optional", False)
|
||||
}
|
||||
sources = self._get_weight_sources(model)
|
||||
|
||||
# Keep strict behavior if no source metadata exists.
|
||||
@@ -509,11 +515,6 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
if getattr(model, "lora_is_fused", False):
|
||||
return
|
||||
|
||||
# A warm HWR restore already brings back the fused final-layout weights.
|
||||
if self._hwr_state is not None and self._hwr_state.get("warm_snapshot") is not None:
|
||||
setattr(model, "lora_is_fused", True)
|
||||
return
|
||||
|
||||
lora_path = getattr(self.od_config, "lora_path", None)
|
||||
if not lora_path:
|
||||
return
|
||||
@@ -531,6 +532,111 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
else:
|
||||
logger.warning("Pipeline %s does not support loading distilled LoRA weights.", model.__class__.__name__)
|
||||
|
||||
def _broadcast_model_weights(
|
||||
self,
|
||||
model: nn.Module,
|
||||
target_device: torch.device,
|
||||
src_rank: int = 0,
|
||||
bucket_cap_bytes: int = 256 * 1024 * 1024,
|
||||
) -> None:
|
||||
"""Broadcast model parameters and buffers from src_rank to all other ranks using coalesced bucketing."""
|
||||
if not torch.distributed.is_initialized() or torch.distributed.get_world_size() <= 1:
|
||||
return
|
||||
|
||||
rank = torch.distributed.get_rank()
|
||||
world_size = torch.distributed.get_world_size()
|
||||
backend = torch.distributed.get_backend()
|
||||
is_cpu_backend = backend == "gloo"
|
||||
|
||||
logger.info(
|
||||
"Worker %d: %s full model weights via %s across %d ranks",
|
||||
rank,
|
||||
"Broadcasting" if rank == src_rank else "Receiving",
|
||||
backend,
|
||||
world_size,
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
|
||||
all_tensors = [p.data for _, p in model.named_parameters() if p.numel() > 0] + [
|
||||
b.data for _, b in model.named_buffers() if b.numel() > 0
|
||||
]
|
||||
if not all_tensors:
|
||||
return
|
||||
|
||||
count = len(all_tensors)
|
||||
total_bytes = sum(t.numel() * t.element_size() for t in all_tensors)
|
||||
|
||||
# Group tensors into buckets by dtype and maximum byte size
|
||||
buckets: list[list[torch.Tensor]] = []
|
||||
curr_bucket: list[torch.Tensor] = []
|
||||
curr_bytes = 0
|
||||
|
||||
for tensor in all_tensors:
|
||||
t_bytes = tensor.numel() * tensor.element_size()
|
||||
if curr_bucket and (curr_bucket[0].dtype != tensor.dtype or curr_bytes + t_bytes > bucket_cap_bytes):
|
||||
buckets.append(curr_bucket)
|
||||
curr_bucket = []
|
||||
curr_bytes = 0
|
||||
curr_bucket.append(tensor)
|
||||
curr_bytes += t_bytes
|
||||
|
||||
if curr_bucket:
|
||||
buckets.append(curr_bucket)
|
||||
|
||||
for bucket in buckets:
|
||||
tot_numel = sum(t.numel() for t in bucket)
|
||||
dtype = bucket[0].dtype
|
||||
|
||||
if is_cpu_backend:
|
||||
if rank == src_rank:
|
||||
flat_cpu = torch.cat([t.detach().to("cpu").reshape(-1) for t in bucket])
|
||||
else:
|
||||
flat_cpu = torch.empty(tot_numel, dtype=dtype)
|
||||
torch.distributed.broadcast(flat_cpu, src=src_rank)
|
||||
if rank != src_rank:
|
||||
offset = 0
|
||||
for t in bucket:
|
||||
n = t.numel()
|
||||
t.copy_(flat_cpu[offset : offset + n].view_as(t))
|
||||
offset += n
|
||||
del flat_cpu
|
||||
else:
|
||||
if rank == src_rank:
|
||||
flat_cpu = torch.cat([t.detach().to("cpu").reshape(-1) for t in bucket])
|
||||
dev_flat = flat_cpu.to(target_device, non_blocking=False)
|
||||
del flat_cpu
|
||||
torch.distributed.broadcast(dev_flat, src=src_rank)
|
||||
del dev_flat
|
||||
else:
|
||||
dev_flat = torch.empty(tot_numel, dtype=dtype, device=target_device)
|
||||
torch.distributed.broadcast(dev_flat, src=src_rank)
|
||||
flat_cpu = dev_flat.to("cpu", non_blocking=False)
|
||||
del dev_flat
|
||||
offset = 0
|
||||
for t in bucket:
|
||||
n = t.numel()
|
||||
t.copy_(flat_cpu[offset : offset + n].view_as(t), non_blocking=False)
|
||||
offset += n
|
||||
del flat_cpu
|
||||
|
||||
if not is_cpu_backend and target_device.type != "cpu":
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
torch.distributed.barrier()
|
||||
|
||||
elapsed = time.perf_counter() - t0
|
||||
gb = total_bytes / 1e9
|
||||
logger.info(
|
||||
"Worker %d: Shared weight broadcast complete (%d tensors, %d buckets, %.2f GB) in %.2fs (%.2f GB/s)",
|
||||
rank,
|
||||
count,
|
||||
len(buckets),
|
||||
gb,
|
||||
elapsed,
|
||||
gb / max(elapsed, 1e-6),
|
||||
)
|
||||
|
||||
def load_model(
|
||||
self,
|
||||
load_device: str,
|
||||
@@ -573,10 +679,21 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
with set_default_torch_dtype(self.od_config.dtype):
|
||||
if self.parallel_config.use_hsdp:
|
||||
model = self._load_model_with_hsdp(
|
||||
target_device=device, load_format=load_format, custom_pipeline_name=custom_pipeline_name
|
||||
target_device=device,
|
||||
load_format=load_format,
|
||||
custom_pipeline_name=custom_pipeline_name,
|
||||
offload_after_quant=offload_after_quant,
|
||||
)
|
||||
else:
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=False)
|
||||
# The model is headed back to host memory right after online
|
||||
# quantization, so over-wide NPU-unquantizable fallback weights
|
||||
# load straight into host memory instead of round-tripping
|
||||
# through the accelerator (~24 GiB startup peak on MiniMax H3).
|
||||
from vllm_omni.quantization.int8_config import load_unquantizable_fallback_on_cpu
|
||||
|
||||
fallback_ctx = load_unquantizable_fallback_on_cpu() if offload_after_quant else contextlib.nullcontext()
|
||||
with fallback_ctx:
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=False)
|
||||
|
||||
resolved_offload = resolve_offload(self.od_config)
|
||||
distributed_offload = resolved_offload.strategy is OffloadStrategy.DISTRIBUTED_LAYER_WISE
|
||||
@@ -615,8 +732,9 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
if unsupported_methods:
|
||||
raise ValueError(
|
||||
"DLO+AllGather supports online quantization only for "
|
||||
"per-tensor FP8, INT8, and MXFP8 linears; unsupported "
|
||||
f"online methods: {', '.join(sorted(unsupported_methods))}. "
|
||||
"per-tensor FP8, INT8, and MXFP8 linears "
|
||||
"(host-loaded unquantized fallback layers are also allowed); "
|
||||
f"unsupported online methods: {', '.join(sorted(unsupported_methods))}. "
|
||||
"Use rank-local transfer for the affected component or "
|
||||
"disable online quantization."
|
||||
)
|
||||
@@ -654,6 +772,10 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
if hwr_active and hwr_state is not None:
|
||||
self.host_weight_plan = cast(HostWeightPlan | None, hwr_state.get("plan"))
|
||||
if dit_distributed_offload and not hwr_active and not self._force_canonical_load:
|
||||
lora_backend = getattr(self.od_config, "lora_backend", None)
|
||||
has_distilled_lora = lora_backend in (LoRABackend.DISTILL, "distill") and bool(
|
||||
getattr(self.od_config, "lora_path", None)
|
||||
)
|
||||
plan_result = build_checkpoint_mmap_plan(
|
||||
model,
|
||||
dit_modules=tuple(zip(modules.dit_names, modules.dits)),
|
||||
@@ -662,6 +784,7 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
tensor_parallel_size=tensor_parallel_size,
|
||||
use_hsdp=use_hsdp,
|
||||
online_quantization=any(self._has_online_quant(dit) for dit in modules.dits),
|
||||
has_distilled_lora=has_distilled_lora,
|
||||
)
|
||||
self.host_weight_plan = plan_result.plan
|
||||
|
||||
@@ -689,7 +812,6 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
sources=ordinary_sources,
|
||||
planned_weights=host_weight_plan.bindings,
|
||||
)
|
||||
self._maybe_fuse_distilled_lora(model)
|
||||
else:
|
||||
if dit_distributed_offload and plan_result is not None:
|
||||
logger.info(
|
||||
@@ -749,9 +871,24 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
del model
|
||||
return self.load_fresh_canonical_model()
|
||||
raise
|
||||
self._log_w4a8_fallback_load_summaries(model)
|
||||
self._attach_offload_startup_state(model)
|
||||
return model
|
||||
|
||||
@staticmethod
|
||||
def _log_w4a8_fallback_load_summaries(model: nn.Module) -> None:
|
||||
"""Ask discovered DiTs to report W4A8 state at the common load exit.
|
||||
|
||||
Each DiT derives readiness from its processed layers, so a deferred
|
||||
weight plan cannot be mistaken for the ordinary or HSDP load path.
|
||||
"""
|
||||
components = ModuleDiscovery.discover(model)
|
||||
for component_name, dit in zip(components.dit_names, components.dits):
|
||||
candidate = getattr(dit, "_log_w4a8_fallback_load_summary", None)
|
||||
if callable(candidate):
|
||||
reporter = cast(Callable[[str], None], candidate)
|
||||
reporter(component_name)
|
||||
|
||||
@staticmethod
|
||||
def _request_offload_after_quant(model: nn.Module) -> int:
|
||||
"""Ask online-quant layers to return to host memory once quantized.
|
||||
@@ -805,6 +942,11 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
scale, packing, or aliasing layouts (e.g. dual-scale fp4 pairs,
|
||||
swizzled or NZ hardware formats) and remain fail-closed until
|
||||
validated.
|
||||
|
||||
``UnquantizedHostLinearMethod`` is also allowed: it backs layers too
|
||||
wide for npu_quant_matmul, loads their weights straight into host
|
||||
memory, and its runtime layout is a plain contiguous bf16 weight —
|
||||
identical to the ordinary unquantized path DLO already shards.
|
||||
"""
|
||||
from vllm.model_executor.layers.quantization.online.fp8 import (
|
||||
Fp8PerTensorOnlineLinearMethod,
|
||||
@@ -813,6 +955,7 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
from vllm_omni.quantization.int8_config import (
|
||||
Int8OnlineLinearMethod,
|
||||
NPUInt8OnlineLinearMethod,
|
||||
UnquantizedHostLinearMethod,
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -834,6 +977,7 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
Fp8PerTensorOnlineLinearMethod,
|
||||
Int8OnlineLinearMethod,
|
||||
NPUInt8OnlineLinearMethod,
|
||||
UnquantizedHostLinearMethod,
|
||||
*mxfp8_online_methods,
|
||||
)
|
||||
|
||||
@@ -961,6 +1105,16 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
# that have loaded weights tracking currently.
|
||||
if loaded_weights is not None:
|
||||
weights_not_loaded = weights_to_load - loaded_weights
|
||||
# Offline formats can require scales that older online loaders
|
||||
# were allowed to synthesize. Do not apply that legacy tolerance
|
||||
# to an explicitly required checkpoint tensor.
|
||||
required_missing = {
|
||||
name
|
||||
for name, param in model.named_parameters()
|
||||
if name in weights_not_loaded and getattr(param, "is_checkpoint_required", False)
|
||||
}
|
||||
if required_missing:
|
||||
raise ValueError(f"Required weights were not initialized from checkpoint: {required_missing}")
|
||||
# NOTE: if the model is quantized, ignore not_loaded check for scale
|
||||
# weights. ModelOpt FP8 carries a per-tensor `weight_scale` and a
|
||||
# static activation `input_scale`, which the quant method may
|
||||
@@ -1073,6 +1227,7 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
target_device: torch.device,
|
||||
load_format: str = "default",
|
||||
custom_pipeline_name: str | type[nn.Module] | None = None,
|
||||
offload_after_quant: bool = False,
|
||||
) -> nn.Module:
|
||||
"""Load model with HSDP sharding for inference.
|
||||
|
||||
@@ -1096,9 +1251,54 @@ class DiffusersPipelineLoader(HWRLoaderMixin):
|
||||
# mapping (QKV fusion, etc.).
|
||||
if load_format == "diffusers":
|
||||
raise ValueError("HSDP is not supported with the diffusers adapter load format")
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=True)
|
||||
self.load_weights(model)
|
||||
self._maybe_fuse_distilled_lora(model)
|
||||
# Same host-fallback bound as the ordinary path: with a quant config the
|
||||
# HSDP path initializes on the accelerator (hsdp_defer_to_cpu=False), so
|
||||
# over-wide NPU-unquantizable fallback weights would otherwise round-trip
|
||||
# through the device before apply_hsdp_to_model shards them. Loading them
|
||||
# straight into host memory keeps the load-time device peak at the
|
||||
# quantizable layers alone; sharding then distributes the fallback like
|
||||
# any other parameter. Broadcast loading excludes online quantization
|
||||
# already, so the context below only ever matters on the ordinary
|
||||
# per-rank branch -- but spanning both is harmless.
|
||||
from vllm_omni.quantization.int8_config import load_unquantizable_fallback_on_cpu
|
||||
|
||||
fallback_ctx = load_unquantizable_fallback_on_cpu() if offload_after_quant else contextlib.nullcontext()
|
||||
with fallback_ctx:
|
||||
model = self._init_from_load_format(load_format, target_device, custom_pipeline_name, is_hsdp=True)
|
||||
world_size = 1
|
||||
rank = 0
|
||||
if torch.distributed.is_initialized():
|
||||
world_size = torch.distributed.get_world_size()
|
||||
rank = torch.distributed.get_rank()
|
||||
|
||||
has_online_quant = self._has_online_quant(model) or (
|
||||
self.quant_config is not None and not getattr(self.quant_config, "is_checkpoint_quantized", False)
|
||||
)
|
||||
enable_broadcast = bool(getattr(self.od_config, "enable_broadcast_weight_load", False)) and world_size > 1
|
||||
|
||||
if enable_broadcast and has_online_quant:
|
||||
logger.info(
|
||||
"Worker %d: Online quantization detected; falling back to ordinary "
|
||||
"per-rank weight loading for HSDP",
|
||||
rank,
|
||||
)
|
||||
enable_broadcast = False
|
||||
|
||||
if enable_broadcast:
|
||||
if rank == 0:
|
||||
self.load_weights(model)
|
||||
self._maybe_fuse_distilled_lora(model)
|
||||
self._broadcast_model_weights(model, target_device=target_device, src_rank=0)
|
||||
if (
|
||||
rank != 0
|
||||
and getattr(self.od_config, "lora_backend", None) in (LoRABackend.DISTILL, "distill")
|
||||
and getattr(self.od_config, "lora_path", None)
|
||||
and hasattr(model, "load_lora_weights")
|
||||
):
|
||||
setattr(model, "lora_is_fused", True)
|
||||
else:
|
||||
self.load_weights(model)
|
||||
self._maybe_fuse_distilled_lora(model)
|
||||
|
||||
# Quantization methods must finish while parameters are ordinary local
|
||||
# tensors. Some post-load transforms use operations (for example,
|
||||
|
||||
@@ -322,6 +322,7 @@ def build_checkpoint_mmap_plan(
|
||||
tensor_parallel_size: int,
|
||||
use_hsdp: bool,
|
||||
online_quantization: bool,
|
||||
has_distilled_lora: bool = False,
|
||||
) -> HostWeightPlanResult:
|
||||
"""Build a complete direct-checkpoint plan or return a fallback reason."""
|
||||
if tensor_parallel_size != 1:
|
||||
@@ -330,6 +331,8 @@ def build_checkpoint_mmap_plan(
|
||||
return HostWeightPlanResult(None, "HSDP requires the ordinary loader")
|
||||
if online_quantization:
|
||||
return HostWeightPlanResult(None, "online quantization requires the ordinary loader")
|
||||
if has_distilled_lora:
|
||||
return HostWeightPlanResult(None, "distilled LoRA requires the ordinary loader")
|
||||
|
||||
remap_fn = getattr(type(pipeline), "_remap_ckpt_key", None)
|
||||
if not callable(remap_fn):
|
||||
|
||||
@@ -30,8 +30,7 @@ Two environmental factors mask the race on main:
|
||||
``cached_files`` (plural) which batch-resolves every shard listed in the
|
||||
index up-front via ``os.path.isfile`` and raises immediately if any shard
|
||||
is still sitting under its ``*.incomplete`` name. Same wave of v5 changes
|
||||
that introduced ``tie_weights(missing_keys=..., recompute_mapping=...)``
|
||||
(see the Dynin shim in ``dynin_omni_token2text.py``).
|
||||
that introduced ``tie_weights(missing_keys=..., recompute_mapping=...)``.
|
||||
* CI shares ``HF_HOME=/fsx/hf_cache`` across pipelines (both the
|
||||
``vllm-omni`` and ``vllm-omni-rebase`` pipelines mount the same FS). That
|
||||
cache is normally warm for long-lived repos like ``Qwen-Image-Edit-2509``,
|
||||
@@ -195,19 +194,22 @@ def _repo_prefetch_lock(model: str) -> Iterator[None]:
|
||||
flock_held = False
|
||||
|
||||
# --- fcntl.flock path ---
|
||||
fcntl_mod: Any = None
|
||||
try:
|
||||
import fcntl # type: ignore[import-not-found]
|
||||
except ImportError: # pragma: no cover - non-POSIX (Windows)
|
||||
fcntl = None
|
||||
import fcntl as _fcntl
|
||||
|
||||
if fcntl is not None:
|
||||
fcntl_mod = _fcntl
|
||||
except ImportError: # pragma: no cover - non-POSIX (Windows)
|
||||
pass
|
||||
|
||||
if fcntl_mod is not None:
|
||||
try:
|
||||
lock_dir = _node_lock_dir()
|
||||
except OSError as exc:
|
||||
logger.warning("Could not allocate lock dir for prefetch of %s (%s); skipping flock", model, exc)
|
||||
fcntl = None # force dotfile fallback
|
||||
fcntl_mod = None # force dotfile fallback
|
||||
|
||||
if fcntl is not None and lock_dir is not None:
|
||||
if fcntl_mod is not None and lock_dir is not None:
|
||||
lock_path = os.path.join(lock_dir, _safe_repo_filename(model))
|
||||
try:
|
||||
fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
@@ -217,7 +219,7 @@ def _repo_prefetch_lock(model: str) -> Iterator[None]:
|
||||
|
||||
if fd is not None:
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
fcntl_mod.flock(fd, fcntl_mod.LOCK_EX)
|
||||
flock_held = True
|
||||
logger.info("Acquired flock prefetch lock for %s at %s", model, lock_path)
|
||||
except OSError as exc:
|
||||
@@ -249,9 +251,9 @@ def _repo_prefetch_lock(model: str) -> Iterator[None]:
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if flock_held and fd is not None:
|
||||
if flock_held and fd is not None and fcntl_mod is not None:
|
||||
with contextlib.suppress(OSError):
|
||||
fcntl.flock(fd, fcntl.LOCK_UN)
|
||||
fcntl_mod.flock(fd, fcntl_mod.LOCK_UN)
|
||||
if fd is not None:
|
||||
with contextlib.suppress(OSError):
|
||||
os.close(fd)
|
||||
|
||||
@@ -17,8 +17,14 @@ class DiffusionModelMetadata:
|
||||
supported_control_upload_types: tuple[str, ...] = ()
|
||||
attention_mask_free: bool = False
|
||||
final_output_type: str | None = None
|
||||
# Whether ``/v1/videos`` accepts source media plus per-token video/audio
|
||||
# noise masks for latent initialization. Unknown pipelines must remain
|
||||
# opted out so uploaded files never reach a model that cannot consume them.
|
||||
supports_latent_mask_editing: bool = False
|
||||
|
||||
|
||||
# FLUX.2 Klein supports up to four reference images.
|
||||
FLUX2_KLEIN_MAX_INPUT_IMAGES = 4
|
||||
QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES = 4
|
||||
# Qwen-Image 2.1 image-conditioned generation caps condition images at 4.
|
||||
QWEN_IMAGE_21_MAX_INPUT_IMAGES = 4
|
||||
@@ -29,6 +35,10 @@ BOOGU_IMAGE_MAX_INPUT_IMAGES = 1
|
||||
|
||||
|
||||
_DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
"Flux2KleinPipeline": DiffusionModelMetadata(
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=FLUX2_KLEIN_MAX_INPUT_IMAGES,
|
||||
),
|
||||
"QwenImageEditPlusPipeline": DiffusionModelMetadata(
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=QWEN_IMAGE_EDIT_PLUS_MAX_INPUT_IMAGES,
|
||||
@@ -54,6 +64,7 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=9,
|
||||
supports_mixed_reference_inputs=True,
|
||||
supports_latent_mask_editing=True,
|
||||
final_output_type="video",
|
||||
# H3 represents alignment padding as a second packed sequence. The
|
||||
# packed TRTLLM backend consumes cu_seqlens and isolates that padding.
|
||||
@@ -68,6 +79,7 @@ _DIFFUSION_MODEL_METADATA: dict[str, DiffusionModelMetadata] = {
|
||||
supports_multimodal_inputs=True,
|
||||
max_multimodal_image_inputs=9,
|
||||
supports_mixed_reference_inputs=True,
|
||||
supports_latent_mask_editing=True,
|
||||
final_output_type="video",
|
||||
attention_mask_free=True,
|
||||
),
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from vllm_omni.diffusion.models.anima.pipeline_anima import AnimaPipeline
|
||||
|
||||
__all__ = [
|
||||
"AnimaPipeline",
|
||||
]
|
||||
@@ -0,0 +1,321 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from collections.abc import Iterable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
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
|
||||
|
||||
ANIMA_TEXT_CONDITIONER_CONFIG = {
|
||||
"source_dim": 1024,
|
||||
"target_dim": 1024,
|
||||
"model_dim": 1024,
|
||||
"num_layers": 6,
|
||||
"num_attention_heads": 16,
|
||||
"mlp_ratio": 4.0,
|
||||
"target_vocab_size": 32128,
|
||||
"use_self_attention": True,
|
||||
"use_layer_norm": False,
|
||||
"min_sequence_length": 512,
|
||||
}
|
||||
|
||||
|
||||
def _rotate_half(hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
hidden_states_1 = hidden_states[..., : hidden_states.shape[-1] // 2]
|
||||
hidden_states_2 = hidden_states[..., hidden_states.shape[-1] // 2 :]
|
||||
return torch.cat((-hidden_states_2, hidden_states_1), dim=-1)
|
||||
|
||||
|
||||
def _apply_rotary_pos_emb(
|
||||
hidden_states: torch.Tensor,
|
||||
cos: torch.Tensor,
|
||||
sin: torch.Tensor,
|
||||
unsqueeze_dim: int = 1,
|
||||
) -> torch.Tensor:
|
||||
cos = cos.unsqueeze(unsqueeze_dim)
|
||||
sin = sin.unsqueeze(unsqueeze_dim)
|
||||
return (hidden_states * cos) + (_rotate_half(hidden_states) * sin)
|
||||
|
||||
|
||||
class AnimaRotaryEmbedding(nn.Module):
|
||||
def __init__(self, head_dim: int, rope_theta: float = 10000.0) -> None:
|
||||
super().__init__()
|
||||
inv_freq = 1.0 / (
|
||||
rope_theta ** (torch.arange(0, head_dim, 2, dtype=torch.int64).to(dtype=torch.float32) / head_dim)
|
||||
)
|
||||
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
||||
inv_freq_expanded = inv_freq_expanded.to(hidden_states.device)
|
||||
position_ids_expanded = position_ids[:, None, :].float()
|
||||
|
||||
freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2)
|
||||
emb = torch.cat((freqs, freqs), dim=-1)
|
||||
cos = emb.cos()
|
||||
sin = emb.sin()
|
||||
return cos.to(dtype=hidden_states.dtype), sin.to(dtype=hidden_states.dtype)
|
||||
|
||||
|
||||
class AnimaTextConditionerAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
query_dim: int,
|
||||
context_dim: int,
|
||||
num_attention_heads: int,
|
||||
attention_head_dim: int,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
inner_dim = num_attention_heads * attention_head_dim
|
||||
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.attention_head_dim = attention_head_dim
|
||||
self.q_proj = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.q_norm = nn.RMSNorm(attention_head_dim, eps=1e-6)
|
||||
self.k_proj = nn.Linear(context_dim, inner_dim, bias=False)
|
||||
self.k_norm = nn.RMSNorm(attention_head_dim, eps=1e-6)
|
||||
self.v_proj = nn.Linear(context_dim, inner_dim, bias=False)
|
||||
self.o_proj = nn.Linear(inner_dim, query_dim, bias=False)
|
||||
self.attn = Attention(
|
||||
num_heads=num_attention_heads,
|
||||
head_size=attention_head_dim,
|
||||
softmax_scale=1.0 / (attention_head_dim**0.5),
|
||||
causal=False,
|
||||
num_kv_heads=num_attention_heads,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
encoder_hidden_states: torch.Tensor | None = None,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
encoder_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
encoder_hidden_states = hidden_states if encoder_hidden_states is None else encoder_hidden_states
|
||||
input_shape = hidden_states.shape[:-1]
|
||||
encoder_input_shape = encoder_hidden_states.shape[:-1]
|
||||
|
||||
query = self.q_proj(hidden_states)
|
||||
key = self.k_proj(encoder_hidden_states)
|
||||
value = self.v_proj(encoder_hidden_states)
|
||||
|
||||
query = query.view(*input_shape, self.num_attention_heads, self.attention_head_dim)
|
||||
key = key.view(*encoder_input_shape, self.num_attention_heads, self.attention_head_dim)
|
||||
value = value.view(*encoder_input_shape, self.num_attention_heads, self.attention_head_dim)
|
||||
|
||||
query = self.q_norm(query)
|
||||
key = self.k_norm(key)
|
||||
|
||||
if position_embeddings is not None:
|
||||
if encoder_position_embeddings is None:
|
||||
raise ValueError("encoder_position_embeddings is required with rotary embeddings.")
|
||||
cos, sin = position_embeddings
|
||||
query = _apply_rotary_pos_emb(query, cos, sin, unsqueeze_dim=2)
|
||||
cos, sin = encoder_position_embeddings
|
||||
key = _apply_rotary_pos_emb(key, cos, sin, unsqueeze_dim=2)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = self.attn(query, key, value, attn_metadata=attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3).contiguous()
|
||||
return self.o_proj(hidden_states)
|
||||
|
||||
|
||||
class AnimaTextConditionerBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
source_dim: int,
|
||||
model_dim: int,
|
||||
num_attention_heads: int = 16,
|
||||
mlp_ratio: float = 4.0,
|
||||
use_self_attention: bool = True,
|
||||
use_layer_norm: bool = False,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.use_self_attention = use_self_attention
|
||||
norm_cls = nn.LayerNorm if use_layer_norm else nn.RMSNorm
|
||||
norm_kwargs = {} if use_layer_norm else {"eps": 1e-6}
|
||||
|
||||
if use_self_attention:
|
||||
self.norm_self_attn = norm_cls(model_dim, **norm_kwargs)
|
||||
self.self_attn = AnimaTextConditionerAttention(
|
||||
query_dim=model_dim,
|
||||
context_dim=model_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=model_dim // num_attention_heads,
|
||||
prefix=f"{prefix}.self_attn" if prefix else "self_attn",
|
||||
)
|
||||
|
||||
self.norm_cross_attn = norm_cls(model_dim, **norm_kwargs)
|
||||
self.cross_attn = AnimaTextConditionerAttention(
|
||||
query_dim=model_dim,
|
||||
context_dim=source_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=model_dim // num_attention_heads,
|
||||
prefix=f"{prefix}.cross_attn" if prefix else "cross_attn",
|
||||
)
|
||||
self.norm_mlp = norm_cls(model_dim, **norm_kwargs)
|
||||
self.mlp = nn.Sequential(
|
||||
nn.Linear(model_dim, int(model_dim * mlp_ratio)),
|
||||
nn.GELU(),
|
||||
nn.Linear(int(model_dim * mlp_ratio), model_dim),
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
target_attention_mask: torch.Tensor | None = None,
|
||||
source_attention_mask: torch.Tensor | None = None,
|
||||
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
source_position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
if self.use_self_attention:
|
||||
norm_hidden_states = self.norm_self_attn(hidden_states)
|
||||
attn_hidden_states = self.self_attn(
|
||||
norm_hidden_states,
|
||||
attention_mask=target_attention_mask,
|
||||
position_embeddings=position_embeddings,
|
||||
encoder_position_embeddings=position_embeddings,
|
||||
)
|
||||
hidden_states = hidden_states + attn_hidden_states
|
||||
|
||||
norm_hidden_states = self.norm_cross_attn(hidden_states)
|
||||
attn_hidden_states = self.cross_attn(
|
||||
norm_hidden_states,
|
||||
attention_mask=source_attention_mask,
|
||||
encoder_hidden_states=encoder_hidden_states,
|
||||
position_embeddings=position_embeddings,
|
||||
encoder_position_embeddings=source_position_embeddings,
|
||||
)
|
||||
hidden_states = hidden_states + attn_hidden_states
|
||||
hidden_states = hidden_states + self.mlp(self.norm_mlp(hidden_states))
|
||||
return hidden_states
|
||||
|
||||
|
||||
def is_conditioner_block_module(name: str, module: nn.Module) -> bool:
|
||||
return "blocks" in name and name.split(".")[-1].isdigit()
|
||||
|
||||
|
||||
class AnimaTextConditioner(nn.Module):
|
||||
_repeated_blocks = ["AnimaTextConditionerBlock"]
|
||||
_hsdp_shard_conditions = [is_conditioner_block_module]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
source_dim: int = 1024,
|
||||
target_dim: int = 1024,
|
||||
model_dim: int = 1024,
|
||||
num_layers: int = 6,
|
||||
num_attention_heads: int = 16,
|
||||
mlp_ratio: float = 4.0,
|
||||
target_vocab_size: int = 32128,
|
||||
use_self_attention: bool = True,
|
||||
use_layer_norm: bool = False,
|
||||
min_sequence_length: int = 512,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = SimpleNamespace(
|
||||
source_dim=source_dim,
|
||||
target_dim=target_dim,
|
||||
model_dim=model_dim,
|
||||
num_layers=num_layers,
|
||||
num_attention_heads=num_attention_heads,
|
||||
mlp_ratio=mlp_ratio,
|
||||
target_vocab_size=target_vocab_size,
|
||||
use_self_attention=use_self_attention,
|
||||
use_layer_norm=use_layer_norm,
|
||||
min_sequence_length=min_sequence_length,
|
||||
extra_config=kwargs,
|
||||
)
|
||||
self.embed = nn.Embedding(target_vocab_size, target_dim)
|
||||
self.in_proj = nn.Linear(target_dim, model_dim) if model_dim != target_dim else nn.Identity()
|
||||
self.rotary_emb = AnimaRotaryEmbedding(model_dim // num_attention_heads)
|
||||
self.blocks = nn.ModuleList(
|
||||
[
|
||||
AnimaTextConditionerBlock(
|
||||
source_dim=source_dim,
|
||||
model_dim=model_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
mlp_ratio=mlp_ratio,
|
||||
use_self_attention=use_self_attention,
|
||||
use_layer_norm=use_layer_norm,
|
||||
prefix=f"blocks.{i}",
|
||||
)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
self.out_proj = nn.Linear(model_dim, target_dim)
|
||||
self.norm = nn.RMSNorm(target_dim, eps=1e-6)
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
@staticmethod
|
||||
def _prepare_attention_mask(attention_mask: torch.Tensor | None) -> torch.Tensor | None:
|
||||
if attention_mask is None:
|
||||
return None
|
||||
return attention_mask.to(torch.bool)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
source_hidden_states: torch.Tensor,
|
||||
target_input_ids: torch.Tensor,
|
||||
target_attention_mask: torch.Tensor | None = None,
|
||||
source_attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
target_attention_mask = self._prepare_attention_mask(target_attention_mask)
|
||||
source_attention_mask = self._prepare_attention_mask(source_attention_mask)
|
||||
|
||||
hidden_states = self.embed(target_input_ids).to(dtype=source_hidden_states.dtype)
|
||||
hidden_states = self.in_proj(hidden_states)
|
||||
|
||||
position_ids = torch.arange(hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
|
||||
source_position_ids = torch.arange(source_hidden_states.shape[1], device=hidden_states.device).unsqueeze(0)
|
||||
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
||||
source_position_embeddings = self.rotary_emb(hidden_states, source_position_ids)
|
||||
|
||||
for block in self.blocks:
|
||||
hidden_states = block(
|
||||
hidden_states,
|
||||
source_hidden_states,
|
||||
target_attention_mask=target_attention_mask,
|
||||
source_attention_mask=source_attention_mask,
|
||||
position_embeddings=position_embeddings,
|
||||
source_position_embeddings=source_position_embeddings,
|
||||
)
|
||||
|
||||
hidden_states = self.norm(self.out_proj(hidden_states))
|
||||
|
||||
if target_attention_mask is not None:
|
||||
hidden_states = hidden_states * target_attention_mask.to(hidden_states).unsqueeze(-1)
|
||||
|
||||
if hidden_states.shape[1] < self.config.min_sequence_length:
|
||||
hidden_states = F.pad(hidden_states, (0, 0, 0, self.config.min_sequence_length - hidden_states.shape[1]))
|
||||
|
||||
return hidden_states
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
params = dict(self.named_parameters())
|
||||
loaded = set()
|
||||
for name, tensor in weights:
|
||||
if name not in params:
|
||||
continue
|
||||
param = params[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, tensor)
|
||||
loaded.add(name)
|
||||
return loaded
|
||||
@@ -0,0 +1,705 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from collections.abc import Iterable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from diffusers.models.embeddings import Timesteps, apply_rotary_emb
|
||||
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
||||
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.distributed.hsdp_utils import is_transformer_block_module
|
||||
|
||||
ANIMA_TRANSFORMER_CONFIG = {
|
||||
"in_channels": 16,
|
||||
"out_channels": 16,
|
||||
"num_attention_heads": 16,
|
||||
"attention_head_dim": 128,
|
||||
"num_layers": 28,
|
||||
"mlp_ratio": 4.0,
|
||||
"text_embed_dim": 1024,
|
||||
"adaln_lora_dim": 256,
|
||||
"max_size": (128, 240, 240),
|
||||
"patch_size": (1, 2, 2),
|
||||
"rope_scale": (1.0, 4.0, 4.0),
|
||||
"concat_padding_mask": True,
|
||||
"extra_pos_embed_type": None,
|
||||
}
|
||||
|
||||
|
||||
# NOTE: We import and use diffusers' `apply_rotary_emb` instead of a custom native implementation
|
||||
# to prevent numerical drift in bfloat16. Diffusers upcasts queries, keys, and rotary frequency
|
||||
# tensors to float32 before computing the rotation, and casts back to bfloat16 at the end.
|
||||
# Performing the entire computation in bfloat16 accumulates precision errors across the 28
|
||||
# transformer blocks, which is heavily amplified by Classifier-Free Guidance (CFG).
|
||||
|
||||
|
||||
class CosmosPatchEmbed(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
in_channels: int,
|
||||
out_channels: int,
|
||||
patch_size: tuple[int, int, int],
|
||||
bias: bool = True,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.patch_size = patch_size
|
||||
self.proj = nn.Linear(in_channels * patch_size[0] * patch_size[1] * patch_size[2], out_channels, bias=bias)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
||||
p_t, p_h, p_w = self.patch_size
|
||||
hidden_states = hidden_states.reshape(
|
||||
batch_size,
|
||||
num_channels,
|
||||
num_frames // p_t,
|
||||
p_t,
|
||||
height // p_h,
|
||||
p_h,
|
||||
width // p_w,
|
||||
p_w,
|
||||
)
|
||||
hidden_states = hidden_states.permute(0, 2, 4, 6, 1, 3, 5, 7).flatten(4, 7)
|
||||
return self.proj(hidden_states)
|
||||
|
||||
|
||||
class CosmosTimestepEmbedding(nn.Module):
|
||||
def __init__(self, in_features: int, out_features: int) -> None:
|
||||
super().__init__()
|
||||
self.linear_1 = nn.Linear(in_features, out_features, bias=False)
|
||||
self.activation = nn.SiLU()
|
||||
self.linear_2 = nn.Linear(out_features, 3 * out_features, bias=False)
|
||||
|
||||
def forward(self, timesteps: torch.Tensor) -> torch.Tensor:
|
||||
emb = self.linear_1(timesteps)
|
||||
emb = self.activation(emb)
|
||||
return self.linear_2(emb)
|
||||
|
||||
|
||||
class CosmosEmbedding(nn.Module):
|
||||
def __init__(self, embedding_dim: int, condition_dim: int) -> None:
|
||||
super().__init__()
|
||||
self.time_proj = Timesteps(embedding_dim, flip_sin_to_cos=True, downscale_freq_shift=0.0)
|
||||
self.t_embedder = CosmosTimestepEmbedding(embedding_dim, condition_dim)
|
||||
self.norm = nn.RMSNorm(embedding_dim, eps=1e-6)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, timestep: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
timesteps_proj = self.time_proj(timestep).type_as(hidden_states)
|
||||
temb = self.t_embedder(timesteps_proj)
|
||||
embedded_timestep = self.norm(timesteps_proj)
|
||||
return temb, embedded_timestep
|
||||
|
||||
|
||||
class CosmosAdaLayerNorm(nn.Module):
|
||||
def __init__(self, in_features: int, hidden_features: int) -> None:
|
||||
super().__init__()
|
||||
self.embedding_dim = in_features
|
||||
self.activation = nn.SiLU()
|
||||
self.norm = nn.LayerNorm(in_features, elementwise_affine=False, eps=1e-6)
|
||||
self.linear_1 = nn.Linear(in_features, hidden_features, bias=False)
|
||||
self.linear_2 = nn.Linear(hidden_features, 2 * in_features, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
embedded_timestep: torch.Tensor,
|
||||
temb: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
embedded_timestep = self.activation(embedded_timestep)
|
||||
embedded_timestep = self.linear_1(embedded_timestep)
|
||||
embedded_timestep = self.linear_2(embedded_timestep)
|
||||
|
||||
if temb is not None:
|
||||
embedded_timestep = embedded_timestep + temb[..., : 2 * self.embedding_dim]
|
||||
|
||||
shift, scale = embedded_timestep.chunk(2, dim=-1)
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if embedded_timestep.ndim == 2:
|
||||
shift, scale = (x.unsqueeze(1) for x in (shift, scale))
|
||||
|
||||
return hidden_states * (1 + scale) + shift
|
||||
|
||||
|
||||
class CosmosAdaLayerNormZero(nn.Module):
|
||||
def __init__(self, in_features: int, hidden_features: int | None = None) -> None:
|
||||
super().__init__()
|
||||
self.norm = nn.LayerNorm(in_features, elementwise_affine=False, eps=1e-6)
|
||||
self.activation = nn.SiLU()
|
||||
self.linear_1 = (
|
||||
nn.Identity() if hidden_features is None else nn.Linear(in_features, hidden_features, bias=False)
|
||||
)
|
||||
self.linear_2 = nn.Linear(hidden_features or in_features, 3 * in_features, bias=False)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
embedded_timestep: torch.Tensor,
|
||||
temb: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
embedded_timestep = self.activation(embedded_timestep)
|
||||
embedded_timestep = self.linear_1(embedded_timestep)
|
||||
embedded_timestep = self.linear_2(embedded_timestep)
|
||||
|
||||
if temb is not None:
|
||||
embedded_timestep = embedded_timestep + temb
|
||||
|
||||
shift, scale, gate = embedded_timestep.chunk(3, dim=-1)
|
||||
hidden_states = self.norm(hidden_states)
|
||||
|
||||
if embedded_timestep.ndim == 2:
|
||||
shift, scale, gate = (x.unsqueeze(1) for x in (shift, scale, gate))
|
||||
|
||||
hidden_states = hidden_states * (1 + scale) + shift
|
||||
return hidden_states, gate
|
||||
|
||||
|
||||
class CosmosGELU(nn.Module):
|
||||
def __init__(self, dim: int, inner_dim: int, bias: bool = False) -> None:
|
||||
super().__init__()
|
||||
self.proj = nn.Linear(dim, inner_dim, bias=bias)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
return F.gelu(self.proj(hidden_states))
|
||||
|
||||
|
||||
class CosmosFeedForward(nn.Module):
|
||||
def __init__(self, dim: int, mult: float = 4.0, bias: bool = False) -> None:
|
||||
super().__init__()
|
||||
inner_dim = int(dim * mult)
|
||||
self.net = nn.ModuleList(
|
||||
[
|
||||
CosmosGELU(dim, inner_dim, bias=bias),
|
||||
nn.Identity(),
|
||||
nn.Linear(inner_dim, dim, bias=bias),
|
||||
]
|
||||
)
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
for module in self.net:
|
||||
hidden_states = module(hidden_states)
|
||||
return hidden_states
|
||||
|
||||
|
||||
class CosmosAttention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
query_dim: int,
|
||||
cross_attention_dim: int | None = None,
|
||||
heads: int = 8,
|
||||
dim_head: int = 64,
|
||||
out_bias: bool = False,
|
||||
img_context: bool = False,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
inner_dim = heads * dim_head
|
||||
cross_attention_dim = query_dim if cross_attention_dim is None else cross_attention_dim
|
||||
|
||||
self.heads = heads
|
||||
self.dim_head = dim_head
|
||||
self.out_dim = inner_dim
|
||||
self.query_dim = query_dim
|
||||
self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=False)
|
||||
self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=False)
|
||||
self.norm_q = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.norm_k = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.to_out = nn.ModuleList([nn.Linear(inner_dim, query_dim, bias=out_bias), nn.Identity()])
|
||||
self.attn = Attention(
|
||||
num_heads=heads,
|
||||
head_size=dim_head,
|
||||
softmax_scale=1.0 / (dim_head**0.5),
|
||||
causal=False,
|
||||
num_kv_heads=heads,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
self.img_context = img_context
|
||||
if img_context:
|
||||
self.q_img = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.k_img = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.v_img = nn.Linear(query_dim, inner_dim, bias=False)
|
||||
self.q_img_norm = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.k_img_norm = nn.RMSNorm(dim_head, eps=1e-6)
|
||||
self.img_attn = Attention(
|
||||
num_heads=heads,
|
||||
head_size=dim_head,
|
||||
softmax_scale=1.0 / (dim_head**0.5),
|
||||
causal=False,
|
||||
num_kv_heads=heads,
|
||||
prefix=f"{prefix}.img_attn" if prefix else "img_attn",
|
||||
)
|
||||
|
||||
def _attention(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | None = None,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
encoder_hidden_states = hidden_states if encoder_hidden_states is None else encoder_hidden_states
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
encoder_seq_len = encoder_hidden_states.shape[1]
|
||||
|
||||
query = self.to_q(hidden_states).view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
key = self.to_k(encoder_hidden_states).view(batch_size, encoder_seq_len, self.heads, self.dim_head)
|
||||
value = self.to_v(encoder_hidden_states).view(batch_size, encoder_seq_len, self.heads, self.dim_head)
|
||||
|
||||
query = self.norm_q(query)
|
||||
key = self.norm_k(key)
|
||||
|
||||
if image_rotary_emb is not None:
|
||||
# We use diffusers' apply_rotary_emb to leverage its internal float32 rotation upcasting
|
||||
# logic, resolving the bfloat16 cumulative precision drift vs. the reference pipeline.
|
||||
query = apply_rotary_emb(query, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
key = apply_rotary_emb(key, image_rotary_emb, sequence_dim=1, use_real_unbind_dim=-2)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = self.attn(query, key, value, attn_metadata=attn_metadata)
|
||||
return hidden_states.flatten(2, 3).type_as(query)
|
||||
|
||||
def _image_attention(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
img_context: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
batch_size, seq_len, _ = hidden_states.shape
|
||||
img_seq_len = img_context.shape[1]
|
||||
|
||||
query = self.q_img(hidden_states).view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
key = self.k_img(img_context).view(batch_size, img_seq_len, self.heads, self.dim_head)
|
||||
value = self.v_img(img_context).view(batch_size, img_seq_len, self.heads, self.dim_head)
|
||||
|
||||
query = self.q_img_norm(query)
|
||||
key = self.k_img_norm(key)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = self.img_attn(query, key, value, attn_metadata=attn_metadata)
|
||||
return hidden_states.flatten(2, 3).type_as(query)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None] | None = None,
|
||||
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
|
||||
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
if self.img_context:
|
||||
if not isinstance(encoder_hidden_states, tuple):
|
||||
raise ValueError("Expected encoder_hidden_states as (text_context, img_context).")
|
||||
text_context, img_context = encoder_hidden_states
|
||||
text_mask, img_mask = attention_mask if attention_mask is not None else (None, None)
|
||||
query_states = hidden_states
|
||||
hidden_states = self._attention(query_states, text_context, text_mask, image_rotary_emb)
|
||||
if img_context is not None:
|
||||
hidden_states = hidden_states + self._image_attention(query_states, img_context, img_mask)
|
||||
else:
|
||||
hidden_states = self._attention(hidden_states, encoder_hidden_states, attention_mask, image_rotary_emb)
|
||||
|
||||
hidden_states = self.to_out[0](hidden_states)
|
||||
return self.to_out[1](hidden_states)
|
||||
|
||||
|
||||
class CosmosTransformerBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
num_attention_heads: int,
|
||||
attention_head_dim: int,
|
||||
cross_attention_dim: int,
|
||||
mlp_ratio: float = 4.0,
|
||||
adaln_lora_dim: int = 256,
|
||||
out_bias: bool = False,
|
||||
img_context: bool = False,
|
||||
before_proj: bool = False,
|
||||
after_proj: bool = False,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
hidden_size = num_attention_heads * attention_head_dim
|
||||
|
||||
self.norm1 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
|
||||
self.img_context = img_context
|
||||
self.attn1 = CosmosAttention(
|
||||
query_dim=hidden_size,
|
||||
cross_attention_dim=None,
|
||||
heads=num_attention_heads,
|
||||
dim_head=attention_head_dim,
|
||||
out_bias=out_bias,
|
||||
prefix=f"{prefix}.attn1" if prefix else "attn1",
|
||||
)
|
||||
self.norm2 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
|
||||
self.attn2 = CosmosAttention(
|
||||
query_dim=hidden_size,
|
||||
cross_attention_dim=cross_attention_dim,
|
||||
heads=num_attention_heads,
|
||||
dim_head=attention_head_dim,
|
||||
out_bias=out_bias,
|
||||
img_context=img_context,
|
||||
prefix=f"{prefix}.attn2" if prefix else "attn2",
|
||||
)
|
||||
self.norm3 = CosmosAdaLayerNormZero(in_features=hidden_size, hidden_features=adaln_lora_dim)
|
||||
self.ff = CosmosFeedForward(hidden_size, mult=mlp_ratio, bias=out_bias)
|
||||
|
||||
self.before_proj = nn.Linear(hidden_size, hidden_size) if before_proj else None
|
||||
self.after_proj = nn.Linear(hidden_size, hidden_size) if after_proj else None
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None],
|
||||
embedded_timestep: torch.Tensor,
|
||||
temb: torch.Tensor | None = None,
|
||||
image_rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
extra_pos_emb: torch.Tensor | None = None,
|
||||
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
|
||||
controlnet_residual: torch.Tensor | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
block_idx: int | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
if self.before_proj is not None:
|
||||
hidden_states = self.before_proj(hidden_states) + latents
|
||||
|
||||
if extra_pos_emb is not None:
|
||||
hidden_states = hidden_states + extra_pos_emb
|
||||
|
||||
norm_hidden_states, gate = self.norm1(hidden_states, embedded_timestep, temb)
|
||||
attn_output = self.attn1(norm_hidden_states, image_rotary_emb=image_rotary_emb)
|
||||
hidden_states = hidden_states + gate * attn_output
|
||||
|
||||
norm_hidden_states, gate = self.norm2(hidden_states, embedded_timestep, temb)
|
||||
attn_output = self.attn2(
|
||||
norm_hidden_states, encoder_hidden_states=encoder_hidden_states, attention_mask=attention_mask
|
||||
)
|
||||
hidden_states = hidden_states + gate * attn_output
|
||||
|
||||
norm_hidden_states, gate = self.norm3(hidden_states, embedded_timestep, temb)
|
||||
ff_output = self.ff(norm_hidden_states)
|
||||
hidden_states = hidden_states + gate * ff_output
|
||||
|
||||
if controlnet_residual is not None:
|
||||
if self.after_proj is not None:
|
||||
raise ValueError("controlnet_residual is incompatible with after_proj.")
|
||||
hidden_states = hidden_states + controlnet_residual
|
||||
|
||||
if self.after_proj is not None:
|
||||
return hidden_states, self.after_proj(hidden_states)
|
||||
|
||||
return hidden_states
|
||||
|
||||
|
||||
class CosmosRotaryPosEmbed(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
max_size: tuple[int, int, int] = (128, 240, 240),
|
||||
patch_size: tuple[int, int, int] = (1, 2, 2),
|
||||
base_fps: int = 24,
|
||||
rope_scale: tuple[float, float, float] = (2.0, 1.0, 1.0),
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.max_size = [size // patch for size, patch in zip(max_size, patch_size)]
|
||||
self.patch_size = patch_size
|
||||
self.base_fps = base_fps
|
||||
|
||||
self.dim_h = hidden_size // 6 * 2
|
||||
self.dim_w = hidden_size // 6 * 2
|
||||
self.dim_t = hidden_size - self.dim_h - self.dim_w
|
||||
|
||||
self.h_ntk_factor = rope_scale[1] ** (self.dim_h / (self.dim_h - 2))
|
||||
self.w_ntk_factor = rope_scale[2] ** (self.dim_w / (self.dim_w - 2))
|
||||
self.t_ntk_factor = rope_scale[0] ** (self.dim_t / (self.dim_t - 2))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, fps: float | None = None) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
_, _, num_frames, height, width = hidden_states.shape
|
||||
pe_size = [num_frames // self.patch_size[0], height // self.patch_size[1], width // self.patch_size[2]]
|
||||
device = hidden_states.device
|
||||
|
||||
h_theta = 10000.0 * self.h_ntk_factor
|
||||
w_theta = 10000.0 * self.w_ntk_factor
|
||||
t_theta = 10000.0 * self.t_ntk_factor
|
||||
|
||||
seq = torch.arange(max(self.max_size), device=device, dtype=torch.float32)
|
||||
dim_h_range = torch.arange(0, self.dim_h, 2, device=device, dtype=torch.float32)[: self.dim_h // 2] / self.dim_h
|
||||
dim_w_range = torch.arange(0, self.dim_w, 2, device=device, dtype=torch.float32)[: self.dim_w // 2] / self.dim_w
|
||||
dim_t_range = torch.arange(0, self.dim_t, 2, device=device, dtype=torch.float32)[: self.dim_t // 2] / self.dim_t
|
||||
h_spatial_freqs = 1.0 / (h_theta**dim_h_range)
|
||||
w_spatial_freqs = 1.0 / (w_theta**dim_w_range)
|
||||
temporal_freqs = 1.0 / (t_theta**dim_t_range)
|
||||
|
||||
emb_h = torch.outer(seq[: pe_size[1]], h_spatial_freqs)[None, :, None, :].repeat(pe_size[0], 1, pe_size[2], 1)
|
||||
emb_w = torch.outer(seq[: pe_size[2]], w_spatial_freqs)[None, None, :, :].repeat(pe_size[0], pe_size[1], 1, 1)
|
||||
if fps is None:
|
||||
emb_t = torch.outer(seq[: pe_size[0]], temporal_freqs)
|
||||
else:
|
||||
emb_t = torch.outer(seq[: pe_size[0]] / fps * self.base_fps, temporal_freqs)
|
||||
emb_t = emb_t[:, None, None, :].repeat(1, pe_size[1], pe_size[2], 1)
|
||||
|
||||
freqs = torch.cat([emb_t, emb_h, emb_w] * 2, dim=-1).flatten(0, 2).float()
|
||||
return torch.cos(freqs), torch.sin(freqs)
|
||||
|
||||
|
||||
class CosmosLearnablePositionalEmbed(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
hidden_size: int,
|
||||
max_size: tuple[int, int, int],
|
||||
patch_size: tuple[int, int, int],
|
||||
eps: float = 1e-6,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.max_size = [size // patch for size, patch in zip(max_size, patch_size)]
|
||||
self.patch_size = patch_size
|
||||
self.eps = eps
|
||||
self.pos_emb_t = nn.Parameter(torch.zeros(self.max_size[0], hidden_size))
|
||||
self.pos_emb_h = nn.Parameter(torch.zeros(self.max_size[1], hidden_size))
|
||||
self.pos_emb_w = nn.Parameter(torch.zeros(self.max_size[2], hidden_size))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, _, num_frames, height, width = hidden_states.shape
|
||||
pe_size = [num_frames // self.patch_size[0], height // self.patch_size[1], width // self.patch_size[2]]
|
||||
|
||||
emb_t = self.pos_emb_t[: pe_size[0]][None, :, None, None, :].repeat(batch_size, 1, pe_size[1], pe_size[2], 1)
|
||||
emb_h = self.pos_emb_h[: pe_size[1]][None, None, :, None, :].repeat(batch_size, pe_size[0], 1, pe_size[2], 1)
|
||||
emb_w = self.pos_emb_w[: pe_size[2]][None, None, None, :, :].repeat(batch_size, pe_size[0], pe_size[1], 1, 1)
|
||||
emb = (emb_t + emb_h + emb_w).flatten(1, 3)
|
||||
|
||||
norm = torch.linalg.vector_norm(emb, dim=-1, keepdim=True, dtype=torch.float32)
|
||||
norm = torch.add(self.eps, norm, alpha=np.sqrt(norm.numel() / emb.numel()))
|
||||
return (emb / norm).type_as(hidden_states)
|
||||
|
||||
|
||||
class AnimaTransformer3DModel(nn.Module):
|
||||
_repeated_blocks = ["CosmosTransformerBlock"]
|
||||
_hsdp_shard_conditions = [is_transformer_block_module]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels: int = 16,
|
||||
out_channels: int = 16,
|
||||
num_attention_heads: int = 32,
|
||||
attention_head_dim: int = 128,
|
||||
num_layers: int = 28,
|
||||
mlp_ratio: float = 4.0,
|
||||
text_embed_dim: int = 1024,
|
||||
adaln_lora_dim: int = 256,
|
||||
max_size: tuple[int, int, int] = (128, 240, 240),
|
||||
patch_size: tuple[int, int, int] = (1, 2, 2),
|
||||
rope_scale: tuple[float, float, float] = (2.0, 1.0, 1.0),
|
||||
concat_padding_mask: bool = True,
|
||||
extra_pos_embed_type: str | None = "learnable",
|
||||
use_crossattn_projection: bool = False,
|
||||
crossattn_proj_in_channels: int = 1024,
|
||||
encoder_hidden_states_channels: int = 1024,
|
||||
controlnet_block_every_n: int | None = None,
|
||||
img_context_dim_in: int | None = None,
|
||||
img_context_num_tokens: int = 256,
|
||||
img_context_dim_out: int = 2048,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
hidden_size = num_attention_heads * attention_head_dim
|
||||
self.config = SimpleNamespace(
|
||||
in_channels=in_channels,
|
||||
out_channels=out_channels,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=attention_head_dim,
|
||||
num_layers=num_layers,
|
||||
mlp_ratio=mlp_ratio,
|
||||
text_embed_dim=text_embed_dim,
|
||||
adaln_lora_dim=adaln_lora_dim,
|
||||
max_size=max_size,
|
||||
patch_size=patch_size,
|
||||
rope_scale=rope_scale,
|
||||
concat_padding_mask=concat_padding_mask,
|
||||
extra_pos_embed_type=extra_pos_embed_type,
|
||||
use_crossattn_projection=use_crossattn_projection,
|
||||
crossattn_proj_in_channels=crossattn_proj_in_channels,
|
||||
encoder_hidden_states_channels=encoder_hidden_states_channels,
|
||||
controlnet_block_every_n=controlnet_block_every_n,
|
||||
img_context_dim_in=img_context_dim_in,
|
||||
img_context_num_tokens=img_context_num_tokens,
|
||||
img_context_dim_out=img_context_dim_out,
|
||||
extra_config=kwargs,
|
||||
)
|
||||
|
||||
patch_embed_in_channels = in_channels + 1 if concat_padding_mask else in_channels
|
||||
self.patch_embed = CosmosPatchEmbed(patch_embed_in_channels, hidden_size, patch_size, bias=False)
|
||||
self.rope = CosmosRotaryPosEmbed(
|
||||
hidden_size=attention_head_dim,
|
||||
max_size=max_size,
|
||||
patch_size=patch_size,
|
||||
rope_scale=rope_scale,
|
||||
)
|
||||
self.learnable_pos_embed: CosmosLearnablePositionalEmbed | None = None
|
||||
if extra_pos_embed_type == "learnable":
|
||||
self.learnable_pos_embed = CosmosLearnablePositionalEmbed(
|
||||
hidden_size=hidden_size,
|
||||
max_size=max_size,
|
||||
patch_size=patch_size,
|
||||
)
|
||||
self.time_embed = CosmosEmbedding(hidden_size, hidden_size)
|
||||
self.transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
CosmosTransformerBlock(
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=attention_head_dim,
|
||||
cross_attention_dim=text_embed_dim,
|
||||
mlp_ratio=mlp_ratio,
|
||||
adaln_lora_dim=adaln_lora_dim,
|
||||
out_bias=False,
|
||||
img_context=img_context_dim_in is not None and img_context_dim_in > 0,
|
||||
prefix=f"transformer_blocks.{i}",
|
||||
)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
self.norm_out = CosmosAdaLayerNorm(hidden_size, adaln_lora_dim)
|
||||
self.proj_out = nn.Linear(hidden_size, patch_size[0] * patch_size[1] * patch_size[2] * out_channels, bias=False)
|
||||
|
||||
self.crossattn_proj: nn.Module | None = None
|
||||
if use_crossattn_projection:
|
||||
self.crossattn_proj = nn.Sequential(
|
||||
nn.Linear(crossattn_proj_in_channels, encoder_hidden_states_channels, bias=True),
|
||||
nn.GELU(),
|
||||
)
|
||||
|
||||
self.img_context_proj: nn.Module | None = None
|
||||
if img_context_dim_in:
|
||||
self.img_context_proj = nn.Sequential(
|
||||
nn.Linear(img_context_dim_in, img_context_dim_out, bias=True),
|
||||
nn.GELU(),
|
||||
)
|
||||
|
||||
self.gradient_checkpointing = False
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
timestep: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | tuple[torch.Tensor, torch.Tensor | None],
|
||||
block_controlnet_hidden_states: list[torch.Tensor] | None = None,
|
||||
attention_mask: torch.Tensor | tuple[torch.Tensor | None, torch.Tensor | None] | None = None,
|
||||
fps: float | None = None,
|
||||
condition_mask: torch.Tensor | None = None,
|
||||
padding_mask: torch.Tensor | None = None,
|
||||
return_dict: bool = True,
|
||||
) -> Transformer2DModelOutput | tuple[torch.Tensor]:
|
||||
batch_size, _, num_frames, height, width = hidden_states.shape
|
||||
|
||||
if condition_mask is not None:
|
||||
hidden_states = torch.cat([hidden_states, condition_mask], dim=1)
|
||||
|
||||
if self.config.concat_padding_mask:
|
||||
if padding_mask is None:
|
||||
raise ValueError("padding_mask is required when concat_padding_mask=True.")
|
||||
padding_mask_resized = F.interpolate(
|
||||
padding_mask,
|
||||
size=list(hidden_states.shape[-2:]),
|
||||
mode="nearest",
|
||||
)
|
||||
hidden_states = torch.cat(
|
||||
[hidden_states, padding_mask_resized.unsqueeze(2).repeat(batch_size, 1, num_frames, 1, 1)],
|
||||
dim=1,
|
||||
)
|
||||
|
||||
if isinstance(attention_mask, torch.Tensor) and attention_mask.ndim != 2:
|
||||
attention_mask = attention_mask.squeeze(1).squeeze(1)
|
||||
|
||||
image_rotary_emb = self.rope(hidden_states, fps=fps)
|
||||
extra_pos_emb = self.learnable_pos_embed(hidden_states) if self.learnable_pos_embed is not None else None
|
||||
|
||||
p_t, p_h, p_w = self.config.patch_size
|
||||
post_patch_num_frames = num_frames // p_t
|
||||
post_patch_height = height // p_h
|
||||
post_patch_width = width // p_w
|
||||
|
||||
hidden_states = self.patch_embed(hidden_states)
|
||||
hidden_states = hidden_states.flatten(1, 3)
|
||||
|
||||
if timestep.ndim == 1:
|
||||
temb, embedded_timestep = self.time_embed(hidden_states, timestep)
|
||||
elif timestep.ndim == 5:
|
||||
if timestep.shape != (batch_size, 1, num_frames, 1, 1):
|
||||
raise ValueError(f"Expected timestep shape [B, 1, T, 1, 1], got {timestep.shape}.")
|
||||
timestep = timestep.flatten()
|
||||
temb, embedded_timestep = self.time_embed(hidden_states, timestep)
|
||||
temb, embedded_timestep = (
|
||||
x.view(batch_size, post_patch_num_frames, 1, 1, -1)
|
||||
.expand(-1, -1, post_patch_height, post_patch_width, -1)
|
||||
.flatten(1, 3)
|
||||
for x in (temb, embedded_timestep)
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Expected timestep shape [B, 1, T, 1, 1] or [T], got {timestep.shape}.")
|
||||
|
||||
text_context, img_context = (
|
||||
encoder_hidden_states if isinstance(encoder_hidden_states, tuple) else (encoder_hidden_states, None)
|
||||
)
|
||||
if self.config.use_crossattn_projection:
|
||||
if self.crossattn_proj is None:
|
||||
raise ValueError("crossattn_proj is required when use_crossattn_projection=True.")
|
||||
text_context = self.crossattn_proj(text_context)
|
||||
if img_context is not None and self.config.img_context_dim_in:
|
||||
if self.img_context_proj is None:
|
||||
raise ValueError("img_context_proj is required when img_context_dim_in is set.")
|
||||
img_context = self.img_context_proj(img_context)
|
||||
processed_encoder_hidden_states = (
|
||||
(text_context, img_context) if isinstance(encoder_hidden_states, tuple) else text_context
|
||||
)
|
||||
|
||||
controlnet_block_index_map = {}
|
||||
if block_controlnet_hidden_states is not None:
|
||||
n_blocks = len(self.transformer_blocks)
|
||||
controlnet_block_index_map = {
|
||||
block_idx: block_controlnet_hidden_states[idx]
|
||||
for idx, block_idx in list(enumerate(range(0, n_blocks, self.config.controlnet_block_every_n)))
|
||||
}
|
||||
|
||||
for block_idx, block in enumerate(self.transformer_blocks):
|
||||
hidden_states = block(
|
||||
hidden_states,
|
||||
processed_encoder_hidden_states,
|
||||
embedded_timestep,
|
||||
temb,
|
||||
image_rotary_emb,
|
||||
extra_pos_emb,
|
||||
attention_mask,
|
||||
controlnet_block_index_map.get(block_idx),
|
||||
)
|
||||
|
||||
hidden_states = self.norm_out(hidden_states, embedded_timestep, temb)
|
||||
hidden_states = self.proj_out(hidden_states)
|
||||
hidden_states = hidden_states.unflatten(2, (p_h, p_w, p_t, -1))
|
||||
hidden_states = hidden_states.unflatten(1, (post_patch_num_frames, post_patch_height, post_patch_width))
|
||||
hidden_states = hidden_states.permute(0, 7, 1, 6, 2, 4, 3, 5)
|
||||
hidden_states = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
||||
|
||||
if not return_dict:
|
||||
return (hidden_states,)
|
||||
|
||||
return Transformer2DModelOutput(sample=hidden_states)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
params = dict(self.named_parameters())
|
||||
loaded = set()
|
||||
for name, tensor in weights:
|
||||
if name not in params:
|
||||
continue
|
||||
param = params[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, tensor)
|
||||
loaded.add(name)
|
||||
return loaded
|
||||
@@ -0,0 +1,795 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import inspect
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from collections.abc import Callable, Iterable
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from diffusers.image_processor import VaeImageProcessor
|
||||
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from safetensors.torch import load_file
|
||||
from torch import nn
|
||||
from transformers import AutoTokenizer, Qwen3Model, T5TokenizerFast
|
||||
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_qwenimage import DistributedAutoencoderKLQwenImage
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.models.anima.anima_text_conditioner import (
|
||||
ANIMA_TEXT_CONDITIONER_CONFIG,
|
||||
AnimaTextConditioner,
|
||||
)
|
||||
from vllm_omni.diffusion.models.anima.anima_transformer import ANIMA_TRANSFORMER_CONFIG, AnimaTransformer3DModel
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.offloader.config import OffloadStrategy, resolve_offload_strategy
|
||||
from vllm_omni.diffusion.profiler.diffusion_pipeline_profiler import DiffusionPipelineProfilerMixin
|
||||
from vllm_omni.diffusion.utils.size_utils import normalize_min_aligned_size
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ANIMA_VAE_SCALE_FACTOR = 8
|
||||
|
||||
|
||||
def retrieve_timesteps(
|
||||
scheduler: Any,
|
||||
num_inference_steps: int | None = None,
|
||||
device: str | torch.device | None = None,
|
||||
timesteps: list[int] | None = None,
|
||||
sigmas: list[float] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> tuple[torch.Tensor, int]:
|
||||
if timesteps is not None and sigmas is not None:
|
||||
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
||||
if timesteps is not None:
|
||||
if "timesteps" not in inspect.signature(scheduler.set_timesteps).parameters:
|
||||
raise ValueError(
|
||||
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
||||
f" timestep schedules. Please check whether you are using the correct scheduler."
|
||||
)
|
||||
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
||||
scheduler_timesteps = scheduler.timesteps
|
||||
num_inference_steps = len(scheduler_timesteps)
|
||||
elif sigmas is not None:
|
||||
if "sigmas" not in inspect.signature(scheduler.set_timesteps).parameters:
|
||||
raise ValueError(
|
||||
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
||||
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
||||
)
|
||||
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
||||
scheduler_timesteps = scheduler.timesteps
|
||||
num_inference_steps = len(scheduler_timesteps)
|
||||
else:
|
||||
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
||||
scheduler_timesteps = scheduler.timesteps
|
||||
if num_inference_steps is None:
|
||||
num_inference_steps = len(scheduler_timesteps)
|
||||
return cast(torch.Tensor, scheduler_timesteps), num_inference_steps
|
||||
|
||||
|
||||
_ANIMA_ORIGINAL_TRANSFORMER_RENAMES = {
|
||||
"t_embedder.1": "time_embed.t_embedder",
|
||||
"t_embedding_norm": "time_embed.norm",
|
||||
"blocks": "transformer_blocks",
|
||||
"adaln_modulation_self_attn.1": "norm1.linear_1",
|
||||
"adaln_modulation_self_attn.2": "norm1.linear_2",
|
||||
"adaln_modulation_cross_attn.1": "norm2.linear_1",
|
||||
"adaln_modulation_cross_attn.2": "norm2.linear_2",
|
||||
"adaln_modulation_mlp.1": "norm3.linear_1",
|
||||
"adaln_modulation_mlp.2": "norm3.linear_2",
|
||||
"self_attn": "attn1",
|
||||
"cross_attn": "attn2",
|
||||
"q_proj": "to_q",
|
||||
"k_proj": "to_k",
|
||||
"v_proj": "to_v",
|
||||
"output_proj": "to_out.0",
|
||||
"q_norm": "norm_q",
|
||||
"k_norm": "norm_k",
|
||||
"mlp.layer1": "ff.net.0.proj",
|
||||
"mlp.layer2": "ff.net.2",
|
||||
"x_embedder.proj.1": "patch_embed.proj",
|
||||
"final_layer.adaln_modulation.1": "norm_out.linear_1",
|
||||
"final_layer.adaln_modulation.2": "norm_out.linear_2",
|
||||
"final_layer.linear": "proj_out",
|
||||
}
|
||||
|
||||
_ANIMA_ORIGINAL_TRANSFORMER_DROP_KEYS = (
|
||||
"accum_video_sample_counter",
|
||||
"accum_image_sample_counter",
|
||||
"accum_iteration",
|
||||
"accum_train_in_hours",
|
||||
"pos_embedder.seq",
|
||||
"pos_embedder.dim_spatial_range",
|
||||
"pos_embedder.dim_temporal_range",
|
||||
"_extra_state",
|
||||
)
|
||||
|
||||
|
||||
def _anima_vae_scale_factor_from_vae(vae: Any) -> int:
|
||||
vae_config = getattr(vae, "config", None)
|
||||
spatial_compression_ratio = getattr(vae_config, "spatial_compression_ratio", None)
|
||||
if spatial_compression_ratio is not None:
|
||||
return int(spatial_compression_ratio)
|
||||
temporal_downsample = getattr(vae, "temperal_downsample", None)
|
||||
if temporal_downsample is not None:
|
||||
return int(2 ** len(temporal_downsample))
|
||||
return ANIMA_VAE_SCALE_FACTOR
|
||||
|
||||
|
||||
def get_anima_post_process_func(od_config: OmniDiffusionConfig) -> Callable[[torch.Tensor], Any]:
|
||||
image_processor = VaeImageProcessor(vae_scale_factor=ANIMA_VAE_SCALE_FACTOR)
|
||||
|
||||
def post_process_func(images: torch.Tensor) -> Any:
|
||||
return image_processor.postprocess(images)
|
||||
|
||||
return post_process_func
|
||||
|
||||
|
||||
class AnimaPipeline(nn.Module, DiffusionPipelineProfilerMixin, ProgressBarMixin):
|
||||
"""Native Anima model path.
|
||||
|
||||
The Anima transformer checkpoint is distributed as a single safetensors
|
||||
file. This loader builds the native pipeline components and runs the denoise
|
||||
transformer/text-conditioner directly.
|
||||
"""
|
||||
|
||||
supports_step_execution = False
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, device: torch.device | str | None = None) -> None:
|
||||
super().__init__()
|
||||
self.od_config = od_config
|
||||
self.parallel_config = od_config.parallel_config
|
||||
self.device = device or get_local_device()
|
||||
self.weights_sources: list[str] = []
|
||||
|
||||
self._raise_unsupported_features()
|
||||
|
||||
self._interrupt = False
|
||||
self._guidance_scale = 1.0
|
||||
self._num_timesteps = 0
|
||||
self._current_timestep = None
|
||||
self._profiler_initialized = False
|
||||
|
||||
def _raise_unsupported_features(self) -> None:
|
||||
pc = self.od_config.parallel_config
|
||||
if pc.cfg_parallel_size > 1:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support CFG parallel. Validate native CFG first.")
|
||||
if pc.sequence_parallel_size is not None and pc.sequence_parallel_size > 1:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support sequence parallelism. Add an _sp_plan first.")
|
||||
if pc.tensor_parallel_size > 1:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support tensor parallelism. Port TP linears first.")
|
||||
if pc.use_hsdp:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support HSDP. Validate sharding after native load.")
|
||||
if self.od_config.cache_backend not in ("none", None):
|
||||
raise NotImplementedError("AnimaPipeline does not yet support TeaCache or Cache-DiT.")
|
||||
if self.od_config.quantization_config is not None:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support quantized checkpoints.")
|
||||
if resolve_offload_strategy(self.od_config) is not OffloadStrategy.NONE:
|
||||
raise NotImplementedError("AnimaPipeline does not yet support CPU offload.")
|
||||
|
||||
@staticmethod
|
||||
def _sub_state_dict(state_dict: dict[str, torch.Tensor], prefix: str) -> dict[str, torch.Tensor]:
|
||||
return {key.removeprefix(prefix): value for key, value in state_dict.items() if key.startswith(prefix)}
|
||||
|
||||
@staticmethod
|
||||
def _convert_original_transformer_state_dict(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
|
||||
if "patch_embed.proj.weight" in state_dict:
|
||||
return state_dict
|
||||
|
||||
# The raw Anima checkpoint uses the original training names for a
|
||||
# Cosmos-style denoiser. Convert those keys to the local
|
||||
# AnimaTransformer3DModel module names before strict loading.
|
||||
converted_state_dict = {}
|
||||
for key, value in state_dict.items():
|
||||
new_key = key.removeprefix("net.")
|
||||
if any(drop_key in new_key for drop_key in _ANIMA_ORIGINAL_TRANSFORMER_DROP_KEYS):
|
||||
continue
|
||||
for old_key, new_name in _ANIMA_ORIGINAL_TRANSFORMER_RENAMES.items():
|
||||
new_key = new_key.replace(old_key, new_name)
|
||||
if new_key in converted_state_dict:
|
||||
raise ValueError(f"Duplicate converted Anima transformer key: {new_key}")
|
||||
converted_state_dict[new_key] = value
|
||||
return converted_state_dict
|
||||
|
||||
@staticmethod
|
||||
def _split_single_file_state_dict(
|
||||
state_dict: dict[str, torch.Tensor],
|
||||
) -> tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]]:
|
||||
transformer_state_dict = AnimaPipeline._sub_state_dict(state_dict, "transformer.")
|
||||
text_conditioner_state_dict = AnimaPipeline._sub_state_dict(state_dict, "text_conditioner.")
|
||||
if transformer_state_dict and text_conditioner_state_dict:
|
||||
return transformer_state_dict, text_conditioner_state_dict
|
||||
|
||||
text_conditioner_state_dict = AnimaPipeline._sub_state_dict(state_dict, "net.llm_adapter.")
|
||||
if text_conditioner_state_dict:
|
||||
transformer_state_dict = {
|
||||
key: value for key, value in state_dict.items() if not key.startswith("net.llm_adapter.")
|
||||
}
|
||||
return transformer_state_dict, text_conditioner_state_dict
|
||||
|
||||
raise ValueError(
|
||||
"Anima native loader could not find text-conditioner weights. Expected either "
|
||||
"`text_conditioner.*` Diffusers keys or `net.llm_adapter.*` original Anima keys."
|
||||
)
|
||||
|
||||
def _load_native_denoiser_components(
|
||||
self,
|
||||
state_dict: dict[str, torch.Tensor] | None = None,
|
||||
) -> tuple[AnimaTransformer3DModel, AnimaTextConditioner]:
|
||||
if state_dict is None:
|
||||
model_path = self.od_config.model
|
||||
if not isinstance(model_path, str) or not os.path.isfile(model_path):
|
||||
raise ValueError(f"AnimaPipeline currently requires a local file path, got: {model_path}")
|
||||
|
||||
state_dict = load_file(model_path, device="cpu")
|
||||
transformer_state_dict, text_conditioner_state_dict = self._split_single_file_state_dict(state_dict)
|
||||
del state_dict
|
||||
transformer_state_dict = self._convert_original_transformer_state_dict(transformer_state_dict)
|
||||
|
||||
config_path = Path(self.od_config.model).with_suffix(".json")
|
||||
config = json.loads(config_path.read_text()) if config_path.is_file() else {}
|
||||
text_conditioner_config = {**ANIMA_TEXT_CONDITIONER_CONFIG, **config.get("text_conditioner", {})}
|
||||
transformer_config = {**ANIMA_TRANSFORMER_CONFIG, **config.get("transformer", {})}
|
||||
|
||||
native_text_conditioner = AnimaTextConditioner(**cast(dict[str, Any], text_conditioner_config))
|
||||
native_text_conditioner.load_state_dict(text_conditioner_state_dict, strict=True)
|
||||
native_text_conditioner.to(device=self.device, dtype=self.od_config.dtype)
|
||||
del text_conditioner_state_dict
|
||||
|
||||
native_transformer = AnimaTransformer3DModel(**cast(dict[str, Any], transformer_config))
|
||||
native_transformer.load_state_dict(transformer_state_dict, strict=True)
|
||||
native_transformer.to(device=self.device, dtype=self.od_config.dtype)
|
||||
del transformer_state_dict
|
||||
|
||||
return native_transformer, native_text_conditioner
|
||||
|
||||
def _component_path(self, name: str, default_model: str) -> str:
|
||||
custom_args = self.od_config.custom_pipeline_args or {}
|
||||
return str(custom_args.get(f"{name}_model", custom_args.get(f"{name}_path", default_model)))
|
||||
|
||||
@staticmethod
|
||||
def _from_pretrained_kwargs(model: str, subfolder: str | None = None) -> dict[str, Any]:
|
||||
kwargs: dict[str, Any] = {"local_files_only": os.path.exists(model)}
|
||||
if subfolder is not None and os.path.isdir(os.path.join(model, subfolder)):
|
||||
kwargs["subfolder"] = subfolder
|
||||
return kwargs
|
||||
|
||||
def _load_outer_components(self) -> tuple[Any, Any, Any, Any, Any]:
|
||||
custom_args = self.od_config.custom_pipeline_args or {}
|
||||
components_model_value = custom_args.get("components_model", custom_args.get("components_path"))
|
||||
if components_model_value is None:
|
||||
if not isinstance(self.od_config.model, str):
|
||||
raise ValueError("AnimaPipeline requires `model` or `components_model` to load outer components.")
|
||||
checkpoint_dir = os.path.dirname(os.path.abspath(self.od_config.model))
|
||||
components_model = checkpoint_dir if os.path.isdir(checkpoint_dir) else self.od_config.model
|
||||
else:
|
||||
components_model = str(components_model_value)
|
||||
|
||||
text_encoder_model = self._component_path("text_encoder", components_model)
|
||||
vae_model = self._component_path("vae", components_model)
|
||||
tokenizer_model = self._component_path("tokenizer", components_model)
|
||||
t5_tokenizer_model = self._component_path("t5_tokenizer", components_model)
|
||||
|
||||
text_encoder = Qwen3Model.from_pretrained(
|
||||
text_encoder_model,
|
||||
torch_dtype=self.od_config.dtype,
|
||||
**self._from_pretrained_kwargs(text_encoder_model, "text_encoder"),
|
||||
).to(self.device)
|
||||
vae = DistributedAutoencoderKLQwenImage.from_pretrained(
|
||||
vae_model,
|
||||
torch_dtype=self.od_config.dtype,
|
||||
**self._from_pretrained_kwargs(vae_model, "vae"),
|
||||
).to(self.device)
|
||||
tokenizer = AutoTokenizer.from_pretrained(
|
||||
tokenizer_model,
|
||||
**self._from_pretrained_kwargs(tokenizer_model, "tokenizer"),
|
||||
)
|
||||
t5_tokenizer = T5TokenizerFast.from_pretrained(
|
||||
t5_tokenizer_model,
|
||||
**self._from_pretrained_kwargs(t5_tokenizer_model, "t5_tokenizer"),
|
||||
)
|
||||
|
||||
scheduler_model = self._component_path("scheduler", components_model)
|
||||
has_scheduler_config = os.path.isfile(os.path.join(scheduler_model, "scheduler_config.json")) or os.path.isdir(
|
||||
os.path.join(scheduler_model, "scheduler")
|
||||
)
|
||||
if has_scheduler_config:
|
||||
scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
|
||||
scheduler_model,
|
||||
**self._from_pretrained_kwargs(scheduler_model, "scheduler"),
|
||||
)
|
||||
else:
|
||||
scheduler = FlowMatchEulerDiscreteScheduler(shift=3.0)
|
||||
|
||||
return text_encoder, tokenizer, t5_tokenizer, vae, scheduler
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]] | None = None) -> set[str]:
|
||||
logger.info("Loading Anima transformer/text-conditioner directly from single-file checkpoint.")
|
||||
state_dict = dict(weights) if weights is not None else None
|
||||
loaded = set(state_dict.keys()) if state_dict is not None else set()
|
||||
if not state_dict:
|
||||
state_dict = None
|
||||
with set_current_diffusion_config(self.od_config):
|
||||
native_transformer, native_text_conditioner = self._load_native_denoiser_components(state_dict)
|
||||
text_encoder, tokenizer, t5_tokenizer, vae, scheduler = self._load_outer_components()
|
||||
|
||||
self.transformer = native_transformer
|
||||
self.text_conditioner = native_text_conditioner
|
||||
self.text_encoder = text_encoder
|
||||
self.tokenizer = tokenizer
|
||||
self.t5_tokenizer = t5_tokenizer
|
||||
self.vae = vae
|
||||
self.scheduler = scheduler
|
||||
self.vae_scale_factor = _anima_vae_scale_factor_from_vae(self.vae)
|
||||
self._setup_profiler()
|
||||
return loaded
|
||||
|
||||
def _setup_profiler(self) -> None:
|
||||
if self._profiler_initialized:
|
||||
return
|
||||
self.setup_diffusion_pipeline_profiler(
|
||||
profiler_targets=["vae.decode", "diffuse", "text_encoder.forward"],
|
||||
enable_diffusion_pipeline_profiler=self.od_config.enable_diffusion_pipeline_profiler,
|
||||
)
|
||||
self._profiler_initialized = True
|
||||
|
||||
def _extract_prompts(self, prompts: list[Any]) -> tuple[str | list[str] | None, str | list[str] | None]:
|
||||
"""Extract prompt and negative_prompt from OmniPromptType list."""
|
||||
prompt = [p if isinstance(p, str) else (p.get("prompt") or "") for p in prompts] or None
|
||||
if all(isinstance(p, str) or p.get("negative_prompt") is None for p in prompts):
|
||||
negative_prompt = None
|
||||
elif prompts:
|
||||
negative_prompt = ["" if isinstance(p, str) else (p.get("negative_prompt") or "") for p in prompts]
|
||||
else:
|
||||
negative_prompt = None
|
||||
return prompt, negative_prompt
|
||||
|
||||
def _get_qwen_prompt_embeds(
|
||||
self,
|
||||
prompt: str | list[str],
|
||||
max_sequence_length: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
prompt = [prompt] if isinstance(prompt, str) else prompt
|
||||
|
||||
text_inputs = self.tokenizer(
|
||||
prompt,
|
||||
padding="longest",
|
||||
max_length=max_sequence_length,
|
||||
truncation=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
text_input_ids = text_inputs.input_ids.to(device)
|
||||
prompt_attention_mask = text_inputs.attention_mask.to(device)
|
||||
if text_input_ids.shape[-1] == 0:
|
||||
text_input_ids = text_input_ids.new_zeros((text_input_ids.shape[0], 1))
|
||||
prompt_attention_mask = prompt_attention_mask.new_zeros((prompt_attention_mask.shape[0], 1))
|
||||
|
||||
prompt_embeds = self.text_encoder(
|
||||
input_ids=text_input_ids,
|
||||
attention_mask=prompt_attention_mask,
|
||||
output_hidden_states=False,
|
||||
).last_hidden_state
|
||||
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
||||
prompt_embeds = prompt_embeds * prompt_attention_mask.to(prompt_embeds).unsqueeze(-1)
|
||||
|
||||
return prompt_embeds, prompt_attention_mask
|
||||
|
||||
def _get_t5_prompt_ids(
|
||||
self,
|
||||
prompt: str | list[str],
|
||||
max_sequence_length: int,
|
||||
device: torch.device,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
prompt = [prompt] if isinstance(prompt, str) else prompt
|
||||
|
||||
text_inputs = self.t5_tokenizer(
|
||||
prompt,
|
||||
padding="longest",
|
||||
max_length=max_sequence_length,
|
||||
truncation=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
return text_inputs.input_ids.to(device), text_inputs.attention_mask.to(device)
|
||||
|
||||
def encode_prompt(
|
||||
self,
|
||||
prompt: str | list[str],
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
prepare_unconditional_embeds: bool = True,
|
||||
max_sequence_length: int = 512,
|
||||
device: torch.device | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
) -> dict[str, torch.Tensor | None]:
|
||||
device = device or self.device
|
||||
dtype = dtype or self.text_encoder.dtype
|
||||
|
||||
prompt = [prompt] if isinstance(prompt, str) else prompt
|
||||
batch_size = len(prompt)
|
||||
|
||||
prompt_embeds, prompt_attention_mask = self._get_qwen_prompt_embeds(
|
||||
prompt=prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
t5_input_ids, t5_attention_mask = self._get_t5_prompt_ids(
|
||||
prompt=prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
)
|
||||
|
||||
negative_prompt_embeds = None
|
||||
negative_prompt_attention_mask = None
|
||||
negative_t5_input_ids = None
|
||||
negative_t5_attention_mask = None
|
||||
if prepare_unconditional_embeds:
|
||||
if negative_prompt is None:
|
||||
negative_prompt = ""
|
||||
if isinstance(negative_prompt, str):
|
||||
negative_prompt = [negative_prompt] * batch_size
|
||||
elif len(negative_prompt) != batch_size:
|
||||
raise ValueError(
|
||||
f"`negative_prompt` length ({len(negative_prompt)}) must match prompt batch size ({batch_size})."
|
||||
)
|
||||
|
||||
negative_prompt_embeds, negative_prompt_attention_mask = self._get_qwen_prompt_embeds(
|
||||
prompt=negative_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
dtype=dtype,
|
||||
)
|
||||
negative_t5_input_ids, negative_t5_attention_mask = self._get_t5_prompt_ids(
|
||||
prompt=negative_prompt,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=device,
|
||||
)
|
||||
|
||||
return {
|
||||
"qwen_prompt_embeds": prompt_embeds,
|
||||
"qwen_attention_mask": prompt_attention_mask,
|
||||
"t5_input_ids": t5_input_ids,
|
||||
"t5_attention_mask": t5_attention_mask,
|
||||
"negative_qwen_prompt_embeds": negative_prompt_embeds,
|
||||
"negative_qwen_attention_mask": negative_prompt_attention_mask,
|
||||
"negative_t5_input_ids": negative_t5_input_ids,
|
||||
"negative_t5_attention_mask": negative_t5_attention_mask,
|
||||
}
|
||||
|
||||
def condition_prompt_embeds(
|
||||
self,
|
||||
qwen_prompt_embeds: torch.Tensor,
|
||||
qwen_attention_mask: torch.Tensor,
|
||||
t5_input_ids: torch.Tensor,
|
||||
t5_attention_mask: torch.Tensor,
|
||||
device: torch.device | None = None,
|
||||
conditioning_dtype: torch.dtype | None = None,
|
||||
output_dtype: torch.dtype | None = None,
|
||||
) -> torch.Tensor:
|
||||
device = device or self.device
|
||||
conditioning_dtype = conditioning_dtype or self.text_conditioner.dtype
|
||||
output_dtype = output_dtype or self.transformer.dtype
|
||||
|
||||
prompt_embeds = self.text_conditioner(
|
||||
source_hidden_states=qwen_prompt_embeds.to(device=device, dtype=conditioning_dtype),
|
||||
target_input_ids=t5_input_ids.to(device),
|
||||
target_attention_mask=t5_attention_mask.to(device),
|
||||
source_attention_mask=qwen_attention_mask.to(device),
|
||||
)
|
||||
return prompt_embeds.to(dtype=output_dtype, device=device)
|
||||
|
||||
def prepare_latents(
|
||||
self,
|
||||
batch_size: int,
|
||||
num_channels_latents: int,
|
||||
height: int,
|
||||
width: int,
|
||||
dtype: torch.dtype | None = None,
|
||||
device: torch.device | None = None,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
device = device or self.device
|
||||
dtype = dtype or self.transformer.dtype
|
||||
if latents is not None:
|
||||
return latents.to(device=device, dtype=dtype)
|
||||
|
||||
latent_height = height // self.vae_scale_factor
|
||||
latent_width = width // self.vae_scale_factor
|
||||
shape = (batch_size, num_channels_latents, 1, latent_height, latent_width)
|
||||
|
||||
if isinstance(generator, list) and len(generator) != batch_size:
|
||||
raise ValueError(
|
||||
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
||||
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
||||
)
|
||||
|
||||
# Draw latents in float32 then cast
|
||||
latents = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
|
||||
sigma_max = (
|
||||
getattr(self.scheduler.config, "sigma_max", 1.0)
|
||||
if hasattr(self, "scheduler") and hasattr(self.scheduler, "config")
|
||||
else 1.0
|
||||
)
|
||||
return latents.to(dtype=dtype) * sigma_max
|
||||
|
||||
def prepare_timesteps(
|
||||
self,
|
||||
num_inference_steps: int,
|
||||
sigmas: list[float] | None = None,
|
||||
device: torch.device | None = None,
|
||||
) -> tuple[torch.Tensor, int]:
|
||||
device = device or self.device
|
||||
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
|
||||
return retrieve_timesteps(
|
||||
self.scheduler,
|
||||
device=device,
|
||||
sigmas=sigmas,
|
||||
)
|
||||
|
||||
def diffuse(
|
||||
self,
|
||||
prompt_embeds: torch.Tensor,
|
||||
negative_prompt_embeds: torch.Tensor | None,
|
||||
latents: torch.Tensor,
|
||||
padding_mask: torch.Tensor,
|
||||
timesteps: torch.Tensor,
|
||||
do_true_cfg: bool,
|
||||
true_cfg_scale: float,
|
||||
) -> torch.Tensor:
|
||||
self.scheduler.set_begin_index(0)
|
||||
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for i, t in enumerate(timesteps):
|
||||
if self.interrupt:
|
||||
continue
|
||||
self._current_timestep = t
|
||||
|
||||
# Broadcast timestep to match batch size
|
||||
timestep = t.expand(latents.shape[0]).to(dtype=self.transformer.dtype, device=latents.device)
|
||||
timestep = timestep / 1000.0 # normalize to 0..1 range
|
||||
|
||||
# Predict noise
|
||||
latent_model_input = latents.to(self.transformer.dtype)
|
||||
|
||||
# Positive pass
|
||||
noise_pred = self.transformer(
|
||||
hidden_states=latent_model_input,
|
||||
timestep=timestep,
|
||||
encoder_hidden_states=prompt_embeds,
|
||||
padding_mask=padding_mask,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
|
||||
# Negative / uncond pass
|
||||
if do_true_cfg and negative_prompt_embeds is not None:
|
||||
noise_pred_uncond = self.transformer(
|
||||
hidden_states=latent_model_input,
|
||||
timestep=timestep,
|
||||
encoder_hidden_states=negative_prompt_embeds,
|
||||
padding_mask=padding_mask,
|
||||
return_dict=False,
|
||||
)[0]
|
||||
noise_pred = noise_pred_uncond + true_cfg_scale * (noise_pred - noise_pred_uncond)
|
||||
|
||||
# Scheduler step
|
||||
latents_dtype = latents.dtype
|
||||
latents = self.scheduler.step(noise_pred.to(latents_dtype), t, latents, return_dict=False)[0]
|
||||
if latents.dtype != latents_dtype:
|
||||
latents = latents.to(latents_dtype)
|
||||
|
||||
pbar.update()
|
||||
|
||||
return latents
|
||||
|
||||
def decode_latents(
|
||||
self,
|
||||
latents: torch.Tensor,
|
||||
output_type: str = "pil",
|
||||
) -> DiffusionOutput:
|
||||
"""Decode final latents."""
|
||||
if output_type == "latent":
|
||||
return DiffusionOutput(
|
||||
output=latents,
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
latents = latents.to(self.vae.dtype)
|
||||
latents_mean = (
|
||||
torch.tensor(self.vae.config.latents_mean)
|
||||
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
||||
.to(latents.device, latents.dtype)
|
||||
)
|
||||
latents_std = (
|
||||
torch.tensor(self.vae.config.latents_std)
|
||||
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
||||
.to(latents.device, latents.dtype)
|
||||
)
|
||||
latents = latents * latents_std + latents_mean
|
||||
image = self.vae.decode(latents, return_dict=False)[0][:, :, 0]
|
||||
return DiffusionOutput(
|
||||
output=image,
|
||||
stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
req: DiffusionRequestBatch,
|
||||
prompt: str | list[str] | None = None,
|
||||
negative_prompt: str | list[str] | None = None,
|
||||
true_cfg_scale: float = 4.0,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
num_inference_steps: int = 50,
|
||||
sigmas: list[float] | None = None,
|
||||
guidance_scale: float = 4.0,
|
||||
num_images_per_prompt: int = 1,
|
||||
generator: torch.Generator | list[torch.Generator] | None = None,
|
||||
latents: torch.Tensor | None = None,
|
||||
output_type: str | None = "pil",
|
||||
max_sequence_length: int = 512,
|
||||
) -> list[DiffusionOutput]:
|
||||
if req.num_reqs != 1:
|
||||
raise ValueError("AnimaPipeline supports one request per forward.")
|
||||
extracted_prompt, negative_prompt = self._extract_prompts(req.prompts)
|
||||
prompt = extracted_prompt or prompt
|
||||
if prompt is None:
|
||||
prompt = ""
|
||||
|
||||
height = req.sampling_params.height or height or 1024
|
||||
width = req.sampling_params.width or width or 1024
|
||||
height, width = normalize_min_aligned_size(height, width, self.vae_scale_factor * 2)
|
||||
if height is None or width is None:
|
||||
raise ValueError("AnimaPipeline requires resolved height and width.")
|
||||
height = int(height)
|
||||
width = int(width)
|
||||
if req.sampling_params.output_type is not None:
|
||||
output_type = req.sampling_params.output_type
|
||||
output_type = output_type or "pil"
|
||||
|
||||
num_inference_steps = req.sampling_params.num_inference_steps or num_inference_steps
|
||||
sigmas = req.sampling_params.sigmas or sigmas
|
||||
max_sequence_length = req.sampling_params.max_sequence_length or max_sequence_length
|
||||
generator = req.sampling_params.generator or generator
|
||||
if req.sampling_params.guidance_scale_provided:
|
||||
guidance_scale = req.sampling_params.guidance_scale
|
||||
if req.sampling_params.true_cfg_scale is None:
|
||||
true_cfg_scale = guidance_scale
|
||||
if req.sampling_params.true_cfg_scale is not None:
|
||||
true_cfg_scale = req.sampling_params.true_cfg_scale
|
||||
num_images_per_prompt = (
|
||||
req.sampling_params.num_outputs_per_prompt
|
||||
if req.sampling_params.num_outputs_per_prompt > 0
|
||||
else num_images_per_prompt
|
||||
)
|
||||
|
||||
self._guidance_scale = guidance_scale
|
||||
self._interrupt = False
|
||||
|
||||
if isinstance(prompt, str):
|
||||
batch_size = 1
|
||||
else:
|
||||
batch_size = len(prompt)
|
||||
|
||||
do_true_cfg = guidance_scale > 1.0
|
||||
|
||||
# Encode prompts
|
||||
enc_out = self.encode_prompt(
|
||||
prompt=prompt,
|
||||
negative_prompt=negative_prompt,
|
||||
prepare_unconditional_embeds=do_true_cfg,
|
||||
max_sequence_length=max_sequence_length,
|
||||
device=self.device,
|
||||
dtype=self.text_encoder.dtype,
|
||||
)
|
||||
qwen_prompt_embeds = enc_out["qwen_prompt_embeds"]
|
||||
qwen_attention_mask = enc_out["qwen_attention_mask"]
|
||||
t5_input_ids = enc_out["t5_input_ids"]
|
||||
t5_attention_mask = enc_out["t5_attention_mask"]
|
||||
if (
|
||||
qwen_prompt_embeds is None
|
||||
or qwen_attention_mask is None
|
||||
or t5_input_ids is None
|
||||
or t5_attention_mask is None
|
||||
):
|
||||
raise ValueError("Anima prompt encoding did not produce all required positive embeddings.")
|
||||
|
||||
# Condition prompt embeds
|
||||
prompt_embeds = self.condition_prompt_embeds(
|
||||
qwen_prompt_embeds=qwen_prompt_embeds,
|
||||
qwen_attention_mask=qwen_attention_mask,
|
||||
t5_input_ids=t5_input_ids,
|
||||
t5_attention_mask=t5_attention_mask,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
negative_prompt_embeds = None
|
||||
negative_qwen_prompt_embeds = enc_out["negative_qwen_prompt_embeds"]
|
||||
if do_true_cfg and negative_qwen_prompt_embeds is not None:
|
||||
negative_qwen_attention_mask = enc_out["negative_qwen_attention_mask"]
|
||||
negative_t5_input_ids = enc_out["negative_t5_input_ids"]
|
||||
negative_t5_attention_mask = enc_out["negative_t5_attention_mask"]
|
||||
if (
|
||||
negative_qwen_attention_mask is None
|
||||
or negative_t5_input_ids is None
|
||||
or negative_t5_attention_mask is None
|
||||
):
|
||||
raise ValueError("Anima prompt encoding did not produce all required negative embeddings.")
|
||||
negative_prompt_embeds = self.condition_prompt_embeds(
|
||||
qwen_prompt_embeds=negative_qwen_prompt_embeds,
|
||||
qwen_attention_mask=negative_qwen_attention_mask,
|
||||
t5_input_ids=negative_t5_input_ids,
|
||||
t5_attention_mask=negative_t5_attention_mask,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
# Repeat for num_images_per_prompt
|
||||
_, seq_len, _ = prompt_embeds.shape
|
||||
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
||||
prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
||||
|
||||
if negative_prompt_embeds is not None:
|
||||
_, seq_len, _ = negative_prompt_embeds.shape
|
||||
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
||||
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
|
||||
|
||||
# Prepare latents
|
||||
latents = self.prepare_latents(
|
||||
batch_size=batch_size * num_images_per_prompt,
|
||||
num_channels_latents=16, # Cosmos/Anima has 16 channels
|
||||
height=height,
|
||||
width=width,
|
||||
dtype=torch.float32,
|
||||
device=self.device,
|
||||
generator=generator,
|
||||
latents=latents,
|
||||
)
|
||||
|
||||
# Prepare padding mask
|
||||
padding_mask = latents.new_zeros(1, 1, height, width, dtype=self.transformer.dtype)
|
||||
|
||||
# Prepare timesteps
|
||||
timesteps, num_inference_steps = self.prepare_timesteps(
|
||||
num_inference_steps=num_inference_steps,
|
||||
sigmas=sigmas,
|
||||
device=self.device,
|
||||
)
|
||||
self._num_timesteps = len(timesteps)
|
||||
|
||||
# Denoise loop
|
||||
latents = self.diffuse(
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
latents=latents,
|
||||
padding_mask=padding_mask,
|
||||
timesteps=timesteps,
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=true_cfg_scale,
|
||||
)
|
||||
|
||||
self._current_timestep = None
|
||||
return [self.decode_latents(latents, output_type=output_type)]
|
||||
|
||||
@property
|
||||
def guidance_scale(self) -> float:
|
||||
return self._guidance_scale
|
||||
|
||||
@property
|
||||
def num_timesteps(self) -> int:
|
||||
return self._num_timesteps
|
||||
|
||||
@property
|
||||
def current_timestep(self) -> torch.Tensor | None:
|
||||
return self._current_timestep
|
||||
|
||||
@property
|
||||
def interrupt(self) -> bool:
|
||||
return self._interrupt
|
||||
@@ -0,0 +1,16 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""AuK diffusion-stage components: the flow transformer, the codec, the pipeline."""
|
||||
|
||||
from vllm_omni.diffusion.models.auk.auk_transformer import AuKTransformer, dit_state_dict, sample_latents
|
||||
from vllm_omni.diffusion.models.auk.auk_vae import AuKVAE
|
||||
from vllm_omni.diffusion.models.auk.pipeline_auk import AuKPipeline, get_auk_post_process_func
|
||||
|
||||
__all__ = [
|
||||
"AuKPipeline",
|
||||
"AuKTransformer",
|
||||
"AuKVAE",
|
||||
"dit_state_dict",
|
||||
"get_auk_post_process_func",
|
||||
"sample_latents",
|
||||
]
|
||||
@@ -0,0 +1,677 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""The AuK audio DiT as a self-contained inference module.
|
||||
|
||||
Two phases. ``num_layers`` double-stream blocks attend jointly over text and
|
||||
audio while keeping each stream's residual separate, then
|
||||
``num_single_layers`` single-stream blocks run over the concatenated
|
||||
``[text | ref audio | target audio]`` sequence. Only the target-audio slice is
|
||||
projected back to latent space, so the module predicts a flow-matching
|
||||
velocity for the target frames and :func:`sample_latents` integrates it.
|
||||
|
||||
Parameter names and shapes match the AuK reference backbone, so a released
|
||||
checkpoint loads with ``load_state_dict(strict=True)`` once the
|
||||
``transformer.`` prefix is stripped (see :func:`dit_state_dict`).
|
||||
|
||||
Deliberate differences from the reference, all inference-only:
|
||||
|
||||
* ``x_transformers`` and ``torchdiffeq`` are gone. Rotary embeddings are
|
||||
computed here (interleaved GPT-J pairs, no xpos scaling) and the ODE is an
|
||||
explicit Euler loop.
|
||||
* Dropout, activation checkpointing, the ``flash_attn`` backend switch and the
|
||||
zero-init of the modulation layers are training concerns and are dropped.
|
||||
* The timestep sinusoid is cast to the time MLP's weight dtype rather than to
|
||||
the timestep's own dtype, so an fp32 timestep works against half-precision
|
||||
weights outside autocast.
|
||||
* ``attn_mask_enabled`` defaults to ``True``, the value the released config
|
||||
sets, rather than the reference's ``False``.
|
||||
"""
|
||||
|
||||
import math
|
||||
from collections.abc import Iterable, Mapping
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch import nn
|
||||
|
||||
__all__ = ["AuKTransformer", "dit_state_dict", "sample_latents"]
|
||||
|
||||
|
||||
def _sdpa(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor | None) -> torch.Tensor:
|
||||
"""The single attention call site, so the backend can be swapped in one place.
|
||||
|
||||
``q``/``k``/``v`` are ``[B, H, N, D]``. ``mask`` is a boolean key-padding
|
||||
mask ``[B, K]`` in which ``True`` marks a valid key; it is broadcast to
|
||||
``[B, H, Q, K]`` only when given.
|
||||
"""
|
||||
attn_mask = None
|
||||
if mask is not None:
|
||||
attn_mask = mask[:, None, None, :].expand(q.shape[0], q.shape[1], q.shape[-2], k.shape[-2])
|
||||
return F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=0.0, is_causal=False)
|
||||
|
||||
|
||||
def _rotate_half(x: torch.Tensor) -> torch.Tensor:
|
||||
"""Rotate interleaved GPT-J pairs: ``(x1, x2) -> (-x2, x1)``."""
|
||||
pairs = x.reshape(*x.shape[:-1], -1, 2)
|
||||
x1, x2 = pairs.unbind(dim=-1)
|
||||
return torch.stack((-x2, x1), dim=-1).flatten(-2)
|
||||
|
||||
|
||||
def _apply_rope(x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
||||
"""Apply rotary frequencies ``[1, 1, N, D]`` to ``x`` ``[B, H, N, D]`` in fp32."""
|
||||
out_dtype = x.dtype
|
||||
x32 = x.float()
|
||||
out = x32 * freqs.cos() + _rotate_half(x32) * freqs.sin()
|
||||
return out.to(out_dtype)
|
||||
|
||||
|
||||
class Rotary(nn.Module):
|
||||
"""Rotary position frequencies for one stream, evaluated in fp32.
|
||||
|
||||
The frequencies live in a buffer so that a released checkpoint's own copy
|
||||
of them loads with ``strict=True``. They are recomputed whenever the
|
||||
module has been cast below fp32: rounding either the frequencies or the
|
||||
integer positions to bf16 wrecks the phase at long positions.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, base: float = 10000.0) -> None:
|
||||
super().__init__()
|
||||
if dim % 2 != 0:
|
||||
raise ValueError(f"rotary dim must be even, got {dim}")
|
||||
self.dim = dim
|
||||
self.base = base
|
||||
self.register_buffer("inv_freq", self._frequencies(torch.device("cpu")))
|
||||
|
||||
def _frequencies(self, device: torch.device) -> torch.Tensor:
|
||||
exponents = torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim
|
||||
return 1.0 / (self.base**exponents)
|
||||
|
||||
def forward(self, seq_len: int) -> torch.Tensor:
|
||||
"""Return frequencies ``[1, 1, seq_len, dim]`` for positions ``0..seq_len-1``."""
|
||||
inv_freq = self.inv_freq
|
||||
if inv_freq.dtype != torch.float32:
|
||||
inv_freq = self._frequencies(inv_freq.device)
|
||||
pos = torch.arange(seq_len, device=inv_freq.device, dtype=torch.float32)
|
||||
freqs = torch.outer(pos, inv_freq)
|
||||
return torch.stack((freqs, freqs), dim=-1).flatten(-2)[None, None]
|
||||
|
||||
|
||||
class TimeEmbedding(nn.Module):
|
||||
"""Sinusoidal timestep features followed by a two-layer MLP."""
|
||||
|
||||
def __init__(self, dim: int, freq_embed_dim: int = 256) -> None:
|
||||
super().__init__()
|
||||
self.freq_embed_dim = freq_embed_dim
|
||||
self.time_mlp = nn.Sequential(nn.Linear(freq_embed_dim, dim), nn.SiLU(), nn.Linear(dim, dim))
|
||||
|
||||
def forward(self, timestep: torch.Tensor, scale: float = 1000.0) -> torch.Tensor:
|
||||
half = self.freq_embed_dim // 2
|
||||
decay = math.log(10000) / (half - 1)
|
||||
freqs = torch.exp(torch.arange(half, device=timestep.device, dtype=torch.float32) * -decay)
|
||||
angles = scale * timestep.unsqueeze(1) * freqs.unsqueeze(0)
|
||||
hidden = torch.cat((angles.sin(), angles.cos()), dim=-1)
|
||||
return self.time_mlp(hidden.to(self.time_mlp[0].weight.dtype))
|
||||
|
||||
|
||||
class ConvPosEmbedding(nn.Module):
|
||||
"""Depthwise-grouped conv stack that adds local position information."""
|
||||
|
||||
def __init__(self, dim: int, kernel_size: int = 31, groups: int = 16) -> None:
|
||||
super().__init__()
|
||||
if kernel_size % 2 == 0:
|
||||
raise ValueError(f"kernel_size must be odd, got {kernel_size}")
|
||||
padding = kernel_size // 2
|
||||
self.conv1d = nn.Sequential(
|
||||
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=padding),
|
||||
nn.Mish(),
|
||||
nn.Conv1d(dim, dim, kernel_size, groups=groups, padding=padding),
|
||||
nn.Mish(),
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
||||
keep = None if mask is None else mask.unsqueeze(1)
|
||||
x = x.transpose(1, 2)
|
||||
if keep is not None:
|
||||
x = x.masked_fill(~keep, 0.0)
|
||||
for layer in self.conv1d:
|
||||
x = layer(x)
|
||||
# Re-zero padding after each convolution so it cannot bleed into
|
||||
# valid frames through the kernel window.
|
||||
if keep is not None and isinstance(layer, nn.Conv1d):
|
||||
x = x.masked_fill(~keep, 0.0)
|
||||
return x.transpose(1, 2)
|
||||
|
||||
|
||||
class AudioEmbedding(nn.Module):
|
||||
"""Project audio latents to model width and add conv position information."""
|
||||
|
||||
def __init__(self, latent_dim: int, dim: int) -> None:
|
||||
super().__init__()
|
||||
self.linear = nn.Linear(latent_dim, dim)
|
||||
self.conv_pos_embed = ConvPosEmbedding(dim)
|
||||
|
||||
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
|
||||
x = self.linear(x)
|
||||
return self.conv_pos_embed(x, mask=mask) + x
|
||||
|
||||
|
||||
class AdaLayerNorm(nn.Module):
|
||||
"""Timestep-conditioned modulation for a block: six chunks from one projection."""
|
||||
|
||||
def __init__(self, dim: int) -> None:
|
||||
super().__init__()
|
||||
self.silu = nn.SiLU()
|
||||
self.linear = nn.Linear(dim, dim * 6)
|
||||
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, emb: torch.Tensor
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.linear(self.silu(emb)).chunk(6, dim=1)
|
||||
x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
|
||||
return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
|
||||
|
||||
|
||||
class AdaLayerNormFinal(nn.Module):
|
||||
"""Timestep-conditioned modulation before the output projection."""
|
||||
|
||||
def __init__(self, dim: int) -> None:
|
||||
super().__init__()
|
||||
self.silu = nn.SiLU()
|
||||
self.linear = nn.Linear(dim, dim * 2)
|
||||
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
||||
|
||||
def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
|
||||
scale, shift = self.linear(self.silu(emb)).chunk(2, dim=1)
|
||||
return self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
|
||||
|
||||
|
||||
class FeedForward(nn.Module):
|
||||
"""SwiGLU feed-forward with the gate projection fused into ``linear_in``."""
|
||||
|
||||
def __init__(self, dim: int, mult: float = 4.0) -> None:
|
||||
super().__init__()
|
||||
inner_dim = int(dim * mult)
|
||||
self.linear_in = nn.Linear(dim, inner_dim * 2, bias=False)
|
||||
self.linear_out = nn.Linear(inner_dim, dim, bias=False)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
gate, up = self.linear_in(x).chunk(2, dim=-1)
|
||||
return self.linear_out(F.silu(gate) * up)
|
||||
|
||||
|
||||
class Attention(nn.Module):
|
||||
"""Self-attention with per-head QK RMSNorm and rotary positions.
|
||||
|
||||
``to_out`` stays a ``ModuleList`` because the released checkpoints name the
|
||||
output projection ``to_out.0``; the reference's trailing dropout carries no
|
||||
parameters and is dropped.
|
||||
"""
|
||||
|
||||
def __init__(self, dim: int, heads: int, dim_head: int, attn_mask_enabled: bool = True) -> None:
|
||||
super().__init__()
|
||||
self.heads = heads
|
||||
self.dim_head = dim_head
|
||||
self.attn_mask_enabled = attn_mask_enabled
|
||||
inner_dim = heads * dim_head
|
||||
self.to_qkv = nn.Linear(dim, 3 * inner_dim)
|
||||
self.q_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
|
||||
self.k_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
|
||||
self.to_out = nn.ModuleList([nn.Linear(inner_dim, dim)])
|
||||
|
||||
def _merge_heads(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return x.transpose(1, 2).reshape(x.shape[0], -1, self.heads * self.dim_head)
|
||||
|
||||
def _qkv(
|
||||
self,
|
||||
packed: torch.Tensor,
|
||||
q_norm: nn.Module,
|
||||
k_norm: nn.Module,
|
||||
rope: torch.Tensor | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Split a packed QKV projection into heads, RMSNorm Q/K, then rotate."""
|
||||
q, k, v = (t.view(t.shape[0], -1, self.heads, self.dim_head).transpose(1, 2) for t in packed.chunk(3, dim=-1))
|
||||
q = q_norm(q)
|
||||
k = k_norm(k)
|
||||
if rope is not None:
|
||||
q = _apply_rope(q, rope)
|
||||
k = _apply_rope(k, rope)
|
||||
return q, k, v
|
||||
|
||||
def _project(self, x: torch.Tensor, rope: torch.Tensor | None) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
return self._qkv(self.to_qkv(x), self.q_norm, self.k_norm, rope)
|
||||
|
||||
def forward(
|
||||
self, x: torch.Tensor, mask: torch.Tensor | None = None, rope: torch.Tensor | None = None
|
||||
) -> torch.Tensor:
|
||||
q, k, v = self._project(x, rope)
|
||||
attn_mask = mask if self.attn_mask_enabled else None
|
||||
out = self._merge_heads(_sdpa(q, k, v, attn_mask).to(q.dtype))
|
||||
out = self.to_out[0](out)
|
||||
if mask is not None:
|
||||
out = out.masked_fill(~mask.unsqueeze(-1), 0.0)
|
||||
return out
|
||||
|
||||
|
||||
class JointAttention(Attention):
|
||||
"""Attention over the audio and text streams jointly, with separate projections."""
|
||||
|
||||
def __init__(self, dim: int, heads: int, dim_head: int, context_dim: int, attn_mask_enabled: bool = True) -> None:
|
||||
super().__init__(dim, heads, dim_head, attn_mask_enabled)
|
||||
inner_dim = heads * dim_head
|
||||
self.to_qkv_c = nn.Linear(context_dim, 3 * inner_dim)
|
||||
self.c_q_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
|
||||
self.c_k_norm = nn.RMSNorm(dim_head, elementwise_affine=True)
|
||||
self.to_out_c = nn.Linear(inner_dim, context_dim)
|
||||
|
||||
def _project_context(self, c: torch.Tensor, c_rope: torch.Tensor | None) -> tuple[torch.Tensor, ...]:
|
||||
return self._qkv(self.to_qkv_c(c), self.c_q_norm, self.c_k_norm, c_rope)
|
||||
|
||||
def forward( # type: ignore[override] # joint attention takes the context stream too
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
c: torch.Tensor,
|
||||
mask: torch.Tensor | None = None,
|
||||
rope: torch.Tensor | None = None,
|
||||
c_rope: torch.Tensor | None = None,
|
||||
c_mask: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
audio_len = x.shape[1]
|
||||
q, k, v = self._project(x, rope)
|
||||
c_q, c_k, c_v = self._project_context(c, c_rope)
|
||||
|
||||
q = torch.cat([q, c_q], dim=2)
|
||||
k = torch.cat([k, c_k], dim=2)
|
||||
v = torch.cat([v, c_v], dim=2)
|
||||
|
||||
joint_mask = None
|
||||
if self.attn_mask_enabled and mask is not None:
|
||||
if c_mask is not None:
|
||||
joint_mask = torch.cat([mask, c_mask], dim=1)
|
||||
else:
|
||||
joint_mask = F.pad(mask, (0, c.shape[1]), value=True)
|
||||
|
||||
out = self._merge_heads(_sdpa(q, k, v, joint_mask).to(q.dtype))
|
||||
x_out = self.to_out[0](out[:, :audio_len])
|
||||
c_out = self.to_out_c(out[:, audio_len:])
|
||||
|
||||
if mask is not None:
|
||||
x_out = x_out.masked_fill(~mask.unsqueeze(-1), 0.0)
|
||||
if c_mask is not None:
|
||||
c_out = c_out.masked_fill(~c_mask.unsqueeze(-1), 0.0)
|
||||
return x_out, c_out
|
||||
|
||||
|
||||
class DoubleBlock(nn.Module):
|
||||
"""MM-DiT block: joint attention, separate modulation and feed-forward per stream."""
|
||||
|
||||
def __init__(self, dim: int, heads: int, dim_head: int, ff_mult: float, attn_mask_enabled: bool) -> None:
|
||||
super().__init__()
|
||||
self.attn_norm_c = AdaLayerNorm(dim)
|
||||
self.attn_norm_x = AdaLayerNorm(dim)
|
||||
self.attn = JointAttention(
|
||||
dim=dim, heads=heads, dim_head=dim_head, context_dim=dim, attn_mask_enabled=attn_mask_enabled
|
||||
)
|
||||
self.ff_norm_c = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
||||
self.ff_c = FeedForward(dim=dim, mult=ff_mult)
|
||||
self.ff_norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
||||
self.ff_x = FeedForward(dim=dim, mult=ff_mult)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
c: torch.Tensor,
|
||||
t: torch.Tensor,
|
||||
mask: torch.Tensor | None,
|
||||
rope: torch.Tensor,
|
||||
c_rope: torch.Tensor,
|
||||
c_mask: torch.Tensor | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
norm_c, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.attn_norm_c(c, t)
|
||||
norm_x, x_gate_msa, x_shift_mlp, x_scale_mlp, x_gate_mlp = self.attn_norm_x(x, t)
|
||||
|
||||
x_attn, c_attn = self.attn(x=norm_x, c=norm_c, mask=mask, rope=rope, c_rope=c_rope, c_mask=c_mask)
|
||||
|
||||
c = c + c_gate_msa[:, None] * c_attn
|
||||
norm_c = self.ff_norm_c(c) * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
|
||||
c = c + c_gate_mlp[:, None] * self.ff_c(norm_c)
|
||||
|
||||
x = x + x_gate_msa[:, None] * x_attn
|
||||
norm_x = self.ff_norm_x(x) * (1 + x_scale_mlp[:, None]) + x_shift_mlp[:, None]
|
||||
x = x + x_gate_mlp[:, None] * self.ff_x(norm_x)
|
||||
return c, x
|
||||
|
||||
|
||||
class SingleBlock(nn.Module):
|
||||
"""DiT block over the concatenated text and audio sequence."""
|
||||
|
||||
def __init__(self, dim: int, heads: int, dim_head: int, ff_mult: float, attn_mask_enabled: bool) -> None:
|
||||
super().__init__()
|
||||
self.attn_norm = AdaLayerNorm(dim)
|
||||
self.attn = Attention(dim=dim, heads=heads, dim_head=dim_head, attn_mask_enabled=attn_mask_enabled)
|
||||
self.ff_norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
|
||||
self.ff = FeedForward(dim=dim, mult=ff_mult)
|
||||
|
||||
def forward(self, x: torch.Tensor, t: torch.Tensor, mask: torch.Tensor | None, rope: torch.Tensor) -> torch.Tensor:
|
||||
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, t)
|
||||
x = x + gate_msa[:, None] * self.attn(x=norm, mask=mask, rope=rope)
|
||||
norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
||||
return x + gate_mlp[:, None] * self.ff(norm)
|
||||
|
||||
|
||||
class AuKTransformer(nn.Module):
|
||||
"""Flow-matching velocity predictor for AuK audio latents.
|
||||
|
||||
Args:
|
||||
dim: Model width.
|
||||
heads: Attention heads.
|
||||
dim_head: Per-head width.
|
||||
ff_mult: Feed-forward expansion factor.
|
||||
latent_dim: Audio VAE latent channels, the input and output width.
|
||||
text_hidden_dim: Width of the pre-encoded text hidden states.
|
||||
num_layers: Double-stream (joint attention) block count.
|
||||
num_single_layers: Single-stream block count.
|
||||
attn_mask_enabled: Apply padding masks inside attention. When ``False``
|
||||
attention runs unmasked, though padded outputs are still zeroed,
|
||||
which is what the reference does with the flag off.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
dim: int,
|
||||
heads: int,
|
||||
dim_head: int,
|
||||
ff_mult: float,
|
||||
latent_dim: int,
|
||||
text_hidden_dim: int,
|
||||
num_layers: int,
|
||||
num_single_layers: int,
|
||||
attn_mask_enabled: bool = True,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.latent_dim = latent_dim
|
||||
self.text_cond: torch.Tensor | None = None
|
||||
self.text_uncond: torch.Tensor | None = None
|
||||
|
||||
self.time_embed = TimeEmbedding(dim)
|
||||
self.txt_norm = nn.RMSNorm(dim, elementwise_affine=True)
|
||||
self.txt_proj = nn.Linear(text_hidden_dim, dim)
|
||||
self.audio_embed = AudioEmbedding(latent_dim, dim)
|
||||
self.rotary_embed = Rotary(dim_head)
|
||||
|
||||
self.transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
DoubleBlock(
|
||||
dim=dim, heads=heads, dim_head=dim_head, ff_mult=ff_mult, attn_mask_enabled=attn_mask_enabled
|
||||
)
|
||||
for _ in range(num_layers)
|
||||
]
|
||||
)
|
||||
self.single_transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
SingleBlock(
|
||||
dim=dim, heads=heads, dim_head=dim_head, ff_mult=ff_mult, attn_mask_enabled=attn_mask_enabled
|
||||
)
|
||||
for _ in range(num_single_layers)
|
||||
]
|
||||
)
|
||||
|
||||
self.norm_out = AdaLayerNormFinal(dim)
|
||||
self.proj_out = nn.Linear(dim, latent_dim)
|
||||
|
||||
def project_text(self, text: torch.Tensor) -> torch.Tensor:
|
||||
"""Project LLM hidden states ``[B, nt, text_hidden_dim]`` to model width."""
|
||||
return self.txt_norm(self.txt_proj(text))
|
||||
|
||||
def clear_cache(self) -> None:
|
||||
"""Drop the cached text projection. Call this when the conditioning changes."""
|
||||
self.text_cond = None
|
||||
self.text_uncond = None
|
||||
|
||||
def _embed_audio(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
ref: torch.Tensor | None,
|
||||
drop_audio_cond: bool,
|
||||
mask: torch.Tensor | None,
|
||||
ref_mask: torch.Tensor | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None, int]:
|
||||
"""Embed the target latents, prepending the reference prompt when present.
|
||||
|
||||
Returns the ``[ref | target]`` sequence, its padding mask and the
|
||||
reference length, which the caller uses to slice the target back out.
|
||||
"""
|
||||
if ref is not None and ref.shape[1] == 0:
|
||||
ref = None
|
||||
|
||||
target = self.audio_embed(x, mask=mask)
|
||||
if ref is None:
|
||||
return target, mask, 0
|
||||
|
||||
if drop_audio_cond:
|
||||
ref = torch.zeros_like(ref)
|
||||
prompt = self.audio_embed(ref, mask=ref_mask)
|
||||
audio = torch.cat([prompt, target], dim=1)
|
||||
prompt_len = prompt.shape[1]
|
||||
|
||||
audio_mask = None
|
||||
if mask is not None or ref_mask is not None:
|
||||
if mask is None:
|
||||
mask = x.new_ones(x.shape[:2], dtype=torch.bool)
|
||||
if ref_mask is None:
|
||||
ref_mask = ref.new_ones(ref.shape[:2], dtype=torch.bool)
|
||||
audio_mask = torch.cat([ref_mask, mask], dim=1)
|
||||
return audio, audio_mask, prompt_len
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
text: torch.Tensor,
|
||||
time: torch.Tensor,
|
||||
*,
|
||||
mask: torch.Tensor | None = None,
|
||||
c_mask: torch.Tensor | None = None,
|
||||
ref: torch.Tensor | None = None,
|
||||
ref_mask: torch.Tensor | None = None,
|
||||
drop_audio_cond: bool = False,
|
||||
drop_text: bool = False,
|
||||
cfg_infer: bool = False,
|
||||
cache: bool = False,
|
||||
) -> torch.Tensor:
|
||||
"""Predict the flow-matching velocity for the target frames of ``x``.
|
||||
|
||||
Args:
|
||||
x: Noised target latents ``[B, n, latent_dim]``.
|
||||
text: Pre-encoded text hidden states ``[B, nt, text_hidden_dim]``.
|
||||
time: Flow-matching timestep, a scalar or ``[B]``.
|
||||
mask: Target padding mask ``[B, n]``, ``True`` where valid.
|
||||
c_mask: Text padding mask ``[B, nt]``. Inferred from all-zero text
|
||||
rows when omitted.
|
||||
ref: Reference prompt latents ``[B, np, latent_dim]``, prepended to
|
||||
the audio sequence. A zero-length ``ref`` counts as absent.
|
||||
ref_mask: Reference padding mask ``[B, np]``.
|
||||
drop_audio_cond: Zero the reference prompt, for the CFG uncond branch.
|
||||
drop_text: Zero the projected text, for the CFG uncond branch.
|
||||
cfg_infer: Run the cond and uncond branches as one batch of ``2B``,
|
||||
cond first. ``drop_audio_cond`` and ``drop_text`` are then
|
||||
driven per branch and ignored.
|
||||
cache: Reuse the projected text across calls, for an ODE loop over
|
||||
fixed conditioning. Only the ``cfg_infer`` path caches, as in
|
||||
the reference. Call :meth:`clear_cache` when the text changes.
|
||||
|
||||
Returns:
|
||||
Velocity ``[B, n, latent_dim]``, or ``[2B, n, latent_dim]`` under
|
||||
``cfg_infer``.
|
||||
"""
|
||||
batch = x.shape[0]
|
||||
if time.ndim == 0:
|
||||
time = time.repeat(batch)
|
||||
t = self.time_embed(time)
|
||||
|
||||
if c_mask is None:
|
||||
# Padding rows are all-zero in the text encoder's output.
|
||||
c_mask = text.abs().sum(-1) > 0
|
||||
|
||||
if cfg_infer:
|
||||
if cache and self.text_cond is not None:
|
||||
c_cond, c_uncond = self.text_cond, self.text_uncond
|
||||
else:
|
||||
c_cond = self.project_text(text)
|
||||
# The uncond branch drops the text, which is exactly a zeroed projection.
|
||||
c_uncond = torch.zeros_like(c_cond)
|
||||
if cache:
|
||||
self.text_cond, self.text_uncond = c_cond, c_uncond
|
||||
x_cond, mask_cond, prompt_len = self._embed_audio(x, ref, False, mask, ref_mask)
|
||||
x_uncond, mask_uncond, _ = self._embed_audio(x, ref, True, mask, ref_mask)
|
||||
|
||||
x = torch.cat((x_cond, x_uncond), dim=0)
|
||||
c = torch.cat((c_cond, c_uncond), dim=0)
|
||||
t = torch.cat((t, t), dim=0)
|
||||
c_mask = torch.cat((c_mask, c_mask), dim=0)
|
||||
audio_mask = None
|
||||
if mask_cond is not None and mask_uncond is not None:
|
||||
audio_mask = torch.cat((mask_cond, mask_uncond), dim=0)
|
||||
else:
|
||||
c = self.project_text(text)
|
||||
if drop_text:
|
||||
c = torch.zeros_like(c)
|
||||
x, audio_mask, prompt_len = self._embed_audio(x, ref, drop_audio_cond, mask, ref_mask)
|
||||
|
||||
seq_len = x.shape[1]
|
||||
text_len = c.shape[1]
|
||||
rope_audio = self.rotary_embed(seq_len)
|
||||
rope_text = self.rotary_embed(text_len)
|
||||
|
||||
for block in self.transformer_blocks:
|
||||
c, x = block(x, c, t, mask=audio_mask, rope=rope_audio, c_rope=rope_text, c_mask=c_mask)
|
||||
|
||||
x = torch.cat([c, x], dim=1)
|
||||
rope = self.rotary_embed(text_len + seq_len)
|
||||
single_mask = None if audio_mask is None else torch.cat([c_mask, audio_mask], dim=1)
|
||||
|
||||
for block in self.single_transformer_blocks:
|
||||
x = block(x, t, mask=single_mask, rope=rope)
|
||||
|
||||
x = x[:, text_len + prompt_len :]
|
||||
return self.proj_out(self.norm_out(x, t))
|
||||
|
||||
|
||||
def dit_state_dict(
|
||||
checkpoint: Mapping[str, torch.Tensor] | Iterable[tuple[str, torch.Tensor]],
|
||||
prefix: str = "transformer.",
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""Select the DiT tensors out of a full AuK checkpoint and strip ``prefix``.
|
||||
|
||||
Released checkpoints wrap the backbone under ``transformer.`` alongside the
|
||||
text-encoder layer-fusion parameters, which this module does not own.
|
||||
"""
|
||||
items = checkpoint.items() if isinstance(checkpoint, Mapping) else checkpoint
|
||||
return {name[len(prefix) :]: tensor for name, tensor in items if name.startswith(prefix)}
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def sample_latents(
|
||||
dit: AuKTransformer,
|
||||
*,
|
||||
text: torch.Tensor,
|
||||
c_mask: torch.Tensor | None,
|
||||
ref: torch.Tensor,
|
||||
ref_mask: torch.Tensor | None,
|
||||
gen_frames: int,
|
||||
nfe: int = 32,
|
||||
cfg_strength: float = 1.0,
|
||||
sway_sampling_coef: float | None = None,
|
||||
t_grid: list[float] | None = None,
|
||||
seed: int | None = None,
|
||||
generator: torch.Generator | None = None,
|
||||
latent_dim: int | None = None,
|
||||
device: torch.device | str | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Integrate the flow from noise to audio latents with explicit Euler steps.
|
||||
|
||||
Single-request only: the batch dimension carries the CFG branches, not
|
||||
separate prompts, so no target padding mask is needed.
|
||||
|
||||
Args:
|
||||
dit: The velocity model.
|
||||
text: Pre-encoded text hidden states ``[1, nt, text_hidden_dim]``.
|
||||
c_mask: Text padding mask ``[1, nt]``.
|
||||
ref: Reference prompt latents ``[1, np, latent_dim]``.
|
||||
ref_mask: Reference padding mask ``[1, np]``.
|
||||
gen_frames: Target latent frames to generate.
|
||||
nfe: Euler steps, ignored when ``t_grid`` is given.
|
||||
cfg_strength: Classifier-free guidance weight. Below ``1e-5`` the
|
||||
uncond branch is skipped entirely.
|
||||
sway_sampling_coef: Reshapes the uniform time grid towards ``t=0``.
|
||||
t_grid: Explicit timesteps, overriding ``nfe`` and the sway reshape.
|
||||
seed: Seeds the global RNG before drawing the noise. Ignored when
|
||||
``generator`` is given.
|
||||
generator: Draws the initial noise from its own RNG, leaving the global
|
||||
one untouched.
|
||||
latent_dim: Latent channels; defaults to the model's.
|
||||
device: Device for the noise; defaults to the reference's.
|
||||
dtype: Dtype for the noise and the Euler accumulator; defaults to the
|
||||
reference's, which is the reference implementation's rule. Pass
|
||||
``torch.float32`` explicitly when serving half-precision weights.
|
||||
Drawing the noise at bf16 instead of fp32 moves a 32-step CFG
|
||||
trajectory by 0.025 relative MSE, roughly 17 times what bf16
|
||||
weights themselves cost, because the draw consumes the generator
|
||||
differently and starts the ODE somewhere else. Keeping it fp32
|
||||
costs a few tens of KB and no measurable time.
|
||||
|
||||
Returns:
|
||||
The target latents at ``t=1``, ``[1, gen_frames, latent_dim]``.
|
||||
"""
|
||||
device = torch.device(device) if device is not None else ref.device
|
||||
dtype = dtype if dtype is not None else ref.dtype
|
||||
latent_dim = latent_dim if latent_dim is not None else dit.latent_dim
|
||||
|
||||
if generator is None:
|
||||
if seed is not None:
|
||||
torch.manual_seed(seed)
|
||||
x = torch.randn(gen_frames, latent_dim, device=device, dtype=dtype).unsqueeze(0)
|
||||
else:
|
||||
x = (
|
||||
torch.randn(gen_frames, latent_dim, generator=generator, device=generator.device, dtype=dtype)
|
||||
.to(device)
|
||||
.unsqueeze(0)
|
||||
)
|
||||
|
||||
if t_grid is not None:
|
||||
t = torch.tensor(t_grid, device=device, dtype=torch.float32)
|
||||
else:
|
||||
t = torch.linspace(0, 1, nfe + 1, device=device, dtype=torch.float32)
|
||||
if sway_sampling_coef is not None:
|
||||
t = t + sway_sampling_coef * (torch.cos(math.pi / 2 * t) - 1 + t)
|
||||
|
||||
guided = cfg_strength >= 1e-5
|
||||
if t.numel() < 2 or not bool(torch.all(t[1:] > t[:-1])):
|
||||
raise ValueError(
|
||||
f"AuK sampling needs a strictly increasing time grid with at least two points; got {t.tolist()}"
|
||||
)
|
||||
try:
|
||||
for i in range(t.shape[0] - 1):
|
||||
if guided:
|
||||
pred = dit(
|
||||
x,
|
||||
text,
|
||||
t[i],
|
||||
c_mask=c_mask,
|
||||
ref=ref,
|
||||
ref_mask=ref_mask,
|
||||
cfg_infer=True,
|
||||
cache=True,
|
||||
)
|
||||
v_cond, v_uncond = pred.chunk(2, dim=0)
|
||||
v = v_cond + (v_cond - v_uncond) * cfg_strength
|
||||
else:
|
||||
v = dit(x, text, t[i], c_mask=c_mask, ref=ref, ref_mask=ref_mask)
|
||||
x = x + (t[i + 1] - t[i]) * v
|
||||
finally:
|
||||
# The cached text projections belong to this request only; a failed
|
||||
# step must not leak them into the next one.
|
||||
dit.clear_cache()
|
||||
return x
|
||||
@@ -0,0 +1,505 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
#
|
||||
# Adapted from the AuK reference release (MIT), which in turn adapts NVIDIA
|
||||
# BigVGAN (MIT), jik876/hifi-gan (MIT), junjun3518/alias-free-torch
|
||||
# (Apache-2.0), EdwardDixon/snake (MIT) and adefossez/julius (MIT).
|
||||
"""BigVGAN-flow VAE for AuK: 24 kHz mono waveform <-> 50 Hz, 64-channel latents.
|
||||
|
||||
Inference only. The reference module also carries a residual coupling flow, a KL
|
||||
term and a discriminator; all three are training-only, so the released
|
||||
``flow.*`` tensors are skipped (see :meth:`AuKVAE.load_weights`).
|
||||
|
||||
Parameter and buffer names follow the reference release, so the published
|
||||
``vae.safetensors`` loads without a key map. That is also why the convolutions
|
||||
are built with the legacy ``weight_norm`` parametrization (``weight_g`` /
|
||||
``weight_v``): :meth:`remove_weight_norm` folds them into plain weights once
|
||||
the checkpoint is in.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import math
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from safetensors.torch import load_file
|
||||
from torch import nn
|
||||
from torch.nn.utils import remove_weight_norm as _fold_weight_norm
|
||||
from torch.nn.utils import weight_norm as _apply_weight_norm
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
__all__ = ["AuKVAE"]
|
||||
|
||||
# Checkpoint prefix owned by the training-only coupling flow.
|
||||
TRAINING_ONLY_PREFIX = "flow."
|
||||
|
||||
|
||||
def _weight_norm(module: nn.Module) -> nn.Module:
|
||||
"""Legacy ``weight_g``/``weight_v`` split, which is how the release stores these tensors."""
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", message=".*weight_norm.*deprecated.*", category=FutureWarning)
|
||||
return _apply_weight_norm(module)
|
||||
|
||||
|
||||
def _same_padding(kernel_size: int, dilation: int = 1) -> int:
|
||||
return int((kernel_size * dilation - dilation) / 2)
|
||||
|
||||
|
||||
def _kaiser_sinc_filter(cutoff: float, half_width: float, kernel_size: int) -> torch.Tensor:
|
||||
"""Kaiser-windowed sinc low-pass, returned as a ``[1, 1, kernel_size]`` conv kernel."""
|
||||
half_size = kernel_size // 2
|
||||
attenuation = 2.285 * (half_size - 1) * math.pi * (4 * half_width) + 7.95
|
||||
if attenuation > 50.0:
|
||||
beta = 0.1102 * (attenuation - 8.7)
|
||||
elif attenuation >= 21.0:
|
||||
beta = 0.5842 * (attenuation - 21.0) ** 0.4 + 0.07886 * (attenuation - 21.0)
|
||||
else:
|
||||
beta = 0.0
|
||||
window = torch.kaiser_window(kernel_size, beta=beta, periodic=False)
|
||||
if kernel_size % 2 == 0:
|
||||
time = torch.arange(-half_size, half_size) + 0.5
|
||||
else:
|
||||
time = torch.arange(kernel_size) - half_size
|
||||
if cutoff == 0:
|
||||
return torch.zeros_like(time).view(1, 1, kernel_size)
|
||||
taps = 2 * cutoff * window * torch.sinc(2 * cutoff * time)
|
||||
# Normalize to unit sum so a constant input passes through unscaled.
|
||||
return (taps / taps.sum()).view(1, 1, kernel_size)
|
||||
|
||||
|
||||
class Conv(nn.Conv1d):
|
||||
"""1-D convolution over ``[B, C, T]``; ``causal`` swaps centred padding for a left pad."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
in_channels: int,
|
||||
out_channels: int,
|
||||
kernel_size: int = 1,
|
||||
stride: int = 1,
|
||||
dilation: int = 1,
|
||||
bias: bool = True,
|
||||
causal: bool = False,
|
||||
) -> None:
|
||||
super().__init__(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=stride,
|
||||
padding=0 if causal else _same_padding(kernel_size, dilation),
|
||||
dilation=dilation,
|
||||
bias=bias,
|
||||
)
|
||||
self.causal = causal
|
||||
self.left_padding = dilation * (kernel_size - 1) if causal else 0
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
if self.causal:
|
||||
x = F.pad(x, (self.left_padding, 0))
|
||||
return super().forward(x)
|
||||
|
||||
|
||||
class ConvTranspose(nn.ConvTranspose1d):
|
||||
"""Transposed 1-D convolution; ``causal`` drops the trailing ``stride`` samples instead of padding."""
|
||||
|
||||
def __init__(
|
||||
self, in_channels: int, out_channels: int, kernel_size: int, stride: int, causal: bool = False
|
||||
) -> None:
|
||||
if causal and kernel_size != 2 * stride:
|
||||
raise ValueError(f"causal ConvTranspose needs kernel_size == 2 * stride, got {kernel_size} and {stride}")
|
||||
super().__init__(
|
||||
in_channels,
|
||||
out_channels,
|
||||
kernel_size,
|
||||
stride=stride,
|
||||
padding=0 if causal else (kernel_size - stride) // 2,
|
||||
)
|
||||
self.causal = causal
|
||||
self.trim = stride
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
x = super().forward(x)
|
||||
return x[:, :, : -self.trim] if self.causal else x
|
||||
|
||||
|
||||
class NormConv(nn.Module):
|
||||
"""Weight-normalized conv held under ``layer``; the attribute name is load-bearing for the checkpoint."""
|
||||
|
||||
def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 1, stride: int = 1) -> None:
|
||||
super().__init__()
|
||||
self.layer = _weight_norm(
|
||||
nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, padding=(kernel_size - 1) // 2)
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.layer(x)
|
||||
|
||||
|
||||
class ResStack(nn.Module):
|
||||
"""Stack of dilated residual conv pairs. The leaky slope is torch's 0.01 default, as upstream."""
|
||||
|
||||
def __init__(self, channels: int, kernel_size: int = 3, base: int = 3, nums: int = 4) -> None:
|
||||
super().__init__()
|
||||
self.layers = nn.ModuleList(
|
||||
[
|
||||
nn.Sequential(
|
||||
nn.LeakyReLU(),
|
||||
_weight_norm(nn.Conv1d(channels, channels, kernel_size, dilation=base**i, padding=base**i)),
|
||||
nn.LeakyReLU(),
|
||||
_weight_norm(nn.Conv1d(channels, channels, kernel_size, dilation=1, padding=1)),
|
||||
)
|
||||
for i in range(nums)
|
||||
]
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
for layer in self.layers:
|
||||
x = x + layer(x)
|
||||
return x
|
||||
|
||||
|
||||
class Encoder(nn.Module):
|
||||
"""Strided conv encoder over ``[B, 1, T]``, emitting ``[B, 2 * latent_dim, T / hop]`` mean/log-std pairs."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
latent_dim: int,
|
||||
channels: tuple[int, ...],
|
||||
down_sample_factors: tuple[int, ...],
|
||||
in_channels: int = 1,
|
||||
proj_kernel_size: int = 3,
|
||||
stack_kernel_size: int = 3,
|
||||
stack_dilation_base: int = 2,
|
||||
stacks: int = 6,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
layers: list[nn.Module] = [
|
||||
NormConv(in_channels, channels[0], kernel_size=proj_kernel_size),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
]
|
||||
for in_c, out_c, factor in zip(channels[:-1], channels[1:], down_sample_factors, strict=True):
|
||||
layers += [
|
||||
NormConv(in_c, out_c, kernel_size=factor * 2, stride=factor),
|
||||
ResStack(out_c, stack_kernel_size, stack_dilation_base, stacks),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
]
|
||||
layers.append(NormConv(channels[-1], latent_dim * 2, kernel_size=proj_kernel_size))
|
||||
self.generator = nn.Sequential(*layers)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.generator(x)
|
||||
|
||||
|
||||
class SnakeBeta(nn.Module):
|
||||
"""``x + sin^2(alpha * x) / beta`` with per-channel learned alpha and beta (log-scale in AuK)."""
|
||||
|
||||
def __init__(self, channels: int, alpha_logscale: bool = False) -> None:
|
||||
super().__init__()
|
||||
self.alpha_logscale = alpha_logscale
|
||||
init = torch.zeros(channels) if alpha_logscale else torch.ones(channels)
|
||||
self.alpha = nn.Parameter(init.clone())
|
||||
self.beta = nn.Parameter(init.clone())
|
||||
self.eps = 1e-9
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
alpha = self.alpha.unsqueeze(0).unsqueeze(-1)
|
||||
beta = self.beta.unsqueeze(0).unsqueeze(-1)
|
||||
if self.alpha_logscale:
|
||||
alpha = torch.exp(alpha)
|
||||
beta = torch.exp(beta)
|
||||
return x + (1.0 / (beta + self.eps)) * torch.sin(x * alpha).pow(2)
|
||||
|
||||
|
||||
class LowPass(nn.Module):
|
||||
"""Fixed FIR low-pass with replicate padding, applied per channel."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cutoff: float = 0.5,
|
||||
half_width: float = 0.6,
|
||||
stride: int = 1,
|
||||
kernel_size: int = 12,
|
||||
causal: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if not 0.0 <= cutoff <= 0.5:
|
||||
raise ValueError(f"cutoff must lie in [0, 0.5], got {cutoff}")
|
||||
if causal:
|
||||
self.pad_left, self.pad_right = kernel_size - 1, 0
|
||||
else:
|
||||
even = kernel_size % 2 == 0
|
||||
self.pad_left = kernel_size // 2 - int(even)
|
||||
self.pad_right = kernel_size // 2
|
||||
self.stride = stride
|
||||
self.register_buffer("filter", _kaiser_sinc_filter(cutoff, half_width, kernel_size))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
channels = x.size(1)
|
||||
x = F.pad(x, (self.pad_left, self.pad_right), mode="replicate")
|
||||
return F.conv1d(x, self.filter.expand(channels, -1, -1), stride=self.stride, groups=channels)
|
||||
|
||||
|
||||
class Upsample(nn.Module):
|
||||
"""Band-limited interpolation by ``ratio``. Always non-causal, matching how AuK builds it."""
|
||||
|
||||
def __init__(self, ratio: int = 2, kernel_size: int = 12) -> None:
|
||||
super().__init__()
|
||||
self.ratio = ratio
|
||||
self.pad = kernel_size // ratio - 1
|
||||
self.pad_left = self.pad * ratio + (kernel_size - ratio) // 2
|
||||
self.pad_right = self.pad * ratio + (kernel_size - ratio + 1) // 2
|
||||
self.register_buffer("filter", _kaiser_sinc_filter(0.5 / ratio, 0.6 / ratio, kernel_size))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
channels = x.size(1)
|
||||
x = F.pad(x, (self.pad, self.pad), mode="replicate")
|
||||
x = self.ratio * F.conv_transpose1d(x, self.filter.expand(channels, -1, -1), stride=self.ratio, groups=channels)
|
||||
return x[..., self.pad_left : -self.pad_right]
|
||||
|
||||
|
||||
class Downsample(nn.Module):
|
||||
"""Decimation by ``ratio`` behind a low-pass; ``lowpass`` holds the filter buffer."""
|
||||
|
||||
def __init__(self, ratio: int = 2, kernel_size: int = 12, causal: bool = False) -> None:
|
||||
super().__init__()
|
||||
self.lowpass = LowPass(
|
||||
cutoff=0.5 / ratio, half_width=0.6 / ratio, stride=ratio, kernel_size=kernel_size, causal=causal
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.lowpass(x)
|
||||
|
||||
|
||||
class AliasFreeActivation(nn.Module):
|
||||
"""Oversample, apply the pointwise activation, decimate, so snake harmonics do not fold back."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
activation: nn.Module,
|
||||
up_ratio: int = 2,
|
||||
down_ratio: int = 2,
|
||||
up_kernel_size: int = 12,
|
||||
down_kernel_size: int = 12,
|
||||
causal: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.act = activation
|
||||
self.upsample = Upsample(up_ratio, up_kernel_size)
|
||||
self.downsample = Downsample(down_ratio, down_kernel_size, causal=causal)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.downsample(self.act(self.upsample(x)))
|
||||
|
||||
|
||||
class AmpBlock(nn.Module):
|
||||
"""Anti-aliased multi-periodicity residual block: alternating alias-free snake and dilated convs."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
channels: int,
|
||||
kernel_size: int,
|
||||
dilations: tuple[int, ...],
|
||||
snake_logscale: bool = True,
|
||||
causal: bool = True,
|
||||
act_causal: bool = False,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.convs1 = nn.ModuleList(
|
||||
[_weight_norm(Conv(channels, channels, kernel_size, 1, dilation=d, causal=causal)) for d in dilations]
|
||||
)
|
||||
self.convs2 = nn.ModuleList(
|
||||
[_weight_norm(Conv(channels, channels, kernel_size, 1, dilation=1, causal=causal)) for _ in dilations]
|
||||
)
|
||||
self.activations = nn.ModuleList(
|
||||
[
|
||||
AliasFreeActivation(SnakeBeta(channels, alpha_logscale=snake_logscale), causal=act_causal)
|
||||
for _ in range(len(self.convs1) + len(self.convs2))
|
||||
]
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
acts1, acts2 = self.activations[::2], self.activations[1::2]
|
||||
for conv1, conv2, act1, act2 in zip(self.convs1, self.convs2, acts1, acts2, strict=True):
|
||||
x = conv2(act2(conv1(act1(x)))) + x
|
||||
return x
|
||||
|
||||
|
||||
class AuKVAE(nn.Module):
|
||||
"""AuK's audio codec: :meth:`encode` waveform to normalized latents, :meth:`decode` back.
|
||||
|
||||
Build from the released ``model.vae.model_init_kwargs`` with :meth:`from_config`, then
|
||||
:meth:`load_weights`. Latents are normalized by the checkpoint's global statistics, which is
|
||||
the space the rectified-flow transformer works in.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
upsample_rates: tuple[int, ...] = (5, 4, 3, 2, 2, 2),
|
||||
upsample_kernel_sizes: tuple[int, ...] = (10, 8, 6, 4, 4, 4),
|
||||
upsample_initial_channel: int = 1536,
|
||||
resblock_kernel_sizes: tuple[int, ...] = (3, 7, 11),
|
||||
resblock_dilation_sizes: tuple[tuple[int, ...], ...] = ((1, 3, 5), (1, 3, 5), (1, 3, 5)),
|
||||
downsample_rates: tuple[int, ...] = (2, 2, 2, 3, 4, 5),
|
||||
downsample_channels: tuple[int, ...] = (12, 24, 48, 96, 192, 384, 768),
|
||||
snake_logscale: bool = True,
|
||||
latent_dim: int = 64,
|
||||
use_vae: bool = True,
|
||||
causal: bool = True,
|
||||
act_causal: bool = True,
|
||||
sample_rate: int = 24000,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
if not use_vae:
|
||||
raise ValueError("AuKVAE requires use_vae=True: the encoder head emits mean/log-std pairs")
|
||||
self.latent_dim = latent_dim
|
||||
self.sample_rate = sample_rate
|
||||
self.hop_size = math.prod(downsample_rates)
|
||||
self.num_kernels = len(resblock_kernel_sizes)
|
||||
self.num_upsamples = len(upsample_rates)
|
||||
self._norm_folded = False
|
||||
|
||||
self.register_buffer("global_mean", torch.zeros(latent_dim, dtype=torch.float32))
|
||||
self.register_buffer("global_log_std", torch.ones(latent_dim, dtype=torch.float32))
|
||||
|
||||
self.audio_encoder = Encoder(
|
||||
latent_dim=latent_dim,
|
||||
channels=tuple(downsample_channels),
|
||||
down_sample_factors=tuple(downsample_rates),
|
||||
)
|
||||
|
||||
self.conv_pre = _weight_norm(Conv(latent_dim, upsample_initial_channel, 7, 1, causal=False))
|
||||
self.ups = nn.ModuleList()
|
||||
for i, (rate, kernel) in enumerate(zip(upsample_rates, upsample_kernel_sizes, strict=True)):
|
||||
# One-element inner list: the checkpoint keys are ``ups.<i>.0.*``.
|
||||
self.ups.append(
|
||||
nn.ModuleList(
|
||||
[
|
||||
_weight_norm(
|
||||
ConvTranspose(
|
||||
upsample_initial_channel // (2**i),
|
||||
upsample_initial_channel // (2 ** (i + 1)),
|
||||
kernel,
|
||||
rate,
|
||||
causal=causal,
|
||||
)
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
self.resblocks = nn.ModuleList()
|
||||
channels = upsample_initial_channel
|
||||
for i in range(self.num_upsamples):
|
||||
channels = upsample_initial_channel // (2 ** (i + 1))
|
||||
for kernel, dilations in zip(resblock_kernel_sizes, resblock_dilation_sizes, strict=True):
|
||||
self.resblocks.append(
|
||||
AmpBlock(
|
||||
channels,
|
||||
kernel,
|
||||
tuple(dilations),
|
||||
snake_logscale=snake_logscale,
|
||||
causal=causal,
|
||||
act_causal=act_causal,
|
||||
)
|
||||
)
|
||||
|
||||
self.activation_post = AliasFreeActivation(
|
||||
SnakeBeta(channels, alpha_logscale=snake_logscale), causal=act_causal
|
||||
)
|
||||
self.conv_post = _weight_norm(Conv(channels, 1, 7, 1, causal=causal, bias=False))
|
||||
|
||||
@classmethod
|
||||
def from_config(cls, cfg: dict) -> AuKVAE:
|
||||
"""Build from the released ``model_init_kwargs`` mapping, ignoring training-only entries."""
|
||||
accepted = set(inspect.signature(cls.__init__).parameters) - {"self"}
|
||||
return cls(**{key: value for key, value in cfg.items() if key in accepted})
|
||||
|
||||
def load_weights(
|
||||
self, path: str | Path, *, device: str | torch.device | None = None, fold_weight_norm: bool = True
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Load a released ``vae.safetensors``, then fold weight norm away. Returns (missing, unexpected).
|
||||
|
||||
``device`` defaults to where the module already lives, which is the placement that matters:
|
||||
the fold reduces ``weight_v`` to a norm, and a CPU reduction lands up to one ULP away from the
|
||||
accelerator's. The encoder amplifies its activations roughly fiftyfold, so that one ULP grows
|
||||
into a ~4e-4 relative drift by the latent head. Move the module first, then load.
|
||||
"""
|
||||
target = self.global_mean.device if device is None else torch.device(device)
|
||||
missing, unexpected = self.load_state_dict(load_file(str(path), device=str(target)), strict=False)
|
||||
missing, unexpected = list(missing), list(unexpected)
|
||||
stray = [key for key in missing + unexpected if not key.startswith(TRAINING_ONLY_PREFIX)]
|
||||
if stray:
|
||||
raise ValueError(f"AuK VAE weights at {path} do not match this module: {sorted(stray)[:8]}")
|
||||
logger.info(
|
||||
"Loaded AuK VAE from %s (skipped %d training-only %s* tensors)", path, len(unexpected), TRAINING_ONLY_PREFIX
|
||||
)
|
||||
if fold_weight_norm:
|
||||
self.remove_weight_norm()
|
||||
return missing, unexpected
|
||||
|
||||
def remove_weight_norm(self) -> None:
|
||||
"""Fold ``weight_g``/``weight_v`` into plain weights, on whichever device the module is on.
|
||||
|
||||
Idempotent, and meant to run once the checkpoint is in. See :meth:`load_weights` for why the
|
||||
device this runs on is a numeric decision rather than a convenience.
|
||||
"""
|
||||
if self._norm_folded:
|
||||
return
|
||||
folded = 0
|
||||
for module in self.modules():
|
||||
if hasattr(module, "weight_g"):
|
||||
_fold_weight_norm(module)
|
||||
folded += 1
|
||||
self._norm_folded = True
|
||||
logger.debug("Folded weight norm on %d AuK VAE convolutions", folded)
|
||||
|
||||
def encode(
|
||||
self, wav: torch.Tensor, *, sample: bool = False, generator: torch.Generator | None = None
|
||||
) -> torch.Tensor:
|
||||
"""Encode a mono ``[1, T]`` waveform at :attr:`sample_rate` into ``[1, T / hop_size, latent_dim]``.
|
||||
|
||||
``sample=False`` takes the posterior mean, which is what a reproducible pipeline wants;
|
||||
``sample=True`` draws ``mean + randn * exp(log_std)`` from ``generator``. Latents come back
|
||||
normalized by the checkpoint's global statistics.
|
||||
"""
|
||||
if wav.dim() != 2 or wav.size(0) != 1:
|
||||
raise ValueError(f"encode expects a mono [1, T] waveform, got {tuple(wav.shape)}")
|
||||
# Statistics stay in fp32 even under an ambient autocast, as in the reference.
|
||||
with torch.autocast(device_type=wav.device.type, enabled=False):
|
||||
mean, log_std = self.audio_encoder(wav.unsqueeze(1)).chunk(2, dim=1)
|
||||
if sample:
|
||||
latents = mean + self._noise_like(mean, generator) * torch.exp(log_std)
|
||||
else:
|
||||
latents = mean
|
||||
latents = latents.transpose(1, 2).float()
|
||||
return (latents - self.global_mean.float()) / torch.sqrt(self.global_log_std.float())
|
||||
|
||||
def decode(self, latents: torch.Tensor) -> torch.Tensor:
|
||||
"""Decode normalized ``[B, Np, latent_dim]`` latents into a ``[B, Np * hop_size]`` waveform in [-1, 1]."""
|
||||
if latents.dim() != 3 or latents.size(-1) != self.latent_dim:
|
||||
raise ValueError(f"decode expects [B, Np, {self.latent_dim}] latents, got {tuple(latents.shape)}")
|
||||
x = latents.float() * torch.sqrt(self.global_log_std.float()) + self.global_mean.float()
|
||||
x = self.conv_pre(x.permute(0, 2, 1))
|
||||
for i in range(self.num_upsamples):
|
||||
for up in self.ups[i]:
|
||||
x = up(x)
|
||||
first = i * self.num_kernels
|
||||
residual = self.resblocks[first](x)
|
||||
for j in range(1, self.num_kernels):
|
||||
residual = residual + self.resblocks[first + j](x)
|
||||
x = residual / self.num_kernels
|
||||
x = self.conv_post(self.activation_post(x))
|
||||
return torch.clamp(x, min=-1.0, max=1.0).squeeze(1)
|
||||
|
||||
@staticmethod
|
||||
def _noise_like(reference: torch.Tensor, generator: torch.Generator | None) -> torch.Tensor:
|
||||
"""Draw standard normal noise shaped like ``reference``; ``generator`` decides which RNG stream."""
|
||||
device = reference.device if generator is None else generator.device
|
||||
noise = torch.randn(reference.shape, generator=generator, dtype=reference.dtype, device=device)
|
||||
return noise.to(reference.device)
|
||||
@@ -0,0 +1,486 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""AuK audio-editing pipeline for vLLM-Omni.
|
||||
|
||||
Turns a layer-fused text condition (produced by the encoder stage) plus an
|
||||
optional source clip into a 24 kHz waveform: the source clip is encoded to VAE
|
||||
latents, a rectified-flow DiT integrates the target latents conditioned on
|
||||
both, and the BigVGAN-flow decoder renders the waveform.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Iterable
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torchaudio
|
||||
from safetensors import safe_open
|
||||
from torch import nn
|
||||
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.auk.auk_transformer import AuKTransformer, dit_state_dict, sample_latents
|
||||
from vllm_omni.diffusion.models.auk.auk_vae import AuKVAE
|
||||
from vllm_omni.diffusion.models.interface import (
|
||||
SupportAudioInput,
|
||||
SupportAudioOutput,
|
||||
SupportsComponentDiscovery,
|
||||
)
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch
|
||||
from vllm_omni.model_extras.auk import resolve_gen_frames
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# Longest ref + target latent sequence the released checkpoints accept.
|
||||
MAX_LATENT_FRAMES = 65536
|
||||
|
||||
# Weight-file layout: the DiT lives under this prefix; the layer-fusion
|
||||
# parameters sit next to it but belong to the encoder stage.
|
||||
_DIT_PREFIX = "transformer."
|
||||
_FUSION_KEYS = frozenset({"layer_weights", "layer_scale"})
|
||||
|
||||
# The distilled variant only reproduces its training recipe at these settings.
|
||||
_FLASH_NFE = 4
|
||||
_FLASH_CFG = 0.0
|
||||
# Decorrelates the VAE posterior draw from the initial latent for the same request seed.
|
||||
_VAE_SEED_OFFSET = 0x5EED_0A0C
|
||||
|
||||
|
||||
def get_auk_post_process_func(od_config: OmniDiffusionConfig):
|
||||
"""Create the post-processing function for AuK audio output.
|
||||
|
||||
Tensor output types pass through; anything else becomes a numpy waveform.
|
||||
The sample rate is not attached here: the output formatter reads
|
||||
``AuKPipeline.audio_sample_rate`` for audio-output pipelines.
|
||||
"""
|
||||
|
||||
del od_config # The conversion does not depend on the config.
|
||||
|
||||
def post_process_func(
|
||||
audio: torch.Tensor,
|
||||
output_type: str = "np",
|
||||
):
|
||||
if output_type in ("pt", "latent"):
|
||||
return audio
|
||||
return audio.cpu().float().numpy()
|
||||
|
||||
return post_process_func
|
||||
|
||||
|
||||
def _prompt_mapping(prompt: Any) -> dict[str, Any]:
|
||||
"""Return the prompt dict, or an empty mapping for a bare text prompt."""
|
||||
|
||||
if isinstance(prompt, dict):
|
||||
return prompt
|
||||
return {}
|
||||
|
||||
|
||||
def _unwrap_single(value: Any) -> Any:
|
||||
"""Unwrap the one-element lists the serving layer sometimes produces."""
|
||||
|
||||
if isinstance(value, list) and len(value) == 1:
|
||||
return value[0]
|
||||
return value
|
||||
|
||||
|
||||
def _split_audio(audio: Any, default_sample_rate: int) -> tuple[Any, int]:
|
||||
"""Split a multimodal audio item into raw samples and a sample rate."""
|
||||
|
||||
if isinstance(audio, (tuple, list)) and len(audio) == 2 and isinstance(audio[1], (int, float)):
|
||||
return audio[0], int(audio[1])
|
||||
return audio, default_sample_rate
|
||||
|
||||
|
||||
class AuKPipeline(nn.Module, SupportAudioInput, SupportAudioOutput, SupportsComponentDiscovery):
|
||||
"""Instruction-driven audio generation and editing with AuK.
|
||||
|
||||
One request per forward: the rectified-flow ODE runs over the whole target
|
||||
span and the batch dimension carries the CFG branches, so there is nothing
|
||||
to share between requests yet.
|
||||
|
||||
Args:
|
||||
od_config: OmniDiffusion configuration. ``od_config.model`` must be an
|
||||
assembled AuK directory (``config.json``, ``auk.safetensors``,
|
||||
``vae.safetensors``), as produced by
|
||||
``tools/prepare_auk_checkpoint.py``.
|
||||
prefix: Unused; kept for the pipeline construction contract.
|
||||
"""
|
||||
|
||||
supports_request_batch = False
|
||||
|
||||
# Picked up by ``supports_audio_output`` in the diffusion engine so the
|
||||
# default stage metadata reports ``final_output_type="audio"`` and the
|
||||
# ``multimodal_output`` payload includes the sample rate.
|
||||
support_audio_output: ClassVar[bool] = True
|
||||
support_audio_input: ClassVar[bool] = True
|
||||
audio_sample_rate: ClassVar[int] = 24000
|
||||
|
||||
# The DiT cannot run without an encoder-stage text condition, which the
|
||||
# engine's synthetic warmup request has no way to produce.
|
||||
dummy_run_num_frames: ClassVar[int] = 0
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = ["dit"]
|
||||
_encoder_modules: ClassVar[list[str]] = []
|
||||
_vae_modules: ClassVar[list[str]] = ["vae"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
od_config: OmniDiffusionConfig,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
del prefix # Weights are not namespaced: one checkpoint, one pipeline.
|
||||
self.od_config = od_config
|
||||
self.device = get_local_device()
|
||||
self.dtype = getattr(od_config, "dtype", None) or torch.bfloat16
|
||||
|
||||
model_dir = od_config.model
|
||||
if not model_dir or not os.path.isdir(model_dir):
|
||||
raise ValueError(
|
||||
f"AuK needs an assembled local checkpoint directory, got {model_dir!r}. "
|
||||
"Build one with tools/prepare_auk_checkpoint.py."
|
||||
)
|
||||
config = _read_config(model_dir)
|
||||
|
||||
vae_config = dict(config["vae"])
|
||||
self.latent_dim = int(vae_config["latent_dim"])
|
||||
self.hop_size = int(vae_config["downsample_rate"])
|
||||
self.sample_rate = int(vae_config["target_sample_rate"])
|
||||
|
||||
self.variant = str(config.get("variant", "base"))
|
||||
self.is_flash = self.variant == "flash"
|
||||
self.flash_t_grid = [float(t) for t in config.get("flash_t_grid") or ()]
|
||||
if self.is_flash and len(self.flash_t_grid) != _FLASH_NFE + 1:
|
||||
raise ValueError(f"The flash variant needs a {_FLASH_NFE + 1}-point flash_t_grid, got {self.flash_t_grid}.")
|
||||
defaults = dict(config.get("defaults") or {})
|
||||
self.default_nfe = int(defaults.get("nfe", 32))
|
||||
self.default_cfg = float(defaults.get("cfg", 2.0))
|
||||
self.default_sway = defaults.get("sway", -1.0)
|
||||
self._flash_lock_logged = False
|
||||
|
||||
# The codec is small and numerically sensitive: it stays in fp32. It
|
||||
# must sit on the inference device BEFORE load_weights folds weight
|
||||
# norm: a CPU fold lands one ULP off the accelerator's and the encoder
|
||||
# amplifies that into a 1e-2 latent drift.
|
||||
self.vae = AuKVAE.from_config(vae_config["model_init_kwargs"]).to(device=self.device, dtype=torch.float32)
|
||||
self.vae.load_weights(os.path.join(model_dir, "vae.safetensors"))
|
||||
self.vae = self.vae.eval()
|
||||
self.vae.requires_grad_(False)
|
||||
self._check_vae_geometry()
|
||||
|
||||
# The transformer owns every key the checkpoint tool writes into `dit`,
|
||||
# `attn_mask_enabled` included, so the section passes straight through.
|
||||
self.dit = AuKTransformer(latent_dim=self.latent_dim, **config["dit"])
|
||||
self.dit = self.dit.to(dtype=self.dtype)
|
||||
self.dit.load_state_dict(_read_dit_weights(model_dir, self.dtype), strict=True)
|
||||
self.dit = self.dit.to(device=self.device).eval()
|
||||
self.dit.requires_grad_(False)
|
||||
|
||||
logger.info(
|
||||
"AuK pipeline ready: variant=%s dtype=%s latent_dim=%d hop=%d sample_rate=%d",
|
||||
self.variant,
|
||||
self.dtype,
|
||||
self.latent_dim,
|
||||
self.hop_size,
|
||||
self.sample_rate,
|
||||
)
|
||||
|
||||
# The assembled checkpoint is not a diffusers layout: __init__ reads
|
||||
# auk.safetensors and vae.safetensors directly, so the loader has no
|
||||
# component sources to stream and load_weights only reports what is loaded.
|
||||
weights_sources: ClassVar[tuple] = ()
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
stray = [name for name, _ in weights]
|
||||
if stray:
|
||||
logger.warning("AuKPipeline ignores %d loader-provided weights (e.g. %s)", len(stray), stray[:3])
|
||||
return {name for name, _ in self.named_parameters()}
|
||||
|
||||
def _check_vae_geometry(self) -> None:
|
||||
"""Fail fast when config.json and the VAE disagree on latent geometry."""
|
||||
|
||||
declared = {
|
||||
"latent_dim": (self.latent_dim, int(self.vae.latent_dim)),
|
||||
"downsample_rate": (self.hop_size, int(self.vae.hop_size)),
|
||||
"target_sample_rate": (self.sample_rate, int(self.vae.sample_rate)),
|
||||
}
|
||||
bad = {name: pair for name, pair in declared.items() if pair[0] != pair[1]}
|
||||
if bad:
|
||||
raise ValueError(f"config.json and the AuK VAE disagree (config, vae): {bad}")
|
||||
if self.sample_rate != self.audio_sample_rate:
|
||||
raise ValueError(
|
||||
f"AuK advertises {self.audio_sample_rate} Hz output but the checkpoint is {self.sample_rate} Hz."
|
||||
)
|
||||
|
||||
def _resolve_generator(self, sampling_params: Any) -> torch.Generator | None:
|
||||
"""Per-request generator; the process-global RNG is never seeded."""
|
||||
|
||||
generator = sampling_params.generator
|
||||
if isinstance(generator, list):
|
||||
if len(generator) > 1:
|
||||
logger.warning(
|
||||
"AuKPipeline runs one request per forward; using the first of %d generators", len(generator)
|
||||
)
|
||||
generator = generator[0] if generator else None
|
||||
if generator is None and sampling_params.seed is not None:
|
||||
generator = torch.Generator(device=self.device).manual_seed(int(sampling_params.seed))
|
||||
return generator
|
||||
|
||||
def _prepare_waveform(self, audio: Any) -> torch.Tensor:
|
||||
"""Return mono float32 samples ``[1, T]`` at the VAE sample rate.
|
||||
|
||||
``T`` is truncated to a whole number of latent frames. The encoder is
|
||||
causal, so dropping a trailing partial frame leaves every emitted frame
|
||||
unchanged.
|
||||
"""
|
||||
|
||||
data, sample_rate = _split_audio(audio, self.sample_rate)
|
||||
if isinstance(data, np.ndarray):
|
||||
wav = torch.from_numpy(np.ascontiguousarray(data))
|
||||
else:
|
||||
wav = torch.as_tensor(data)
|
||||
wav = wav.detach().to(device="cpu", dtype=torch.float32)
|
||||
|
||||
if wav.ndim == 1:
|
||||
wav = wav.unsqueeze(0)
|
||||
elif wav.ndim == 2:
|
||||
# Accept both [channels, samples] and soundfile's [samples, channels];
|
||||
# the channel axis is the short one (at most 8 wide).
|
||||
if wav.shape[0] > wav.shape[1] and wav.shape[1] <= 8:
|
||||
wav = wav.transpose(0, 1)
|
||||
if wav.shape[0] > 1:
|
||||
wav = wav.mean(dim=0, keepdim=True)
|
||||
else:
|
||||
raise ValueError(f"AuK audio input must be [samples] or [channels, samples], got {tuple(wav.shape)}.")
|
||||
|
||||
if wav.shape[-1] == 0:
|
||||
raise ValueError("AuK audio input is empty.")
|
||||
if not torch.isfinite(wav).all():
|
||||
raise ValueError("AuK audio input contains NaN or Inf.")
|
||||
|
||||
if sample_rate != self.sample_rate:
|
||||
wav = torchaudio.functional.resample(wav, sample_rate, self.sample_rate)
|
||||
|
||||
frames = wav.shape[-1] // self.hop_size
|
||||
if frames < 1:
|
||||
raise ValueError(
|
||||
f"AuK audio input is shorter than one latent frame ({self.hop_size} samples at {self.sample_rate} Hz)."
|
||||
)
|
||||
return wav[..., : frames * self.hop_size]
|
||||
|
||||
def _encode_source(
|
||||
self,
|
||||
audio: Any,
|
||||
*,
|
||||
sample: bool,
|
||||
generator: torch.Generator | None,
|
||||
) -> torch.Tensor:
|
||||
"""Encode the source clip to normalized latents ``[1, np, latent_dim]``."""
|
||||
|
||||
if audio is None:
|
||||
return torch.zeros(1, 0, self.latent_dim, device=self.device, dtype=torch.float32)
|
||||
wav = self._prepare_waveform(_unwrap_single(audio)).to(self.device)
|
||||
return self.vae.encode(wav, sample=sample, generator=generator)
|
||||
|
||||
def _target_frames(self, gen_seconds: Any, ref_frames: int) -> int:
|
||||
"""Target latent length, capped by the remaining context."""
|
||||
|
||||
frames = resolve_gen_frames(
|
||||
None if gen_seconds is None else float(gen_seconds),
|
||||
ref_frames,
|
||||
sample_rate=self.sample_rate,
|
||||
hop=self.hop_size,
|
||||
)
|
||||
budget = MAX_LATENT_FRAMES - ref_frames
|
||||
if budget < 1:
|
||||
raise ValueError(
|
||||
f"The source clip already fills the {MAX_LATENT_FRAMES}-frame context ({ref_frames} frames)."
|
||||
)
|
||||
if frames > budget:
|
||||
logger.warning("AuK target of %d frames exceeds the remaining context; clamping to %d.", frames, budget)
|
||||
frames = budget
|
||||
return frames
|
||||
|
||||
def _resolve_schedule(
|
||||
self,
|
||||
sampling_params: Any,
|
||||
knobs: dict[str, Any],
|
||||
) -> tuple[int, float, float | None, list[float] | None]:
|
||||
"""Resolve (nfe, cfg, sway, t_grid), locking the distilled recipe on Flash.
|
||||
|
||||
A knob present but ``None`` counts as unspecified: the stage input
|
||||
processor fills every key it knows about, whether the caller set it or
|
||||
not.
|
||||
"""
|
||||
|
||||
steps = sampling_params.num_inference_steps
|
||||
nfe = self.default_nfe if steps is None else int(steps)
|
||||
if nfe < 1:
|
||||
raise ValueError(f"num_inference_steps must be >= 1 for AuK; got {steps}")
|
||||
cfg = float(sampling_params.guidance_scale) if sampling_params.guidance_scale_provided else self.default_cfg
|
||||
sway = knobs.get("sway")
|
||||
sway = self.default_sway if sway is None else float(sway)
|
||||
raw_grid = knobs.get("t_grid")
|
||||
t_grid = [float(t) for t in raw_grid] if raw_grid else None
|
||||
|
||||
if not self.is_flash:
|
||||
return nfe, cfg, sway, t_grid
|
||||
|
||||
locked = (_FLASH_NFE, _FLASH_CFG, None, self.flash_t_grid)
|
||||
if (nfe, cfg, sway, t_grid) != locked and not self._flash_lock_logged:
|
||||
self._flash_lock_logged = True
|
||||
logger.warning(
|
||||
"AuK-Flash ignores per-request sampling knobs (asked nfe=%s cfg=%s sway=%s t_grid=%s); "
|
||||
"using the distilled recipe nfe=%d cfg=%s with the checkpoint time grid.",
|
||||
nfe,
|
||||
cfg,
|
||||
sway,
|
||||
t_grid,
|
||||
_FLASH_NFE,
|
||||
_FLASH_CFG,
|
||||
)
|
||||
return locked
|
||||
|
||||
def _dit_autocast(self):
|
||||
"""Match the reference, which runs the DiT under bf16 autocast."""
|
||||
|
||||
return torch.autocast(
|
||||
device_type=self.device.type,
|
||||
dtype=self.dtype,
|
||||
enabled=self.dtype in (torch.bfloat16, torch.float16),
|
||||
)
|
||||
|
||||
def forward(self, req: DiffusionRequestBatch) -> list[DiffusionOutput]:
|
||||
"""Generate one waveform.
|
||||
|
||||
Args:
|
||||
req: Request batch holding exactly one request. The prompt carries
|
||||
``prompt_embeds`` (the fused text condition ``[nt, 2048]``), an
|
||||
optional ``multi_modal_data["audio"]`` source clip, and
|
||||
``additional_information["auk"]`` with ``gen_seconds``,
|
||||
``sway``, ``t_grid`` and ``vae_sample``. ``num_inference_steps``,
|
||||
``guidance_scale`` and ``seed``/``generator`` come from the
|
||||
sampling params.
|
||||
|
||||
Returns:
|
||||
One ``DiffusionOutput`` whose ``output`` is a float32 mono waveform
|
||||
``[T]`` at 24 kHz, or the normalized target latents
|
||||
``[1, gen_frames, latent_dim]`` when ``output_type`` is ``latent``.
|
||||
"""
|
||||
|
||||
assert req.num_reqs == 1, f"AuKPipeline runs one request per forward, got {req.num_reqs}."
|
||||
prompt = _prompt_mapping(req.prompts[0])
|
||||
sampling_params = req.sampling_params
|
||||
knobs = dict((prompt.get("additional_information") or {}).get("auk") or {})
|
||||
|
||||
text = _unwrap_single(prompt.get("prompt_embeds"))
|
||||
if text is None:
|
||||
raise ValueError("AuK stage 1 needs `prompt_embeds`, the fused text condition from the encoder stage.")
|
||||
text = torch.as_tensor(text).to(device=self.device, dtype=self.dtype)
|
||||
if text.ndim == 3 and text.shape[0] == 1:
|
||||
text = text[0]
|
||||
if text.ndim != 2:
|
||||
raise ValueError(f"AuK `prompt_embeds` must be [nt, text_hidden_dim], got {tuple(text.shape)}.")
|
||||
text = text.unsqueeze(0)
|
||||
c_mask = torch.ones(text.shape[:2], dtype=torch.bool, device=self.device)
|
||||
|
||||
generator = self._resolve_generator(sampling_params)
|
||||
audio = (prompt.get("multi_modal_data") or {}).get("audio")
|
||||
output_type = sampling_params.output_type or "np"
|
||||
|
||||
with torch.inference_mode():
|
||||
# The VAE posterior draw gets its own generator, seeded with a
|
||||
# fixed offset from the request seed: the initial latent below then
|
||||
# still equals the reference's fresh manual_seed draw, and the two
|
||||
# noise streams are not copies of each other.
|
||||
vae_generator = None
|
||||
if knobs.get("vae_sample") and generator is not None:
|
||||
vae_seed = (int(generator.initial_seed()) + _VAE_SEED_OFFSET) % (2**63)
|
||||
vae_generator = torch.Generator(device=self.device).manual_seed(vae_seed)
|
||||
ref = self._encode_source(audio, sample=bool(knobs.get("vae_sample")), generator=vae_generator)
|
||||
ref_frames = ref.shape[1]
|
||||
ref_mask = torch.ones(ref.shape[:2], dtype=torch.bool, device=self.device)
|
||||
gen_frames = self._target_frames(knobs.get("gen_seconds"), ref_frames)
|
||||
nfe, cfg, sway, t_grid = self._resolve_schedule(sampling_params, knobs)
|
||||
|
||||
with self._dit_autocast():
|
||||
latents = sample_latents(
|
||||
self.dit,
|
||||
text=text,
|
||||
c_mask=c_mask,
|
||||
ref=ref,
|
||||
ref_mask=ref_mask,
|
||||
gen_frames=gen_frames,
|
||||
nfe=nfe,
|
||||
cfg_strength=cfg,
|
||||
sway_sampling_coef=sway,
|
||||
t_grid=t_grid,
|
||||
seed=None,
|
||||
latent_dim=self.latent_dim,
|
||||
device=self.device,
|
||||
dtype=torch.float32,
|
||||
generator=generator,
|
||||
)
|
||||
|
||||
latents = latents.float()
|
||||
if not torch.isfinite(latents).all():
|
||||
raise RuntimeError("AuK generated latents contain NaN or Inf.")
|
||||
if output_type == "latent":
|
||||
return [DiffusionOutput(output=latents.detach().cpu())]
|
||||
|
||||
wav = self.vae.decode(latents)
|
||||
|
||||
# One mono waveform per request; the formatter expects [T].
|
||||
wav = wav.detach().to(device="cpu", dtype=torch.float32).reshape(-1)
|
||||
if not torch.isfinite(wav).all():
|
||||
raise RuntimeError("AuK generated audio contains NaN or Inf.")
|
||||
return [DiffusionOutput(output=wav)]
|
||||
|
||||
|
||||
def _read_config(model_dir: str) -> dict[str, Any]:
|
||||
"""Read the assembled AuK ``config.json``."""
|
||||
|
||||
path = os.path.join(model_dir, "config.json")
|
||||
try:
|
||||
with open(path) as handle:
|
||||
config = json.load(handle)
|
||||
except FileNotFoundError as exc:
|
||||
raise ValueError(f"AuK checkpoint is missing config.json: {path}") from exc
|
||||
except json.JSONDecodeError as exc:
|
||||
logger.error("AuK config.json is not valid JSON: %s", path)
|
||||
raise ValueError(f"AuK config.json is not valid JSON: {path}") from exc
|
||||
|
||||
missing = [key for key in ("dit", "vae") if key not in config]
|
||||
if missing:
|
||||
raise ValueError(f"AuK config.json is missing required sections {missing}: {path}")
|
||||
return config
|
||||
|
||||
|
||||
def _read_dit_weights(model_dir: str, dtype: torch.dtype) -> dict[str, torch.Tensor]:
|
||||
"""Read the DiT state dict from ``auk.safetensors``, cast to ``dtype``.
|
||||
|
||||
Tensors are cast one at a time so the fp32 checkpoint is never fully
|
||||
resident alongside the model.
|
||||
"""
|
||||
|
||||
path = os.path.join(model_dir, "auk.safetensors")
|
||||
if not os.path.isfile(path):
|
||||
raise ValueError(f"AuK checkpoint is missing auk.safetensors: {path}")
|
||||
|
||||
with safe_open(path, framework="pt", device="cpu") as checkpoint:
|
||||
keys = list(checkpoint.keys())
|
||||
state = dit_state_dict(((key, checkpoint.get_tensor(key).to(dtype)) for key in keys), _DIT_PREFIX)
|
||||
|
||||
if not state:
|
||||
raise ValueError(f"AuK checkpoint has no '{_DIT_PREFIX}*' weights: {path}")
|
||||
unexpected = sorted(key for key in keys if key not in _FUSION_KEYS and not key.startswith(_DIT_PREFIX))
|
||||
if unexpected:
|
||||
logger.warning("Ignoring %d unrecognized keys in %s, e.g. %s", len(unexpected), path, unexpected[:5])
|
||||
return state
|
||||
@@ -1,6 +1,7 @@
|
||||
# Copyright 2025 Bytedance Ltd. and/or its affiliates.
|
||||
# Copyright (c) 2024 The Qwen Team and The HuggingFace Inc. team.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
#
|
||||
# This file has been modified by ByteDance Ltd. and/or its affiliates.
|
||||
#
|
||||
@@ -48,10 +49,10 @@ from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_sp_group,
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
from vllm_omni.diffusion.layers.mot.mot_layernorm import MoTRMSNorm
|
||||
from vllm_omni.diffusion.layers.mot.mot_qkv_parallel_linear import MoTQKVParallelLinear
|
||||
from vllm_omni.diffusion.layers.mot.mot_row_parallel_linear import MoTRowParallelLinear
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
from vllm_omni.diffusion.models.bagel.mot.mot_layernorm import MoTRMSNorm
|
||||
from vllm_omni.diffusion.models.bagel.mot.mot_qkv_parallel_linear import MoTQKVParallelLinear
|
||||
from vllm_omni.diffusion.models.bagel.mot.mot_row_parallel_linear import MoTRowParallelLinear
|
||||
from vllm_omni.diffusion.utils.kv_utils import left_pad_stack
|
||||
from vllm_omni.model_executor.layers.timestep_embedding import timestep_embedding
|
||||
|
||||
|
||||
File renamed without changes.
+4
-1
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
# ruff: noqa: N803, E741
|
||||
"""Mixture-of-Tokens (MoT) RMS Normalization layer.
|
||||
|
||||
@@ -68,7 +71,7 @@ class MoTRMSNorm(CustomOp):
|
||||
return ir.ops.rms_norm(x, self.weight.data, self.variance_epsilon)
|
||||
|
||||
# gen mode – fused MoT Triton kernel
|
||||
from vllm_omni.diffusion.layers.mot.ops.mot_rms_norm import (
|
||||
from vllm_omni.diffusion.models.bagel.mot.ops.mot_rms_norm import (
|
||||
mot_rms_norm,
|
||||
)
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ from vllm.model_executor.layers.quantization.base_config import (
|
||||
from vllm.model_executor.utils import set_weight_attrs
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from vllm_omni.diffusion.layers.mot.ops.mot_gemm import invoke_mot_gemm
|
||||
from vllm_omni.diffusion.models.bagel.mot.ops.mot_gemm import invoke_mot_gemm
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ from vllm.model_executor.layers.quantization.base_config import (
|
||||
from vllm.model_executor.utils import set_weight_attrs
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from vllm_omni.diffusion.layers.mot.ops.mot_gemm import invoke_mot_gemm
|
||||
from vllm_omni.diffusion.models.bagel.mot.ops.mot_gemm import invoke_mot_gemm
|
||||
|
||||
|
||||
class MoTRowParallelLinear(RowParallelLinear):
|
||||
File renamed without changes.
+3
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
# ruff: noqa: N803, E741
|
||||
import functools
|
||||
import json
|
||||
+3
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
# ruff: noqa: N803, E741
|
||||
import torch
|
||||
from vllm.triton_utils import tl, triton
|
||||
@@ -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
|
||||
"""
|
||||
BagelPipeline implementation for vLLM-Omni.
|
||||
"""
|
||||
@@ -316,6 +316,11 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
|
||||
"bagel.connector",
|
||||
"bagel.vit_pos_embed",
|
||||
]
|
||||
# LoRA scanning target. ``_dit_modules`` holds the dotted path
|
||||
# "language_model.model", which DiffusionLoRAManager cannot resolve as a
|
||||
# pipeline attribute, so the top-level ``bagel`` module (LLM plus ViT,
|
||||
# connector, and VAE projections) is declared explicitly here.
|
||||
_lora_components: ClassVar[list[str]] = ["bagel"]
|
||||
supports_step_execution: ClassVar[bool] = True
|
||||
|
||||
def __init__(self, *, od_config: OmniDiffusionConfig, prefix: str = ""):
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
# inference caches (TeaCache/TaylorSeer) are not ported.
|
||||
|
||||
import itertools
|
||||
from collections import defaultdict
|
||||
from collections.abc import Iterable
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
@@ -24,17 +25,25 @@ import torch.nn.functional as F
|
||||
from diffusers.models.embeddings import Timesteps, get_1d_rotary_pos_embed
|
||||
from einops import rearrange, repeat
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
MergedColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
ReplicatedLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON
|
||||
|
||||
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.layers.fused_qk_norm_rope import (
|
||||
_fused_cuda_supported,
|
||||
fused_qk_norm_rope,
|
||||
fused_qk_norm_rope_min_tokens,
|
||||
)
|
||||
from vllm_omni.diffusion.layers.norm import RMSNorm
|
||||
from vllm_omni.diffusion.models.utils import make_attention_mask
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
@@ -43,7 +52,10 @@ if TYPE_CHECKING:
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
RotaryEmbedding = tuple[torch.Tensor, torch.Tensor]
|
||||
# (cos, sin) — optionally (cos, sin, packed_table) where packed_table is the
|
||||
# fp32 [tokens, head_dim] = [cos(theta) | sin(theta)] layout the fused
|
||||
# qk-norm+RoPE op consumes; the eager path ignores the third element.
|
||||
RotaryEmbedding = tuple[torch.Tensor, ...]
|
||||
RotaryFrequencyTables = list[RotaryEmbedding]
|
||||
|
||||
|
||||
@@ -56,9 +68,12 @@ def apply_rotary_emb(x: torch.Tensor, rotary_emb: RotaryEmbedding) -> torch.Tens
|
||||
|
||||
Args:
|
||||
x: Query or key tensor of shape [B, S, H, D].
|
||||
rotary_emb: Cosine and sine tensors, each shaped [B, S, D].
|
||||
rotary_emb: Cosine and sine tensors, each shaped [B, S, D]. The tuple
|
||||
may carry a third element (the packed table for the fused
|
||||
qk-norm+RoPE path); it is ignored here, hence the indexed access
|
||||
instead of tuple unpacking.
|
||||
"""
|
||||
freqs_cos, freqs_sin = rotary_emb
|
||||
freqs_cos, freqs_sin = rotary_emb[0], rotary_emb[1]
|
||||
freqs_cos = freqs_cos.unsqueeze(2)
|
||||
freqs_sin = freqs_sin.unsqueeze(2)
|
||||
|
||||
@@ -73,6 +88,87 @@ def apply_rotary_emb(x: torch.Tensor, rotary_emb: RotaryEmbedding) -> torch.Tens
|
||||
return x_out.type_as(x)
|
||||
|
||||
|
||||
# The fused qk-norm+RoPE path is always on where the fast path exists; on
|
||||
# other platforms the eager chain below is the behaviour-identical fallback.
|
||||
_FUSED_QK_NORM_ROPE = HAS_TRITON and current_platform.is_cuda()
|
||||
|
||||
# Boogu's default for the fused-path token gate: fuse only when a rotary table
|
||||
# spans at least this many positions (counted as B*S). Below the crossover a
|
||||
# request is host-bound and the fused path's per-call Python launch (custom-op
|
||||
# impl + Triton launcher) can cost more end-to-end than the kernel saves.
|
||||
# Measured on one H200: on the pre-#6871 main, 512^2 (1.1k tokens) paid
|
||||
# +191 ms/request and the crossover sat at ~2,350 tokens; on the current main
|
||||
# the 512^2 family measures as noise (+/-25 ms, sign-inconsistent) while
|
||||
# >=768^2 (2.3k tokens) gains. The crossover is host-dependent — re-benchmark
|
||||
# on your hardware and override with VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS
|
||||
# (0 = always fuse); see fused_qk_norm_rope_min_tokens().
|
||||
_FUSED_MIN_TOKENS = 2048
|
||||
|
||||
|
||||
def _with_packed_rope_table(rotary_emb: RotaryEmbedding) -> RotaryEmbedding:
|
||||
"""Append the packed fp32 table the fused qk-norm+RoPE op consumes.
|
||||
|
||||
``freqs_cos``/``freqs_sin`` are theta-repeat-interleaved ``[B, S, D]``
|
||||
(``cos[2i] == cos[2i+1] == cos(theta_i)``), so taking every even column
|
||||
yields the theta-width halves and the packed table is
|
||||
``[B*S, D] = [cos(theta) | sin(theta)]``. Tables spanning fewer positions
|
||||
(counted as ``B*S``) than the token gate — Boogu's ``_FUSED_MIN_TOKENS``
|
||||
default, overridable through ``VLLM_OMNI_FUSED_QK_NORM_ROPE_MIN_TOKENS``
|
||||
(``0`` = always fuse) — are returned unchanged: without the third element
|
||||
every consumer stays on the eager chain (this also keeps short tables like
|
||||
the context refiner's off the fused path).
|
||||
"""
|
||||
freqs_cos, freqs_sin = rotary_emb[0], rotary_emb[1]
|
||||
if freqs_cos.shape[0] * freqs_cos.shape[1] < fused_qk_norm_rope_min_tokens(_FUSED_MIN_TOKENS):
|
||||
return rotary_emb
|
||||
packed = torch.cat((freqs_cos[..., ::2], freqs_sin[..., ::2]), dim=-1)
|
||||
return freqs_cos, freqs_sin, packed.reshape(-1, freqs_cos.shape[-1]).float()
|
||||
|
||||
|
||||
def _qk_norm_rope(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
norm_q,
|
||||
norm_k,
|
||||
rotary_emb: RotaryEmbedding | None,
|
||||
dtype: torch.dtype,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Per-head Q/K RMSNorm + RoPE + cast, fused into one kernel launch when
|
||||
a packed rope table is present; otherwise the original eager chain."""
|
||||
# Gate on the op's own fast-path predicate: when the fused CUDA kernel
|
||||
# cannot run (dtype, device, or geometry outside even
|
||||
# rotary_dim <= head_dim <= 256), the original chain below must be used
|
||||
# bit-exactly rather than the op's internal eager fallback, whose rounding
|
||||
# differs from vLLM's RMSNorm by one ulp on a fraction of elements.
|
||||
if (
|
||||
rotary_emb is not None
|
||||
and len(rotary_emb) > 2
|
||||
and rotary_emb[2] is not None
|
||||
and _fused_cuda_supported(query, key, query.shape[-1], query.shape[-1], interleaved=True)
|
||||
):
|
||||
batch, seq_len, num_heads, head_dim = query.shape
|
||||
num_kv_heads = key.shape[2]
|
||||
fused_q, fused_k = fused_qk_norm_rope(
|
||||
query.view(batch * seq_len, num_heads, head_dim),
|
||||
key.view(batch * seq_len, num_kv_heads, head_dim),
|
||||
norm_q.weight,
|
||||
norm_k.weight,
|
||||
rotary_emb[2],
|
||||
norm_q.variance_epsilon,
|
||||
interleaved=True,
|
||||
)
|
||||
return (
|
||||
fused_q.view(batch, seq_len, num_heads, head_dim),
|
||||
fused_k.view(batch, seq_len, num_kv_heads, head_dim),
|
||||
)
|
||||
query = norm_q(query)
|
||||
key = norm_k(key)
|
||||
if rotary_emb is not None:
|
||||
query = apply_rotary_emb(query, rotary_emb)
|
||||
key = apply_rotary_emb(key, rotary_emb)
|
||||
return query.to(dtype), key.to(dtype)
|
||||
|
||||
|
||||
def swiglu(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
||||
return F.silu(x.float(), inplace=False).to(x.dtype) * y
|
||||
|
||||
@@ -166,7 +262,14 @@ class LuminaLayerNormContinuous(nn.Module):
|
||||
|
||||
|
||||
class LuminaFeedForward(nn.Module):
|
||||
"""SwiGLU feed-forward with tensor-parallel projections."""
|
||||
"""SwiGLU feed-forward with tensor-parallel projections.
|
||||
|
||||
The ``gate`` and ``input`` projections are fused into a single
|
||||
``MergedColumnParallelLinear`` (one GEMM instead of two), matching the
|
||||
``gate_up_proj`` convention used by the Hunyuan Image 3 port. The SwiGLU
|
||||
activation keeps its float32 computation for numerical parity with
|
||||
upstream.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -182,20 +285,13 @@ class LuminaFeedForward(nn.Module):
|
||||
inner_dim = int(ffn_dim_multiplier * inner_dim)
|
||||
inner_dim = multiple_of * ((inner_dim + multiple_of - 1) // multiple_of)
|
||||
|
||||
self.linear_1 = ColumnParallelLinear(
|
||||
dim,
|
||||
inner_dim,
|
||||
self.gate_up_proj = MergedColumnParallelLinear(
|
||||
input_size=dim,
|
||||
output_sizes=[inner_dim, inner_dim],
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "linear_1"),
|
||||
) # gate
|
||||
self.linear_3 = ColumnParallelLinear(
|
||||
dim,
|
||||
inner_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "linear_3"),
|
||||
) # input
|
||||
prefix=_join_prefix(prefix, "gate_up_proj"),
|
||||
)
|
||||
self.linear_2 = RowParallelLinear(
|
||||
inner_dim,
|
||||
dim,
|
||||
@@ -205,8 +301,8 @@ class LuminaFeedForward(nn.Module):
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
h1, _ = self.linear_1(x)
|
||||
h2, _ = self.linear_3(x)
|
||||
gate_up, _ = self.gate_up_proj(x)
|
||||
h1, h2 = gate_up.chunk(2, dim=-1)
|
||||
out, _ = self.linear_2(swiglu(h1, h2))
|
||||
return out
|
||||
|
||||
@@ -499,28 +595,15 @@ class BooguImageSelfAttention(nn.Module):
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.head_dim = dim // num_attention_heads
|
||||
kv_dim = self.head_dim * num_kv_heads
|
||||
|
||||
self.to_q = ColumnParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
self.to_qkv = QKVParallelLinear(
|
||||
hidden_size=dim,
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=num_attention_heads,
|
||||
total_num_kv_heads=num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "to_q"),
|
||||
)
|
||||
self.to_k = ColumnParallelLinear(
|
||||
dim,
|
||||
kv_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "to_k"),
|
||||
)
|
||||
self.to_v = ColumnParallelLinear(
|
||||
dim,
|
||||
kv_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "to_v"),
|
||||
prefix=_join_prefix(prefix, "to_qkv"),
|
||||
)
|
||||
self.norm_q = RMSNorm(self.head_dim, eps=1e-5)
|
||||
self.norm_k = RMSNorm(self.head_dim, eps=1e-5)
|
||||
@@ -532,8 +615,10 @@ class BooguImageSelfAttention(nn.Module):
|
||||
prefix=_join_prefix(prefix, "to_out"),
|
||||
)
|
||||
|
||||
self.num_local_heads = self.to_q.output_size_per_partition // self.head_dim
|
||||
self.num_local_kv_heads = self.to_k.output_size_per_partition // self.head_dim
|
||||
self.num_local_heads = self.to_qkv.num_heads
|
||||
self.num_local_kv_heads = self.to_qkv.num_kv_heads
|
||||
self.q_size = self.num_local_heads * self.head_dim
|
||||
self.kv_size = self.num_local_kv_heads * self.head_dim
|
||||
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_local_heads,
|
||||
@@ -551,21 +636,14 @@ class BooguImageSelfAttention(nn.Module):
|
||||
) -> torch.Tensor:
|
||||
dtype = hidden_states.dtype
|
||||
|
||||
query, _ = self.to_q(hidden_states)
|
||||
key, _ = self.to_k(hidden_states)
|
||||
value, _ = self.to_v(hidden_states)
|
||||
qkv, _ = self.to_qkv(hidden_states)
|
||||
query, key, value = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
|
||||
|
||||
query = query.unflatten(-1, (self.num_local_heads, self.head_dim))
|
||||
key = key.unflatten(-1, (self.num_local_kv_heads, self.head_dim))
|
||||
value = value.unflatten(-1, (self.num_local_kv_heads, self.head_dim))
|
||||
|
||||
query = self.norm_q(query)
|
||||
key = self.norm_k(key)
|
||||
|
||||
if rotary_emb is not None:
|
||||
query = apply_rotary_emb(query, rotary_emb)
|
||||
key = apply_rotary_emb(key, rotary_emb)
|
||||
query, key = query.to(dtype), key.to(dtype)
|
||||
query, key = _qk_norm_rope(query, key, self.norm_q, self.norm_k, rotary_emb, dtype)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
attn_output = self.attn(query, key, value, attn_metadata)
|
||||
@@ -595,50 +673,24 @@ class BooguImageJointAttention(nn.Module):
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.head_dim = dim // num_attention_heads
|
||||
kv_dim = self.head_dim * num_kv_heads
|
||||
|
||||
self.img_to_q = ColumnParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
self.img_to_qkv = QKVParallelLinear(
|
||||
hidden_size=dim,
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=num_attention_heads,
|
||||
total_num_kv_heads=num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "img_to_q"),
|
||||
prefix=_join_prefix(prefix, "img_to_qkv"),
|
||||
)
|
||||
self.img_to_k = ColumnParallelLinear(
|
||||
dim,
|
||||
kv_dim,
|
||||
self.instruct_to_qkv = QKVParallelLinear(
|
||||
hidden_size=dim,
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=num_attention_heads,
|
||||
total_num_kv_heads=num_kv_heads,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "img_to_k"),
|
||||
)
|
||||
self.img_to_v = ColumnParallelLinear(
|
||||
dim,
|
||||
kv_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "img_to_v"),
|
||||
)
|
||||
|
||||
self.instruct_to_q = ColumnParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "instruct_to_q"),
|
||||
)
|
||||
self.instruct_to_k = ColumnParallelLinear(
|
||||
dim,
|
||||
kv_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "instruct_to_k"),
|
||||
)
|
||||
self.instruct_to_v = ColumnParallelLinear(
|
||||
dim,
|
||||
kv_dim,
|
||||
bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "instruct_to_v"),
|
||||
prefix=_join_prefix(prefix, "instruct_to_qkv"),
|
||||
)
|
||||
|
||||
self.norm_q = RMSNorm(self.head_dim, eps=1e-5)
|
||||
@@ -669,8 +721,10 @@ class BooguImageJointAttention(nn.Module):
|
||||
prefix=_join_prefix(prefix, "to_out"),
|
||||
)
|
||||
|
||||
self.num_local_heads = self.img_to_q.output_size_per_partition // self.head_dim
|
||||
self.num_local_kv_heads = self.img_to_k.output_size_per_partition // self.head_dim
|
||||
self.num_local_heads = self.img_to_qkv.num_heads
|
||||
self.num_local_kv_heads = self.img_to_qkv.num_kv_heads
|
||||
self.q_size = self.num_local_heads * self.head_dim
|
||||
self.kv_size = self.num_local_kv_heads * self.head_dim
|
||||
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_local_heads,
|
||||
@@ -692,13 +746,13 @@ class BooguImageJointAttention(nn.Module):
|
||||
dtype = img_hidden_states.dtype
|
||||
batch_size = img_hidden_states.shape[0]
|
||||
|
||||
img_query, _ = self.img_to_q(img_hidden_states)
|
||||
img_key, _ = self.img_to_k(img_hidden_states)
|
||||
img_value, _ = self.img_to_v(img_hidden_states)
|
||||
img_qkv, _ = self.img_to_qkv(img_hidden_states)
|
||||
img_query, img_key, img_value = img_qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
|
||||
|
||||
instruct_query, _ = self.instruct_to_q(instruct_hidden_states)
|
||||
instruct_key, _ = self.instruct_to_k(instruct_hidden_states)
|
||||
instruct_value, _ = self.instruct_to_v(instruct_hidden_states)
|
||||
instruct_qkv, _ = self.instruct_to_qkv(instruct_hidden_states)
|
||||
instruct_query, instruct_key, instruct_value = instruct_qkv.split(
|
||||
[self.q_size, self.kv_size, self.kv_size], dim=-1
|
||||
)
|
||||
|
||||
query, key, value = _concat_instruction_image_features(
|
||||
[img_query, img_key, img_value],
|
||||
@@ -711,13 +765,7 @@ class BooguImageJointAttention(nn.Module):
|
||||
key = key.view(batch_size, -1, self.num_local_kv_heads, self.head_dim)
|
||||
value = value.view(batch_size, -1, self.num_local_kv_heads, self.head_dim)
|
||||
|
||||
query = self.norm_q(query)
|
||||
key = self.norm_k(key)
|
||||
|
||||
if rotary_emb is not None:
|
||||
query = apply_rotary_emb(query, rotary_emb)
|
||||
key = apply_rotary_emb(key, rotary_emb)
|
||||
query, key = query.to(dtype), key.to(dtype)
|
||||
query, key = _qk_norm_rope(query, key, self.norm_q, self.norm_k, rotary_emb, dtype)
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=joint_attention_mask) if joint_attention_mask is not None else None
|
||||
attn_output = self.attn(query, key, value, attn_metadata)
|
||||
@@ -1053,6 +1101,44 @@ def _cal_preprocessed_instruction_feat_dim(instruction_feature_configs: dict) ->
|
||||
raise ValueError(f"Invalid reduce_type: {reduce_type}")
|
||||
|
||||
|
||||
# Packed (fused) projections vs. the logical sub-projections the diffusers
|
||||
# checkpoint stores, in the ``(param_name, shard_name, shard_id)`` form used
|
||||
# across vllm-omni. ``load_weights`` consumes it directly, and loader consumers
|
||||
# that discover it via ``stacked_params_mapping`` (LoRA, quantized loaders) get
|
||||
# the packed -> sub-layer relationship for free.
|
||||
#
|
||||
# The QKV entries stay leaf-scoped: each fused source (``to_q`` on the
|
||||
# self-attention module, ``img_to_q`` / ``instruct_to_q`` on the joint
|
||||
# attention) has a distinct leaf, and ``.to_q.`` cannot collide with
|
||||
# ``.img_to_q.`` because the preceding character is ``_`` rather than ``.``.
|
||||
# The FFN entries are path-qualified instead: ``linear_1`` also names the
|
||||
# timestep embedder and the ``norm_out`` projections, which must load 1:1 and
|
||||
# are not fused.
|
||||
_BOOGU_STACKED_PARAMS_MAPPING = (
|
||||
# self-attention: noise / reference-image / context refiners, the
|
||||
# single-stream blocks, and the double-stream image self-attention.
|
||||
(".to_qkv.", ".to_q.", "q"),
|
||||
(".to_qkv.", ".to_k.", "k"),
|
||||
(".to_qkv.", ".to_v.", "v"),
|
||||
# joint (instruction + image) attention of the double-stream blocks.
|
||||
(".img_to_qkv.", ".img_to_q.", "q"),
|
||||
(".img_to_qkv.", ".img_to_k.", "k"),
|
||||
(".img_to_qkv.", ".img_to_v.", "v"),
|
||||
(".instruct_to_qkv.", ".instruct_to_q.", "q"),
|
||||
(".instruct_to_qkv.", ".instruct_to_k.", "k"),
|
||||
(".instruct_to_qkv.", ".instruct_to_v.", "v"),
|
||||
# feed-forward gate/up: ``linear_1`` is the gate (shard 0) and
|
||||
# ``linear_3`` the input (shard 1), matching the packed order the SwiGLU
|
||||
# activation consumes.
|
||||
(".feed_forward.gate_up_proj.", ".feed_forward.linear_1.", 0),
|
||||
(".feed_forward.gate_up_proj.", ".feed_forward.linear_3.", 1),
|
||||
(".img_feed_forward.gate_up_proj.", ".img_feed_forward.linear_1.", 0),
|
||||
(".img_feed_forward.gate_up_proj.", ".img_feed_forward.linear_3.", 1),
|
||||
(".instruct_feed_forward.gate_up_proj.", ".instruct_feed_forward.linear_1.", 0),
|
||||
(".instruct_feed_forward.gate_up_proj.", ".instruct_feed_forward.linear_3.", 1),
|
||||
)
|
||||
|
||||
|
||||
class BooguImageTransformer2DModel(nn.Module):
|
||||
"""Boogu-Image transformer with mixed stream topology.
|
||||
|
||||
@@ -1078,6 +1164,10 @@ class BooguImageTransformer2DModel(nn.Module):
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
# Published here rather than in ``load_weights`` so loader consumers
|
||||
# that only inspect the module tree (LoRA discovery, quantized weight
|
||||
# loaders) always see the packed -> sub-layer relationship.
|
||||
self.stacked_params_mapping = list(_BOOGU_STACKED_PARAMS_MAPPING)
|
||||
self.od_config = od_config
|
||||
cfg = od_config.tf_model_config
|
||||
|
||||
@@ -1449,6 +1539,11 @@ class BooguImageTransformer2DModel(nn.Module):
|
||||
shift += ref_img_len
|
||||
idx += 1
|
||||
|
||||
if _FUSED_QK_NORM_ROPE:
|
||||
# The rebuilt per-reference-image tuple needs its own packed
|
||||
# table; the forward-level tuples do not flow into this batch.
|
||||
batch_ref_img_rotary_emb = _with_packed_rope_table(batch_ref_img_rotary_emb)
|
||||
|
||||
for layer in self.ref_image_refiner:
|
||||
batch_ref_image_hidden_states = layer(
|
||||
batch_ref_image_hidden_states, batch_ref_img_mask, batch_ref_img_rotary_emb, batch_temb
|
||||
@@ -1534,6 +1629,17 @@ class BooguImageTransformer2DModel(nn.Module):
|
||||
device,
|
||||
)
|
||||
|
||||
if _FUSED_QK_NORM_ROPE:
|
||||
# One packed [cos|sin] table per rotary embedding that reaches an
|
||||
# attention, built once per forward; the tuples grow a third
|
||||
# element that the fused path consumes and the eager path ignores.
|
||||
# (ref_img_rotary_emb is packed inside img_patch_embed_and_refine,
|
||||
# on the rebuilt per-reference-image batch tuple.)
|
||||
context_rotary_emb = _with_packed_rope_table(context_rotary_emb)
|
||||
noise_rotary_emb = _with_packed_rope_table(noise_rotary_emb)
|
||||
rotary_emb = _with_packed_rope_table(rotary_emb)
|
||||
combined_img_rotary_emb = _with_packed_rope_table(combined_img_rotary_emb)
|
||||
|
||||
# Context refinement.
|
||||
for layer in self.context_refiner:
|
||||
instruction_hidden_states = layer(instruction_hidden_states, instruction_attention_mask, context_rotary_emb)
|
||||
@@ -1612,7 +1718,7 @@ class BooguImageTransformer2DModel(nn.Module):
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load diffusers-named checkpoint weights into the native module.
|
||||
|
||||
Two name promotions relative to upstream (see step 8/10 findings):
|
||||
Name promotions relative to upstream (see step 8/10 findings):
|
||||
|
||||
- ``*.img_instruct_attn.processor.{img,instruct}_{to_q,to_k,to_v}`` /
|
||||
``{instruct,img}_out`` -> drop ``.processor`` (upstream keeps the
|
||||
@@ -1621,9 +1727,29 @@ class BooguImageTransformer2DModel(nn.Module):
|
||||
- ``*.to_out.0.weight`` -> ``*.to_out.weight`` (diffusers wraps the
|
||||
output projection in a ``ModuleList``; the native module uses a plain
|
||||
linear).
|
||||
|
||||
Packed Q/K/V and FFN gate/input matrices are folded onto the fused
|
||||
``QKVParallelLinear`` / ``MergedColumnParallelLinear`` parameters using
|
||||
:attr:`stacked_params_mapping` — the same mapping loader consumers such
|
||||
as LoRA discovery and quantized weight loaders read.
|
||||
|
||||
A fused parameter is only reported as loaded once *every* one of its
|
||||
source matrices has arrived. The caller compares parameter names, so
|
||||
reporting e.g. ``to_qkv`` complete after the first shard would let a
|
||||
checkpoint carrying only ``to_q`` start up with the ``k``/``v`` slices
|
||||
left uninitialized.
|
||||
"""
|
||||
stacked_params_mapping = self.stacked_params_mapping
|
||||
# The shard ids each fused parameter is assembled from, keyed by the
|
||||
# mapping entry that produces it.
|
||||
expected_shards: dict[str, set[str | int]] = defaultdict(set)
|
||||
for param_name, _weight_name, packed_shard_id in stacked_params_mapping:
|
||||
expected_shards[param_name].add(packed_shard_id)
|
||||
|
||||
params_dict = dict(self.named_parameters())
|
||||
loaded_params: set[str] = set()
|
||||
# Fused parameter -> (mapping entry that produced it, shards received).
|
||||
fused_params: dict[str, tuple[str, set[str | int]]] = {}
|
||||
|
||||
for name, loaded_weight in weights:
|
||||
original_name = name
|
||||
@@ -1632,15 +1758,36 @@ class BooguImageTransformer2DModel(nn.Module):
|
||||
if ".to_out.0." in name:
|
||||
name = name.replace(".to_out.0.", ".to_out.")
|
||||
|
||||
shard_id: str | int | None = None
|
||||
matched_entry: str | None = None
|
||||
for param_name, weight_name, packed_shard_id in stacked_params_mapping:
|
||||
if weight_name in name:
|
||||
name = name.replace(weight_name, param_name)
|
||||
shard_id = packed_shard_id
|
||||
matched_entry = param_name
|
||||
break
|
||||
|
||||
if name not in params_dict:
|
||||
logger.warning("Skipping unexpected checkpoint weight %s", original_name)
|
||||
continue
|
||||
|
||||
param = params_dict[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, loaded_weight)
|
||||
if matched_entry is None:
|
||||
weight_loader(param, loaded_weight)
|
||||
else:
|
||||
weight_loader(param, loaded_weight, shard_id)
|
||||
_, received = fused_params.setdefault(name, (matched_entry, set()))
|
||||
received.add(shard_id)
|
||||
loaded_params.add(name)
|
||||
|
||||
# Withdraw any fused parameter that only received part of its source
|
||||
# matrices, so the caller's "not initialized from checkpoint" check
|
||||
# reports it as missing instead of accepting a half-filled parameter.
|
||||
for name, (matched_entry, received) in fused_params.items():
|
||||
if received != expected_shards[matched_entry]:
|
||||
loaded_params.discard(name)
|
||||
|
||||
unloaded_params = sorted(params_dict.keys() - loaded_params)
|
||||
if unloaded_params:
|
||||
logger.warning("Model parameters not loaded from checkpoint: %s", unloaded_params)
|
||||
|
||||
@@ -34,9 +34,13 @@ from diffusers.models.autoencoders.autoencoder_kl import AutoencoderKL
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from torch import nn
|
||||
from torch.nn.attention import SDPBackend, sdpa_kernel
|
||||
from transformers import Qwen3VLForConditionalGeneration, Qwen3VLProcessor
|
||||
from transformers import AutoModel, Qwen3VLConfig, Qwen3VLForConditionalGeneration, Qwen3VLModel, Qwen3VLProcessor
|
||||
from vllm.config.quantization import QuantizationConfigArgs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
|
||||
from vllm.model_executor.layers.quantization.online.base import OnlineQuantizationConfig
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader, WeightsMapper
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
@@ -54,6 +58,7 @@ from vllm_omni.diffusion.models.boogu_image.scheduling_flow_match_euler_discrete
|
||||
)
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput, SupportsComponentDiscovery
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
from vllm_omni.diffusion.models.utils import create_transformers_model_with_vllm_linears
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.request_batch import DiffusionRequestBatch, split_diffusion_output_by_request
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import download_weights_from_hf_specific
|
||||
@@ -243,6 +248,7 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
|
||||
self.od_config = od_config
|
||||
self._raise_unsupported_features()
|
||||
transformer_quant_config = resolve_component_quant_config(od_config.quantization_config, "transformer")
|
||||
mllm_quant_config = resolve_component_quant_config(od_config.quantization_config, "mllm")
|
||||
self.weights_sources = [
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=od_config.model,
|
||||
@@ -273,22 +279,7 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
|
||||
local_files_only=local_files_only,
|
||||
revision=od_config.revision,
|
||||
)
|
||||
|
||||
mllm = from_pretrained_with_prefetch(
|
||||
Qwen3VLForConditionalGeneration.from_pretrained,
|
||||
model,
|
||||
subfolder="mllm",
|
||||
prefetch_list=boogu_subfolders,
|
||||
local_files_only=local_files_only,
|
||||
torch_dtype=od_config.dtype,
|
||||
revision=od_config.revision,
|
||||
)
|
||||
# Upstream reuses the full VLM as an optional instruction rewriter and
|
||||
# encodes with its inner model (no ``lm_head``); the rewriter is not
|
||||
# ported, so keep only the inner ``Qwen3VLModel`` as the encoder.
|
||||
if hasattr(mllm, "lm_head"):
|
||||
mllm = mllm.model
|
||||
self.mllm = mllm.to(self._execution_device)
|
||||
self.mllm = self._load_mllm(model, local_files_only, mllm_quant_config, boogu_subfolders)
|
||||
|
||||
self.processor = Qwen3VLProcessor.from_pretrained(
|
||||
model,
|
||||
@@ -323,6 +314,68 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
|
||||
self.SYSTEM_PROMPT_4_TI2I = SYSTEM_PROMPT_4_TI2I_UNIFIED
|
||||
self.SYSTEM_PROMPT_4_I2I = SYSTEM_PROMPT_4_TI2I_UNIFIED
|
||||
|
||||
def _load_mllm(
|
||||
self,
|
||||
model_path: str,
|
||||
local_files_only: bool,
|
||||
quant_config: QuantizationConfig | None,
|
||||
prefetch_list: list[str],
|
||||
) -> Qwen3VLModel:
|
||||
"""Load MLLM through HF, or prepare it for deferred online FP8 loading."""
|
||||
config = None
|
||||
if quant_config is not None:
|
||||
if not isinstance(quant_config, Fp8Config):
|
||||
raise ValueError(
|
||||
"Boogu MLLM only supports FP8 quantization. Set mllm to null to disable online quantization."
|
||||
)
|
||||
config = Qwen3VLConfig.from_pretrained(
|
||||
model_path, subfolder="mllm", local_files_only=local_files_only, revision=self.od_config.revision
|
||||
)
|
||||
|
||||
# With no MLLM quantization override, or with checkpoint quantization
|
||||
# metadata, preserve HF model initialization and weight loading.
|
||||
if config is None or getattr(config, "quantization_config", None):
|
||||
mllm = from_pretrained_with_prefetch(
|
||||
Qwen3VLForConditionalGeneration.from_pretrained,
|
||||
model_path,
|
||||
subfolder="mllm",
|
||||
prefetch_list=prefetch_list,
|
||||
local_files_only=local_files_only,
|
||||
torch_dtype=self.od_config.dtype,
|
||||
revision=self.od_config.revision,
|
||||
)
|
||||
# Upstream reuses the full VLM as an optional instruction rewriter and
|
||||
# encodes with its inner model (no ``lm_head``); the rewriter is not
|
||||
# ported, so keep only the inner ``Qwen3VLModel`` as the encoder.
|
||||
if hasattr(mllm, "lm_head"):
|
||||
mllm = mllm.model
|
||||
return mllm.to(self._execution_device)
|
||||
|
||||
online_quant_config = OnlineQuantizationConfig(
|
||||
QuantizationConfigArgs(linear="fp8_per_block", ignore=quant_config.ignored_layers)
|
||||
)
|
||||
|
||||
mllm = create_transformers_model_with_vllm_linears(
|
||||
AutoModel,
|
||||
config,
|
||||
online_quant_config,
|
||||
dtype=self.od_config.dtype,
|
||||
device=self._execution_device,
|
||||
prefix="mllm",
|
||||
skip_modules=("mllm.visual",),
|
||||
)
|
||||
|
||||
self.weights_sources.append(
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=model_path,
|
||||
subfolder="mllm",
|
||||
revision=self.od_config.revision,
|
||||
prefix="mllm.",
|
||||
)
|
||||
)
|
||||
|
||||
return mllm.requires_grad_(False).eval()
|
||||
|
||||
def _raise_unsupported_features(self) -> None:
|
||||
"""Reject execution modes that do not have Boogu-specific support."""
|
||||
parallel_config = self.od_config.parallel_config
|
||||
@@ -339,7 +392,8 @@ class BooguImagePipeline(CFGParallelMixin, nn.Module, ProgressBarMixin, Supports
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
loader = AutoWeightsLoader(self)
|
||||
return loader.load_weights(weights)
|
||||
mapper = WeightsMapper(orig_to_new_prefix={"mllm.lm_head.": None, "mllm.model.": "mllm."})
|
||||
return loader.load_weights(weights, mapper=mapper)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Prompt encoding (upstream ``encode_instruction``, t2i path)
|
||||
|
||||
@@ -38,13 +38,24 @@ EMBODIMENT_TO_DOMAIN_ID: dict[str, int] = {
|
||||
"bridge_orig_lerobot": 7,
|
||||
"droid_lerobot": 8,
|
||||
"robomind-franka": 8,
|
||||
"embodiment_b": 9,
|
||||
# Backward-compatible alias for the pre-generator Cosmos Framework name.
|
||||
"galbot": 9,
|
||||
"robomind-franka-dual": 12,
|
||||
"robomind-ur": 13,
|
||||
"agibotworld": 15,
|
||||
"embodiment_c_gripper": 15,
|
||||
"embodiment_c_gripper_ext": 15,
|
||||
# Backward-compatible aliases for the pre-generator Cosmos Framework names.
|
||||
"agibot_gear_gripper": 15,
|
||||
"agibot_gear_gripper_ext": 15,
|
||||
"xdof_yam": 16,
|
||||
"molmoact2_yam": 16,
|
||||
"abc_yam": 16,
|
||||
"fractal": 20,
|
||||
"drawanything": 21,
|
||||
"behavior1k_lerobot": 22,
|
||||
"maniparena": 23,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Scheduled A16 execution for quantized Cosmos3 checkpoints."""
|
||||
|
||||
from .checkpoint import resolve_mixed_precision_config
|
||||
from .config import Cosmos3MixedPrecisionConfig
|
||||
from .runtime import Cosmos3MixedPrecisionRuntime
|
||||
|
||||
__all__ = [
|
||||
"Cosmos3MixedPrecisionConfig",
|
||||
"Cosmos3MixedPrecisionRuntime",
|
||||
"resolve_mixed_precision_config",
|
||||
]
|
||||
@@ -0,0 +1,176 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Checkpoint discovery for the Cosmos3 diffusion-step precision policy."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Literal, cast
|
||||
|
||||
from .config import Cosmos3MixedPrecisionConfig, ReasonerPolicy, _non_negative_int
|
||||
|
||||
PolicySource = Literal[
|
||||
"none",
|
||||
"checkpoint",
|
||||
"additional_config",
|
||||
"additional_config_disabled",
|
||||
]
|
||||
|
||||
_COMPONENT = "transformer"
|
||||
_POLICY_FIELDS = frozenset(
|
||||
{
|
||||
"schema_version",
|
||||
"type",
|
||||
"index_space",
|
||||
"scope",
|
||||
"default_mode",
|
||||
"first_steps",
|
||||
"last_steps",
|
||||
"overlap",
|
||||
"reasoner",
|
||||
}
|
||||
)
|
||||
_STEP_RANGE_FIELDS = frozenset({"count", "mode"})
|
||||
_SUPPORTED_MODEL_OPT_CONFIGS = frozenset(
|
||||
{
|
||||
"modelopt",
|
||||
"modelopt_fp4",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def resolve_mixed_precision_config(
|
||||
od_config: object,
|
||||
) -> tuple[Cosmos3MixedPrecisionConfig | None, PolicySource]:
|
||||
"""Resolve an explicit runtime override before the checkpoint default."""
|
||||
override_present, override = Cosmos3MixedPrecisionConfig.resolve_additional_config(
|
||||
getattr(od_config, "additional_config", None)
|
||||
)
|
||||
if override_present:
|
||||
if override is not None:
|
||||
_validate_checkpoint_quantization(od_config)
|
||||
source: PolicySource = "additional_config" if override is not None else "additional_config_disabled"
|
||||
return override, source
|
||||
|
||||
checkpoint = read_checkpoint_policy(od_config)
|
||||
if checkpoint is not None:
|
||||
return checkpoint, "checkpoint"
|
||||
return None, "none"
|
||||
|
||||
|
||||
def read_checkpoint_policy(od_config: object) -> Cosmos3MixedPrecisionConfig | None:
|
||||
"""Read and validate a policy from ``transformer/config.json``.
|
||||
|
||||
Missing metadata preserves ordinary checkpoint behavior. Metadata that is
|
||||
present but malformed or incompatible fails closed.
|
||||
"""
|
||||
tf_config = getattr(od_config, "tf_model_config", None)
|
||||
params = getattr(tf_config, "params", None)
|
||||
if not isinstance(params, Mapping):
|
||||
return None
|
||||
|
||||
disk_quant_config = params.get("quantization_config")
|
||||
if not isinstance(disk_quant_config, Mapping):
|
||||
return None
|
||||
|
||||
if "runtime" not in disk_quant_config:
|
||||
return None
|
||||
runtime_config = disk_quant_config["runtime"]
|
||||
if not isinstance(runtime_config, Mapping):
|
||||
raise TypeError("quantization_config.runtime must be a mapping")
|
||||
|
||||
if "diffusion_step_policy" not in runtime_config:
|
||||
return None
|
||||
raw_policy = runtime_config["diffusion_step_policy"]
|
||||
if not isinstance(raw_policy, Mapping):
|
||||
raise TypeError("quantization_config.runtime.diffusion_step_policy must be a mapping")
|
||||
|
||||
policy = _parse_policy(raw_policy)
|
||||
if policy is None:
|
||||
return None
|
||||
_validate_checkpoint_quantization(od_config)
|
||||
return policy
|
||||
|
||||
|
||||
def _parse_policy(policy: Mapping[str, object]) -> Cosmos3MixedPrecisionConfig | None:
|
||||
fields = set(policy)
|
||||
unknown = fields - _POLICY_FIELDS
|
||||
if unknown:
|
||||
raise ValueError(f"Unknown diffusion_step_policy fields: {sorted(unknown)}")
|
||||
missing = _POLICY_FIELDS - fields
|
||||
if missing:
|
||||
raise ValueError(f"Missing diffusion_step_policy fields: {sorted(missing)}")
|
||||
|
||||
schema_version = policy["schema_version"]
|
||||
if not isinstance(schema_version, int) or isinstance(schema_version, bool) or schema_version != 1:
|
||||
raise ValueError("diffusion_step_policy.schema_version must be the integer 1")
|
||||
if policy["type"] != "first_last_n":
|
||||
raise ValueError("diffusion_step_policy.type must be 'first_last_n'")
|
||||
if policy["index_space"] != "denoising_loop_iteration":
|
||||
raise ValueError("diffusion_step_policy.index_space must be 'denoising_loop_iteration'")
|
||||
if policy["default_mode"] != "native":
|
||||
raise ValueError("diffusion_step_policy.default_mode must be 'native'")
|
||||
if policy["overlap"] != "a16":
|
||||
raise ValueError("diffusion_step_policy.overlap must be 'a16'")
|
||||
|
||||
scope = policy["scope"]
|
||||
if not isinstance(scope, list) or not scope or not all(isinstance(item, str) for item in scope):
|
||||
raise TypeError("diffusion_step_policy.scope must be a non-empty list of strings")
|
||||
|
||||
first_steps = _parse_step_range(policy["first_steps"], "first_steps")
|
||||
last_steps = _parse_step_range(policy["last_steps"], "last_steps")
|
||||
|
||||
reasoner = policy["reasoner"]
|
||||
if reasoner not in {"native", "a16"}:
|
||||
raise ValueError("diffusion_step_policy.reasoner must be 'native' or 'a16'")
|
||||
|
||||
if _COMPONENT not in scope:
|
||||
return None
|
||||
return Cosmos3MixedPrecisionConfig(
|
||||
first_steps=first_steps,
|
||||
last_steps=last_steps,
|
||||
reasoner=cast(ReasonerPolicy, reasoner),
|
||||
)
|
||||
|
||||
|
||||
def _parse_step_range(value: object, name: str) -> int:
|
||||
if not isinstance(value, Mapping):
|
||||
raise TypeError(f"diffusion_step_policy.{name} must be a mapping")
|
||||
fields = set(value)
|
||||
unknown = fields - _STEP_RANGE_FIELDS
|
||||
if unknown:
|
||||
raise ValueError(f"Unknown diffusion_step_policy.{name} fields: {sorted(unknown)}")
|
||||
missing = _STEP_RANGE_FIELDS - fields
|
||||
if missing:
|
||||
raise ValueError(f"Missing diffusion_step_policy.{name} fields: {sorted(missing)}")
|
||||
if value["mode"] != "a16":
|
||||
raise ValueError(f"diffusion_step_policy.{name}.mode must be 'a16'")
|
||||
return _non_negative_int(value["count"], f"diffusion_step_policy.{name}.count")
|
||||
|
||||
|
||||
def _validate_checkpoint_quantization(od_config: object) -> None:
|
||||
# Match the effective quantization used to construct the transformer linears.
|
||||
quant_config = getattr(od_config, "quantization_config", None)
|
||||
if quant_config is None:
|
||||
tf_config = getattr(od_config, "tf_model_config", None)
|
||||
quant_config = getattr(tf_config, "quant_config", None)
|
||||
|
||||
get_name = getattr(quant_config, "get_name", None)
|
||||
name = get_name() if callable(get_name) else None
|
||||
if name not in _SUPPORTED_MODEL_OPT_CONFIGS:
|
||||
raise ValueError(f"diffusion_step_policy requires a serialized ModelOpt FP8 or NVFP4 checkpoint, got {name!r}")
|
||||
|
||||
if name == "modelopt":
|
||||
_require_serialized(quant_config, "is_checkpoint_fp8_serialized", "FP8")
|
||||
return
|
||||
if name == "modelopt_fp4":
|
||||
if getattr(quant_config, "quant_method", "NVFP4") != "NVFP4":
|
||||
raise ValueError("diffusion_step_policy requires checkpoint-native NVFP4 W4A4 linears")
|
||||
_require_serialized(quant_config, "is_checkpoint_nvfp4_serialized", "NVFP4")
|
||||
return
|
||||
|
||||
|
||||
def _require_serialized(quant_config: object | None, flag: str, format_name: str) -> None:
|
||||
if not bool(getattr(quant_config, flag, False)):
|
||||
raise ValueError(f"diffusion_step_policy requires serialized ModelOpt {format_name} weights")
|
||||
@@ -0,0 +1,106 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Configuration parsing and denoising-step policy for mixed precision."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal, cast
|
||||
|
||||
ReasonerPolicy = Literal["native", "a16"]
|
||||
|
||||
_REASONER_POLICIES = frozenset({"native", "a16"})
|
||||
_CONFIG_FIELDS = frozenset({"enabled", "first_steps", "last_steps", "reasoner"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Cosmos3MixedPrecisionConfig:
|
||||
"""Validated precision policy shared by every quantization strategy."""
|
||||
|
||||
first_steps: int = 3
|
||||
last_steps: int = 3
|
||||
reasoner: ReasonerPolicy = "a16"
|
||||
|
||||
@classmethod
|
||||
def from_additional_config(
|
||||
cls,
|
||||
additional_config: Mapping[str, object] | None,
|
||||
) -> Cosmos3MixedPrecisionConfig | None:
|
||||
"""Parse Cosmos3 fields from vLLM-Omni's additional configuration."""
|
||||
_, config = cls.resolve_additional_config(additional_config)
|
||||
return config
|
||||
|
||||
@classmethod
|
||||
def resolve_additional_config(
|
||||
cls,
|
||||
additional_config: Mapping[str, object] | None,
|
||||
) -> tuple[bool, Cosmos3MixedPrecisionConfig | None]:
|
||||
"""Return whether an override was supplied and its effective policy.
|
||||
|
||||
The separate presence bit distinguishes an absent runtime override from
|
||||
an explicit disable. That distinction matters when a checkpoint owns a
|
||||
default policy.
|
||||
"""
|
||||
if additional_config is not None and not isinstance(additional_config, Mapping):
|
||||
raise TypeError("additional_config must be a mapping")
|
||||
values = additional_config or {}
|
||||
if "cosmos3_mixed_precision" not in values:
|
||||
return False, None
|
||||
raw_config = values["cosmos3_mixed_precision"]
|
||||
if not isinstance(raw_config, Mapping):
|
||||
raise TypeError("cosmos3_mixed_precision must be a mapping")
|
||||
unknown = set(raw_config) - _CONFIG_FIELDS
|
||||
if unknown:
|
||||
raise ValueError(f"Unknown cosmos3_mixed_precision fields: {sorted(unknown)}")
|
||||
|
||||
enabled = raw_config.get("enabled", True)
|
||||
if not isinstance(enabled, bool):
|
||||
raise TypeError("cosmos3_mixed_precision.enabled must be a boolean")
|
||||
if not enabled:
|
||||
conflicting = set(raw_config) - {"enabled"}
|
||||
if conflicting:
|
||||
raise ValueError(
|
||||
"cosmos3_mixed_precision.enabled=false cannot be combined with "
|
||||
f"schedule fields: {sorted(conflicting)}"
|
||||
)
|
||||
return True, None
|
||||
|
||||
first_steps = _non_negative_int(
|
||||
raw_config.get("first_steps", 3),
|
||||
"cosmos3_mixed_precision.first_steps",
|
||||
)
|
||||
last_steps = _non_negative_int(
|
||||
raw_config.get("last_steps", 3),
|
||||
"cosmos3_mixed_precision.last_steps",
|
||||
)
|
||||
|
||||
reasoner = str(raw_config.get("reasoner", "a16")).lower()
|
||||
if reasoner not in _REASONER_POLICIES:
|
||||
raise ValueError(
|
||||
f"cosmos3_mixed_precision.reasoner must be one of {sorted(_REASONER_POLICIES)}, got {reasoner!r}"
|
||||
)
|
||||
config = cls(
|
||||
first_steps=first_steps,
|
||||
last_steps=last_steps,
|
||||
reasoner=cast(ReasonerPolicy, reasoner),
|
||||
)
|
||||
if first_steps == 0 and last_steps == 0 and reasoner == "native":
|
||||
return True, None
|
||||
return True, config
|
||||
|
||||
def use_high_precision(self, step_index: int, num_steps: int) -> bool:
|
||||
"""Select the high path for an actual scheduler-step index."""
|
||||
if num_steps <= 0:
|
||||
raise ValueError(f"num_steps must be positive, got {num_steps}")
|
||||
if step_index < 0 or step_index >= num_steps:
|
||||
raise IndexError(f"step_index must be in [0, {num_steps}), got {step_index}")
|
||||
return step_index < self.first_steps or step_index >= num_steps - self.last_steps
|
||||
|
||||
|
||||
def _non_negative_int(value: object, name: str) -> int:
|
||||
"""Validate an integer configuration field without accepting booleans."""
|
||||
if not isinstance(value, int) or isinstance(value, bool) or value < 0:
|
||||
raise TypeError(f"{name} must be a non-negative integer")
|
||||
return value
|
||||
@@ -0,0 +1,116 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Format-agnostic schedule state, linear discovery, and dispatch."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
from vllm.model_executor.layers.linear import LinearBase, LinearMethodBase
|
||||
|
||||
from .config import Cosmos3MixedPrecisionConfig
|
||||
from .strategy import (
|
||||
Cosmos3PrecisionStrategy,
|
||||
Fp8W8A8W8A16Strategy,
|
||||
Nvfp4W4A4W4A16Strategy,
|
||||
)
|
||||
|
||||
PrecisionPath = Literal["reasoner", "generation"]
|
||||
_STRATEGIES: tuple[Cosmos3PrecisionStrategy, ...] = (
|
||||
Fp8W8A8W8A16Strategy(),
|
||||
Nvfp4W4A4W4A16Strategy(),
|
||||
)
|
||||
|
||||
|
||||
def _strategy_for(method: object | None) -> Cosmos3PrecisionStrategy | None:
|
||||
return next((strategy for strategy in _STRATEGIES if strategy.accepts(method)), None)
|
||||
|
||||
|
||||
class Cosmos3MixedPrecisionLinearMethod(LinearMethodBase):
|
||||
"""Dispatch between a checkpoint-native method and dense A16."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_method: LinearMethodBase,
|
||||
strategy: Cosmos3PrecisionStrategy,
|
||||
runtime: Cosmos3MixedPrecisionRuntime,
|
||||
module_name: str,
|
||||
path: PrecisionPath,
|
||||
) -> None:
|
||||
self.base_method = base_method
|
||||
self.strategy = strategy
|
||||
self.runtime = runtime
|
||||
self.module_name = module_name
|
||||
self.path = path
|
||||
|
||||
def create_weights(self, *args, **kwargs) -> None:
|
||||
self.base_method.create_weights(*args, **kwargs)
|
||||
|
||||
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
|
||||
self.strategy.validate_before_processing(
|
||||
self.base_method,
|
||||
layer,
|
||||
self.module_name,
|
||||
)
|
||||
self.base_method.process_weights_after_loading(layer)
|
||||
self.strategy.validate_after_processing(layer, self.module_name)
|
||||
|
||||
def apply(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if not self.runtime.use_high_precision(self.path):
|
||||
return self.base_method.apply(layer, x, bias)
|
||||
return self.strategy.apply_high(layer, x, bias)
|
||||
|
||||
|
||||
class Cosmos3MixedPrecisionRuntime:
|
||||
"""Own one transformer's schedule state and wrapped linear inventory."""
|
||||
|
||||
def __init__(self, config: Cosmos3MixedPrecisionConfig) -> None:
|
||||
self.config = config
|
||||
# TODO: Make this request-local before Cosmos3 supports interleaved
|
||||
# denoising requests on one transformer instance.
|
||||
self._generation_high_precision = False
|
||||
|
||||
def install(self, transformer: torch.nn.Module) -> None:
|
||||
components: dict[PrecisionPath, torch.nn.Module] = {
|
||||
"generation": transformer.gen_layers,
|
||||
}
|
||||
if self.config.reasoner == "a16":
|
||||
components["reasoner"] = transformer.language_model.layers
|
||||
|
||||
wrapped_count = 0
|
||||
for path, component in components.items():
|
||||
for local_name, layer in component.named_modules():
|
||||
if not isinstance(layer, LinearBase):
|
||||
continue
|
||||
base_method = getattr(layer, "quant_method", None)
|
||||
strategy = _strategy_for(base_method)
|
||||
if strategy is None:
|
||||
continue
|
||||
module_name = getattr(layer, "prefix", None) or f"{path}.{local_name}"
|
||||
layer.quant_method = Cosmos3MixedPrecisionLinearMethod(
|
||||
base_method,
|
||||
strategy,
|
||||
self,
|
||||
module_name,
|
||||
path,
|
||||
)
|
||||
wrapped_count += 1
|
||||
|
||||
if not wrapped_count:
|
||||
raise ValueError("Cosmos3 mixed precision found no compatible FP8 or NVFP4 ModelOpt linears")
|
||||
|
||||
def use_high_precision(self, path: PrecisionPath) -> bool:
|
||||
return self.config.reasoner == "a16" if path == "reasoner" else self._generation_high_precision
|
||||
|
||||
def set_step(self, step_index: int, num_steps: int) -> None:
|
||||
self._generation_high_precision = self.config.use_high_precision(step_index, num_steps)
|
||||
|
||||
def reset(self) -> None:
|
||||
self._generation_high_precision = False
|
||||
@@ -0,0 +1,218 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Format-specific live-weight validation and reference A16 materialization."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
ModelOptFp8LinearMethod,
|
||||
ModelOptNvFp4LinearMethod,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.utils import nvfp4_emulation_utils
|
||||
|
||||
_NVFP4_BLOCK_SIZE = 16
|
||||
|
||||
|
||||
class Cosmos3PrecisionStrategy:
|
||||
"""Quantization-format boundary behind the shared precision schedule."""
|
||||
|
||||
def accepts(self, method: object | None) -> bool:
|
||||
"""Return whether this strategy owns a native linear method."""
|
||||
raise NotImplementedError
|
||||
|
||||
def validate_before_processing(
|
||||
self,
|
||||
method: object,
|
||||
layer: torch.nn.Module,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
"""Reject native transforms that cannot support live dequantization."""
|
||||
|
||||
def validate_after_processing(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
"""Validate the live native weight representation."""
|
||||
raise NotImplementedError
|
||||
|
||||
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
|
||||
"""Materialize the live quantized weight as a dense BF16 matrix."""
|
||||
raise NotImplementedError
|
||||
|
||||
def apply_high(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
x: torch.Tensor,
|
||||
bias: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the reference dense A16 path."""
|
||||
input_size = int(layer.input_size_per_partition)
|
||||
output_size = int(layer.output_size_per_partition)
|
||||
weight = self.materialize(layer)
|
||||
expected_shape = (output_size, input_size)
|
||||
if tuple(weight.shape) != expected_shape:
|
||||
raise RuntimeError(f"Dense weight shape {tuple(weight.shape)} does not match {expected_shape}")
|
||||
x_2d = x.reshape(-1, x.shape[-1])
|
||||
if x_2d.shape[1] != input_size:
|
||||
raise ValueError(f"Expected activation width {input_size}, got {x_2d.shape[1]}")
|
||||
weight = weight.to(dtype=x.dtype)
|
||||
if bias is not None and bias.dtype != x.dtype:
|
||||
bias = bias.to(dtype=x.dtype)
|
||||
output = F.linear(x_2d, weight, bias)
|
||||
return output.view(*x.shape[:-1], output_size)
|
||||
|
||||
|
||||
class Fp8W8A8W8A16Strategy(Cosmos3PrecisionStrategy):
|
||||
"""Use native ModelOpt W8A8 or reference dense W8A16."""
|
||||
|
||||
def accepts(self, method: object | None) -> bool:
|
||||
return isinstance(method, ModelOptFp8LinearMethod)
|
||||
|
||||
def validate_before_processing(
|
||||
self,
|
||||
method: object,
|
||||
layer: torch.nn.Module,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
if hasattr(layer, "pre_quant_scale"):
|
||||
raise ValueError(f"{module_name} uses unsupported SmoothQuant pre_quant_scale")
|
||||
weight_scale = getattr(layer, "weight_scale", None)
|
||||
if not isinstance(weight_scale, torch.Tensor) or weight_scale.numel() != 1:
|
||||
raise ValueError(f"{module_name} requires serialized tensorwise FP8 weights")
|
||||
fp8_kernel = getattr(method, "fp8_linear", None)
|
||||
from vllm.model_executor.kernels.linear.scaled_mm.marlin import (
|
||||
MarlinFP8ScaledMMLinearKernel,
|
||||
)
|
||||
|
||||
if isinstance(fp8_kernel, MarlinFP8ScaledMMLinearKernel):
|
||||
raise ValueError(
|
||||
f"{module_name} selected Marlin FP8, which repacks the only weight copy; "
|
||||
"use a backend that retains canonical FP8 weights"
|
||||
)
|
||||
|
||||
def validate_after_processing(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
weight = getattr(layer, "weight", None)
|
||||
scale = getattr(layer, "weight_scale", None)
|
||||
if not isinstance(weight, torch.Tensor) or weight.dtype != torch.float8_e4m3fn:
|
||||
dtype = getattr(weight, "dtype", None)
|
||||
raise TypeError(f"{module_name} requires a canonical FP8 weight, got {dtype}")
|
||||
if weight.ndim != 2:
|
||||
raise ValueError(f"{module_name} requires a rank-2 FP8 weight, got {tuple(weight.shape)}")
|
||||
if not isinstance(scale, torch.Tensor):
|
||||
raise ValueError(f"{module_name} has an FP8 weight but no weight_scale")
|
||||
if scale.numel() != 1:
|
||||
raise ValueError(f"{module_name} requires one live FP8 weight scale")
|
||||
input_size = int(layer.input_size_per_partition)
|
||||
output_size = int(layer.output_size_per_partition)
|
||||
if weight.shape[0] < input_size or weight.shape[1] < output_size:
|
||||
raise ValueError(
|
||||
f"{module_name} live FP8 weight shape {tuple(weight.shape)} does not cover "
|
||||
f"(K, N)=({input_size}, {output_size})"
|
||||
)
|
||||
_validate_positive_finite_scale(scale, module_name)
|
||||
|
||||
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
|
||||
input_size = int(layer.input_size_per_partition)
|
||||
output_size = int(layer.output_size_per_partition)
|
||||
weight = layer.weight[:input_size, :output_size]
|
||||
scale = layer.weight_scale.reshape(1).to(device=weight.device, dtype=torch.float32)
|
||||
return (weight.to(torch.float32) * scale).t().to(torch.bfloat16)
|
||||
|
||||
|
||||
class Nvfp4W4A4W4A16Strategy(Cosmos3PrecisionStrategy):
|
||||
"""Use native ModelOpt W4A4 or reference dense W4A16."""
|
||||
|
||||
def accepts(self, method: object | None) -> bool:
|
||||
return isinstance(method, ModelOptNvFp4LinearMethod)
|
||||
|
||||
def validate_before_processing(
|
||||
self,
|
||||
method: object,
|
||||
layer: torch.nn.Module,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
kernel = getattr(method, "kernel", None)
|
||||
from vllm.model_executor.kernels.linear.nvfp4.cutlass import (
|
||||
CutlassNvFp4LinearKernel,
|
||||
)
|
||||
from vllm.model_executor.kernels.linear.nvfp4.flashinfer import (
|
||||
FlashInferCuteDslNvFp4LinearKernel,
|
||||
FlashInferCutlassNvFp4LinearKernel,
|
||||
)
|
||||
|
||||
compatible_kernels = (
|
||||
CutlassNvFp4LinearKernel,
|
||||
FlashInferCuteDslNvFp4LinearKernel,
|
||||
FlashInferCutlassNvFp4LinearKernel,
|
||||
)
|
||||
if not isinstance(kernel, compatible_kernels):
|
||||
kernel_name = type(kernel).__name__ if kernel is not None else "none"
|
||||
raise ValueError(
|
||||
f"{module_name} selected unsupported NVFP4 backend {kernel_name}; "
|
||||
"live W4A16 dequantization requires a CUTLASS-compatible layout"
|
||||
)
|
||||
global_scale = _nvfp4_global_scale(layer)
|
||||
if global_scale is None or global_scale.numel() != 1:
|
||||
raise ValueError(f"{module_name} is missing ModelOpt NVFP4 scales")
|
||||
|
||||
def validate_after_processing(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
module_name: str,
|
||||
) -> None:
|
||||
packed = getattr(layer, "weight", None)
|
||||
scale = getattr(layer, "weight_scale", None)
|
||||
global_scale = getattr(layer, "weight_global_scale", None)
|
||||
if not isinstance(packed, torch.Tensor) or packed.dtype != torch.uint8:
|
||||
dtype = getattr(packed, "dtype", None)
|
||||
raise TypeError(f"{module_name} requires a live packed NVFP4 weight, got {dtype}")
|
||||
if not isinstance(scale, torch.Tensor) or not isinstance(global_scale, torch.Tensor):
|
||||
raise ValueError(f"{module_name} is missing live NVFP4 scales")
|
||||
output_size = int(layer.output_size_per_partition)
|
||||
input_size = int(layer.input_size_per_partition)
|
||||
if input_size % _NVFP4_BLOCK_SIZE != 0:
|
||||
raise ValueError(f"{module_name} input size {input_size} is not divisible by {_NVFP4_BLOCK_SIZE}")
|
||||
expected_weight = (output_size, input_size // 2)
|
||||
if packed.shape[0] < expected_weight[0] or packed.shape[1] < expected_weight[1]:
|
||||
raise ValueError(
|
||||
f"{module_name} live NVFP4 weight shape {tuple(packed.shape)} does not cover {expected_weight}"
|
||||
)
|
||||
_validate_positive_finite_scale(global_scale, module_name)
|
||||
lut_handle = nvfp4_emulation_utils.kE2M1ToFloat_handle
|
||||
if lut_handle.val.device != packed.device:
|
||||
lut_handle.val = lut_handle.val.to(packed.device)
|
||||
|
||||
def materialize(self, layer: torch.nn.Module) -> torch.Tensor:
|
||||
output_size = int(layer.output_size_per_partition)
|
||||
input_size = int(layer.input_size_per_partition)
|
||||
packed = layer.weight[:output_size, : input_size // 2]
|
||||
return nvfp4_emulation_utils.dequantize_to_dtype(
|
||||
packed,
|
||||
layer.weight_scale,
|
||||
layer.weight_global_scale,
|
||||
torch.bfloat16,
|
||||
_NVFP4_BLOCK_SIZE,
|
||||
True,
|
||||
)
|
||||
|
||||
|
||||
def _validate_positive_finite_scale(scale: torch.Tensor, module_name: str) -> None:
|
||||
values = scale.detach().float()
|
||||
if not torch.isfinite(values).all() or not (values > 0).all():
|
||||
raise ValueError(f"{module_name} has a non-finite or non-positive weight scale")
|
||||
|
||||
|
||||
def _nvfp4_global_scale(layer: torch.nn.Module) -> torch.Tensor | None:
|
||||
for name in ("weight_scale_2", "weight_global_scale"):
|
||||
value = getattr(layer, name, None)
|
||||
if isinstance(value, torch.Tensor):
|
||||
return value
|
||||
return 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
|
||||
"""Cosmos3 text/image/video/sound/action pipeline for vllm-omni.
|
||||
|
||||
One pipeline class serves the Cosmos3 family modes. Output modality is selected
|
||||
@@ -34,6 +34,7 @@ import math
|
||||
import os
|
||||
import time
|
||||
from collections.abc import Iterable, Mapping
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import fields
|
||||
from typing import Any, ClassVar
|
||||
|
||||
@@ -138,6 +139,7 @@ from .utils import (
|
||||
ensure_gripper_array,
|
||||
extract_robolab_image,
|
||||
extract_robolab_prompt_image,
|
||||
get_robolab_domain_id,
|
||||
lazy_action_transform_pipeline,
|
||||
make_robolab_action_postprocess_inputs,
|
||||
next_robolab_seed,
|
||||
@@ -947,6 +949,20 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
model_path = od_config.model
|
||||
local_files_only = os.path.exists(model_path)
|
||||
|
||||
# Validate guidance parallelism from checkpoint metadata before loading
|
||||
# components. Distilled checkpoints have only a conditional branch.
|
||||
scheduler_config = FlowUniPCMultistepScheduler.load_config(
|
||||
model_path,
|
||||
subfolder="scheduler",
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
self.is_distilled_model = scheduler_config.get("_class_name") == COSMOS3_DISTILLED_CHECKPOINT_SCHEDULER_CLASS
|
||||
if self.is_distilled_model and od_config.parallel_config.cfg_parallel_size > 1:
|
||||
raise ValueError(
|
||||
"Distilled Cosmos3 checkpoints run without classifier-free guidance. "
|
||||
"Set --cfg-parallel-size 1 and use --ulysses-degree for multi-GPU inference."
|
||||
)
|
||||
|
||||
# --- Tokenizer ---
|
||||
self.tokenizer = AutoTokenizer.from_pretrained(
|
||||
model_path,
|
||||
@@ -1009,20 +1025,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
logger.info("Cosmos3: session state manager enabled (max_sessions=%d)", mm_max_sessions)
|
||||
|
||||
# --- Scheduler ---
|
||||
# Distilled model differs from regular one only by scheduler,
|
||||
# distilled one uses FlowMatchEulerDiscreteScheduler, while
|
||||
# regular should use FlowUniPCMultistepScheduler
|
||||
|
||||
scheduler_config = FlowUniPCMultistepScheduler.load_config(
|
||||
model_path,
|
||||
subfolder="scheduler",
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
|
||||
scheduler_class_name = scheduler_config.get("_class_name")
|
||||
|
||||
self.is_distilled_model = False
|
||||
if scheduler_class_name == COSMOS3_DISTILLED_CHECKPOINT_SCHEDULER_CLASS:
|
||||
if self.is_distilled_model:
|
||||
fixed_step_config = scheduler_config.get("fixed_step_sampler_config")
|
||||
if not isinstance(fixed_step_config, dict) or fixed_step_config.get("sample_type") != "sde":
|
||||
raise ValueError("Cosmos3 distilled scheduler requires fixed_step_sampler_config.sample_type=sde.")
|
||||
@@ -1034,7 +1037,6 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
stochastic_sampling=True,
|
||||
)
|
||||
self._scheduler_init_t_list = list(t_list)
|
||||
self.is_distilled_model = True
|
||||
else:
|
||||
# Preserve compatible solver settings from the checkpoint, but keep
|
||||
# the base shift neutral. The concrete request shift is applied when
|
||||
@@ -1074,8 +1076,10 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
|
||||
self._guidance_scale = None
|
||||
self._num_timesteps = None
|
||||
self._current_step_index = None
|
||||
self._current_sigma = None
|
||||
self._cosmos3_branch_caches: dict[str, tuple[Any, Any]] | None = None
|
||||
self._robolab_transform = None
|
||||
self._robolab_transforms: dict[bool, Any] = {}
|
||||
|
||||
# Set True by ``enable_cache_for_cosmos3`` when cache-dit is enabled on
|
||||
# this pipeline. Tells the sequential-CFG loop to keep paired
|
||||
@@ -1290,17 +1294,24 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
or a tuple in video, action, sound order for multimodal generation.
|
||||
"""
|
||||
cache_key = kwargs.pop("_cosmos3_cache_key", None)
|
||||
if cache_key is None:
|
||||
return self.transformer(**kwargs)
|
||||
context_name = str(kwargs.pop("_cache_context", "cond"))
|
||||
|
||||
branch_caches = self._cosmos3_branch_caches
|
||||
if branch_caches is None:
|
||||
return self.transformer(**kwargs)
|
||||
|
||||
cache_key = str(cache_key)
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = branch_caches.get(cache_key, (None, None))
|
||||
prediction = self.transformer(**kwargs)
|
||||
branch_caches[cache_key] = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
|
||||
context_factory = getattr(self, "_cache_context_factory", None)
|
||||
context = context_factory(context_name) if callable(context_factory) else nullcontext()
|
||||
with context:
|
||||
if cache_key is None:
|
||||
prediction = self.transformer(**kwargs)
|
||||
else:
|
||||
branch_caches = self._cosmos3_branch_caches
|
||||
if branch_caches is None:
|
||||
prediction = self.transformer(**kwargs)
|
||||
else:
|
||||
cache_key = str(cache_key)
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = branch_caches.get(
|
||||
cache_key, (None, None)
|
||||
)
|
||||
prediction = self.transformer(**kwargs)
|
||||
branch_caches[cache_key] = (self.transformer.cached_kv, self.transformer.cached_freqs_gen)
|
||||
return prediction
|
||||
|
||||
def combine_multi_branch_cfg_noise(
|
||||
@@ -1394,11 +1405,18 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
return val
|
||||
return default
|
||||
|
||||
def _get_robolab_transform(self):
|
||||
if self._robolab_transform is None:
|
||||
def _get_robolab_transform(self, *, format_prompt_as_json: bool = False):
|
||||
transforms = getattr(self, "_robolab_transforms", None)
|
||||
if transforms is None:
|
||||
transforms = {}
|
||||
self._robolab_transforms = transforms
|
||||
if format_prompt_as_json not in transforms:
|
||||
action_dim = int(getattr(self.transformer, "action_dim", 64))
|
||||
self._robolab_transform = lazy_action_transform_pipeline(action_dim)
|
||||
return self._robolab_transform
|
||||
transforms[format_prompt_as_json] = lazy_action_transform_pipeline(
|
||||
action_dim,
|
||||
format_prompt_as_json=format_prompt_as_json,
|
||||
)
|
||||
return transforms[format_prompt_as_json]
|
||||
|
||||
def _build_robolab_policy_inputs(
|
||||
self,
|
||||
@@ -1443,7 +1461,8 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
resolution = str(extra_param("resolution", ROBOLAB_DEFAULT_RESOLUTION))
|
||||
fps = float(extra_param("conditioning_fps", ROBOLAB_DEFAULT_CONDITIONING_FPS))
|
||||
domain_name = str(extra_param("domain_name", ROBOLAB_DEFAULT_DOMAIN_NAME))
|
||||
domain_id = resolve_domain_id(domain_name=domain_name, require_explicit=True)
|
||||
domain_id = get_robolab_domain_id(domain_name)
|
||||
format_prompt_as_json = self._truthy(extra_param("format_prompt_as_json", False))
|
||||
|
||||
if use_state and history_length < 1:
|
||||
raise ValueError("RoboLab history_length must be >= 1 when use_state is true.")
|
||||
@@ -1506,7 +1525,9 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
"action": action,
|
||||
# Cosmos Framework consumes this as an integer conditioning bucket.
|
||||
"conditioning_fps": torch.tensor(fps, dtype=torch.long),
|
||||
"mode": ACTION_MODE_POLICY,
|
||||
# Cosmos Framework 1.2 renamed the internal policy transform mode to
|
||||
# ``wam``. The public vLLM action_mode remains ``policy``.
|
||||
"mode": "wam",
|
||||
"domain_id": torch.tensor(domain_id, dtype=torch.long),
|
||||
"viewpoint": "concat_view",
|
||||
"additional_view_description": ROBOLAB_CONCAT_VIEW_DESCRIPTION,
|
||||
@@ -1514,7 +1535,9 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
if history_action is not None:
|
||||
sample["history_action"] = history_action
|
||||
|
||||
sample = self._get_robolab_transform()(sample, resolution)
|
||||
sample = self._get_robolab_transform(format_prompt_as_json=format_prompt_as_json)(sample, resolution)
|
||||
if isinstance(sample.get("ai_caption"), dict):
|
||||
sample["ai_caption"] = json.dumps(sample["ai_caption"])
|
||||
sequence_plan = sample["sequence_plan"]
|
||||
video_tensor = sample["video"].float() / 127.5 - 1.0
|
||||
raw_action_dim_tensor = sample.get("raw_action_dim")
|
||||
@@ -1798,6 +1821,11 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
|
||||
def _resolve_guidance_scale(self, sp: OmniDiffusionSamplingParams, default: float) -> float:
|
||||
if self.is_distilled_model:
|
||||
if sp.guidance_scale_provided and float(sp.guidance_scale) != 1.0:
|
||||
logger.warning_once(
|
||||
"Distilled Cosmos3 checkpoints run without classifier-free guidance. "
|
||||
"The requested guidance_scale is overridden to 1.0; negative_prompt does not affect generation."
|
||||
)
|
||||
return 1.0
|
||||
if sp.guidance_scale_provided:
|
||||
return float(sp.guidance_scale)
|
||||
@@ -1822,6 +1850,39 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
def num_timesteps(self):
|
||||
return self._num_timesteps
|
||||
|
||||
@property
|
||||
def current_step_index(self):
|
||||
return self._current_step_index
|
||||
|
||||
@property
|
||||
def current_sigma(self):
|
||||
return self._current_sigma
|
||||
|
||||
def _set_denoise_step_metadata(
|
||||
self,
|
||||
step_index: int,
|
||||
timesteps: torch.Tensor,
|
||||
scheduler: Any,
|
||||
) -> None:
|
||||
self._current_step_index = step_index
|
||||
self._num_timesteps = len(timesteps)
|
||||
sigmas = getattr(scheduler, "sigmas", None)
|
||||
self._current_sigma = sigmas[step_index] if sigmas is not None and step_index < len(sigmas) else None
|
||||
|
||||
def _clear_denoise_step_metadata(self) -> None:
|
||||
self._current_step_index = None
|
||||
self._current_sigma = None
|
||||
|
||||
def _set_mixed_precision_step(self, step_index: int, num_steps: int) -> None:
|
||||
setter = getattr(self.transformer, "set_mixed_precision_step", None)
|
||||
if setter is not None:
|
||||
setter(step_index, num_steps)
|
||||
|
||||
def _reset_mixed_precision(self) -> None:
|
||||
resetter = getattr(self.transformer, "reset_mixed_precision", None)
|
||||
if resetter is not None:
|
||||
resetter()
|
||||
|
||||
@staticmethod
|
||||
def _distilled_unsupported_error(detail: str) -> ValueError:
|
||||
return ValueError(
|
||||
@@ -2819,7 +2880,9 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
# Each CFG-parallel rank runs exactly one branch (rank 0 -> cond,
|
||||
# else uncond), so session keying loads/stores only this rank's branch.
|
||||
cfg_rank_is_negative = get_classifier_free_guidance_rank() != 0
|
||||
for t in self.progress_bar(timesteps):
|
||||
for step_index, t in enumerate(self.progress_bar(timesteps)):
|
||||
self._set_denoise_step_metadata(step_index, timesteps, step_scheduler)
|
||||
self._set_mixed_precision_step(step_index, len(timesteps))
|
||||
timestep = t.unsqueeze(0)
|
||||
# Outside the interval, scale=1 makes the combined output equal
|
||||
# the cond branch. Every rank remains on the same iteration and
|
||||
@@ -2830,6 +2893,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
do_true_cfg=True,
|
||||
true_cfg_scale=step_scale,
|
||||
positive_kwargs=dict(
|
||||
_cache_context="cond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
@@ -2839,6 +2903,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
**shared_kwargs,
|
||||
),
|
||||
negative_kwargs=dict(
|
||||
_cache_context="uncond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
@@ -2858,13 +2923,16 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
uncond_cache: tuple = (None, None)
|
||||
keep_uncond_for_cache = self._cache_requires_paired_cfg()
|
||||
|
||||
for t in self.progress_bar(timesteps):
|
||||
for step_index, t in enumerate(self.progress_bar(timesteps)):
|
||||
self._set_denoise_step_metadata(step_index, timesteps, step_scheduler)
|
||||
self._set_mixed_precision_step(step_index, len(timesteps))
|
||||
timestep = t.unsqueeze(0)
|
||||
cfg_active = _cfg_active_at(t)
|
||||
|
||||
if not self._kv_load_und(kv_state, is_negative=False):
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = cond_cache
|
||||
noise_cond = self.transformer(
|
||||
noise_cond = self.predict_noise(
|
||||
_cache_context="cond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
@@ -2881,7 +2949,8 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
if cfg_active or keep_uncond_for_cache:
|
||||
if not self._kv_load_und(kv_state, is_negative=True):
|
||||
self.transformer.cached_kv, self.transformer.cached_freqs_gen = uncond_cache
|
||||
noise_uncond = self.transformer(
|
||||
noise_uncond = self.predict_noise(
|
||||
_cache_context="uncond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
@@ -2912,10 +2981,13 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
else:
|
||||
# No CFG: a single cond branch per step. Bespoke (state None) keeps
|
||||
# using the transformer-instance cache exactly as before.
|
||||
for t in self.progress_bar(timesteps):
|
||||
for step_index, t in enumerate(self.progress_bar(timesteps)):
|
||||
self._set_denoise_step_metadata(step_index, timesteps, step_scheduler)
|
||||
self._set_mixed_precision_step(step_index, len(timesteps))
|
||||
timestep = t.unsqueeze(0)
|
||||
self._kv_load_und(kv_state, is_negative=False)
|
||||
noise_pred = self.transformer(
|
||||
noise_pred = self.predict_noise(
|
||||
_cache_context="cond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
@@ -2928,6 +3000,8 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
self._kv_capture_und(kv_state, is_negative=False)
|
||||
_assign_step_out(_step(noise_pred, t, latents, action_latents, sound_latents))
|
||||
finally:
|
||||
self._clear_denoise_step_metadata()
|
||||
self._reset_mixed_precision()
|
||||
# Cosmos3 currently receives a unique request_id rather than a
|
||||
# reusable rollout session id. Retaining its state would only pin
|
||||
# K/V buffers on device after this generation finishes.
|
||||
@@ -3112,7 +3186,9 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
self.transformer.reset_cache()
|
||||
self._cosmos3_branch_caches = {}
|
||||
try:
|
||||
for t in self.progress_bar(timesteps):
|
||||
for step_index, t in enumerate(self.progress_bar(timesteps)):
|
||||
self._set_denoise_step_metadata(step_index, timesteps, self.scheduler)
|
||||
self._set_mixed_precision_step(step_index, len(timesteps))
|
||||
timestep = t.unsqueeze(0)
|
||||
step_guidance = guidance_scale if _active_at(t, guidance_interval) else 1.0
|
||||
step_control = control_guidance if _active_at(t, control_guidance_interval) else 1.0
|
||||
@@ -3120,6 +3196,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
needs_control_cfg = step_control != 1.0
|
||||
|
||||
cond_full_kwargs = dict(
|
||||
_cache_context="cond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
@@ -3133,6 +3210,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
branches_kwargs = [
|
||||
cond_full_kwargs,
|
||||
dict(
|
||||
_cache_context="cond_no_control",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
@@ -3142,6 +3220,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
**shared_kwargs,
|
||||
),
|
||||
dict(
|
||||
_cache_context="uncond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
@@ -3167,6 +3246,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
branches_kwargs = [
|
||||
cond_full_kwargs,
|
||||
dict(
|
||||
_cache_context="cond_no_control",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=cond_ids,
|
||||
@@ -3190,6 +3270,7 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
branches_kwargs = [
|
||||
cond_full_kwargs,
|
||||
dict(
|
||||
_cache_context="uncond",
|
||||
hidden_states=latents,
|
||||
timestep=timestep,
|
||||
text_ids=uncond_ids,
|
||||
@@ -3224,6 +3305,8 @@ class Cosmos3OmniDiffusersPipeline(
|
||||
)[0]
|
||||
latents = velocity_mask * latents + (1.0 - velocity_mask) * condition_latents
|
||||
finally:
|
||||
self._clear_denoise_step_metadata()
|
||||
self._reset_mixed_precision()
|
||||
self._cosmos3_branch_caches = None
|
||||
self.transformer.reset_cache()
|
||||
return latents
|
||||
|
||||
@@ -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 VFM Transformer for vllm-omni.
|
||||
|
||||
Implements the Mixture-of-Transformers architecture with two pathways:
|
||||
@@ -14,7 +14,7 @@ from __future__ import annotations
|
||||
import math
|
||||
from collections.abc import Iterator
|
||||
from contextlib import AbstractContextManager, contextmanager, nullcontext
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -40,6 +40,12 @@ from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_
|
||||
from vllm_omni.diffusion.layers.norm import RMSNorm as _VllmRMSNorm
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .mixed_precision import (
|
||||
Cosmos3MixedPrecisionConfig,
|
||||
Cosmos3MixedPrecisionRuntime,
|
||||
resolve_mixed_precision_config,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.offloader.sequential_backend import SequentialOffloadHook
|
||||
|
||||
@@ -136,6 +142,26 @@ def _od_config_get(od_config: Any, key: str, default: Any = None) -> Any:
|
||||
return default if value is None else value
|
||||
|
||||
|
||||
def _validate_mixed_precision_runtime(
|
||||
config: Cosmos3MixedPrecisionConfig | None,
|
||||
od_config: OmniDiffusionConfig,
|
||||
) -> None:
|
||||
if config is None:
|
||||
return
|
||||
if get_tensor_model_parallel_world_size() != 1:
|
||||
raise ValueError("Cosmos3 mixed precision currently supports tensor parallel size 1 only")
|
||||
if int(getattr(od_config, "max_num_seqs", 1)) != 1:
|
||||
raise ValueError("Cosmos3 mixed precision currently supports one active request per worker")
|
||||
if bool(getattr(od_config, "enable_distributed_layerwise_offload", False)):
|
||||
raise ValueError(
|
||||
"Cosmos3 mixed precision does not support distributed layer-wise offload "
|
||||
"because its direct loader bypasses ModelOpt post-load transformations"
|
||||
)
|
||||
parallel_config = getattr(od_config, "parallel_config", None)
|
||||
if bool(getattr(parallel_config, "use_hsdp", False)):
|
||||
raise ValueError("Cosmos3 mixed precision has not validated live backend weights under HSDP")
|
||||
|
||||
|
||||
def _as_bool(value: Any) -> bool:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
@@ -401,7 +427,7 @@ class TimestepEmbedder(nn.Module):
|
||||
max_period: int = 10000,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
# Following diffusers naming pattern here for checkpoint compatibility.
|
||||
# Preserve checkpoint-compatible parameter names.
|
||||
self.linear_1 = nn.Linear(frequency_embedding_size, hidden_size, bias=True)
|
||||
self.act = nn.SiLU()
|
||||
self.linear_2 = nn.Linear(hidden_size, hidden_size, bias=True)
|
||||
@@ -1079,6 +1105,28 @@ class Cosmos3GenSPPrepare(nn.Module):
|
||||
return hidden_gen, freqs_cos, freqs_sin
|
||||
|
||||
|
||||
class _GenPrepared(NamedTuple):
|
||||
"""GEN-pathway state shared by normal and cached execution."""
|
||||
|
||||
hidden_gen: torch.Tensor
|
||||
time_embed: torch.Tensor
|
||||
t: int
|
||||
h: int
|
||||
w: int
|
||||
s_video: int
|
||||
s_control: int
|
||||
s_action: int
|
||||
s_sound: int
|
||||
has_control: bool
|
||||
has_action: bool
|
||||
has_sound: bool
|
||||
action_domain_ids: torch.Tensor | None
|
||||
ulysses_size: int
|
||||
use_multi_control_attention: bool
|
||||
multi_control_token_sizes: tuple[int, ...] | None
|
||||
multi_control_weights: tuple[float, ...] | None
|
||||
|
||||
|
||||
class Cosmos3VFMTransformer(nn.Module):
|
||||
"""Cosmos3 VFM Transformer: UND language model + GEN denoising layers.
|
||||
|
||||
@@ -1241,6 +1289,19 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
|
||||
dtype = od_config.dtype
|
||||
quant_config = getattr(od_config, "quantization_config", None) if od_config else None
|
||||
mixed_precision_config, mixed_precision_source = resolve_mixed_precision_config(od_config)
|
||||
if mixed_precision_config is None:
|
||||
if mixed_precision_source == "additional_config_disabled":
|
||||
logger.info("Cosmos3 checkpoint mixed-precision policy disabled by additional_config")
|
||||
else:
|
||||
logger.info(
|
||||
"Cosmos3 mixed precision active (source=%s): first_steps=%d last_steps=%d reasoner=%s",
|
||||
mixed_precision_source,
|
||||
mixed_precision_config.first_steps,
|
||||
mixed_precision_config.last_steps,
|
||||
mixed_precision_config.reasoner,
|
||||
)
|
||||
_validate_mixed_precision_runtime(mixed_precision_config, od_config)
|
||||
|
||||
self.language_model = self._language_model_cls(
|
||||
hidden_size=self.hidden_size,
|
||||
@@ -1300,6 +1361,11 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
]
|
||||
)
|
||||
|
||||
self.mixed_precision_runtime: Cosmos3MixedPrecisionRuntime | None = None
|
||||
if mixed_precision_config is not None:
|
||||
self.mixed_precision_runtime = Cosmos3MixedPrecisionRuntime(mixed_precision_config)
|
||||
self.mixed_precision_runtime.install(self)
|
||||
|
||||
self.norm_moe_gen = RMSNorm(self.hidden_size, eps=self.rms_norm_eps)
|
||||
self.gen_sp_prepare = Cosmos3GenSPPrepare()
|
||||
self.gen_sp_gather = nn.Identity()
|
||||
@@ -1631,6 +1697,61 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
pad = (-(base + sound_frames)) % ulysses_size
|
||||
return sound_frames + pad
|
||||
|
||||
def _run_gen_layers(
|
||||
self,
|
||||
hidden_gen: torch.Tensor,
|
||||
*,
|
||||
s_video: int,
|
||||
s_control: int,
|
||||
s_action: int,
|
||||
s_sound: int,
|
||||
has_action: bool,
|
||||
has_sound: bool,
|
||||
has_control: bool,
|
||||
ulysses_size: int,
|
||||
use_multi_control_attention: bool,
|
||||
multi_control_token_sizes: tuple[int, ...] | None,
|
||||
multi_control_weights: tuple[float, ...] | None,
|
||||
) -> torch.Tensor:
|
||||
"""Run the complete GEN decoder between full-layout boundaries."""
|
||||
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.")
|
||||
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)
|
||||
freqs_gen = (freqs_cos, freqs_sin)
|
||||
|
||||
if len(self.gen_layers) == len(self.cached_kv):
|
||||
for layer, (k_und, v_und) in zip(self.gen_layers, self.cached_kv, strict=True):
|
||||
hidden_gen = layer(
|
||||
hidden_gen,
|
||||
k_und=k_und,
|
||||
v_und=v_und,
|
||||
freqs_cos=freqs_cos,
|
||||
freqs_sin=freqs_sin,
|
||||
control_token_sizes=multi_control_token_sizes,
|
||||
control_weights=multi_control_weights,
|
||||
)
|
||||
# Cache-dit's block wrapper may return a tuple; unwrap it.
|
||||
if isinstance(hidden_gen, tuple):
|
||||
hidden_gen = hidden_gen[0]
|
||||
else:
|
||||
# Cache-dit patches gen_layers to a grouped wrapper.
|
||||
for layer in self.gen_layers:
|
||||
hidden_gen = layer(
|
||||
hidden_gen,
|
||||
cached_kv=self.cached_kv,
|
||||
freqs_gen=freqs_gen,
|
||||
control_token_sizes=multi_control_token_sizes,
|
||||
control_weights=multi_control_weights,
|
||||
)
|
||||
if isinstance(hidden_gen, tuple):
|
||||
hidden_gen = hidden_gen[0]
|
||||
|
||||
if not use_multi_control_attention:
|
||||
hidden_gen = self.gen_sp_gather(hidden_gen)
|
||||
return hidden_gen
|
||||
|
||||
# -- Forward -------------------------------------------------------------
|
||||
|
||||
def forward(
|
||||
@@ -1653,7 +1774,51 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
transfer_share_vision_temporal_positions: bool = True,
|
||||
**kwargs,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, ...]:
|
||||
"""Run the shared Cosmos3 GEN preprocess, stack, and postprocess path."""
|
||||
if kwargs:
|
||||
raise TypeError(f"Unexpected Cosmos3 transformer kwargs: {sorted(kwargs)}")
|
||||
prep = self._gen_preprocess(
|
||||
hidden_states,
|
||||
timestep,
|
||||
text_ids,
|
||||
text_mask,
|
||||
video_shape,
|
||||
fps=fps,
|
||||
action_latents=action_latents,
|
||||
action_domain_ids=action_domain_ids,
|
||||
action_noisy_mask=action_noisy_mask,
|
||||
action_start_frame_offset=action_start_frame_offset,
|
||||
action_fps=action_fps,
|
||||
sound_latents=sound_latents,
|
||||
noisy_frame_mask=noisy_frame_mask,
|
||||
control_latents=control_latents,
|
||||
control_weights=control_weights,
|
||||
transfer_share_vision_temporal_positions=transfer_share_vision_temporal_positions,
|
||||
)
|
||||
return self._gen_postprocess(self._run_gen_stack(prep), prep)
|
||||
|
||||
def _gen_preprocess(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
timestep: torch.Tensor,
|
||||
text_ids: torch.Tensor,
|
||||
text_mask: torch.Tensor,
|
||||
video_shape: tuple[int, int, int],
|
||||
fps: float | None = None,
|
||||
action_latents: torch.Tensor | None = None,
|
||||
action_domain_ids: torch.Tensor | None = None,
|
||||
action_noisy_mask: torch.Tensor | None = None,
|
||||
action_start_frame_offset: int = 1,
|
||||
action_fps: float | None = None,
|
||||
sound_latents: torch.Tensor | None = None,
|
||||
noisy_frame_mask: torch.Tensor | None = None,
|
||||
control_latents: list[torch.Tensor] | tuple[torch.Tensor, ...] | torch.Tensor | None = None,
|
||||
control_weights: list[float] | tuple[float, ...] | torch.Tensor | None = None,
|
||||
transfer_share_vision_temporal_positions: bool = True,
|
||||
) -> _GenPrepared:
|
||||
"""
|
||||
Prepare the packed GEN sequence before its cacheable execution region.
|
||||
|
||||
Args:
|
||||
hidden_states: [B, C, t, h, w] noisy latents
|
||||
timestep: [B] diffusion timestep
|
||||
@@ -1676,13 +1841,9 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
transfer controls. Values are normalized to sum to one.
|
||||
|
||||
Returns:
|
||||
[B, C, t, h, w] velocity prediction, or
|
||||
tuple outputs in video, action, sound order when action/sound streams
|
||||
are provided. Transfer-control streams condition the video prediction
|
||||
and are not returned.
|
||||
Packed GEN inputs and metadata consumed by the shared execution and
|
||||
postprocessing helpers.
|
||||
"""
|
||||
if kwargs:
|
||||
raise TypeError(f"Unexpected Cosmos3 transformer kwargs: {sorted(kwargs)}")
|
||||
t, h, w = video_shape
|
||||
hp, wp, _, _ = self._pad_to_patch_size(h, w)
|
||||
text_lengths = text_mask.sum(dim=1)
|
||||
@@ -1882,79 +2043,90 @@ class Cosmos3VFMTransformer(nn.Module):
|
||||
hidden_parts.append(hidden_sound)
|
||||
hidden_gen = torch.cat(hidden_parts, dim=1)
|
||||
|
||||
# Run GEN layers. UND K/V (replicated) is passed to each layer;
|
||||
# the Cosmos3CrossAttention forwards them as joint_key/value so the
|
||||
# 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.")
|
||||
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)
|
||||
freqs_gen = (freqs_cos, freqs_sin)
|
||||
return _GenPrepared(
|
||||
hidden_gen=hidden_gen,
|
||||
time_embed=time_embed,
|
||||
t=t,
|
||||
h=h,
|
||||
w=w,
|
||||
s_video=s_video,
|
||||
s_control=s_control,
|
||||
s_action=s_action,
|
||||
s_sound=s_sound,
|
||||
has_control=has_control,
|
||||
has_action=has_action,
|
||||
has_sound=has_sound,
|
||||
action_domain_ids=action_domain_ids,
|
||||
ulysses_size=ulysses_size,
|
||||
use_multi_control_attention=use_multi_control_attention,
|
||||
multi_control_token_sizes=multi_control_token_sizes,
|
||||
multi_control_weights=multi_control_weights,
|
||||
)
|
||||
|
||||
if len(self.gen_layers) == len(self.cached_kv):
|
||||
for layer, (k_und, v_und) in zip(self.gen_layers, self.cached_kv, strict=True):
|
||||
hidden_gen = layer(
|
||||
hidden_gen,
|
||||
k_und=k_und,
|
||||
v_und=v_und,
|
||||
freqs_cos=freqs_cos,
|
||||
freqs_sin=freqs_sin,
|
||||
control_token_sizes=multi_control_token_sizes,
|
||||
control_weights=multi_control_weights,
|
||||
)
|
||||
# Cache-dit's block wrapper may return a tuple; unwrap it.
|
||||
if isinstance(hidden_gen, tuple):
|
||||
hidden_gen = hidden_gen[0]
|
||||
else:
|
||||
# Cache-dit patches gen_layers to a grouped wrapper.
|
||||
for layer in self.gen_layers:
|
||||
hidden_gen = layer(
|
||||
hidden_gen,
|
||||
cached_kv=self.cached_kv,
|
||||
freqs_gen=freqs_gen,
|
||||
control_token_sizes=multi_control_token_sizes,
|
||||
control_weights=multi_control_weights,
|
||||
)
|
||||
if isinstance(hidden_gen, tuple):
|
||||
hidden_gen = hidden_gen[0]
|
||||
def _run_gen_stack(self, prep: _GenPrepared) -> torch.Tensor:
|
||||
"""Execute the cacheable full-layout GEN stack, including final norm."""
|
||||
hidden_gen = self._run_gen_layers(
|
||||
prep.hidden_gen,
|
||||
s_video=prep.s_video,
|
||||
s_control=prep.s_control,
|
||||
s_action=prep.s_action,
|
||||
s_sound=prep.s_sound,
|
||||
has_action=prep.has_action,
|
||||
has_sound=prep.has_sound,
|
||||
has_control=prep.has_control,
|
||||
ulysses_size=prep.ulysses_size,
|
||||
use_multi_control_attention=prep.use_multi_control_attention,
|
||||
multi_control_token_sizes=prep.multi_control_token_sizes,
|
||||
multi_control_weights=prep.multi_control_weights,
|
||||
)
|
||||
return self.norm_moe_gen(hidden_gen)
|
||||
|
||||
if not use_multi_control_attention:
|
||||
hidden_gen = self.gen_sp_gather(hidden_gen)
|
||||
def _gen_postprocess(
|
||||
self,
|
||||
hidden_gen: torch.Tensor,
|
||||
prep: _GenPrepared,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, ...]:
|
||||
"""Project an already-normalized packed GEN state to model outputs."""
|
||||
if not prep.has_action and not prep.has_sound and not prep.has_control:
|
||||
return self.unpatchify(self.proj_out(hidden_gen), prep.t, prep.h, prep.w)
|
||||
|
||||
# Final norm and project back to latent space
|
||||
hidden_gen = self.norm_moe_gen(hidden_gen)
|
||||
if not has_action and not has_sound and not has_control:
|
||||
return self.unpatchify(self.proj_out(hidden_gen), t, h, w)
|
||||
|
||||
split_sizes = []
|
||||
if has_control:
|
||||
split_sizes.append(s_control)
|
||||
split_sizes.append(s_video)
|
||||
if has_action:
|
||||
split_sizes.append(s_action)
|
||||
if has_sound:
|
||||
split_sizes.append(s_sound)
|
||||
split_hidden = hidden_gen.split(split_sizes, dim=1)
|
||||
split_idx = 0
|
||||
if has_control:
|
||||
split_idx += 1
|
||||
hidden_video = split_hidden[split_idx]
|
||||
split_sizes = []
|
||||
if prep.has_control:
|
||||
split_sizes.append(prep.s_control)
|
||||
split_sizes.append(prep.s_video)
|
||||
if prep.has_action:
|
||||
split_sizes.append(prep.s_action)
|
||||
if prep.has_sound:
|
||||
split_sizes.append(prep.s_sound)
|
||||
split_hidden = hidden_gen.split(split_sizes, dim=1)
|
||||
split_idx = 0
|
||||
if prep.has_control:
|
||||
split_idx += 1
|
||||
video_pred = self.unpatchify(self.proj_out(hidden_video), t, h, w)
|
||||
if has_control:
|
||||
return video_pred
|
||||
outputs: list[torch.Tensor] = [video_pred]
|
||||
if has_action:
|
||||
hidden_action = split_hidden[split_idx]
|
||||
split_idx += 1
|
||||
assert action_domain_ids is not None
|
||||
outputs.append(self.unpack_action(self.action_proj_out(hidden_action, action_domain_ids)))
|
||||
if has_sound:
|
||||
hidden_sound = split_hidden[split_idx]
|
||||
outputs.append(self.unpack_sound(self.audio_proj_out(hidden_sound)))
|
||||
return tuple(outputs)
|
||||
hidden_video = split_hidden[split_idx]
|
||||
split_idx += 1
|
||||
video_pred = self.unpatchify(self.proj_out(hidden_video), prep.t, prep.h, prep.w)
|
||||
if prep.has_control:
|
||||
return video_pred
|
||||
|
||||
outputs: list[torch.Tensor] = [video_pred]
|
||||
if prep.has_action:
|
||||
hidden_action = split_hidden[split_idx]
|
||||
split_idx += 1
|
||||
assert prep.action_domain_ids is not None
|
||||
outputs.append(self.unpack_action(self.action_proj_out(hidden_action, prep.action_domain_ids)))
|
||||
if prep.has_sound:
|
||||
hidden_sound = split_hidden[split_idx]
|
||||
outputs.append(self.unpack_sound(self.audio_proj_out(hidden_sound)))
|
||||
return tuple(outputs)
|
||||
|
||||
def post_load_weights(self) -> None:
|
||||
"""Post-load processing: ensure correct dtypes."""
|
||||
self.time_embedder.to(torch.float32)
|
||||
|
||||
def set_mixed_precision_step(self, step_index: int, num_steps: int) -> None:
|
||||
if self.mixed_precision_runtime is not None:
|
||||
self.mixed_precision_runtime.set_step(step_index, num_steps)
|
||||
|
||||
def reset_mixed_precision(self) -> None:
|
||||
if self.mixed_precision_runtime is not None:
|
||||
self.mixed_precision_runtime.reset()
|
||||
@@ -78,6 +78,12 @@ ROBOLAB_CONCAT_VIEW_DESCRIPTION = (
|
||||
"sides, with the robot visible."
|
||||
)
|
||||
|
||||
_LEGACY_EMBODIMENT_ALIASES = {
|
||||
"galbot": "embodiment_b",
|
||||
"agibot_gear_gripper": "embodiment_c_gripper",
|
||||
"agibot_gear_gripper_ext": "embodiment_c_gripper_ext",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RoboLabPolicyInputs:
|
||||
@@ -252,33 +258,83 @@ def extract_robolab_prompt_image(prompt_data: Any | None) -> np.ndarray | None:
|
||||
return ensure_rgb_uint8_image(image, "multi_modal_data.image")
|
||||
|
||||
|
||||
_ROBOLAB_FRAMEWORK_IMPORT_ERROR = (
|
||||
"Cosmos3 RoboLab policy serving requires a compatible cosmos_framework source on PYTHONPATH."
|
||||
)
|
||||
_ROBOLAB_FRAMEWORK_IMPORTS: dict[str, tuple[str, str]] = {
|
||||
"ActionTransformPipeline": (
|
||||
"cosmos_framework.data.generator.action.utils.transforms",
|
||||
"ActionTransformPipeline",
|
||||
),
|
||||
"convert_rotation": (
|
||||
"cosmos_framework.data.generator.action.utils.pose_utils",
|
||||
"convert_rotation",
|
||||
),
|
||||
"pose_abs_to_rel": (
|
||||
"cosmos_framework.data.generator.action.utils.pose_utils",
|
||||
"pose_abs_to_rel",
|
||||
),
|
||||
"pose_rel_to_abs": (
|
||||
"cosmos_framework.data.generator.action.utils.pose_utils",
|
||||
"pose_rel_to_abs",
|
||||
),
|
||||
"build_abs_pose_from_components": (
|
||||
"cosmos_framework.data.generator.action.utils.pose_utils",
|
||||
"build_abs_pose_from_components",
|
||||
),
|
||||
"FlowUniPCMultistepScheduler": (
|
||||
"cosmos_framework.model.generator.diffusion.samplers.fm_solvers_unipc",
|
||||
"FlowUniPCMultistepScheduler",
|
||||
),
|
||||
"get_domain_id": (
|
||||
"cosmos_framework.data.generator.action.utils.domain_utils",
|
||||
"get_domain_id",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def lazy_import(module_name: str, symbol_name: str, error_message: str):
|
||||
try:
|
||||
module = import_module(module_name)
|
||||
except ModuleNotFoundError as exc:
|
||||
raise ModuleNotFoundError(error_message) from exc
|
||||
return getattr(module, symbol_name)
|
||||
return getattr(module, symbol_name)
|
||||
except (ImportError, AttributeError) as exc:
|
||||
raise ImportError(
|
||||
f"{error_message} Could not import required symbol {symbol_name!r} from {module_name!r}."
|
||||
) from exc
|
||||
|
||||
|
||||
def lazy_action_transform_pipeline(max_action_dim: int):
|
||||
ActionTransformPipeline = lazy_import(
|
||||
"cosmos_framework.data.vfm.action.transforms",
|
||||
"ActionTransformPipeline",
|
||||
"Cosmos3 RoboLab policy serving requires cosmos_framework on PYTHONPATH so the "
|
||||
"golden ActionTransformPipeline can be reused.",
|
||||
def _load_robolab_framework_symbol(symbol_name: str):
|
||||
module_name, exported_name = _ROBOLAB_FRAMEWORK_IMPORTS[symbol_name]
|
||||
return lazy_import(
|
||||
module_name,
|
||||
exported_name,
|
||||
_ROBOLAB_FRAMEWORK_IMPORT_ERROR,
|
||||
)
|
||||
return ActionTransformPipeline(max_action_dim=max_action_dim, cfg_dropout_rate=0.0)
|
||||
|
||||
|
||||
def preflight_cosmos3_action_framework_imports() -> None:
|
||||
"""Validate every Cosmos Framework symbol used by action policy serving."""
|
||||
for symbol_name in _ROBOLAB_FRAMEWORK_IMPORTS:
|
||||
_load_robolab_framework_symbol(symbol_name)
|
||||
|
||||
|
||||
def lazy_action_transform_pipeline(max_action_dim: int, *, format_prompt_as_json: bool = False):
|
||||
ActionTransformPipeline = _load_robolab_framework_symbol("ActionTransformPipeline")
|
||||
return ActionTransformPipeline(
|
||||
max_action_dim=max_action_dim,
|
||||
cfg_dropout_rate=0.0,
|
||||
format_prompt_as_json=format_prompt_as_json,
|
||||
)
|
||||
|
||||
|
||||
def get_robolab_domain_id(domain_name: str) -> int:
|
||||
get_domain_id = _load_robolab_framework_symbol("get_domain_id")
|
||||
canonical_name = _LEGACY_EMBODIMENT_ALIASES.get(domain_name.lower().strip(), domain_name)
|
||||
return int(get_domain_id(canonical_name))
|
||||
|
||||
|
||||
def build_robolab_unipc_scheduler(num_steps: int, shift: float, device: torch.device):
|
||||
FlowUniPCMultistepScheduler = lazy_import(
|
||||
"cosmos_framework.model.vfm.diffusion.samplers.fm_solvers_unipc",
|
||||
"FlowUniPCMultistepScheduler",
|
||||
(
|
||||
"Cosmos3 RoboLab policy serving requires cosmos_framework on PYTHONPATH so the "
|
||||
"golden FlowUniPCMultistepScheduler can be reused."
|
||||
),
|
||||
)
|
||||
FlowUniPCMultistepScheduler = _load_robolab_framework_symbol("FlowUniPCMultistepScheduler")
|
||||
|
||||
scheduler = FlowUniPCMultistepScheduler(
|
||||
num_train_timesteps=1000,
|
||||
@@ -290,38 +346,22 @@ def build_robolab_unipc_scheduler(num_steps: int, shift: float, device: torch.de
|
||||
|
||||
|
||||
def convert_midtrain_rotation(value: Any, src: str, dst: str) -> np.ndarray:
|
||||
convert_rotation = lazy_import(
|
||||
"cosmos_framework.data.vfm.action.pose_utils",
|
||||
"convert_rotation",
|
||||
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
|
||||
)
|
||||
convert_rotation = _load_robolab_framework_symbol("convert_rotation")
|
||||
return convert_rotation(value, src, dst)
|
||||
|
||||
|
||||
def pose_abs_to_rel(*args, **kwargs) -> np.ndarray:
|
||||
pose_abs_to_rel_func = lazy_import(
|
||||
"cosmos_framework.data.vfm.action.pose_utils",
|
||||
"pose_abs_to_rel",
|
||||
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
|
||||
)
|
||||
pose_abs_to_rel_func = _load_robolab_framework_symbol("pose_abs_to_rel")
|
||||
return pose_abs_to_rel_func(*args, **kwargs)
|
||||
|
||||
|
||||
def pose_rel_to_abs(*args, **kwargs) -> np.ndarray:
|
||||
pose_rel_to_abs_func = lazy_import(
|
||||
"cosmos_framework.data.vfm.action.pose_utils",
|
||||
"pose_rel_to_abs",
|
||||
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
|
||||
)
|
||||
pose_rel_to_abs_func = _load_robolab_framework_symbol("pose_rel_to_abs")
|
||||
return pose_rel_to_abs_func(*args, **kwargs)
|
||||
|
||||
|
||||
def build_abs_pose_from_components(*args, **kwargs) -> np.ndarray:
|
||||
build_abs_pose_from_components_func = lazy_import(
|
||||
"cosmos_framework.data.vfm.action.pose_utils",
|
||||
"build_abs_pose_from_components",
|
||||
"Cosmos3 RoboLab midtrain action serving requires cosmos_framework pose_utils on PYTHONPATH.",
|
||||
)
|
||||
build_abs_pose_from_components_func = _load_robolab_framework_symbol("build_abs_pose_from_components")
|
||||
return build_abs_pose_from_components_func(*args, **kwargs)
|
||||
|
||||
|
||||
|
||||
@@ -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 https://github.com/FunAudioLLM/CosyVoice/tree/main/cosyvoice/flow/DiT
|
||||
# Refactored to use vllm_omni diffusion infrastructure for optimized attention backends
|
||||
|
||||
@@ -15,8 +15,10 @@ from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
from x_transformers.x_transformers import RotaryEmbedding, apply_rotary_pos_emb
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.layer import Attention as DiffusionAttention
|
||||
from vllm_omni.model_executor.layers.timestep_embedding import DiTTimestepEmbedding
|
||||
from vllm_omni.model_executor.models.cosyvoice3.runtime import cosyvoice3_batch_flow_profile
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -52,6 +54,22 @@ def get_pos_embed_indices(start, length, max_pos, scale=1.0):
|
||||
return pos
|
||||
|
||||
|
||||
def _normalize_attention_mask(mask: torch.Tensor | None, batch_size: int, seq_len: int) -> torch.Tensor | None:
|
||||
if mask is None:
|
||||
return None
|
||||
if mask.dim() == 2:
|
||||
attn_mask = mask
|
||||
elif mask.dim() == 3 and mask.shape[1] == 1:
|
||||
attn_mask = mask[:, 0]
|
||||
elif mask.dim() == 4:
|
||||
attn_mask = mask[:, 0, -1]
|
||||
else:
|
||||
return None
|
||||
if attn_mask.shape != (batch_size, seq_len):
|
||||
return None
|
||||
return attn_mask.bool()
|
||||
|
||||
|
||||
class FeedForward(nn.Module):
|
||||
"""Feed-forward network with GELU activation."""
|
||||
|
||||
@@ -114,42 +132,39 @@ class DiTAttention(nn.Module):
|
||||
) -> torch.Tensor:
|
||||
batch_size, seq_len = x.shape[0], x.shape[1]
|
||||
|
||||
# Project to Q, K, V
|
||||
query = self.to_q(x)
|
||||
key = self.to_k(x)
|
||||
value = self.to_v(x)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_qkv_projection"):
|
||||
query = self.to_q(x)
|
||||
key = self.to_k(x)
|
||||
value = self.to_v(x)
|
||||
|
||||
# Apply rotary position embedding
|
||||
if rope is not None:
|
||||
freqs, xpos_scale = rope
|
||||
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
|
||||
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
|
||||
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_rope"):
|
||||
if rope is not None:
|
||||
freqs, xpos_scale = rope
|
||||
q_xpos_scale, k_xpos_scale = (xpos_scale, xpos_scale**-1.0) if xpos_scale is not None else (1.0, 1.0)
|
||||
query = apply_rotary_pos_emb(query, freqs, q_xpos_scale)
|
||||
key = apply_rotary_pos_emb(key, freqs, k_xpos_scale)
|
||||
|
||||
# Reshape for attention: (batch, seq, heads, head_dim)
|
||||
query = query.view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
key = key.view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
value = value.view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_backend"):
|
||||
# Reshape for attention: (batch, seq, heads, head_dim)
|
||||
query = query.view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
key = key.view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
value = value.view(batch_size, seq_len, self.heads, self.dim_head)
|
||||
|
||||
# Use diffusion attention backend
|
||||
# The diffusion Attention layer expects (batch, seq, heads, head_dim)
|
||||
out = self.attn(query, key, value, attn_metadata=None)
|
||||
# The diffusion Attention layer expects (batch, seq, heads, head_dim)
|
||||
attn_mask = _normalize_attention_mask(mask, batch_size, seq_len)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attn_mask) if attn_mask is not None else None
|
||||
out = self.attn(query, key, value, attn_metadata=attn_metadata)
|
||||
|
||||
# Some attention backends return a non-contiguous layout.
|
||||
out = out.reshape(batch_size, seq_len, self.inner_dim)
|
||||
out = out.to(query.dtype)
|
||||
|
||||
# Output projection
|
||||
out = self.to_out(out)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_output_projection"):
|
||||
# Some attention backends return a non-contiguous layout.
|
||||
out = out.reshape(batch_size, seq_len, self.inner_dim)
|
||||
out = out.to(x.dtype)
|
||||
out = self.to_out(out)
|
||||
|
||||
# Apply mask if provided
|
||||
if mask is not None:
|
||||
if mask.dim() == 2:
|
||||
mask = mask.unsqueeze(-1)
|
||||
elif mask.dim() == 4:
|
||||
# (batch, heads, seq, seq) -> use last dim
|
||||
mask = mask[:, 0, -1].unsqueeze(-1)
|
||||
out = out.masked_fill(~mask.bool(), 0.0)
|
||||
attn_mask = _normalize_attention_mask(mask, batch_size, seq_len)
|
||||
if attn_mask is not None:
|
||||
out = out.masked_fill(~attn_mask.unsqueeze(-1), 0.0)
|
||||
|
||||
return out
|
||||
|
||||
@@ -172,18 +187,19 @@ class DiTBlock(nn.Module):
|
||||
self.ff = FeedForward(dim=dim, mult=ff_mult, dropout=dropout, approximate="tanh")
|
||||
|
||||
def forward(self, x, t, mask=None, rope=None):
|
||||
# pre-norm & modulation for attention input
|
||||
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_adalayernorm_attention"):
|
||||
norm, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.attn_norm(x, emb=t)
|
||||
|
||||
# attention
|
||||
attn_output = self.attn(x=norm, mask=mask, rope=rope)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention"):
|
||||
attn_output = self.attn(x=norm, mask=mask, rope=rope)
|
||||
|
||||
# process attention output for input x
|
||||
x = x + gate_msa.unsqueeze(1) * attn_output
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_attention_residual"):
|
||||
x = x + gate_msa.unsqueeze(1) * attn_output
|
||||
|
||||
ff_norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
||||
ff_output = self.ff(ff_norm)
|
||||
x = x + gate_mlp.unsqueeze(1) * ff_output
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_layernorm_ffn"):
|
||||
ff_norm = self.ff_norm(x) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
||||
ff_output = self.ff(ff_norm)
|
||||
x = x + gate_mlp.unsqueeze(1) * ff_output
|
||||
|
||||
return x
|
||||
|
||||
@@ -205,19 +221,20 @@ class CausalConvPositionEmbedding(nn.Module):
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None):
|
||||
if mask is not None:
|
||||
mask = mask[..., None]
|
||||
x = x.masked_fill(~mask, 0.0)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_causal_conv_position_embedding"):
|
||||
if mask is not None:
|
||||
mask = mask[..., None]
|
||||
x = x.masked_fill(~mask, 0.0)
|
||||
|
||||
x = x.permute(0, 2, 1)
|
||||
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
|
||||
x = self.conv1(x)
|
||||
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
|
||||
x = self.conv2(x)
|
||||
out = x.permute(0, 2, 1)
|
||||
x = x.permute(0, 2, 1)
|
||||
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
|
||||
x = self.conv1(x)
|
||||
x = F.pad(x, (self.kernel_size - 1, 0, 0, 0))
|
||||
x = self.conv2(x)
|
||||
out = x.permute(0, 2, 1)
|
||||
|
||||
if mask is not None:
|
||||
out = out.masked_fill(~mask, 0.0)
|
||||
if mask is not None:
|
||||
out = out.masked_fill(~mask, 0.0)
|
||||
|
||||
return out
|
||||
|
||||
@@ -327,13 +344,15 @@ class InputEmbedding(nn.Module):
|
||||
self.conv_pos_embed = CausalConvPositionEmbedding(dim=out_dim)
|
||||
|
||||
def forward(self, x, cond, text_embed, spks):
|
||||
to_cat = [x, cond, text_embed]
|
||||
if self.spk_dim > 0:
|
||||
spks = repeat(spks, "b c -> b t c", t=x.shape[1])
|
||||
to_cat.append(spks)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_input_projection"):
|
||||
to_cat = [x, cond, text_embed]
|
||||
if self.spk_dim > 0:
|
||||
spks = repeat(spks, "b c -> b t c", t=x.shape[1])
|
||||
to_cat.append(spks)
|
||||
|
||||
x = self.proj(torch.cat(to_cat, dim=-1))
|
||||
x = self.conv_pos_embed(x) + x
|
||||
x = self.proj(torch.cat(to_cat, dim=-1))
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_input_causal_conv"):
|
||||
x = self.conv_pos_embed(x) + x
|
||||
return x
|
||||
|
||||
|
||||
@@ -385,31 +404,37 @@ class DiT(nn.Module):
|
||||
self.num_decoding_left_chunks = num_decoding_left_chunks
|
||||
|
||||
def forward(self, x, mask, mu, t, spks=None, cond=None):
|
||||
x = x.transpose(1, 2)
|
||||
mu = mu.transpose(1, 2)
|
||||
cond = cond.transpose(1, 2)
|
||||
spks = spks.unsqueeze(dim=1)
|
||||
batch, seq_len = x.shape[0], x.shape[1]
|
||||
if t.ndim == 0:
|
||||
t = t.repeat(batch)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_prepare_inputs"):
|
||||
x = x.transpose(1, 2)
|
||||
mu = mu.transpose(1, 2)
|
||||
cond = cond.transpose(1, 2)
|
||||
spks = spks.unsqueeze(dim=1)
|
||||
batch, seq_len = x.shape[0], x.shape[1]
|
||||
if t.ndim == 0:
|
||||
t = t.repeat(batch)
|
||||
|
||||
# t: conditioning time, c: context (text + masked cond audio), x: noised input audio
|
||||
t = self.time_embed(t)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_time_embedding"):
|
||||
t = self.time_embed(t)
|
||||
x = self.input_embed(x, cond, mu, spks.squeeze(1))
|
||||
|
||||
rope = self.rotary_embed.forward_from_seq_len(seq_len)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_rope_and_mask"):
|
||||
rope = self.rotary_embed.forward_from_seq_len(seq_len)
|
||||
attn_mask = mask[:, 0].bool() if mask.dim() == 3 and mask.shape[1] == 1 else mask.bool()
|
||||
|
||||
if self.long_skip_connection is not None:
|
||||
residual = x
|
||||
|
||||
attn_mask = mask.bool().repeat(1, x.size(1), 1).unsqueeze(dim=1)
|
||||
|
||||
for block in self.transformer_blocks:
|
||||
x = block(x, t, mask=attn_mask.bool(), rope=rope)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_transformer_blocks"):
|
||||
for block_index, block in enumerate(self.transformer_blocks):
|
||||
with cosyvoice3_batch_flow_profile(f"cosyvoice3_dit_transformer_block_{block_index}"):
|
||||
x = block(x, t, mask=attn_mask.bool(), rope=rope)
|
||||
|
||||
if self.long_skip_connection is not None:
|
||||
x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_long_skip_projection"):
|
||||
x = self.long_skip_connection(torch.cat((x, residual), dim=-1))
|
||||
|
||||
x = self.norm_out(x, t)
|
||||
output = self.proj_out(x).transpose(1, 2)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_final_adalayernorm"):
|
||||
x = self.norm_out(x, t)
|
||||
with cosyvoice3_batch_flow_profile("cosyvoice3_dit_final_projection"):
|
||||
output = self.proj_out(x).transpose(1, 2)
|
||||
return output
|
||||
@@ -17,6 +17,7 @@ import re as re_module
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Iterable
|
||||
from contextlib import contextmanager
|
||||
from typing import ClassVar
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -121,6 +122,10 @@ class DreamZeroPipeline(nn.Module, CFGParallelMixin):
|
||||
methods below. The runner binds one session state only for ``forward()``.
|
||||
"""
|
||||
|
||||
# Generic warmup cannot synthesize robot observations. AR-Diffusion uses
|
||||
# ar_diffusion_warmup_requests() for model-specific warmup instead.
|
||||
dummy_run_num_frames: ClassVar[int] = 0
|
||||
|
||||
_POSITIVE_BRANCH = "positive"
|
||||
_NEGATIVE_BRANCH = "negative"
|
||||
_ar_diffusion_kv_state = None
|
||||
@@ -715,7 +720,7 @@ class DreamZeroPipeline(nn.Module, CFGParallelMixin):
|
||||
|
||||
def warmup_compile(self) -> None:
|
||||
"""Warm up compiled text/image/VAE paths before timed inference."""
|
||||
if not torch.cuda.is_available():
|
||||
if not torch.accelerator.is_available():
|
||||
return
|
||||
|
||||
state = self.state
|
||||
@@ -796,12 +801,12 @@ class DreamZeroPipeline(nn.Module, CFGParallelMixin):
|
||||
latents: tuple[torch.Tensor, torch.Tensor],
|
||||
do_true_cfg: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Post-step sync: .contiguous() + cuda.synchronize()"""
|
||||
"""Post-step sync: .contiguous() + accelerator stream synchronize"""
|
||||
latents = tuple(t.contiguous() for t in latents)
|
||||
if do_true_cfg and get_classifier_free_guidance_world_size() > 1:
|
||||
device = next((t.device for t in latents if t.is_cuda), None)
|
||||
device = next((t.device for t in latents if t.device.type != "cpu"), None)
|
||||
if device is not None:
|
||||
torch.cuda.current_stream(device).synchronize()
|
||||
torch.accelerator.current_stream(device).synchronize()
|
||||
return latents
|
||||
|
||||
# -----------------------------------------------------------------------
|
||||
|
||||
@@ -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: https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformers/transformer_ernie_image.py
|
||||
|
||||
from collections.abc import Iterable
|
||||
@@ -28,6 +28,9 @@ from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelInput,
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
from vllm_omni.diffusion.models.ernie_image.fused_rope import (
|
||||
try_fused_qk_rotary_emb,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -101,6 +104,26 @@ def _apply_rotary_emb(
|
||||
return torch.cat((x_rot * cos_ + x_rotated * sin_, x[..., rot_dim:]), dim=-1)
|
||||
|
||||
|
||||
def _apply_qk_rotary_emb(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
freqs_cos: torch.Tensor,
|
||||
freqs_sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
fused = try_fused_qk_rotary_emb(
|
||||
query,
|
||||
key,
|
||||
freqs_cos,
|
||||
freqs_sin,
|
||||
)
|
||||
if fused is not None:
|
||||
return fused
|
||||
return (
|
||||
_apply_rotary_emb(query, freqs_cos, freqs_sin),
|
||||
_apply_rotary_emb(key, freqs_cos, freqs_sin),
|
||||
)
|
||||
|
||||
|
||||
class ErnieImageEmbedND3(nn.Module):
|
||||
def __init__(self, dim: int, theta: int, axes_dim: tuple[int, int, int]):
|
||||
super().__init__()
|
||||
@@ -340,8 +363,7 @@ class ErnieImageAttention(nn.Module):
|
||||
|
||||
if image_rotary_emb is not None:
|
||||
freqs_cos, freqs_sin = image_rotary_emb
|
||||
query = _apply_rotary_emb(query, freqs_cos, freqs_sin)
|
||||
key = _apply_rotary_emb(key, freqs_cos, freqs_sin)
|
||||
query, key = _apply_qk_rotary_emb(query, key, freqs_cos, freqs_sin)
|
||||
|
||||
attn_metadata = None
|
||||
if attention_mask is not None:
|
||||
@@ -599,17 +621,12 @@ class ErnieImageTransformer2DModel(nn.Module):
|
||||
hidden_states, freqs_cos, freqs_sin, attention_mask = self.unified_prepare(hidden_states, text_bth, text_lens)
|
||||
attention_mask = self._slice_attention_mask_for_ring(attention_mask)
|
||||
rotary_pos_emb = (freqs_cos, freqs_sin)
|
||||
S = hidden_states.shape[0]
|
||||
|
||||
sample = self.time_proj(timestep)
|
||||
sample = sample.to(dtype=dtype)
|
||||
c = self.time_embedding(sample)
|
||||
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = [
|
||||
t.unsqueeze(0).expand(S, -1, -1).contiguous() for t in self.adaLN_modulation(c).chunk(6, dim=-1)
|
||||
]
|
||||
temb = self.adaLN_modulation(c).chunk(6, dim=-1)
|
||||
|
||||
for layer in self.layers:
|
||||
temb = [shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp]
|
||||
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
||||
hidden_states = self._gradient_checkpointing_func(
|
||||
layer,
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Lossless eager Q/K RoPE fusion for ERNIE-Image."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import OrderedDict
|
||||
|
||||
import torch
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_FAILED_KEYS_MAX_SIZE = 128
|
||||
_FAILED_KEYS: OrderedDict[tuple[object, ...], None] = OrderedDict()
|
||||
|
||||
|
||||
if HAS_TRITON:
|
||||
|
||||
@triton.jit
|
||||
def _round_bf16_to_fp32(value):
|
||||
"""RNE-round FP32 to BF16 precision in 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 _qk_rope_kernel(
|
||||
out_q_ptr,
|
||||
out_k_ptr,
|
||||
q_ptr,
|
||||
k_ptr,
|
||||
cos_ptr,
|
||||
sin_ptr,
|
||||
heads,
|
||||
head_dim: tl.constexpr,
|
||||
rotary_dim: tl.constexpr,
|
||||
rotary_half: tl.constexpr,
|
||||
heads_block: tl.constexpr,
|
||||
half_block: tl.constexpr,
|
||||
tail_block: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0).to(tl.int64)
|
||||
is_key = tl.program_id(1)
|
||||
base = row * heads * head_dim
|
||||
head_offsets = tl.arange(0, heads_block)[:, None]
|
||||
head_mask = head_offsets < heads
|
||||
columns = tl.arange(0, half_block)[None, :]
|
||||
column_mask = columns < rotary_half
|
||||
mask = head_mask & column_mask
|
||||
|
||||
if is_key == 0:
|
||||
input_ptr = q_ptr
|
||||
output_ptr = out_q_ptr
|
||||
else:
|
||||
input_ptr = k_ptr
|
||||
output_ptr = out_k_ptr
|
||||
|
||||
first_offsets = base + head_offsets * head_dim + columns
|
||||
second_offsets = first_offsets + rotary_half
|
||||
first = tl.load(input_ptr + first_offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
second = tl.load(input_ptr + second_offsets, mask=mask, other=0.0).to(tl.float32)
|
||||
|
||||
# The eager path casts FP32 frequencies to BF16, duplicates adjacent
|
||||
# values, rounds both BF16 multiplies, and finally rounds the add.
|
||||
first_freq = columns // 2
|
||||
second_freq = (rotary_half + columns) // 2
|
||||
cos_first = _round_bf16_to_fp32(tl.load(cos_ptr + row * rotary_half + first_freq, mask=column_mask))
|
||||
cos_second = _round_bf16_to_fp32(tl.load(cos_ptr + row * rotary_half + second_freq, mask=column_mask))
|
||||
sin_first = _round_bf16_to_fp32(tl.load(sin_ptr + row * rotary_half + first_freq, mask=column_mask))
|
||||
sin_second = _round_bf16_to_fp32(tl.load(sin_ptr + row * rotary_half + second_freq, mask=column_mask))
|
||||
|
||||
out_first = _round_bf16_to_fp32(first * cos_first) + _round_bf16_to_fp32(-second * sin_first)
|
||||
out_second = _round_bf16_to_fp32(second * cos_second) + _round_bf16_to_fp32(first * sin_second)
|
||||
tl.store(output_ptr + first_offsets, out_first, mask=mask)
|
||||
tl.store(output_ptr + second_offsets, out_second, mask=mask)
|
||||
|
||||
if head_dim > rotary_dim:
|
||||
tail_columns = rotary_dim + tl.arange(0, tail_block)[None, :]
|
||||
tail_mask = head_mask & (tail_columns < head_dim)
|
||||
tail_offsets = base + head_offsets * head_dim + tail_columns
|
||||
tail = tl.load(input_ptr + tail_offsets, mask=tail_mask, other=0.0)
|
||||
tl.store(output_ptr + tail_offsets, tail, mask=tail_mask)
|
||||
|
||||
|
||||
def _runtime_key(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
freqs_cos: torch.Tensor,
|
||||
) -> tuple[object, ...]:
|
||||
return (
|
||||
query.device.index,
|
||||
tuple(query.shape),
|
||||
tuple(key.shape),
|
||||
tuple(freqs_cos.shape),
|
||||
query.dtype,
|
||||
freqs_cos.dtype,
|
||||
)
|
||||
|
||||
|
||||
def _is_failed_runtime_key(runtime_key: tuple[object, ...]) -> bool:
|
||||
if runtime_key not in _FAILED_KEYS:
|
||||
return False
|
||||
_FAILED_KEYS.move_to_end(runtime_key)
|
||||
return True
|
||||
|
||||
|
||||
def _record_failed_runtime_key(runtime_key: tuple[object, ...]) -> None:
|
||||
_FAILED_KEYS[runtime_key] = None
|
||||
_FAILED_KEYS.move_to_end(runtime_key)
|
||||
while len(_FAILED_KEYS) > _FAILED_KEYS_MAX_SIZE:
|
||||
_FAILED_KEYS.popitem(last=False)
|
||||
|
||||
|
||||
def _supported_inputs(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
freqs_cos: torch.Tensor,
|
||||
freqs_sin: torch.Tensor,
|
||||
) -> bool:
|
||||
if torch.compiler.is_compiling():
|
||||
return False
|
||||
if any(tensor.requires_grad for tensor in (query, key, freqs_cos, freqs_sin)):
|
||||
return False
|
||||
if not HAS_TRITON or not current_omni_platform.is_cuda():
|
||||
return False
|
||||
if query.dtype is not torch.bfloat16 or not query.is_cuda:
|
||||
return False
|
||||
if query.ndim != 4 or key.shape != query.shape or key.dtype is not query.dtype or key.device != query.device:
|
||||
return False
|
||||
if not query.is_contiguous() or not key.is_contiguous():
|
||||
return False
|
||||
if freqs_cos.dtype is not torch.float32 or freqs_sin.dtype is not torch.float32:
|
||||
return False
|
||||
if not freqs_cos.is_cuda or freqs_cos.device != query.device:
|
||||
return False
|
||||
if freqs_sin.device != query.device or freqs_sin.shape != freqs_cos.shape:
|
||||
return False
|
||||
if not freqs_cos.is_contiguous() or not freqs_sin.is_contiguous():
|
||||
return False
|
||||
batch, sequence, _, head_dim = query.shape
|
||||
rotary_half = freqs_cos.shape[-1] if freqs_cos.ndim == 3 else 0
|
||||
return (
|
||||
query.numel() > 0
|
||||
and freqs_cos.shape == (batch, sequence, rotary_half)
|
||||
and rotary_half > 0
|
||||
and rotary_half * 2 <= head_dim
|
||||
)
|
||||
|
||||
|
||||
def _launch_fused_qk_rotary_emb(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
freqs_cos: torch.Tensor,
|
||||
freqs_sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
batch, sequence, heads, head_dim = query.shape
|
||||
rotary_half = freqs_cos.shape[-1]
|
||||
rotary_dim = rotary_half * 2
|
||||
tail = head_dim - rotary_dim
|
||||
output_query = torch.empty_like(query)
|
||||
output_key = torch.empty_like(key)
|
||||
with torch.accelerator.device_index(query.device.index):
|
||||
_qk_rope_kernel[(batch * sequence, 2)](
|
||||
output_query,
|
||||
output_key,
|
||||
query,
|
||||
key,
|
||||
freqs_cos,
|
||||
freqs_sin,
|
||||
heads,
|
||||
head_dim=head_dim,
|
||||
rotary_dim=rotary_dim,
|
||||
rotary_half=rotary_half,
|
||||
heads_block=triton.next_power_of_2(heads),
|
||||
half_block=triton.next_power_of_2(rotary_half),
|
||||
tail_block=triton.next_power_of_2(max(tail, 1)),
|
||||
)
|
||||
return output_query, output_key
|
||||
|
||||
|
||||
def try_fused_qk_rotary_emb(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
freqs_cos: torch.Tensor,
|
||||
freqs_sin: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor] | None:
|
||||
"""Return fused Q/K outputs, or ``None`` to request the eager fallback."""
|
||||
|
||||
if not _supported_inputs(query, key, freqs_cos, freqs_sin):
|
||||
return None
|
||||
|
||||
runtime_key = _runtime_key(query, key, freqs_cos)
|
||||
if _is_failed_runtime_key(runtime_key):
|
||||
return None
|
||||
|
||||
try:
|
||||
return _launch_fused_qk_rotary_emb(query, key, freqs_cos, freqs_sin)
|
||||
except Exception:
|
||||
_record_failed_runtime_key(runtime_key)
|
||||
logger.exception("ERNIE-Image fused Q/K RoPE failed; using the eager fallback")
|
||||
return None
|
||||
|
||||
|
||||
__all__ = ["try_fused_qk_rotary_emb"]
|
||||
@@ -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
|
||||
|
||||
import math
|
||||
from collections.abc import Iterable
|
||||
@@ -124,8 +124,8 @@ class GlmImageImageProjector(nn.Module):
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
batch_size, channel, height, width = hidden_states.shape
|
||||
post_patch_height = torch.tensor(height // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
post_patch_width = torch.tensor(width // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
post_patch_height = height // self.patch_size
|
||||
post_patch_width = width // self.patch_size
|
||||
|
||||
# Reshape: [B, C, H, W] -> [B, H', W', C*p*p] -> [B, H'*W', C*p*p]
|
||||
hidden_states = hidden_states.reshape(
|
||||
@@ -189,18 +189,16 @@ class GlmImagePrepare(nn.Module):
|
||||
self,
|
||||
image_projector: nn.Module,
|
||||
rope: GlmImageRotaryPosEmbed,
|
||||
patch_size: int,
|
||||
):
|
||||
super().__init__()
|
||||
self.image_projector = image_projector
|
||||
self.rope = rope
|
||||
self.patch_size = patch_size
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
prior_hidden_states: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Process hidden_states and compute RoPE embeddings.
|
||||
|
||||
Args:
|
||||
@@ -211,14 +209,7 @@ class GlmImagePrepare(nn.Module):
|
||||
hidden_states: Patched hidden states [B, seq_len, D]
|
||||
rope_cos: RoPE cos embeddings [seq_len, dim]
|
||||
rope_sin: RoPE sin embeddings [seq_len, dim]
|
||||
post_patch_height: Scalar tensor for height after patching
|
||||
post_patch_width: Scalar tensor for width after patching
|
||||
"""
|
||||
batch_size, num_channels, height, width = hidden_states.shape
|
||||
|
||||
post_patch_height = torch.tensor(height // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
post_patch_width = torch.tensor(width // self.patch_size, device=hidden_states.device, dtype=torch.int64)
|
||||
|
||||
# Compute RoPE (uses original 4D hidden_states shape)
|
||||
image_rotary_emb = self.rope(hidden_states)
|
||||
rope_cos = image_rotary_emb[0].to(hidden_states.device)
|
||||
@@ -231,7 +222,7 @@ class GlmImagePrepare(nn.Module):
|
||||
if prior_hidden_states is not None:
|
||||
hidden_states = hidden_states + prior_hidden_states
|
||||
|
||||
return hidden_states, rope_cos, rope_sin, post_patch_height, post_patch_width
|
||||
return hidden_states, rope_cos, rope_sin
|
||||
|
||||
|
||||
class GlmImageAdaLayerNormZero(nn.Module):
|
||||
@@ -961,7 +952,6 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
1: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
|
||||
# RoPE sin: [seq_len, dim] - shard along sequence dimension
|
||||
2: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
|
||||
# post_patch_height and post_patch_width are scalars, not sharded
|
||||
},
|
||||
# Gather output at proj_out
|
||||
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
|
||||
@@ -1044,7 +1034,7 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
)
|
||||
|
||||
# Prepare module for SP (encapsulates patch embedding and RoPE for _sp_plan)
|
||||
self.prepare = GlmImagePrepare(self.image_projector, self.rope, patch_size)
|
||||
self.prepare = GlmImagePrepare(self.image_projector, self.rope)
|
||||
|
||||
self.time_condition_embed = GlmImageCombinedTimestepSizeEmbeddings(
|
||||
embedding_dim=time_embed_dim,
|
||||
@@ -1137,12 +1127,10 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
|
||||
# 1. Prepare hidden_states and RoPE via GlmImagePrepare module
|
||||
# _sp_plan will shard hidden_states and RoPE together via split_output=True
|
||||
hidden_states, rope_cos, rope_sin, post_patch_height_t, post_patch_width_t = self.prepare(
|
||||
hidden_states, prior_hidden_states
|
||||
)
|
||||
hidden_states, rope_cos, rope_sin = self.prepare(hidden_states, prior_hidden_states)
|
||||
image_rotary_emb = (rope_cos, rope_sin)
|
||||
post_patch_height = int(post_patch_height_t.item())
|
||||
post_patch_width = int(post_patch_width_t.item())
|
||||
post_patch_height = height // self.patch_size
|
||||
post_patch_width = width // self.patch_size
|
||||
|
||||
# Timestep conditioning
|
||||
temb = self.time_condition_embed(timestep, target_size, crop_coords, hidden_states.dtype)
|
||||
@@ -1163,8 +1151,6 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
device=hidden_states.device,
|
||||
)
|
||||
hidden_states_mask[:, ctx.sp_original_seq_len :] = False
|
||||
if hidden_states_mask.all():
|
||||
hidden_states_mask = None
|
||||
|
||||
# 2. Transformer blocks
|
||||
for layer_idx, block in enumerate(self.transformer_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
|
||||
# Adapted from Helios (https://github.com/BestWishYsh/Helios)
|
||||
|
||||
import math
|
||||
@@ -27,10 +27,7 @@ from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
from vllm_omni.diffusion.cache.cachedit import CacheDiTAdapterConfig
|
||||
from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelInput,
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.sp_plan import SequenceParallelOutput
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import (
|
||||
@@ -448,6 +445,12 @@ class HeliosCrossAttention(nn.Module):
|
||||
num_kv_heads=self.num_heads,
|
||||
softmax_scale=1.0 / (head_dim**0.5),
|
||||
causal=False,
|
||||
# Text K/V is replicated on every SP rank, so Ulysses must not be
|
||||
# used here: its all-to-all would treat the per-rank replicas as
|
||||
# sequence shards and ws-fold duplicate the keys. Sharded Q over
|
||||
# full replicated K/V is correct locally and needs no
|
||||
# communication (same as Wan2.2 cross-attn).
|
||||
skip_sequence_parallel=True,
|
||||
)
|
||||
|
||||
def project_kv(self, encoder_hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
@@ -624,16 +627,50 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
_hsdp_shard_conditions = [_is_transformer_block]
|
||||
|
||||
_sp_plan = {
|
||||
"rope": {
|
||||
0: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True, auto_pad=True),
|
||||
1: SequenceParallelInput(split_dim=1, expected_dims=4, split_output=True, auto_pad=True),
|
||||
},
|
||||
"blocks.0": {
|
||||
"hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, auto_pad=True),
|
||||
},
|
||||
# "rope" and "blocks.0" are intentionally omitted.
|
||||
# The rope hook splits along dim=1 of the 5D output [B, D, T, H, W],
|
||||
# which is the frequency dimension, NOT the sequence dimension.
|
||||
# The blocks.0 hook splits the concatenated hidden_states as a whole,
|
||||
# which can put all history tokens in one rank (original_context_length=0).
|
||||
# Instead, hidden_states and rotary_emb are split per-component in
|
||||
# forward() after flatten+transpose, ensuring each rank gets half
|
||||
# of each component (history and current).
|
||||
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
|
||||
}
|
||||
|
||||
def _sp_split_seq(self, x: torch.Tensor) -> torch.Tensor:
|
||||
"""Split tensor along sequence dim (dim=1) for Ulysses SP.
|
||||
|
||||
If seq_len is not divisible by world_size, replicate the last
|
||||
token(s) to pad to a divisible length. This avoids crashing
|
||||
on non-divisible history components (which use different patch
|
||||
sizes and thus produce different token counts).
|
||||
|
||||
Residual caveat: the replicated padding tokens attend unmasked
|
||||
in attn1 on the last rank (at most ws-1 replicas per component).
|
||||
The impact is bounded, but this is the first place to look if
|
||||
odd resolutions ever show quality drift.
|
||||
"""
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_sequence_parallel_rank,
|
||||
get_sequence_parallel_world_size,
|
||||
)
|
||||
|
||||
ws = get_sequence_parallel_world_size()
|
||||
if ws > 1 and x.dim() >= 2 and x.shape[1] > 0:
|
||||
seq_len = x.shape[1]
|
||||
remainder = seq_len % ws
|
||||
if remainder != 0:
|
||||
pad = ws - remainder
|
||||
# Replicate the last token to fill the padding
|
||||
last = x[:, -1:, ...].expand(-1, pad, *([-1] * (x.dim() - 2)))
|
||||
x = torch.cat([x, last], dim=1)
|
||||
seq_len = x.shape[1]
|
||||
r = get_sequence_parallel_rank()
|
||||
n = seq_len // ws
|
||||
x = x[:, r * n : (r + 1) * n, ...].contiguous()
|
||||
return x
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
patch_size: tuple[int, ...] = (1, 2, 2),
|
||||
@@ -860,6 +897,9 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
device=hidden_states.device,
|
||||
)
|
||||
rotary_emb = rotary_emb.flatten(2).transpose(1, 2)
|
||||
# USP: per-component split (each rank gets half of current frames)
|
||||
hidden_states = self._sp_split_seq(hidden_states)
|
||||
rotary_emb = self._sp_split_seq(rotary_emb)
|
||||
original_context_length = hidden_states.shape[1]
|
||||
|
||||
# 2. Process short history latents
|
||||
@@ -876,6 +916,9 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
device=latents_history_short.device,
|
||||
)
|
||||
rotary_emb_history_short = rotary_emb_history_short.flatten(2).transpose(1, 2)
|
||||
# USP: per-component split
|
||||
latents_history_short = self._sp_split_seq(latents_history_short)
|
||||
rotary_emb_history_short = self._sp_split_seq(rotary_emb_history_short)
|
||||
|
||||
hidden_states = torch.cat([latents_history_short, hidden_states], dim=1)
|
||||
rotary_emb = torch.cat([rotary_emb_history_short, rotary_emb], dim=1)
|
||||
@@ -896,6 +939,9 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
rotary_emb_history_mid = pad_for_3d_conv(rotary_emb_history_mid, (2, 2, 2))
|
||||
rotary_emb_history_mid = center_down_sample_3d(rotary_emb_history_mid, (2, 2, 2))
|
||||
rotary_emb_history_mid = rotary_emb_history_mid.flatten(2).transpose(1, 2)
|
||||
# USP: per-component split
|
||||
latents_history_mid = self._sp_split_seq(latents_history_mid)
|
||||
rotary_emb_history_mid = self._sp_split_seq(rotary_emb_history_mid)
|
||||
|
||||
hidden_states = torch.cat([latents_history_mid, hidden_states], dim=1)
|
||||
rotary_emb = torch.cat([rotary_emb_history_mid, rotary_emb], dim=1)
|
||||
@@ -916,6 +962,9 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
rotary_emb_history_long = pad_for_3d_conv(rotary_emb_history_long, (4, 4, 4))
|
||||
rotary_emb_history_long = center_down_sample_3d(rotary_emb_history_long, (4, 4, 4))
|
||||
rotary_emb_history_long = rotary_emb_history_long.flatten(2).transpose(1, 2)
|
||||
# USP: per-component split
|
||||
latents_history_long = self._sp_split_seq(latents_history_long)
|
||||
rotary_emb_history_long = self._sp_split_seq(rotary_emb_history_long)
|
||||
|
||||
hidden_states = torch.cat([latents_history_long, hidden_states], dim=1)
|
||||
rotary_emb = torch.cat([rotary_emb_history_long, rotary_emb], dim=1)
|
||||
@@ -958,6 +1007,18 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
timestep_proj = timestep_proj.permute(0, 2, 1, 3)
|
||||
|
||||
# 6. Transformer blocks
|
||||
# Manually increment _sp_shard_depth so that attention layers
|
||||
# know SP is active and perform Ulysses All-to-All communication.
|
||||
# Normally this is done by split_output=True hooks (e.g. rope),
|
||||
# but those are removed because they split the wrong dimension.
|
||||
from vllm_omni.diffusion.forward_context import (
|
||||
get_forward_context,
|
||||
is_forward_context_available,
|
||||
)
|
||||
|
||||
if is_forward_context_available():
|
||||
get_forward_context()._sp_shard_depth += 1
|
||||
|
||||
hidden_states = hidden_states.contiguous()
|
||||
encoder_hidden_states = encoder_hidden_states.contiguous()
|
||||
rotary_emb = rotary_emb.contiguous()
|
||||
@@ -979,6 +1040,11 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
hidden_states = self.proj_out(hidden_states)
|
||||
|
||||
# 8. Unpatchify
|
||||
# proj_out gather may include padded tokens from non-divisible
|
||||
# sequences. Slice to the expected size before reshape.
|
||||
expected_seq = post_patch_num_frames * post_patch_height * post_patch_width
|
||||
if hidden_states.shape[1] > expected_seq:
|
||||
hidden_states = hidden_states[:, :expected_seq, :]
|
||||
hidden_states = hidden_states.reshape(
|
||||
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
|
||||
)
|
||||
|
||||
@@ -535,19 +535,23 @@ class HeliosPipeline(
|
||||
"zero_steps": int(extra.get("zero_steps", 1)),
|
||||
}
|
||||
)
|
||||
self.prepare_next_chunk(state)
|
||||
return state
|
||||
|
||||
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"])
|
||||
num_media_frames = int(state.extra["window_num_frames"])
|
||||
num_latent_frames = int(state.extra["num_latent_frames_per_chunk"])
|
||||
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))
|
||||
return ChunkMediaSpec(
|
||||
num_media_frames=num_media_frames,
|
||||
fps=float(fps),
|
||||
num_latent_frames=num_latent_frames,
|
||||
)
|
||||
|
||||
@override
|
||||
def prepare_next_chunk(self, state: StepRequestState) -> None:
|
||||
|
||||
@@ -75,7 +75,11 @@ from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
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.forward_context import (
|
||||
get_paged_kv_computed_tokens,
|
||||
paged_kv_prefill,
|
||||
set_forward_context_denoise_step_idx,
|
||||
)
|
||||
from vllm_omni.diffusion.layers.fused_moe import FusedMoE
|
||||
from vllm_omni.diffusion.layers.norm import RMSNorm
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
@@ -1097,8 +1101,6 @@ class ImageKVCacheManager(nn.Module):
|
||||
layer resolves the actual CUDA or Ascend paged kernel.
|
||||
"""
|
||||
|
||||
if uncond_cfg_prefill:
|
||||
raise RuntimeError("Hunyuan negative-CFG prefill must run before paged row activation")
|
||||
if self._injected_ar_kv is not None:
|
||||
raise NotImplementedError("Hunyuan Scheduler-paged KV does not support imported AR KV")
|
||||
if not query_lens or len(seq_lens) != len(query_lens):
|
||||
@@ -1109,7 +1111,6 @@ class ImageKVCacheManager(nn.Module):
|
||||
self.clear_legacy_prompt_kv_cache()
|
||||
bs = len(query_lens)
|
||||
q_len = query_lens[0]
|
||||
seq_len = seq_lens[0]
|
||||
assert query.shape[0] == bs * q_len, f"{query.shape[0]} != {bs * q_len}"
|
||||
|
||||
head_num_per_rank = query.shape[1]
|
||||
@@ -1121,22 +1122,19 @@ class ImageKVCacheManager(nn.Module):
|
||||
value = value.reshape(bs, q_len, kv_head_num_per_rank, head_dim)
|
||||
|
||||
joint_text_query = joint_text_key = joint_text_value = None
|
||||
if self.sp_size > 1 and first_step:
|
||||
if self.sp_size > 1 and uncond_cfg_prefill:
|
||||
joint_text_query, joint_text_key, joint_text_value = query, key, value
|
||||
query, key, value = query[:, :0], key[:, :0], value[:, :0]
|
||||
elif self.sp_size > 1 and first_step:
|
||||
if shard_image_size is None or shard_image_size <= 0:
|
||||
raise ValueError("Hunyuan paged Ulysses requires a positive local image shard size")
|
||||
local_prompt_len = seq_len - shard_image_size
|
||||
joint_query_len = query.shape[1] - shard_image_size
|
||||
if local_prompt_len != joint_query_len:
|
||||
raise ValueError(
|
||||
"Hunyuan paged Ulysses prompt layout mismatch: "
|
||||
f"key_prompt={local_prompt_len}, query_prompt={joint_query_len}"
|
||||
)
|
||||
joint_text_query = query[:, :joint_query_len]
|
||||
joint_text_key = key[:, :local_prompt_len]
|
||||
joint_text_value = value[:, :local_prompt_len]
|
||||
joint_text_key = key[:, :joint_query_len]
|
||||
joint_text_value = value[:, :joint_query_len]
|
||||
query = query[:, joint_query_len:]
|
||||
key = key[:, local_prompt_len:]
|
||||
value = value[:, local_prompt_len:]
|
||||
key = key[:, joint_query_len:]
|
||||
value = value[:, joint_query_len:]
|
||||
|
||||
if joint_text_query is None:
|
||||
attn_metadata = AttentionMetadata(full_attn_spans=full_attn_spans)
|
||||
@@ -1254,6 +1252,8 @@ class ImageKVCacheManager(nn.Module):
|
||||
) -> torch.Tensor:
|
||||
self.image_token_len = kwargs.get("num_image_tokens")
|
||||
if self.attn.is_paged_kv_active():
|
||||
# A native connector fills the same Scheduler-owned pages as
|
||||
# local prefill. Imported prefixes need no dense reconstruction.
|
||||
full_attn_spans = kwargs.get("full_attn_spans")
|
||||
if full_attn_spans is None:
|
||||
raise ValueError("Hunyuan Scheduler-paged KV requires full_attn_spans metadata")
|
||||
@@ -1837,7 +1837,9 @@ class HunYuanAttention(nn.Module):
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
scaling=self.scaling,
|
||||
image_token_len=4097,
|
||||
prefix=f"{prefix}.image_attn",
|
||||
# Native Mooncake pairs this canonical KV layer name with the AR
|
||||
# HunYuanAttention: model.layers.N.self_attn.attn. Keep both in sync.
|
||||
prefix=f"model.{prefix}",
|
||||
)
|
||||
self.image_rope2d_emb = HunYuanRotary2DEmbedder(
|
||||
num_heads=self.num_heads,
|
||||
@@ -2964,7 +2966,10 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
seq_lens=[prefill_seq_len],
|
||||
num_image_tokens=0,
|
||||
ar_kv_reuse_len=negative_reuse_len,
|
||||
full_attn_spans=model_kwargs["full_attn_spans"][batch_slice]
|
||||
full_attn_spans=[
|
||||
[(start, min(end, prefill_seq_len)) for start, end in spans if start < prefill_seq_len]
|
||||
for spans in model_kwargs["full_attn_spans"][batch_slice]
|
||||
]
|
||||
if model_kwargs.get("full_attn_spans")
|
||||
else None,
|
||||
)
|
||||
@@ -3019,6 +3024,28 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
device,
|
||||
):
|
||||
ar_kv_data = model_kwargs.pop("ar_kv_data", None)
|
||||
computed_tokens = get_paged_kv_computed_tokens()
|
||||
if computed_tokens and computed_tokens[0] > 0:
|
||||
positive_reuse_len = computed_tokens[0]
|
||||
if (
|
||||
len(computed_tokens) > 1
|
||||
and computed_tokens[1] < positive_reuse_len
|
||||
and (not cfg_parallel_ready or cfg_rank == 1)
|
||||
):
|
||||
prefill_inputs = self._build_negative_cfg_prefill_inputs(
|
||||
input_ids,
|
||||
model_kwargs,
|
||||
batch_size,
|
||||
computed_tokens[1],
|
||||
positive_reuse_len,
|
||||
cfg_parallel_ready,
|
||||
)
|
||||
with (
|
||||
paged_kv_prefill(1, positive_reuse_len),
|
||||
torch.autocast(device_type=device.type, dtype=torch.bfloat16),
|
||||
):
|
||||
self.model.forward_call(**prefill_inputs)
|
||||
return self._truncate_reused_prefix(input_ids, model_kwargs, positive_reuse_len), positive_reuse_len
|
||||
if ar_kv_data is None:
|
||||
logger.debug(
|
||||
"[AR KV Reuse] cfg_rank=%s: no AR KV received, fallback to full recompute (reuse_len=0)",
|
||||
@@ -3040,7 +3067,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
|
||||
# 3. negative cfg prefill
|
||||
# For CFG distilled models, skip negative CFG prefill (cfg_factor=1, no negative prompt)
|
||||
if self.do_classifier_free_guidance and not self.model.config.cfg_distilled:
|
||||
if self.do_classifier_free_guidance and not getattr(self.model.config, "cfg_distilled", False):
|
||||
self._maybe_run_negative_cfg_prefill(
|
||||
input_ids=input_ids,
|
||||
model_kwargs=model_kwargs,
|
||||
@@ -3151,7 +3178,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
# For CFG distilled models, skip CFG parallel (cfg_factor=1, no negative branch)
|
||||
cfg_parallel_ready = (
|
||||
self.do_classifier_free_guidance
|
||||
and not self.model.config.cfg_distilled
|
||||
and not getattr(self.model.config, "cfg_distilled", False)
|
||||
and get_classifier_free_guidance_world_size() == 2
|
||||
)
|
||||
|
||||
@@ -3207,7 +3234,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
self._split_model_kwargs_for_cfg_parallel(model_kwargs, batch_size, cfg_rank)
|
||||
else:
|
||||
# For CFG distilled models, cfg_factor is always 1 (CFG embedded in model)
|
||||
if self.model.config.cfg_distilled:
|
||||
if getattr(self.model.config, "cfg_distilled", False):
|
||||
cfg_factor = 1
|
||||
else:
|
||||
cfg_factor = 1 + self.do_classifier_free_guidance
|
||||
@@ -3252,7 +3279,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
# Sequential CFG: double the batch
|
||||
latent_model_input = torch.cat([latents] * cfg_factor)
|
||||
|
||||
if self.model.config.use_meanflow:
|
||||
if getattr(self.model.config, "use_meanflow", False):
|
||||
r = self.scheduler.get_timestep_r(t)
|
||||
r_expand = r.repeat(latent_model_input.shape[0])
|
||||
else:
|
||||
@@ -3281,7 +3308,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
|
||||
if should_compute:
|
||||
# Handle guidance for CFG distilled models
|
||||
if self.model.config.cfg_distilled:
|
||||
if getattr(self.model.config, "cfg_distilled", False):
|
||||
model_kwargs["guidance"] = torch.tensor(
|
||||
[1000.0 * self._guidance_scale],
|
||||
device=self.device,
|
||||
@@ -3308,7 +3335,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
# Perform guidance
|
||||
# For CFG distilled models, guidance is already embedded in the model,
|
||||
# so we skip the explicit CFG computation
|
||||
if self.model.config.cfg_distilled:
|
||||
if getattr(self.model.config, "cfg_distilled", False):
|
||||
# CFG distilled: guidance is handled internally via guidance_emb
|
||||
pass
|
||||
elif cfg_parallel_ready:
|
||||
|
||||
@@ -338,6 +338,9 @@ class HunyuanImage3Pipeline(
|
||||
supports_step_execution: ClassVar[bool] = True
|
||||
supports_request_batch = False
|
||||
support_image_input = True
|
||||
# The warmup request's blank image routes this AR+diffusion model down its
|
||||
# image-edit path, where the token block cannot match the latent patch grid.
|
||||
dummy_run_num_frames: ClassVar[int] = 0
|
||||
_dit_modules: ClassVar[list[str]] = ["model"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["vision_model"]
|
||||
_vae_modules: ClassVar[list[str]] = ["vae"]
|
||||
@@ -364,6 +367,8 @@ class HunyuanImage3Pipeline(
|
||||
|
||||
def __init__(self, od_config: OmniDiffusionConfig) -> None:
|
||||
self.hf_config = get_config(od_config.model, trust_remote_code=True)
|
||||
self.hf_config.cfg_distilled = _config_flag(self.hf_config, "cfg_distilled")
|
||||
self.hf_config.use_meanflow = _config_flag(self.hf_config, "use_meanflow")
|
||||
super().__init__(self.hf_config)
|
||||
# update diffusion config
|
||||
self.generation_config = GenerationConfig.from_pretrained(od_config.model)
|
||||
@@ -1279,7 +1284,9 @@ class HunyuanImage3Pipeline(
|
||||
|
||||
# 4. Encode conditional images
|
||||
# Skip encoding if AR KV reuse is enabled
|
||||
has_ar_kv = kwargs.get("ar_kv_data")
|
||||
has_ar_kv = kwargs.get("ar_kv_data") or request_layout_utils.native_kv_covers_cond_images(
|
||||
output, kwargs.get("kv_computed_tokens", ())
|
||||
)
|
||||
if batch_cond_image_info is not None and len(batch_cond_image_info[0]) > 0 and not has_ar_kv:
|
||||
cond_vae_images, cond_timestep, cond_vit_images = self._encode_cond_image(
|
||||
batch_cond_image_info, cfg_factor[mode], generator=generator
|
||||
@@ -1891,6 +1898,7 @@ class HunyuanImage3Pipeline(
|
||||
pipe._guidance_scale = guidance_scale
|
||||
pipe._guidance_rescale = getattr(sampling, "guidance_rescale", 0.0)
|
||||
|
||||
ar_kv_kwargs = self._extract_ar_kv_from_sampling(sampling)
|
||||
model_kwargs = self.prepare_model_inputs(
|
||||
prompt=prompt,
|
||||
cot_text=cot_text,
|
||||
@@ -1903,8 +1911,10 @@ class HunyuanImage3Pipeline(
|
||||
batch_cond_image_info=batch_cond_image_info,
|
||||
bot_task=tokenizer_bot_task,
|
||||
prepared_layout=request_layout_utils.get_hunyuan_prepared_layout(state),
|
||||
kv_computed_tokens=state.extra.get("kv_computed_tokens", ()),
|
||||
**ar_kv_kwargs,
|
||||
)
|
||||
model_kwargs.update(self._extract_ar_kv_from_sampling(sampling))
|
||||
model_kwargs.update(ar_kv_kwargs)
|
||||
model_kwargs["use_cache"] = False
|
||||
|
||||
input_ids = model_kwargs.pop("input_ids")
|
||||
@@ -2334,6 +2344,7 @@ class HunyuanImage3Pipeline(
|
||||
batch_cond_image_info=batch_cond_image_info,
|
||||
bot_task=tokenizer_bot_task,
|
||||
prepared_layout=request_layout_utils.get_hunyuan_prepared_layout(req.requests[0]),
|
||||
kv_computed_tokens=getattr(req.requests[0], "kv_computed_tokens", ()),
|
||||
**ar_kv_kwargs,
|
||||
)
|
||||
|
||||
|
||||
@@ -60,6 +60,48 @@ HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS: dict[str, int] = {
|
||||
"<img_ratio_36>": 130106,
|
||||
}
|
||||
|
||||
|
||||
def validate_special_token_ids(tokenizer: Any) -> None:
|
||||
"""Fail fast if a real tokenizer's ids drift from the hardcoded table.
|
||||
|
||||
``HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS`` exists so stop-token / trigger-tag
|
||||
resolution doesn't need a tokenizer round-trip, but that only holds as
|
||||
long as the ids match ``tokenizer.json`` for whatever model repo/revision
|
||||
is actually loaded. Call this once a real tokenizer is available (the
|
||||
example scripts do, right after loading it) to catch drift immediately
|
||||
instead of silently producing a request that runs to completion with the
|
||||
wrong stop tokens. Not wired into ``build_prompt_tokens`` itself: callers
|
||||
that intentionally pass a stand-in tokenizer with different ids (e.g.
|
||||
this module's own unit tests) must not be forced through this check.
|
||||
|
||||
Both ``tencent/HunyuanImage-3.0`` (base) and ``-Instruct`` report the
|
||||
same ``model_class_name`` (``HunyuanImage3ForCausalMM``), so this hook
|
||||
fires for either checkpoint -- but the base tokenizer's vocab doesn't
|
||||
include the Instruct-only ``<img_ratio_33>``-``<img_ratio_36>`` tokens
|
||||
(added for it2i's second aspect-ratio range). A token the tokenizer
|
||||
doesn't recognize at all (``convert_tokens_to_ids`` returning
|
||||
``unk_token_id``, or ``None`` for tokenizers without an unk concept) is
|
||||
"not part of this checkpoint's vocab," not "drifted"; only an id that
|
||||
resolves to something *else* indicates the hardcoded table is stale.
|
||||
"""
|
||||
unk_id = getattr(tokenizer, "unk_token_id", None)
|
||||
mismatches: dict[str, tuple[int, int]] = {}
|
||||
for tok, expected_id in HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS.items():
|
||||
actual_id = tokenizer.convert_tokens_to_ids(tok)
|
||||
if actual_id is None or (unk_id is not None and actual_id == unk_id):
|
||||
continue # not in this checkpoint's vocab -- nothing to compare
|
||||
if actual_id != expected_id:
|
||||
mismatches[tok] = (expected_id, actual_id)
|
||||
if mismatches:
|
||||
details = ", ".join(f"{tok!r}: expected {exp}, got {act}" for tok, (exp, act) in mismatches.items())
|
||||
raise ValueError(
|
||||
"HunyuanImage-3.0 tokenizer special-token ids no longer match "
|
||||
f"HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS ({details}). The loaded "
|
||||
"tokenizer/model revision has likely changed; update the hardcoded "
|
||||
"table in prompt_utils.py to match."
|
||||
)
|
||||
|
||||
|
||||
# bot_task -> (sys_type, trigger_tag).
|
||||
# ``vanilla`` is special-cased downstream: it bypasses the chat template
|
||||
# (no ``User:`` / ``Assistant:`` framing) and is only valid with
|
||||
@@ -317,12 +359,106 @@ def build_prompt_tokens(
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ARPromptInputs:
|
||||
"""Fully-resolved AR-stage inputs for one HunyuanImage3 request.
|
||||
|
||||
Consolidates the three things every caller (offline example, OpenAI
|
||||
server) must compute before submitting an AR request: the AR prefill
|
||||
(as segment-tokenized ``prompt_token_ids`` when a tokenizer is
|
||||
available, else a formatted ``prompt`` string), the resolved DiT
|
||||
system-prompt type, and the AR ``stop_token_ids``.
|
||||
"""
|
||||
|
||||
prompt: str | None
|
||||
prompt_token_ids: list[int] | None
|
||||
system_prompt_type: str
|
||||
stop_token_ids: list[int]
|
||||
|
||||
|
||||
def build_ar_prompt_inputs(
|
||||
user_prompt: str,
|
||||
task: str = "t2i",
|
||||
bot_task: str | None | _DefaultBotTask = _DEFAULT_BOT_TASK,
|
||||
sys_type: str | None = None,
|
||||
custom_system_prompt: str | None = None,
|
||||
num_images: int = 1,
|
||||
tokenizer: Any | None = None,
|
||||
image_size: str | None = None,
|
||||
) -> ARPromptInputs:
|
||||
"""Build the complete AR-stage inputs for a HunyuanImage3 request.
|
||||
|
||||
Wraps :func:`build_prompt_tokens` (byte-for-byte HF parity when
|
||||
``tokenizer`` is given), the :func:`build_prompt` string fallback (when
|
||||
no tokenizer is available), and :func:`resolve_stop_token_ids` behind
|
||||
one call, so a caller doesn't have to re-derive the AR prefill/stop-token
|
||||
logic -- and, critically, doesn't have to independently resolve
|
||||
``bot_task`` for the prompt-building call vs. the stop-token call, which
|
||||
can silently diverge if a caller passes the same nominal ``bot_task``
|
||||
value to both but resolves "omitted" vs. "explicit None" differently for
|
||||
each (this seam always forwards the identical resolved value to both).
|
||||
|
||||
Used by all four offline shared task examples: ``text_to_image.py`` /
|
||||
``image_edit.py`` (via ``model_extras.hunyuan_image3.build_ar_stage_inputs``)
|
||||
and ``x_to_text.py`` (via ``build_x_to_text_prompt``, which also calls
|
||||
``build_ar_stage_inputs``). The OpenAI server's ``serving_chat.py`` does
|
||||
not currently call this seam -- it still independently calls
|
||||
``build_prompt``/``build_prompt_tokens``/``resolve_stop_token_ids``, and
|
||||
can hit exactly the divergence described above when ``bot_task`` is
|
||||
omitted from ``extra_body`` (pre-existing, unrelated to this module).
|
||||
``image_size`` follows the same convention as :func:`resolve_stop_token_ids`
|
||||
(``None``/``"auto"`` lets the AR predict the aspect ratio; an explicit
|
||||
``"{w}x{h}"`` makes it stop at the terminator).
|
||||
"""
|
||||
if tokenizer is not None:
|
||||
result = build_prompt_tokens(
|
||||
user_prompt,
|
||||
tokenizer,
|
||||
task=task,
|
||||
bot_task=bot_task,
|
||||
sys_type=sys_type,
|
||||
custom_system_prompt=custom_system_prompt,
|
||||
num_images=num_images,
|
||||
)
|
||||
prompt_str: str | None = None
|
||||
prompt_token_ids: list[int] | None = result.token_ids
|
||||
system_prompt_type = result.system_prompt_type
|
||||
else:
|
||||
prompt_str = build_prompt(
|
||||
user_prompt,
|
||||
task=task,
|
||||
bot_task=bot_task,
|
||||
sys_type=sys_type,
|
||||
custom_system_prompt=custom_system_prompt,
|
||||
num_images=num_images,
|
||||
)
|
||||
prompt_token_ids = None
|
||||
_, resolved_bot_task = _normalize_task_and_bot_task(task, bot_task)
|
||||
system_prompt_type = sys_type or resolve_sys_type(resolved_bot_task)
|
||||
|
||||
stop_token_ids = resolve_stop_token_ids(
|
||||
task=task,
|
||||
bot_task=bot_task,
|
||||
tokenizer=tokenizer,
|
||||
image_size=image_size,
|
||||
)
|
||||
return ARPromptInputs(
|
||||
prompt=prompt_str,
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
system_prompt_type=system_prompt_type,
|
||||
stop_token_ids=stop_token_ids,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS",
|
||||
"validate_special_token_ids",
|
||||
"MAX_IMAGES_PER_REQUEST",
|
||||
"_TASK_PRESETS",
|
||||
"ARPromptInputs",
|
||||
"available_bot_tasks",
|
||||
"available_tasks",
|
||||
"build_ar_prompt_inputs",
|
||||
"build_prompt",
|
||||
"build_prompt_tokens",
|
||||
"resolve_stop_token_ids",
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -373,7 +373,32 @@ def build_hunyuan_diffusion_kv_requests(
|
||||
real_pos = tokenizer_output.real_pos
|
||||
assert prefix_positions is not None and real_pos is not None
|
||||
|
||||
def boundary_rows(field_name: str) -> list[int | None]:
|
||||
positions = getattr(tokenizer_output, field_name)
|
||||
if positions is None:
|
||||
return [None] * cfg_factor
|
||||
if not isinstance(positions, list) or not positions:
|
||||
raise ValueError(f"Hunyuan {field_name} must be a non-empty boundary list")
|
||||
# Batched tokenizer output contains a separate boundary for each CFG
|
||||
# row. Never broadcast a conditional boundary into a negative row.
|
||||
if cfg_factor == 1 and len(positions) == 1 and (positions[0] is None or type(positions[0]) is int):
|
||||
return positions
|
||||
if len(positions) == cfg_factor and all(
|
||||
isinstance(row, list) and len(row) == 1 and (row[0] is None or type(row[0]) is int) for row in positions
|
||||
):
|
||||
return [row[0] for row in positions]
|
||||
raise ValueError(f"Hunyuan {field_name} must contain one boundary per CFG row")
|
||||
|
||||
think_boundaries = boundary_rows("think_recaption_end_pos")
|
||||
uncond_boundaries = boundary_rows("uncond_cfg_start_pos")
|
||||
|
||||
target_len = hunyuan_num_image_tokens(prepared_layout.generated_image_info)
|
||||
reusable_lens = [0] * cfg_factor
|
||||
if think_boundaries[0] is not None:
|
||||
reusable_lens[0] = think_boundaries[0] or 0
|
||||
if any(boundary is not None for boundary in uncond_boundaries):
|
||||
for sequence_id in range(1, cfg_factor):
|
||||
reusable_lens[sequence_id] = min(reusable_lens[0], uncond_boundaries[sequence_id] or 0)
|
||||
return tuple(
|
||||
DiffusionKVRequest(
|
||||
f"{request.request_id}/diffusion-kv/{sequence_id}",
|
||||
@@ -383,6 +408,7 @@ def build_hunyuan_diffusion_kv_requests(
|
||||
prefix_len=int(prefix_row[-1].item()),
|
||||
target_len=target_len,
|
||||
seq_len=int(valid_row[-1].item()),
|
||||
prompt_token_ids=tokenizer_output.tokens[sequence_id, : reusable_lens[sequence_id]].tolist(),
|
||||
# Prompt and reference-image tokens are already embedded in this
|
||||
# row's primary self-attention sequence. Hunyuan therefore has no
|
||||
# independently projected cross/joint-attention KV context.
|
||||
@@ -401,3 +427,14 @@ def get_hunyuan_prepared_layout(source: Any) -> HunyuanPreparedLayout | None:
|
||||
f"HunyuanImage3 expected prepared_layout to be HunyuanPreparedLayout, got {type(prepared_layout).__name__}"
|
||||
)
|
||||
return prepared_layout
|
||||
|
||||
|
||||
def native_kv_covers_cond_images(output: TokenizerEncodeOutput, computed_tokens: tuple[int, ...]) -> bool:
|
||||
"""Skip image encoding only when every CFG row already contains its image KV."""
|
||||
image_slices = output.joint_image_slices
|
||||
if not image_slices or len(image_slices) != len(computed_tokens):
|
||||
return False
|
||||
return all(
|
||||
slices and all(image_slice.stop <= computed for image_slice in slices)
|
||||
for slices, computed in zip(image_slices, computed_tokens, strict=True)
|
||||
)
|
||||
@@ -92,6 +92,13 @@ class SupportsStepExecution(Protocol):
|
||||
``prepare_encode()`` (one-time request setup), ``denoise_step()``
|
||||
(one denoise forward), ``step_scheduler()`` (one scheduler update),
|
||||
and ``post_decode()`` (final decode).
|
||||
|
||||
A pipeline may additionally set the optional class attribute
|
||||
``supports_chunk_step_grouping = True`` to declare that its request state
|
||||
may advance through every denoise step of its current chunk without a
|
||||
serving-scheduler cycle in between (a capability, not a policy: the runner
|
||||
that owns the scheduling decision chooses whether to group steps). It is
|
||||
optional so it does not become part of the runtime protocol check.
|
||||
"""
|
||||
|
||||
supports_step_execution: ClassVar[bool] = True
|
||||
@@ -151,10 +158,10 @@ class SupportsInteractionApply(Protocol):
|
||||
"""Optional protocol for pipelines with unified mid-generation, chunk-boundary hooks."""
|
||||
|
||||
def peek_chunk_media(self, state: StepRequestState) -> ChunkMediaSpec:
|
||||
"""Return the media timeline represented by the upcoming/current chunk.
|
||||
"""Return the media timeline and latent frame count for the upcoming/current chunk.
|
||||
|
||||
Useful when interaction handler needs interpolation/integration on a frame-by-frame basis,
|
||||
or for backpressure/pacing.
|
||||
and/or for backpressure/pacing.
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ from vllm_omni.diffusion.models.bagel.pipeline_bagel import (
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
from vllm_omni.model_executor.models.utils import normalize_decoded_video_frames
|
||||
|
||||
from .lance_transformer import (
|
||||
LanceBagel,
|
||||
@@ -1454,6 +1455,8 @@ class LancePipeline(BagelPipeline):
|
||||
frames_bgr.append(_cv2.cvtColor(f, _cv2.COLOR_BGR2RGB))
|
||||
cap.release()
|
||||
video_raw = _np.stack(frames_bgr, axis=0)
|
||||
elif isinstance(video_input, (list, tuple)):
|
||||
video_raw, origin_fps = normalize_decoded_video_frames(video_input, default_fps=origin_fps_default)
|
||||
elif isinstance(video_input, _np.ndarray):
|
||||
video_raw = video_input
|
||||
origin_fps = origin_fps_default
|
||||
|
||||
@@ -25,6 +25,7 @@ from vllm_omni.experimental.ar_diffusion.tick_protocol import (
|
||||
|
||||
LINGBOT_CAMERA_ACTION_SCHEMA = "lingbot.camera_actions.v1"
|
||||
LINGBOT_CAMERA_TRAJECTORY_SCHEMA = "lingbot.camera_trajectory.v1"
|
||||
LINGBOT_CONTROLLER_TRANSLATION_UNIT = 0.05
|
||||
_ACTION_ORDER = ("w", "a", "s", "d", "i", "j", "k", "l")
|
||||
_VALID_ACTIONS = frozenset(_ACTION_ORDER)
|
||||
_REFERENCE_HEIGHT = 480
|
||||
@@ -282,7 +283,7 @@ def integrate_lingbot_camera_actions(
|
||||
"""Convert latent-frame WASD/IJKL controls to cumulative C2W poses.
|
||||
|
||||
Calibration and motion constants intentionally match SGLang's LingBot
|
||||
adapter: movement 0.05, pitch 4 degrees, yaw 6 degrees, pitch clamp 85
|
||||
adapter: movement 0.05 (LINGBOT_CONTROLLER_TRANSLATION_UNIT), pitch 4 degrees, yaw 6 degrees, pitch clamp 85
|
||||
degrees, and target-resolution focal lengths of 500 pixels.
|
||||
"""
|
||||
|
||||
@@ -325,13 +326,31 @@ def integrate_lingbot_camera_actions(
|
||||
right /= right_norm + 1e-6
|
||||
|
||||
movement = np.zeros(3, dtype=np.float64)
|
||||
movement += forward * 0.05 * (("w" in actions) - ("s" in actions))
|
||||
movement += right * 0.05 * (("d" in actions) - ("a" in actions))
|
||||
movement += forward * LINGBOT_CONTROLLER_TRANSLATION_UNIT * (("w" in actions) - ("s" in actions))
|
||||
movement += right * LINGBOT_CONTROLLER_TRANSLATION_UNIT * (("d" in actions) - ("a" in actions))
|
||||
# Keep the cumulative controller pose in FP64 between chunks, matching
|
||||
# SGLang's NumPy integration and avoiding long-session drift.
|
||||
current_pose = np.eye(4, dtype=np.float64)
|
||||
current_pose[:3, :3] = new_rotation
|
||||
current_pose[:3, 3] = translation + movement
|
||||
poses.append(current_pose)
|
||||
|
||||
trajectory = camera_trajectory_from_absolute_pose(torch.from_numpy(np.stack(poses)), width=width, height=height)
|
||||
return trajectory, current_pitch
|
||||
|
||||
|
||||
def camera_trajectory_from_absolute_pose(
|
||||
poses: torch.Tensor,
|
||||
*,
|
||||
width: int,
|
||||
height: int,
|
||||
) -> CameraTrajectory:
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("camera action resolution must be positive.")
|
||||
if poses.ndim != 3 or poses.shape[-2:] != (4, 4):
|
||||
raise ValueError(f"absolute camera poses must have shape [frames, 4, 4], got {tuple(poses.shape)}.")
|
||||
if poses.shape[0] == 0:
|
||||
raise ValueError("absolute camera poses must not be empty.")
|
||||
# build_plucker_embedding expects intrinsics in the 832x480 reference
|
||||
# coordinate system. These values become SGLang's [500, 500, W/2, H/2]
|
||||
# after that function scales them to the requested resolution.
|
||||
@@ -342,9 +361,7 @@ def integrate_lingbot_camera_actions(
|
||||
_REFERENCE_HEIGHT / 2,
|
||||
)
|
||||
trajectory = CameraTrajectory(
|
||||
# Keep the cumulative controller pose in FP64 between chunks, matching
|
||||
# SGLang's NumPy integration and avoiding long-session drift.
|
||||
poses=torch.from_numpy(np.stack(poses)),
|
||||
poses=poses,
|
||||
intrinsics=torch.tensor(reference_intrinsics, dtype=torch.float32).repeat(len(poses), 1),
|
||||
)
|
||||
return trajectory, current_pitch
|
||||
return trajectory
|
||||
@@ -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
|
||||
"""Camera trajectory loading and geometry for LingBot World v2 conditioning."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +19,6 @@ import torch
|
||||
|
||||
_REFERENCE_HEIGHT = 480
|
||||
_REFERENCE_WIDTH = 832
|
||||
_MAX_ACTION_FRAMES = 117
|
||||
_MAX_SOURCE_ACTION_FRAMES = 4096
|
||||
_MAX_NPY_HEADER_BYTES = 10_000
|
||||
_DIRECTORY_OPEN_FLAGS = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
||||
@@ -207,9 +206,7 @@ def _load_bounded_npy(
|
||||
array = np.load(snapshot_file, allow_pickle=False)
|
||||
except (EOFError, TypeError, ValueError):
|
||||
raise ValueError(f"{filename} does not contain a valid numeric NPY array.") from None
|
||||
# Official LingBot trajectories may be longer than one request. Only
|
||||
# materialize the bounded prefix that any supported request can consume.
|
||||
result: np.ndarray = np.asarray(array[:_MAX_ACTION_FRAMES], dtype=np.float32)
|
||||
result: np.ndarray = np.asarray(array, dtype=np.float32)
|
||||
return result
|
||||
|
||||
|
||||
@@ -392,7 +389,11 @@ def _invert_camera_poses(poses: torch.Tensor) -> torch.Tensor:
|
||||
return inverse
|
||||
|
||||
|
||||
def _prepare_framewise_poses(raw_poses: torch.Tensor) -> torch.Tensor:
|
||||
def _prepare_framewise_poses(
|
||||
raw_poses: torch.Tensor,
|
||||
*,
|
||||
translation_scale: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Convert raw C2W poses to normalized first-relative framewise deltas."""
|
||||
|
||||
# Remove global placement, then convert the sequence to framewise deltas.
|
||||
@@ -405,12 +406,19 @@ def _prepare_framewise_poses(raw_poses: torch.Tensor) -> torch.Tensor:
|
||||
relative_poses[1:],
|
||||
)
|
||||
|
||||
# Only relative direction/magnitude matters to the checkpoint; normalizing
|
||||
# by the largest step removes the trajectory's arbitrary translation scale.
|
||||
# Normalizing the control's scale. Different between scripted and realtime input.
|
||||
translations = relative_poses[:, :3, 3]
|
||||
max_translation_norm = torch.linalg.vector_norm(translations, dim=-1).max()
|
||||
if max_translation_norm > 0:
|
||||
relative_poses[:, :3, 3] = translations / max_translation_norm
|
||||
if translation_scale is None:
|
||||
# Scripted action_path input: divide by the largest step so an arbitrary recording scale becomes 1.
|
||||
scale = torch.linalg.vector_norm(translations, dim=-1).max()
|
||||
else:
|
||||
# Realtime interaction input: use the controller translation unit (one WASD step = full speed).
|
||||
# It cannot see future motion or normalize globally.
|
||||
if translation_scale <= 0:
|
||||
raise ValueError(f"translation_scale must be > 0, got {translation_scale}")
|
||||
scale = translation_scale
|
||||
if float(scale) > 0:
|
||||
relative_poses[:, :3, 3] = translations / scale
|
||||
return relative_poses
|
||||
|
||||
|
||||
@@ -423,6 +431,7 @@ def build_plucker_embedding(
|
||||
target_width: int,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
translation_scale: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Build checkpoint-ordered ``(ray origin, ray direction)`` channels."""
|
||||
|
||||
@@ -441,7 +450,10 @@ def build_plucker_embedding(
|
||||
|
||||
# Compute geometry in at least FP32, then cast at the model boundary.
|
||||
compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
|
||||
poses = _prepare_framewise_poses(trajectory.poses.to(device=device, dtype=compute_dtype))
|
||||
poses = _prepare_framewise_poses(
|
||||
trajectory.poses.to(device=device, dtype=compute_dtype),
|
||||
translation_scale=translation_scale,
|
||||
)
|
||||
intrinsics = trajectory.intrinsics.to(device=device, dtype=compute_dtype).clone()
|
||||
intrinsics[:, (0, 2)] *= width / _REFERENCE_WIDTH
|
||||
intrinsics[:, (1, 3)] *= height / _REFERENCE_HEIGHT
|
||||
|
||||
@@ -22,6 +22,7 @@ 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 (
|
||||
CameraModulationCache,
|
||||
LingBotAttentionCache,
|
||||
LingBotTransformerCache,
|
||||
)
|
||||
@@ -109,11 +110,16 @@ class LingBotDMDBlockRunner:
|
||||
start_frame: int,
|
||||
timestep_value: float,
|
||||
step_index: int,
|
||||
camera_cache: CameraModulationCache | None = None,
|
||||
) -> 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.
|
||||
|
||||
``camera_cache`` is the block's camera-modulation cache when the caller
|
||||
holds it across separate calls (the stepwise path); ``generate_block``
|
||||
opens the window itself instead.
|
||||
"""
|
||||
if not self.enforce_eager:
|
||||
torch.compiler.cudagraph_mark_step_begin()
|
||||
@@ -130,6 +136,7 @@ class LingBotDMDBlockRunner:
|
||||
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=False),
|
||||
start_frame=start_frame,
|
||||
update_cache=False,
|
||||
camera_modulation_cache=camera_cache,
|
||||
)
|
||||
if flow_prediction.shape != current_latents.shape:
|
||||
raise RuntimeError(
|
||||
@@ -172,11 +179,13 @@ class LingBotDMDBlockRunner:
|
||||
cache: LingBotTransformerCache | None,
|
||||
ar: ARBlockContext | None,
|
||||
start_frame: int,
|
||||
camera_cache: CameraModulationCache | None = None,
|
||||
) -> 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()``.
|
||||
on the stepwise path it belongs to ``post_decode()``. ``camera_cache``
|
||||
is as in ``probe_step``.
|
||||
"""
|
||||
# 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)
|
||||
@@ -190,6 +199,7 @@ class LingBotDMDBlockRunner:
|
||||
cache=self._block_cache(condition=condition, cache=cache, ar=ar, commit_current=True),
|
||||
start_frame=start_frame,
|
||||
update_cache=True,
|
||||
camera_modulation_cache=camera_cache,
|
||||
)
|
||||
if ar is not None:
|
||||
ar.state.commit_paged_context(ar.branch)
|
||||
@@ -210,6 +220,10 @@ class LingBotDMDBlockRunner:
|
||||
"""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)
|
||||
# Every forward below -- each probe and the commit -- reads the same camera trajectory, so the camera
|
||||
# injector is built once per block: one cache for the whole loop, exactly as the stepwise path holds
|
||||
# one per block across its separate calls.
|
||||
camera_cache = CameraModulationCache()
|
||||
for step_index, (timestep_value, sigma) in enumerate(schedule):
|
||||
flow_prediction = self.probe_step(
|
||||
current_latents=current_latents,
|
||||
@@ -221,6 +235,7 @@ class LingBotDMDBlockRunner:
|
||||
start_frame=start_frame,
|
||||
timestep_value=timestep_value,
|
||||
step_index=step_index,
|
||||
camera_cache=camera_cache,
|
||||
)
|
||||
next_sigma = schedule[step_index + 1][1] if step_index + 1 < len(schedule) else None
|
||||
current_latents = self.apply_transition(
|
||||
@@ -235,5 +250,6 @@ class LingBotDMDBlockRunner:
|
||||
cache=cache,
|
||||
ar=ar,
|
||||
start_frame=start_frame,
|
||||
camera_cache=camera_cache,
|
||||
)
|
||||
return current_latents
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 1332 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user