Merge branch 'main' into lance-model-support; drop lance.yaml
Resolves conflicts in:
- vllm_omni/diffusion/registry.py: keep both LancePipeline (HEAD)
and MingImagePipeline (main) entries.
- vllm_omni/diffusion/models/bagel/bagel_transformer.py: take main's
simpler cfg_batched payload; HEAD referenced undefined locals.
Also strips vllm_omni/deploy/lance.yaml -- Lance is single-stage
diffusion, so its engine knobs (pipeline=lance, enforce_eager,
trust_remote_code, max_num_seqs=1, ...) flow directly to Omni(...)
/ vllm-omni serve instead of through a deploy YAML.
create_default_diffusion builds the stage config from those kwargs.
Touched: examples/offline_inference/lance/{end2end,gradio_demo}.py,
tests/e2e/online_serving/test_lance.py, tests/helpers/stage_config.py.
Signed-off-by: lishunyang12 <lishunyang12@163.com>
This commit is contained in:
commit
c15f51a2f6
419 files changed
+46193
-5592
No files matched your search
@@ -0,0 +1,104 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
from torch.nn.attention import SDPBackend, sdpa_kernel
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import (
|
||||
AttentionBackend,
|
||||
AttentionImpl,
|
||||
AttentionMetadata,
|
||||
)
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import _maybe_reshape_attn_mask
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class CuDNNAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
|
||||
@classmethod
|
||||
def supports_attention_mask(cls) -> bool:
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_supported_head_sizes() -> list[int]:
|
||||
# cuDNN 9.5+ FMHA on Blackwell supports any head_dim divisible by 8
|
||||
# up to 256 for BF16/FP16. Empty list = "accept any"; the sdpa_kernel
|
||||
# fallback chain handles shapes cuDNN can't take.
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "CUDNN_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type["CuDNNAttentionImpl"]:
|
||||
return CuDNNAttentionImpl
|
||||
|
||||
|
||||
class CuDNNAttentionImpl(AttentionImpl):
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
softmax_scale: float,
|
||||
causal: bool = False,
|
||||
num_kv_heads: int | None = None,
|
||||
prefix: str = "",
|
||||
**extra_impl_args,
|
||||
) -> None:
|
||||
self.causal = causal
|
||||
self.softmax_scale = softmax_scale
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
attention_mask = None
|
||||
if attn_metadata:
|
||||
attention_mask = _maybe_reshape_attn_mask(query, key, attn_metadata.attn_mask, mask_mode="broadcast_k")
|
||||
|
||||
query, key, value = (x.permute(0, 2, 1, 3) for x in (query, key, value))
|
||||
# Pin cuDNN exclusively. A priority list like [CUDNN, FLASH, MATH] hits a
|
||||
# PyTorch SDPA dispatch quirk: when FLASH rejects a non-None attn_mask,
|
||||
# cuDNN gets runtime-disabled in the same call and the dispatcher falls
|
||||
# through to MATH even though cuDNN alone handles the mask fine
|
||||
# (~11 ms vs ~215 ms for MATH on sm_120 HV-1.5 shapes).
|
||||
#
|
||||
# Fall back to the default SDPA dispatcher if cuDNN rejects the shape,
|
||||
# e.g. under torch.compile where Dynamo sees a symbolic head_dim and
|
||||
# cuDNN's kernel selection fails (observed in LTX-2 audio attention).
|
||||
# The unpinned dispatcher then picks EFFICIENT/MATH instead of raising.
|
||||
try:
|
||||
with sdpa_kernel([SDPBackend.CUDNN_ATTENTION]):
|
||||
output = torch.nn.functional.scaled_dot_product_attention(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=0.0,
|
||||
is_causal=self.causal,
|
||||
scale=self.softmax_scale,
|
||||
)
|
||||
except RuntimeError as e:
|
||||
if "No available kernel" not in str(e):
|
||||
raise
|
||||
logger.warning_once(
|
||||
"cuDNN SDPA rejected this shape; falling back to default SDPA dispatcher. "
|
||||
"Set DIFFUSION_ATTENTION_BACKEND=TORCH_SDPA for the full dispatcher path on every call."
|
||||
)
|
||||
output = torch.nn.functional.scaled_dot_product_attention(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
attn_mask=attention_mask,
|
||||
dropout_p=0.0,
|
||||
is_causal=self.causal,
|
||||
scale=self.softmax_scale,
|
||||
)
|
||||
return output.permute(0, 2, 1, 3)
|
||||
@@ -0,0 +1,183 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import (
|
||||
AttentionBackend,
|
||||
AttentionImpl,
|
||||
AttentionMetadata,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
try:
|
||||
from flashinfer.prefill import single_prefill_with_kv_cache
|
||||
|
||||
HAS_FLASHINFER = True
|
||||
except Exception as e:
|
||||
HAS_FLASHINFER = False
|
||||
logger.warning(
|
||||
"FlashInfer is unavailable; FLASHINFER_ATTN backend will not work. Reason: %s",
|
||||
e,
|
||||
)
|
||||
|
||||
|
||||
class FlashInferAttentionBackend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
|
||||
@classmethod
|
||||
def supports_attention_mask(cls) -> bool:
|
||||
# FlashInfer single_prefill_with_kv_cache accepts a ``custom_mask`` kwarg
|
||||
# (2D boolean, ``True`` = keep) for non-causal attention. See reviewer
|
||||
# comment on #3079 and the flashinfer docs:
|
||||
# https://docs.flashinfer.ai/generated/flashinfer.prefill.single_prefill_with_kv_cache.html
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_supported_head_sizes() -> list[int]:
|
||||
# FlashInfer dense prefill is well-tested for these head_dims on
|
||||
# Ampere/Hopper/Blackwell. Covers the dominant diffusion DiT shapes
|
||||
# (SD3 = 64, Flux/HV/Wan = 128, joint-attn = 256).
|
||||
return [64, 128, 256]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "FLASHINFER_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type["FlashInferAttentionImpl"]:
|
||||
return FlashInferAttentionImpl
|
||||
|
||||
|
||||
class FlashInferAttentionImpl(AttentionImpl):
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
softmax_scale: float,
|
||||
causal: bool = False,
|
||||
num_kv_heads: int | None = None,
|
||||
prefix: str = "",
|
||||
**extra_impl_args,
|
||||
) -> None:
|
||||
self.causal = causal
|
||||
self.softmax_scale = softmax_scale
|
||||
|
||||
@staticmethod
|
||||
def _pack_mask_for_flashinfer(
|
||||
attn_mask: torch.Tensor, batch_size: int, qo_len: int, kv_len: int
|
||||
) -> torch.Tensor | None:
|
||||
"""Convert a diffusion-style attn_mask into the boolean form
|
||||
FlashInfer's ``custom_mask`` expects (``True`` = keep).
|
||||
|
||||
Returns either ``(qo_len, kv_len)`` (shared across the batch) or
|
||||
``(batch_size, qo_len, kv_len)`` (per-sample), or ``None`` when the
|
||||
mask is all-keep (elide). Only boolean masks are handled here;
|
||||
additive/float masks raise ``ValueError`` so the caller falls back to
|
||||
SDPA, which applies them with the correct softmax semantics. Shape
|
||||
mismatches also raise ``ValueError``.
|
||||
"""
|
||||
mask = attn_mask
|
||||
if mask.dtype != torch.bool:
|
||||
# Additive masks (0 / -inf / -1e4 / finfo.min) cannot be faithfully
|
||||
# reduced to a boolean keep-mask here; SDPA handles them correctly.
|
||||
raise ValueError(
|
||||
f"non-boolean attn_mask (dtype={mask.dtype}); FlashInfer custom_mask "
|
||||
"is boolean-only — deferring to SDPA"
|
||||
)
|
||||
# Diffusion masks arrive as (qo,kv), (1,1,kv), (B,1,1,kv), (B,1,qo,kv)
|
||||
# or (B,H,qo,kv). The mask is identical across heads, so collapse the
|
||||
# head dim, but keep a real batch dim — indexing mask[0] would reuse
|
||||
# sample 0's padding for every sample (wrong under CFG / mixed lengths).
|
||||
if mask.dim() == 4:
|
||||
mask = mask[:, 0] # (B, qo|1, kv)
|
||||
if mask.dim() == 3 and mask.shape[0] == 1:
|
||||
mask = mask[0] # (qo|1, kv) — shared across the batch
|
||||
try:
|
||||
if mask.dim() >= 3:
|
||||
mask = mask.broadcast_to((batch_size, qo_len, kv_len))
|
||||
else:
|
||||
mask = mask.broadcast_to((qo_len, kv_len))
|
||||
except RuntimeError as e:
|
||||
raise ValueError(
|
||||
f"attn_mask shape {tuple(attn_mask.shape)} cannot broadcast to "
|
||||
f"(batch={batch_size}, qo_len={qo_len}, kv_len={kv_len})"
|
||||
) from e
|
||||
if mask.all():
|
||||
return None
|
||||
# ``broadcast_to`` returns a non-contiguous view; materialize for the
|
||||
# kernel, which reads from GPU memory directly.
|
||||
return mask.contiguous()
|
||||
|
||||
def _sdpa_fallback(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None,
|
||||
) -> torch.Tensor:
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPAImpl
|
||||
|
||||
impl = SDPAImpl(
|
||||
num_heads=query.shape[2],
|
||||
head_size=query.shape[3],
|
||||
softmax_scale=self.softmax_scale,
|
||||
causal=self.causal,
|
||||
)
|
||||
return impl.forward_cuda(query, key, value, attn_metadata)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
if not HAS_FLASHINFER:
|
||||
raise ImportError(
|
||||
"FLASHINFER_ATTN backend requires flashinfer. "
|
||||
"Install it or set DIFFUSION_ATTENTION_BACKEND to another backend."
|
||||
)
|
||||
|
||||
# Try the custom_mask path; if the mask can't be packed into the
|
||||
# (qo_len, kv_len) layout FlashInfer expects, fall back to SDPA
|
||||
# instead of risking an illegal-memory-access crash in the kernel.
|
||||
# Input layout is (B, S, H, D); FlashInfer dense prefill takes (S, H, D).
|
||||
batch_size = query.shape[0]
|
||||
|
||||
custom_mask = None
|
||||
if attn_metadata is not None and attn_metadata.attn_mask is not None:
|
||||
try:
|
||||
custom_mask = self._pack_mask_for_flashinfer(
|
||||
attn_metadata.attn_mask,
|
||||
batch_size=batch_size,
|
||||
qo_len=query.shape[1],
|
||||
kv_len=key.shape[1],
|
||||
)
|
||||
except ValueError as e:
|
||||
logger.debug("Falling back to SDPA for mask path: %s", e)
|
||||
return self._sdpa_fallback(query, key, value, attn_metadata)
|
||||
# FlashInfer cannot combine causal masking with a custom_mask; rather
|
||||
# than silently dropping the explicit mask (diverging from SDPA), let
|
||||
# SDPA handle the causal+mask case correctly.
|
||||
if custom_mask is not None and self.causal:
|
||||
logger.debug("causal=True with explicit attn_mask; deferring to SDPA")
|
||||
return self._sdpa_fallback(query, key, value, attn_metadata)
|
||||
|
||||
outputs = []
|
||||
for b in range(batch_size):
|
||||
kwargs: dict = {
|
||||
"sm_scale": self.softmax_scale,
|
||||
"causal": self.causal,
|
||||
"return_lse": False,
|
||||
}
|
||||
if custom_mask is not None:
|
||||
kwargs["custom_mask"] = custom_mask if custom_mask.dim() == 2 else custom_mask[b]
|
||||
out = single_prefill_with_kv_cache(query[b], key[b], value[b], **kwargs)
|
||||
outputs.append(out)
|
||||
|
||||
if batch_size == 1:
|
||||
return outputs[0].unsqueeze(0)
|
||||
return torch.stack(outputs, dim=0)
|
||||
@@ -59,6 +59,9 @@ class DiffusionAttentionBackendEnum(Enum, metaclass=_DiffusionBackendEnumMeta):
|
||||
FLASH_ATTN = "vllm_omni.diffusion.attention.backends.flash_attn.FlashAttentionBackend"
|
||||
TORCH_SDPA = "vllm_omni.diffusion.attention.backends.sdpa.SDPABackend"
|
||||
SAGE_ATTN = "vllm_omni.diffusion.attention.backends.sage_attn.SageAttentionBackend"
|
||||
SAGE_ATTN_3 = "vllm_omni.diffusion.attention.backends.sage_attn3.SageAttention3Backend"
|
||||
CUDNN_ATTN = "vllm_omni.diffusion.attention.backends.cudnn_attn.CuDNNAttentionBackend"
|
||||
FLASHINFER_ATTN = "vllm_omni.diffusion.attention.backends.flashinfer_attn.FlashInferAttentionBackend"
|
||||
|
||||
def get_path(self, include_classname: bool = True) -> str:
|
||||
"""Get the class path for this backend (respects overrides).
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import (
|
||||
AttentionBackend,
|
||||
AttentionImpl,
|
||||
AttentionMetadata,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
try:
|
||||
from sageattn3 import sageattn3_blackwell # noqa: F401
|
||||
except ImportError:
|
||||
logger.warning(
|
||||
"SageAttention3Backend is not available. Install `sageattn3` from "
|
||||
"https://github.com/thu-ml/SageAttention/tree/main/sageattention3_blackwell"
|
||||
)
|
||||
raise ImportError
|
||||
|
||||
|
||||
# Wrapping sageattn3_blackwell as a torch.library custom op keeps it opaque to
|
||||
# torch.compile. Otherwise Dynamo graph-breaks on the raw pybind11 kernel and
|
||||
# Inductor fails scheduling with KeyError: 'op5'. The hasattr guard keeps this
|
||||
# idempotent across test re-imports that pop the module from sys.modules.
|
||||
if not hasattr(torch.ops.vllm_omni, "sageattn3_blackwell"):
|
||||
|
||||
@torch.library.custom_op("vllm_omni::sageattn3_blackwell", mutates_args=())
|
||||
def _sageattn3_blackwell_op(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
is_causal: bool,
|
||||
) -> torch.Tensor:
|
||||
from sageattn3 import sageattn3_blackwell as _kernel
|
||||
|
||||
return _kernel(query, key, value, is_causal=is_causal)
|
||||
|
||||
@_sageattn3_blackwell_op.register_fake
|
||||
def _(query, key, value, is_causal):
|
||||
return torch.empty_like(query)
|
||||
|
||||
|
||||
_sageattn3_blackwell_op = torch.ops.vllm_omni.sageattn3_blackwell
|
||||
|
||||
|
||||
class SageAttention3Backend(AttentionBackend):
|
||||
accept_output_buffer: bool = True
|
||||
|
||||
@staticmethod
|
||||
def get_supported_head_sizes() -> list[int]:
|
||||
return [64, 128, 256]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "SAGE_ATTN_3"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type["SageAttention3Impl"]:
|
||||
return SageAttention3Impl
|
||||
|
||||
|
||||
class SageAttention3Impl(AttentionImpl):
|
||||
_warned_gqa_fallback_global: bool = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
softmax_scale: float,
|
||||
causal: bool = False,
|
||||
num_kv_heads: int | None = None,
|
||||
prefix: str = "",
|
||||
**extra_impl_args,
|
||||
) -> None:
|
||||
self.causal = causal
|
||||
self.softmax_scale = softmax_scale
|
||||
self.dropout = extra_impl_args.get("dropout_p", 0.0)
|
||||
|
||||
def forward_cuda(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
query = query.transpose(1, 2).contiguous()
|
||||
key = key.transpose(1, 2).contiguous()
|
||||
value = value.transpose(1, 2).contiguous()
|
||||
|
||||
if key.shape[1] != query.shape[1]:
|
||||
if query.shape[1] % key.shape[1] != 0:
|
||||
raise ValueError(
|
||||
"GQA/MQA requires query heads to be a multiple of KV heads, "
|
||||
f"got q_heads={query.shape[1]} and kv_heads={key.shape[1]}"
|
||||
)
|
||||
if not type(self)._warned_gqa_fallback_global:
|
||||
logger.warning("SageAttention3 does not support GQA/MQA (Hq != Hkv); falling back to torch SDPA.")
|
||||
type(self)._warned_gqa_fallback_global = True
|
||||
output = F.scaled_dot_product_attention(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
is_causal=self.causal,
|
||||
dropout_p=self.dropout,
|
||||
scale=self.softmax_scale,
|
||||
enable_gqa=True,
|
||||
)
|
||||
else:
|
||||
output = _sageattn3_blackwell_op(query, key, value, self.causal)
|
||||
|
||||
return output.transpose(1, 2).contiguous()
|
||||
@@ -30,10 +30,6 @@ def _maybe_reshape_attn_mask(
|
||||
- broadcast_k: [batch_size, 1, 1, seq_len_k]
|
||||
- full_qk: [batch_size, 1, seq_len_q, seq_len_k]
|
||||
"""
|
||||
# Skip Attention Mask if all values are 1, `None` mask can speedup the computation
|
||||
if attn_mask is not None and torch.all(attn_mask != 0):
|
||||
attn_mask = None
|
||||
|
||||
# Reshape Attention Mask
|
||||
# 2D [batch_size, seq_len_k] mask only.
|
||||
if (
|
||||
@@ -89,6 +85,7 @@ class SDPAImpl(AttentionImpl):
|
||||
) -> None:
|
||||
self.causal = causal
|
||||
self.softmax_scale = softmax_scale
|
||||
self.requires_gqa = num_heads != num_kv_heads
|
||||
if backend_kwargs:
|
||||
logger.warning("SDPAImpl ignoring backend_kwargs: %s", list(backend_kwargs.keys()))
|
||||
|
||||
@@ -115,6 +112,7 @@ class SDPAImpl(AttentionImpl):
|
||||
dropout_p=0.0,
|
||||
is_causal=self.causal,
|
||||
scale=self.softmax_scale,
|
||||
enable_gqa=self.requires_gqa,
|
||||
)
|
||||
out = output.permute(0, 2, 1, 3)
|
||||
return out
|
||||
|
||||
@@ -10,7 +10,7 @@ import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
# import torch.distributed as dist # Not used directly here, but good practice if needed
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_globals import HAS_FA3, HAS_FLASH_ATTN
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_globals import HAS_AITER, HAS_FA3, HAS_FLASH_ATTN
|
||||
from vllm_omni.diffusion.attention.backends.ring.ring_selector import AttnType
|
||||
from vllm_omni.diffusion.attention.parallel.base import (
|
||||
ParallelAttentionContext,
|
||||
@@ -110,13 +110,12 @@ class RingParallelAttention:
|
||||
if backend_pref is not None:
|
||||
backend_pref = backend_pref.lower()
|
||||
|
||||
# Determine attention type with fallback chain: FA3 -> FA2 -> SDPA
|
||||
# FP32 is not supported by Flash Attention, force SDPA
|
||||
if query.dtype == torch.float32:
|
||||
backend_pref = "sdpa"
|
||||
elif not HAS_FA3 and not HAS_FLASH_ATTN:
|
||||
elif not HAS_FA3 and not HAS_FLASH_ATTN and not HAS_AITER:
|
||||
if backend_pref != "sdpa":
|
||||
logger.warning_once("Flash Attention (FA2/FA3) is not available! Force enabling SDPA.")
|
||||
logger.warning_once("Flash Attention (FA2/FA3/AITER) is not available! Force enabling SDPA.")
|
||||
backend_pref = "sdpa"
|
||||
|
||||
# Extract joint tensors
|
||||
@@ -147,7 +146,13 @@ class RingParallelAttention:
|
||||
from vllm_omni.diffusion.attention.backends.ring_flash_attn import ring_flash_attn_func
|
||||
|
||||
# Prefer FA3 over FA2 for better performance (FA3 supports Ampere/Ada/Hopper)
|
||||
attn_type = AttnType.FA3 if HAS_FA3 else AttnType.FA
|
||||
# On ROCm, use AITER
|
||||
if HAS_FA3:
|
||||
attn_type = AttnType.FA3
|
||||
elif HAS_AITER:
|
||||
attn_type = AttnType.AITER
|
||||
else:
|
||||
attn_type = AttnType.FA
|
||||
|
||||
return ring_flash_attn_func(
|
||||
query,
|
||||
|
||||
+12
-1
@@ -5,12 +5,19 @@ Cache module for diffusion model inference acceleration.
|
||||
|
||||
This module provides a unified cache backend system for different caching strategies:
|
||||
- TeaCache: Timestep Embedding Aware Cache for adaptive transformer caching
|
||||
- MagCache: Magnitude-based Cache for adaptive transformer caching
|
||||
- cache-dit: DBCache, SCM, and TaylorSeer caching strategies
|
||||
|
||||
Cache backends are instantiated directly via their constructors and configured via OmniDiffusionConfig.
|
||||
"""
|
||||
|
||||
from vllm_omni.diffusion.cache.base import CacheBackend
|
||||
from vllm_omni.diffusion.cache.prompt_embed_cache import (
|
||||
PromptEmbedCache,
|
||||
install_prompt_embed_cache,
|
||||
resolve_prompt_embed_cache_config,
|
||||
uninstall_prompt_embed_cache,
|
||||
)
|
||||
from vllm_omni.diffusion.cache.teacache import (
|
||||
CacheContext,
|
||||
TeaCacheConfig,
|
||||
@@ -20,8 +27,12 @@ from vllm_omni.diffusion.cache.teacache.backend import TeaCacheBackend
|
||||
|
||||
__all__ = [
|
||||
"CacheBackend",
|
||||
"TeaCacheConfig",
|
||||
"CacheContext",
|
||||
"TeaCacheBackend",
|
||||
"TeaCacheConfig",
|
||||
"apply_teacache_hook",
|
||||
"PromptEmbedCache",
|
||||
"install_prompt_embed_cache",
|
||||
"resolve_prompt_embed_cache_config",
|
||||
"uninstall_prompt_embed_cache",
|
||||
]
|
||||
+228
-1
@@ -18,6 +18,7 @@ from cache_dit import BlockAdapter, DBCacheConfig, ForwardPattern, ParamsModifie
|
||||
from cache_dit.caching.block_adapters import FakeDiffusionPipeline
|
||||
from cache_dit.caching.cache_adapters.cache_adapter import CachedAdapter
|
||||
from cache_dit.caching.cache_blocks.pattern_0_1_2 import CachedBlocks_Pattern_0_1_2
|
||||
from cache_dit.caching.cache_blocks.pattern_3_4_5 import CachedBlocks_Pattern_3_4_5
|
||||
from cache_dit.caching.cache_contexts import BasicCacheConfig
|
||||
from cache_dit.caching.cache_contexts.cache_manager import CachedContextManager
|
||||
from vllm.logger import init_logger
|
||||
@@ -1170,6 +1171,162 @@ def enable_cache_for_bagel(pipeline: Any, cache_config: Any) -> Callable[[int],
|
||||
return refresh_cache_context
|
||||
|
||||
|
||||
class SensenovaCachedBlocks(CachedBlocks_Pattern_3_4_5):
|
||||
"""
|
||||
Custom CachedBlocks for SenseNova-U1 that only caches image-token hidden
|
||||
states during denoising.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def _is_denoising_call(cls, kwargs: dict[str, Any]) -> bool:
|
||||
if kwargs.get("cache_dit_skip", False):
|
||||
return False
|
||||
|
||||
# Prefix/text forwards either omit image_gen_indicators or update the
|
||||
# DynamicCache. Denoising forwards are gen-only and use update_cache=False.
|
||||
if kwargs.get("update_cache", True):
|
||||
return False
|
||||
|
||||
exist_gen = kwargs.get("exist_gen")
|
||||
exist_und = kwargs.get("exist_und")
|
||||
if exist_gen is None or exist_und is None:
|
||||
image_gen_indicators = kwargs.get("image_gen_indicators")
|
||||
if image_gen_indicators is None:
|
||||
return False
|
||||
exist_gen = image_gen_indicators.any().item()
|
||||
exist_und = (~image_gen_indicators).any().item()
|
||||
|
||||
return exist_gen and not exist_und
|
||||
|
||||
@staticmethod
|
||||
def _strip_cache_only_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
|
||||
kwargs = dict(kwargs)
|
||||
kwargs.pop("cache_dit_skip", None)
|
||||
return kwargs
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, *args, **kwargs):
|
||||
block_kwargs = self._strip_cache_only_kwargs(kwargs)
|
||||
if not self._is_denoising_call(kwargs):
|
||||
hidden_states, new_encoder_hidden_states = self.call_blocks(
|
||||
hidden_states,
|
||||
*args,
|
||||
**block_kwargs,
|
||||
)
|
||||
return self._process_forward_outputs(hidden_states, new_encoder_hidden_states)
|
||||
|
||||
return super().forward(hidden_states, *args, **block_kwargs)
|
||||
|
||||
|
||||
class SensenovaCachedAdapter(CachedAdapter):
|
||||
"""Custom CachedAdapter for SenseNova-U1 that uses SensenovaCachedBlocks."""
|
||||
|
||||
@classmethod
|
||||
def collect_unified_blocks(
|
||||
cls,
|
||||
block_adapter: BlockAdapter,
|
||||
contexts_kwargs: list[dict],
|
||||
) -> list[dict[str, torch.nn.ModuleList]]:
|
||||
BlockAdapter.assert_normalized(block_adapter)
|
||||
|
||||
total_cached_blocks: list[dict[str, torch.nn.ModuleList]] = []
|
||||
assert hasattr(block_adapter.pipe, "_context_manager")
|
||||
|
||||
for i in range(len(block_adapter.transformer)):
|
||||
unified_blocks_bind_context = {}
|
||||
for j in range(len(block_adapter.blocks[i])):
|
||||
cache_config: BasicCacheConfig = contexts_kwargs[i * len(block_adapter.blocks[i]) + j]["cache_config"]
|
||||
unified_blocks_bind_context[block_adapter.unique_blocks_name[i][j]] = torch.nn.ModuleList(
|
||||
[
|
||||
SensenovaCachedBlocks(
|
||||
# 0. Transformer blocks configuration
|
||||
block_adapter.blocks[i][j],
|
||||
transformer=block_adapter.transformer[i],
|
||||
forward_pattern=block_adapter.forward_pattern[i][j],
|
||||
check_forward_pattern=block_adapter.check_forward_pattern,
|
||||
check_num_outputs=block_adapter.check_num_outputs,
|
||||
# 1. Cache/Prune context configuration
|
||||
cache_prefix=block_adapter.blocks_name[i][j],
|
||||
cache_context=block_adapter.unique_blocks_name[i][j],
|
||||
context_manager=block_adapter.pipe._context_manager,
|
||||
cache_type=cache_config.cache_type,
|
||||
)
|
||||
]
|
||||
)
|
||||
|
||||
total_cached_blocks.append(unified_blocks_bind_context)
|
||||
|
||||
return total_cached_blocks
|
||||
|
||||
|
||||
def enable_cache_for_sensenova_u1(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
|
||||
"""Enable cache-dit for SenseNova-U1 model.
|
||||
|
||||
Args:
|
||||
pipeline: The SenseNova-U1 pipeline instance.
|
||||
cache_config: DiffusionCacheConfig instance with cache configuration.
|
||||
|
||||
Returns:
|
||||
A refresh function that can be called to update cache context with new num_inference_steps.
|
||||
"""
|
||||
transformer = getattr(getattr(pipeline, "language_model", None), "model", None)
|
||||
if transformer is None or not hasattr(transformer, "layers"):
|
||||
raise ValueError("SenseNovaU1Pipeline cache-dit expects pipeline.language_model.model.layers.")
|
||||
|
||||
# Build DBCacheConfig
|
||||
db_cache_config = _build_db_cache_config(cache_config)
|
||||
|
||||
calibrator_config = None
|
||||
if cache_config.enable_taylorseer:
|
||||
taylorseer_order = cache_config.taylorseer_order
|
||||
calibrator_config = TaylorSeerCalibratorConfig(taylorseer_order=taylorseer_order)
|
||||
logger.info(f"TaylorSeer enabled with order={taylorseer_order}")
|
||||
|
||||
modifier = ParamsModifier(
|
||||
cache_config=db_cache_config,
|
||||
calibrator_config=calibrator_config,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Enabling cache-dit on SenseNova-U1 decoder layers: "
|
||||
f"Fn={db_cache_config.Fn_compute_blocks}, "
|
||||
f"Bn={db_cache_config.Bn_compute_blocks}, "
|
||||
f"W={db_cache_config.max_warmup_steps}, "
|
||||
)
|
||||
|
||||
SensenovaCachedAdapter.apply(
|
||||
BlockAdapter(
|
||||
transformer=transformer,
|
||||
blocks=transformer.layers,
|
||||
forward_pattern=ForwardPattern.Pattern_3,
|
||||
params_modifiers=[modifier],
|
||||
check_forward_pattern=True,
|
||||
has_separate_cfg=True,
|
||||
),
|
||||
cache_config=db_cache_config,
|
||||
calibrator_config=calibrator_config,
|
||||
)
|
||||
|
||||
def refresh_cache_context(pipeline: Any, num_inference_steps: int, verbose: bool = True) -> None:
|
||||
transformer = pipeline.language_model.model
|
||||
if cache_config.scm_steps_mask_policy is None:
|
||||
cache_dit.refresh_context(transformer, num_inference_steps=num_inference_steps, verbose=verbose)
|
||||
else:
|
||||
cache_dit.refresh_context(
|
||||
transformer,
|
||||
cache_config=DBCacheConfig().reset(
|
||||
num_inference_steps=num_inference_steps,
|
||||
steps_computation_mask=cache_dit.steps_mask(
|
||||
mask_policy=cache_config.scm_steps_mask_policy,
|
||||
total_steps=num_inference_steps,
|
||||
),
|
||||
steps_computation_policy=cache_config.scm_steps_policy,
|
||||
),
|
||||
verbose=verbose,
|
||||
)
|
||||
|
||||
return refresh_cache_context
|
||||
|
||||
|
||||
def enable_cache_for_flux2(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
|
||||
"""Enable cache-dit for Flux.2-dev pipeline.
|
||||
|
||||
@@ -1320,6 +1477,74 @@ def enable_cache_for_glm_image(pipeline: Any, cache_config: Any) -> Callable[[in
|
||||
return refresh_cache_context
|
||||
|
||||
|
||||
def enable_cache_for_dreamid_omni(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
|
||||
"""Enable cache-dit for DreamID-Omni fused pipeline.
|
||||
|
||||
Args:
|
||||
pipeline: The DreamIDOmni pipeline instance.
|
||||
cache_config: DiffusionCacheConfig instance with cache configuration.
|
||||
|
||||
Returns:
|
||||
A refresh function that can be called with a new ``num_inference_steps``
|
||||
to update the cache context for the pipeline.
|
||||
"""
|
||||
transformer = getattr(pipeline, "transformer", None)
|
||||
fused_blocks = getattr(transformer, "fused_blocks", None)
|
||||
if transformer is None or fused_blocks is None:
|
||||
raise ValueError("DreamIDOmniPipeline cache-dit expects pipeline.transformer.fused_blocks.")
|
||||
|
||||
db_cache_config = _build_db_cache_config(cache_config)
|
||||
|
||||
calibrator = None
|
||||
if cache_config.enable_taylorseer:
|
||||
taylorseer_order = cache_config.taylorseer_order
|
||||
calibrator = TaylorSeerCalibratorConfig(taylorseer_order=taylorseer_order)
|
||||
logger.info(f"TaylorSeer enabled with order={taylorseer_order}")
|
||||
|
||||
modifier = ParamsModifier(
|
||||
cache_config=db_cache_config,
|
||||
calibrator_config=calibrator,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Enabling cache-dit on DreamID-Omni fused blocks: "
|
||||
f"Fn={db_cache_config.Fn_compute_blocks}, "
|
||||
f"Bn={db_cache_config.Bn_compute_blocks}, "
|
||||
f"W={db_cache_config.max_warmup_steps}, "
|
||||
)
|
||||
|
||||
cache_dit.enable_cache(
|
||||
BlockAdapter(
|
||||
transformer=transformer,
|
||||
blocks=fused_blocks,
|
||||
forward_pattern=ForwardPattern.Pattern_0,
|
||||
params_modifiers=[modifier],
|
||||
has_separate_cfg=True,
|
||||
),
|
||||
cache_config=db_cache_config,
|
||||
)
|
||||
|
||||
def refresh_cache_context(pipeline: Any, num_inference_steps: int, verbose: bool = True) -> None:
|
||||
transformer = pipeline.transformer
|
||||
if cache_config.scm_steps_mask_policy is None:
|
||||
cache_dit.refresh_context(transformer, num_inference_steps=num_inference_steps, verbose=verbose)
|
||||
else:
|
||||
cache_dit.refresh_context(
|
||||
transformer,
|
||||
cache_config=DBCacheConfig().reset(
|
||||
num_inference_steps=num_inference_steps,
|
||||
steps_computation_mask=cache_dit.steps_mask(
|
||||
mask_policy=cache_config.scm_steps_mask_policy,
|
||||
total_steps=num_inference_steps,
|
||||
),
|
||||
steps_computation_policy=cache_config.scm_steps_policy,
|
||||
),
|
||||
verbose=verbose,
|
||||
)
|
||||
|
||||
return refresh_cache_context
|
||||
|
||||
|
||||
def enable_cache_for_ernie_image(pipeline: Any, cache_config: Any) -> Callable[[int], None]:
|
||||
"""Enable cache-dit for ERNIE-Image pipeline.
|
||||
|
||||
@@ -1413,7 +1638,7 @@ def enable_cache_for_helios(pipeline: Any, cache_config: Any) -> Callable[[int],
|
||||
params_modifiers=[
|
||||
ParamsModifier(cache_config=db_cache_config, calibrator_config=calibrator_config),
|
||||
],
|
||||
has_separate_cfg=False,
|
||||
has_separate_cfg=True,
|
||||
),
|
||||
cache_config=db_cache_config,
|
||||
calibrator_config=calibrator_config,
|
||||
@@ -1519,8 +1744,10 @@ CUSTOM_DIT_ENABLERS.update(
|
||||
"LTX23Pipeline": enable_cache_for_ltx2,
|
||||
"LTX23ImageToVideoPipeline": enable_cache_for_ltx2,
|
||||
"BagelPipeline": enable_cache_for_bagel,
|
||||
"SenseNovaU1Pipeline": enable_cache_for_sensenova_u1,
|
||||
"GlmImagePipeline": enable_cache_for_glm_image,
|
||||
"Flux2Pipeline": enable_cache_for_flux2,
|
||||
"DreamIDOmniPipeline": enable_cache_for_dreamid_omni,
|
||||
"ErnieImagePipeline": enable_cache_for_ernie_image,
|
||||
"HunyuanVideo15Pipeline": enable_cache_for_hunyuan_video_15,
|
||||
"HunyuanVideo15I2VPipeline": enable_cache_for_hunyuan_video_15,
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from vllm_omni.diffusion.cache.magcache.config import MagCacheConfig
|
||||
from vllm_omni.diffusion.cache.magcache.hook import (
|
||||
MagCacheBlockHook,
|
||||
MagCacheHeadHook,
|
||||
MagCacheState,
|
||||
apply_mag_cache_hook,
|
||||
)
|
||||
from vllm_omni.diffusion.cache.magcache.strategy import (
|
||||
Flux2MagCacheStrategy,
|
||||
FluxMagCacheStrategy,
|
||||
MagCacheStrategy,
|
||||
MagCacheStrategyRegistry,
|
||||
get_strategy,
|
||||
register_strategy,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Flux2MagCacheStrategy",
|
||||
"FluxMagCacheStrategy",
|
||||
"MagCacheBlockHook",
|
||||
"MagCacheConfig",
|
||||
"MagCacheHeadHook",
|
||||
"MagCacheState",
|
||||
"MagCacheStrategy",
|
||||
"MagCacheStrategyRegistry",
|
||||
"apply_mag_cache_hook",
|
||||
"get_strategy",
|
||||
"register_strategy",
|
||||
]
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
MagCache backend implementation.
|
||||
|
||||
This module provides the MagCache backend that implements the CacheBackend
|
||||
interface using the hooks-based MagCache system.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.cache.base import CacheBackend
|
||||
from vllm_omni.diffusion.cache.magcache.config import MagCacheConfig
|
||||
from vllm_omni.diffusion.cache.magcache.hook import (
|
||||
apply_mag_cache_hook,
|
||||
)
|
||||
from vllm_omni.diffusion.cache.magcache.strategy import (
|
||||
get_strategy,
|
||||
)
|
||||
from vllm_omni.diffusion.data import DiffusionCacheConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class MagCacheBackend(CacheBackend):
|
||||
"""
|
||||
MagCache implementation using hooks.
|
||||
|
||||
MagCache (Magnitude-based Cache) is an adaptive caching technique that
|
||||
speeds up diffusion inference by reusing transformer block computations
|
||||
based on accumulated magnitude error between timesteps.
|
||||
|
||||
The backend applies MagCache hooks to the transformer which intercept the
|
||||
forward pass and implement the caching logic transparently.
|
||||
|
||||
Example:
|
||||
>>> from vllm_omni.diffusion.data import DiffusionCacheConfig
|
||||
>>> from vllm_omni.diffusion.cache.magcache.config import MagCacheConfig
|
||||
>>> from vllm_omni.diffusion.cache.magcache.strategy import FluxMagCacheStrategy
|
||||
>>> cache_config = DiffusionCacheConfig(
|
||||
... mag_ratios=FluxMagCacheStrategy.FLUX_MAG_RATIOS,
|
||||
... num_inference_steps=28,
|
||||
... mag_threshold=0.24,
|
||||
... mag_max_skip_steps=5,
|
||||
... mag_retention_ratio=0.1,
|
||||
... )
|
||||
>>> backend = MagCacheBackend(cache_config)
|
||||
>>> backend.enable(pipeline)
|
||||
>>> backend.refresh(pipeline, num_inference_steps=50)
|
||||
"""
|
||||
|
||||
def __init__(self, config: DiffusionCacheConfig):
|
||||
super().__init__(config)
|
||||
self._registered = False
|
||||
self._magcache_config: MagCacheConfig | None = None
|
||||
self._transformer_id: int | None = None
|
||||
|
||||
def enable(self, pipeline: Any) -> None:
|
||||
"""Enable MagCache on transformer using hooks.
|
||||
|
||||
This creates a MagCacheConfig from the backend's DiffusionCacheConfig
|
||||
and applies the MagCache hook to the transformer.
|
||||
|
||||
Args:
|
||||
pipeline: Diffusion pipeline instance. Extracts transformer and transformer_type:
|
||||
- transformer: pipeline.transformer
|
||||
- transformer_type: pipeline.transformer.__class__.__name__
|
||||
"""
|
||||
transformer = pipeline.transformer
|
||||
transformer_type = transformer.__class__.__name__
|
||||
|
||||
num_inference_steps = self.config.num_inference_steps or 28
|
||||
|
||||
mag_ratios = self.config.mag_ratios
|
||||
strategy = None
|
||||
|
||||
if mag_ratios is None and not self.config.mag_calibrate:
|
||||
strategy = get_strategy(transformer_type)
|
||||
original_ratios = strategy.mag_ratios
|
||||
|
||||
if len(original_ratios) != num_inference_steps and hasattr(strategy, "nearest_interp"):
|
||||
mag_ratios = strategy.nearest_interp(original_ratios, num_inference_steps)
|
||||
logger.info(
|
||||
f"MagCache: Interpolated mag_ratios from {len(original_ratios)} to {num_inference_steps} steps"
|
||||
)
|
||||
else:
|
||||
mag_ratios = original_ratios
|
||||
if len(original_ratios) != num_inference_steps:
|
||||
logger.warning(
|
||||
f"MagCache: mag_ratios length ({len(original_ratios)}) != "
|
||||
f"num_inference_steps ({num_inference_steps}), "
|
||||
f"this may cause unexpected behavior"
|
||||
)
|
||||
|
||||
logger.info(f"MagCache: Using mag_ratios from {type(strategy).__name__}")
|
||||
|
||||
if mag_ratios is None and not self.config.mag_calibrate:
|
||||
raise ValueError(
|
||||
f"mag_ratios must be provided for MagCache. "
|
||||
f"For {transformer_type}, you need to provide mag_ratios or run in calibrate mode."
|
||||
)
|
||||
|
||||
self._magcache_config = MagCacheConfig(
|
||||
transformer_type=transformer_type,
|
||||
threshold=self.config.mag_threshold,
|
||||
max_skip_steps=self.config.mag_max_skip_steps,
|
||||
retention_ratio=self.config.mag_retention_ratio,
|
||||
num_inference_steps=num_inference_steps,
|
||||
mag_calibrate=self.config.mag_calibrate,
|
||||
mag_ratios=mag_ratios if not self.config.mag_calibrate else None,
|
||||
)
|
||||
self._transformer_id = id(transformer)
|
||||
|
||||
apply_mag_cache_hook(transformer, self._magcache_config, strategy=strategy)
|
||||
|
||||
self._registered = True
|
||||
self.enabled = True
|
||||
|
||||
def refresh(self, pipeline: Any, num_inference_steps: int) -> None:
|
||||
"""Refresh MagCache state for new generation.
|
||||
|
||||
Clears all cached residuals and resets counters/accumulators.
|
||||
Should be called before each generation to ensure clean state.
|
||||
|
||||
Args:
|
||||
pipeline: Diffusion pipeline instance. Extracts transformer via pipeline.transformer.
|
||||
num_inference_steps: Number of inference steps for the current generation.
|
||||
May be used for cache context updates.
|
||||
"""
|
||||
transformer = pipeline.transformer
|
||||
current_transformer_id = id(transformer)
|
||||
|
||||
needs_re_register = False
|
||||
|
||||
if self._registered and hasattr(self, "_transformer_id"):
|
||||
if current_transformer_id != self._transformer_id:
|
||||
logger.warning(
|
||||
f"Transformer was replaced (id changed from {self._transformer_id} "
|
||||
f"to {current_transformer_id}), re-registering hooks"
|
||||
)
|
||||
needs_re_register = True
|
||||
|
||||
if not self._registered or needs_re_register:
|
||||
self.enable(pipeline)
|
||||
return
|
||||
|
||||
blocks_with_hooks = []
|
||||
|
||||
for name, submodule in transformer.named_children():
|
||||
if not isinstance(submodule, torch.nn.ModuleList):
|
||||
continue
|
||||
for index, block in enumerate(submodule):
|
||||
registry = getattr(block, "_hook_registry", None)
|
||||
if registry is not None and len(registry._hooks) > 0:
|
||||
blocks_with_hooks.append((f"{name}.{index}", block, registry))
|
||||
|
||||
if not blocks_with_hooks:
|
||||
logger.warning("No hooks found on transformer blocks, re-registering")
|
||||
apply_mag_cache_hook(transformer, self._magcache_config)
|
||||
self._transformer_id = current_transformer_id
|
||||
else:
|
||||
for name, block, registry in blocks_with_hooks:
|
||||
for hook in registry._hooks.values():
|
||||
if hasattr(hook, "reset_state"):
|
||||
hook.reset_state(block)
|
||||
|
||||
def is_enabled(self) -> bool:
|
||||
"""Check if MagCache is enabled.
|
||||
|
||||
Returns:
|
||||
True if enabled, False otherwise.
|
||||
"""
|
||||
return self.enabled
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass
|
||||
class MagCacheConfig:
|
||||
"""
|
||||
Configuration for MagCache applied to transformer models.
|
||||
|
||||
MagCache (Magnitude-based Cache) is an adaptive caching technique that speeds up
|
||||
diffusion model inference by reusing transformer block computations based on
|
||||
magnitude ratios between consecutive timesteps.
|
||||
|
||||
Reference: https://github.com/Zehong-Ma/MagCache
|
||||
|
||||
Args:
|
||||
threshold: Accumulated error threshold. Higher = more aggressive skipping (faster, lower quality).
|
||||
Default: 0.24
|
||||
max_skip_steps: Max consecutive skip steps (K).
|
||||
Default: 5
|
||||
retention_ratio: Fraction of initial steps where skipping is disabled (stability).
|
||||
Default: 0.1
|
||||
num_inference_steps: Total inference steps. Required for retention step calculation.
|
||||
Default: 28
|
||||
mag_ratios: Pre-computed magnitude ratios per step. Calibrate or use strategy defaults.
|
||||
Default: None
|
||||
mag_calibrate: If True, runs without skipping and logs norm_ratios for calibration.
|
||||
Default: False
|
||||
transformer_type: Transformer class name for logging.
|
||||
Default: "FluxTransformer2DModel"
|
||||
"""
|
||||
|
||||
threshold: float = 0.24
|
||||
max_skip_steps: int = 5
|
||||
retention_ratio: float = 0.1
|
||||
num_inference_steps: int = 28
|
||||
mag_ratios: torch.Tensor | list[float] | None = None
|
||||
mag_calibrate: bool = False
|
||||
transformer_type: str = "FluxTransformer2DModel"
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Validate and set default coefficients."""
|
||||
if self.threshold <= 0:
|
||||
raise ValueError(f"threshold must be positive, got {self.threshold}")
|
||||
|
||||
if self.max_skip_steps <= 0:
|
||||
raise ValueError(f"max_skip_steps must be positive, got {self.max_skip_steps}")
|
||||
|
||||
if not 0 < self.retention_ratio < 1:
|
||||
raise ValueError(f"retention_ratio must be in (0, 1), got {self.retention_ratio}")
|
||||
|
||||
if self.num_inference_steps is None:
|
||||
raise ValueError(
|
||||
"num_inference_steps must be provided for MagCache. "
|
||||
"This is required to determine retention steps and interpolate mag_ratios. "
|
||||
"For Flux models, use num_inference_steps=28."
|
||||
)
|
||||
|
||||
if self.num_inference_steps <= 0:
|
||||
raise ValueError(f"num_inference_steps must be positive, got {self.num_inference_steps}")
|
||||
|
||||
if not self.mag_calibrate and self.mag_ratios is None:
|
||||
raise ValueError(
|
||||
"mag_ratios must be provided for MagCache inference because these ratios "
|
||||
"are model-dependent. To get them for your model:\n"
|
||||
"1. Initialize MagCacheConfig(mag_calibrate=True, ...)\n"
|
||||
"2. Run inference on your model once.\n"
|
||||
"3. Copy the printed ratios array and pass it to mag_ratios in the config.\n"
|
||||
"For Flux models, you can import FLUX_MAG_RATIOS from vllm_omni.diffusion.cache.magcache.strategy."
|
||||
)
|
||||
|
||||
if not self.mag_calibrate and self.mag_ratios is not None:
|
||||
if not torch.is_tensor(self.mag_ratios):
|
||||
self.mag_ratios = torch.tensor(self.mag_ratios)
|
||||
+610
@@ -0,0 +1,610 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Hook-based MagCache implementation for vLLM-Omni.
|
||||
|
||||
This module implements a diffusers-style hook system for MagCache (Magnitude-based Cache),
|
||||
providing adaptive caching for diffusion model inference.
|
||||
|
||||
MagCache speeds up inference by skipping transformer block computations when the accumulated
|
||||
magnitude error is below a threshold, reusing cached residuals instead.
|
||||
|
||||
Based on: https://github.com/Zehong-Ma/MagCache
|
||||
Reference: diffusers/src/diffusers/hooks/mag_cache.py
|
||||
|
||||
Architecture:
|
||||
- MagCacheStrategy: Model-specific strategy for preprocessing/postprocessing
|
||||
- MagCacheState: Per-step state tracking residuals and accumulated error
|
||||
- MagCacheHeadHook: Decides whether to skip based on accumulated error
|
||||
- MagCacheBlockHook: Computes and stores residuals at tail block
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from diffusers.hooks._helpers import TransformerBlockMetadata, TransformerBlockRegistry
|
||||
from diffusers.utils.torch_utils import unwrap_module
|
||||
|
||||
from vllm_omni.diffusion.cache.magcache.config import MagCacheConfig
|
||||
from vllm_omni.diffusion.cache.magcache.state import MagCacheState
|
||||
from vllm_omni.diffusion.cache.magcache.strategy import MagCacheStrategy, MagCacheStrategyRegistry
|
||||
from vllm_omni.diffusion.hooks.base import HookRegistry, ModelHook, StateManager
|
||||
from vllm_omni.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_MAG_CACHE_LEADER_BLOCK_HOOK = "mag_cache_leader_block_hook"
|
||||
_MAG_CACHE_BLOCK_HOOK = "mag_cache_block_hook"
|
||||
|
||||
|
||||
class MagCacheHeadHook(ModelHook):
|
||||
"""Head block hook for MagCache - decides whether to skip computation."""
|
||||
|
||||
_HOOK_NAME = "mag_cache_head"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
state_manager: StateManager,
|
||||
config: MagCacheConfig,
|
||||
strategy: MagCacheStrategy | None = None,
|
||||
is_tail: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
self.state_manager = state_manager
|
||||
self.config = config
|
||||
self._strategy = strategy
|
||||
self._metadata = None
|
||||
self._is_tail = is_tail
|
||||
|
||||
def initialize_hook(self, module: torch.nn.Module) -> torch.nn.Module:
|
||||
unwrapped_module = unwrap_module(module)
|
||||
block_class = unwrapped_module.__class__
|
||||
|
||||
try:
|
||||
self._metadata = TransformerBlockRegistry.get(block_class)
|
||||
except ValueError:
|
||||
if self._strategy is not None:
|
||||
metadata = self._strategy.register_block_metadata(block_class)
|
||||
if metadata is not None:
|
||||
TransformerBlockRegistry.register(model_class=block_class, metadata=metadata)
|
||||
else:
|
||||
TransformerBlockRegistry.register(
|
||||
model_class=block_class,
|
||||
metadata=TransformerBlockMetadata(
|
||||
return_hidden_states_index=1,
|
||||
return_encoder_hidden_states_index=0,
|
||||
),
|
||||
)
|
||||
else:
|
||||
TransformerBlockRegistry.register(
|
||||
model_class=block_class,
|
||||
metadata=TransformerBlockMetadata(
|
||||
return_hidden_states_index=1,
|
||||
return_encoder_hidden_states_index=0,
|
||||
),
|
||||
)
|
||||
self._metadata = TransformerBlockRegistry.get(block_class)
|
||||
|
||||
return module
|
||||
|
||||
@torch.compiler.disable
|
||||
def new_forward(self, module: torch.nn.Module, *args, **kwargs):
|
||||
if self.state_manager._current_context is None:
|
||||
self.state_manager.set_context("magcache")
|
||||
|
||||
if hasattr(self._metadata, "hidden_states_argument_name"):
|
||||
arg_name = self._metadata.hidden_states_argument_name
|
||||
else:
|
||||
arg_name = "hidden_states"
|
||||
hidden_states = self._metadata._get_parameter_from_args_kwargs(arg_name, args, kwargs)
|
||||
|
||||
state: MagCacheState = self.state_manager.get_state()
|
||||
state.head_block_input = hidden_states
|
||||
|
||||
if state._is_first_step:
|
||||
state.accumulated_ratio = 1.0
|
||||
state.accumulated_err = 0.0
|
||||
state.accumulated_steps = 0
|
||||
state._is_first_step = False
|
||||
|
||||
should_compute = True
|
||||
|
||||
if self.config.mag_calibrate:
|
||||
should_compute = True
|
||||
else:
|
||||
current_step = state.step_index
|
||||
if current_step >= len(self.config.mag_ratios):
|
||||
current_scale = 1.0
|
||||
else:
|
||||
current_scale = self.config.mag_ratios[current_step]
|
||||
|
||||
retention_step = int(self.config.retention_ratio * self.config.num_inference_steps + 0.5)
|
||||
|
||||
if current_step >= retention_step:
|
||||
state.accumulated_ratio *= current_scale
|
||||
state.accumulated_steps += 1
|
||||
state.accumulated_err += abs(1.0 - state.accumulated_ratio)
|
||||
|
||||
if (
|
||||
state.previous_residual is not None
|
||||
and state.accumulated_err <= self.config.threshold
|
||||
and state.accumulated_steps <= self.config.max_skip_steps
|
||||
):
|
||||
should_compute = False
|
||||
else:
|
||||
state.accumulated_ratio = 1.0
|
||||
state.accumulated_steps = 0
|
||||
state.accumulated_err = 0.0
|
||||
|
||||
state.should_compute = should_compute
|
||||
|
||||
if not should_compute:
|
||||
res = state.previous_residual
|
||||
|
||||
if isinstance(res, tuple):
|
||||
res = tuple(r.to(hidden_states.device) for r in res)
|
||||
|
||||
if self._strategy is not None:
|
||||
original_encoder_hidden_states = self._metadata._get_parameter_from_args_kwargs(
|
||||
"encoder_hidden_states", args, kwargs
|
||||
)
|
||||
if original_encoder_hidden_states.device != res[1].device:
|
||||
original_encoder_hidden_states = original_encoder_hidden_states.to(res[1].device)
|
||||
output, enc_output = self._strategy.apply_residual_tuple(
|
||||
hidden_states, original_encoder_hidden_states, res
|
||||
)
|
||||
ret_list = [None] * 2
|
||||
ret_list[self._metadata.return_hidden_states_index] = output
|
||||
ret_list[self._metadata.return_encoder_hidden_states_index] = enc_output
|
||||
return self.log_cache_hit(state, output, ret_list)
|
||||
else:
|
||||
raise RuntimeError(
|
||||
f"MagCache residual is tuple but no strategy available for {self._metadata.transformer_type}. "
|
||||
f"Please register a MagCacheStrategy for this model."
|
||||
)
|
||||
elif res.device != hidden_states.device:
|
||||
res = res.to(hidden_states.device)
|
||||
|
||||
if self._strategy is not None:
|
||||
output = self._strategy.apply_residual(hidden_states, res)
|
||||
elif res.shape == hidden_states.shape:
|
||||
output = hidden_states + res
|
||||
elif (
|
||||
hidden_states.ndim == 3
|
||||
and res.ndim == 3
|
||||
and hidden_states.shape[0] == res.shape[0]
|
||||
and hidden_states.shape[2] == res.shape[2]
|
||||
):
|
||||
diff = hidden_states.shape[1] - res.shape[1]
|
||||
if diff > 0:
|
||||
output = hidden_states.clone()
|
||||
output[:, diff:, :] = output[:, diff:, :] + res
|
||||
else:
|
||||
output = hidden_states + res
|
||||
else:
|
||||
output = hidden_states + res
|
||||
|
||||
if self._metadata.return_encoder_hidden_states_index is not None:
|
||||
original_encoder_hidden_states = self._metadata._get_parameter_from_args_kwargs(
|
||||
"encoder_hidden_states", args, kwargs
|
||||
)
|
||||
max_idx = max(
|
||||
self._metadata.return_hidden_states_index, self._metadata.return_encoder_hidden_states_index
|
||||
)
|
||||
ret_list = [None] * (max_idx + 1)
|
||||
ret_list[self._metadata.return_hidden_states_index] = output
|
||||
ret_list[self._metadata.return_encoder_hidden_states_index] = original_encoder_hidden_states
|
||||
return self.log_cache_hit(state, output, ret_list)
|
||||
else:
|
||||
return self.log_cache_hit(state, output, None)
|
||||
else:
|
||||
output = self.fn_ref.original_forward(*args, **kwargs)
|
||||
result = self.log_cache_miss(state, output)
|
||||
|
||||
if self._is_tail:
|
||||
if isinstance(output, tuple):
|
||||
out_hidden = output[self._metadata.return_hidden_states_index]
|
||||
else:
|
||||
out_hidden = output
|
||||
|
||||
in_hidden = state.head_block_input
|
||||
|
||||
if in_hidden is not None:
|
||||
if self._strategy is not None:
|
||||
residual = self._strategy.compute_residual(out_hidden, in_hidden)
|
||||
elif out_hidden.shape == in_hidden.shape:
|
||||
residual = out_hidden - in_hidden
|
||||
else:
|
||||
residual = out_hidden
|
||||
|
||||
if self.config.mag_calibrate:
|
||||
self._perform_calibration_head(state, residual)
|
||||
|
||||
state.previous_residual = residual
|
||||
self._advance_step_head(state)
|
||||
|
||||
return result
|
||||
|
||||
def _perform_calibration_head(
|
||||
self,
|
||||
state: MagCacheState,
|
||||
current_residual: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
) -> None:
|
||||
if self._strategy is not None:
|
||||
ratio, std, cos_dis = self._strategy.compute_calibration_metrics(current_residual, state.previous_residual)
|
||||
else:
|
||||
if state.previous_residual is None:
|
||||
ratio, std, cos_dis = 1.0, 0.0, 0.0
|
||||
else:
|
||||
ratio, std, cos_dis = 1.0, 0.0, 0.0
|
||||
|
||||
state.calibration_ratios.append(ratio)
|
||||
state.norm_ratios.append(round(ratio, 5))
|
||||
state.norm_stds.append(round(std, 5))
|
||||
state.cos_dises.append(round(cos_dis, 5))
|
||||
|
||||
def _advance_step_head(self, state: MagCacheState) -> None:
|
||||
state.step_index += 1
|
||||
if state.step_index >= self.config.num_inference_steps:
|
||||
if self.config.mag_calibrate:
|
||||
logger.info("MagCache calibration complete.")
|
||||
logger.info(f"norm_ratios: {state.norm_ratios}")
|
||||
logger.info(f"norm_stds: {state.norm_stds}")
|
||||
logger.info(f"cos_dises: {state.cos_dises}")
|
||||
logger.info("Copy these values to DiffusionCacheConfig(mag_ratios=...) for production use")
|
||||
|
||||
state.step_index = 0
|
||||
state.accumulated_ratio = 1.0
|
||||
state.accumulated_steps = 0
|
||||
state.accumulated_err = 0.0
|
||||
state.previous_residual = None
|
||||
state.calibration_ratios = []
|
||||
state.norm_ratios = []
|
||||
state.norm_stds = []
|
||||
state.cos_dises = []
|
||||
state._is_first_step = True
|
||||
|
||||
def log_cache_hit(self, state: MagCacheState, output, ret):
|
||||
step = state.step_index
|
||||
if state.previous_residual is not None:
|
||||
if isinstance(state.previous_residual, tuple):
|
||||
residual_shape = tuple(r.shape for r in state.previous_residual)
|
||||
else:
|
||||
residual_shape = state.previous_residual.shape
|
||||
else:
|
||||
residual_shape = "None"
|
||||
logger.debug(
|
||||
f"[MagCache][HEAD] STEP={step}: CACHE_HIT (err={state.accumulated_err:.6f}, "
|
||||
f"steps_skipped={state.accumulated_steps}, residual_shape={residual_shape}"
|
||||
)
|
||||
return ret if ret is not None else output
|
||||
|
||||
def log_cache_miss(self, state: MagCacheState, output):
|
||||
step = state.step_index
|
||||
residual_norm = 0.0
|
||||
if state.previous_residual is not None:
|
||||
if isinstance(state.previous_residual, tuple):
|
||||
residual_norm = sum(float(torch.norm(r).item()) for r in state.previous_residual)
|
||||
else:
|
||||
residual_norm = float(torch.norm(state.previous_residual).item())
|
||||
logger.debug(
|
||||
f"[MagCache][HEAD] STEP={step}: CACHE_MISS "
|
||||
f"(err={state.accumulated_err:.6f}, acc_ratio={state.accumulated_ratio:.6f}, "
|
||||
f"residual_norm={residual_norm:.6f}, threshold={self.config.threshold}, "
|
||||
f"max_skip={self.config.max_skip_steps})"
|
||||
)
|
||||
return output
|
||||
|
||||
def reset_state(self, module: torch.nn.Module) -> torch.nn.Module:
|
||||
self.state_manager.reset()
|
||||
return module
|
||||
|
||||
|
||||
class MagCacheBlockHook(ModelHook):
|
||||
"""Block hook for MagCache - computes residuals at tail block."""
|
||||
|
||||
_HOOK_NAME = "mag_cache_block"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
state_manager: StateManager,
|
||||
is_tail: bool = False,
|
||||
config: MagCacheConfig | None = None,
|
||||
strategy: MagCacheStrategy | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.state_manager = state_manager
|
||||
self.is_tail = is_tail
|
||||
self.config = config
|
||||
self._strategy = strategy
|
||||
self._metadata = None
|
||||
|
||||
def initialize_hook(self, module: torch.nn.Module) -> torch.nn.Module:
|
||||
unwrapped_module = unwrap_module(module)
|
||||
block_class = unwrapped_module.__class__
|
||||
|
||||
try:
|
||||
self._metadata = TransformerBlockRegistry.get(block_class)
|
||||
except ValueError:
|
||||
if self._strategy is not None:
|
||||
metadata = self._strategy.register_block_metadata(block_class)
|
||||
if metadata is not None:
|
||||
TransformerBlockRegistry.register(model_class=block_class, metadata=metadata)
|
||||
else:
|
||||
TransformerBlockRegistry.register(
|
||||
model_class=block_class,
|
||||
metadata=TransformerBlockMetadata(
|
||||
return_hidden_states_index=1,
|
||||
return_encoder_hidden_states_index=0,
|
||||
),
|
||||
)
|
||||
else:
|
||||
TransformerBlockRegistry.register(
|
||||
model_class=block_class,
|
||||
metadata=TransformerBlockMetadata(
|
||||
return_hidden_states_index=1,
|
||||
return_encoder_hidden_states_index=0,
|
||||
),
|
||||
)
|
||||
self._metadata = TransformerBlockRegistry.get(block_class)
|
||||
|
||||
return module
|
||||
|
||||
def reset_state(self, module: torch.nn.Module) -> torch.nn.Module:
|
||||
self.state_manager.reset()
|
||||
return module
|
||||
|
||||
@torch.compiler.disable
|
||||
def new_forward(self, module: torch.nn.Module, *args, **kwargs):
|
||||
if self.state_manager._current_context is None:
|
||||
self.state_manager.set_context("magcache")
|
||||
state: MagCacheState = self.state_manager.get_state()
|
||||
|
||||
if not state.should_compute:
|
||||
res = state.previous_residual
|
||||
if res is None:
|
||||
res = torch.zeros_like(args[0])
|
||||
|
||||
if hasattr(self._metadata, "hidden_states_argument_name"):
|
||||
arg_name = self._metadata.hidden_states_argument_name
|
||||
else:
|
||||
arg_name = "hidden_states"
|
||||
hidden_states = self._metadata._get_parameter_from_args_kwargs(arg_name, args, kwargs)
|
||||
|
||||
if self.is_tail:
|
||||
self.advance_step(state)
|
||||
|
||||
if self._metadata.return_encoder_hidden_states_index is not None:
|
||||
encoder_hidden_states = self._metadata._get_parameter_from_args_kwargs(
|
||||
"encoder_hidden_states", args, kwargs
|
||||
)
|
||||
|
||||
if self._strategy is not None:
|
||||
out_hidden, enc_out = self._strategy.apply_residual_tuple(hidden_states, encoder_hidden_states, res)
|
||||
else:
|
||||
out_hidden = hidden_states + res
|
||||
enc_out = encoder_hidden_states
|
||||
|
||||
max_idx = max(
|
||||
self._metadata.return_hidden_states_index, self._metadata.return_encoder_hidden_states_index
|
||||
)
|
||||
ret_list = [None] * (max_idx + 1)
|
||||
ret_list[self._metadata.return_hidden_states_index] = out_hidden
|
||||
ret_list[self._metadata.return_encoder_hidden_states_index] = enc_out
|
||||
return tuple(ret_list)
|
||||
|
||||
if self._strategy is not None:
|
||||
output = self._strategy.apply_residual(hidden_states, res)
|
||||
else:
|
||||
output = hidden_states + res
|
||||
|
||||
return output
|
||||
|
||||
output = self.fn_ref.original_forward(*args, **kwargs)
|
||||
|
||||
if self.is_tail:
|
||||
if isinstance(output, tuple):
|
||||
out_hidden = output[self._metadata.return_hidden_states_index]
|
||||
else:
|
||||
out_hidden = output
|
||||
|
||||
in_hidden = state.head_block_input
|
||||
|
||||
if in_hidden is None:
|
||||
return output
|
||||
|
||||
if self._strategy is not None:
|
||||
residual = self._strategy.compute_residual(output, in_hidden)
|
||||
elif out_hidden.shape == in_hidden.shape:
|
||||
residual = out_hidden - in_hidden
|
||||
elif out_hidden.ndim == 3 and in_hidden.ndim == 3 and out_hidden.shape[2] == in_hidden.shape[2]:
|
||||
residual = out_hidden - in_hidden
|
||||
else:
|
||||
residual = out_hidden
|
||||
|
||||
if self.config.mag_calibrate:
|
||||
self.perform_calibration(state, residual)
|
||||
|
||||
state.previous_residual = residual
|
||||
self.advance_step(state)
|
||||
|
||||
self.log_residual_computed(state, residual)
|
||||
|
||||
return output
|
||||
|
||||
def log_residual_computed(
|
||||
self,
|
||||
state: MagCacheState,
|
||||
residual: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
) -> None:
|
||||
step = state.step_index
|
||||
if residual is None:
|
||||
residual_norm = 0.0
|
||||
residual_shape = "None"
|
||||
elif isinstance(residual, tuple):
|
||||
residual_norm = sum(float(torch.norm(r).item()) for r in residual)
|
||||
residual_shape = tuple(r.shape for r in residual)
|
||||
else:
|
||||
residual_norm = float(torch.norm(residual).item())
|
||||
residual_shape = residual.shape
|
||||
logger.debug(
|
||||
f"[MagCache][TAIL] STEP={step}: RESIDUAL_COMPUTED (norm={residual_norm:.6f}, shape={residual_shape})"
|
||||
)
|
||||
|
||||
def perform_calibration(
|
||||
self,
|
||||
state: MagCacheState,
|
||||
current_residual: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
) -> None:
|
||||
if self._strategy is not None:
|
||||
ratio, std, cos_dis = self._strategy.compute_calibration_metrics(current_residual, state.previous_residual)
|
||||
else:
|
||||
|
||||
def _get_norm(residual: torch.Tensor | tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
|
||||
if isinstance(residual, tuple):
|
||||
return sum(torch.linalg.norm(r.float(), dim=-1) for r in residual)
|
||||
return torch.linalg.norm(residual.float(), dim=-1)
|
||||
|
||||
if state.previous_residual is None:
|
||||
ratio, std, cos_dis = 1.0, 0.0, 0.0
|
||||
else:
|
||||
curr_norm = _get_norm(current_residual)
|
||||
prev_norm = _get_norm(state.previous_residual)
|
||||
ratio = (curr_norm / (prev_norm + 1e-8)).mean().item()
|
||||
std = (curr_norm / (prev_norm + 1e-8)).std().item()
|
||||
cos_dis = (
|
||||
(
|
||||
1
|
||||
- F.cosine_similarity(
|
||||
current_residual.flatten(0, -2) if current_residual.ndim > 2 else current_residual,
|
||||
state.previous_residual.flatten(0, -2)
|
||||
if state.previous_residual.ndim > 2
|
||||
else state.previous_residual,
|
||||
dim=-1,
|
||||
eps=1e-8,
|
||||
)
|
||||
)
|
||||
.mean()
|
||||
.item()
|
||||
)
|
||||
|
||||
state.calibration_ratios.append(ratio)
|
||||
state.norm_ratios.append(round(ratio, 5))
|
||||
state.norm_stds.append(round(std, 5))
|
||||
state.cos_dises.append(round(cos_dis, 5))
|
||||
|
||||
def advance_step(self, state: MagCacheState) -> None:
|
||||
state.step_index += 1
|
||||
if state.step_index >= self.config.num_inference_steps:
|
||||
if self.config.mag_calibrate:
|
||||
logger.info("MagCache calibration complete.")
|
||||
logger.info(f"norm_ratios: {state.norm_ratios}")
|
||||
logger.info(f"norm_stds: {state.norm_stds}")
|
||||
logger.info(f"cos_dises: {state.cos_dises}")
|
||||
logger.info("Copy these values to DiffusionCacheConfig(mag_ratios=...) for production use")
|
||||
|
||||
state.step_index = 0
|
||||
state.accumulated_ratio = 1.0
|
||||
state.accumulated_steps = 0
|
||||
state.accumulated_err = 0.0
|
||||
state.previous_residual = None
|
||||
state.calibration_ratios = []
|
||||
state.norm_ratios = []
|
||||
state.norm_stds = []
|
||||
state.cos_dises = []
|
||||
state._is_first_step = True
|
||||
|
||||
|
||||
def apply_mag_cache_hook(
|
||||
module: torch.nn.Module,
|
||||
config: MagCacheConfig,
|
||||
strategy: MagCacheStrategy | None = None,
|
||||
) -> None:
|
||||
"""Apply MagCache optimization to a transformer module.
|
||||
|
||||
Args:
|
||||
module: Transformer model to optimize (e.g., FluxTransformer2DModel)
|
||||
config: MagCacheConfig specifying caching parameters
|
||||
strategy: Optional strategy to use. If None, will be looked up from registry.
|
||||
"""
|
||||
HookRegistry.check_if_exists_or_initialize(module)
|
||||
|
||||
transformer_type = config.transformer_type
|
||||
if strategy is None:
|
||||
strategy = MagCacheStrategyRegistry.get_if_exists(transformer_type)
|
||||
|
||||
if strategy is None:
|
||||
logger.warning(
|
||||
f"MagCache: No strategy found for '{transformer_type}'. "
|
||||
f"Using default behavior. Available strategies: {list(MagCacheStrategyRegistry._registry.keys())}"
|
||||
)
|
||||
else:
|
||||
strategy_name = type(strategy).__name__
|
||||
logger.info(f"MagCache: Applying {strategy_name} for '{transformer_type}'")
|
||||
if hasattr(type(strategy), "register_blocks"):
|
||||
type(strategy).register_blocks()
|
||||
|
||||
state_manager = StateManager(MagCacheState, (), {})
|
||||
remaining_blocks = []
|
||||
|
||||
for name, submodule in module.named_children():
|
||||
if not isinstance(submodule, torch.nn.ModuleList):
|
||||
continue
|
||||
for index, block in enumerate(submodule):
|
||||
remaining_blocks.append((f"{name}.{index}", block))
|
||||
|
||||
if not remaining_blocks:
|
||||
logger.warning("MagCache: No transformer blocks found to apply hooks.")
|
||||
return
|
||||
|
||||
if len(remaining_blocks) == 1:
|
||||
name, block = remaining_blocks[0]
|
||||
logger.info(f"MagCache: Applying Head+Tail Hook to single block '{name}'")
|
||||
_apply_mag_cache_head_hook(block, state_manager, config, strategy, is_tail=True)
|
||||
return
|
||||
|
||||
head_block_name, head_block = remaining_blocks.pop(0)
|
||||
tail_block_name, tail_block = remaining_blocks.pop(-1)
|
||||
|
||||
logger.info(f"MagCache: Applying Head Hook to {head_block_name}")
|
||||
_apply_mag_cache_head_hook(head_block, state_manager, config, strategy)
|
||||
|
||||
for name, block in remaining_blocks:
|
||||
_apply_mag_cache_block_hook(block, state_manager, config, strategy=strategy)
|
||||
|
||||
logger.info(f"MagCache: Applying Tail Hook to {tail_block_name}")
|
||||
_apply_mag_cache_block_hook(tail_block, state_manager, config, is_tail=True, strategy=strategy)
|
||||
|
||||
|
||||
def _apply_mag_cache_head_hook(
|
||||
block: torch.nn.Module,
|
||||
state_manager: StateManager,
|
||||
config: MagCacheConfig,
|
||||
strategy: MagCacheStrategy | None = None,
|
||||
is_tail: bool = False,
|
||||
) -> None:
|
||||
registry = HookRegistry.check_if_exists_or_initialize(block)
|
||||
|
||||
if registry.get_hook(_MAG_CACHE_LEADER_BLOCK_HOOK) is not None:
|
||||
registry.remove_hook(_MAG_CACHE_LEADER_BLOCK_HOOK)
|
||||
|
||||
hook = MagCacheHeadHook(state_manager, config, strategy, is_tail=is_tail)
|
||||
registry.register_hook(_MAG_CACHE_LEADER_BLOCK_HOOK, hook)
|
||||
|
||||
|
||||
def _apply_mag_cache_block_hook(
|
||||
block: torch.nn.Module,
|
||||
state_manager: StateManager,
|
||||
config: MagCacheConfig,
|
||||
is_tail: bool = False,
|
||||
strategy: MagCacheStrategy | None = None,
|
||||
) -> None:
|
||||
registry = HookRegistry.check_if_exists_or_initialize(block)
|
||||
|
||||
if registry.get_hook(_MAG_CACHE_BLOCK_HOOK) is not None:
|
||||
registry.remove_hook(_MAG_CACHE_BLOCK_HOOK)
|
||||
|
||||
hook = MagCacheBlockHook(state_manager, is_tail, config, strategy)
|
||||
registry.register_hook(_MAG_CACHE_BLOCK_HOOK, hook)
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
MagCache state management.
|
||||
|
||||
This module contains the MagCacheState class which manages the internal state
|
||||
for MagCache caching logic, including residuals, accumulated metrics, and step tracking.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
class MagCacheState:
|
||||
"""State management for MagCache caching logic."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Initialize empty MagCache state."""
|
||||
self.previous_residual: torch.Tensor | tuple[torch.Tensor, torch.Tensor] | None = None
|
||||
self.head_block_input: torch.Tensor | tuple[torch.Tensor, torch.Tensor] | None = None
|
||||
self.should_compute: bool = True
|
||||
self.accumulated_ratio: float = 1.0
|
||||
self.accumulated_err: float = 0.0
|
||||
self.accumulated_steps: int = 0
|
||||
self.step_index: int = 0
|
||||
self.calibration_ratios: list[float] = []
|
||||
self.norm_ratios: list[float] = []
|
||||
self.norm_stds: list[float] = []
|
||||
self.cos_dises: list[float] = []
|
||||
self._is_first_step: bool = True
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Reset all state variables for a new inference run."""
|
||||
self.previous_residual = None
|
||||
self.head_block_input = None
|
||||
self.should_compute = True
|
||||
self.accumulated_ratio = 1.0
|
||||
self.accumulated_err = 0.0
|
||||
self.accumulated_steps = 0
|
||||
self.step_index = 0
|
||||
self.calibration_ratios = []
|
||||
self.norm_ratios = []
|
||||
self.norm_stds = []
|
||||
self.cos_dises = []
|
||||
self._is_first_step = True
|
||||
+488
@@ -0,0 +1,488 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
MagCache strategy definitions for different model architectures.
|
||||
|
||||
This module provides model-specific strategies for MagCache, allowing easy
|
||||
extension to new models by implementing the MagCacheStrategy interface.
|
||||
|
||||
Architecture:
|
||||
- MagCacheStrategy: Abstract base class defining the strategy interface
|
||||
- FluxMagCacheStrategy: Strategy for Flux (dual-stream) models
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
import torch
|
||||
from diffusers.hooks._helpers import TransformerBlockMetadata
|
||||
|
||||
|
||||
class MagCacheStrategy(ABC):
|
||||
"""
|
||||
Abstract base class for MagCache strategies.
|
||||
|
||||
Each model architecture requires a specific strategy to handle:
|
||||
- Residual computation (how to calculate the residual for caching)
|
||||
- Residual application (how to apply cached residual)
|
||||
- Model-specific magnitude ratios
|
||||
|
||||
Implement this class to add support for new model architectures.
|
||||
"""
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def mag_ratios(self) -> torch.Tensor:
|
||||
"""Return the default mag_ratios tensor for this model.
|
||||
|
||||
This tensor defines caching ratios for each transformer block.
|
||||
Values should be calibrated for the specific model architecture.
|
||||
|
||||
Returns:
|
||||
1D tensor of mag_ratios (one per transformer block).
|
||||
"""
|
||||
pass
|
||||
|
||||
def register_block_metadata(self, block_class: type) -> TransformerBlockMetadata | None:
|
||||
"""Register model-specific transformer block metadata.
|
||||
|
||||
Override this method to provide custom metadata for transformer blocks
|
||||
that have non-standard output formats (e.g., tuple returns).
|
||||
|
||||
Args:
|
||||
block_class: The transformer block class to register.
|
||||
|
||||
Returns:
|
||||
TransformerBlockMetadata if custom registration is needed, None otherwise.
|
||||
"""
|
||||
return None
|
||||
|
||||
def compute_residual(
|
||||
self,
|
||||
output: torch.Tensor,
|
||||
head_input: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Compute residual between block output and input.
|
||||
|
||||
Default implementation: output - head_input.
|
||||
Override this method for models with non-standard output formats.
|
||||
|
||||
Args:
|
||||
output: Output from transformer blocks.
|
||||
head_input: Input to the first block.
|
||||
|
||||
Returns:
|
||||
Residual tensor for caching.
|
||||
"""
|
||||
return output - head_input
|
||||
|
||||
def apply_residual(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply cached residual to hidden states.
|
||||
|
||||
Default implementation: add residual to hidden_states.
|
||||
This works for most model architectures.
|
||||
|
||||
Args:
|
||||
hidden_states: Current hidden states.
|
||||
residual: Cached residual to apply.
|
||||
|
||||
Returns:
|
||||
Hidden states with residual added.
|
||||
"""
|
||||
return hidden_states + residual
|
||||
|
||||
def apply_residual_tuple(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
residual: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Apply cached residual tuple to both hidden_states and encoder_hidden_states.
|
||||
|
||||
Default implementation: add residuals separately.
|
||||
Override this method for models with specific residual application logic.
|
||||
|
||||
Args:
|
||||
hidden_states: Current hidden states.
|
||||
encoder_hidden_states: Current encoder hidden states.
|
||||
residual: Tuple of (hidden_states_residual, encoder_hidden_states_residual).
|
||||
|
||||
Returns:
|
||||
Tuple of (hidden_states, encoder_hidden_states) with residuals applied.
|
||||
"""
|
||||
h_res, e_res = residual
|
||||
return hidden_states + h_res, encoder_hidden_states + e_res
|
||||
|
||||
def compute_calibration_metrics(
|
||||
self,
|
||||
current_residual: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
previous_residual: torch.Tensor | tuple[torch.Tensor, torch.Tensor] | None,
|
||||
) -> tuple[float, float, float]:
|
||||
"""Compute calibration metrics for mag_ratios generation.
|
||||
|
||||
Default implementation computes norm ratios and cosine dissimilarity.
|
||||
Override this method for models with custom metric computation.
|
||||
|
||||
Args:
|
||||
current_residual: Residual from the current step.
|
||||
previous_residual: Residual from the previous step (None for first step).
|
||||
|
||||
Returns:
|
||||
Tuple of (norm_ratio, norm_std, cos_dis):
|
||||
- norm_ratio: Mean ratio of current to previous residual norms
|
||||
- norm_std: Standard deviation of the norm ratios
|
||||
- cos_dis: Mean cosine dissimilarity (1 - cosine_similarity)
|
||||
"""
|
||||
import torch.nn.functional as F
|
||||
|
||||
if previous_residual is None:
|
||||
return 1.0, 0.0, 0.0
|
||||
|
||||
curr_norm = torch.linalg.norm(current_residual.float(), dim=-1)
|
||||
prev_norm = torch.linalg.norm(previous_residual.float(), dim=-1)
|
||||
|
||||
ratio = (curr_norm / (prev_norm + 1e-8)).mean().item()
|
||||
std = (curr_norm / (prev_norm + 1e-8)).std().item()
|
||||
cos_dis = (1 - F.cosine_similarity(current_residual, previous_residual, dim=-1, eps=1e-8)).mean().item()
|
||||
|
||||
return ratio, std, cos_dis
|
||||
|
||||
def get_calibration_metrics_names(self) -> tuple[str, str, str]:
|
||||
"""Return the names of calibration metrics for logging.
|
||||
|
||||
Returns:
|
||||
Tuple of metric names in order: (norm_ratio_name, norm_std_name, cos_dis_name)
|
||||
"""
|
||||
return ("norm_ratio", "norm_std", "cos_dis")
|
||||
|
||||
|
||||
class FluxMagCacheStrategy(MagCacheStrategy):
|
||||
"""
|
||||
MagCache strategy for Flux (dual-stream) models.
|
||||
|
||||
Flux architecture:
|
||||
- transformer blocks (dual-stream): image tokens and text tokens
|
||||
processed independently with separate weights
|
||||
- single transformer blocks (single-stream): concatenated sequence
|
||||
(image + text tokens) shares the same group of weights
|
||||
- Final norm_out and proj_out layers
|
||||
|
||||
This strategy provides:
|
||||
- mag_ratios: Pre-computed magnitude ratios for Flux (28 steps)
|
||||
- compute_residual: Handles tuple output format
|
||||
- apply_residual_tuple: Handles decoder residual only
|
||||
"""
|
||||
|
||||
FLUX_MAG_RATIOS = torch.tensor(
|
||||
[
|
||||
1.0,
|
||||
1.07313,
|
||||
1.21035,
|
||||
1.04432,
|
||||
1.06818,
|
||||
1.05547,
|
||||
1.0183,
|
||||
1.03405,
|
||||
1.02574,
|
||||
1.03042,
|
||||
1.02739,
|
||||
1.01955,
|
||||
1.01585,
|
||||
1.02439,
|
||||
1.01154,
|
||||
1.01377,
|
||||
1.00994,
|
||||
1.01444,
|
||||
1.00839,
|
||||
1.02269,
|
||||
1.0007,
|
||||
1.00714,
|
||||
1.00484,
|
||||
1.01381,
|
||||
1.00426,
|
||||
0.99764,
|
||||
1.00778,
|
||||
1.00233,
|
||||
]
|
||||
)
|
||||
|
||||
@property
|
||||
def mag_ratios(self) -> torch.Tensor:
|
||||
"""Return default mag_ratios for Flux model."""
|
||||
return self.FLUX_MAG_RATIOS
|
||||
|
||||
def compute_residual(
|
||||
self,
|
||||
output: torch.Tensor,
|
||||
head_input: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Compute residual for Flux output format (tuple or single tensor).
|
||||
|
||||
Flux single transformer blocks return a tuple, so we extract
|
||||
the decoder output (index 1) before computing residual.
|
||||
"""
|
||||
if isinstance(output, tuple):
|
||||
decoder_output = output[1] if len(output) > 1 else output[0]
|
||||
return decoder_output - head_input
|
||||
else:
|
||||
return output - head_input
|
||||
|
||||
def apply_residual_tuple(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
residual: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Apply residual tuple for Flux - only add decoder residual.
|
||||
|
||||
Flux has separate image and text processing, so the residual
|
||||
is only applied to the decoder (image) branch.
|
||||
"""
|
||||
if isinstance(residual, tuple):
|
||||
decoder_residual = residual[1]
|
||||
else:
|
||||
decoder_residual = residual
|
||||
|
||||
output = hidden_states + decoder_residual
|
||||
enc_output = encoder_hidden_states
|
||||
|
||||
return output, enc_output
|
||||
|
||||
@staticmethod
|
||||
def nearest_interp(src_array: torch.Tensor, target_length: int) -> torch.Tensor:
|
||||
"""Interpolate mag_ratios to target length using nearest neighbor."""
|
||||
src_length = len(src_array)
|
||||
if target_length == 1:
|
||||
return src_array[-1:]
|
||||
|
||||
scale = (src_length - 1) / (target_length - 1)
|
||||
grid = torch.arange(target_length, device=src_array.device, dtype=torch.float32)
|
||||
mapped_indices = torch.round(grid * scale).long()
|
||||
|
||||
return src_array[mapped_indices]
|
||||
|
||||
|
||||
class Flux2MagCacheStrategy(FluxMagCacheStrategy):
|
||||
"""MagCache strategy for Flux2 model.
|
||||
|
||||
Flux2 shares the same dual-stream architecture as Flux, but may have
|
||||
different tensor shapes in some transformer blocks, requiring special
|
||||
handling in residual computation.
|
||||
"""
|
||||
|
||||
FLUX2_MAG_RATIOS = torch.tensor(
|
||||
[
|
||||
1.0,
|
||||
0.96528,
|
||||
1.11559,
|
||||
1.0565,
|
||||
1.00425,
|
||||
1.0805,
|
||||
0.98616,
|
||||
1.09289,
|
||||
1.03196,
|
||||
1.06679,
|
||||
1.03941,
|
||||
1.05375,
|
||||
1.03128,
|
||||
1.05349,
|
||||
1.01983,
|
||||
1.05535,
|
||||
1.0662,
|
||||
1.05748,
|
||||
1.00318,
|
||||
1.05222,
|
||||
1.04556,
|
||||
1.0506,
|
||||
1.05058,
|
||||
1.05219,
|
||||
1.02025,
|
||||
1.05052,
|
||||
1.04143,
|
||||
1.0498,
|
||||
]
|
||||
)
|
||||
|
||||
@property
|
||||
def mag_ratios(self) -> torch.Tensor:
|
||||
"""Return default mag_ratios for Flux2 model."""
|
||||
return self.FLUX2_MAG_RATIOS
|
||||
|
||||
def register_block_metadata(self, block_class: type) -> TransformerBlockMetadata | None:
|
||||
"""Register Flux2-specific block metadata based on block type.
|
||||
|
||||
Flux2 has two block types with different output formats:
|
||||
- Dual-stream (Flux2TransformerBlock): returns (encoder_hidden_states, hidden_states)
|
||||
- Single-stream (Flux2SingleTransformerBlock): returns single tensor
|
||||
"""
|
||||
class_name = block_class.__name__
|
||||
is_single_stream = "Single" in class_name
|
||||
|
||||
if is_single_stream:
|
||||
return TransformerBlockMetadata(
|
||||
return_hidden_states_index=0,
|
||||
return_encoder_hidden_states_index=None,
|
||||
)
|
||||
else:
|
||||
return TransformerBlockMetadata(
|
||||
return_hidden_states_index=1,
|
||||
return_encoder_hidden_states_index=0,
|
||||
)
|
||||
|
||||
def compute_residual(
|
||||
self,
|
||||
output: torch.Tensor,
|
||||
head_input: torch.Tensor,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Compute residual for Flux2 with dual-stream support.
|
||||
|
||||
For dual-stream blocks, computes residual for both encoder and decoder branches.
|
||||
For single-stream blocks: if shapes match, computes output - input; otherwise returns output.
|
||||
"""
|
||||
if isinstance(output, tuple):
|
||||
enc_output, dec_output = output[0], output[1]
|
||||
|
||||
if isinstance(head_input, tuple):
|
||||
enc_head, dec_head = head_input[0], head_input[1]
|
||||
else:
|
||||
enc_head = head_input[:, : enc_output.shape[1], ...]
|
||||
dec_head = head_input[:, enc_output.shape[1] :, ...]
|
||||
|
||||
enc_residual = enc_output - enc_head
|
||||
dec_residual = dec_output - dec_head
|
||||
|
||||
return (enc_residual, dec_residual)
|
||||
else:
|
||||
if output.shape == head_input.shape:
|
||||
return output - head_input
|
||||
else:
|
||||
return output
|
||||
|
||||
def apply_residual_tuple(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
residual: tuple[torch.Tensor, torch.Tensor],
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Apply residual tuple for Flux2 with shape mismatch handling.
|
||||
|
||||
For Flux2 dual-stream blocks, handles the case where hidden_states
|
||||
and decoder_residual may have different shapes.
|
||||
"""
|
||||
if isinstance(residual, tuple):
|
||||
decoder_residual = residual[1]
|
||||
else:
|
||||
decoder_residual = residual
|
||||
|
||||
if hidden_states.shape == decoder_residual.shape:
|
||||
output = hidden_states + decoder_residual
|
||||
else:
|
||||
output = hidden_states
|
||||
enc_output = encoder_hidden_states
|
||||
|
||||
return output, enc_output
|
||||
|
||||
def apply_residual(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
residual: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply residual for Flux2.
|
||||
|
||||
For single-stream blocks: if shapes match, adds residual; otherwise returns input.
|
||||
For dual-stream blocks: applies decoder residual only.
|
||||
"""
|
||||
if isinstance(residual, tuple):
|
||||
dec_residual = residual[1]
|
||||
if hidden_states.shape == dec_residual.shape:
|
||||
return hidden_states + dec_residual
|
||||
else:
|
||||
return hidden_states
|
||||
else:
|
||||
if residual.shape == hidden_states.shape:
|
||||
return hidden_states + residual
|
||||
else:
|
||||
return hidden_states
|
||||
|
||||
|
||||
class MagCacheStrategyRegistry:
|
||||
"""Registry for MagCache strategies by transformer type."""
|
||||
|
||||
_registry: dict[str, MagCacheStrategy] = {}
|
||||
|
||||
@classmethod
|
||||
def register(cls, name: str, strategy: MagCacheStrategy) -> None:
|
||||
"""Register a strategy with explicit name.
|
||||
|
||||
Args:
|
||||
name: Transformer model type identifier (e.g., "FluxTransformer2DModel")
|
||||
strategy: MagCacheStrategy instance
|
||||
"""
|
||||
cls._registry[name] = strategy
|
||||
|
||||
@classmethod
|
||||
def get(cls, transformer_type: str) -> MagCacheStrategy:
|
||||
"""Get strategy for given transformer type."""
|
||||
if transformer_type not in cls._registry:
|
||||
available = list(cls._registry.keys())
|
||||
raise ValueError(f"Unknown model type: '{transformer_type}'. Available types: {available}")
|
||||
return cls._registry[transformer_type]
|
||||
|
||||
@classmethod
|
||||
def get_if_exists(cls, transformer_type: str) -> MagCacheStrategy | None:
|
||||
"""Get strategy if exists, None otherwise."""
|
||||
return cls._registry.get(transformer_type)
|
||||
|
||||
|
||||
MagCacheStrategyRegistry.register("FluxTransformer2DModel", FluxMagCacheStrategy())
|
||||
|
||||
MagCacheStrategyRegistry.register("Flux2Transformer2DModel", Flux2MagCacheStrategy())
|
||||
|
||||
|
||||
def register_strategy(
|
||||
transformer_cls_name: str,
|
||||
strategy: MagCacheStrategy,
|
||||
) -> None:
|
||||
"""Register a MagCache strategy for a model type.
|
||||
|
||||
This allows extending MagCache support to new models without modifying
|
||||
the core MagCache code.
|
||||
|
||||
Args:
|
||||
transformer_cls_name: Transformer model type identifier (class name or type string)
|
||||
Must match pipeline.transformer.__class__.__name__
|
||||
strategy: MagCacheStrategy instance for this model type
|
||||
|
||||
Example:
|
||||
>>> class MyModelMagCacheStrategy(MagCacheStrategy):
|
||||
... @property
|
||||
... def mag_ratios(self):
|
||||
... return torch.tensor([...])
|
||||
>>> register_strategy("MyModelTransformer", MyModelMagCacheStrategy())
|
||||
"""
|
||||
MagCacheStrategyRegistry.register(transformer_cls_name, strategy)
|
||||
|
||||
|
||||
def get_strategy(transformer_cls_name: str) -> MagCacheStrategy:
|
||||
"""Get strategy function for given transformer class.
|
||||
|
||||
This function looks up the strategy based on the exact transformer_cls_name string,
|
||||
which should match the transformer type in the pipeline (i.e., pipeline.transformer.__class__.__name__).
|
||||
|
||||
Args:
|
||||
transformer_cls_name: Transformer class name (e.g., "FluxTransformer2DModel")
|
||||
Must exactly match a registered strategy.
|
||||
|
||||
Returns:
|
||||
MagCacheStrategy instance for the model
|
||||
|
||||
Raises:
|
||||
ValueError: If model type not found in registry
|
||||
"""
|
||||
return MagCacheStrategyRegistry.get(transformer_cls_name)
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Prompt-embedding cache for diffusion pipelines.
|
||||
|
||||
Text encoders are the single most expensive per-request preprocessing step in
|
||||
most diffusion pipelines, and their inputs are frequently identical across
|
||||
requests (e.g. in GRPO-style rollouts the same prompt is submitted many times
|
||||
with different seeds to sample different images). Re-running the text encoder
|
||||
for each of those requests wastes compute and GPU memory.
|
||||
|
||||
This module provides a small LRU cache plus a transparent wrapper for a
|
||||
pipeline's ``encode_prompt`` method. Because almost every diffusion pipeline in
|
||||
``vllm_omni/diffusion/models`` routes all text-encoder invocations through
|
||||
``self.encode_prompt(...)``, wrapping that single method is sufficient to
|
||||
cache results model-wide without per-pipeline edits.
|
||||
|
||||
Design points:
|
||||
* The wrapper is installed by :class:`DiffusionModelRunner` after the
|
||||
pipeline has loaded, so each runner process owns its own cache.
|
||||
* Cache keys are derived from the bound ``encode_prompt`` arguments. Only
|
||||
inputs we can safely hash (``str`` / ``int`` / ``float`` / ``bool`` /
|
||||
``None`` / ``bytes`` / ``torch.device`` / ``torch.dtype`` / numpy
|
||||
scalars / nested lists/tuples/dicts of those) participate in the key.
|
||||
If any argument is a tensor, PIL image, or other non-trivial object, we
|
||||
bypass the cache for that call to guarantee correctness.
|
||||
* If a caller passes precomputed ``*_embeds`` into ``encode_prompt`` the
|
||||
wrapper also bypasses the cache because the call is already short-circuit.
|
||||
* Cache values are detached tensors. Downstream pipeline code typically
|
||||
does non-inplace ops (``.repeat``, ``.view``, slicing); we do not clone
|
||||
on hit since outputs are treated as read-only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import inspect
|
||||
import os
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# Sentinel returned by :func:`_hashable` when an input cannot be hashed
|
||||
# safely (e.g. tensor / PIL image / custom object). Any such input disables
|
||||
# caching for that specific call.
|
||||
_NOT_HASHABLE = object()
|
||||
|
||||
# Sentinel returned by :meth:`PromptEmbedCache.get` to distinguish a cache
|
||||
# miss from a legitimate cached value of ``None``.
|
||||
_CACHE_MISS = object()
|
||||
|
||||
# Argument names whose presence of a non-None value means the caller is
|
||||
# providing precomputed embeddings. In every pipeline we inspected, passing
|
||||
# these makes ``encode_prompt`` a cheap passthrough, so caching it has no
|
||||
# benefit and just wastes memory on large tensor keys.
|
||||
_PRECOMPUTED_EMBED_ARGS = (
|
||||
"prompt_embeds",
|
||||
"negative_prompt_embeds",
|
||||
"pooled_prompt_embeds",
|
||||
"negative_pooled_prompt_embeds",
|
||||
"prompt_embeds_mask",
|
||||
"negative_prompt_embeds_mask",
|
||||
)
|
||||
|
||||
|
||||
def _hashable(obj: Any) -> Any:
|
||||
"""Convert *obj* into a hashable representation or return ``_NOT_HASHABLE``.
|
||||
|
||||
Only inputs whose textual / scalar identity fully determines the
|
||||
``encode_prompt`` output are considered safe. Tensors and PIL images (which
|
||||
flow through e.g. image-edit pipelines) deliberately disable caching for
|
||||
that call rather than risk stale results. Common value-like configuration
|
||||
objects such as ``torch.device`` and ``torch.dtype`` are normalized to
|
||||
stable string forms so they can participate in cache keys safely.
|
||||
"""
|
||||
if obj is None or isinstance(obj, (str, int, float, bool, bytes)):
|
||||
return obj
|
||||
if isinstance(obj, torch.device):
|
||||
return ("__torch_device__", str(obj))
|
||||
if isinstance(obj, torch.dtype):
|
||||
return ("__torch_dtype__", str(obj))
|
||||
if type(obj).__module__.split(".", 1)[0] == "numpy" and hasattr(obj, "item"):
|
||||
try:
|
||||
return _hashable(obj.item())
|
||||
except (ValueError, TypeError):
|
||||
return _NOT_HASHABLE
|
||||
if isinstance(obj, (list, tuple)):
|
||||
out = []
|
||||
for item in obj:
|
||||
h = _hashable(item)
|
||||
if h is _NOT_HASHABLE:
|
||||
return _NOT_HASHABLE
|
||||
out.append(h)
|
||||
return ("__seq__", tuple(out))
|
||||
if isinstance(obj, dict):
|
||||
items = []
|
||||
for k in sorted(obj.keys(), key=repr):
|
||||
v = _hashable(obj[k])
|
||||
if v is _NOT_HASHABLE:
|
||||
return _NOT_HASHABLE
|
||||
items.append((repr(k), v))
|
||||
return ("__dict__", tuple(items))
|
||||
# torch.Tensor, PIL.Image, np.ndarray, and any other object → not safe.
|
||||
return _NOT_HASHABLE
|
||||
|
||||
|
||||
def _detach_output(value: Any) -> Any:
|
||||
"""Detach tensors in the return value so the cache never holds grad state."""
|
||||
if isinstance(value, torch.Tensor):
|
||||
return value.detach()
|
||||
if isinstance(value, tuple):
|
||||
detached = tuple(_detach_output(v) for v in value)
|
||||
# Preserve namedtuple types so attribute access keeps working.
|
||||
if hasattr(value, "_fields"):
|
||||
return type(value)(*detached)
|
||||
return detached
|
||||
if isinstance(value, list):
|
||||
return [_detach_output(v) for v in value]
|
||||
if isinstance(value, dict):
|
||||
return {k: _detach_output(v) for k, v in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
class PromptEmbedCache:
|
||||
"""Thread-safe LRU cache for ``encode_prompt`` outputs.
|
||||
|
||||
The cache stores whatever ``encode_prompt`` returns (tensor, tuple of
|
||||
tensors, ``None``, etc.). Lookup / insertion is O(1) amortized. Eviction
|
||||
is least-recently-used.
|
||||
"""
|
||||
|
||||
def __init__(self, max_size: int = 32, enabled: bool = True) -> None:
|
||||
if max_size <= 0:
|
||||
raise ValueError(f"max_size must be positive, got {max_size}")
|
||||
self.max_size = max_size
|
||||
self.enabled = enabled
|
||||
self._store: OrderedDict[Any, Any] = OrderedDict()
|
||||
self._lock = threading.Lock()
|
||||
self.hits = 0
|
||||
self.misses = 0
|
||||
self.bypassed = 0
|
||||
|
||||
def get(self, key: Any) -> Any:
|
||||
"""Return the cached value or ``_CACHE_MISS`` if absent.
|
||||
|
||||
Returning a sentinel (rather than ``None``) lets callers cache
|
||||
legitimate ``None`` results from the wrapped function.
|
||||
"""
|
||||
with self._lock:
|
||||
if key not in self._store:
|
||||
self.misses += 1
|
||||
return _CACHE_MISS
|
||||
self._store.move_to_end(key)
|
||||
self.hits += 1
|
||||
return self._store[key]
|
||||
|
||||
def put(self, key: Any, value: Any) -> None:
|
||||
with self._lock:
|
||||
self._store[key] = value
|
||||
self._store.move_to_end(key)
|
||||
while len(self._store) > self.max_size:
|
||||
self._store.popitem(last=False)
|
||||
|
||||
def clear(self) -> None:
|
||||
with self._lock:
|
||||
self._store.clear()
|
||||
|
||||
def stats(self) -> dict[str, int]:
|
||||
with self._lock:
|
||||
return {
|
||||
"size": len(self._store),
|
||||
"max_size": self.max_size,
|
||||
"hits": self.hits,
|
||||
"misses": self.misses,
|
||||
"bypassed": self.bypassed,
|
||||
}
|
||||
|
||||
|
||||
def _build_key(
|
||||
signature: inspect.Signature,
|
||||
model_tag: str,
|
||||
args: tuple,
|
||||
kwargs: dict,
|
||||
) -> Any:
|
||||
"""Return a hashable cache key or ``None`` if this call must bypass cache.
|
||||
|
||||
We bind the raw positional / keyword arguments to the method signature so
|
||||
that keyword and positional invocations with the same underlying values
|
||||
collide in the cache.
|
||||
"""
|
||||
try:
|
||||
bound = signature.bind_partial(*args, **kwargs)
|
||||
except TypeError:
|
||||
return None
|
||||
bound.apply_defaults()
|
||||
|
||||
# Bypass when the caller supplies precomputed embeddings.
|
||||
for name in _PRECOMPUTED_EMBED_ARGS:
|
||||
if name in bound.arguments and bound.arguments[name] is not None:
|
||||
return None
|
||||
|
||||
items: list[tuple[str, Any]] = []
|
||||
for name in sorted(bound.arguments.keys()):
|
||||
h = _hashable(bound.arguments[name])
|
||||
if h is _NOT_HASHABLE:
|
||||
return None
|
||||
items.append((name, h))
|
||||
return (model_tag, tuple(items))
|
||||
|
||||
|
||||
def install_prompt_embed_cache(
|
||||
pipeline: Any,
|
||||
*,
|
||||
max_size: int = 32,
|
||||
enabled: bool = True,
|
||||
model_tag: str | None = None,
|
||||
) -> PromptEmbedCache | None:
|
||||
"""Wrap ``pipeline.encode_prompt`` so results are cached by argument identity.
|
||||
|
||||
Idempotent: calling twice on the same pipeline is a no-op and returns the
|
||||
existing cache. Returns ``None`` if the pipeline has no ``encode_prompt``
|
||||
method.
|
||||
"""
|
||||
existing = getattr(pipeline, "_prompt_embed_cache", None)
|
||||
if existing is not None:
|
||||
return existing
|
||||
|
||||
encode_fn = getattr(pipeline, "encode_prompt", None)
|
||||
if encode_fn is None or not callable(encode_fn):
|
||||
logger.debug(
|
||||
"Prompt-embed cache: pipeline %s has no encode_prompt(); skipping.",
|
||||
type(pipeline).__name__,
|
||||
)
|
||||
return None
|
||||
|
||||
try:
|
||||
signature = inspect.signature(encode_fn)
|
||||
except (TypeError, ValueError) as e:
|
||||
logger.warning(
|
||||
"Prompt-embed cache: cannot introspect encode_prompt on %s (%s); skipping.",
|
||||
type(pipeline).__name__,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
cache = PromptEmbedCache(max_size=max_size, enabled=enabled)
|
||||
tag = model_tag or type(pipeline).__name__
|
||||
|
||||
@functools.wraps(encode_fn)
|
||||
def cached_encode_prompt(*args: Any, **kwargs: Any) -> Any:
|
||||
if not cache.enabled:
|
||||
return encode_fn(*args, **kwargs)
|
||||
key = _build_key(signature, tag, args, kwargs)
|
||||
if key is None:
|
||||
with cache._lock:
|
||||
cache.bypassed += 1
|
||||
return encode_fn(*args, **kwargs)
|
||||
hit = cache.get(key)
|
||||
if hit is not _CACHE_MISS:
|
||||
return hit
|
||||
out = encode_fn(*args, **kwargs)
|
||||
cache.put(key, _detach_output(out))
|
||||
return out
|
||||
|
||||
cached_encode_prompt.__wrapped__ = encode_fn # type: ignore[attr-defined]
|
||||
# Use object.__setattr__ to bypass diffusers ModelMixin attribute checks.
|
||||
try:
|
||||
pipeline.encode_prompt = cached_encode_prompt # type: ignore[assignment]
|
||||
except Exception:
|
||||
object.__setattr__(pipeline, "encode_prompt", cached_encode_prompt)
|
||||
object.__setattr__(pipeline, "_prompt_embed_cache", cache)
|
||||
object.__setattr__(pipeline, "_prompt_embed_cache_original_fn", encode_fn)
|
||||
|
||||
logger.info(
|
||||
"Prompt-embed cache installed on %s (max_size=%d, enabled=%s).",
|
||||
tag,
|
||||
max_size,
|
||||
enabled,
|
||||
)
|
||||
return cache
|
||||
|
||||
|
||||
def uninstall_prompt_embed_cache(pipeline: Any) -> None:
|
||||
"""Restore the original ``encode_prompt`` on *pipeline* if wrapped."""
|
||||
original = getattr(pipeline, "_prompt_embed_cache_original_fn", None)
|
||||
if original is None:
|
||||
return
|
||||
try:
|
||||
pipeline.encode_prompt = original # type: ignore[assignment]
|
||||
except Exception:
|
||||
object.__setattr__(pipeline, "encode_prompt", original)
|
||||
for attr in ("_prompt_embed_cache", "_prompt_embed_cache_original_fn"):
|
||||
if hasattr(pipeline, attr):
|
||||
try:
|
||||
delattr(pipeline, attr)
|
||||
except Exception:
|
||||
object.__setattr__(pipeline, attr, None)
|
||||
|
||||
|
||||
def resolve_prompt_embed_cache_config(
|
||||
enable: bool | None = None,
|
||||
max_size: int | None = None,
|
||||
) -> tuple[bool, int]:
|
||||
"""Combine explicit args with env-var overrides.
|
||||
|
||||
Environment variables (useful for quick enablement in GRPO jobs without
|
||||
touching config files):
|
||||
|
||||
``OMNI_DIFFUSION_PROMPT_EMBED_CACHE`` (``1``/``0``/``true``/``false``)
|
||||
``OMNI_DIFFUSION_PROMPT_EMBED_CACHE_SIZE`` (positive int)
|
||||
"""
|
||||
env_enable = os.environ.get("OMNI_DIFFUSION_PROMPT_EMBED_CACHE")
|
||||
if env_enable is not None:
|
||||
parsed = env_enable.strip().lower()
|
||||
if parsed in ("1", "true", "yes", "on"):
|
||||
enable = True
|
||||
elif parsed in ("0", "false", "no", "off"):
|
||||
enable = False
|
||||
|
||||
env_size = os.environ.get("OMNI_DIFFUSION_PROMPT_EMBED_CACHE_SIZE")
|
||||
if env_size is not None:
|
||||
try:
|
||||
env_size_int = int(env_size)
|
||||
if env_size_int > 0:
|
||||
max_size = env_size_int
|
||||
except ValueError:
|
||||
logger.warning(
|
||||
"Ignoring non-integer OMNI_DIFFUSION_PROMPT_EMBED_CACHE_SIZE=%r.",
|
||||
env_size,
|
||||
)
|
||||
|
||||
return bool(enable), int(max_size or 32)
|
||||
+10
-4
@@ -2,6 +2,7 @@ from typing import Any
|
||||
|
||||
from vllm_omni.diffusion.cache.base import CacheBackend
|
||||
from vllm_omni.diffusion.cache.cache_dit_backend import CacheDiTBackend
|
||||
from vllm_omni.diffusion.cache.magcache.backend import MagCacheBackend
|
||||
from vllm_omni.diffusion.cache.teacache.backend import TeaCacheBackend
|
||||
from vllm_omni.diffusion.data import DiffusionCacheConfig
|
||||
|
||||
@@ -12,14 +13,15 @@ def get_cache_backend(cache_backend: str | None, cache_config: Any) -> CacheBack
|
||||
This is a selector function that routes to the appropriate backend implementation.
|
||||
- cache_dit: Uses CacheDiTBackend with enable()/refresh() interface
|
||||
- tea_cache: Uses TeaCacheBackend with enable()/refresh() interface
|
||||
- mag_cache: Uses MagCacheBackend with enable()/refresh() interface
|
||||
|
||||
Args:
|
||||
cache_backend: Cache backend name ("cache_dit", "tea_cache", or None).
|
||||
cache_backend: Cache backend name ("cache_dit", "tea_cache", "mag_cache", or None).
|
||||
cache_config: Cache configuration (dict or DiffusionCacheConfig instance).
|
||||
|
||||
Returns:
|
||||
Cache backend instance (CacheDiTBackend or TeaCacheBackend) if cache_backend is set,
|
||||
None otherwise.
|
||||
Cache backend instance (CacheDiTBackend, TeaCacheBackend, or MagCacheBackend)
|
||||
if cache_backend is set, None otherwise.
|
||||
|
||||
Raises:
|
||||
ValueError: If cache_backend is unsupported.
|
||||
@@ -34,5 +36,9 @@ def get_cache_backend(cache_backend: str | None, cache_config: Any) -> CacheBack
|
||||
return CacheDiTBackend(cache_config)
|
||||
elif cache_backend == "tea_cache":
|
||||
return TeaCacheBackend(cache_config)
|
||||
elif cache_backend == "mag_cache":
|
||||
return MagCacheBackend(cache_config)
|
||||
else:
|
||||
raise ValueError(f"Unsupported cache backend: {cache_backend}. Supported: 'cache_dit', 'tea_cache'")
|
||||
raise ValueError(
|
||||
f"Unsupported cache backend: {cache_backend}. Supported: 'cache_dit', 'tea_cache', 'mag_cache'"
|
||||
)
|
||||
@@ -77,7 +77,7 @@ class DefaultAdapter:
|
||||
os.path.join("transformer", "config.json"),
|
||||
od_config.model,
|
||||
)
|
||||
od_config.tf_model_config = TransformerConfig.from_dict(tf_config_dict)
|
||||
od_config.set_tf_model_config(TransformerConfig.from_dict(tf_config_dict))
|
||||
|
||||
loader = DiffusersPipelineLoader(LoadConfig(), od_config=od_config)
|
||||
# load_model will handle dtypes / device placement, put in .eval() mode
|
||||
@@ -202,6 +202,7 @@ class TeaCacheCoefficientEstimator:
|
||||
self.hook.start_collection()
|
||||
req = OmniDiffusionRequest(
|
||||
prompts=[prompt],
|
||||
request_id="teacache-coefficient-estimator",
|
||||
sampling_params=OmniDiffusionSamplingParams(
|
||||
num_inference_steps=generate_kwargs.get("num_inference_steps", 20),
|
||||
seed=generate_kwargs.get("seed", 42),
|
||||
|
||||
+4
-11
@@ -277,8 +277,10 @@ def extract_qwen_context(
|
||||
|
||||
def postprocess(h):
|
||||
"""Apply Qwen-specific output postprocessing."""
|
||||
t = temb.chunk(2, dim=0)[0] if module.zero_cond_t else temb
|
||||
h = module.norm_out(h, t)
|
||||
if getattr(module, "zero_cond_t", False):
|
||||
h = module.norm_out(h, temb.chunk(2, dim=0)[0])
|
||||
else:
|
||||
h = module.norm_out(h, temb)
|
||||
output = module.proj_out(h)
|
||||
if not return_dict:
|
||||
return (output,)
|
||||
@@ -305,12 +307,9 @@ def extract_bagel_context(
|
||||
packed_vae_position_ids: torch.LongTensor,
|
||||
packed_text_ids: torch.LongTensor,
|
||||
packed_text_indexes: torch.LongTensor,
|
||||
packed_indexes: torch.LongTensor,
|
||||
packed_position_ids: torch.LongTensor,
|
||||
packed_seqlens: torch.IntTensor,
|
||||
key_values_lens: torch.IntTensor,
|
||||
past_key_values: Any,
|
||||
packed_key_value_indexes: torch.LongTensor,
|
||||
**kwargs: Any,
|
||||
) -> CacheContext:
|
||||
"""
|
||||
@@ -324,12 +323,9 @@ def extract_bagel_context(
|
||||
packed_vae_position_ids: Position IDs for VAE tokens
|
||||
packed_text_ids: Text token IDs
|
||||
packed_text_indexes: Indexes for text tokens in packed sequence
|
||||
packed_indexes: Global indexes
|
||||
packed_position_ids: Global position IDs
|
||||
packed_seqlens: Sequence lengths
|
||||
key_values_lens: KV cache lengths
|
||||
past_key_values: KV cache
|
||||
packed_key_value_indexes: KV cache indexes
|
||||
**kwargs: Additional keyword arguments
|
||||
|
||||
Returns:
|
||||
@@ -373,10 +369,7 @@ def extract_bagel_context(
|
||||
packed_query_sequence=packed_sequence,
|
||||
query_lens=packed_seqlens,
|
||||
packed_query_position_ids=packed_position_ids,
|
||||
packed_query_indexes=packed_indexes,
|
||||
past_key_values=past_key_values,
|
||||
key_values_lens=key_values_lens,
|
||||
packed_key_value_indexes=packed_key_value_indexes,
|
||||
update_past_key_values=False,
|
||||
is_causal=False,
|
||||
**extra_inputs,
|
||||
|
||||
@@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any
|
||||
import diffusers
|
||||
import torch
|
||||
from PIL import Image
|
||||
from pydantic import model_validator
|
||||
from pydantic import Field, model_validator
|
||||
from typing_extensions import Self
|
||||
from vllm.config.utils import config
|
||||
from vllm.logger import init_logger
|
||||
@@ -281,7 +281,7 @@ class TransformerConfig:
|
||||
@dataclass
|
||||
class DiffusionCacheConfig:
|
||||
"""
|
||||
Configuration for cache adapters (TeaCache, cache-dit, etc.).
|
||||
Configuration for cache adapters (TeaCache, cache-dit, MagCache, etc.).
|
||||
|
||||
This dataclass provides a unified interface for cache configuration parameters.
|
||||
It can be initialized from a dictionary and accessed via attributes.
|
||||
@@ -291,6 +291,8 @@ class DiffusionCacheConfig:
|
||||
- cache-dit: Fn_compute_blocks, Bn_compute_blocks, max_warmup_steps,
|
||||
residual_diff_threshold, enable_taylorseer, taylorseer_order,
|
||||
scm_steps_mask_policy, scm_steps_policy
|
||||
- MagCache: mag_threshold, mag_max_skip_steps, mag_retention_ratio,
|
||||
mag_ratios, mag_calibrate
|
||||
|
||||
Example:
|
||||
>>> # From dict (user-facing API) - partial config uses defaults for missing keys
|
||||
@@ -300,7 +302,7 @@ class DiffusionCacheConfig:
|
||||
>>> print(config.Fn_compute_blocks) # 8 (default)
|
||||
>>> # Empty dict uses all defaults
|
||||
>>> default_config = DiffusionCacheConfig.from_dict({})
|
||||
>>> print(default_config.rel_l1_thresh) # 0.2 (default)
|
||||
>>> print(config.rel_l1_thresh) # 0.2 (default)
|
||||
"""
|
||||
|
||||
# TeaCache parameters [tea_cache only]
|
||||
@@ -308,6 +310,18 @@ class DiffusionCacheConfig:
|
||||
rel_l1_thresh: float = 0.2
|
||||
coefficients: list[float] | None = None # Uses model-specific defaults if None
|
||||
|
||||
# MagCache parameters [mag_cache only]
|
||||
# Default: 0.24 threshold for accumulated magnitude error
|
||||
mag_threshold: float = 0.24
|
||||
# Default: 5 maximum consecutive skip steps (K)
|
||||
mag_max_skip_steps: int = 5
|
||||
# Default: 0.1 fraction of initial steps where skipping is disabled (stability)
|
||||
mag_retention_ratio: float = 0.1
|
||||
# Default: None magnitude ratios (model-specific, required for inference)
|
||||
mag_ratios: list[float] | None = None
|
||||
# Default: False calibration mode (computes mag_ratios on first run)
|
||||
mag_calibrate: bool = False
|
||||
|
||||
# cache-dit parameters [cache-dit only]
|
||||
# Default: 1 forward compute block (optimized for single-transformer models)
|
||||
# Use 1 as default instead of cache-dit's 8, optimized for single-transformer models
|
||||
@@ -432,6 +446,15 @@ class OmniDiffusionConfig:
|
||||
cache_config: DiffusionCacheConfig | dict[str, Any] = field(default_factory=dict)
|
||||
enable_cache_dit_summary: bool = False
|
||||
|
||||
# Prompt-embedding cache. When enabled, ``DiffusionModelRunner`` wraps the
|
||||
# pipeline's ``encode_prompt`` so repeated calls with identical prompt
|
||||
# arguments (e.g. GRPO rollouts that sample the same prompt many times
|
||||
# with different seeds) reuse the text-encoder output instead of re-running
|
||||
# it. Safe against inputs that cannot be hashed (tensors, PIL images):
|
||||
# those calls transparently bypass the cache.
|
||||
enable_prompt_embed_cache: bool = False
|
||||
prompt_embed_cache_size: int = 32
|
||||
|
||||
# Distributed executor backend
|
||||
distributed_executor_backend: str = "mp"
|
||||
nccl_port: int | None = None
|
||||
@@ -593,6 +616,9 @@ class OmniDiffusionConfig:
|
||||
# Maximum number of sequences to generate in a batch
|
||||
max_num_seqs: int = 1
|
||||
|
||||
# Supplementary model specific parameters
|
||||
extras: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def is_moe(self) -> bool:
|
||||
num_experts = self.tf_model_config.get("num_experts", None)
|
||||
@@ -606,6 +632,25 @@ class OmniDiffusionConfig:
|
||||
|
||||
return False
|
||||
|
||||
def _resolve_master_port(self) -> int:
|
||||
"""Resolve torch.distributed master port without unnecessary random jitter.
|
||||
|
||||
Precedence:
|
||||
1. ``MASTER_PORT`` environment variable (set by orchestrators for multi-replica launch).
|
||||
2. Explicit ``master_port`` passed at construction time.
|
||||
3. An OS-assigned ephemeral port when neither is provided.
|
||||
"""
|
||||
from vllm.utils.network_utils import get_open_port
|
||||
|
||||
from vllm_omni.diffusion import envs
|
||||
|
||||
env_port = envs.MASTER_PORT
|
||||
if env_port is not None:
|
||||
return self.settle_port(env_port, port_inc=37)
|
||||
if self.master_port is not None:
|
||||
return self.settle_port(self.master_port, port_inc=37)
|
||||
return self.settle_port(get_open_port(), port_inc=37)
|
||||
|
||||
def settle_port(self, port: int, port_inc: int = 42, max_attempts: int = 100) -> int:
|
||||
"""
|
||||
Find an available port with retry logic.
|
||||
@@ -642,9 +687,7 @@ class OmniDiffusionConfig:
|
||||
)
|
||||
|
||||
def __post_init__(self):
|
||||
# TODO: remove hard code
|
||||
initial_master_port = (self.master_port or 30005) + random.randint(0, 100)
|
||||
self.master_port = self.settle_port(initial_master_port, 37)
|
||||
self.master_port = self._resolve_master_port()
|
||||
|
||||
if isinstance(self.profiler_config, dict):
|
||||
from vllm.config import ProfilerConfig
|
||||
@@ -745,8 +788,11 @@ class OmniDiffusionConfig:
|
||||
return
|
||||
|
||||
is_checkpoint_fp8 = bool(getattr(tf_config.quant_config, "is_checkpoint_fp8_serialized", False))
|
||||
should_use_checkpoint_config = self.quantization_config is None or (
|
||||
is_checkpoint_fp8 and self._is_generic_fp8_quant_config(self.quantization_config)
|
||||
is_checkpoint_nvfp4 = bool(getattr(tf_config.quant_config, "is_checkpoint_nvfp4_serialized", False))
|
||||
should_use_checkpoint_config = (
|
||||
self.quantization_config is None
|
||||
or (is_checkpoint_fp8 and self._is_generic_fp8_quant_config(self.quantization_config))
|
||||
or (is_checkpoint_nvfp4 and self._is_generic_nvfp4_quant_config(self.quantization_config))
|
||||
)
|
||||
if should_use_checkpoint_config:
|
||||
self.quantization_config = tf_config.quant_config
|
||||
@@ -766,6 +812,17 @@ class OmniDiffusionConfig:
|
||||
return quant_config.get_name() == "fp8"
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _is_generic_nvfp4_quant_config(quant_config: object) -> bool:
|
||||
if isinstance(quant_config, str):
|
||||
return quant_config.lower() in {"fp4", "nvfp4", "modelopt_fp4"}
|
||||
if isinstance(quant_config, Mapping):
|
||||
method = quant_config.get("method", quant_config.get("quant_method"))
|
||||
return isinstance(method, str) and method.lower() in {"fp4", "nvfp4", "modelopt_fp4"}
|
||||
if hasattr(quant_config, "get_name"):
|
||||
return quant_config.get_name() == "modelopt_fp4"
|
||||
return False
|
||||
|
||||
def set_tf_model_config(self, tf_config: "TransformerConfig") -> None:
|
||||
"""Assign `tf_model_config` and propagate quantization if detected.
|
||||
|
||||
@@ -894,6 +951,17 @@ class OmniDiffusionConfig:
|
||||
self.model_class_name = "SenseNovaU1Pipeline"
|
||||
self.tf_model_config = TransformerConfig()
|
||||
self.update_multimodal_support()
|
||||
elif "BailingMM2NativeForConditionalGeneration" in architectures or model_type in (
|
||||
"bailingmm_moe_v2_lite",
|
||||
"ming_flash_omni",
|
||||
"ming_flash_omni_thinker",
|
||||
):
|
||||
# Ming-flash-omni-2.0 — imagegen stage uses the custom
|
||||
# ``MingImagePipeline`` (ZImage DiT + Qwen2 connector). See
|
||||
# vllm_omni/diffusion/models/ming_flash_omni/pipeline_ming_imagegen.py.
|
||||
self.model_class_name = "MingImagePipeline"
|
||||
self.tf_model_config = TransformerConfig()
|
||||
self.update_multimodal_support()
|
||||
elif model_type == "nextstep":
|
||||
if self.model_class_name is None:
|
||||
self.model_class_name = "NextStep11Pipeline"
|
||||
@@ -999,6 +1067,28 @@ class DiffusionOutput:
|
||||
# memory usage info
|
||||
peak_memory_mb: float = 0.0
|
||||
|
||||
# When True, move all tensor fields (including tensors inside
|
||||
# ``custom_output``) to CPU at construction time. Useful when the output
|
||||
# is shipped across process boundaries (e.g. step-execution mode) and the
|
||||
# receiving side must not initialise a stray CUDA context.
|
||||
to_cpu: bool = False
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.to_cpu:
|
||||
return
|
||||
|
||||
def _maybe_to_cpu(value: Any) -> Any:
|
||||
if isinstance(value, torch.Tensor):
|
||||
return value.detach().cpu()
|
||||
return value
|
||||
|
||||
self.output = _maybe_to_cpu(self.output)
|
||||
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)
|
||||
if self.custom_output:
|
||||
self.custom_output = {k: _maybe_to_cpu(v) for k, v in self.custom_output.items()}
|
||||
|
||||
|
||||
class DiffusionRequestAbortedError(RuntimeError):
|
||||
"""Raised when a diffusion request ends via user-visible abort."""
|
||||
|
||||
@@ -30,10 +30,10 @@ from vllm_omni.diffusion.registry import (
|
||||
get_diffusion_post_process_func,
|
||||
get_diffusion_pre_process_func,
|
||||
)
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.request import DUMMY_DIFFUSION_REQUEST_ID, OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.sched import RequestScheduler, SchedulerInterface, StepScheduler
|
||||
from vllm_omni.diffusion.sched.interface import DiffusionRequestStatus
|
||||
from vllm_omni.diffusion.worker.utils import BatchRunnerOutput, RunnerOutput
|
||||
from vllm_omni.diffusion.worker.utils import BaseRunnerOutput, BatchRunnerOutput, RunnerOutput
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniTextPrompt
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
@@ -83,6 +83,13 @@ def supports_audio_output(model_class_name: str) -> bool:
|
||||
return bool(getattr(model_cls, "support_audio_output", False))
|
||||
|
||||
|
||||
def get_dummy_run_num_frames(model_class_name: str, supports_audio_input: bool) -> int:
|
||||
model_cls = DiffusionModelRegistry._try_load_model_cls(model_class_name)
|
||||
if model_cls is not None and hasattr(model_cls, "dummy_run_num_frames"):
|
||||
return int(getattr(model_cls, "dummy_run_num_frames"))
|
||||
return 2 if supports_audio_input or supports_audio_output(model_class_name) else 1
|
||||
|
||||
|
||||
def get_extra_body_params(model_class_name: str) -> frozenset[str]:
|
||||
"""Return the set of extra_body keys accepted by a pipeline.
|
||||
|
||||
@@ -217,7 +224,7 @@ class DiffusionEngine:
|
||||
logger.warning("Output is None, returning empty OmniRequestOutput")
|
||||
return [
|
||||
OmniRequestOutput.from_diffusion(
|
||||
request_id=request.request_ids[i] if i < len(request.request_ids) else "",
|
||||
request_id=request.request_id,
|
||||
images=[],
|
||||
prompt=prompt,
|
||||
metrics={},
|
||||
@@ -304,7 +311,7 @@ class DiffusionEngine:
|
||||
if len(request.prompts) == 1:
|
||||
# Single request: return single OmniRequestOutput
|
||||
prompt = request.prompts[0]
|
||||
request_id = request.request_ids[0] if request.request_ids else ""
|
||||
request_id = request.request_id
|
||||
|
||||
if is_text_output:
|
||||
return [
|
||||
@@ -368,10 +375,9 @@ class DiffusionEngine:
|
||||
# Split images based on num_outputs_per_prompt for each request
|
||||
results = []
|
||||
output_idx = 0
|
||||
request_id = request.request_id
|
||||
|
||||
for i, prompt in enumerate(request.prompts):
|
||||
request_id = request.request_ids[i] if i < len(request.request_ids) else ""
|
||||
|
||||
# Get images for this request
|
||||
num_outputs = request.sampling_params.num_outputs_per_prompt
|
||||
start_idx = output_idx
|
||||
@@ -467,17 +473,17 @@ class DiffusionEngine:
|
||||
runner_output = self.execute_fn(sched_output)
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"Execution failed for diffusion requests %s", sched_output.scheduled_req_ids, exc_info=True
|
||||
"Execution failed for diffusion requests %s", sched_output.scheduled_request_ids, exc_info=True
|
||||
)
|
||||
runner_output = BatchRunnerOutput.from_list(
|
||||
[
|
||||
RunnerOutput(
|
||||
req_id=req_id,
|
||||
request_id=request_id,
|
||||
step_index=None,
|
||||
finished=True,
|
||||
result=DiffusionOutput(error=str(exc)),
|
||||
)
|
||||
for req_id in sched_output.scheduled_req_ids
|
||||
for request_id in sched_output.scheduled_request_ids
|
||||
]
|
||||
)
|
||||
|
||||
@@ -544,7 +550,7 @@ class DiffusionEngine:
|
||||
def _handle_finished_requests(
|
||||
self,
|
||||
finished_ids: set[str],
|
||||
runner_output: RunnerOutput | None = None,
|
||||
runner_output: BaseRunnerOutput | None = None,
|
||||
missing_result_error: str = "Diffusion execution finished without a final output",
|
||||
):
|
||||
for rid in finished_ids:
|
||||
@@ -553,7 +559,7 @@ class DiffusionEngine:
|
||||
if fut is None:
|
||||
continue
|
||||
if runner_output is not None:
|
||||
_output = runner_output.get_req_output(rid)
|
||||
_output = runner_output.get_request_output(rid)
|
||||
else:
|
||||
_output = None
|
||||
out = self._finalize_finished_request(rid, _output, missing_result_error)
|
||||
@@ -579,11 +585,11 @@ class DiffusionEngine:
|
||||
if self._closed:
|
||||
raise RuntimeError("DiffusionEngine is closed.")
|
||||
fut = self.main_loop.create_future()
|
||||
sched_req_id = self.scheduler.add_request(request)
|
||||
self._out_queue[sched_req_id] = fut
|
||||
request_id = self.scheduler.add_request(request)
|
||||
self._out_queue[request_id] = fut
|
||||
self._cv.notify_all()
|
||||
|
||||
return sched_req_id
|
||||
return request_id
|
||||
|
||||
async def get_result(self, request_id: str) -> DiffusionOutput:
|
||||
fut = self._out_queue.get(request_id)
|
||||
@@ -599,37 +605,37 @@ class DiffusionEngine:
|
||||
async def async_add_req_and_wait_for_response(self, request: OmniDiffusionRequest) -> DiffusionOutput:
|
||||
# No lock needed: add_request is already protected by self._cv, and
|
||||
# all executor calls are serialized inside the busy loop.
|
||||
sched_req_id = self.add_request(request)
|
||||
return await self.get_result(sched_req_id)
|
||||
request_id = self.add_request(request)
|
||||
return await self.get_result(request_id)
|
||||
|
||||
def add_req_and_wait_for_response(self, request: OmniDiffusionRequest) -> DiffusionOutput:
|
||||
with self._rpc_lock:
|
||||
if self._closed:
|
||||
raise RuntimeError("DiffusionEngine is closed.")
|
||||
target_sched_req_id = self.scheduler.add_request(request)
|
||||
target_request_id = self.scheduler.add_request(request)
|
||||
|
||||
# keep scheduling and executing until the target request is finished
|
||||
while True:
|
||||
self._process_aborts_queue()
|
||||
sched_output = self.scheduler.schedule()
|
||||
if sched_output.is_empty:
|
||||
if target_sched_req_id in sched_output.finished_req_ids:
|
||||
return self._finalize_finished_request(target_sched_req_id)
|
||||
if target_request_id in sched_output.finished_req_ids:
|
||||
return self._finalize_finished_request(target_request_id)
|
||||
if not self.scheduler.has_requests():
|
||||
raise RuntimeError("Diffusion scheduler has no runnable requests.")
|
||||
continue
|
||||
|
||||
# NOTE: add_req_and_wait_for_response() is synchronous, will be only called
|
||||
# within _dummy_run, only one request will be scheduled
|
||||
sched_req_id = sched_output.scheduled_req_ids[0]
|
||||
request_id = sched_output.scheduled_request_ids[0]
|
||||
try:
|
||||
runner_output = self.execute_fn(sched_output)
|
||||
except EngineDeadError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
logger.error("Execution failed for diffusion request %s", sched_req_id, exc_info=True)
|
||||
logger.error("Execution failed for diffusion request %s", request_id, exc_info=True)
|
||||
runner_output = RunnerOutput(
|
||||
req_id=sched_req_id,
|
||||
request_id=request_id,
|
||||
step_index=None,
|
||||
finished=True,
|
||||
result=DiffusionOutput(error=str(exc)),
|
||||
@@ -642,10 +648,10 @@ class DiffusionEngine:
|
||||
# sync func should receive one result
|
||||
if not isinstance(runner_output, RunnerOutput) and not len(runner_output) == 1:
|
||||
raise ValueError("Sync func should receive one result at one time")
|
||||
if target_sched_req_id in finished_req_ids:
|
||||
runner_output = runner_output.get_req_output(target_sched_req_id)
|
||||
if target_request_id in finished_req_ids:
|
||||
runner_output = runner_output.get_request_output(target_request_id)
|
||||
return self._finalize_finished_request(
|
||||
target_sched_req_id,
|
||||
target_request_id,
|
||||
runner_output=runner_output,
|
||||
missing_result_error="Diffusion execution finished without a final output.",
|
||||
)
|
||||
@@ -691,13 +697,15 @@ class DiffusionEngine:
|
||||
dummy_audio = np.random.randn(audio_sr * 2).astype(np.float32)
|
||||
prompt.setdefault("multi_modal_data", {})["audio"] = dummy_audio
|
||||
|
||||
num_frames = get_dummy_run_num_frames(self.od_config.model_class_name, supports_audio_input)
|
||||
req = OmniDiffusionRequest(
|
||||
prompts=[prompt],
|
||||
request_ids=["dummy_req_id"],
|
||||
request_id=DUMMY_DIFFUSION_REQUEST_ID,
|
||||
sampling_params=OmniDiffusionSamplingParams(
|
||||
height=height,
|
||||
width=width,
|
||||
num_inference_steps=num_inference_steps,
|
||||
num_frames=num_frames,
|
||||
# Keep warmup path minimal and robust across text encoders.
|
||||
# Some models may fail when warmup implicitly triggers
|
||||
# classifier-free guidance with an empty negative prompt.
|
||||
@@ -899,34 +907,27 @@ class DiffusionEngine:
|
||||
def _abort_requests(self, request_ids: str | Iterable[str]) -> None:
|
||||
request_ids = [request_ids] if isinstance(request_ids, str) else list(request_ids)
|
||||
|
||||
sched_req_ids: list[str] = []
|
||||
for request_id in dict.fromkeys(request_ids):
|
||||
sched_req_id = self.scheduler.get_sched_req_id(request_id)
|
||||
if sched_req_id is not None:
|
||||
sched_req_ids.append(sched_req_id)
|
||||
|
||||
for sched_req_id in dict.fromkeys(sched_req_ids):
|
||||
if self.scheduler.get_request_state(sched_req_id) is not None:
|
||||
self.scheduler.finish_requests(sched_req_id, DiffusionRequestStatus.FINISHED_ABORTED)
|
||||
if self.scheduler.get_request_state(request_id) is not None:
|
||||
self.scheduler.finish_requests(request_id, DiffusionRequestStatus.FINISHED_ABORTED)
|
||||
|
||||
def _finalize_finished_request(
|
||||
self,
|
||||
sched_req_id: str,
|
||||
request_id: str,
|
||||
runner_output: RunnerOutput | None = None,
|
||||
missing_result_error: str = "Diffusion scheduler finished target request without execution output.",
|
||||
) -> DiffusionOutput:
|
||||
state = self.scheduler.get_request_state(sched_req_id)
|
||||
popped_state = self.scheduler.pop_request_state(sched_req_id)
|
||||
state = self.scheduler.get_request_state(request_id)
|
||||
popped_state = self.scheduler.pop_request_state(request_id)
|
||||
state = state or popped_state
|
||||
|
||||
if state is None:
|
||||
raise RuntimeError(f"Diffusion scheduler lost state for request {sched_req_id}.")
|
||||
raise RuntimeError(f"Diffusion scheduler lost state for request {request_id}.")
|
||||
|
||||
if state.status == DiffusionRequestStatus.FINISHED_ABORTED:
|
||||
request_id = state.req.request_ids[0] if state.req.request_ids else sched_req_id
|
||||
return DiffusionOutput(
|
||||
aborted=True,
|
||||
abort_message=f"Request {request_id} aborted.",
|
||||
abort_message=f"Request {state.req.request_id} aborted.",
|
||||
)
|
||||
|
||||
if runner_output is not None and runner_output.result is not None:
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from diffusers import AutoencoderKLHunyuanVideo15
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor import (
|
||||
DistributedOperator,
|
||||
DistributedVaeMixin,
|
||||
GridSpec,
|
||||
TileTask,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class DistributedAutoencoderKLHunyuanVideo15(AutoencoderKLHunyuanVideo15, DistributedVaeMixin):
|
||||
@classmethod
|
||||
def from_pretrained(cls, *args: Any, **kwargs: Any):
|
||||
model = super().from_pretrained(*args, **kwargs)
|
||||
model.init_distributed()
|
||||
return model
|
||||
|
||||
def tile_split(self, z: torch.Tensor) -> tuple[list[TileTask], GridSpec]:
|
||||
_, _, _, height, width = z.shape
|
||||
overlap_height = int(self.tile_latent_min_height * (1 - self.tile_overlap_factor))
|
||||
overlap_width = int(self.tile_latent_min_width * (1 - self.tile_overlap_factor))
|
||||
blend_height = int(self.tile_sample_min_height * self.tile_overlap_factor)
|
||||
blend_width = int(self.tile_sample_min_width * self.tile_overlap_factor)
|
||||
row_limit_height = self.tile_sample_min_height - blend_height
|
||||
row_limit_width = self.tile_sample_min_width - blend_width
|
||||
|
||||
tiletask_list = []
|
||||
for i in range(0, height, overlap_height):
|
||||
for j in range(0, width, overlap_width):
|
||||
tile = z[:, :, :, i : i + self.tile_latent_min_height, j : j + self.tile_latent_min_width]
|
||||
tiletask_list.append(
|
||||
TileTask(
|
||||
len(tiletask_list),
|
||||
(i // overlap_height, j // overlap_width),
|
||||
tile,
|
||||
workload=tile.shape[3] * tile.shape[4],
|
||||
)
|
||||
)
|
||||
|
||||
grid_spec = GridSpec(
|
||||
split_dims=(3, 4),
|
||||
grid_shape=(tiletask_list[-1].grid_coord[0] + 1, tiletask_list[-1].grid_coord[1] + 1),
|
||||
tile_spec={
|
||||
"blend_height": blend_height,
|
||||
"blend_width": blend_width,
|
||||
"row_limit_height": row_limit_height,
|
||||
"row_limit_width": row_limit_width,
|
||||
},
|
||||
output_dtype=self.dtype,
|
||||
)
|
||||
return tiletask_list, grid_spec
|
||||
|
||||
def tile_exec(self, task: TileTask) -> torch.Tensor:
|
||||
return self.decoder(task.tensor)
|
||||
|
||||
def tile_merge(self, coord_tensor_map: dict[tuple[int, ...], torch.Tensor], grid_spec: GridSpec) -> torch.Tensor:
|
||||
grid_h, grid_w = grid_spec.grid_shape
|
||||
result_rows = []
|
||||
for i in range(grid_h):
|
||||
result_row = []
|
||||
for j in range(grid_w):
|
||||
tile = coord_tensor_map[(i, j)]
|
||||
if i > 0:
|
||||
tile = self.blend_v(coord_tensor_map[(i - 1, j)], tile, grid_spec.tile_spec["blend_height"])
|
||||
if j > 0:
|
||||
tile = self.blend_h(coord_tensor_map[(i, j - 1)], tile, grid_spec.tile_spec["blend_width"])
|
||||
result_row.append(
|
||||
tile[
|
||||
:,
|
||||
:,
|
||||
:,
|
||||
: grid_spec.tile_spec["row_limit_height"],
|
||||
: grid_spec.tile_spec["row_limit_width"],
|
||||
]
|
||||
)
|
||||
result_rows.append(torch.cat(result_row, dim=-1))
|
||||
return torch.cat(result_rows, dim=-2)
|
||||
|
||||
def encode_tile_split(self, x: torch.Tensor) -> tuple[list[TileTask], GridSpec]:
|
||||
_, _, _, height, width = x.shape
|
||||
overlap_height = int(self.tile_sample_min_height * (1 - self.tile_overlap_factor))
|
||||
overlap_width = int(self.tile_sample_min_width * (1 - self.tile_overlap_factor))
|
||||
blend_height = int(self.tile_latent_min_height * self.tile_overlap_factor)
|
||||
blend_width = int(self.tile_latent_min_width * self.tile_overlap_factor)
|
||||
row_limit_height = self.tile_latent_min_height - blend_height
|
||||
row_limit_width = self.tile_latent_min_width - blend_width
|
||||
|
||||
tiletask_list = []
|
||||
for i in range(0, height, overlap_height):
|
||||
for j in range(0, width, overlap_width):
|
||||
tile = x[:, :, :, i : i + self.tile_sample_min_height, j : j + self.tile_sample_min_width]
|
||||
tiletask_list.append(
|
||||
TileTask(
|
||||
len(tiletask_list),
|
||||
(i // overlap_height, j // overlap_width),
|
||||
tile,
|
||||
workload=tile.shape[3] * tile.shape[4],
|
||||
)
|
||||
)
|
||||
|
||||
grid_spec = GridSpec(
|
||||
split_dims=(3, 4),
|
||||
grid_shape=(tiletask_list[-1].grid_coord[0] + 1, tiletask_list[-1].grid_coord[1] + 1),
|
||||
tile_spec={
|
||||
"blend_height": blend_height,
|
||||
"blend_width": blend_width,
|
||||
"row_limit_height": row_limit_height,
|
||||
"row_limit_width": row_limit_width,
|
||||
},
|
||||
output_dtype=self.dtype,
|
||||
)
|
||||
return tiletask_list, grid_spec
|
||||
|
||||
def encode_tile_exec(self, task: TileTask) -> torch.Tensor:
|
||||
return self.encoder(task.tensor)
|
||||
|
||||
def tiled_encode(self, x: torch.Tensor) -> torch.Tensor:
|
||||
if not self.is_distributed_enabled():
|
||||
return super().tiled_encode(x)
|
||||
|
||||
logger.debug("Encode running with distributed executor")
|
||||
return self.distributed_executor.execute(
|
||||
x,
|
||||
DistributedOperator(
|
||||
split=self.encode_tile_split,
|
||||
exec=self.encode_tile_exec,
|
||||
merge=self.tile_merge,
|
||||
),
|
||||
broadcast_result=True,
|
||||
)
|
||||
|
||||
def tiled_decode(self, z: torch.Tensor) -> torch.Tensor:
|
||||
if not self.is_distributed_enabled():
|
||||
return super().tiled_decode(z)
|
||||
|
||||
logger.debug("Decode running with distributed executor")
|
||||
return self.distributed_executor.execute(
|
||||
z,
|
||||
DistributedOperator(split=self.tile_split, exec=self.tile_exec, merge=self.tile_merge),
|
||||
broadcast_result=True,
|
||||
)
|
||||
@@ -125,7 +125,7 @@ class DistributedVaeExecutor:
|
||||
|
||||
# 2. local decode
|
||||
assigned = self._balance_tasks(tiletask_list, pp_size)
|
||||
local_tasks = assigned[self.rank] if pp_size <= self.world_size else []
|
||||
local_tasks = assigned[self.rank] if self.rank < pp_size else []
|
||||
local_results = [(t.tile_id, operator.exec(t)) for t in local_tasks]
|
||||
|
||||
# 3. compute shape per rank
|
||||
|
||||
@@ -10,5 +10,7 @@ from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
def get_local_device() -> torch.device:
|
||||
"""Return the torch device for the current rank based on detected device type."""
|
||||
if current_omni_platform.is_initialized():
|
||||
return current_omni_platform.get_torch_device(current_omni_platform.current_device())
|
||||
local_rank = int(os.environ.get("LOCAL_RANK", 0))
|
||||
return current_omni_platform.get_torch_device(local_rank)
|
||||
@@ -60,11 +60,11 @@ class BackgroundResources:
|
||||
for proc in self.processes:
|
||||
if not proc.is_alive():
|
||||
continue
|
||||
proc.join(30)
|
||||
proc.join(5)
|
||||
if proc.is_alive():
|
||||
logger.warning("Terminating diffusion worker %s after timeout", proc.name)
|
||||
proc.terminate()
|
||||
proc.join(30)
|
||||
proc.join(5)
|
||||
|
||||
|
||||
class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
@@ -311,7 +311,7 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
raise RuntimeError(f"Unexpected response type for execute_request: {type(result)!r}")
|
||||
|
||||
return RunnerOutput(
|
||||
req_id=new_req.sched_req_id,
|
||||
request_id=new_req.request_id,
|
||||
step_index=None,
|
||||
finished=True,
|
||||
result=result,
|
||||
@@ -334,9 +334,9 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
# TODO: Remove this fallback; DiffusionOutput cannot faithfully represent
|
||||
# failed multi-request step batches.
|
||||
if isinstance(result, DiffusionOutput):
|
||||
req_id = scheduler_output.scheduled_req_ids[0] if scheduler_output.scheduled_req_ids else ""
|
||||
request_id = scheduler_output.scheduled_request_ids[0] if scheduler_output.scheduled_request_ids else ""
|
||||
return RunnerOutput(
|
||||
req_id=req_id,
|
||||
request_id=request_id,
|
||||
step_index=None,
|
||||
finished=True,
|
||||
result=result,
|
||||
|
||||
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import vllm.ir
|
||||
from vllm.config import VllmConfig
|
||||
@@ -11,6 +12,9 @@ from vllm_omni.diffusion.attention.backends.abstract import (
|
||||
)
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import torch
|
||||
|
||||
|
||||
@dataclass
|
||||
class ForwardContext:
|
||||
@@ -23,6 +27,8 @@ class ForwardContext:
|
||||
attn_metadata: dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None = None
|
||||
split_text_embed_in_sp: bool = False
|
||||
denoise_step_idx: int | None = None
|
||||
# Per-request reference latent for img2img DiT models (e.g. Ming)
|
||||
ref_latent: torch.Tensor | None = None
|
||||
# whether to split the text embed in sequence parallel, if True, the text embed will be split in sequence parallel
|
||||
|
||||
# Sequence Parallel padding support
|
||||
@@ -171,3 +177,14 @@ def set_forward_context_denoise_step_idx(step_idx: int | None) -> None:
|
||||
"""Set the current diffusion denoise step on the active ForwardContext."""
|
||||
if _forward_context is not None:
|
||||
_forward_context.denoise_step_idx = step_idx
|
||||
|
||||
|
||||
def set_forward_context_ref_latent(ref_latent: torch.Tensor | None) -> None:
|
||||
"""Set the per-request reference latent on the active ForwardContext.
|
||||
|
||||
Used by img2img-capable DiT models (e.g. Ming-flash-omni-2.0) so the
|
||||
transformer can read the reference latent from request scope instead of
|
||||
module instance state.
|
||||
"""
|
||||
if _forward_context is not None:
|
||||
_forward_context.ref_latent = ref_latent
|
||||
@@ -15,6 +15,9 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class BaseState:
|
||||
@@ -27,17 +30,24 @@ class BaseState:
|
||||
class StateManager:
|
||||
"""Manage per-context hook state instances."""
|
||||
|
||||
def __init__(self, state_cls: Callable[[], BaseState]):
|
||||
def __init__(self, state_cls: Callable[[], BaseState], init_args: tuple = (), init_kwargs: dict | None = None):
|
||||
self._state_cls = state_cls
|
||||
self._init_args = init_args
|
||||
self._init_kwargs = init_kwargs or {}
|
||||
self._states: dict[str, BaseState] = {}
|
||||
self._context: str = "default"
|
||||
|
||||
@property
|
||||
def _current_context(self) -> str | None:
|
||||
"""Alias for _context for compatibility with diffusers hook code."""
|
||||
return self._context if self._context != "default" else None
|
||||
|
||||
def set_context(self, name: str) -> None:
|
||||
self._context = name or "default"
|
||||
|
||||
def get_state(self) -> BaseState:
|
||||
if self._context not in self._states:
|
||||
self._states[self._context] = self._state_cls()
|
||||
self._states[self._context] = self._state_cls(*self._init_args, **self._init_kwargs)
|
||||
return self._states[self._context]
|
||||
|
||||
def reset(self) -> None:
|
||||
@@ -190,6 +200,22 @@ class HookRegistry:
|
||||
|
||||
return registry
|
||||
|
||||
@classmethod
|
||||
def check_if_exists_or_initialize(cls, module: nn.Module) -> HookRegistry:
|
||||
"""Get existing registry or create a new one for the module.
|
||||
|
||||
This method ensures a HookRegistry exists on the module and returns it.
|
||||
If a registry doesn't exist, it creates one and attaches it to the module.
|
||||
This is equivalent to get_or_create() for compatibility with diffusers API.
|
||||
|
||||
Args:
|
||||
module: The module to get/create a registry for.
|
||||
|
||||
Returns:
|
||||
The HookRegistry for this module.
|
||||
"""
|
||||
return cls.get_or_create(module)
|
||||
|
||||
def update_sorted_hooks(self):
|
||||
"""Sort hooks by name, which dictates pre/post process order."""
|
||||
sorted_hooks = [self._hooks[k] for k in sorted(self._hooks) if self._hooks[k] != self._new_fwd_impl_hook]
|
||||
@@ -205,7 +231,23 @@ class HookRegistry:
|
||||
name: Unique name for this hook.
|
||||
hook: The hook instance to register.
|
||||
"""
|
||||
if name in self._hooks:
|
||||
logger.warning(f"Hook with name '{name}' already exists. Overwriting existing hook.")
|
||||
self.remove_hook(name)
|
||||
|
||||
hook.initialize_hook(self.module)
|
||||
|
||||
if hasattr(hook, "fn_ref"):
|
||||
hook.fn_ref.original_forward = self.module._omni_original_forward
|
||||
else:
|
||||
original_forward = self.module._omni_original_forward # type: ignore[attr-defined]
|
||||
|
||||
class _FnRef:
|
||||
def __init__(self, orig_forward):
|
||||
self.original_forward = orig_forward
|
||||
|
||||
hook.fn_ref = _FnRef(original_forward)
|
||||
|
||||
self._hooks[name] = hook
|
||||
# We can only have one hook that overrides new_forward,
|
||||
# since we don't currently have a mechanism for combining them.
|
||||
@@ -290,3 +332,17 @@ class HookRegistry:
|
||||
hook = self._hooks.get(name)
|
||||
if hook is not None:
|
||||
hook.reset_state(self.module)
|
||||
|
||||
def reset(self) -> None:
|
||||
"""Reset all hooks and clear the registry.
|
||||
|
||||
This removes all hooks from the registry and resets each hook's state.
|
||||
Also restores module.forward to its original implementation.
|
||||
"""
|
||||
for name, hook in list(self._hooks.items()):
|
||||
hook.reset_state(self.module)
|
||||
self._hooks.clear()
|
||||
|
||||
if hasattr(self.module, "_omni_original_forward"):
|
||||
self.module.forward = self.module._omni_original_forward # type: ignore[attr-defined]
|
||||
delattr(self.module, "_omni_original_forward")
|
||||
@@ -128,7 +128,6 @@ class InlineStageDiffusionClient(StageClientBase):
|
||||
request = OmniDiffusionRequest(
|
||||
prompts=[prompt],
|
||||
sampling_params=sampling_params,
|
||||
request_ids=[request_id],
|
||||
request_id=request_id,
|
||||
kv_sender_info=kv_sender_info,
|
||||
)
|
||||
@@ -187,7 +186,6 @@ class InlineStageDiffusionClient(StageClientBase):
|
||||
request = OmniDiffusionRequest(
|
||||
prompts=prompts,
|
||||
sampling_params=sampling_params,
|
||||
request_ids=[f"{request_id}-{i}" for i in range(len(prompts))],
|
||||
request_id=request_id,
|
||||
kv_sender_info=kv_sender_info,
|
||||
)
|
||||
|
||||
@@ -94,10 +94,18 @@ class RotaryEmbedding(CustomOp):
|
||||
self.interleaved = not is_neox_style
|
||||
self.apply_rotary_emb_flash_attn = None
|
||||
self.has_mindie = False
|
||||
# ``find_spec("flash_attn")`` is True as long as *any* package publishes
|
||||
# the ``flash_attn`` namespace — including ``flash-attn-4``, which ships
|
||||
# only ``flash_attn.cute`` and no ``flash_attn.ops``. Guard the import
|
||||
# so a partial namespace doesn't crash the RoPE init; the CUDA forward
|
||||
# path uses ``vllm.vllm_flash_attn.layers.rotary`` anyway.
|
||||
if find_spec("flash_attn") is not None:
|
||||
from flash_attn.ops.triton.rotary import apply_rotary
|
||||
try:
|
||||
from flash_attn.ops.triton.rotary import apply_rotary
|
||||
|
||||
self.apply_rotary_emb_flash_attn = apply_rotary
|
||||
self.apply_rotary_emb_flash_attn = apply_rotary
|
||||
except ImportError:
|
||||
pass
|
||||
if find_spec("mindiesd") is not None:
|
||||
self.has_mindie = True
|
||||
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from torch import nn
|
||||
|
||||
from .modelopt import ModelOptFp8CheckpointAdapter
|
||||
from .modelopt import (
|
||||
ModelOptFp8CheckpointAdapter,
|
||||
ModelOptMixedPrecisionCheckpointAdapter,
|
||||
ModelOptNvFp4CheckpointAdapter,
|
||||
)
|
||||
|
||||
|
||||
def get_checkpoint_adapter(
|
||||
@@ -10,13 +14,19 @@ def get_checkpoint_adapter(
|
||||
source: object,
|
||||
quant_config: object | None,
|
||||
use_safetensors: bool,
|
||||
) -> ModelOptFp8CheckpointAdapter | None:
|
||||
) -> ModelOptFp8CheckpointAdapter | ModelOptNvFp4CheckpointAdapter | ModelOptMixedPrecisionCheckpointAdapter | None:
|
||||
if ModelOptFp8CheckpointAdapter.is_compatible(source, quant_config, use_safetensors):
|
||||
return ModelOptFp8CheckpointAdapter(model, source)
|
||||
if ModelOptNvFp4CheckpointAdapter.is_compatible(source, quant_config, use_safetensors):
|
||||
return ModelOptNvFp4CheckpointAdapter(model, source)
|
||||
if ModelOptMixedPrecisionCheckpointAdapter.is_compatible(source, quant_config, use_safetensors):
|
||||
return ModelOptMixedPrecisionCheckpointAdapter(model, source)
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ModelOptFp8CheckpointAdapter",
|
||||
"ModelOptMixedPrecisionCheckpointAdapter",
|
||||
"ModelOptNvFp4CheckpointAdapter",
|
||||
"get_checkpoint_adapter",
|
||||
]
|
||||
@@ -11,7 +11,7 @@ from vllm.model_executor.utils import get_packed_modules_mapping
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
MODEL_OPT_SCALE_SUFFIXES = (".input_scale", ".weight_scale", ".weight_scale_inv")
|
||||
MODEL_OPT_SCALE_SUFFIXES = (".input_scale", ".weight_scale", ".weight_scale_2", ".weight_scale_inv")
|
||||
DEFAULT_PACKED_MODULES_MAPPING = {
|
||||
"to_qkv": ("to_q", "to_k", "to_v"),
|
||||
"add_kv_proj": ("add_q_proj", "add_k_proj", "add_v_proj"),
|
||||
@@ -249,3 +249,24 @@ class ModelOptFp8CheckpointAdapter:
|
||||
|
||||
self._check_pending_weights(state)
|
||||
self._log_adaptation_summary(state)
|
||||
|
||||
|
||||
class ModelOptNvFp4CheckpointAdapter(ModelOptFp8CheckpointAdapter):
|
||||
@staticmethod
|
||||
def _is_checkpoint_quant_config(quant_config: object | None) -> bool:
|
||||
return (
|
||||
quant_config is not None
|
||||
and hasattr(quant_config, "get_name")
|
||||
and quant_config.get_name() == "modelopt_fp4"
|
||||
and bool(getattr(quant_config, "is_checkpoint_nvfp4_serialized", False))
|
||||
)
|
||||
|
||||
|
||||
class ModelOptMixedPrecisionCheckpointAdapter(ModelOptFp8CheckpointAdapter):
|
||||
@staticmethod
|
||||
def _is_checkpoint_quant_config(quant_config: object | None) -> bool:
|
||||
return (
|
||||
quant_config is not None
|
||||
and hasattr(quant_config, "get_name")
|
||||
and quant_config.get_name() == "modelopt_mixed"
|
||||
)
|
||||
@@ -55,6 +55,23 @@ TRANSFORMER_WEIGHTS_INDEX = "model.safetensors.index.json"
|
||||
INDEX_FILES = [DIFFUSION_MODEL_WEIGHTS_INDEX, TRANSFORMER_WEIGHTS_INDEX]
|
||||
|
||||
|
||||
def _resolve_custom_pipeline_cls(custom_pipeline_name: str | type | None) -> type:
|
||||
"""Resolve a custom pipeline reference to a class.
|
||||
|
||||
Accepts either a fully qualified name string (resolved via import) or an
|
||||
already-imported class object (returned as-is).
|
||||
"""
|
||||
if custom_pipeline_name is None:
|
||||
raise ValueError("custom_pipeline_name is required for load_format='custom_pipeline'")
|
||||
if isinstance(custom_pipeline_name, str):
|
||||
return resolve_obj_by_qualname(custom_pipeline_name)
|
||||
if isinstance(custom_pipeline_name, type):
|
||||
return custom_pipeline_name
|
||||
raise TypeError(
|
||||
f"custom_pipeline_name must be a qualified name string or a class, got {type(custom_pipeline_name).__name__}"
|
||||
)
|
||||
|
||||
|
||||
class DiffusersPipelineLoader:
|
||||
"""Model loader that can load diffusers pipeline components from disk."""
|
||||
|
||||
@@ -294,17 +311,32 @@ class DiffusersPipelineLoader:
|
||||
od_config: OmniDiffusionConfig,
|
||||
load_device: str,
|
||||
load_format: str | None = "default",
|
||||
custom_pipeline_name: str | None = None,
|
||||
custom_pipeline_name: str | type[nn.Module] | None = None,
|
||||
device: torch.device | None = None,
|
||||
) -> nn.Module:
|
||||
"""Load a model with the given configurations."""
|
||||
if load_format is None:
|
||||
load_format = "default"
|
||||
self.od_config = od_config
|
||||
# CPU offload + FP8: load weights on device for FP8 quantization
|
||||
# CPU offload + quantization: for offline-quantized models (e.g., AutoRound MXFP8),
|
||||
# weights are already quantized in the checkpoint — load directly on CPU.
|
||||
# For online quantization, load on device so quantization can run on accelerator,
|
||||
# then move back to CPU afterward.
|
||||
offload_after_quant = False
|
||||
if load_device == "cpu" and od_config.quantization_config is not None:
|
||||
load_device = device.type
|
||||
logger.info(f"Quantization enabled with CPU offload, using {load_device} for weight loading")
|
||||
quant_cfg = od_config.quantization_config
|
||||
is_offline = getattr(quant_cfg, "data_type", None) == "mx_fp" or getattr(
|
||||
quant_cfg, "is_checkpoint_quantized", False
|
||||
)
|
||||
if not is_offline:
|
||||
load_device = device.type
|
||||
offload_after_quant = True
|
||||
logger.info(
|
||||
"Online quantization with CPU offload, using %s for weight loading (will offload back to CPU)",
|
||||
load_device,
|
||||
)
|
||||
else:
|
||||
logger.info("Offline-quantized model with CPU offload, loading weights directly on CPU")
|
||||
|
||||
target_device = torch.device(load_device)
|
||||
with set_default_torch_dtype(od_config.dtype):
|
||||
@@ -313,19 +345,34 @@ class DiffusersPipelineLoader:
|
||||
od_config, target_device=device, load_format=load_format, custom_pipeline_name=custom_pipeline_name
|
||||
)
|
||||
else:
|
||||
with target_device:
|
||||
if load_format == "default":
|
||||
model = initialize_model(od_config)
|
||||
elif load_format == "diffusers":
|
||||
model = DiffusersAdapterPipeline(od_config=od_config, device=target_device)
|
||||
elif load_format == "custom_pipeline":
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
if load_format == "custom_pipeline":
|
||||
# NOTE: Custom pipelines call HuggingFace `from_pretrained(...).to(device)`
|
||||
# internally. If we construct them under `with target_device:` (CUDA),
|
||||
# safetensors takes a direct-to-GPU fast path that calls `cudaMalloc`
|
||||
# via the driver API and BYPASSES PyTorch's caching allocator.
|
||||
# That makes those bytes invisible to CuMemAllocator, so `sleep()`
|
||||
# cannot offload/unmap them and GPU memory stays pinned.
|
||||
#
|
||||
# Fix: build the custom pipeline on CPU first (no default device
|
||||
# context), then explicitly move it to the target device. The
|
||||
# subsequent `.to(target_device)` issues `torch.empty(..., device=cuda)`
|
||||
# + `copy_`, which goes through the caching allocator and is fully
|
||||
# tracked by CuMemAllocator.
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
|
||||
model_cls = resolve_obj_by_qualname(custom_pipeline_name)
|
||||
with set_current_diffusion_config(od_config):
|
||||
model = model_cls(od_config=od_config)
|
||||
else:
|
||||
raise ValueError(f"Unknown load_format: {load_format}")
|
||||
model_cls = _resolve_custom_pipeline_cls(custom_pipeline_name)
|
||||
with set_current_diffusion_config(od_config):
|
||||
model = model_cls(od_config=od_config)
|
||||
if target_device.type != "cpu":
|
||||
model.to(target_device)
|
||||
else:
|
||||
with target_device:
|
||||
if load_format == "default":
|
||||
model = initialize_model(od_config)
|
||||
elif load_format == "diffusers":
|
||||
model = DiffusersAdapterPipeline(od_config=od_config, device=target_device)
|
||||
else:
|
||||
raise ValueError(f"Unknown load_format: {load_format}")
|
||||
logger.debug("Loading weights on %s ...", load_device)
|
||||
if load_format == "diffusers":
|
||||
# DiffusersAdapterPipeline.load_weights() calls
|
||||
@@ -342,6 +389,10 @@ class DiffusersPipelineLoader:
|
||||
# This is needed for vLLM's quantization methods that need to transform weights
|
||||
self._process_weights_after_loading(model, target_device)
|
||||
|
||||
if offload_after_quant:
|
||||
model.to("cpu")
|
||||
logger.info("Quantization complete, offloaded model back to CPU")
|
||||
|
||||
return model.eval()
|
||||
|
||||
def _process_weights_after_loading(self, model: nn.Module, target_device: torch.device) -> None:
|
||||
@@ -563,7 +614,7 @@ class DiffusersPipelineLoader:
|
||||
od_config: OmniDiffusionConfig,
|
||||
target_device: torch.device,
|
||||
load_format: str = "default",
|
||||
custom_pipeline_name: str | None = None,
|
||||
custom_pipeline_name: str | type[nn.Module] | None = None,
|
||||
) -> nn.Module:
|
||||
"""Load model with HSDP sharding for inference.
|
||||
|
||||
@@ -591,9 +642,9 @@ class DiffusersPipelineLoader:
|
||||
if load_format == "default":
|
||||
model = initialize_model(od_config)
|
||||
elif load_format == "custom_pipeline":
|
||||
model_cls = _resolve_custom_pipeline_cls(custom_pipeline_name)
|
||||
from vllm_omni.diffusion.config import set_current_diffusion_config
|
||||
|
||||
model_cls = resolve_obj_by_qualname(custom_pipeline_name)
|
||||
with set_current_diffusion_config(od_config):
|
||||
model = model_cls(od_config=od_config)
|
||||
self.load_weights(model)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -793,13 +793,7 @@ class BagelPipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipelineProf
|
||||
cfg_renorm_type=gen_params.cfg_renorm_type,
|
||||
**generation_input,
|
||||
cfg_text_packed_position_ids=generation_input_cfg_text["cfg_packed_position_ids"],
|
||||
cfg_text_packed_query_indexes=generation_input_cfg_text["cfg_packed_query_indexes"],
|
||||
cfg_text_key_values_lens=generation_input_cfg_text["cfg_key_values_lens"],
|
||||
cfg_text_packed_key_value_indexes=generation_input_cfg_text["cfg_packed_key_value_indexes"],
|
||||
cfg_img_packed_position_ids=generation_input_cfg_img["cfg_packed_position_ids"],
|
||||
cfg_img_packed_query_indexes=generation_input_cfg_img["cfg_packed_query_indexes"],
|
||||
cfg_img_key_values_lens=generation_input_cfg_img["cfg_key_values_lens"],
|
||||
cfg_img_packed_key_value_indexes=generation_input_cfg_img["cfg_packed_key_value_indexes"],
|
||||
return_trajectory_latents=req.sampling_params.return_trajectory_latents,
|
||||
scheduler=self.scheduler,
|
||||
scheduler_kwargs=self.scheduler_kwargs,
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.distributed import get_tensor_model_parallel_world_size
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.linear import ColumnParallelLinear
|
||||
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
|
||||
try:
|
||||
from dreamid_omni.modules.model import WanLayerNorm, WanRMSNorm
|
||||
from dreamid_omni.modules.model import WanLayerNorm
|
||||
except ImportError:
|
||||
raise ImportError("Failed to import from dependency 'dreamid_omni'.")
|
||||
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.models.dreamid_omni.wan2_2 import WanModel, rope_apply
|
||||
from vllm_omni.diffusion.models.dreamid_omni.wan2_2 import (
|
||||
DistributedRMSNorm,
|
||||
WanModel,
|
||||
rope_apply,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -128,8 +138,8 @@ class FusedBlock(nn.Module):
|
||||
|
||||
def forward(
|
||||
self,
|
||||
vid,
|
||||
audio,
|
||||
hidden_states,
|
||||
encoder_hidden_states,
|
||||
attn: Attention,
|
||||
vid_e,
|
||||
vid_seq_lens,
|
||||
@@ -148,6 +158,8 @@ class FusedBlock(nn.Module):
|
||||
audio_ref_lengths,
|
||||
audio_freqs_scaling,
|
||||
):
|
||||
vid = hidden_states
|
||||
audio = encoder_hidden_states
|
||||
vid_block = self.vid_block
|
||||
audio_block = self.audio_block
|
||||
|
||||
@@ -241,26 +253,36 @@ class FusedBlock(nn.Module):
|
||||
class FusionModel(nn.Module):
|
||||
_layerwise_offload_blocks_attrs = ["fused_blocks"]
|
||||
|
||||
packed_modules_mapping = {
|
||||
"to_qkv": ["q", "k", "v"],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _is_fused_block(name: str, module) -> bool:
|
||||
return "fused_blocks" in name and name.split(".")[-1].isdigit()
|
||||
|
||||
_hsdp_shard_conditions = [_is_fused_block]
|
||||
|
||||
def __init__(self, video_config=None, audio_config=None):
|
||||
def __init__(
|
||||
self,
|
||||
video_config=None,
|
||||
audio_config=None,
|
||||
*,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
):
|
||||
super().__init__()
|
||||
has_video = True
|
||||
has_audio = True
|
||||
self.device = get_local_device()
|
||||
if video_config is not None:
|
||||
self.video_model = WanModel(**video_config)
|
||||
self.video_model = WanModel(quant_config=quant_config, prefix="video_model", **video_config)
|
||||
else:
|
||||
has_video = False
|
||||
self.video_model = None
|
||||
logger.warning("No video model is provided!")
|
||||
|
||||
if audio_config is not None:
|
||||
self.audio_model = WanModel(**audio_config)
|
||||
self.audio_model = WanModel(quant_config=quant_config, prefix="audio_model", **audio_config)
|
||||
else:
|
||||
has_audio = False
|
||||
self.audio_model = None
|
||||
@@ -270,11 +292,12 @@ class FusionModel(nn.Module):
|
||||
assert len(self.video_model.blocks) == len(self.audio_model.blocks)
|
||||
self.num_blocks = len(self.video_model.blocks)
|
||||
|
||||
self.inject_cross_attention_kv_projections()
|
||||
self.inject_cross_attention_kv_projections(quant_config=quant_config)
|
||||
|
||||
self.num_heads = self.video_model.num_heads
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.full_num_heads = self.video_model.num_heads
|
||||
self.num_heads = self.full_num_heads // tp_size
|
||||
self.head_dim = self.video_model.dim // self.video_model.num_heads
|
||||
# Make a single shared instance to pass in at forward time
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_heads,
|
||||
head_size=self.head_dim,
|
||||
@@ -313,21 +336,42 @@ class FusionModel(nn.Module):
|
||||
|
||||
return super().load_state_dict(state_dict, strict=strict, assign=assign)
|
||||
|
||||
def inject_cross_attention_kv_projections(self):
|
||||
for vid_block in self.video_model.blocks:
|
||||
vid_block.cross_attn.k_fusion = nn.Linear(vid_block.dim, vid_block.dim)
|
||||
vid_block.cross_attn.v_fusion = nn.Linear(vid_block.dim, vid_block.dim)
|
||||
vid_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(vid_block.dim, elementwise_affine=True)
|
||||
vid_block.cross_attn.norm_k_fusion = (
|
||||
WanRMSNorm(vid_block.dim, eps=1e-6) if vid_block.qk_norm else nn.Identity()
|
||||
def inject_cross_attention_kv_projections(
|
||||
self,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
):
|
||||
def _make_kv_proj(dim: int, prefix: str) -> ColumnParallelLinear:
|
||||
# K/V projections for the cross-modal (a2v / v2a) attention path.
|
||||
# Inputs are full latents, so we quantize matched to self_attn.
|
||||
return ColumnParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=True,
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
for audio_block in self.audio_model.blocks:
|
||||
audio_block.cross_attn.k_fusion = nn.Linear(audio_block.dim, audio_block.dim)
|
||||
audio_block.cross_attn.v_fusion = nn.Linear(audio_block.dim, audio_block.dim)
|
||||
audio_block.cross_attn.pre_attn_norm_fusion = WanLayerNorm(audio_block.dim, elementwise_affine=True)
|
||||
audio_block.cross_attn.norm_k_fusion = (
|
||||
WanRMSNorm(audio_block.dim, eps=1e-6) if audio_block.qk_norm else nn.Identity()
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
for i, vid_block in enumerate(self.video_model.blocks):
|
||||
cross = vid_block.cross_attn
|
||||
block_prefix = f"video_model.blocks.{i}.cross_attn"
|
||||
cross.k_fusion = _make_kv_proj(vid_block.dim, f"{block_prefix}.k_fusion")
|
||||
cross.v_fusion = _make_kv_proj(vid_block.dim, f"{block_prefix}.v_fusion")
|
||||
cross.pre_attn_norm_fusion = WanLayerNorm(vid_block.dim, elementwise_affine=True)
|
||||
cross.norm_k_fusion = (
|
||||
DistributedRMSNorm(vid_block.dim // tp_size, eps=1e-6) if vid_block.qk_norm else nn.Identity()
|
||||
)
|
||||
|
||||
for i, audio_block in enumerate(self.audio_model.blocks):
|
||||
cross = audio_block.cross_attn
|
||||
block_prefix = f"audio_model.blocks.{i}.cross_attn"
|
||||
cross.k_fusion = _make_kv_proj(audio_block.dim, f"{block_prefix}.k_fusion")
|
||||
cross.v_fusion = _make_kv_proj(audio_block.dim, f"{block_prefix}.v_fusion")
|
||||
cross.pre_attn_norm_fusion = WanLayerNorm(audio_block.dim, elementwise_affine=True)
|
||||
cross.norm_k_fusion = (
|
||||
DistributedRMSNorm(audio_block.dim // tp_size, eps=1e-6) if audio_block.qk_norm else nn.Identity()
|
||||
)
|
||||
|
||||
def _detach_blocks_from_backbones(self) -> None:
|
||||
|
||||
@@ -13,6 +13,11 @@ from PIL import Image, ImageOps
|
||||
from torch import nn
|
||||
from torchvision.transforms import Compose, Normalize
|
||||
from tqdm import tqdm
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_rank,
|
||||
get_tensor_model_parallel_world_size,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
@@ -124,7 +129,8 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
|
||||
self.text_encoder = self.text_model.model
|
||||
|
||||
# Fusion model — weights are loaded later via load_weights()
|
||||
self.model = FusionModel(VIDEO_CONFIG, AUDIO_CONFIG)
|
||||
quant_config = getattr(self.od_config, "quantization_config", None)
|
||||
self.model = FusionModel(VIDEO_CONFIG, AUDIO_CONFIG, quant_config=quant_config)
|
||||
self.transformer = self.model
|
||||
|
||||
fusion_path = self.od_config.tf_model_config.get("fusion", None)
|
||||
@@ -236,10 +242,75 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
|
||||
return ref_vae_latents, ref_audio_lengths
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
prefix = "model."
|
||||
state_dict = {name[len(prefix) :]: tensor for name, tensor in weights if name.startswith(prefix)}
|
||||
self.model.load_state_dict(state_dict, strict=True)
|
||||
return {prefix + k for k in state_dict}
|
||||
pipeline_prefix = "model."
|
||||
|
||||
qkv_stacked_mapping = [
|
||||
(".self_attn.to_qkv", ".self_attn.q", "q"),
|
||||
(".self_attn.to_qkv", ".self_attn.k", "k"),
|
||||
(".self_attn.to_qkv", ".self_attn.v", "v"),
|
||||
]
|
||||
|
||||
params_dict = dict(self.model.named_parameters())
|
||||
loaded_local: set[str] = set()
|
||||
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
tp_rank = get_tensor_model_parallel_rank() if tp_size > 1 else 0
|
||||
|
||||
def _maybe_shard_weight(weight: torch.Tensor, param: torch.Tensor) -> torch.Tensor:
|
||||
"""Slice a checkpoint tensor to this rank's TP shard when the
|
||||
param is a TP-local shape but the checkpoint stores the full one.
|
||||
"""
|
||||
if tp_size <= 1 or weight.shape == param.shape:
|
||||
return weight
|
||||
if weight.ndim == 1 and weight.numel() == param.numel() * tp_size:
|
||||
return weight.chunk(tp_size, dim=0)[tp_rank]
|
||||
if weight.ndim == 2:
|
||||
if weight.shape[0] == param.shape[0] * tp_size:
|
||||
return weight.chunk(tp_size, dim=0)[tp_rank]
|
||||
if weight.shape[1] == param.shape[1] * tp_size:
|
||||
return weight.chunk(tp_size, dim=1)[tp_rank]
|
||||
return weight
|
||||
|
||||
for full_name, loaded_weight in weights:
|
||||
if not full_name.startswith(pipeline_prefix):
|
||||
continue
|
||||
name = full_name[len(pipeline_prefix) :]
|
||||
|
||||
# Fused-QKV stacking: route checkpoint's separate
|
||||
# - ...self_attn.{q,k,v}: weights into the corresponding
|
||||
# - ...self_attn.to_qkv : via its sharded weight_loader.
|
||||
stacked_hit = False
|
||||
for fused_name, raw_name, shard_id in qkv_stacked_mapping:
|
||||
if raw_name not in name:
|
||||
continue
|
||||
stacked = name.replace(raw_name, fused_name)
|
||||
if stacked not in params_dict:
|
||||
continue
|
||||
param = params_dict[stacked]
|
||||
param.weight_loader(param, loaded_weight, shard_id)
|
||||
loaded_local.add(stacked)
|
||||
stacked_hit = True
|
||||
break
|
||||
if stacked_hit:
|
||||
continue
|
||||
|
||||
if name not in params_dict:
|
||||
logger.warning(f"Skipping DreamID-Omni weight {full_name} -- not found in model parameters")
|
||||
continue
|
||||
param = params_dict[name]
|
||||
weight_loader = getattr(param, "weight_loader", None)
|
||||
if weight_loader is not None:
|
||||
# Parallel Linears handle TP sharding internally
|
||||
weight_loader(param, loaded_weight)
|
||||
else:
|
||||
default_weight_loader(param, _maybe_shard_weight(loaded_weight, param))
|
||||
loaded_local.add(name)
|
||||
|
||||
# Detach must happen before `DiffusersPipelineLoader._process_weights_after_loading`
|
||||
# and before any forward pass that triggers layerwise-offload hooks.
|
||||
self.model._detach_blocks_from_backbones()
|
||||
|
||||
return {pipeline_prefix + k for k in loaded_local}
|
||||
|
||||
def get_scheduler_time_steps(self, sampling_steps, solver_name="unipc", device=0, shift=5.0):
|
||||
torch.manual_seed(4)
|
||||
@@ -375,6 +446,33 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
|
||||
)[0].squeeze(0)
|
||||
return video_noise, audio_noise
|
||||
|
||||
def encode_prompt(
|
||||
self,
|
||||
prompt: str,
|
||||
video_negative_prompt: str = "",
|
||||
audio_negative_prompt: str = "",
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""Encode the positive and negative prompts via ``self.text_model``.
|
||||
|
||||
This is the single text-encoder entrypoint so that the runner-level
|
||||
prompt-embedding cache (see
|
||||
``vllm_omni/diffusion/cache/prompt_embed_cache.py``) can transparently
|
||||
memoize results when the same prompts are submitted repeatedly (e.g.
|
||||
GRPO rollouts that sample the same prompt with different seeds).
|
||||
|
||||
Returns:
|
||||
(audio_pos, video_pos, video_neg, audio_neg) embeddings cast to
|
||||
``self.target_dtype``. ``audio_pos`` and ``video_pos`` are the
|
||||
same tensor, matching the original inline behavior.
|
||||
"""
|
||||
text_embeddings = self.text_model(
|
||||
[prompt, video_negative_prompt, audio_negative_prompt],
|
||||
device=self.device,
|
||||
)
|
||||
text_embeddings = [emb.to(self.target_dtype) for emb in text_embeddings]
|
||||
# Index 0 is the positive embedding, shared between video and audio branches.
|
||||
return text_embeddings[0], text_embeddings[0], text_embeddings[1], text_embeddings[2]
|
||||
|
||||
def forward(
|
||||
self,
|
||||
request: OmniDiffusionRequest,
|
||||
@@ -432,12 +530,13 @@ class DreamIDOmniPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Suppor
|
||||
)
|
||||
|
||||
# 3. text embedding
|
||||
text_embeddings = self.text_model([prompt, video_negative_prompt, audio_negative_prompt], device=self.device)
|
||||
text_embeddings = [emb.to(self.target_dtype) for emb in text_embeddings]
|
||||
text_embeddings_audio_pos = text_embeddings[0]
|
||||
text_embeddings_video_pos = text_embeddings[0]
|
||||
text_embeddings_video_neg = text_embeddings[1]
|
||||
text_embeddings_audio_neg = text_embeddings[2]
|
||||
text_embeddings_audio_pos, text_embeddings_video_pos, text_embeddings_video_neg, text_embeddings_audio_neg = (
|
||||
self.encode_prompt(
|
||||
prompt=prompt,
|
||||
video_negative_prompt=video_negative_prompt,
|
||||
audio_negative_prompt=audio_negative_prompt,
|
||||
)
|
||||
)
|
||||
|
||||
video_latent_h, video_latent_w = height // 16, width // 16
|
||||
|
||||
|
||||
@@ -6,6 +6,16 @@ import torch.amp as amp
|
||||
import torch.nn as nn
|
||||
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
||||
from diffusers.models.modeling_utils import ModelMixin
|
||||
from vllm.distributed import (
|
||||
get_tensor_model_parallel_world_size,
|
||||
tensor_model_parallel_all_reduce,
|
||||
)
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
|
||||
@@ -17,7 +27,6 @@ try:
|
||||
MLPProj,
|
||||
ModulationAdd,
|
||||
WanLayerNorm,
|
||||
WanRMSNorm,
|
||||
rope_apply, # diff from wan2.2
|
||||
rope_params,
|
||||
sinusoidal_embedding_1d,
|
||||
@@ -26,42 +35,99 @@ except ImportError:
|
||||
raise ImportError("Failed to import from dependency 'dreamid_omni'.")
|
||||
|
||||
|
||||
class DistributedRMSNorm(nn.Module):
|
||||
"""RMSNorm that computes global RMS across tensor parallel ranks.
|
||||
|
||||
Mirrors `vllm_omni/diffusion/models/wan2_2/wan2_2_transformer.py::DistributedRMSNorm`
|
||||
"""
|
||||
|
||||
def __init__(self, hidden_size: int, eps: float = 1e-6):
|
||||
super().__init__()
|
||||
self.eps = eps
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size))
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
x_dtype = x.dtype
|
||||
x_float = x.float()
|
||||
local_sum_sq = x_float.pow(2).sum(dim=-1, keepdim=True)
|
||||
local_count = x.shape[-1]
|
||||
|
||||
if tp_size > 1:
|
||||
local_sum_sq = tensor_model_parallel_all_reduce(local_sum_sq)
|
||||
local_count = local_count * tp_size
|
||||
|
||||
rms = torch.sqrt(local_sum_sq / local_count + self.eps)
|
||||
return (x_float / rms * self.weight.float()).to(x_dtype)
|
||||
|
||||
|
||||
class WanSelfAttention(nn.Module):
|
||||
"""Optimized self-attention module using vLLM layers."""
|
||||
|
||||
def __init__(self, dim, num_heads, window_size=(-1, -1), qk_norm=True, eps=1e-6):
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
num_heads,
|
||||
window_size=(-1, -1),
|
||||
qk_norm=True,
|
||||
eps=1e-6,
|
||||
*,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
assert dim % num_heads == 0
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.num_heads = num_heads
|
||||
self.head_dim = dim // num_heads
|
||||
self.window_size = window_size
|
||||
self.qk_norm = qk_norm
|
||||
self.eps = eps
|
||||
|
||||
# layers
|
||||
self.q = nn.Linear(dim, dim)
|
||||
self.k = nn.Linear(dim, dim)
|
||||
self.v = nn.Linear(dim, dim)
|
||||
self.o = nn.Linear(dim, dim)
|
||||
self.norm_q = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
|
||||
self.norm_k = WanRMSNorm(dim, eps=eps) if qk_norm else nn.Identity()
|
||||
self.to_qkv = QKVParallelLinear(
|
||||
hidden_size=dim,
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=num_heads,
|
||||
bias=True,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.to_qkv" if prefix else "to_qkv",
|
||||
)
|
||||
self.num_heads = self.to_qkv.num_heads
|
||||
self.num_kv_heads = self.to_qkv.num_kv_heads
|
||||
self.tp_inner_dim = self.num_heads * self.head_dim
|
||||
self.tp_kv_dim = self.num_kv_heads * self.head_dim
|
||||
|
||||
self.o = RowParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=True,
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.o" if prefix else "o",
|
||||
)
|
||||
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps) if qk_norm else nn.Identity()
|
||||
self.norm_k = DistributedRMSNorm(self.tp_kv_dim, eps=eps) if qk_norm else nn.Identity()
|
||||
# Unified attention layer
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_heads,
|
||||
head_size=self.head_dim,
|
||||
num_kv_heads=self.num_heads,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
softmax_scale=1.0 / (self.head_dim**0.5),
|
||||
causal=False,
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
# query, key, value function
|
||||
def qkv_fn(self, x):
|
||||
b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
|
||||
b, s = x.shape[:2]
|
||||
qkv, _ = self.to_qkv(x)
|
||||
q_size = self.num_heads * self.head_dim
|
||||
kv_size = self.num_kv_heads * self.head_dim
|
||||
q, k, v = qkv.split([q_size, kv_size, kv_size], dim=-1)
|
||||
|
||||
q = self.norm_q(self.q(x)).view(b, s, n, d)
|
||||
k = self.norm_k(self.k(x)).view(b, s, n, d)
|
||||
v = self.v(x).view(b, s, n, d)
|
||||
q = self.norm_q(q).view(b, s, self.num_heads, self.head_dim)
|
||||
k = self.norm_k(k).view(b, s, self.num_kv_heads, self.head_dim)
|
||||
v = v.view(b, s, self.num_kv_heads, self.head_dim)
|
||||
return q, k, v
|
||||
|
||||
def forward(self, x, seq_lens, grid_sizes, freqs, ref_lengths=None, freqs_scaling=None):
|
||||
@@ -87,14 +153,97 @@ class WanSelfAttention(nn.Module):
|
||||
return x
|
||||
|
||||
|
||||
class WanT2VCrossAttention(WanSelfAttention):
|
||||
def qkv_fn(self, x, context):
|
||||
b, n, d = x.size(0), self.num_heads, self.head_dim
|
||||
class WanT2VCrossAttention(nn.Module):
|
||||
"""Text -> latent cross-attention."""
|
||||
|
||||
# compute query, key, value
|
||||
q = self.norm_q(self.q(x)).view(b, -1, n, d)
|
||||
k = self.norm_k(self.k(context)).view(b, -1, n, d)
|
||||
v = self.v(context).view(b, -1, n, d)
|
||||
def __init__(
|
||||
self,
|
||||
dim,
|
||||
num_heads,
|
||||
window_size=(-1, -1),
|
||||
qk_norm=True,
|
||||
eps=1e-6,
|
||||
*,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
assert dim % num_heads == 0
|
||||
self.dim = dim
|
||||
self.head_dim = dim // num_heads
|
||||
self.window_size = window_size
|
||||
self.qk_norm = qk_norm
|
||||
self.eps = eps
|
||||
|
||||
# Separate Q/K/V — Q's input differs from K/V's input (text context)
|
||||
self.q = ColumnParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=True,
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.q" if prefix else "q",
|
||||
)
|
||||
self.k = ColumnParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=True,
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.k" if prefix else "k",
|
||||
)
|
||||
self.v = ColumnParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=True,
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.v" if prefix else "v",
|
||||
)
|
||||
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
self.num_heads = num_heads // tp_size
|
||||
self.num_kv_heads = self.num_heads
|
||||
self.tp_inner_dim = self.num_heads * self.head_dim
|
||||
|
||||
self.norm_q = DistributedRMSNorm(self.tp_inner_dim, eps=eps) if qk_norm else nn.Identity()
|
||||
self.norm_k = DistributedRMSNorm(self.tp_inner_dim, eps=eps) if qk_norm else nn.Identity()
|
||||
|
||||
self.o = RowParallelLinear(
|
||||
dim,
|
||||
dim,
|
||||
bias=True,
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.o" if prefix else "o",
|
||||
)
|
||||
|
||||
# Kept for interface parity with WanSelfAttention;
|
||||
# the active cross-attention path in DreamID-Omni uses the shared FusionModel.attn.
|
||||
# Disable kv quant to prevent affecting quality.
|
||||
self.attn = Attention(
|
||||
num_heads=self.num_heads,
|
||||
head_size=self.head_dim,
|
||||
num_kv_heads=self.num_kv_heads,
|
||||
softmax_scale=1.0 / (self.head_dim**0.5),
|
||||
causal=False,
|
||||
prefix=prefix,
|
||||
disable_kv_quant=True,
|
||||
)
|
||||
|
||||
def qkv_fn(self, x, context):
|
||||
b = x.size(0)
|
||||
|
||||
q = self.q(x)
|
||||
k = self.k(context)
|
||||
v = self.v(context)
|
||||
q = self.norm_q(q).view(b, -1, self.num_heads, self.head_dim)
|
||||
k = self.norm_k(k).view(b, -1, self.num_kv_heads, self.head_dim)
|
||||
v = v.view(b, -1, self.num_kv_heads, self.head_dim)
|
||||
|
||||
return q, k, v
|
||||
|
||||
@@ -142,6 +291,9 @@ class WanAttentionBlock(nn.Module):
|
||||
cross_attn_norm=False,
|
||||
eps=1e-6,
|
||||
additional_emb_length=None,
|
||||
*,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
@@ -154,7 +306,15 @@ class WanAttentionBlock(nn.Module):
|
||||
|
||||
# layers
|
||||
self.norm1 = WanLayerNorm(dim, eps)
|
||||
self.self_attn = WanSelfAttention(dim, num_heads, window_size, qk_norm, eps)
|
||||
self.self_attn = WanSelfAttention(
|
||||
dim,
|
||||
num_heads,
|
||||
window_size,
|
||||
qk_norm,
|
||||
eps,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.self_attn" if prefix else "self_attn",
|
||||
)
|
||||
self.norm3 = WanLayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
||||
if cross_attn_type == "i2v_cross_attn":
|
||||
assert additional_emb_length is not None, "additional_emb_length should be specified for i2v_cross_attn"
|
||||
@@ -167,9 +327,32 @@ class WanAttentionBlock(nn.Module):
|
||||
(-1, -1),
|
||||
qk_norm,
|
||||
eps,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.cross_attn" if prefix else "cross_attn",
|
||||
)
|
||||
self.norm2 = WanLayerNorm(dim, eps)
|
||||
self.ffn = nn.Sequential(nn.Linear(dim, ffn_dim), nn.GELU(approximate="tanh"), nn.Linear(ffn_dim, dim))
|
||||
# FFN layout: Stay compatible with upstream DreamID-Omni checkpoints
|
||||
self.ffn = nn.Sequential(
|
||||
ColumnParallelLinear(
|
||||
dim,
|
||||
ffn_dim,
|
||||
bias=True,
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.ffn.0" if prefix else "ffn.0",
|
||||
),
|
||||
nn.GELU(approximate="tanh"),
|
||||
RowParallelLinear(
|
||||
ffn_dim,
|
||||
dim,
|
||||
bias=True,
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.ffn.2" if prefix else "ffn.2",
|
||||
),
|
||||
)
|
||||
|
||||
# modulation
|
||||
self.modulation = ModulationAdd(dim, 6)
|
||||
@@ -243,6 +426,9 @@ class WanModel(ModelMixin, ConfigMixin):
|
||||
cross_attn_norm=True,
|
||||
temporal_rope_scaling_factor=1.0,
|
||||
eps=1e-6,
|
||||
*,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
r"""
|
||||
Initialize the diffusion model backbone.
|
||||
@@ -357,8 +543,10 @@ class WanModel(ModelMixin, ConfigMixin):
|
||||
cross_attn_norm,
|
||||
eps,
|
||||
additional_emb_length,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.blocks.{layer_idx}" if prefix else f"blocks.{layer_idx}",
|
||||
)
|
||||
for _ in range(num_layers)
|
||||
for layer_idx in range(num_layers)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -247,8 +247,10 @@ class ErnieImagePipeline(
|
||||
|
||||
@staticmethod
|
||||
def _is_warmup_request(req: OmniDiffusionRequest) -> bool:
|
||||
request_ids = getattr(req, "request_ids", None) or ()
|
||||
return len(request_ids) == 1 and request_ids[0] == "dummy_req_id"
|
||||
is_dummy_run = getattr(req, "is_dummy_run", None)
|
||||
if callable(is_dummy_run):
|
||||
return bool(is_dummy_run())
|
||||
return OmniDiffusionRequest.is_dummy_run_request_id(getattr(req, "request_id", None))
|
||||
|
||||
@staticmethod
|
||||
def _should_apply_pe(req: OmniDiffusionRequest) -> bool:
|
||||
|
||||
@@ -25,7 +25,13 @@ 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.layers.rope import RotaryEmbedding
|
||||
from vllm_omni.diffusion.data import DiffusionParallelConfig, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
SequenceParallelInput,
|
||||
SequenceParallelOutput,
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding, apply_rope_to_qk
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
@@ -91,6 +97,7 @@ class Flux2FeedForward(nn.Module):
|
||||
class Flux2Attention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
parallel_config: DiffusionParallelConfig,
|
||||
query_dim: int,
|
||||
heads: int = 8,
|
||||
dim_head: int = 64,
|
||||
@@ -106,6 +113,7 @@ class Flux2Attention(nn.Module):
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.parallel_config = parallel_config
|
||||
self.head_dim = dim_head
|
||||
self.inner_dim = out_dim if out_dim is not None else dim_head * heads
|
||||
self.query_dim = query_dim
|
||||
@@ -206,34 +214,82 @@ class Flux2Attention(nn.Module):
|
||||
encoder_query = self.norm_added_q(encoder_query)
|
||||
encoder_key = self.norm_added_k(encoder_key)
|
||||
|
||||
query = torch.cat([encoder_query, query], dim=1)
|
||||
key = torch.cat([encoder_key, key], dim=1)
|
||||
value = torch.cat([encoder_value, value], dim=1)
|
||||
|
||||
if image_rotary_emb is not None:
|
||||
cos, sin = image_rotary_emb
|
||||
cos = cos.to(query.dtype)
|
||||
sin = sin.to(query.dtype)
|
||||
query = self.rope(query, cos, sin)
|
||||
key = self.rope(key, cos, sin)
|
||||
|
||||
attn_metadata = None
|
||||
if attention_mask is not None:
|
||||
if attention_mask.dim() == 3:
|
||||
attention_mask = attention_mask.unsqueeze(1)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
|
||||
|
||||
hidden_states = self.attn(query, key, value, attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
|
||||
|
||||
if encoder_hidden_states is not None:
|
||||
context_len = encoder_hidden_states.shape[1]
|
||||
encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
|
||||
[context_len, hidden_states.shape[1] - context_len],
|
||||
dim=1,
|
||||
sp_size = self.parallel_config.sequence_parallel_size
|
||||
use_sp_joint_attention = (
|
||||
sp_size is not None
|
||||
and sp_size > 1
|
||||
and is_forward_context_available()
|
||||
and not get_forward_context().split_text_embed_in_sp
|
||||
)
|
||||
# Contiguous for FP8 quantization in RowParallelLinear
|
||||
encoder_hidden_states = self.to_add_out(encoder_hidden_states.contiguous())
|
||||
|
||||
if use_sp_joint_attention and image_rotary_emb is not None:
|
||||
cos, sin = image_rotary_emb
|
||||
cos = cos.to(query.dtype)
|
||||
sin = sin.to(query.dtype)
|
||||
txt_len = encoder_query.shape[1]
|
||||
txt_cos, img_cos = cos[:txt_len], cos[txt_len:]
|
||||
txt_sin, img_sin = sin[:txt_len], sin[txt_len:]
|
||||
|
||||
query = self.rope(query, img_cos, img_sin)
|
||||
key = self.rope(key, img_cos, img_sin)
|
||||
encoder_query = self.rope(encoder_query, txt_cos, txt_sin)
|
||||
encoder_key = self.rope(encoder_key, txt_cos, txt_sin)
|
||||
|
||||
attn_metadata = AttentionMetadata(
|
||||
joint_query=encoder_query,
|
||||
joint_key=encoder_key,
|
||||
joint_value=encoder_value,
|
||||
joint_strategy="front",
|
||||
)
|
||||
hidden_states_mask: torch.Tensor | None = kwargs.get("hidden_states_mask", None)
|
||||
encoder_hidden_states_mask: torch.Tensor | None = kwargs.get("encoder_hidden_states_mask", None)
|
||||
if hidden_states_mask is not None:
|
||||
attn_metadata.attn_mask = hidden_states_mask
|
||||
if encoder_hidden_states_mask is not None:
|
||||
attn_metadata.joint_attn_mask = encoder_hidden_states_mask
|
||||
|
||||
hidden_states = self.attn(query, key, value, attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
|
||||
|
||||
txt_len = encoder_hidden_states.shape[1]
|
||||
encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
|
||||
[txt_len, hidden_states.shape[1] - txt_len],
|
||||
dim=1,
|
||||
)
|
||||
encoder_hidden_states = self.to_add_out(encoder_hidden_states.contiguous())
|
||||
else:
|
||||
query = torch.cat([encoder_query, query], dim=1)
|
||||
key = torch.cat([encoder_key, key], dim=1)
|
||||
value = torch.cat([encoder_value, value], dim=1)
|
||||
|
||||
query, key = apply_rope_to_qk(self.rope, query, key, image_rotary_emb)
|
||||
|
||||
attn_metadata = None
|
||||
if attention_mask is not None:
|
||||
if attention_mask.dim() == 3:
|
||||
attention_mask = attention_mask.unsqueeze(1)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
|
||||
|
||||
hidden_states = self.attn(query, key, value, attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
|
||||
|
||||
context_len = encoder_hidden_states.shape[1]
|
||||
encoder_hidden_states, hidden_states = hidden_states.split_with_sizes(
|
||||
[context_len, hidden_states.shape[1] - context_len],
|
||||
dim=1,
|
||||
)
|
||||
encoder_hidden_states = self.to_add_out(encoder_hidden_states.contiguous())
|
||||
else:
|
||||
query, key = apply_rope_to_qk(self.rope, query, key, image_rotary_emb)
|
||||
|
||||
attn_metadata = None
|
||||
if attention_mask is not None:
|
||||
if attention_mask.dim() == 3:
|
||||
attention_mask = attention_mask.unsqueeze(1)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
|
||||
|
||||
hidden_states = self.attn(query, key, value, attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3).to(query.dtype)
|
||||
|
||||
hidden_states = self.to_out[0](hidden_states.contiguous())
|
||||
hidden_states = self.to_out[1](hidden_states)
|
||||
@@ -250,6 +306,7 @@ class Flux2ParallelSelfAttention(nn.Module):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parallel_config: DiffusionParallelConfig,
|
||||
query_dim: int,
|
||||
heads: int = 8,
|
||||
dim_head: int = 64,
|
||||
@@ -265,6 +322,7 @@ class Flux2ParallelSelfAttention(nn.Module):
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.parallel_config = parallel_config
|
||||
self.head_dim = dim_head
|
||||
self.inner_dim = out_dim if out_dim is not None else dim_head * heads
|
||||
self.query_dim = query_dim
|
||||
@@ -327,20 +385,59 @@ class Flux2ParallelSelfAttention(nn.Module):
|
||||
query = self.norm_q(query)
|
||||
key = self.norm_k(key)
|
||||
|
||||
if image_rotary_emb is not None:
|
||||
sp_size = self.parallel_config.sequence_parallel_size
|
||||
text_seq_len = kwargs.get("text_seq_len", None)
|
||||
use_sp_single_stream = (
|
||||
sp_size is not None
|
||||
and sp_size > 1
|
||||
and text_seq_len is not None
|
||||
and is_forward_context_available()
|
||||
and not get_forward_context().split_text_embed_in_sp
|
||||
)
|
||||
|
||||
if use_sp_single_stream and image_rotary_emb is not None:
|
||||
cos, sin = image_rotary_emb
|
||||
cos = cos.to(query.dtype)
|
||||
sin = sin.to(query.dtype)
|
||||
query = self.rope(query, cos, sin)
|
||||
key = self.rope(key, cos, sin)
|
||||
txt_cos, img_cos = cos[:text_seq_len], cos[text_seq_len:]
|
||||
txt_sin, img_sin = sin[:text_seq_len], sin[text_seq_len:]
|
||||
|
||||
attn_metadata = None
|
||||
if attention_mask is not None:
|
||||
if attention_mask.dim() == 3:
|
||||
attention_mask = attention_mask.unsqueeze(1)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
|
||||
img_query = query[:, text_seq_len:]
|
||||
img_key = key[:, text_seq_len:]
|
||||
img_value = value[:, text_seq_len:]
|
||||
text_query = query[:, :text_seq_len]
|
||||
text_key = key[:, :text_seq_len]
|
||||
text_value = value[:, :text_seq_len]
|
||||
|
||||
attn_output = self.attn(query, key, value, attn_metadata)
|
||||
img_query = self.rope(img_query, img_cos, img_sin)
|
||||
img_key = self.rope(img_key, img_cos, img_sin)
|
||||
text_query = self.rope(text_query, txt_cos, txt_sin)
|
||||
text_key = self.rope(text_key, txt_cos, txt_sin)
|
||||
|
||||
attn_metadata = AttentionMetadata(
|
||||
joint_query=text_query,
|
||||
joint_key=text_key,
|
||||
joint_value=text_value,
|
||||
joint_strategy="front",
|
||||
)
|
||||
hidden_states_mask: torch.Tensor | None = kwargs.get("hidden_states_mask", None)
|
||||
encoder_hidden_states_mask: torch.Tensor | None = kwargs.get("encoder_hidden_states_mask", None)
|
||||
if hidden_states_mask is not None:
|
||||
attn_metadata.attn_mask = hidden_states_mask
|
||||
if encoder_hidden_states_mask is not None:
|
||||
attn_metadata.joint_attn_mask = encoder_hidden_states_mask
|
||||
|
||||
attn_output = self.attn(img_query, img_key, img_value, attn_metadata)
|
||||
else:
|
||||
query, key = apply_rope_to_qk(self.rope, query, key, image_rotary_emb)
|
||||
|
||||
attn_metadata = None
|
||||
if attention_mask is not None:
|
||||
if attention_mask.dim() == 3:
|
||||
attention_mask = attention_mask.unsqueeze(1)
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask)
|
||||
|
||||
attn_output = self.attn(query, key, value, attn_metadata)
|
||||
attn_output = attn_output.flatten(2, 3).to(query.dtype)
|
||||
|
||||
mlp_hidden_states = self.mlp_act_fn(mlp_hidden_states)
|
||||
@@ -352,6 +449,7 @@ class Flux2ParallelSelfAttention(nn.Module):
|
||||
class Flux2SingleTransformerBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
parallel_config: DiffusionParallelConfig,
|
||||
dim: int,
|
||||
num_attention_heads: int,
|
||||
attention_head_dim: int,
|
||||
@@ -364,6 +462,7 @@ class Flux2SingleTransformerBlock(nn.Module):
|
||||
super().__init__()
|
||||
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
self.attn = Flux2ParallelSelfAttention(
|
||||
parallel_config=parallel_config,
|
||||
query_dim=dim,
|
||||
dim_head=attention_head_dim,
|
||||
heads=num_attention_heads,
|
||||
@@ -387,6 +486,13 @@ class Flux2SingleTransformerBlock(nn.Module):
|
||||
split_hidden_states: bool = False,
|
||||
text_seq_len: int | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Forward pass for Flux2SingleTransformerBlock with SP support.
|
||||
|
||||
In SP mode: image hidden_states is chunked (B, img_len/SP, D),
|
||||
text encoder_hidden_states is full (B, txt_len, D).
|
||||
The block concatenates them for joint attention.
|
||||
"""
|
||||
if encoder_hidden_states is not None:
|
||||
text_seq_len = encoder_hidden_states.shape[1]
|
||||
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
||||
@@ -400,6 +506,7 @@ class Flux2SingleTransformerBlock(nn.Module):
|
||||
attn_output = self.attn(
|
||||
hidden_states=norm_hidden_states,
|
||||
image_rotary_emb=image_rotary_emb,
|
||||
text_seq_len=text_seq_len,
|
||||
**joint_attention_kwargs,
|
||||
)
|
||||
|
||||
@@ -416,6 +523,7 @@ class Flux2SingleTransformerBlock(nn.Module):
|
||||
class Flux2TransformerBlock(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
parallel_config: DiffusionParallelConfig,
|
||||
dim: int,
|
||||
num_attention_heads: int,
|
||||
attention_head_dim: int,
|
||||
@@ -432,6 +540,7 @@ class Flux2TransformerBlock(nn.Module):
|
||||
self.norm1_context = nn.LayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
|
||||
self.attn = Flux2Attention(
|
||||
parallel_config=parallel_config,
|
||||
query_dim=dim,
|
||||
added_kv_proj_dim=dim,
|
||||
dim_head=attention_head_dim,
|
||||
@@ -543,6 +652,47 @@ class Flux2PosEmbed(nn.Module):
|
||||
return freqs_cos, freqs_sin
|
||||
|
||||
|
||||
class Flux2RopePrepare(nn.Module):
|
||||
"""Prepares RoPE embeddings for sequence parallel.
|
||||
|
||||
This module encapsulates the RoPE computation for Flux.2-dev.
|
||||
For dual-stream attention, text components (outputs 0, 1) are replicated
|
||||
across SP ranks, while image components (outputs 2, 3) are sharded.
|
||||
|
||||
NOTE: The hidden_states projection is handled separately in forward()
|
||||
so that _sp_plan can shard it at the root level.
|
||||
"""
|
||||
|
||||
def __init__(self, pos_embed: Flux2PosEmbed):
|
||||
super().__init__()
|
||||
self.pos_embed = pos_embed
|
||||
|
||||
def forward(
|
||||
self,
|
||||
img_ids: torch.Tensor,
|
||||
txt_ids: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Compute RoPE embeddings for text and image sequences.
|
||||
|
||||
Args:
|
||||
img_ids: Image position IDs (img_seq_len, n_axes)
|
||||
txt_ids: Text position IDs (txt_seq_len, n_axes)
|
||||
|
||||
Returns:
|
||||
Tuple of cosine / sine components for text & image
|
||||
in the order: (txt_cos, txt_sin, img_cos, img_sin)
|
||||
|
||||
NOTE: careful about output orders if this is refactored in the
|
||||
future; we need to match the _sp_plan indices, since text
|
||||
components (0 & 1) need to be replicated across SP ranks,
|
||||
while image components (2 & 3) must be sharded.
|
||||
"""
|
||||
img_freqs_cos, img_freqs_sin = self.pos_embed(img_ids)
|
||||
txt_freqs_cos, txt_freqs_sin = self.pos_embed(txt_ids)
|
||||
return txt_freqs_cos, txt_freqs_sin, img_freqs_cos, img_freqs_sin
|
||||
|
||||
|
||||
class Flux2TimestepGuidanceEmbeddings(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -601,9 +751,22 @@ class Flux2Modulation(nn.Module):
|
||||
class Flux2Transformer2DModel(nn.Module):
|
||||
"""
|
||||
The Transformer model introduced in Flux 2.
|
||||
|
||||
Supports Sequence Parallelism (Ulysses and Ring) when configured via OmniDiffusionConfig.
|
||||
"""
|
||||
|
||||
_repeated_blocks = ["Flux2TransformerBlock", "Flux2SingleTransformerBlock"]
|
||||
_sp_plan = {
|
||||
"": {
|
||||
"hidden_states": SequenceParallelInput(split_dim=1, expected_dims=3, auto_pad=True),
|
||||
},
|
||||
"rope_prepare": {
|
||||
2: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
|
||||
3: SequenceParallelInput(split_dim=0, expected_dims=2, split_output=True, auto_pad=True),
|
||||
},
|
||||
"proj_out": SequenceParallelOutput(gather_dim=1, expected_dims=3),
|
||||
}
|
||||
"""SP plan: shard hidden_states at root level, shard img_freqs at rope_prepare, gather output at proj_out."""
|
||||
|
||||
@staticmethod
|
||||
def _is_transformer_block(name: str, module) -> bool:
|
||||
@@ -628,6 +791,7 @@ class Flux2Transformer2DModel(nn.Module):
|
||||
eps: float = 1e-6,
|
||||
guidance_embeds: bool = True,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
od_config: OmniDiffusionConfig | None = None,
|
||||
):
|
||||
super().__init__()
|
||||
self.guidance_embeds = guidance_embeds
|
||||
@@ -652,7 +816,13 @@ class Flux2Transformer2DModel(nn.Module):
|
||||
guidance_embeds=guidance_embeds,
|
||||
)
|
||||
|
||||
if od_config is not None:
|
||||
self.parallel_config = od_config.parallel_config
|
||||
else:
|
||||
self.parallel_config = DiffusionParallelConfig()
|
||||
|
||||
self.pos_embed = Flux2PosEmbed(theta=rope_theta, axes_dim=axes_dims_rope)
|
||||
self.rope_prepare = Flux2RopePrepare(self.pos_embed)
|
||||
self.time_guidance_embed = Flux2TimestepGuidanceEmbeddings(
|
||||
in_channels=timestep_guidance_channels,
|
||||
embedding_dim=self.inner_dim,
|
||||
@@ -670,6 +840,7 @@ class Flux2Transformer2DModel(nn.Module):
|
||||
self.transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
Flux2TransformerBlock(
|
||||
parallel_config=self.parallel_config,
|
||||
dim=self.inner_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=attention_head_dim,
|
||||
@@ -686,6 +857,7 @@ class Flux2Transformer2DModel(nn.Module):
|
||||
self.single_transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
Flux2SingleTransformerBlock(
|
||||
parallel_config=self.parallel_config,
|
||||
dim=self.inner_dim,
|
||||
num_attention_heads=num_attention_heads,
|
||||
attention_head_dim=attention_head_dim,
|
||||
@@ -722,6 +894,9 @@ class Flux2Transformer2DModel(nn.Module):
|
||||
joint_attention_kwargs = joint_attention_kwargs or {}
|
||||
|
||||
num_txt_tokens = encoder_hidden_states.shape[1]
|
||||
sp_size = self.parallel_config.sequence_parallel_size
|
||||
if sp_size and sp_size > 1 and is_forward_context_available():
|
||||
get_forward_context().split_text_embed_in_sp = False
|
||||
|
||||
timestep = timestep.to(hidden_states.dtype) * 1000
|
||||
if guidance is not None:
|
||||
@@ -742,18 +917,43 @@ class Flux2Transformer2DModel(nn.Module):
|
||||
txt_ids = txt_ids[0]
|
||||
|
||||
if is_torch_npu_available():
|
||||
freqs_cos_image, freqs_sin_image = self.pos_embed(img_ids.cpu())
|
||||
image_rotary_emb = (freqs_cos_image.npu(), freqs_sin_image.npu())
|
||||
freqs_cos_text, freqs_sin_text = self.pos_embed(txt_ids.cpu())
|
||||
text_rotary_emb = (freqs_cos_text.npu(), freqs_sin_text.npu())
|
||||
txt_freqs_cos, txt_freqs_sin, img_freqs_cos, img_freqs_sin = self.rope_prepare(img_ids.cpu(), txt_ids.cpu())
|
||||
txt_freqs_cos = txt_freqs_cos.npu()
|
||||
txt_freqs_sin = txt_freqs_sin.npu()
|
||||
img_freqs_cos = img_freqs_cos.npu()
|
||||
img_freqs_sin = img_freqs_sin.npu()
|
||||
else:
|
||||
image_rotary_emb = self.pos_embed(img_ids)
|
||||
text_rotary_emb = self.pos_embed(txt_ids)
|
||||
txt_freqs_cos, txt_freqs_sin, img_freqs_cos, img_freqs_sin = self.rope_prepare(img_ids, txt_ids)
|
||||
concat_rotary_emb = (
|
||||
torch.cat([text_rotary_emb[0], image_rotary_emb[0]], dim=0),
|
||||
torch.cat([text_rotary_emb[1], image_rotary_emb[1]], dim=0),
|
||||
torch.cat([txt_freqs_cos, img_freqs_cos], dim=0),
|
||||
torch.cat([txt_freqs_sin, img_freqs_sin], dim=0),
|
||||
)
|
||||
|
||||
# Create separate masks for image and text portions for Ulysses SP joint attention
|
||||
hidden_states_mask = None
|
||||
encoder_hidden_states_mask = None
|
||||
if is_forward_context_available():
|
||||
ctx = get_forward_context()
|
||||
else:
|
||||
ctx = None
|
||||
if ctx is not None and ctx.sp_original_seq_len is not None and ctx.sp_padding_size > 0:
|
||||
batch_size = hidden_states.shape[0]
|
||||
img_padded_seq_len = ctx.sp_original_seq_len + ctx.sp_padding_size
|
||||
hidden_states_mask = torch.ones(
|
||||
batch_size,
|
||||
img_padded_seq_len,
|
||||
dtype=torch.bool,
|
||||
device=hidden_states.device,
|
||||
)
|
||||
hidden_states_mask[:, ctx.sp_original_seq_len :] = False
|
||||
if hidden_states_mask.all():
|
||||
hidden_states_mask = None
|
||||
|
||||
if hidden_states_mask is not None:
|
||||
joint_attention_kwargs["hidden_states_mask"] = hidden_states_mask
|
||||
if encoder_hidden_states_mask is not None:
|
||||
joint_attention_kwargs["encoder_hidden_states_mask"] = encoder_hidden_states_mask
|
||||
|
||||
for index_block, block in enumerate(self.transformer_blocks):
|
||||
encoder_hidden_states, hidden_states = block(
|
||||
hidden_states=hidden_states,
|
||||
@@ -773,6 +973,7 @@ class Flux2Transformer2DModel(nn.Module):
|
||||
temb_mod_params=single_stream_mod,
|
||||
image_rotary_emb=concat_rotary_emb,
|
||||
joint_attention_kwargs=joint_attention_kwargs,
|
||||
text_seq_len=num_txt_tokens,
|
||||
)
|
||||
|
||||
hidden_states = hidden_states[:, num_txt_tokens:, ...]
|
||||
|
||||
@@ -398,7 +398,9 @@ class Flux2Pipeline(nn.Module, CFGParallelMixin, SupportImageInput, ProgressBarM
|
||||
self._execution_device
|
||||
)
|
||||
transformer_kwargs = get_transformer_config_kwargs(od_config.tf_model_config, Flux2Transformer2DModel)
|
||||
self.transformer = Flux2Transformer2DModel(quant_config=od_config.quantization_config, **transformer_kwargs)
|
||||
self.transformer = Flux2Transformer2DModel(
|
||||
quant_config=od_config.quantization_config, od_config=od_config, **transformer_kwargs
|
||||
)
|
||||
|
||||
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) if getattr(self, "vae", None) else 8
|
||||
self.image_processor = Flux2ImageProcessor(vae_scale_factor=self.vae_scale_factor * 2)
|
||||
|
||||
@@ -15,6 +15,7 @@ from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
ReplicatedLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
@@ -33,6 +34,9 @@ from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -230,11 +234,24 @@ class GlmImagePrepare(nn.Module):
|
||||
class GlmImageAdaLayerNormZero(nn.Module):
|
||||
"""Adaptive LayerNorm with zero initialization for both image and text streams."""
|
||||
|
||||
def __init__(self, embedding_dim: int, dim: int) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
embedding_dim: int,
|
||||
dim: int,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
|
||||
self.norm_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
|
||||
self.linear = nn.Linear(embedding_dim, 12 * dim, bias=True)
|
||||
self.linear = ReplicatedLinear(
|
||||
embedding_dim,
|
||||
12 * dim,
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.linear",
|
||||
)
|
||||
|
||||
def forward(
|
||||
self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
|
||||
@@ -244,6 +261,8 @@ class GlmImageAdaLayerNormZero(nn.Module):
|
||||
norm_encoder_hidden_states = self.norm_context(encoder_hidden_states).to(dtype=dtype)
|
||||
|
||||
emb = self.linear(temb)
|
||||
if isinstance(emb, tuple):
|
||||
emb = emb[0]
|
||||
(
|
||||
shift_msa,
|
||||
c_shift_msa,
|
||||
@@ -286,14 +305,25 @@ class GlmImageAdaLayerNormContinuous(nn.Module):
|
||||
elementwise_affine: bool = True,
|
||||
eps: float = 1e-5,
|
||||
bias: bool = True,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
|
||||
self.linear = ReplicatedLinear(
|
||||
conditioning_embedding_dim,
|
||||
embedding_dim * 2,
|
||||
bias=bias,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.linear",
|
||||
)
|
||||
self.norm = nn.LayerNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
|
||||
|
||||
def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
|
||||
# NO SiLU here
|
||||
emb = self.linear(conditioning_embedding.to(x.dtype))
|
||||
if isinstance(emb, tuple):
|
||||
emb = emb[0]
|
||||
scale, shift = torch.chunk(emb, 2, dim=1)
|
||||
x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
|
||||
return x
|
||||
@@ -469,6 +499,7 @@ class GlmImageAttention(nn.Module):
|
||||
out_bias: bool = True,
|
||||
eps: float = 1e-5,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
@@ -485,6 +516,7 @@ class GlmImageAttention(nn.Module):
|
||||
bias=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.to_qkv",
|
||||
)
|
||||
|
||||
# QK normalization (LayerNorm, not RMSNorm for GLM-Image)
|
||||
@@ -501,6 +533,7 @@ class GlmImageAttention(nn.Module):
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.to_out.0",
|
||||
),
|
||||
nn.Dropout(0.0),
|
||||
]
|
||||
@@ -554,7 +587,7 @@ class GlmImageAttention(nn.Module):
|
||||
hidden_states_combined = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
||||
|
||||
# QKV projection
|
||||
qkv = self.to_qkv(hidden_states_combined)
|
||||
qkv = self.to_qkv(hidden_states_combined.contiguous())
|
||||
q_size = self.to_qkv.num_heads * self.head_dim
|
||||
kv_size = self.to_qkv.num_kv_heads * self.head_dim
|
||||
query, key, value = qkv.split([q_size, kv_size, kv_size], dim=-1)
|
||||
@@ -604,8 +637,12 @@ class GlmImageAttention(nn.Module):
|
||||
# Project combined [text, image] outputs, then split.
|
||||
# This keeps SP numerically aligned with the non-SP path.
|
||||
joint_hidden_states_out = joint_hidden_states_out.flatten(2, 3).to(dtype)
|
||||
# Contiguous for FP8/W4A16 quantized RowParallelLinear
|
||||
for module in self.to_out:
|
||||
joint_hidden_states_out = module(joint_hidden_states_out)
|
||||
if isinstance(module, RowParallelLinear):
|
||||
joint_hidden_states_out = module(joint_hidden_states_out.contiguous())
|
||||
else:
|
||||
joint_hidden_states_out = module(joint_hidden_states_out)
|
||||
|
||||
encoder_hidden_states_out = joint_hidden_states_out[:, :text_seq_length, :]
|
||||
hidden_states_out = joint_hidden_states_out[:, text_seq_length:, :]
|
||||
@@ -645,7 +682,10 @@ class GlmImageAttention(nn.Module):
|
||||
|
||||
# Output projection
|
||||
for module in self.to_out:
|
||||
hidden_states_out = module(hidden_states_out)
|
||||
if isinstance(module, RowParallelLinear):
|
||||
hidden_states_out = module(hidden_states_out.contiguous())
|
||||
else:
|
||||
hidden_states_out = module(hidden_states_out)
|
||||
|
||||
# Split back to text and image
|
||||
encoder_hidden_states_out = hidden_states_out[:, :text_seq_length, :]
|
||||
@@ -663,6 +703,7 @@ class ColumnParallelGELU(nn.Module):
|
||||
approximate: str = "none",
|
||||
bias: bool = True,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.proj = ColumnParallelLinear(
|
||||
@@ -672,6 +713,7 @@ class ColumnParallelGELU(nn.Module):
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.proj",
|
||||
)
|
||||
self.approximate = approximate
|
||||
|
||||
@@ -688,6 +730,7 @@ class ColumnParallelSiLU(nn.Module):
|
||||
*,
|
||||
bias: bool = True,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.proj = ColumnParallelLinear(
|
||||
@@ -697,6 +740,7 @@ class ColumnParallelSiLU(nn.Module):
|
||||
gather_output=False,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.proj",
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
@@ -714,6 +758,7 @@ class GlmImageFeedForward(nn.Module):
|
||||
bias: bool = True,
|
||||
activation_fn: str = "gelu",
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
inner_dim = inner_dim or int(dim * mult)
|
||||
@@ -721,7 +766,7 @@ class GlmImageFeedForward(nn.Module):
|
||||
|
||||
if activation_fn == "linear-silu":
|
||||
layers: list[nn.Module] = [
|
||||
ColumnParallelSiLU(dim, inner_dim, bias=bias, quant_config=quant_config),
|
||||
ColumnParallelSiLU(dim, inner_dim, bias=bias, quant_config=quant_config, prefix=f"{prefix}.net.0"),
|
||||
nn.Identity(),
|
||||
RowParallelLinear(
|
||||
inner_dim,
|
||||
@@ -730,12 +775,20 @@ class GlmImageFeedForward(nn.Module):
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.net.2",
|
||||
),
|
||||
]
|
||||
else:
|
||||
approximate = "tanh" if activation_fn == "gelu-approximate" else "none"
|
||||
layers = [
|
||||
ColumnParallelGELU(dim, inner_dim, approximate=approximate, bias=bias, quant_config=quant_config),
|
||||
ColumnParallelGELU(
|
||||
dim,
|
||||
inner_dim,
|
||||
approximate=approximate,
|
||||
bias=bias,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.net.0",
|
||||
),
|
||||
nn.Identity(),
|
||||
RowParallelLinear(
|
||||
inner_dim,
|
||||
@@ -744,6 +797,7 @@ class GlmImageFeedForward(nn.Module):
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.net.2",
|
||||
),
|
||||
]
|
||||
|
||||
@@ -751,7 +805,12 @@ class GlmImageFeedForward(nn.Module):
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
for module in self.net:
|
||||
hidden_states = module(hidden_states)
|
||||
if isinstance(module, ColumnParallelLinear):
|
||||
hidden_states, _ = module(hidden_states)
|
||||
elif isinstance(module, RowParallelLinear):
|
||||
hidden_states = module(hidden_states.contiguous())
|
||||
else:
|
||||
hidden_states = module(hidden_states)
|
||||
return hidden_states
|
||||
|
||||
|
||||
@@ -765,19 +824,21 @@ class GlmImageTransformerBlock(nn.Module):
|
||||
attention_head_dim: int = 40,
|
||||
time_embed_dim: int = 512,
|
||||
ffn_hidden_dim: int | None = None,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
parallel_config: DiffusionParallelConfig | None = None,
|
||||
quant_config: "QuantizationConfig | None" = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
|
||||
# 1. Attention with AdaLN
|
||||
self.norm1 = GlmImageAdaLayerNormZero(time_embed_dim, dim)
|
||||
self.norm1 = GlmImageAdaLayerNormZero(time_embed_dim, dim, quant_config=quant_config, prefix=f"{prefix}.norm1")
|
||||
self.attn1 = GlmImageAttention(
|
||||
dim=dim,
|
||||
num_heads=num_attention_heads,
|
||||
head_dim=attention_head_dim,
|
||||
quant_config=quant_config,
|
||||
parallel_config=parallel_config,
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.attn1",
|
||||
)
|
||||
|
||||
# 2. Feedforward
|
||||
@@ -789,6 +850,7 @@ class GlmImageTransformerBlock(nn.Module):
|
||||
inner_dim=ffn_hidden_dim,
|
||||
activation_fn="gelu-approximate",
|
||||
quant_config=quant_config,
|
||||
prefix=f"{prefix}.ff",
|
||||
)
|
||||
|
||||
def forward(
|
||||
@@ -959,6 +1021,7 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
inner_dim=inner_dim,
|
||||
activation_fn="gelu",
|
||||
quant_config=quant_config,
|
||||
prefix="glyph_projector",
|
||||
)
|
||||
self.prior_token_embedding = nn.Embedding(prior_vq_quantizer_codebook_size, inner_dim)
|
||||
self.prior_projector = GlmImageFeedForward(
|
||||
@@ -967,6 +1030,7 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
inner_dim=inner_dim,
|
||||
activation_fn="linear-silu",
|
||||
quant_config=quant_config,
|
||||
prefix="prior_projector",
|
||||
)
|
||||
|
||||
# Prepare module for SP (encapsulates patch embedding and RoPE for _sp_plan)
|
||||
@@ -988,15 +1052,20 @@ class GlmImageTransformer2DModel(CachedTransformer):
|
||||
attention_head_dim,
|
||||
time_embed_dim,
|
||||
ffn_hidden_dim=ffn_hidden_dim,
|
||||
quant_config=quant_config,
|
||||
parallel_config=self.parallel_config,
|
||||
quant_config=quant_config,
|
||||
prefix=f"transformer_blocks.{i}",
|
||||
)
|
||||
for _ in range(num_layers)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
|
||||
# 4. Output projection
|
||||
self.norm_out = GlmImageAdaLayerNormContinuous(inner_dim, time_embed_dim, elementwise_affine=False)
|
||||
# Final modulation feeds proj_out; quant_config is NOT applied here
|
||||
# to avoid precision degradation in the final projection layer.
|
||||
self.norm_out = GlmImageAdaLayerNormContinuous(
|
||||
inner_dim, time_embed_dim, elementwise_affine=False, quant_config=None, prefix="norm_out"
|
||||
)
|
||||
self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels, bias=True)
|
||||
|
||||
def forward(
|
||||
|
||||
@@ -301,10 +301,7 @@ class GlmImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
|
||||
# Load transformer (DiT)
|
||||
logger.info("Loading GlmImageTransformer2DModel (DiT)...")
|
||||
self.transformer = GlmImageTransformer2DModel(
|
||||
od_config=od_config,
|
||||
quant_config=od_config.quantization_config,
|
||||
)
|
||||
self.transformer = GlmImageTransformer2DModel(od_config=od_config, quant_config=od_config.quantization_config)
|
||||
|
||||
# Weight sources for DiT loading
|
||||
self.weights_sources = [
|
||||
@@ -689,15 +686,11 @@ class GlmImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
prompt = first_prompt if isinstance(first_prompt, str) else (first_prompt.get("prompt") or "")
|
||||
|
||||
# NOTE: DiffusionEngine does an internal warmup "dummy run" during
|
||||
# initialization. That request has no request_id and does not carry
|
||||
# initialization. That request carries the fixed dummy request_id and does not carry
|
||||
# Stage-0 (AR) outputs via req.extra. For GLM-Image, we allow that
|
||||
# specific warmup request to proceed by synthesizing minimal prior
|
||||
# tokens, while still raising a clear error for real requests.
|
||||
is_dummy_warmup = (
|
||||
not getattr(req, "request_id", None)
|
||||
and prompt == "dummy run"
|
||||
and (req.sampling_params.num_inference_steps == 1)
|
||||
)
|
||||
is_dummy_warmup = req.is_dummy_run()
|
||||
|
||||
# Get pre-computed prompt embeddings if provided
|
||||
if isinstance(first_prompt, str):
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
# Adapted from Helios (https://github.com/BestWishYsh/Helios)
|
||||
|
||||
import math
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Iterable
|
||||
from functools import lru_cache
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -447,21 +448,32 @@ class HeliosCrossAttention(nn.Module):
|
||||
causal=False,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
query = self.to_q(hidden_states)
|
||||
query = self.norm_q(query)
|
||||
|
||||
def project_kv(self, encoder_hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
key = self.to_k(encoder_hidden_states)
|
||||
value = self.to_v(encoder_hidden_states)
|
||||
key = self.norm_k(key)
|
||||
|
||||
query = query.unflatten(2, (self.num_heads, self.head_dim))
|
||||
key = key.unflatten(2, (self.num_heads, self.head_dim))
|
||||
value = value.unflatten(2, (self.num_heads, self.head_dim))
|
||||
return key, value
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor | None = None,
|
||||
encoder_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
query = self.to_q(hidden_states)
|
||||
query = self.norm_q(query)
|
||||
|
||||
if encoder_key_value is None:
|
||||
if encoder_hidden_states is None:
|
||||
raise ValueError("encoder_hidden_states is required when encoder_key_value is not provided.")
|
||||
key, value = self.project_kv(encoder_hidden_states)
|
||||
else:
|
||||
key, value = encoder_key_value
|
||||
|
||||
query = query.unflatten(2, (self.num_heads, self.head_dim))
|
||||
|
||||
hidden_states = self.attn(query, key, value)
|
||||
hidden_states = hidden_states.flatten(2, 3)
|
||||
@@ -526,6 +538,7 @@ class HeliosTransformerBlock(nn.Module):
|
||||
temb: torch.Tensor,
|
||||
rotary_emb: torch.Tensor,
|
||||
original_context_length: int | None = None,
|
||||
cross_attn_key_value: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
) -> torch.Tensor:
|
||||
if temb.ndim == 4:
|
||||
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
||||
@@ -556,12 +569,20 @@ class HeliosTransformerBlock(nn.Module):
|
||||
hidden_states[:, history_seq_len:],
|
||||
)
|
||||
norm_hidden_states = self.norm2(current_hidden_states.float()).type_as(current_hidden_states)
|
||||
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states)
|
||||
attn_output = self.attn2(
|
||||
norm_hidden_states,
|
||||
encoder_hidden_states,
|
||||
encoder_key_value=cross_attn_key_value,
|
||||
)
|
||||
current_hidden_states = current_hidden_states + attn_output
|
||||
hidden_states = torch.cat([history_hidden_states, current_hidden_states], dim=1)
|
||||
else:
|
||||
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
||||
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states)
|
||||
attn_output = self.attn2(
|
||||
norm_hidden_states,
|
||||
encoder_hidden_states,
|
||||
encoder_key_value=cross_attn_key_value,
|
||||
)
|
||||
hidden_states = hidden_states + attn_output
|
||||
|
||||
# 3. Feed-forward
|
||||
@@ -723,11 +744,80 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
# 5. Output norm & projection
|
||||
self.norm_out = HeliosOutputNorm(inner_dim, eps)
|
||||
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
|
||||
self._projected_encoder_cache: OrderedDict[tuple, torch.Tensor] = OrderedDict()
|
||||
self._cross_attn_kv_cache: OrderedDict[tuple, list[tuple[torch.Tensor, torch.Tensor]]] = OrderedDict()
|
||||
self._cross_attn_cache_size = 2
|
||||
|
||||
@property
|
||||
def dtype(self) -> torch.dtype:
|
||||
return next(self.parameters()).dtype
|
||||
|
||||
@staticmethod
|
||||
def _tensor_cache_key(tensor: torch.Tensor) -> tuple:
|
||||
try:
|
||||
version = tensor._version
|
||||
except RuntimeError:
|
||||
version = None
|
||||
|
||||
return (
|
||||
tensor.data_ptr(),
|
||||
tuple(tensor.shape),
|
||||
tuple(tensor.stride()),
|
||||
tensor.dtype,
|
||||
tensor.device.type,
|
||||
tensor.device.index,
|
||||
version,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _get_from_lru(cache: OrderedDict, key: tuple):
|
||||
value = cache.get(key)
|
||||
if value is not None:
|
||||
cache.move_to_end(key)
|
||||
return value
|
||||
|
||||
def _put_lru(self, cache: OrderedDict, key: tuple, value) -> None:
|
||||
cache[key] = value
|
||||
cache.move_to_end(key)
|
||||
while len(cache) > self._cross_attn_cache_size:
|
||||
cache.popitem(last=False)
|
||||
|
||||
def clear_cross_attention_cache(self) -> None:
|
||||
self._projected_encoder_cache.clear()
|
||||
self._cross_attn_kv_cache.clear()
|
||||
|
||||
def _cache_enabled(self) -> bool:
|
||||
return not self.training and not torch.is_grad_enabled() and not torch.compiler.is_compiling()
|
||||
|
||||
def _project_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
if not self._cache_enabled():
|
||||
return self.condition_embedder.text_embedder(encoder_hidden_states)
|
||||
|
||||
cache_key = self._tensor_cache_key(encoder_hidden_states)
|
||||
cached = self._get_from_lru(self._projected_encoder_cache, cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
projected = self.condition_embedder.text_embedder(encoder_hidden_states)
|
||||
self._put_lru(self._projected_encoder_cache, cache_key, projected)
|
||||
return projected
|
||||
|
||||
def _get_cross_attn_key_values(
|
||||
self,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
) -> list[tuple[torch.Tensor, torch.Tensor]] | None:
|
||||
if not self._cache_enabled():
|
||||
return None
|
||||
|
||||
cache_key = self._tensor_cache_key(encoder_hidden_states)
|
||||
cached = self._get_from_lru(self._cross_attn_kv_cache, cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
key_values = [block.attn2.project_kv(encoder_hidden_states) for block in self.blocks]
|
||||
self._put_lru(self._cross_attn_kv_cache, cache_key, key_values)
|
||||
return key_values
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
@@ -836,7 +926,12 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
.expand(batch_size, -1, history_context_length, -1)
|
||||
)
|
||||
|
||||
temb, timestep_proj, encoder_hidden_states = self.condition_embedder(timestep, encoder_hidden_states)
|
||||
temb, timestep_proj, _ = self.condition_embedder(
|
||||
timestep,
|
||||
encoder_hidden_states,
|
||||
is_return_encoder_hidden_states=False,
|
||||
)
|
||||
encoder_hidden_states = self._project_encoder_hidden_states(encoder_hidden_states)
|
||||
timestep_proj = timestep_proj.unflatten(-1, (6, -1))
|
||||
|
||||
if indices_hidden_states is not None and not self.zero_history_timestep:
|
||||
@@ -857,14 +952,17 @@ class HeliosTransformer3DModel(nn.Module):
|
||||
hidden_states = hidden_states.contiguous()
|
||||
encoder_hidden_states = encoder_hidden_states.contiguous()
|
||||
rotary_emb = rotary_emb.contiguous()
|
||||
cross_attn_key_values = self._get_cross_attn_key_values(encoder_hidden_states)
|
||||
|
||||
for block in self.blocks:
|
||||
for block_idx, block in enumerate(self.blocks):
|
||||
cross_attn_key_value = None if cross_attn_key_values is None else cross_attn_key_values[block_idx]
|
||||
hidden_states = block(
|
||||
hidden_states,
|
||||
encoder_hidden_states,
|
||||
timestep_proj,
|
||||
rotary_emb,
|
||||
original_context_length,
|
||||
cross_attn_key_value,
|
||||
)
|
||||
|
||||
# 7. Output normalization
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""HiDream Image diffusion model components."""
|
||||
|
||||
from vllm_omni.diffusion.models.hidream_image.hidream_image_transformer import (
|
||||
HiDreamImageTransformer2DModel,
|
||||
)
|
||||
from vllm_omni.diffusion.models.hidream_image.pipeline_hidream_image import (
|
||||
HiDreamImagePipeline,
|
||||
get_hidream_image_post_process_func,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"HiDreamImageTransformer2DModel",
|
||||
"HiDreamImagePipeline",
|
||||
"get_hidream_image_post_process_func",
|
||||
]
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -891,6 +891,7 @@ class ImageKVCacheManager:
|
||||
# cache related
|
||||
self.image_token_len: int = image_token_len
|
||||
self.image_kv_cache_map: tuple[torch.Tensor, torch.Tensor] | None = None
|
||||
self.image_kv_cache_lens: torch.Tensor | None = None
|
||||
self._injected_ar_kv: list[tuple[torch.Tensor, torch.Tensor]] | None = None
|
||||
|
||||
self.sp_size = get_sequence_parallel_world_size()
|
||||
@@ -904,12 +905,23 @@ class ImageKVCacheManager:
|
||||
prefix=f"{prefix}.attn" if prefix else "",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _get_current_starts(
|
||||
gen_timestep_scatter_index: torch.Tensor | None,
|
||||
ar_kv_len: int = 0,
|
||||
) -> torch.Tensor:
|
||||
assert gen_timestep_scatter_index is not None, (
|
||||
"`gen_timestep_scatter_index` is required to locate the generated image timestep token for image KV reuse."
|
||||
)
|
||||
return gen_timestep_scatter_index[:, -1].to(dtype=torch.long) + ar_kv_len
|
||||
|
||||
def _cache_prompt_kv(
|
||||
self,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
seq_len: int,
|
||||
shard_image_size: int | None = None,
|
||||
gen_timestep_scatter_index: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Cache prompt KV on first_step. Consumes _injected_ar_kv.
|
||||
|
||||
@@ -939,12 +951,26 @@ class ImageKVCacheManager:
|
||||
key = torch.cat(new_keys, dim=0)
|
||||
value = torch.cat(new_values, dim=0)
|
||||
|
||||
image_size = shard_image_size if self.sp_size > 1 else (self.image_token_len + 1)
|
||||
cached_prompt_len = seq_len - image_size
|
||||
cached_prompt_lens = self._get_current_starts(gen_timestep_scatter_index, ar_kv_len)
|
||||
assert torch.all(cached_prompt_lens <= key.shape[1]), (
|
||||
f"cached_prompt_lens({cached_prompt_lens.tolist()}) must be <= key length({key.shape[1]})"
|
||||
)
|
||||
if shard_image_size is not None:
|
||||
expected_prompt_len = seq_len - shard_image_size
|
||||
assert torch.all(cached_prompt_lens == expected_prompt_len), (
|
||||
f"cached_prompt_lens({cached_prompt_lens.tolist()}) != "
|
||||
f"seq_len({seq_len}) - shard_image_size({shard_image_size})"
|
||||
)
|
||||
|
||||
cached_key = key[:, :cached_prompt_len].reshape(-1, num_kv_heads, head_dim)
|
||||
cached_value = value[:, :cached_prompt_len].reshape(-1, num_kv_heads, head_dim)
|
||||
max_cached_prompt_len = int(cached_prompt_lens.max().item())
|
||||
cached_key = key.new_zeros(bs, max_cached_prompt_len, num_kv_heads, head_dim)
|
||||
cached_value = value.new_zeros(bs, max_cached_prompt_len, num_kv_heads, head_dim)
|
||||
for b in range(bs):
|
||||
cached_prompt_len = int(cached_prompt_lens[b].item())
|
||||
cached_key[b, :cached_prompt_len] = key[b, :cached_prompt_len]
|
||||
cached_value[b, :cached_prompt_len] = value[b, :cached_prompt_len]
|
||||
self.image_kv_cache_map = (cached_key, cached_value)
|
||||
self.image_kv_cache_lens = cached_prompt_lens
|
||||
return key, value
|
||||
|
||||
def _reuse_prompt_kv(
|
||||
@@ -954,42 +980,36 @@ class ImageKVCacheManager:
|
||||
seq_len: int,
|
||||
bs: int,
|
||||
shard_image_size: int | None = None,
|
||||
position_ids: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
Reuse cached prompt KV in subsequent denoising steps.
|
||||
|
||||
Non-SP: returns [cached_prompt, new_image, zero_eoi] shaped [bs, seq_len, ...].
|
||||
SP: returns cached prompt only shaped [bs, cached_prompt_len, ...] (used as joint_text).
|
||||
Non-SP: concatenates cached prompt KV with current image KV.
|
||||
SP: returns cached prompt KV only (used as joint_text).
|
||||
"""
|
||||
cached_key, cached_value = self.image_kv_cache_map
|
||||
_, q_len, num_kv_heads, head_dim = key.shape
|
||||
cached_prompt_len = cached_key.shape[0] // bs
|
||||
_, q_len, _, _ = key.shape
|
||||
assert cached_key.dim() == 4 and cached_key.shape[0] == bs
|
||||
max_cached_prompt_len = cached_key.shape[1]
|
||||
|
||||
if shard_image_size is not None:
|
||||
assert cached_prompt_len == seq_len - q_len
|
||||
result_k = cached_key.reshape(bs, cached_prompt_len, num_kv_heads, head_dim)
|
||||
result_v = cached_value.reshape(bs, cached_prompt_len, num_kv_heads, head_dim)
|
||||
return result_k.contiguous(), result_v.contiguous()
|
||||
assert max_cached_prompt_len + q_len == seq_len, (
|
||||
f"max_cached_prompt_len({max_cached_prompt_len}) + q_len({q_len}) != seq_len({seq_len})"
|
||||
)
|
||||
return cached_key.contiguous(), cached_value.contiguous()
|
||||
|
||||
assert cached_prompt_len + 1 == seq_len - q_len, f"{cached_prompt_len + 1} != {seq_len - q_len}"
|
||||
|
||||
key = key.reshape(-1, num_kv_heads, head_dim)
|
||||
value = value.reshape(-1, num_kv_heads, head_dim)
|
||||
zero_eoi = torch.zeros(1, num_kv_heads, head_dim, device=key.device, dtype=key.dtype)
|
||||
|
||||
new_key, new_value = [], []
|
||||
for b in range(bs):
|
||||
cache_base = b * cached_prompt_len
|
||||
img_base = b * q_len
|
||||
new_key.append(cached_key[cache_base : cache_base + cached_prompt_len])
|
||||
new_key.append(key[img_base : img_base + q_len])
|
||||
new_key.append(zero_eoi)
|
||||
new_value.append(cached_value[cache_base : cache_base + cached_prompt_len])
|
||||
new_value.append(value[img_base : img_base + q_len])
|
||||
new_value.append(zero_eoi)
|
||||
|
||||
new_key = torch.cat(new_key).reshape(bs, seq_len, num_kv_heads, head_dim)
|
||||
new_value = torch.cat(new_value).reshape(bs, seq_len, num_kv_heads, head_dim)
|
||||
assert max_cached_prompt_len + q_len == seq_len, (
|
||||
f"max_cached_prompt_len({max_cached_prompt_len}) + q_len({q_len}) != seq_len({seq_len})"
|
||||
)
|
||||
assert self.image_kv_cache_lens is not None
|
||||
if position_ids is not None:
|
||||
assert position_ids.shape == (bs, q_len)
|
||||
assert torch.all(position_ids[:, 0] == self.image_kv_cache_lens), (
|
||||
"The first current position must immediately follow each sample's cached prompt KV."
|
||||
)
|
||||
new_key = torch.cat([cached_key, key], dim=1)
|
||||
new_value = torch.cat([cached_value, value], dim=1)
|
||||
return new_key.contiguous(), new_value.contiguous()
|
||||
|
||||
def _build_neg_ar_kv(
|
||||
@@ -1032,7 +1052,7 @@ class ImageKVCacheManager:
|
||||
|
||||
query_lens = kwargs.get("query_lens")
|
||||
seq_lens = kwargs.get("seq_lens")
|
||||
shard_image_size = kwargs.get("shard_image_size")
|
||||
shard_image_size = kwargs.get("shard_image_size") if self.sp_size > 1 else None
|
||||
bs = len(query_lens)
|
||||
q_len = query_lens[0]
|
||||
seq_len = seq_lens[0]
|
||||
@@ -1058,7 +1078,14 @@ class ImageKVCacheManager:
|
||||
value = value[:, :0, :, :]
|
||||
elif first_step:
|
||||
self.image_kv_cache_map = None # reset first
|
||||
key, value = self._cache_prompt_kv(key, value, seq_len, shard_image_size)
|
||||
self.image_kv_cache_lens = None
|
||||
key, value = self._cache_prompt_kv(
|
||||
key,
|
||||
value,
|
||||
seq_len,
|
||||
shard_image_size,
|
||||
kwargs.get("gen_timestep_scatter_index"),
|
||||
)
|
||||
if self.sp_size > 1:
|
||||
local_prompt_len = seq_len - shard_image_size
|
||||
join_query_len = query.shape[1] - shard_image_size
|
||||
@@ -1070,7 +1097,7 @@ class ImageKVCacheManager:
|
||||
value = value[:, local_prompt_len:, :, :]
|
||||
else:
|
||||
if self.sp_size <= 1:
|
||||
key, value = self._reuse_prompt_kv(key, value, seq_len, bs)
|
||||
key, value = self._reuse_prompt_kv(key, value, seq_len, bs, position_ids=kwargs.get("position_ids"))
|
||||
else:
|
||||
joint_text_query = query[:, :0, :, :]
|
||||
joint_text_key, joint_text_value = self._reuse_prompt_kv(key, value, seq_len, bs, shard_image_size)
|
||||
@@ -1814,6 +1841,7 @@ class HunyuanImage3DecoderLayer(nn.Module):
|
||||
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
||||
hidden_states=hidden_states,
|
||||
attention_mask=attention_mask,
|
||||
position_ids=position_ids,
|
||||
custom_pos_emb=custom_pos_emb,
|
||||
past_key_value=past_key_value,
|
||||
output_attentions=output_attentions,
|
||||
@@ -1878,12 +1906,21 @@ class HunyuanImagePreprocessor(nn.Module):
|
||||
image_token_len: int,
|
||||
is_first_step: bool = False,
|
||||
uncond_cfg_prefill: bool = False,
|
||||
gen_timestep_scatter_index: torch.Tensor | None = None,
|
||||
):
|
||||
# ---------- compute prompt length ----------
|
||||
if uncond_cfg_prefill:
|
||||
prompt_len = hidden_states.shape[1]
|
||||
elif is_first_step:
|
||||
prompt_len = hidden_states.shape[1] - image_token_len - 1
|
||||
assert gen_timestep_scatter_index is not None, (
|
||||
"`gen_timestep_scatter_index` is required to split prompt and "
|
||||
"generated image tokens for sequence parallel image generation."
|
||||
)
|
||||
prompt_lens = gen_timestep_scatter_index[:, -1]
|
||||
assert torch.all(prompt_lens == prompt_lens[0]), (
|
||||
"Sequence parallel image generation requires the generated timestep position to match across the batch."
|
||||
)
|
||||
prompt_len = int(prompt_lens[0].item())
|
||||
else:
|
||||
prompt_len = 0
|
||||
|
||||
@@ -2073,7 +2110,7 @@ class HunyuanImage3Model(nn.Module):
|
||||
return False
|
||||
|
||||
def is_scalar_quant_scale(name: str, tensor: torch.Tensor) -> bool:
|
||||
return tensor.numel() == 1 and name.endswith((".input_scale", ".weight_scale"))
|
||||
return tensor.numel() == 1 and name.endswith((".input_scale", ".weight_scale", ".weight_scale_2"))
|
||||
|
||||
def load_split_param(
|
||||
name: str,
|
||||
@@ -2327,6 +2364,7 @@ class HunyuanImage3Model(nn.Module):
|
||||
num_image_tokens,
|
||||
first_step,
|
||||
uncond_cfg_prefill=uncond_cfg_prefill,
|
||||
gen_timestep_scatter_index=gen_timestep_scatter_index,
|
||||
)
|
||||
assert len(set(query_lens)) == 1 and len(set(seq_lens)) == 1, (
|
||||
"query_lens and seq_lens must be the same for sequence parallel"
|
||||
@@ -2334,15 +2372,15 @@ class HunyuanImage3Model(nn.Module):
|
||||
prompt_size = text_hidden_states.shape[1]
|
||||
shard_image_size = image_hidden_states.shape[1]
|
||||
|
||||
if first_step: # [image tokens, last token]
|
||||
shard_padding_size = shard_image_size * sp_world_size - (num_image_tokens + 1)
|
||||
else: # [image tokens, last token]
|
||||
if first_step:
|
||||
shard_padding_size = shard_image_size * sp_world_size - (origin_query_len - prompt_size)
|
||||
else:
|
||||
shard_padding_size = shard_image_size * sp_world_size - num_image_tokens
|
||||
if first_step:
|
||||
seq_lens = [prompt_size + shard_image_size + ar_kv_reuse_len for _ in seq_lens]
|
||||
else:
|
||||
seq_lens = [x - y for x, y in zip(seq_lens, query_lens)]
|
||||
seq_lens = [seq_len + shard_image_size - 1 for seq_len in seq_lens]
|
||||
seq_lens = [seq_len + shard_image_size for seq_len in seq_lens]
|
||||
query_lens = [prompt_size + shard_image_size for _ in query_lens]
|
||||
|
||||
if prompt_size > 0:
|
||||
@@ -2357,10 +2395,6 @@ class HunyuanImage3Model(nn.Module):
|
||||
position_ids = image_position_ids
|
||||
custom_pos_emb = (image_custom_pos_emb_sin, image_custom_pos_emb_cos)
|
||||
|
||||
if not first_step:
|
||||
assert torch.all(~attention_mask[..., -1]), "The last token should not be attended to"
|
||||
attention_mask = attention_mask[..., :-1] # we attention without last token
|
||||
|
||||
if shard_padding_size > 0:
|
||||
B, H, Q, K = attention_mask.shape
|
||||
pad = shard_padding_size
|
||||
@@ -3091,15 +3125,11 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
|
||||
# Scheduler step (all ranks compute locally in CFG parallel)
|
||||
latents = self.scheduler.step(pred, t, latents, **_scheduler_step_extra_kwargs, return_dict=False)[0]
|
||||
if i != len(timesteps) - 1 and should_compute:
|
||||
offset = model_kwargs.get("ar_kv_reuse_offset", 0)
|
||||
model_kwargs = self.model._update_model_kwargs_for_generation( # noqa
|
||||
model_output,
|
||||
model_kwargs,
|
||||
)
|
||||
if input_ids.shape[1] != model_kwargs["position_ids"].shape[1]:
|
||||
# Select using relative positions
|
||||
index = model_kwargs["position_ids"] - offset
|
||||
input_ids = torch.gather(input_ids, 1, index=index)
|
||||
input_ids = None
|
||||
attention_mask = model_kwargs.get("attention_mask")
|
||||
b, _, q_len1, seq_len = attention_mask.shape
|
||||
query_lens = [q_len1] * b
|
||||
|
||||
@@ -1001,7 +1001,7 @@ class HunyuanImage3Pipeline(
|
||||
if inputs_embeds is not None and past_key_values is None:
|
||||
model_inputs = {"inputs_embeds": inputs_embeds}
|
||||
else:
|
||||
if input_ids.shape[1] != kwargs["position_ids"].shape[1]: # in decode steps
|
||||
if input_ids is not None and input_ids.shape[1] != kwargs["position_ids"].shape[1]: # in decode steps
|
||||
input_ids = torch.gather(input_ids, dim=1, index=kwargs["position_ids"])
|
||||
model_inputs = {"input_ids": input_ids}
|
||||
|
||||
@@ -1082,12 +1082,27 @@ class HunyuanImage3Pipeline(
|
||||
|
||||
# attention mask
|
||||
mask_list = []
|
||||
for attention_mask_i, position_ids_i in zip(
|
||||
model_kwargs["attention_mask"], updated_model_kwargs["position_ids"]
|
||||
current_starts = timestep_position_ids.reshape(-1)
|
||||
max_current_start = int(current_starts.max().item())
|
||||
for attention_mask_i, position_ids_i, current_start_i in zip(
|
||||
model_kwargs["attention_mask"], updated_model_kwargs["position_ids"], current_starts
|
||||
):
|
||||
mask_list.append(
|
||||
torch.index_select(attention_mask_i, dim=1, index=position_ids_i.reshape(-1) - offset)
|
||||
query_mask = torch.index_select(attention_mask_i, dim=1, index=position_ids_i.reshape(-1) - offset)
|
||||
current_start = int(current_start_i.item())
|
||||
prefix_mask = torch.index_select(
|
||||
query_mask,
|
||||
dim=2,
|
||||
index=torch.arange(current_start, device=image_mask.device),
|
||||
)
|
||||
if current_start < max_current_start:
|
||||
prefix_pad = query_mask.new_zeros(
|
||||
query_mask.shape[0],
|
||||
query_mask.shape[1],
|
||||
max_current_start - current_start,
|
||||
)
|
||||
prefix_mask = torch.cat([prefix_mask, prefix_pad], dim=2)
|
||||
current_mask = torch.index_select(query_mask, dim=2, index=position_ids_i.reshape(-1))
|
||||
mask_list.append(torch.cat([prefix_mask, current_mask], dim=2))
|
||||
attention_mask = torch.stack(mask_list, dim=0)
|
||||
updated_model_kwargs["attention_mask"] = attention_mask
|
||||
updated_model_kwargs["gen_timestep_scatter_index"] = model_kwargs["gen_timestep_scatter_index"]
|
||||
@@ -1219,9 +1234,14 @@ class HunyuanImage3Pipeline(
|
||||
)
|
||||
custom_pos_emb = self.get_pos_emb(custom_pos_emb, position_ids)
|
||||
|
||||
inputs_embeds = self.model.embed_tokens(input_ids)
|
||||
|
||||
bsz, seq_len, n_embd = inputs_embeds.shape
|
||||
if input_ids is not None:
|
||||
inputs_embeds = self.model.embed_tokens(input_ids)
|
||||
bsz, seq_len, n_embd = inputs_embeds.shape
|
||||
else:
|
||||
inputs_embeds = None
|
||||
bsz = images.shape[0] if isinstance(images, torch.Tensor) else len(images)
|
||||
seq_len = 0
|
||||
n_embd = self.config.hidden_size
|
||||
|
||||
# Instantiate placeholder tokens: <timestep>, <img> for the gen image
|
||||
if mode == "gen_text":
|
||||
@@ -1232,6 +1252,7 @@ class HunyuanImage3Pipeline(
|
||||
token_h, token_w = None, None
|
||||
else:
|
||||
if first_step:
|
||||
assert inputs_embeds is not None
|
||||
inputs_embeds, token_h, token_w = self.instantiate_vae_image_tokens(
|
||||
inputs_embeds, images, timestep, image_mask
|
||||
)
|
||||
@@ -1253,6 +1274,8 @@ class HunyuanImage3Pipeline(
|
||||
inputs_embeds = self.instantiate_vit_image_tokens(
|
||||
inputs_embeds, cond_vit_images, cond_vit_image_mask, vit_kwargs
|
||||
)
|
||||
assert inputs_embeds is not None
|
||||
bsz, seq_len, n_embd = inputs_embeds.shape
|
||||
|
||||
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
||||
from vllm.forward_context import set_forward_context
|
||||
@@ -1291,7 +1314,7 @@ class HunyuanImage3Pipeline(
|
||||
diffusion_prediction = None
|
||||
else:
|
||||
logits = None
|
||||
hidden_states = hidden_states.to(input_ids.device)
|
||||
hidden_states = hidden_states.to(inputs_embeds.device)
|
||||
assert hidden_states.numel() == bsz * seq_len * n_embd, (
|
||||
f"Shape mismatch: {hidden_states.shape} cannot reshape to ({bsz}, {seq_len}, {n_embd})"
|
||||
)
|
||||
|
||||
@@ -146,6 +146,7 @@ def resolve_stop_token_ids(
|
||||
task: str = "it2i",
|
||||
bot_task: str | None | _DefaultBotTask = _DEFAULT_BOT_TASK,
|
||||
tokenizer: Any | None = None,
|
||||
image_size: str | None = None,
|
||||
) -> list[int]:
|
||||
"""AR stop-token ids for a given (task, bot_task) generation request.
|
||||
|
||||
@@ -171,6 +172,14 @@ def resolve_stop_token_ids(
|
||||
if bot_task not in _BOT_TASK_PRESETS:
|
||||
raise ValueError(f"Unknown bot_task {bot_task!r}. Choose from: {available_bot_tasks()}")
|
||||
if task in ("it2i", "t2i"):
|
||||
need_ratio = image_size is None or image_size == "auto"
|
||||
if not need_ratio:
|
||||
end_of_think_id = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["</think>"]
|
||||
end_of_recaption_id = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["</recaption>"]
|
||||
if bot_task in ("think_recaption", "recaption"):
|
||||
return [end_of_recaption_id]
|
||||
if bot_task == "think":
|
||||
return [end_of_think_id, end_of_recaption_id]
|
||||
# Main ratio range: <img_ratio_0> .. <img_ratio_32>.
|
||||
start = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["<img_ratio_0>"]
|
||||
end = HUNYUAN_IMAGE3_SPECIAL_TOKEN_IDS["<img_ratio_32>"]
|
||||
@@ -219,7 +228,7 @@ def build_prompt(
|
||||
effective_sys_type = sys_type or preset_sys_type
|
||||
|
||||
system_prompt = get_system_prompt(effective_sys_type, bot_task, custom_system_prompt)
|
||||
sys_text = system_prompt or ""
|
||||
sys_text = system_prompt.strip() if system_prompt is not None else ""
|
||||
|
||||
has_image_input = task in ("i2t", "it2i")
|
||||
if has_image_input:
|
||||
@@ -288,7 +297,7 @@ def build_prompt_tokens(
|
||||
)
|
||||
|
||||
system_prompt = get_system_prompt(effective_sys_type, bot_task, custom_system_prompt)
|
||||
sys_text = system_prompt or ""
|
||||
sys_text = system_prompt.strip() if system_prompt is not None else ""
|
||||
|
||||
ids: list[int] = [bos_id]
|
||||
if sys_text:
|
||||
|
||||
@@ -762,7 +762,13 @@ class HunyuanVideo15Transformer3DModel(nn.Module):
|
||||
encoder_hidden_states = torch.stack(new_encoder_hidden_states)
|
||||
encoder_attention_mask = torch.stack(new_encoder_attention_mask)
|
||||
|
||||
# Create explicit attn_mask for image tokens when SP auto_pad is active.
|
||||
max_valid_encoder_tokens = int(encoder_attention_mask.sum(dim=1).max().item())
|
||||
if max_valid_encoder_tokens < encoder_attention_mask.shape[1]:
|
||||
encoder_hidden_states = encoder_hidden_states[:, :max_valid_encoder_tokens]
|
||||
encoder_attention_mask = encoder_attention_mask[:, :max_valid_encoder_tokens]
|
||||
if encoder_attention_mask.all():
|
||||
encoder_attention_mask = None
|
||||
|
||||
ctx = get_forward_context()
|
||||
hidden_states_mask = None
|
||||
if ctx.sp_original_seq_len is not None and ctx.sp_padding_size > 0:
|
||||
@@ -830,9 +836,10 @@ class HunyuanVideo15Transformer3DModel(nn.Module):
|
||||
for param_name, weight_name, shard_id in stacked_params_mapping:
|
||||
if weight_name not in original_name:
|
||||
continue
|
||||
lookup_name = original_name.replace(weight_name, param_name)
|
||||
if lookup_name not in params_dict:
|
||||
break
|
||||
maybe_lookup_name = original_name.replace(weight_name, param_name)
|
||||
if maybe_lookup_name not in params_dict:
|
||||
continue
|
||||
lookup_name = maybe_lookup_name
|
||||
param = params_dict[lookup_name]
|
||||
weight_loader = param.weight_loader
|
||||
weight_loader(param, loaded_weight, shard_id)
|
||||
|
||||
@@ -11,7 +11,6 @@ from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from diffusers import AutoencoderKLHunyuanVideo15
|
||||
from diffusers.schedulers.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
@@ -20,6 +19,9 @@ from transformers import AutoConfig, ByT5Tokenizer, Qwen2_5_VLTextModel, Qwen2To
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_hunyuan_video_15 import (
|
||||
DistributedAutoencoderKLHunyuanVideo15,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
@@ -110,7 +112,7 @@ class HunyuanVideo15Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, Diff
|
||||
t5_config = AutoConfig.from_pretrained(model, subfolder="text_encoder_2", local_files_only=local_files_only)
|
||||
self.text_encoder_2 = T5EncoderModel(t5_config, prefix="text_encoder_2").to(dtype=dtype, device=self.device)
|
||||
|
||||
self.vae = AutoencoderKLHunyuanVideo15.from_pretrained(
|
||||
self.vae = DistributedAutoencoderKLHunyuanVideo15.from_pretrained(
|
||||
model, subfolder="vae", torch_dtype=torch.float32, local_files_only=local_files_only
|
||||
).to(self.device)
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ from typing import Any, cast
|
||||
import numpy as np
|
||||
import PIL.Image
|
||||
import torch
|
||||
from diffusers import AutoencoderKLHunyuanVideo15
|
||||
from diffusers.schedulers.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteScheduler
|
||||
from diffusers.utils.torch_utils import randn_tensor
|
||||
from diffusers.video_processor import VideoProcessor
|
||||
@@ -27,6 +26,9 @@ from transformers import (
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_hunyuan_video_15 import (
|
||||
DistributedAutoencoderKLHunyuanVideo15,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
@@ -139,7 +141,7 @@ class HunyuanVideo15I2VPipeline(
|
||||
model, subfolder="feature_extractor", local_files_only=local_files_only
|
||||
)
|
||||
|
||||
self.vae = AutoencoderKLHunyuanVideo15.from_pretrained(
|
||||
self.vae = DistributedAutoencoderKLHunyuanVideo15.from_pretrained(
|
||||
model, subfolder="vae", torch_dtype=torch.float32, local_files_only=local_files_only
|
||||
).to(self.device)
|
||||
|
||||
|
||||
@@ -67,13 +67,20 @@ def _make_rms_norm(hidden_size: int, *, eps: float, elementwise_affine: bool) ->
|
||||
|
||||
def apply_interleaved_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
|
||||
cos, sin = freqs
|
||||
x_real, x_imag = x.unflatten(2, (-1, 2)).unbind(-1) # [B, S, C // 2]
|
||||
# Concrete pair count instead of -1 keeps SDPA shape static under torch.compile.
|
||||
x_real, x_imag = x.unflatten(2, (x.shape[2] // 2, 2)).unbind(-1) # [B, S, C // 2]
|
||||
x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(2)
|
||||
out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
|
||||
return out
|
||||
|
||||
|
||||
def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
|
||||
def apply_split_rotary_emb(
|
||||
x: torch.Tensor,
|
||||
freqs: tuple[torch.Tensor, torch.Tensor],
|
||||
*,
|
||||
head_dim: int,
|
||||
) -> torch.Tensor:
|
||||
# `head_dim` is plumbed in (not inferred via `-1`) so SDPA shape stays static under torch.compile.
|
||||
cos, sin = freqs
|
||||
|
||||
x_dtype = x.dtype
|
||||
@@ -83,7 +90,7 @@ def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Ten
|
||||
# The cos/sin batch dim may only be broadcastable, so take batch size from x
|
||||
b = x.shape[0]
|
||||
_, h, t, _ = cos.shape
|
||||
x = x.reshape(b, t, h, -1).swapaxes(1, 2)
|
||||
x = x.reshape(b, t, h, head_dim).swapaxes(1, 2)
|
||||
needs_reshape = True
|
||||
|
||||
# Split last dim (2*r) into (d=2, r)
|
||||
@@ -110,7 +117,7 @@ def apply_split_rotary_emb(x: torch.Tensor, freqs: tuple[torch.Tensor, torch.Ten
|
||||
out = out.reshape(*out.shape[:-2], last)
|
||||
|
||||
if needs_reshape:
|
||||
out = out.swapaxes(1, 2).reshape(b, t, -1)
|
||||
out = out.swapaxes(1, 2).reshape(b, t, h * head_dim)
|
||||
|
||||
out = out.to(dtype=x_dtype)
|
||||
return out
|
||||
@@ -488,12 +495,14 @@ class LTX2AudioVideoAttnProcessor:
|
||||
key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb
|
||||
)
|
||||
elif attn.rope_type == "split":
|
||||
query = apply_split_rotary_emb(query, query_rotary_emb)
|
||||
key = apply_split_rotary_emb(key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb)
|
||||
query = apply_split_rotary_emb(query, query_rotary_emb, head_dim=attn.head_dim)
|
||||
key = apply_split_rotary_emb(
|
||||
key, key_rotary_emb if key_rotary_emb is not None else query_rotary_emb, head_dim=attn.head_dim
|
||||
)
|
||||
|
||||
query = query.unflatten(2, (attn.heads, -1))
|
||||
key = key.unflatten(2, (attn.heads, -1))
|
||||
value = value.unflatten(2, (attn.heads, -1))
|
||||
query = query.unflatten(2, (attn.heads, attn.head_dim))
|
||||
key = key.unflatten(2, (attn.heads, attn.head_dim))
|
||||
value = value.unflatten(2, (attn.heads, attn.head_dim))
|
||||
|
||||
attn_metadata = AttentionMetadata(attn_mask=attention_mask) if attention_mask is not None else None
|
||||
hidden_states = attn.attn(query, key, value, attn_metadata)
|
||||
@@ -502,7 +511,7 @@ class LTX2AudioVideoAttnProcessor:
|
||||
|
||||
# LTX-2.3: per-head gated attention
|
||||
if attn.to_gate_logits is not None:
|
||||
hidden_states = hidden_states.unflatten(2, (attn.heads, -1)) # [B, T, H, D]
|
||||
hidden_states = hidden_states.unflatten(2, (attn.heads, attn.head_dim)) # [B, T, H, D]
|
||||
# 2.0 * sigmoid so zero-init gates produce 1.0 (identity)
|
||||
gates = 2.0 * torch.sigmoid(gate_logits) # [B, T, H]
|
||||
hidden_states = hidden_states * gates.unsqueeze(-1)
|
||||
@@ -1391,9 +1400,11 @@ class LTX2AudioVideoRotaryPosEmbed(nn.Module):
|
||||
# Reshape freqs to be compatible with multi-head attention
|
||||
b = cos_freq.shape[0]
|
||||
t = cos_freq.shape[1]
|
||||
# Concrete per-head dim instead of -1 — see apply_split_rotary_emb
|
||||
r = self.dim // self.num_attention_heads // 2
|
||||
|
||||
cos_freq = cos_freq.reshape(b, t, self.num_attention_heads, -1)
|
||||
sin_freq = sin_freq.reshape(b, t, self.num_attention_heads, -1)
|
||||
cos_freq = cos_freq.reshape(b, t, self.num_attention_heads, r)
|
||||
sin_freq = sin_freq.reshape(b, t, self.num_attention_heads, r)
|
||||
|
||||
cos_freqs = torch.swapaxes(cos_freq, 1, 2) # (B,H,T,D//2)
|
||||
sin_freqs = torch.swapaxes(sin_freq, 1, 2) # (B,H,T,D//2)
|
||||
@@ -1939,10 +1950,6 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
# 5. Run transformer blocks
|
||||
for block in self.transformer_blocks:
|
||||
block_kwargs = {
|
||||
"hidden_states": hidden_states,
|
||||
"audio_hidden_states": audio_hidden_states,
|
||||
"encoder_hidden_states": encoder_hidden_states,
|
||||
"audio_encoder_hidden_states": audio_encoder_hidden_states,
|
||||
"temb": temb,
|
||||
"temb_audio": temb_audio,
|
||||
"temb_ca_scale_shift": video_cross_attn_scale_shift,
|
||||
@@ -1958,11 +1965,27 @@ class LTX2VideoTransformer3DModel(nn.Module):
|
||||
"encoder_attention_mask": encoder_attention_mask,
|
||||
"audio_encoder_attention_mask": audio_encoder_attention_mask,
|
||||
}
|
||||
# NOTE: We intentionally pass the first 4 args here positionally,
|
||||
# because CacheDiT expects the first 2 args to be hidden_states
|
||||
# and encoder_hidden_states, so passing them as kwargs will cause
|
||||
# positional / keywords arg collisions.
|
||||
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
||||
hidden_states, audio_hidden_states = self._gradient_checkpointing_func(block, **block_kwargs)
|
||||
hidden_states, audio_hidden_states = self._gradient_checkpointing_func(
|
||||
block,
|
||||
hidden_states,
|
||||
audio_hidden_states,
|
||||
encoder_hidden_states,
|
||||
audio_encoder_hidden_states,
|
||||
**block_kwargs,
|
||||
)
|
||||
else:
|
||||
hidden_states, audio_hidden_states = block(**block_kwargs)
|
||||
|
||||
hidden_states, audio_hidden_states = block(
|
||||
hidden_states,
|
||||
audio_hidden_states,
|
||||
encoder_hidden_states,
|
||||
audio_encoder_hidden_states,
|
||||
**block_kwargs,
|
||||
)
|
||||
# 6. Output layers (including unpatchification)
|
||||
scale_shift_values = self.scale_shift_table[None, None] + embedded_timestep[:, :, None]
|
||||
shift, scale = scale_shift_values[:, :, 0], scale_shift_values[:, :, 1]
|
||||
|
||||
@@ -157,6 +157,9 @@ class _VideoAudioScheduler:
|
||||
|
||||
|
||||
class LTX2Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
|
||||
# Audio is diffused jointly with video; warmup must size audio tokens.
|
||||
dummy_run_num_frames = 2
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
@@ -1118,6 +1121,8 @@ class LTX2Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
|
||||
class LTX2TwoStagesPipeline(nn.Module, SupportsComponentDiscovery):
|
||||
"""LTX2TwoStagesPipeline is for two stages image to video generation"""
|
||||
|
||||
dummy_run_num_frames = 2
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = ["pipe.transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["pipe.text_encoder"]
|
||||
_vae_modules: ClassVar[list[str]] = ["pipe.vae", "pipe.audio_vae"]
|
||||
|
||||
@@ -37,6 +37,12 @@ from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
get_cfg_group,
|
||||
get_classifier_free_guidance_rank,
|
||||
get_classifier_free_guidance_world_size,
|
||||
)
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
|
||||
@@ -44,6 +50,7 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
|
||||
from .pipeline_ltx2 import (
|
||||
_get_prompt_field,
|
||||
_VideoAudioScheduler,
|
||||
calculate_shift,
|
||||
create_transformer_from_config,
|
||||
load_transformer_config,
|
||||
@@ -104,7 +111,7 @@ def get_ltx2_post_process_func(od_config: OmniDiffusionConfig):
|
||||
return post_process_func
|
||||
|
||||
|
||||
class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
class LTX23Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
|
||||
"""Fully independent LTX-2.3 pipeline.
|
||||
|
||||
Key differences from LTX2Pipeline:
|
||||
@@ -115,6 +122,9 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
- CPU offloading: text encoder, connectors, VAE, vocoder stay on CPU
|
||||
"""
|
||||
|
||||
# Audio is diffused jointly with video; warmup must size audio tokens.
|
||||
dummy_run_num_frames = 2
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
@@ -445,6 +455,26 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
def _unpad_audio_latents(latents: torch.Tensor, num_frames: int) -> torch.Tensor:
|
||||
return latents[:, :num_frames]
|
||||
|
||||
@staticmethod
|
||||
def _get_sp_padded_audio_latent_length(audio_latent_length: int, sp_size: int) -> int:
|
||||
if sp_size > 1:
|
||||
audio_latent_length += (sp_size - (audio_latent_length % sp_size)) % sp_size
|
||||
return audio_latent_length
|
||||
|
||||
def _resolve_audio_latent_length(self, audio_latent_length: int, audio_latents: torch.Tensor | None) -> int:
|
||||
if audio_latents is None or audio_latents.ndim != 4:
|
||||
return audio_latent_length
|
||||
|
||||
provided_latent_length = audio_latents.shape[2]
|
||||
sp_size = getattr(self.od_config.parallel_config, "sequence_parallel_size", 1) or 1
|
||||
padded_latent_length = self._get_sp_padded_audio_latent_length(audio_latent_length, int(sp_size))
|
||||
|
||||
# Keep requested duration semantics when callers pass 4D latents that
|
||||
# are already padded for SP; other 4D lengths retain shape inference.
|
||||
if provided_latent_length in {audio_latent_length, padded_latent_length}:
|
||||
return audio_latent_length
|
||||
return provided_latent_length
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Latent preparation
|
||||
# ------------------------------------------------------------------
|
||||
@@ -497,9 +527,11 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
latents: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, int, int]:
|
||||
original_latent_length = audio_latent_length
|
||||
padded_latent_length = original_latent_length
|
||||
latent_mel_bins = num_mel_bins // self.audio_vae_mel_compression_ratio
|
||||
|
||||
sp_size = getattr(self.od_config.parallel_config, "sequence_parallel_size", 1) or 1
|
||||
padded_latent_length = self._get_sp_padded_audio_latent_length(original_latent_length, int(sp_size))
|
||||
|
||||
if latents is not None:
|
||||
if latents.ndim == 4:
|
||||
latents = self._pack_audio_latents(latents)
|
||||
@@ -508,9 +540,32 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
latents = self._normalize_audio_latents(latents, self.audio_vae.latents_mean, self.audio_vae.latents_std)
|
||||
noise = randn_tensor(latents.shape, generator=generator, device=latents.device, dtype=latents.dtype)
|
||||
latents = noise_scale * noise + (1 - noise_scale) * latents
|
||||
|
||||
if latents.shape[1] not in {original_latent_length, padded_latent_length}:
|
||||
raise ValueError(
|
||||
"Provided `audio_latents` has incompatible audio frame count "
|
||||
f"{latents.shape[1]}; expected {original_latent_length} or {padded_latent_length}."
|
||||
)
|
||||
|
||||
if latents.shape[1] == original_latent_length and padded_latent_length > original_latent_length:
|
||||
padding = torch.zeros(
|
||||
latents.shape[0],
|
||||
padded_latent_length - original_latent_length,
|
||||
latents.shape[2],
|
||||
dtype=latents.dtype,
|
||||
device=latents.device,
|
||||
)
|
||||
latents = torch.cat([latents, padding], dim=1)
|
||||
|
||||
return latents.to(device=device, dtype=dtype), original_latent_length, padded_latent_length
|
||||
|
||||
shape = (batch_size, num_channels_latents, padded_latent_length, latent_mel_bins)
|
||||
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."
|
||||
)
|
||||
|
||||
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
||||
latents = self._pack_audio_latents(latents)
|
||||
return latents, original_latent_length, padded_latent_length
|
||||
@@ -593,6 +648,121 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
return cache_context(context_name)
|
||||
return nullcontext()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# CFG helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _combine_x0_space_cfg(
|
||||
sample: torch.Tensor,
|
||||
positive_noise_pred: torch.Tensor,
|
||||
negative_noise_pred: torch.Tensor,
|
||||
sigma: torch.Tensor,
|
||||
guidance_scale: float,
|
||||
) -> torch.Tensor:
|
||||
x0_cond = sample - positive_noise_pred * sigma
|
||||
x0_uncond = sample - negative_noise_pred * sigma
|
||||
x0_guided = x0_cond + (guidance_scale - 1) * (x0_cond - x0_uncond)
|
||||
return (sample - x0_guided) / sigma
|
||||
|
||||
def predict_noise(self, **kwargs):
|
||||
with self._transformer_cache_context("cond_uncond"):
|
||||
noise_pred_video, noise_pred_audio = self.transformer(**kwargs)
|
||||
return noise_pred_video.float(), noise_pred_audio.float()
|
||||
|
||||
def combine_cfg_noise(
|
||||
self,
|
||||
positive_noise_pred,
|
||||
negative_noise_pred,
|
||||
true_cfg_scale,
|
||||
cfg_normalize=False,
|
||||
*,
|
||||
video_latents: torch.Tensor | None = None,
|
||||
audio_latents: torch.Tensor | None = None,
|
||||
video_sigma: torch.Tensor | None = None,
|
||||
audio_sigma: torch.Tensor | None = None,
|
||||
):
|
||||
if video_latents is None or audio_latents is None or video_sigma is None or audio_sigma is None:
|
||||
raise ValueError("LTX23Pipeline applies CFG in x0-space and requires video/audio latents and sigmas.")
|
||||
|
||||
video_pos, audio_pos = positive_noise_pred
|
||||
video_neg, audio_neg = negative_noise_pred
|
||||
video_combined = self._combine_x0_space_cfg(
|
||||
video_latents,
|
||||
video_pos,
|
||||
video_neg,
|
||||
video_sigma,
|
||||
true_cfg_scale,
|
||||
)
|
||||
audio_combined = self._combine_x0_space_cfg(
|
||||
audio_latents,
|
||||
audio_pos,
|
||||
audio_neg,
|
||||
audio_sigma,
|
||||
true_cfg_scale,
|
||||
)
|
||||
if cfg_normalize:
|
||||
video_combined = self.cfg_normalize_function(video_pos, video_combined)
|
||||
audio_combined = self.cfg_normalize_function(audio_pos, audio_combined)
|
||||
return video_combined, audio_combined
|
||||
|
||||
def predict_noise_with_parallel_cfg(
|
||||
self,
|
||||
true_cfg_scale: float,
|
||||
positive_kwargs: dict[str, Any],
|
||||
negative_kwargs: dict[str, Any],
|
||||
cfg_normalize: bool = True,
|
||||
output_slice: int | None = None,
|
||||
*,
|
||||
video_latents: torch.Tensor | None = None,
|
||||
audio_latents: torch.Tensor | None = None,
|
||||
video_sigma: torch.Tensor | None = None,
|
||||
audio_sigma: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
def maybe_slice(pred: tuple[torch.Tensor, torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if output_slice is None:
|
||||
return pred
|
||||
return pred[0][:, :output_slice], pred[1][:, :output_slice]
|
||||
|
||||
cfg_world_size = get_classifier_free_guidance_world_size()
|
||||
if cfg_world_size != 2:
|
||||
raise ValueError(f"LTX23Pipeline parallel CFG requires cfg_parallel_size 2, but got {cfg_world_size}.")
|
||||
|
||||
cfg_group = get_cfg_group()
|
||||
cfg_rank = get_classifier_free_guidance_rank()
|
||||
branch_kwargs = positive_kwargs if cfg_rank == 0 else negative_kwargs
|
||||
local_video_pred, local_audio_pred = maybe_slice(self.predict_noise(**branch_kwargs))
|
||||
|
||||
gathered_video = cfg_group.all_gather(local_video_pred, separate_tensors=True)
|
||||
gathered_audio = cfg_group.all_gather(local_audio_pred, separate_tensors=True)
|
||||
positive_noise_pred = (gathered_video[0], gathered_audio[0])
|
||||
negative_noise_pred = (gathered_video[1], gathered_audio[1])
|
||||
|
||||
return self.combine_cfg_noise(
|
||||
positive_noise_pred,
|
||||
negative_noise_pred,
|
||||
true_cfg_scale,
|
||||
cfg_normalize,
|
||||
video_latents=video_latents,
|
||||
audio_latents=audio_latents,
|
||||
video_sigma=video_sigma,
|
||||
audio_sigma=audio_sigma,
|
||||
)
|
||||
|
||||
def _synchronize_cfg_parallel_step_output(
|
||||
self,
|
||||
latents: tuple[torch.Tensor, torch.Tensor],
|
||||
do_true_cfg: bool,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if not (do_true_cfg and get_classifier_free_guidance_world_size() > 1):
|
||||
return latents
|
||||
|
||||
latents = tuple(tensor.contiguous() for tensor in latents)
|
||||
device = next((tensor.device for tensor in latents if tensor.is_cuda), None)
|
||||
if device is not None:
|
||||
torch.cuda.current_stream(device).synchronize()
|
||||
return latents
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Forward pass
|
||||
# ------------------------------------------------------------------
|
||||
@@ -711,6 +881,12 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
self._attention_kwargs = attention_kwargs
|
||||
self._interrupt = False
|
||||
self._current_timestep = None
|
||||
cfg_world_size = get_classifier_free_guidance_world_size()
|
||||
if self.do_classifier_free_guidance and cfg_world_size not in (1, 2):
|
||||
raise ValueError(
|
||||
f"LTX23Pipeline supports CFG parallelism with cfg_parallel_size 1 or 2, but got {cfg_world_size}."
|
||||
)
|
||||
cfg_parallel_ready = self.do_classifier_free_guidance and cfg_world_size > 1
|
||||
|
||||
if prompt is not None and isinstance(prompt, str):
|
||||
batch_size = 1
|
||||
@@ -757,6 +933,21 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
if torch.cuda.is_available():
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
positive_connector_prompt_embeds = connector_prompt_embeds
|
||||
positive_connector_audio_prompt_embeds = connector_audio_prompt_embeds
|
||||
positive_connector_attention_mask = connector_attention_mask
|
||||
negative_connector_prompt_embeds = None
|
||||
negative_connector_audio_prompt_embeds = None
|
||||
negative_connector_attention_mask = None
|
||||
if self.do_classifier_free_guidance:
|
||||
split_batch = batch_size * num_videos_per_prompt
|
||||
negative_connector_prompt_embeds = connector_prompt_embeds[:split_batch]
|
||||
positive_connector_prompt_embeds = connector_prompt_embeds[split_batch:]
|
||||
negative_connector_audio_prompt_embeds = connector_audio_prompt_embeds[:split_batch]
|
||||
positive_connector_audio_prompt_embeds = connector_audio_prompt_embeds[split_batch:]
|
||||
negative_connector_attention_mask = connector_attention_mask[:split_batch]
|
||||
positive_connector_attention_mask = connector_attention_mask[split_batch:]
|
||||
|
||||
# ---- Prepare latents ----
|
||||
latent_num_frames = (num_frames - 1) // self.vae_temporal_compression_ratio + 1
|
||||
latent_height = height // self.vae_spatial_compression_ratio
|
||||
@@ -783,8 +974,7 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
self.audio_sampling_rate / self.audio_hop_length / float(self.audio_vae_temporal_compression_ratio)
|
||||
)
|
||||
audio_num_frames = round(duration_s * audio_latents_per_second)
|
||||
if audio_latents is not None and audio_latents.ndim == 4:
|
||||
_, _, audio_num_frames, _ = audio_latents.shape
|
||||
audio_num_frames = self._resolve_audio_latent_length(audio_num_frames, audio_latents)
|
||||
|
||||
num_mel_bins = self.audio_vae.config.mel_bins if self.audio_vae is not None else 64
|
||||
latent_mel_bins = num_mel_bins // self.audio_vae_mel_compression_ratio
|
||||
@@ -813,6 +1003,7 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
self.scheduler.config.get("max_shift", 2.05),
|
||||
)
|
||||
audio_scheduler = copy.deepcopy(self.scheduler)
|
||||
video_audio_scheduler = _VideoAudioScheduler(self.scheduler, audio_scheduler)
|
||||
_ = retrieve_timesteps(audio_scheduler, num_inference_steps, device, timesteps, sigmas=sigmas, mu=mu)
|
||||
timesteps, num_inference_steps = retrieve_timesteps(
|
||||
self.scheduler,
|
||||
@@ -839,9 +1030,9 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
audio_latents.device,
|
||||
)
|
||||
|
||||
# ---- CFG: duplicate coords for batch=2 ----
|
||||
# ---- CFG: duplicate coords for single-rank batch=2 CFG ----
|
||||
# Connector outputs are already batch=2 (neg+pos concatenated before connector call)
|
||||
if self.do_classifier_free_guidance:
|
||||
if self.do_classifier_free_guidance and not cfg_parallel_ready:
|
||||
video_coords = video_coords.repeat((2,) + (1,) * (video_coords.ndim - 1))
|
||||
audio_coords = audio_coords.repeat((2,) + (1,) * (audio_coords.ndim - 1))
|
||||
|
||||
@@ -856,60 +1047,112 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
|
||||
|
||||
self._current_timestep = t
|
||||
|
||||
# Duplicate latents for CFG (uncond + cond)
|
||||
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
||||
latent_model_input = latent_model_input.to(connector_prompt_embeds.dtype)
|
||||
audio_latent_model_input = (
|
||||
torch.cat([audio_latents] * 2) if self.do_classifier_free_guidance else audio_latents
|
||||
)
|
||||
audio_latent_model_input = audio_latent_model_input.to(connector_prompt_embeds.dtype)
|
||||
ts = t.expand(latent_model_input.shape[0])
|
||||
|
||||
with self._transformer_cache_context("cond_uncond"):
|
||||
noise_pred_video, noise_pred_audio = self.transformer(
|
||||
hidden_states=latent_model_input,
|
||||
audio_hidden_states=audio_latent_model_input,
|
||||
encoder_hidden_states=connector_prompt_embeds,
|
||||
audio_encoder_hidden_states=connector_audio_prompt_embeds,
|
||||
timestep=ts,
|
||||
sigma=ts, # LTX-2.3: sigma for prompt_adaln
|
||||
encoder_attention_mask=connector_attention_mask,
|
||||
audio_encoder_attention_mask=connector_attention_mask,
|
||||
num_frames=latent_num_frames,
|
||||
height=latent_height,
|
||||
width=latent_width,
|
||||
fps=frame_rate,
|
||||
audio_num_frames=padded_audio_num_frames,
|
||||
video_coords=video_coords,
|
||||
audio_coords=audio_coords,
|
||||
attention_kwargs=attention_kwargs,
|
||||
return_dict=False,
|
||||
if cfg_parallel_ready:
|
||||
latent_model_input = latents.to(positive_connector_prompt_embeds.dtype)
|
||||
audio_latent_model_input = audio_latents.to(positive_connector_prompt_embeds.dtype)
|
||||
ts = t.expand(latent_model_input.shape[0])
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"audio_hidden_states": audio_latent_model_input,
|
||||
"encoder_hidden_states": positive_connector_prompt_embeds,
|
||||
"audio_encoder_hidden_states": positive_connector_audio_prompt_embeds,
|
||||
"timestep": ts,
|
||||
"sigma": ts,
|
||||
"encoder_attention_mask": positive_connector_attention_mask,
|
||||
"audio_encoder_attention_mask": positive_connector_attention_mask,
|
||||
"num_frames": latent_num_frames,
|
||||
"height": latent_height,
|
||||
"width": latent_width,
|
||||
"fps": frame_rate,
|
||||
"audio_num_frames": padded_audio_num_frames,
|
||||
"video_coords": video_coords,
|
||||
"audio_coords": audio_coords,
|
||||
"attention_kwargs": attention_kwargs,
|
||||
"return_dict": False,
|
||||
}
|
||||
negative_kwargs = {
|
||||
**positive_kwargs,
|
||||
"encoder_hidden_states": negative_connector_prompt_embeds,
|
||||
"audio_encoder_hidden_states": negative_connector_audio_prompt_embeds,
|
||||
"encoder_attention_mask": negative_connector_attention_mask,
|
||||
"audio_encoder_attention_mask": negative_connector_attention_mask,
|
||||
}
|
||||
noise_pred_video, noise_pred_audio = self.predict_noise_with_parallel_cfg(
|
||||
true_cfg_scale=guidance_scale,
|
||||
positive_kwargs=positive_kwargs,
|
||||
negative_kwargs=negative_kwargs,
|
||||
cfg_normalize=False,
|
||||
video_latents=latents,
|
||||
audio_latents=audio_latents,
|
||||
video_sigma=self.scheduler.sigmas[i],
|
||||
audio_sigma=audio_scheduler.sigmas[i],
|
||||
)
|
||||
|
||||
noise_pred_video = noise_pred_video.float()
|
||||
noise_pred_audio = noise_pred_audio.float()
|
||||
latents, audio_latents = self.scheduler_step_maybe_with_cfg(
|
||||
(noise_pred_video, noise_pred_audio),
|
||||
(t, t),
|
||||
(latents, audio_latents),
|
||||
do_true_cfg=self.do_classifier_free_guidance,
|
||||
per_request_scheduler=video_audio_scheduler,
|
||||
)
|
||||
latents, audio_latents = self._synchronize_cfg_parallel_step_output(
|
||||
(latents, audio_latents),
|
||||
do_true_cfg=self.do_classifier_free_guidance,
|
||||
)
|
||||
else:
|
||||
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
||||
latent_model_input = latent_model_input.to(connector_prompt_embeds.dtype)
|
||||
audio_latent_model_input = (
|
||||
torch.cat([audio_latents] * 2) if self.do_classifier_free_guidance else audio_latents
|
||||
)
|
||||
audio_latent_model_input = audio_latent_model_input.to(connector_prompt_embeds.dtype)
|
||||
ts = t.expand(latent_model_input.shape[0])
|
||||
|
||||
# CFG in x0-space (delta formulation matching diffusers)
|
||||
if self.do_classifier_free_guidance:
|
||||
noise_pred_video_uncond, noise_pred_video_cond = noise_pred_video.chunk(2)
|
||||
# Convert velocity to x0: x0 = sample - velocity * sigma
|
||||
x0_video_cond = latents - noise_pred_video_cond * self.scheduler.sigmas[i]
|
||||
x0_video_uncond = latents - noise_pred_video_uncond * self.scheduler.sigmas[i]
|
||||
video_cfg_delta = (guidance_scale - 1) * (x0_video_cond - x0_video_uncond)
|
||||
x0_video_guided = x0_video_cond + video_cfg_delta
|
||||
with self._transformer_cache_context("cond_uncond"):
|
||||
noise_pred_video, noise_pred_audio = self.transformer(
|
||||
hidden_states=latent_model_input,
|
||||
audio_hidden_states=audio_latent_model_input,
|
||||
encoder_hidden_states=connector_prompt_embeds,
|
||||
audio_encoder_hidden_states=connector_audio_prompt_embeds,
|
||||
timestep=ts,
|
||||
sigma=ts, # LTX-2.3: sigma for prompt_adaln
|
||||
encoder_attention_mask=connector_attention_mask,
|
||||
audio_encoder_attention_mask=connector_attention_mask,
|
||||
num_frames=latent_num_frames,
|
||||
height=latent_height,
|
||||
width=latent_width,
|
||||
fps=frame_rate,
|
||||
audio_num_frames=padded_audio_num_frames,
|
||||
video_coords=video_coords,
|
||||
audio_coords=audio_coords,
|
||||
attention_kwargs=attention_kwargs,
|
||||
return_dict=False,
|
||||
)
|
||||
|
||||
noise_pred_audio_uncond, noise_pred_audio_cond = noise_pred_audio.chunk(2)
|
||||
x0_audio_cond = audio_latents - noise_pred_audio_cond * audio_scheduler.sigmas[i]
|
||||
x0_audio_uncond = audio_latents - noise_pred_audio_uncond * audio_scheduler.sigmas[i]
|
||||
audio_cfg_delta = (guidance_scale - 1) * (x0_audio_cond - x0_audio_uncond)
|
||||
x0_audio_guided = x0_audio_cond + audio_cfg_delta
|
||||
noise_pred_video = noise_pred_video.float()
|
||||
noise_pred_audio = noise_pred_audio.float()
|
||||
|
||||
# Convert x0 back to velocity: v = (sample - x0) / sigma
|
||||
noise_pred_video = (latents - x0_video_guided) / self.scheduler.sigmas[i]
|
||||
noise_pred_audio = (audio_latents - x0_audio_guided) / audio_scheduler.sigmas[i]
|
||||
if self.do_classifier_free_guidance:
|
||||
noise_pred_video_uncond, noise_pred_video_cond = noise_pred_video.chunk(2)
|
||||
noise_pred_video = self._combine_x0_space_cfg(
|
||||
latents,
|
||||
noise_pred_video_cond,
|
||||
noise_pred_video_uncond,
|
||||
self.scheduler.sigmas[i],
|
||||
guidance_scale,
|
||||
)
|
||||
|
||||
latents = self.scheduler.step(noise_pred_video, t, latents, return_dict=False)[0]
|
||||
audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0]
|
||||
noise_pred_audio_uncond, noise_pred_audio_cond = noise_pred_audio.chunk(2)
|
||||
noise_pred_audio = self._combine_x0_space_cfg(
|
||||
audio_latents,
|
||||
noise_pred_audio_cond,
|
||||
noise_pred_audio_uncond,
|
||||
audio_scheduler.sigmas[i],
|
||||
guidance_scale,
|
||||
)
|
||||
|
||||
latents = self.scheduler.step(noise_pred_video, t, latents, return_dict=False)[0]
|
||||
audio_latents = audio_scheduler.step(noise_pred_audio, t, audio_latents, return_dict=False)[0]
|
||||
|
||||
pbar.update()
|
||||
|
||||
|
||||
@@ -735,6 +735,7 @@ class LTX2ImageToVideoTwoStagesPipeline(nn.Module, SupportsComponentDiscovery):
|
||||
"""LTXImageToVideoTwoStagesPipeline is for two stages image to video generation"""
|
||||
|
||||
support_image_input = True
|
||||
dummy_run_num_frames = 2
|
||||
|
||||
_dit_modules: ClassVar[list[str]] = ["pipe.transformer"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["pipe.text_encoder"]
|
||||
|
||||
@@ -2130,6 +2130,28 @@ class MagiHumanPipeline(nn.Module, ProgressBarMixin, DiffusionPipelineProfilerMi
|
||||
|
||||
return resample(audio_np, target_len)
|
||||
|
||||
def encode_prompt(
|
||||
self,
|
||||
prompt: str,
|
||||
target_length: int | None = None,
|
||||
) -> tuple[torch.Tensor, int]:
|
||||
"""Encode *prompt* with the T5-Gemma text encoder and pad to fixed length.
|
||||
|
||||
This is the single text-encoder entrypoint so the runner-level
|
||||
prompt-embedding cache (see
|
||||
``vllm_omni/diffusion/cache/prompt_embed_cache.py``) can transparently
|
||||
memoize results when the same prompt is submitted repeatedly.
|
||||
|
||||
Returns:
|
||||
``(context, original_context_len)`` matching
|
||||
:func:`_get_padded_t5_gemma_embedding`.
|
||||
"""
|
||||
return _get_padded_t5_gemma_embedding(
|
||||
prompt,
|
||||
self.text_encoder,
|
||||
target_length if target_length is not None else self.t5_gemma_target_length,
|
||||
)
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(
|
||||
self,
|
||||
@@ -2200,11 +2222,7 @@ class MagiHumanPipeline(nn.Module, ProgressBarMixin, DiffusionPipelineProfilerMi
|
||||
device=device,
|
||||
)
|
||||
|
||||
context, original_context_len = _get_padded_t5_gemma_embedding(
|
||||
prompt,
|
||||
self.text_encoder,
|
||||
self.t5_gemma_target_length,
|
||||
)
|
||||
context, original_context_len = self.encode_prompt(prompt)
|
||||
|
||||
if image_path is not None:
|
||||
br_image = self._encode_image(load_image(image_path), br_height, br_width)
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2025 The vLLM-Omni team.
|
||||
|
||||
from .byte5_encoder import MingByT5Encoder
|
||||
from .condition_encoder import MingConditionEncoder
|
||||
from .ming_zimage_transformer import MingZImageTransformer2DModel
|
||||
from .pipeline_ming_imagegen import (
|
||||
MingImagePipeline,
|
||||
get_ming_image_post_process_func,
|
||||
)
|
||||
from .t5_block_mapper import T5EncoderBlockByT5Mapper
|
||||
|
||||
__all__ = [
|
||||
"MingByT5Encoder",
|
||||
"MingConditionEncoder",
|
||||
"MingImagePipeline",
|
||||
"MingZImageTransformer2DModel",
|
||||
"T5EncoderBlockByT5Mapper",
|
||||
"get_ming_image_post_process_func",
|
||||
]
|
||||
@@ -0,0 +1,223 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2025 The vLLM-Omni team.
|
||||
|
||||
"""ByT5 glyph/text encoder for Ming-flash-omni-2.0 image generation.
|
||||
|
||||
Ported from Ming's ``load_byte5_and_byte5_tokenizer`` +
|
||||
``T5EncoderBlockByT5Mapper`` + ``get_condition_embeds_for_image_gen`` byte5
|
||||
branch. The released checkpoint's byte5 weights were trained with font/color
|
||||
special tokens, so we replicate that vocabulary extension before loading —
|
||||
otherwise ``byte5_model.pt`` would shape-mismatch at the embedding layer.
|
||||
|
||||
Typical forward: takes a list of user-supplied prompt strings (possibly with
|
||||
``<cn-font-N>`` / ``<color-N>`` markers), returns ``[B, byte5_max_length,
|
||||
diffusion_c_input_dim]`` features ready to be concatenated onto cap_feats
|
||||
along the sequence dimension.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from transformers import AutoTokenizer, T5ForConditionalGeneration
|
||||
|
||||
from vllm_omni.diffusion.models.ming_flash_omni.t5_block_mapper import (
|
||||
T5EncoderBlockByT5Mapper,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _add_multilingual_special_tokens(
|
||||
tokenizer,
|
||||
text_encoder: nn.Module,
|
||||
font_ann_path: Path,
|
||||
color_ann_path: Path,
|
||||
add_font: bool,
|
||||
add_color: bool,
|
||||
add_align: bool = False,
|
||||
) -> None:
|
||||
"""Extend the byte5 vocab with per-language font + color markers.
|
||||
|
||||
Mirrors ``add_special_token_multilingual`` in Ming's bizgen utils. The token
|
||||
set must match the one the checkpoint was trained with, otherwise the
|
||||
resized embedding table shape won't line up with the shipped weights.
|
||||
"""
|
||||
idx_font_dict = json.loads(font_ann_path.read_text())
|
||||
idx_color_dict = json.loads(color_ann_path.read_text())
|
||||
|
||||
font_tokens: list[str] = []
|
||||
for font_code in idx_font_dict:
|
||||
prefix = font_code[:3]
|
||||
if prefix in ("cn-", "en-", "jp-", "kr-"):
|
||||
font_tokens.append(f"<{prefix}font-{idx_font_dict[font_code]}>")
|
||||
else:
|
||||
font_tokens.append(f"<font-{idx_font_dict[font_code]}>")
|
||||
color_tokens = [f"<color-{i}>" for i in range(len(idx_color_dict))]
|
||||
align_tokens = [f"<align-{i}>" for i in range(3)]
|
||||
|
||||
extra: list[str] = []
|
||||
if add_color:
|
||||
extra += color_tokens
|
||||
if add_font:
|
||||
extra += font_tokens
|
||||
if add_align:
|
||||
extra += align_tokens
|
||||
tokenizer.add_tokens(extra, special_tokens=True)
|
||||
text_encoder.resize_token_embeddings(len(tokenizer))
|
||||
|
||||
|
||||
class MingByT5Encoder(nn.Module):
|
||||
"""Bundles byte5 tokenizer + T5 encoder + T5EncoderBlockByT5Mapper.
|
||||
|
||||
Build with ``MingByT5Encoder.from_checkpoint(<model>/byte5)`` when the
|
||||
checkpoint ships byte5 weights; otherwise callers can skip this and the
|
||||
pipeline falls back to no-byte5 conditioning.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
tokenizer,
|
||||
text_encoder: nn.Module,
|
||||
mapper: T5EncoderBlockByT5Mapper,
|
||||
max_length: int,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.tokenizer = tokenizer
|
||||
self.text_encoder = text_encoder
|
||||
self.mapper = mapper
|
||||
self.max_length = max_length
|
||||
|
||||
@classmethod
|
||||
def from_checkpoint(
|
||||
cls,
|
||||
byte5_dir: Path,
|
||||
*,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> MingByT5Encoder:
|
||||
# Wrap the whole load in fork_rng so any nn.init.normal_ inside
|
||||
# T5ForConditionalGeneration.from_pretrained / vocab-resize cannot
|
||||
# advance the default CPU/CUDA generator state. Without this, the
|
||||
# diffusion pipeline's seeded noise becomes order-dependent across
|
||||
# requests (same-seed replays diverge).
|
||||
cuda_devs = list(range(torch.accelerator.device_count())) if torch.cuda.is_available() else []
|
||||
with torch.random.fork_rng(devices=cuda_devs, enabled=True):
|
||||
return cls._from_checkpoint_impl(byte5_dir, device=device, dtype=dtype)
|
||||
|
||||
@classmethod
|
||||
def _from_checkpoint_impl(
|
||||
cls,
|
||||
byte5_dir: Path,
|
||||
*,
|
||||
device: torch.device,
|
||||
dtype: torch.dtype,
|
||||
) -> MingByT5Encoder:
|
||||
byte5_dir = Path(byte5_dir)
|
||||
# Ming checkpoint uses ``byt5`` (no 'e') in filenames and JSON keys
|
||||
# variable names below keep the ``byte5_`` spelling for readability.
|
||||
cfg_path = byte5_dir / "byt5.json"
|
||||
cfg_raw = json.loads(cfg_path.read_text())
|
||||
cfg = SimpleNamespace(**cfg_raw)
|
||||
byte5_config = cfg.byt5_config
|
||||
mapper_config = cfg.byt5_mapper_config
|
||||
max_length = int(cfg.byt5_max_length)
|
||||
|
||||
# ---- Tokenizer + T5 encoder (base).
|
||||
ckpt_key = byte5_config.get("byt5_ckpt_path")
|
||||
byte5_ckpt_path = byte5_dir / ckpt_key.lstrip("./")
|
||||
tokenizer = AutoTokenizer.from_pretrained(byte5_ckpt_path, local_files_only=True)
|
||||
text_encoder = T5ForConditionalGeneration.from_pretrained(byte5_ckpt_path, local_files_only=True).get_encoder()
|
||||
|
||||
# ---- Extend vocab with font/color markers so the shipped weights load.
|
||||
if byte5_config.get("special_token"):
|
||||
if not byte5_config.get("multilingual", True):
|
||||
raise NotImplementedError(
|
||||
"Non-multilingual byte5 vocab extension is not ported; "
|
||||
"the released Ming checkpoint uses multilingual=True."
|
||||
)
|
||||
_add_multilingual_special_tokens(
|
||||
tokenizer,
|
||||
text_encoder,
|
||||
font_ann_path=byte5_dir / byte5_config["font_ann_path"].lstrip("./"),
|
||||
color_ann_path=byte5_dir / byte5_config["color_ann_path"].lstrip("./"),
|
||||
add_font=bool(byte5_config.get("font_special_token")),
|
||||
add_color=bool(byte5_config.get("color_special_token")),
|
||||
)
|
||||
|
||||
# ---- Load byt5 text-encoder weights (base.pt wraps the backbone in a
|
||||
# trainable-module container; byt5_model.pt has the top-level encoder
|
||||
# state). Follow Ming's two-step load.
|
||||
base_state = torch.load(byte5_dir / "byt5_model" / "base.pt", map_location="cpu", weights_only=False)
|
||||
prefix = "module.text_tower.encoder."
|
||||
base_filtered = {
|
||||
name[len(prefix) :]: state for name, state in base_state["state_dict"].items() if name.startswith(prefix)
|
||||
}
|
||||
text_encoder.load_state_dict(base_filtered, strict=True)
|
||||
del base_state, base_filtered
|
||||
|
||||
encoder_state = torch.load(byte5_dir / "byt5_model" / "byt5_model.pt", map_location="cpu", weights_only=False)
|
||||
text_encoder.load_state_dict(encoder_state)
|
||||
del encoder_state
|
||||
|
||||
text_encoder.to(device=device, dtype=dtype).eval()
|
||||
|
||||
# ---- Mapper.
|
||||
mapper = T5EncoderBlockByT5Mapper(
|
||||
byte5_config=text_encoder.config,
|
||||
num_layers=int(mapper_config["num_layers"]),
|
||||
sdxl_channels=int(mapper_config["sdxl_channels"]),
|
||||
)
|
||||
mapper_state = torch.load(byte5_dir / "byt5_mapper" / "byt5_mapper.pt", map_location="cpu", weights_only=False)
|
||||
# mapper now uses vllm-omni TP-aware T5 layers (fused qkv_proj / wi);
|
||||
mapper.load_weights(mapper_state.items())
|
||||
del mapper_state
|
||||
mapper.to(device=device, dtype=dtype).eval()
|
||||
|
||||
logger.info(
|
||||
"[MingByT5Encoder] ready: d_model=%d mapper_layers=%d sdxl_channels=%d max_length=%d vocab=%d",
|
||||
text_encoder.config.d_model,
|
||||
mapper_config["num_layers"],
|
||||
mapper_config["sdxl_channels"],
|
||||
max_length,
|
||||
len(tokenizer),
|
||||
)
|
||||
return cls(tokenizer, text_encoder, mapper, max_length)
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, texts: list[str]) -> torch.Tensor:
|
||||
"""Tokenize → T5 encode → mapper; masks out padded positions.
|
||||
|
||||
Returns ``[B, max_length, sdxl_channels]``. Padded positions are zeroed
|
||||
so the downstream ``torch.cat`` with cap_feats doesn't inject garbage.
|
||||
"""
|
||||
device = next(self.text_encoder.parameters()).device
|
||||
dtype = next(self.text_encoder.parameters()).dtype
|
||||
|
||||
tokens = self.tokenizer(
|
||||
texts,
|
||||
padding="max_length",
|
||||
max_length=self.max_length,
|
||||
truncation=True,
|
||||
add_special_tokens=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
input_ids = tokens.input_ids.to(device)
|
||||
attention_mask = tokens.attention_mask.to(device)
|
||||
|
||||
encoder_out = self.text_encoder(
|
||||
input_ids=input_ids,
|
||||
attention_mask=attention_mask.float(),
|
||||
)
|
||||
hidden_states = encoder_out[0]
|
||||
feats = self.mapper(hidden_states, attention_mask)
|
||||
feats = feats * attention_mask.unsqueeze(-1).to(dtype=feats.dtype)
|
||||
return feats.to(dtype=dtype)
|
||||
|
||||
|
||||
__all__ = ["MingByT5Encoder"]
|
||||
@@ -0,0 +1,373 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2025 The vLLM-Omni team.
|
||||
#
|
||||
# Adapted from Ming repository (inclusionAI/Ming) — the ``get_condition_embeds
|
||||
# _for_image_gen`` path in modeling_bailingmm2.py.
|
||||
|
||||
"""Ming-flash-omni-2.0 condition encoder for image generation.
|
||||
|
||||
Pipeline (runs inside the imagegen stage):
|
||||
|
||||
thinker hidden states at query-token positions [B, N, 4096]
|
||||
│
|
||||
▼ proj_in (Linear, bias=True)
|
||||
[B, N, 1536]
|
||||
│
|
||||
▼ Qwen2ForCausalLM connector (is_causal=False)
|
||||
loaded from <checkpoint>/connector/
|
||||
[B, N, 1536]
|
||||
│
|
||||
▼ proj_out (Linear, bias=True)
|
||||
[B, N, 2560]
|
||||
│
|
||||
▼ F.normalize(dim=-1) × 1000 (text_encoder_norm)
|
||||
[B, N, 2560]
|
||||
│
|
||||
▼
|
||||
cap_feats consumed by ZImageTransformer2DModel
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm_omni.transformers_utils.configs.ming_flash_omni import MingImageGenConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MingConditionEncoder(nn.Module):
|
||||
"""Wraps a Qwen2 connector + norm/projection, producing DiT condition embeds.
|
||||
|
||||
The connector is a ``Qwen2ForCausalLM`` loaded from the ``connector/``
|
||||
subfolder of the Ming checkpoint. We run its base model in a non-causal
|
||||
(bidirectional) mode, because the connector is used as an encoder over the
|
||||
pre-baked query-token hidden states, not as an autoregressive decoder.
|
||||
|
||||
Args:
|
||||
image_gen_config: ``MingImageGenConfig`` from ``MingFlashOmniConfig``.
|
||||
thinker_hidden_size: Hidden size of the thinker (BailingMoeV2) model.
|
||||
Used to build a ``proj_in`` layer when the connector embedding
|
||||
dim differs. For the released checkpoint this is 4096.
|
||||
device: Placement for the module.
|
||||
dtype: Parameter dtype (typically bfloat16 / float16).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
image_gen_config: MingImageGenConfig,
|
||||
*,
|
||||
thinker_hidden_size: int = 4096,
|
||||
device: torch.device | str | None = None,
|
||||
dtype: torch.dtype | None = None,
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.config = image_gen_config
|
||||
self.thinker_hidden_size = thinker_hidden_size
|
||||
self._target_device = torch.device(device) if device is not None else None
|
||||
self._target_dtype = dtype
|
||||
|
||||
# Populated lazily by ``load_from_checkpoint`` to keep this module
|
||||
# cheap to construct (useful for dummy-init paths and unit tests).
|
||||
self.connector: nn.Module | None = None
|
||||
self.connector_hidden_size: int | None = None
|
||||
self.proj_in: nn.Module = nn.Identity()
|
||||
self.proj_out: nn.Module = nn.Identity()
|
||||
self.norm: nn.Module = nn.Identity()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Weight loading
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def load_from_checkpoint(self, model_path: str | Path) -> None:
|
||||
"""Load the Qwen2 connector + optional projection/norm weights.
|
||||
|
||||
This uses HF transformers directly (not vllm's weight loader) because
|
||||
the connector is small (~1.5B params) and only runs once per request
|
||||
as an encoder — vllm's distributed loading machinery is overkill.
|
||||
"""
|
||||
from transformers import AutoConfig, Qwen2ForCausalLM
|
||||
|
||||
model_path = Path(model_path)
|
||||
connector_path = model_path / self.config.connector_subfolder
|
||||
logger.info("[MingConditionEncoder] loading connector from %s", connector_path)
|
||||
|
||||
connector_cfg = AutoConfig.from_pretrained(connector_path, trust_remote_code=True, local_files_only=True)
|
||||
# Disable causal masking: the connector is used as a bidirectional
|
||||
# encoder over query-token hidden states in image-gen mode.
|
||||
connector_cfg.is_decoder = False
|
||||
self.connector_hidden_size = int(connector_cfg.hidden_size)
|
||||
logger.info(
|
||||
"[MingConditionEncoder] connector hidden_size=%d, layers=%d",
|
||||
self.connector_hidden_size,
|
||||
getattr(connector_cfg, "num_hidden_layers", -1),
|
||||
)
|
||||
|
||||
connector = Qwen2ForCausalLM.from_pretrained(
|
||||
connector_path,
|
||||
config=connector_cfg,
|
||||
torch_dtype=self._target_dtype,
|
||||
local_files_only=True,
|
||||
)
|
||||
# Force bidirectional attention in every self-attn module. Qwen2 layers
|
||||
# do not branch on ``is_causal`` directly, so we monkey-patch the flag
|
||||
# on each attention block (defensive — some transformers versions read
|
||||
# ``self_attn.is_causal`` in forward).
|
||||
patched = 0
|
||||
for module in connector.modules():
|
||||
if hasattr(module, "is_causal"):
|
||||
module.is_causal = False
|
||||
patched += 1
|
||||
logger.info("[MingConditionEncoder] disabled is_causal on %d sub-modules", patched)
|
||||
|
||||
# We only need the base encoder (no LM head).
|
||||
base = getattr(connector, "model", connector)
|
||||
self.connector = base
|
||||
|
||||
# proj_in: align thinker_hidden_size -> connector_hidden_size.
|
||||
# Observed layout of mlp/ on the released checkpoint
|
||||
# (inclusionAI/Ming-flash-omni-2.0):
|
||||
# proj_in.{weight,bias} : Linear(4096 -> 1536)
|
||||
# proj_out.{weight,bias} : Linear(1536 -> 2560)
|
||||
# query_tokens_dict.16x16 : learnable tokens consumed on the thinker
|
||||
# side (NOT loaded here).
|
||||
logger.info(
|
||||
"[MingConditionEncoder] adding proj_in: %d -> %d (bias=True)",
|
||||
self.thinker_hidden_size,
|
||||
self.connector_hidden_size,
|
||||
)
|
||||
self.proj_in = nn.Linear(self.thinker_hidden_size, self.connector_hidden_size, bias=True)
|
||||
|
||||
# NOTE: ``text_encoder_norm=True`` in Ming's mlp/config.json refers to
|
||||
# applying ``F.normalize(..., dim=-1)`` (L2 normalization) on the
|
||||
# FINAL cap_feats AFTER proj_out — NOT an intermediate RMSNorm. See
|
||||
# modeling_bailingmm2.py::get_condition_embeds_for_image_gen. We keep
|
||||
# ``self.norm = nn.Identity`` and apply the L2 normalize explicitly
|
||||
# at the end of ``forward``.
|
||||
self.norm = nn.Identity()
|
||||
|
||||
# proj_out: align connector_hidden_size -> diffusion_c_input_dim.
|
||||
c_out = self.config.diffusion_c_input_dim
|
||||
logger.info(
|
||||
"[MingConditionEncoder] adding proj_out: %d -> %d (bias=True)",
|
||||
self.connector_hidden_size,
|
||||
c_out,
|
||||
)
|
||||
self.proj_out = nn.Linear(self.connector_hidden_size, c_out, bias=True)
|
||||
|
||||
mlp_path = model_path / self.config.mlp_subfolder
|
||||
mlp_cfg_path = mlp_path / "config.json"
|
||||
if mlp_cfg_path.exists() and not json.loads(mlp_cfg_path.read_text()).get("use_identity_mlp", False):
|
||||
# MingImagePipeline skips ZImageModel_withMLP, only correct when its inner MLP is Identity.
|
||||
raise NotImplementedError(f"{mlp_cfg_path} has use_identity_mlp=False; ToClipMLP path not implemented.")
|
||||
self._load_optional_mlp_weights(mlp_path)
|
||||
|
||||
if self._target_device is not None:
|
||||
self.to(self._target_device)
|
||||
if self._target_dtype is not None:
|
||||
self.to(dtype=self._target_dtype)
|
||||
|
||||
logger.info(
|
||||
"[MingConditionEncoder] ready: in=%d -> conn=%d -> out=%d",
|
||||
self.thinker_hidden_size,
|
||||
self.connector_hidden_size,
|
||||
c_out,
|
||||
)
|
||||
|
||||
def _load_optional_mlp_weights(self, mlp_path: Path) -> None:
|
||||
"""Load proj_in / proj_out (and optional norm) weights from mlp/.
|
||||
|
||||
Expected keys — observed on inclusionAI/Ming-flash-omni-2.0:
|
||||
proj_in.weight [1536, 4096]
|
||||
proj_in.bias [1536]
|
||||
proj_out.weight [2560, 1536]
|
||||
proj_out.bias [2560]
|
||||
query_tokens_dict.16x16 [256, 4096] -> thinker-side, skipped here
|
||||
(optional) norm.weight [1536]
|
||||
|
||||
Any extra keys are logged as warnings so we don't silently miss new
|
||||
fields. Missing proj weights are fatal: they are required for the
|
||||
condition path to be meaningful.
|
||||
"""
|
||||
if not mlp_path.exists():
|
||||
logger.warning(
|
||||
"[MingConditionEncoder] mlp/ subfolder missing at %s — proj/norm "
|
||||
"will stay randomly initialized. EXPECT BAD IMAGES until this "
|
||||
"is fixed on real hardware.",
|
||||
mlp_path,
|
||||
)
|
||||
return
|
||||
|
||||
try:
|
||||
from safetensors.torch import load_file # type: ignore
|
||||
except ImportError:
|
||||
logger.exception("[MingConditionEncoder] safetensors not installed")
|
||||
return
|
||||
|
||||
candidates = sorted(mlp_path.glob("*.safetensors"))
|
||||
if not candidates:
|
||||
candidates = sorted(mlp_path.glob("*.bin"))
|
||||
if not candidates:
|
||||
logger.warning("[MingConditionEncoder] no weight files under %s", mlp_path)
|
||||
return
|
||||
|
||||
state: dict[str, torch.Tensor] = {}
|
||||
for p in candidates:
|
||||
logger.info("[MingConditionEncoder] reading mlp weights: %s", p)
|
||||
if p.suffix == ".safetensors":
|
||||
state.update(load_file(str(p)))
|
||||
else:
|
||||
state.update(torch.load(str(p), map_location="cpu"))
|
||||
logger.info(
|
||||
"[MingConditionEncoder] mlp/ keys: %s",
|
||||
sorted(state.keys()),
|
||||
)
|
||||
|
||||
handled: set[str] = set()
|
||||
|
||||
def _copy(dst: nn.Parameter | torch.Tensor, src_key: str) -> bool:
|
||||
src = state.get(src_key)
|
||||
if src is None:
|
||||
logger.error("[MingConditionEncoder] mlp/ missing key %r", src_key)
|
||||
return False
|
||||
if tuple(src.shape) != tuple(dst.shape):
|
||||
logger.error(
|
||||
"[MingConditionEncoder] mlp/%s shape mismatch: checkpoint=%s, module=%s",
|
||||
src_key,
|
||||
tuple(src.shape),
|
||||
tuple(dst.shape),
|
||||
)
|
||||
return False
|
||||
with torch.no_grad():
|
||||
dst.copy_(src.to(dtype=dst.dtype, device=dst.device))
|
||||
handled.add(src_key)
|
||||
logger.info(
|
||||
"[MingConditionEncoder] loaded mlp/%s -> %s",
|
||||
src_key,
|
||||
tuple(dst.shape),
|
||||
)
|
||||
return True
|
||||
|
||||
ok_w = _copy(self.proj_in.weight, "proj_in.weight")
|
||||
ok_b = _copy(self.proj_in.bias, "proj_in.bias")
|
||||
ok_ow = _copy(self.proj_out.weight, "proj_out.weight")
|
||||
ok_ob = _copy(self.proj_out.bias, "proj_out.bias")
|
||||
if not (ok_w and ok_b and ok_ow and ok_ob):
|
||||
logger.error(
|
||||
"[MingConditionEncoder] proj_in/proj_out NOT fully loaded; diffusion conditioning will be garbage."
|
||||
)
|
||||
|
||||
# Optional norm weight (Ming uses plain RMSNorm; may or may not ship).
|
||||
if "norm.weight" in state and hasattr(self.norm, "weight"):
|
||||
_copy(self.norm.weight, "norm.weight")
|
||||
|
||||
# query_tokens_dict lives in mlp/ but is consumed on the thinker side
|
||||
# — we neither need nor load it here. Just log the shape so the
|
||||
# thinker-side patch knows what to expect.
|
||||
for k, v in state.items():
|
||||
if k.startswith("query_tokens_dict"):
|
||||
logger.info(
|
||||
"[MingConditionEncoder] thinker-side parameter %s shape=%s (NOT loaded here; thinker must own it)",
|
||||
k,
|
||||
tuple(v.shape),
|
||||
)
|
||||
handled.add(k)
|
||||
|
||||
leftover = set(state.keys()) - handled
|
||||
if leftover:
|
||||
logger.warning("[MingConditionEncoder] mlp/ unhandled keys: %s", sorted(leftover))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Forward
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def forward(
|
||||
self,
|
||||
thinker_hidden_states: torch.Tensor,
|
||||
attention_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Encode thinker hidden states into DiT condition embeddings.
|
||||
|
||||
Args:
|
||||
thinker_hidden_states: ``[B, N, thinker_hidden_size]`` — sliced at
|
||||
the learnable query-token positions by the stage input
|
||||
processor before being passed here.
|
||||
attention_mask: Optional ``[B, N]`` mask. Defaults to all-ones.
|
||||
|
||||
Returns:
|
||||
``[B, N, diffusion_c_input_dim]`` condition tensor ready for the
|
||||
ZImage transformer's ``cap_feats`` input.
|
||||
"""
|
||||
if self.connector is None:
|
||||
raise RuntimeError("MingConditionEncoder.load_from_checkpoint() must be called before forward().")
|
||||
if thinker_hidden_states.dim() != 3:
|
||||
raise ValueError(f"expected [B, N, H], got shape {tuple(thinker_hidden_states.shape)}")
|
||||
|
||||
b, n, _ = thinker_hidden_states.shape
|
||||
logger.debug(
|
||||
"[MingCondEnc] input shape=%s dtype=%s", tuple(thinker_hidden_states.shape), thinker_hidden_states.dtype
|
||||
)
|
||||
|
||||
x = self.proj_in(thinker_hidden_states) # [B, N, conn_hidden]
|
||||
|
||||
# Ming's ``get_condition_embeds_for_image_gen`` passes a 4D full-ones
|
||||
# attention mask of shape [B, 1, N, N] to the Qwen2 connector,
|
||||
# forcing full bidirectional self-attention over all query positions.
|
||||
if attention_mask is None:
|
||||
attention_mask = torch.ones(
|
||||
(b, 1, n, n),
|
||||
dtype=x.dtype,
|
||||
device=x.device,
|
||||
)
|
||||
elif attention_mask.dim() == 2:
|
||||
mask_2d = attention_mask.to(x.dtype)
|
||||
attention_mask = mask_2d[:, None, None, :].expand(b, 1, n, n)
|
||||
|
||||
out = self.connector(
|
||||
inputs_embeds=x,
|
||||
attention_mask=attention_mask,
|
||||
use_cache=False,
|
||||
output_hidden_states=True,
|
||||
return_dict=True,
|
||||
)
|
||||
hidden = out.hidden_states[-1] # [B, N, conn_hidden]
|
||||
|
||||
cap_feats = self.proj_out(hidden) # [B, N, diffusion_c_input_dim]
|
||||
|
||||
# L2 normalize + ×1000 rescale. Ming's ``get_condition_embeds_for_image_gen``
|
||||
# applies F.normalize; ``ZImageModel_withMLP`` then rescales by 1000
|
||||
# when ``text_encoder_norm=True``. We fold both into one place.
|
||||
cap_feats = torch.nn.functional.normalize(cap_feats, dim=-1)
|
||||
if self.config.text_encoder_norm:
|
||||
cap_feats = cap_feats * 1000.0
|
||||
|
||||
logger.debug("[MingCondEnc] output shape=%s dtype=%s", tuple(cap_feats.shape), cap_feats.dtype)
|
||||
return cap_feats
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Utility
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@torch.no_grad()
|
||||
def zero_negative(
|
||||
self,
|
||||
cap_feats: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Return a zero tensor shaped like ``cap_feats`` for CFG negatives."""
|
||||
return torch.zeros_like(cap_feats)
|
||||
|
||||
def extra_repr(self) -> str:
|
||||
return (
|
||||
f"thinker_hidden_size={self.thinker_hidden_size}, "
|
||||
f"connector_hidden_size={self.connector_hidden_size}, "
|
||||
f"diffusion_c_input_dim={self.config.diffusion_c_input_dim}, "
|
||||
f"text_encoder_norm={self.config.text_encoder_norm}"
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["MingConditionEncoder"]
|
||||
@@ -0,0 +1,50 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2025 The vLLM-Omni team.
|
||||
|
||||
"""Ming-specific subclass of ZImageTransformer2DModel that supports ``ref_x``.
|
||||
|
||||
Ming's img2img path concatenates a VAE-encoded reference latent along the
|
||||
frame axis before patchification, then drops the reference portion from the
|
||||
unpatchified output. This is a surgical override — everything else (attention,
|
||||
RoPE, final layer) stays on the parent implementation.
|
||||
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
from vllm_omni.diffusion.models.z_image.z_image_transformer import ZImageTransformer2DModel
|
||||
|
||||
|
||||
class MingZImageTransformer2DModel(ZImageTransformer2DModel):
|
||||
"""ZImage DiT with Ming's reference-latent support."""
|
||||
|
||||
def forward(
|
||||
self,
|
||||
x: list[torch.Tensor],
|
||||
t,
|
||||
cap_feats: list[torch.Tensor],
|
||||
patch_size=2,
|
||||
f_patch_size=1,
|
||||
):
|
||||
ref_latent = get_forward_context().ref_latent if is_forward_context_available() else None
|
||||
if ref_latent is not None:
|
||||
per_item = ref_latent[0].unsqueeze(1).to(dtype=x[0].dtype, device=x[0].device) # [C, 1, H, W]
|
||||
x = [torch.cat([img, per_item], dim=1) for img in x]
|
||||
return super().forward(x, t, cap_feats, patch_size=patch_size, f_patch_size=f_patch_size)
|
||||
|
||||
def unpatchify(
|
||||
self,
|
||||
x: list[torch.Tensor],
|
||||
size: list[tuple],
|
||||
patch_size,
|
||||
f_patch_size,
|
||||
) -> list[torch.Tensor]:
|
||||
out = super().unpatchify(x, size, patch_size, f_patch_size)
|
||||
# No-op when F==1 (pure t2i); drops the reference-frame prediction when F==2.
|
||||
return [t[:, :1, :, :] for t in out]
|
||||
|
||||
|
||||
__all__ = ["MingZImageTransformer2DModel"]
|
||||
@@ -0,0 +1,520 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2025 The vLLM-Omni team.
|
||||
|
||||
"""Ming-flash-omni-2.0 imagegen (text-to-image / img2img) diffusion pipeline.
|
||||
|
||||
Cross-stage data flow:
|
||||
|
||||
Stage 0 (thinker, llm) Stage 1 (imagegen, diffusion)
|
||||
──────────────────── ──────────────────────────────
|
||||
forward returns thinker2imagegen hook slices
|
||||
multimodal_output[ final_hidden_states at
|
||||
"final_hidden_states"] <imagePatch> positions,
|
||||
↓ returns list[dict] with
|
||||
shared_memory_connector {"extra": {"thinker_hidden_states"}}
|
||||
↓ ──── via OmniMsgpackEncoder ────>
|
||||
MingImagePipeline.forward(req):
|
||||
hidden = req.prompts[0]["extra"][...]
|
||||
cond = condition_encoder(hidden)
|
||||
img = ZImagePipeline-style loop
|
||||
return DiffusionOutput(output=img)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from diffusers.image_processor import VaeImageProcessor
|
||||
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
||||
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl import DistributedAutoencoderKL
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_ref_latent
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.ming_flash_omni.byte5_encoder import (
|
||||
MingByT5Encoder,
|
||||
)
|
||||
from vllm_omni.diffusion.models.ming_flash_omni.condition_encoder import (
|
||||
MingConditionEncoder,
|
||||
)
|
||||
from vllm_omni.diffusion.models.ming_flash_omni.ming_zimage_transformer import (
|
||||
MingZImageTransformer2DModel,
|
||||
)
|
||||
from vllm_omni.diffusion.models.z_image.pipeline_z_image import ZImagePipeline
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.model_executor.model_loader.weight_utils import (
|
||||
download_weights_from_hf_specific,
|
||||
)
|
||||
from vllm_omni.transformers_utils.configs.ming_flash_omni import MingImageGenConfig
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _ZPipelineSamplingParams:
|
||||
"""Typed shim satisfying the attributes ZImagePipeline.forward reads
|
||||
from ``req.sampling_params``. Unlike SimpleNamespace this fails loudly
|
||||
at construction if a required field is missing."""
|
||||
|
||||
height: int
|
||||
width: int
|
||||
num_inference_steps: int
|
||||
guidance_scale: float
|
||||
generator: torch.Generator | None = None
|
||||
strength: float | None = None
|
||||
sigmas: list[float] | None = None
|
||||
max_sequence_length: int = 512
|
||||
guidance_rescale: float | None = None
|
||||
num_outputs_per_prompt: int = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class _ZPipelineRequest:
|
||||
"""Typed shim satisfying the attributes ZImagePipeline.forward reads
|
||||
from ``req``."""
|
||||
|
||||
request_id: str
|
||||
sampling_params: _ZPipelineSamplingParams
|
||||
prompts: list[dict[str, Any]] = field(default_factory=lambda: [{"prompt": "", "negative_prompt": ""}])
|
||||
|
||||
|
||||
class MingImagePipeline(ZImagePipeline):
|
||||
"""Ming-flash-omni-2.0 text-to-image diffusion pipeline.
|
||||
|
||||
Ming-specific components added on top of the inherited contract:
|
||||
* ``condition_encoder`` — Qwen2 connector + proj_in/out + F.normalize×1000
|
||||
* ``byte5`` — Optional ByT5 glyph encoder (loaded if checkpoint
|
||||
ships ``byt5/``)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
od_config: OmniDiffusionConfig,
|
||||
prefix: str = "", # noqa: ARG002
|
||||
) -> None:
|
||||
# Skip ZImagePipeline.__init__ (it would eagerly load the Z-Image text
|
||||
# encoder/tokenizer that Ming replaces with its own condition_encoder).
|
||||
nn.Module.__init__(self)
|
||||
|
||||
model_path = od_config.model
|
||||
if not os.path.exists(model_path):
|
||||
model_path = download_weights_from_hf_specific(model_path, od_config.revision, ["*"])
|
||||
|
||||
dtype = getattr(od_config, "dtype", torch.bfloat16)
|
||||
local_files_only = os.path.exists(model_path)
|
||||
|
||||
self.od_config = od_config
|
||||
self._execution_device = get_local_device()
|
||||
self.device = self._execution_device # Ming convention alias
|
||||
self._dtype = dtype
|
||||
|
||||
# Ming's per-checkpoint image-gen configuration. We cannot rely on
|
||||
# ``od_config.hf_config.image_gen_config`` because the diffusion
|
||||
# stage is started with ``hf_config_name: thinker_config`` (the
|
||||
# BailingMM2Config), which does not carry a MingImageGenConfig.
|
||||
# Fall back to defaults that match the released checkpoint.
|
||||
self.image_gen_config = MingImageGenConfig()
|
||||
logger.info(
|
||||
"[MingImagePipeline] init: model=%s dtype=%s image_gen_config=%s",
|
||||
model_path,
|
||||
dtype,
|
||||
self.image_gen_config,
|
||||
)
|
||||
|
||||
# ----- weights_sources: DiT transformer + VAE.
|
||||
self.weights_sources = [
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=model_path,
|
||||
subfolder=self.image_gen_config.transformer_subfolder,
|
||||
revision=od_config.revision,
|
||||
prefix="transformer.",
|
||||
fall_back_to_pt=True,
|
||||
),
|
||||
DiffusersPipelineLoader.ComponentSource(
|
||||
model_or_path=model_path,
|
||||
subfolder=self.image_gen_config.vae_subfolder,
|
||||
revision=od_config.revision,
|
||||
prefix="vae.",
|
||||
),
|
||||
]
|
||||
|
||||
prefetch_subfolders(
|
||||
model_path,
|
||||
[self.image_gen_config.scheduler_subfolder, self.image_gen_config.vae_subfolder],
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
|
||||
# ----- Scheduler: load config-only from disk + Ming-specific override.
|
||||
self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
|
||||
model_path,
|
||||
subfolder=self.image_gen_config.scheduler_subfolder,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
# Ming forces use_dynamic_shifting=True at runtime regardless of what
|
||||
# the checkpoint scheduler_config.json ships.
|
||||
self.scheduler.config["use_dynamic_shifting"] = True
|
||||
logger.info(
|
||||
"[MingImagePipeline] scheduler: %s (use_dynamic_shifting=True)",
|
||||
type(self.scheduler).__name__,
|
||||
)
|
||||
|
||||
# ----- VAE: DistributedAutoencoderKL.
|
||||
vae_config = DistributedAutoencoderKL.load_config(
|
||||
model_path, subfolder=self.image_gen_config.vae_subfolder, local_files_only=local_files_only
|
||||
)
|
||||
self.vae = DistributedAutoencoderKL.from_config(vae_config).to(self._execution_device, dtype=dtype)
|
||||
self.vae.eval()
|
||||
|
||||
# ----- DiT transformer.
|
||||
self.transformer = MingZImageTransformer2DModel(quant_config=None)
|
||||
|
||||
# Ming brings its own conditioning path — no Z-Image text_encoder /
|
||||
# tokenizer.
|
||||
self.text_encoder = None
|
||||
self.tokenizer = None
|
||||
|
||||
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
||||
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor * 2, do_convert_rgb=True)
|
||||
self.setup_diffusion_pipeline_profiler(
|
||||
enable_diffusion_pipeline_profiler=getattr(od_config, "enable_diffusion_pipeline_profiler", False)
|
||||
)
|
||||
|
||||
# ----- Condition encoder (Qwen2 connector + proj_in/out + norm×1000).
|
||||
self.condition_encoder = MingConditionEncoder(
|
||||
self.image_gen_config,
|
||||
thinker_hidden_size=self.image_gen_config.thinker_hidden_size,
|
||||
device=self.device,
|
||||
dtype=dtype,
|
||||
)
|
||||
self.condition_encoder.load_from_checkpoint(model_path)
|
||||
|
||||
# Optional ByT5 glyph/text encoder. Only loaded when the checkpoint
|
||||
# ``extra_args.image_gen.byte5_text`` requests will be ignored.
|
||||
byte5_dir = Path(model_path) / "byt5"
|
||||
if byte5_dir.exists():
|
||||
self.byte5 = MingByT5Encoder.from_checkpoint(byte5_dir, device=self.device, dtype=dtype)
|
||||
else:
|
||||
self.byte5 = None
|
||||
logger.info("[MingImagePipeline] no byt5/ subfolder at %s; ByT5 enhancement disabled", byte5_dir)
|
||||
|
||||
logger.info("[MingImagePipeline] ready — vae_scale_factor=%d", self.vae_scale_factor)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _resolve_byte5_texts(extra: dict, sampling_params) -> list[str]:
|
||||
"""Resolve byte5 glyph texts.
|
||||
|
||||
Two sources, in order of priority:
|
||||
1. ``extra["byte5_text"]`` — auto-extracted from the user prompt's
|
||||
quoted spans by ``thinker2imagegen`` (already wrapped as
|
||||
``'Text "<glyph>". '`` by Ming's ``get_text_from_prompt``).
|
||||
2. ``sampling_params.extra_args["image_gen"]["byte5_text"]`` — an
|
||||
explicit override for programmatic callers; raw strings without
|
||||
the ``Text "..."`` wrapper are auto-wrapped here to match the
|
||||
distribution ByT5 was trained on.
|
||||
"""
|
||||
# Source 1: auto-extracted, already wrapped. Return as-is if non-empty.
|
||||
raw = extra.get("byte5_text")
|
||||
if isinstance(raw, str):
|
||||
raw = [raw]
|
||||
if isinstance(raw, list):
|
||||
cleaned = [t for t in raw if isinstance(t, str) and t.strip()]
|
||||
if cleaned:
|
||||
return cleaned
|
||||
|
||||
# Source 2: explicit override — wrap raw strings so the byte5 encoder
|
||||
# sees the same ``Text "<glyph>". `` format Ming used during training.
|
||||
raw = ((getattr(sampling_params, "extra_args", None) or {}).get("image_gen") or {}).get("byte5_text")
|
||||
if isinstance(raw, str):
|
||||
raw = [raw]
|
||||
if isinstance(raw, list):
|
||||
out: list[str] = []
|
||||
for t in raw:
|
||||
if not isinstance(t, str):
|
||||
continue
|
||||
s = t.strip()
|
||||
if not s:
|
||||
continue
|
||||
# Don't double-wrap if the caller already supplied ``Text "...". ``.
|
||||
out.append(s if s.startswith('Text "') else f'Text "{s}". ')
|
||||
if out:
|
||||
return out
|
||||
return []
|
||||
|
||||
@torch.inference_mode()
|
||||
def _encode_reference_image(self, ref, height: int, width: int) -> torch.Tensor | None:
|
||||
"""Turn a PIL/tensor reference image into a VAE latent for ``ref_x``.
|
||||
|
||||
Applies the same shift/scale Ming uses (``(z - shift_factor) * scaling_factor``)
|
||||
so the concatenated frame lives in the DiT's latent space.
|
||||
"""
|
||||
if ref is None:
|
||||
return None
|
||||
if not isinstance(ref, torch.Tensor):
|
||||
ref = self.image_processor.preprocess(ref, height, width)
|
||||
ref = ref.to(device=self.device, dtype=self.vae.dtype)
|
||||
latent = self.vae.encode(ref).latent_dist.mode()
|
||||
return (latent - self.vae.config.shift_factor) * self.vae.config.scaling_factor
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Forward
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@torch.inference_mode()
|
||||
def forward(self, req: OmniDiffusionRequest) -> DiffusionOutput:
|
||||
"""Run one text-to-image generation request.
|
||||
|
||||
Args:
|
||||
req: Diffusion request. The cross-stage thinker hidden states
|
||||
must be present at
|
||||
``req.prompts[0]["extra"]["thinker_hidden_states"]`` as a
|
||||
``[N, H]`` (or ``[1, N, H]``) tensor, placed there by
|
||||
``thinker2imagegen``.
|
||||
|
||||
Returns:
|
||||
DiffusionOutput with ``.output`` set to a ``[B, 3, H, W]``
|
||||
image tensor in ``[-1, 1]``. The vllm-omni diffusion engine's
|
||||
output adapter converts this to PIL/base64 downstream.
|
||||
"""
|
||||
first_prompt = req.prompts[0] if req.prompts else None
|
||||
if isinstance(first_prompt, str):
|
||||
prompt_dict: dict[str, Any] = {}
|
||||
elif isinstance(first_prompt, dict):
|
||||
prompt_dict = first_prompt
|
||||
elif first_prompt is not None and hasattr(first_prompt, "_asdict"):
|
||||
prompt_dict = first_prompt._asdict()
|
||||
elif first_prompt is not None and hasattr(first_prompt, "__dict__"):
|
||||
prompt_dict = vars(first_prompt)
|
||||
else:
|
||||
prompt_dict = {}
|
||||
|
||||
extra = prompt_dict.get("extra") or {}
|
||||
hidden = extra.get("thinker_hidden_states")
|
||||
if hidden is None:
|
||||
# Same dual-path convention as glm_image: also check
|
||||
# ``sampling_params.extra_args``.
|
||||
hidden = (req.sampling_params.extra_args or {}).get("thinker_hidden_states")
|
||||
if hidden is None:
|
||||
scale = self.image_gen_config.img_gen_scales[-1]
|
||||
num_query_tokens = scale * scale
|
||||
hidden = torch.zeros(
|
||||
(num_query_tokens, self.image_gen_config.thinker_hidden_size),
|
||||
dtype=self._dtype,
|
||||
device=self.device,
|
||||
)
|
||||
logger.warning(
|
||||
"[MingImagePipeline.forward] 'thinker_hidden_states' missing "
|
||||
"from request; falling back to zero-conditioning %s. This is "
|
||||
"expected during warmup; for real requests verify that "
|
||||
"`custom_process_input_func: thinker2imagegen` is set on the "
|
||||
"diffusion stage in the YAML.",
|
||||
tuple(hidden.shape),
|
||||
)
|
||||
|
||||
if not isinstance(hidden, torch.Tensor):
|
||||
raise TypeError(
|
||||
f"[MingImagePipeline] 'thinker_hidden_states' must be a Tensor, got {type(hidden).__name__}"
|
||||
)
|
||||
|
||||
# Move to the pipeline's device+dtype.
|
||||
target_device = next(self.parameters()).device
|
||||
target_dtype = next(self.parameters()).dtype
|
||||
hidden = hidden.to(device=target_device, dtype=target_dtype)
|
||||
if hidden.dim() == 2:
|
||||
hidden = hidden.unsqueeze(0) # [N, H] -> [1, N, H]
|
||||
logger.debug(
|
||||
"[MingImagePipeline.forward] thinker_hidden_states=%s on %s (%s)",
|
||||
tuple(hidden.shape),
|
||||
target_device,
|
||||
target_dtype,
|
||||
)
|
||||
|
||||
# ----- Condition encoder → cap_feats
|
||||
cap_feats = self.condition_encoder(hidden)
|
||||
logger.debug("[MingImagePipeline.forward] cap_feats=%s", tuple(cap_feats.shape))
|
||||
|
||||
# Real negative CFG conditioning (opt-in). See expand_cfg_prompts.
|
||||
negative_hidden = extra.get("negative_thinker_hidden_states")
|
||||
negative_cap_feats = None
|
||||
if isinstance(negative_hidden, torch.Tensor):
|
||||
negative_hidden = negative_hidden.to(device=target_device, dtype=target_dtype)
|
||||
if negative_hidden.dim() == 2:
|
||||
negative_hidden = negative_hidden.unsqueeze(0)
|
||||
negative_cap_feats = self.condition_encoder(negative_hidden)
|
||||
logger.debug("[MingImagePipeline.forward] negative_cap_feats=%s", tuple(negative_cap_feats.shape))
|
||||
|
||||
# ByT5 text enhancement (opt-in). Appends glyph-aware features along
|
||||
# the sequence dim; negative side gets zeros for the byte5 portion so
|
||||
# CFG doesn't push away from the rendered text.
|
||||
byte5_texts = self._resolve_byte5_texts(extra, req.sampling_params)
|
||||
if byte5_texts and self.byte5 is not None:
|
||||
byte5_feats = self.byte5(byte5_texts).to(device=target_device, dtype=target_dtype)
|
||||
cap_feats = torch.cat((cap_feats, byte5_feats), dim=1)
|
||||
if negative_cap_feats is not None:
|
||||
negative_cap_feats = torch.cat((negative_cap_feats, torch.zeros_like(byte5_feats)), dim=1)
|
||||
logger.debug("[MingImagePipeline.forward] byte5 cat'd: cap_feats=%s", tuple(cap_feats.shape))
|
||||
|
||||
# Sampling knobs: extra_args.image_gen.* > sampling_params.* > MingImageGenConfig defaults.
|
||||
sp = req.sampling_params
|
||||
cfg = self.image_gen_config
|
||||
ig = (sp.extra_args or {}).get("image_gen") or {}
|
||||
resolved: dict[str, Any] = {}
|
||||
for ig_key, sp_attr, default in (
|
||||
("height", "height", cfg.default_height),
|
||||
("width", "width", cfg.default_width),
|
||||
("steps", "num_inference_steps", cfg.num_inference_steps),
|
||||
("cfg", "guidance_scale", cfg.guidance_scale),
|
||||
("seed", "seed", None),
|
||||
):
|
||||
for v in (ig.get(ig_key), getattr(sp, sp_attr), default):
|
||||
if v is not None:
|
||||
resolved[ig_key] = v
|
||||
break
|
||||
|
||||
height = int(resolved["height"])
|
||||
width = int(resolved["width"])
|
||||
num_inference_steps = int(resolved["steps"])
|
||||
guidance_scale = float(resolved["cfg"])
|
||||
seed = resolved.get("seed")
|
||||
|
||||
# Always rebuild the generator from the resolved seed. Reusing
|
||||
# ``sp.generator`` causes two problems:
|
||||
# (1) if the caller pre-seeded it with sp.seed (e.g. the top-level
|
||||
# ``seed`` key on OmniDiffusionSamplingParams), any override via
|
||||
# ``extra_args.image_gen.seed`` would be silently ignored; and
|
||||
# (2) a persistent generator instance accumulates state across
|
||||
# requests → same-seed replays produce different outputs.
|
||||
if seed is not None:
|
||||
generator = torch.Generator(device=target_device).manual_seed(int(seed))
|
||||
else:
|
||||
generator = sp.generator
|
||||
|
||||
# Format prompt_embeds / negative_prompt_embeds as list[Tensor]
|
||||
# (one entry per request) — matches ZImagePipeline's contract when
|
||||
# prompt_embeds are pre-computed.
|
||||
prompt_embeds = [cap_feats[i] for i in range(cap_feats.shape[0])]
|
||||
if negative_cap_feats is not None:
|
||||
negative_prompt_embeds = [negative_cap_feats[i] for i in range(negative_cap_feats.shape[0])]
|
||||
else:
|
||||
negative_prompt_embeds = [self.condition_encoder.zero_negative(e) for e in prompt_embeds]
|
||||
|
||||
z_sp = _ZPipelineSamplingParams(
|
||||
height=height,
|
||||
width=width,
|
||||
num_inference_steps=num_inference_steps,
|
||||
guidance_scale=guidance_scale,
|
||||
generator=generator,
|
||||
)
|
||||
z_req = _ZPipelineRequest(
|
||||
request_id=req.request_id or "ming-imagegen",
|
||||
sampling_params=z_sp,
|
||||
)
|
||||
|
||||
# Reference image (img2img) → VAE-encoded latent published on the
|
||||
# active ForwardContext so MingZImageTransformer2DModel can read it
|
||||
# from request scope inside its forward().
|
||||
ref_latent = self._encode_reference_image(extra.get("reference_image"), height, width)
|
||||
set_forward_context_ref_latent(ref_latent)
|
||||
|
||||
logger.debug(
|
||||
"[MingImagePipeline.forward] running z_pipeline hw=(%d,%d) steps=%d cfg=%.2f seed=%s overrides=%s ref=%s",
|
||||
height,
|
||||
width,
|
||||
num_inference_steps,
|
||||
guidance_scale,
|
||||
seed,
|
||||
ig,
|
||||
None if ref_latent is None else tuple(ref_latent.shape),
|
||||
)
|
||||
try:
|
||||
output = super().forward(
|
||||
z_req,
|
||||
prompt=None,
|
||||
height=height,
|
||||
width=width,
|
||||
num_inference_steps=num_inference_steps,
|
||||
guidance_scale=guidance_scale,
|
||||
prompt_embeds=prompt_embeds,
|
||||
negative_prompt_embeds=negative_prompt_embeds,
|
||||
generator=generator,
|
||||
output_type="pt",
|
||||
return_dict=True,
|
||||
)
|
||||
finally:
|
||||
set_forward_context_ref_latent(None)
|
||||
|
||||
if hasattr(output, "output") and output.output is not None:
|
||||
raw = output.output
|
||||
elif hasattr(output, "images"):
|
||||
raw = output.images
|
||||
else:
|
||||
raw = output
|
||||
if not isinstance(raw, torch.Tensor):
|
||||
raise RuntimeError(f"ZImagePipeline returned non-tensor output: {type(raw).__name__}")
|
||||
if logger.isEnabledFor(logging.DEBUG):
|
||||
logger.debug(
|
||||
"[MingImagePipeline.forward] produced image tensor shape=%s range=[%.3f,%.3f]",
|
||||
tuple(raw.shape),
|
||||
raw.float().min().item(),
|
||||
raw.float().max().item(),
|
||||
)
|
||||
return DiffusionOutput(output=raw)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_ming_image_post_process_func(od_config: OmniDiffusionConfig):
|
||||
"""Return a post-process callable that converts the raw VAE tensor to PIL.
|
||||
|
||||
The diffusion engine calls ``post_process_func(output_data)`` where
|
||||
``output_data`` is the ``DiffusionOutput.output`` tensor returned by
|
||||
``MingImagePipeline.forward``. It has shape ``[B, 3, H, W]`` in ``[-1, 1]``
|
||||
(Z-image VAE convention). We run the standard ``VaeImageProcessor``
|
||||
postprocess to convert it to ``list[PIL.Image]`` which vllm-omni's
|
||||
``OmniRequestOutput.from_diffusion`` then bubbles up as
|
||||
``omni_outputs.images`` for serving_chat to base64-encode.
|
||||
|
||||
Registered via ``_DIFFUSION_POST_PROCESS_FUNCS["MingImagePipeline"]``
|
||||
in vllm_omni/diffusion/registry.py.
|
||||
"""
|
||||
import json
|
||||
|
||||
model_path = od_config.model
|
||||
vae_config_path = os.path.join(model_path, "vae", "config.json")
|
||||
try:
|
||||
with open(vae_config_path) as f:
|
||||
vae_cfg = json.load(f)
|
||||
block_out_channels = vae_cfg.get("block_out_channels", [128, 256, 512, 512])
|
||||
vae_scale_factor = 2 ** (len(block_out_channels) - 1)
|
||||
except Exception:
|
||||
vae_scale_factor = 8 # Ming's Flux-format VAE default
|
||||
|
||||
image_processor = VaeImageProcessor(vae_scale_factor=vae_scale_factor * 2, do_convert_rgb=True)
|
||||
|
||||
def post_process_func(images: torch.Tensor):
|
||||
# VaeImageProcessor.postprocess with default output_type="pil"
|
||||
# returns ``list[PIL.Image]``.
|
||||
return image_processor.postprocess(images.float())
|
||||
|
||||
return post_process_func
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MingImagePipeline",
|
||||
"get_ming_image_post_process_func",
|
||||
]
|
||||
@@ -0,0 +1,129 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# Copyright 2025 The vLLM-Omni team.
|
||||
|
||||
"""T5EncoderBlockByT5Mapper — Ming's per-block T5 stack mapping byte5 features
|
||||
onto the DiT condition space.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from diffusers.models.modeling_utils import ModelMixin
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.models.t5_encoder.t5_encoder import T5Block
|
||||
|
||||
|
||||
class T5EncoderBlockByT5Mapper(ModelMixin):
|
||||
"""Stacks ``num_layers`` T5 encoder blocks on top of byte5 features and
|
||||
projects them to ``sdxl_channels`` (= Ming's ``diffusion_c_input_dim``).
|
||||
"""
|
||||
|
||||
def __init__(self, byte5_config, num_layers: int, sdxl_channels: int | None = None) -> None:
|
||||
super().__init__()
|
||||
if num_layers > 0:
|
||||
self.blocks = nn.ModuleList(
|
||||
[
|
||||
T5Block(
|
||||
byte5_config,
|
||||
has_relative_attention_bias=(i == 0),
|
||||
prefix=f"blocks.{i}",
|
||||
)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
else:
|
||||
self.blocks = None
|
||||
self.layer_norm = RMSNorm(byte5_config.d_model, eps=byte5_config.layer_norm_epsilon)
|
||||
if sdxl_channels is not None:
|
||||
self.channel_mapper = nn.Linear(byte5_config.d_model, sdxl_channels)
|
||||
self.final_layer_norm = RMSNorm(sdxl_channels, eps=byte5_config.layer_norm_epsilon)
|
||||
else:
|
||||
self.channel_mapper = None
|
||||
self.final_layer_norm = None
|
||||
|
||||
def get_extended_attention_mask(self, attention_mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
|
||||
if attention_mask.dim() == 3:
|
||||
extended = attention_mask[:, None, :, :]
|
||||
elif attention_mask.dim() == 2:
|
||||
extended = attention_mask[:, None, None, :]
|
||||
else:
|
||||
raise ValueError(f"Unexpected attention_mask shape {tuple(attention_mask.shape)}")
|
||||
extended = extended.to(dtype=dtype)
|
||||
return (1.0 - extended) * torch.finfo(dtype).min
|
||||
|
||||
def forward(self, inputs_embeds: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
|
||||
extended_mask = self.get_extended_attention_mask(attention_mask, dtype=self.dtype)
|
||||
|
||||
hidden_states = inputs_embeds
|
||||
position_bias = None
|
||||
|
||||
if self.blocks is not None:
|
||||
for block in self.blocks:
|
||||
hidden_states, position_bias = block(
|
||||
hidden_states,
|
||||
mask=extended_mask,
|
||||
position_bias=position_bias,
|
||||
)
|
||||
|
||||
hidden_states = self.layer_norm(hidden_states)
|
||||
if self.channel_mapper is not None:
|
||||
hidden_states = self.channel_mapper(hidden_states)
|
||||
hidden_states = self.final_layer_norm(hidden_states)
|
||||
return hidden_states
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load Ming's HF-format byte5_mapper checkpoint into the fused
|
||||
TP-aware layers.
|
||||
|
||||
Source format (from ``byte5_mapper.pt``):
|
||||
blocks.{i}.layer.0.SelfAttention.{q,k,v,o}.weight
|
||||
blocks.{i}.layer.1.DenseReluDense.{wi_0,wi_1,wo}.weight
|
||||
blocks.{i}.layer.{0,1}.layer_norm.weight
|
||||
{layer_norm, channel_mapper, final_layer_norm}.{weight,bias}
|
||||
|
||||
Target format (after ``T5Block`` from t5_encoder.py):
|
||||
blocks.{i}.layer.0.SelfAttention.qkv_proj.weight (fused q+k+v)
|
||||
blocks.{i}.layer.1.DenseReluDense.wi.weight (fused wi_0+wi_1)
|
||||
(others identical)
|
||||
"""
|
||||
stacked_params_mapping = [
|
||||
(".qkv_proj.", ".q.", "q"),
|
||||
(".qkv_proj.", ".k.", "k"),
|
||||
(".qkv_proj.", ".v.", "v"),
|
||||
(".DenseReluDense.wi.", ".DenseReluDense.wi_0.", 0),
|
||||
(".DenseReluDense.wi.", ".DenseReluDense.wi_1.", 1),
|
||||
]
|
||||
params_dict = dict(self.named_parameters())
|
||||
loaded_params: set[str] = set()
|
||||
|
||||
for name, loaded_weight in weights:
|
||||
matched = False
|
||||
for target_substr, source_substr, shard_id in stacked_params_mapping:
|
||||
if source_substr not in name:
|
||||
continue
|
||||
target_name = name.replace(source_substr, target_substr, 1)
|
||||
if target_name in params_dict:
|
||||
param = params_dict[target_name]
|
||||
param.weight_loader(param, loaded_weight, shard_id)
|
||||
loaded_params.add(target_name)
|
||||
matched = True
|
||||
break
|
||||
|
||||
if matched:
|
||||
continue
|
||||
|
||||
if name in params_dict:
|
||||
param = params_dict[name]
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, loaded_weight)
|
||||
loaded_params.add(name)
|
||||
|
||||
return loaded_params
|
||||
|
||||
|
||||
__all__ = ["T5EncoderBlockByT5Mapper"]
|
||||
@@ -147,6 +147,8 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
ref_text = None
|
||||
lang = "None"
|
||||
instruct = "None"
|
||||
extra = req.sampling_params.extra_args or {}
|
||||
seed = extra.get("seed", None)
|
||||
|
||||
voice_name = None
|
||||
if isinstance(prompt, dict):
|
||||
@@ -157,7 +159,6 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
voice_name = prompt.get("voice_name")
|
||||
lang = prompt.get("lang")
|
||||
instruct = prompt.get("instruct")
|
||||
|
||||
# OmniTextPrompt format (used by offline Omni.generate path):
|
||||
# ref_audio comes via multi_modal_data["audio"] and the rest via
|
||||
# mm_processor_kwargs. Fall back to those when top-level keys are
|
||||
@@ -262,7 +263,6 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
else:
|
||||
cond_ids = torch.cat([text_ids, target_ids], dim=1)
|
||||
cond_len = cond_ids.shape[1]
|
||||
|
||||
uncond_ids = target_ids.clone()
|
||||
uncond_len = target_len
|
||||
max_len = max(cond_len, uncond_len)
|
||||
@@ -297,8 +297,8 @@ class OmniVoicePipeline(nn.Module, SupportAudioOutput):
|
||||
layer_penalty_factor=self.layer_penalty_factor,
|
||||
position_temperature=self.position_temperature,
|
||||
class_temperature=self.class_temperature,
|
||||
seed=seed,
|
||||
)
|
||||
|
||||
# Decode tokens to audio
|
||||
audio = self.decoder(tokens) # [1, 1, samples]
|
||||
|
||||
|
||||
@@ -168,7 +168,10 @@ class OvisImagePipeline(nn.Module, CFGParallelMixin, DiffusionPipelineProfilerMi
|
||||
)
|
||||
|
||||
self.text_encoder = Qwen3Model.from_pretrained(
|
||||
model, subfolder="text_encoder", local_files_only=local_files_only
|
||||
model,
|
||||
subfolder="text_encoder",
|
||||
local_files_only=local_files_only,
|
||||
torch_dtype=od_config.dtype,
|
||||
)
|
||||
|
||||
self.vae = AutoencoderKL.from_pretrained(model, subfolder="vae", local_files_only=local_files_only).to(
|
||||
|
||||
@@ -17,7 +17,6 @@ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
||||
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
||||
from diffusers.models.normalization import AdaLayerNormContinuous
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
@@ -44,11 +43,16 @@ from vllm_omni.diffusion.distributed.sp_plan import (
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context
|
||||
from vllm_omni.diffusion.layers.adalayernorm import AdaLayerNorm
|
||||
from vllm_omni.diffusion.layers.norm import RMSNorm
|
||||
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _join_prefix(prefix: str, suffix: str) -> str:
|
||||
return f"{prefix}.{suffix}" if prefix else suffix
|
||||
|
||||
|
||||
class ImageRopePrepare(nn.Module):
|
||||
"""Prepares image hidden_states and RoPE embeddings for sequence parallel.
|
||||
|
||||
@@ -471,7 +475,12 @@ class FeedForward(nn.Module):
|
||||
|
||||
layers: list[nn.Module] = [
|
||||
ColumnParallelApproxGELU(
|
||||
dim, inner_dim, approximate="tanh", bias=bias, quant_config=quant_config, prefix=prefix
|
||||
dim,
|
||||
inner_dim,
|
||||
approximate="tanh",
|
||||
bias=bias,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "net.0.proj"),
|
||||
),
|
||||
nn.Identity(), # placeholder for weight loading
|
||||
RowParallelLinear(
|
||||
@@ -480,7 +489,7 @@ class FeedForward(nn.Module):
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix=prefix,
|
||||
prefix=_join_prefix(prefix, "net.2"),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -507,6 +516,7 @@ class QwenImageCrossAttention(nn.Module):
|
||||
context_pre_only: bool = False,
|
||||
out_dim: int | None = None,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
) -> None:
|
||||
super().__init__()
|
||||
assert dim % num_heads == 0
|
||||
@@ -523,7 +533,7 @@ class QwenImageCrossAttention(nn.Module):
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=num_heads,
|
||||
quant_config=quant_config,
|
||||
prefix="to_qkv",
|
||||
prefix=_join_prefix(prefix, "to_qkv"),
|
||||
)
|
||||
self.query_num_heads = self.to_qkv.num_heads
|
||||
self.kv_num_heads = self.to_qkv.num_kv_heads
|
||||
@@ -539,7 +549,7 @@ class QwenImageCrossAttention(nn.Module):
|
||||
head_size=head_dim,
|
||||
total_num_heads=num_heads,
|
||||
quant_config=quant_config,
|
||||
prefix="add_kv_proj",
|
||||
prefix=_join_prefix(prefix, "add_kv_proj"),
|
||||
)
|
||||
self.add_query_num_heads = self.add_kv_proj.num_heads
|
||||
self.add_kv_num_heads = self.add_kv_proj.num_kv_heads
|
||||
@@ -552,7 +562,7 @@ class QwenImageCrossAttention(nn.Module):
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix="to_add_out",
|
||||
prefix=_join_prefix(prefix, "to_add_out"),
|
||||
)
|
||||
|
||||
assert not pre_only
|
||||
@@ -563,7 +573,7 @@ class QwenImageCrossAttention(nn.Module):
|
||||
input_is_parallel=True,
|
||||
return_bias=False,
|
||||
quant_config=quant_config,
|
||||
prefix="to_out",
|
||||
prefix=_join_prefix(prefix, "to_out"),
|
||||
)
|
||||
|
||||
self.norm_added_q = RMSNorm(head_dim, eps=eps)
|
||||
@@ -697,6 +707,7 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
eps: float = 1e-6,
|
||||
zero_cond_t: bool = False,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -705,18 +716,20 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
self.attention_head_dim = attention_head_dim
|
||||
|
||||
# Image processing modules.
|
||||
# Modulation linear is kept full precision (quant_config=None) — it
|
||||
# Modulation linear is kept unquantized (quant_config=None) — it
|
||||
# produces shift/scale/gate values that are precision-sensitive
|
||||
# (see #2728).
|
||||
# (see #2728). Use column TP with gather_output=True so weights are
|
||||
# sharded while downstream modulation still receives full [B, 6 * dim].
|
||||
self.img_mod = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
ReplicatedLinear(
|
||||
ColumnParallelLinear(
|
||||
dim,
|
||||
6 * dim,
|
||||
bias=True,
|
||||
gather_output=True,
|
||||
return_bias=False,
|
||||
quant_config=None,
|
||||
prefix="img_mod.1",
|
||||
prefix=_join_prefix(prefix, "img_mod.1"),
|
||||
),
|
||||
)
|
||||
self.img_norm1 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
@@ -727,26 +740,38 @@ class QwenImageTransformerBlock(nn.Module):
|
||||
context_pre_only=False,
|
||||
head_dim=attention_head_dim,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "attn"),
|
||||
)
|
||||
self.img_norm2 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
self.img_mlp = FeedForward(dim=dim, dim_out=dim, quant_config=quant_config, prefix="img_mlp")
|
||||
self.img_mlp = FeedForward(
|
||||
dim=dim,
|
||||
dim_out=dim,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "img_mlp"),
|
||||
)
|
||||
|
||||
# Text processing modules.
|
||||
self.txt_mod = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
ReplicatedLinear(
|
||||
ColumnParallelLinear(
|
||||
dim,
|
||||
6 * dim,
|
||||
bias=True,
|
||||
gather_output=True,
|
||||
return_bias=False,
|
||||
quant_config=None,
|
||||
prefix="txt_mod.1",
|
||||
prefix=_join_prefix(prefix, "txt_mod.1"),
|
||||
),
|
||||
)
|
||||
self.txt_norm1 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
# Text doesn't need separate attention - it's handled by img_attn joint computation
|
||||
self.txt_norm2 = AdaLayerNorm(dim, elementwise_affine=False, eps=eps)
|
||||
self.txt_mlp = FeedForward(dim=dim, dim_out=dim, quant_config=quant_config, prefix="txt_mlp")
|
||||
self.txt_mlp = FeedForward(
|
||||
dim=dim,
|
||||
dim_out=dim,
|
||||
quant_config=quant_config,
|
||||
prefix=_join_prefix(prefix, "txt_mlp"),
|
||||
)
|
||||
|
||||
self.zero_cond_t = zero_cond_t
|
||||
|
||||
@@ -996,8 +1021,9 @@ class QwenImageTransformer2DModel(CachedTransformer):
|
||||
attention_head_dim=attention_head_dim,
|
||||
zero_cond_t=zero_cond_t,
|
||||
quant_config=quant_config,
|
||||
prefix=f"transformer_blocks.{i}",
|
||||
)
|
||||
for _ in range(num_layers)
|
||||
for i in range(num_layers)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@@ -707,7 +707,17 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
return out.past_key_values, out.hidden_states
|
||||
|
||||
def _t2i_predict_v(
|
||||
self, input_embeds, indexes_image, attn_mask, past_key_values, t, z, image_token_num, image_size=None, **_kw
|
||||
self,
|
||||
input_embeds,
|
||||
indexes_image,
|
||||
attn_mask,
|
||||
past_key_values,
|
||||
t,
|
||||
z,
|
||||
image_token_num,
|
||||
image_size=None,
|
||||
cache_dit_skip=False,
|
||||
**_kw,
|
||||
):
|
||||
B, L = z.shape[0], z.shape[1]
|
||||
outputs = self.language_model(
|
||||
@@ -719,6 +729,7 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
attention_mask=attn_mask,
|
||||
past_key_values=past_key_values,
|
||||
update_cache=False,
|
||||
cache_dit_skip=cache_dit_skip,
|
||||
use_cache=True,
|
||||
compute_logits=False,
|
||||
)
|
||||
@@ -1066,6 +1077,13 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
kv_cond = caches["cond"]
|
||||
idx_cond = caches["idx_cond"]
|
||||
mask_cond = caches["mask_cond"]
|
||||
is_it2i = "img_cond" in caches
|
||||
if is_it2i:
|
||||
use_cfg = (t > p.cfg_interval[0] and t < p.cfg_interval[1]) or p.cfg_interval[0] == 0
|
||||
needs_cfg = not (p.cfg_scale == 1 and p.img_cfg_scale == 1)
|
||||
has_cached_partner = use_cfg and needs_cfg
|
||||
else:
|
||||
has_cached_partner = t >= p.cfg_interval[0] and t <= p.cfg_interval[1] and p.cfg_scale > 1
|
||||
|
||||
out_cond = self._t2i_predict_v(
|
||||
image_embeds,
|
||||
@@ -1076,9 +1094,9 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
z,
|
||||
image_token_num=ns.token_h * ns.token_w,
|
||||
image_size=p.image_size,
|
||||
cache_dit_skip=not has_cached_partner,
|
||||
)
|
||||
|
||||
is_it2i = "img_cond" in caches
|
||||
if is_it2i:
|
||||
return self._denoise_step_it2i(out_cond, image_embeds, ns, t, z, caches, p, step_i)
|
||||
return self._denoise_step_t2i(out_cond, image_embeds, ns, t, z, caches, p, step_i)
|
||||
@@ -1153,6 +1171,7 @@ class SenseNovaU1Pipeline(nn.Module, SupportsComponentDiscovery, DiffusionPipeli
|
||||
caches["img_cond"],
|
||||
t,
|
||||
z,
|
||||
cache_dit_skip=True,
|
||||
**predict_kw,
|
||||
)
|
||||
out_uncond = self._t2i_predict_v(
|
||||
|
||||
@@ -587,6 +587,12 @@ class SenseNovaU1DecoderLayer(nn.Module):
|
||||
past_key_values=None,
|
||||
**kwargs,
|
||||
):
|
||||
if isinstance(attention_mask, dict):
|
||||
attention_mask = attention_mask.get(
|
||||
self.attention_type,
|
||||
attention_mask.get("full_attention"),
|
||||
)
|
||||
|
||||
if exist_und and not exist_gen:
|
||||
return self._forward_und(hidden_states, indexes, attention_mask, past_key_values, **kwargs)
|
||||
if not exist_und and exist_gen:
|
||||
@@ -663,7 +669,7 @@ class SenseNovaU1Model(nn.Module):
|
||||
exist_und=exist_und,
|
||||
exist_gen=exist_gen,
|
||||
indexes=indexes,
|
||||
attention_mask=causal_mask_mapping.get(layer.attention_type, causal_mask_mapping.get("full_attention")),
|
||||
attention_mask=causal_mask_mapping,
|
||||
past_key_values=past_key_values,
|
||||
use_cache=use_cache,
|
||||
**kwargs,
|
||||
|
||||
@@ -832,5 +832,8 @@ class ZImagePipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
loaded_weights = loader.load_weights(weights)
|
||||
# Record components loaded by diffusers submodules to satisfy strict checks.
|
||||
loaded_weights |= {f"vae.{name}" for name, _ in self.vae.named_parameters()}
|
||||
loaded_weights |= {f"text_encoder.{name}" for name, _ in self.text_encoder.named_parameters()}
|
||||
# downstream pipelines (e.g. MingImagePipeline) may set ``self.text_encoder = None`` when they
|
||||
# bring their own conditioning path.
|
||||
if self.text_encoder is not None:
|
||||
loaded_weights |= {f"text_encoder.{name}" for name, _ in self.text_encoder.named_parameters()}
|
||||
return loaded_weights
|
||||
@@ -146,6 +146,11 @@ _DIFFUSION_MODELS = {
|
||||
"pipeline_lance",
|
||||
"LancePipeline",
|
||||
),
|
||||
"MingImagePipeline": (
|
||||
"ming_flash_omni",
|
||||
"pipeline_ming_imagegen",
|
||||
"MingImagePipeline",
|
||||
),
|
||||
"InternVLAA1Pipeline": (
|
||||
"internvla_a1",
|
||||
"pipeline_internvla_a1",
|
||||
@@ -266,6 +271,11 @@ _DIFFUSION_MODELS = {
|
||||
"pipeline_diffusers_adapter",
|
||||
"DiffusersAdapterPipeline",
|
||||
),
|
||||
"HiDreamImagePipeline": (
|
||||
"hidream_image",
|
||||
"pipeline_hidream_image",
|
||||
"HiDreamImagePipeline",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
@@ -282,7 +292,6 @@ DiffusionModelRegistry = _ModelRegistry(
|
||||
_NO_CACHE_ACCELERATION = {
|
||||
# Pipelines that do not support cache acceleration (cache_dit / tea_cache).
|
||||
"NextStep11Pipeline",
|
||||
"SenseNovaU1Pipeline",
|
||||
"AudioXPipeline",
|
||||
}
|
||||
|
||||
@@ -468,6 +477,7 @@ _DIFFUSION_POST_PROCESS_FUNCS = {
|
||||
"LongCatImagePipeline": "get_longcat_image_post_process_func",
|
||||
"BagelPipeline": "get_bagel_post_process_func",
|
||||
"LancePipeline": "get_lance_post_process_func",
|
||||
"MingImagePipeline": "get_ming_image_post_process_func",
|
||||
"InternVLAA1Pipeline": "get_internvla_a1_post_process_func",
|
||||
"LongCatImageEditPipeline": "get_longcat_image_post_process_func",
|
||||
"StableDiffusion3Pipeline": "get_sd3_image_post_process_func",
|
||||
@@ -488,6 +498,7 @@ _DIFFUSION_POST_PROCESS_FUNCS = {
|
||||
"OmniVoicePipeline": "get_omnivoice_post_process_func",
|
||||
"DreamIDOmniPipeline": "get_dreamid_omni_post_process_func",
|
||||
"SenseNovaU1Pipeline": "get_sensenova_u1_post_process_func",
|
||||
"HiDreamImagePipeline": "get_hidream_image_post_process_func",
|
||||
}
|
||||
|
||||
_DIFFUSION_PRE_PROCESS_FUNCS = {
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import random
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass
|
||||
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniPromptType
|
||||
|
||||
DUMMY_DIFFUSION_REQUEST_ID = "dummy_req_id"
|
||||
|
||||
|
||||
@dataclass
|
||||
class OmniDiffusionRequest:
|
||||
@@ -24,13 +26,14 @@ class OmniDiffusionRequest:
|
||||
|
||||
prompts: list[OmniPromptType] # Actually supporting str-based prompts
|
||||
sampling_params: OmniDiffusionSamplingParams
|
||||
|
||||
request_ids: list[str] = field(default_factory=list)
|
||||
request_id: str | None = None
|
||||
request_id: str
|
||||
kv_sender_info: dict | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
"""Initialize dependent fields after dataclass initialization."""
|
||||
if not isinstance(self.request_id, str) or not self.request_id:
|
||||
raise ValueError("OmniDiffusionRequest.request_id must be a non-empty string.")
|
||||
|
||||
# When neither a generator nor a seed is provided, assign a random seed
|
||||
# so that all ranks derive the same generator state.
|
||||
if self.sampling_params.generator is None and self.sampling_params.seed is None:
|
||||
@@ -56,3 +59,10 @@ class OmniDiffusionRequest:
|
||||
# so downstream code always has a valid value.
|
||||
if self.sampling_params.guidance_scale_2 is None:
|
||||
self.sampling_params.guidance_scale_2 = self.sampling_params.guidance_scale
|
||||
|
||||
def is_dummy_run(self) -> bool:
|
||||
return self.is_dummy_run_request_id(self.request_id)
|
||||
|
||||
@classmethod
|
||||
def is_dummy_run_request_id(cls, request_id: str | None) -> bool:
|
||||
return request_id == DUMMY_DIFFUSION_REQUEST_ID
|
||||
@@ -46,7 +46,6 @@ class _BaseScheduler(SchedulerInterface):
|
||||
def __init__(self) -> None:
|
||||
self.od_config: OmniDiffusionConfig | None = None
|
||||
self._request_states: dict[str, DiffusionRequestState] = {}
|
||||
self._request_id_to_sched_req_id: dict[str, str] = {}
|
||||
self._step_id: int = 0
|
||||
self._waiting: deque[str] = deque()
|
||||
self._running: list[str] = []
|
||||
@@ -57,7 +56,6 @@ class _BaseScheduler(SchedulerInterface):
|
||||
def initialize(self, od_config: OmniDiffusionConfig) -> None:
|
||||
self.od_config = od_config
|
||||
self._request_states.clear()
|
||||
self._request_id_to_sched_req_id.clear()
|
||||
self._step_id = 0
|
||||
self._waiting.clear()
|
||||
self._running.clear()
|
||||
@@ -71,32 +69,31 @@ class _BaseScheduler(SchedulerInterface):
|
||||
self._reset_scheduler_state()
|
||||
|
||||
def add_request(self, request: OmniDiffusionRequest) -> str:
|
||||
sched_req_id = self._make_sched_req_id(request)
|
||||
return self._add_request_with_sched_req_id(sched_req_id, request)
|
||||
return self._add_request_with_request_id(request.request_id, request)
|
||||
|
||||
def _add_request_with_sched_req_id(self, sched_req_id: str, request: OmniDiffusionRequest) -> str:
|
||||
state = self._make_request_state(sched_req_id, request)
|
||||
request_ids = self._request_ids_for_mapping(request)
|
||||
self._register_request_ids(request_ids, sched_req_id)
|
||||
self._request_states[sched_req_id] = state
|
||||
self._waiting.append(sched_req_id)
|
||||
logger.debug("%s add_request: %s (waiting=%d)", self.__class__.__name__, sched_req_id, len(self._waiting))
|
||||
return sched_req_id
|
||||
def _add_request_with_request_id(self, request_id: str, request: OmniDiffusionRequest) -> str:
|
||||
if request_id in self._request_states:
|
||||
raise ValueError(f"request_id {request_id!r} is already active.")
|
||||
state = self._make_request_state(request_id, request)
|
||||
self._request_states[request_id] = state
|
||||
self._waiting.append(request_id)
|
||||
logger.debug("%s add_request: %s (waiting=%d)", self.__class__.__name__, request_id, len(self._waiting))
|
||||
return request_id
|
||||
|
||||
def schedule(self) -> DiffusionSchedulerOutput:
|
||||
scheduled_new_reqs: list[NewRequestData] = []
|
||||
scheduled_cached_req_ids: list[str] = []
|
||||
scheduled_cached_request_ids: list[str] = []
|
||||
|
||||
# First, schedule the RUNNING request(s)
|
||||
for sched_req_id in self._running:
|
||||
state = self._request_states.get(sched_req_id)
|
||||
for request_id in self._running:
|
||||
state = self._request_states.get(request_id)
|
||||
if state is not None:
|
||||
scheduled_cached_req_ids.append(sched_req_id)
|
||||
scheduled_cached_request_ids.append(request_id)
|
||||
|
||||
# Second, schedule WAITING requests while capacity remains.
|
||||
while self._waiting and len(self._running) < self.max_num_running_reqs:
|
||||
sched_req_id = self._waiting[0]
|
||||
state = self._request_states.get(sched_req_id)
|
||||
request_id = self._waiting[0]
|
||||
state = self._request_states.get(request_id)
|
||||
if state is None:
|
||||
self._waiting.popleft()
|
||||
continue
|
||||
@@ -108,16 +105,16 @@ class _BaseScheduler(SchedulerInterface):
|
||||
if not self._running:
|
||||
self._running_sampling_params_key = state.sampling_params_key
|
||||
state.status = DiffusionRequestStatus.RUNNING
|
||||
self._running.append(sched_req_id)
|
||||
self._running.append(request_id)
|
||||
if was_new_request:
|
||||
scheduled_new_reqs.append(NewRequestData.from_state(state))
|
||||
else:
|
||||
scheduled_cached_req_ids.append(sched_req_id)
|
||||
scheduled_cached_request_ids.append(request_id)
|
||||
|
||||
scheduler_output = DiffusionSchedulerOutput(
|
||||
step_id=self._step_id,
|
||||
scheduled_new_reqs=scheduled_new_reqs,
|
||||
scheduled_cached_reqs=CachedRequestData(sched_req_ids=scheduled_cached_req_ids),
|
||||
scheduled_cached_reqs=CachedRequestData(request_ids=scheduled_cached_request_ids),
|
||||
finished_req_ids=set(self._finished_req_ids),
|
||||
num_running_reqs=len(self._running),
|
||||
num_waiting_reqs=len(self._waiting),
|
||||
@@ -131,40 +128,33 @@ class _BaseScheduler(SchedulerInterface):
|
||||
def has_requests(self) -> bool:
|
||||
return bool(self._waiting or self._running)
|
||||
|
||||
def get_request_state(self, sched_req_id: str) -> DiffusionRequestState | None:
|
||||
return self._request_states.get(sched_req_id)
|
||||
def get_request_state(self, request_id: str) -> DiffusionRequestState | None:
|
||||
return self._request_states.get(request_id)
|
||||
|
||||
def get_sched_req_id(self, request_id: str) -> str | None:
|
||||
return self._request_id_to_sched_req_id.get(request_id)
|
||||
def pop_request_state(self, request_id: str) -> DiffusionRequestState | None:
|
||||
self._pop_extra_request_state(request_id)
|
||||
return self._request_states.pop(request_id, None)
|
||||
|
||||
def pop_request_state(self, sched_req_id: str) -> DiffusionRequestState | None:
|
||||
self._pop_extra_request_state(sched_req_id)
|
||||
state = self._request_states.pop(sched_req_id, None)
|
||||
if state is not None:
|
||||
self._unregister_request_ids(self._request_ids_for_mapping(state.req), sched_req_id)
|
||||
return state
|
||||
|
||||
def preempt_request(self, sched_req_id: str) -> bool:
|
||||
if sched_req_id not in self._request_states:
|
||||
def preempt_request(self, request_id: str) -> bool:
|
||||
if request_id not in self._request_states:
|
||||
return False
|
||||
if sched_req_id in self._running:
|
||||
self._running.remove(sched_req_id)
|
||||
if request_id in self._running:
|
||||
self._running.remove(request_id)
|
||||
if not self._running:
|
||||
self._running_sampling_params_key = None
|
||||
self._waiting.appendleft(sched_req_id)
|
||||
self._request_states[sched_req_id].status = DiffusionRequestStatus.PREEMPTED
|
||||
self._waiting.appendleft(request_id)
|
||||
self._request_states[request_id].status = DiffusionRequestStatus.PREEMPTED
|
||||
return True
|
||||
return False
|
||||
|
||||
def finish_requests(self, sched_req_ids: str | list[str], status: DiffusionRequestStatus) -> None:
|
||||
def finish_requests(self, request_ids: str | list[str], status: DiffusionRequestStatus) -> None:
|
||||
assert DiffusionRequestStatus.is_finished(status)
|
||||
if isinstance(sched_req_ids, str):
|
||||
sched_req_ids = [sched_req_ids]
|
||||
self._finish_requests({sched_req_id: status for sched_req_id in sched_req_ids})
|
||||
if isinstance(request_ids, str):
|
||||
request_ids = [request_ids]
|
||||
self._finish_requests({request_id: status for request_id in request_ids})
|
||||
|
||||
def close(self) -> None:
|
||||
self._request_states.clear()
|
||||
self._request_id_to_sched_req_id.clear()
|
||||
self._waiting.clear()
|
||||
self._running.clear()
|
||||
self._running_sampling_params_key = None
|
||||
@@ -183,33 +173,31 @@ class _BaseScheduler(SchedulerInterface):
|
||||
running_to_remove: set[str] = set()
|
||||
waiting_to_remove: set[str] = set()
|
||||
|
||||
for sched_req_id, status in statuses.items():
|
||||
for request_id, status in statuses.items():
|
||||
assert DiffusionRequestStatus.is_finished(status)
|
||||
state = self._request_states.get(sched_req_id)
|
||||
state = self._request_states.get(request_id)
|
||||
if state is None or state.is_finished():
|
||||
continue
|
||||
|
||||
finished_req_ids.add(sched_req_id)
|
||||
if sched_req_id in self._running:
|
||||
running_to_remove.add(sched_req_id)
|
||||
if sched_req_id in self._waiting:
|
||||
waiting_to_remove.add(sched_req_id)
|
||||
finished_req_ids.add(request_id)
|
||||
if request_id in self._running:
|
||||
running_to_remove.add(request_id)
|
||||
if request_id in self._waiting:
|
||||
waiting_to_remove.add(request_id)
|
||||
|
||||
if running_to_remove:
|
||||
self._running = [sched_req_id for sched_req_id in self._running if sched_req_id not in running_to_remove]
|
||||
self._running = [request_id for request_id in self._running if request_id not in running_to_remove]
|
||||
if not self._running:
|
||||
self._running_sampling_params_key = None
|
||||
if waiting_to_remove:
|
||||
self._waiting = deque(
|
||||
sched_req_id for sched_req_id in self._waiting if sched_req_id not in waiting_to_remove
|
||||
)
|
||||
self._waiting = deque(request_id for request_id in self._waiting if request_id not in waiting_to_remove)
|
||||
|
||||
for sched_req_id in finished_req_ids:
|
||||
state = self._request_states[sched_req_id]
|
||||
status = statuses[sched_req_id]
|
||||
for request_id in finished_req_ids:
|
||||
state = self._request_states[request_id]
|
||||
status = statuses[request_id]
|
||||
state.status = status
|
||||
if status == DiffusionRequestStatus.FINISHED_ERROR:
|
||||
state.error = None if errors is None else errors.get(sched_req_id)
|
||||
state.error = None if errors is None else errors.get(request_id)
|
||||
else:
|
||||
state.error = None
|
||||
|
||||
@@ -227,7 +215,7 @@ class _BaseScheduler(SchedulerInterface):
|
||||
# marked finished at that point, but we still need to surface its id
|
||||
# in this update so the engine can observe the terminal state.
|
||||
finished_req_ids = {
|
||||
sched_req_id for sched_req_id in sched_output.scheduled_req_ids if sched_req_id in self._finished_req_ids
|
||||
request_id for request_id in sched_output.scheduled_request_ids if request_id in self._finished_req_ids
|
||||
}
|
||||
finished_req_ids |= self._finish_requests(statuses, errors)
|
||||
return finished_req_ids
|
||||
@@ -235,12 +223,12 @@ class _BaseScheduler(SchedulerInterface):
|
||||
def _reset_scheduler_state(self) -> None:
|
||||
"""Reset subclass-owned state during initialize()/close()."""
|
||||
|
||||
def _pop_extra_request_state(self, sched_req_id: str) -> None:
|
||||
def _pop_extra_request_state(self, request_id: str) -> None:
|
||||
"""Remove subclass-owned per-request state before popping request state."""
|
||||
|
||||
def _make_request_state(self, sched_req_id: str, request: OmniDiffusionRequest) -> DiffusionRequestState:
|
||||
def _make_request_state(self, request_id: str, request: OmniDiffusionRequest) -> DiffusionRequestState:
|
||||
return DiffusionRequestState(
|
||||
sched_req_id=sched_req_id,
|
||||
request_id=request_id,
|
||||
req=request,
|
||||
sampling_params_key=get_sampling_params_key(request),
|
||||
)
|
||||
@@ -258,24 +246,3 @@ class _BaseScheduler(SchedulerInterface):
|
||||
state = self._request_states.get(self._running[0])
|
||||
self._running_sampling_params_key = None if state is None else state.sampling_params_key
|
||||
return self._running_sampling_params_key
|
||||
|
||||
def _register_request_ids(self, request_ids: list[str], sched_req_id: str) -> None:
|
||||
unique_request_ids = list(dict.fromkeys(request_ids))
|
||||
for request_id in unique_request_ids:
|
||||
existing = self._request_id_to_sched_req_id.get(request_id)
|
||||
if existing is not None and existing != sched_req_id:
|
||||
raise ValueError(f"request_id {request_id!r} is already mapped to active sched_req_id {existing!r}.")
|
||||
for request_id in unique_request_ids:
|
||||
self._request_id_to_sched_req_id[request_id] = sched_req_id
|
||||
|
||||
def _unregister_request_ids(self, request_ids: list[str], sched_req_id: str) -> None:
|
||||
for request_id in request_ids:
|
||||
if self._request_id_to_sched_req_id.get(request_id) == sched_req_id:
|
||||
self._request_id_to_sched_req_id.pop(request_id, None)
|
||||
|
||||
@staticmethod
|
||||
def _request_ids_for_mapping(request: OmniDiffusionRequest) -> list[str]:
|
||||
request_ids = list(request.request_ids)
|
||||
if request_id := getattr(request, "request_id", None):
|
||||
request_ids.append(request_id)
|
||||
return list(dict.fromkeys(request_ids))
|
||||
@@ -4,22 +4,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import enum
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.worker.utils import RunnerOutput
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class DiffusionRequestStatus(enum.IntEnum):
|
||||
"""Request status tracked by diffusion scheduler."""
|
||||
@@ -75,10 +70,7 @@ class SamplingParamsKey:
|
||||
class DiffusionRequestState:
|
||||
"""Scheduler-owned state for one queued OmniDiffusionRequest."""
|
||||
|
||||
# Unique scheduler-owned request ID.
|
||||
# NOTE: This identifies one OmniDiffusionRequest, which may contain multiple request_ids.
|
||||
# TODO: Align this with OmniDiffusionRequest.request_ids once scheduler batching is supported.
|
||||
sched_req_id: str
|
||||
request_id: str
|
||||
req: OmniDiffusionRequest
|
||||
sampling_params_key: SamplingParamsKey | None = None
|
||||
status: DiffusionRequestStatus = DiffusionRequestStatus.WAITING
|
||||
@@ -92,23 +84,23 @@ class DiffusionRequestState:
|
||||
class NewRequestData:
|
||||
"""Full request payload for a newly scheduled diffusion request."""
|
||||
|
||||
sched_req_id: str
|
||||
request_id: str
|
||||
req: OmniDiffusionRequest
|
||||
|
||||
@classmethod
|
||||
def from_state(cls, state: DiffusionRequestState) -> NewRequestData:
|
||||
return cls(sched_req_id=state.sched_req_id, req=state.req)
|
||||
return cls(request_id=state.request_id, req=state.req)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CachedRequestData:
|
||||
"""Cached diffusion requests that only need their scheduler ids resent."""
|
||||
"""Cached diffusion requests that only need their request ids resent."""
|
||||
|
||||
sched_req_ids: list[str]
|
||||
request_ids: list[str]
|
||||
|
||||
@classmethod
|
||||
def make_empty(cls) -> CachedRequestData:
|
||||
return cls(sched_req_ids=[])
|
||||
return cls(request_ids=[])
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -123,21 +115,18 @@ class DiffusionSchedulerOutput:
|
||||
num_waiting_reqs: int
|
||||
|
||||
@cached_property
|
||||
def scheduled_req_ids(self) -> list[str]:
|
||||
def scheduled_request_ids(self) -> list[str]:
|
||||
"""
|
||||
All scheduled request ids in this cycle, including both new and cached ones.
|
||||
NOTE:
|
||||
This id is generated and owned by the scheduler,
|
||||
and may be different from the OmniDiffusionRequest.request_ids.
|
||||
"""
|
||||
return [
|
||||
*(req.sched_req_id for req in self.scheduled_new_reqs),
|
||||
*self.scheduled_cached_reqs.sched_req_ids,
|
||||
*(req.request_id for req in self.scheduled_new_reqs),
|
||||
*self.scheduled_cached_reqs.request_ids,
|
||||
]
|
||||
|
||||
@property
|
||||
def num_scheduled_reqs(self) -> int:
|
||||
return len(self.scheduled_req_ids)
|
||||
return len(self.scheduled_request_ids)
|
||||
|
||||
@property
|
||||
def is_empty(self) -> bool:
|
||||
@@ -147,25 +136,6 @@ class DiffusionSchedulerOutput:
|
||||
class SchedulerInterface(ABC):
|
||||
"""Abstract lifecycle contract for diffusion schedulers."""
|
||||
|
||||
def _make_sched_req_id(self, request: OmniDiffusionRequest) -> str:
|
||||
"""
|
||||
Generate a unique scheduler request ID for the given request.
|
||||
The default implementation uses the first request_id from the request if available,
|
||||
otherwise generates a random one.
|
||||
"""
|
||||
if request.request_ids:
|
||||
base = request.request_ids[0]
|
||||
else:
|
||||
logger.warning("Request has no request_ids, generating a random one. Request: %s", request)
|
||||
base = f"req_{uuid.uuid4().hex[:8]}"
|
||||
|
||||
sched_req_id = base
|
||||
suffix = 1
|
||||
while self.get_request_state(sched_req_id) is not None:
|
||||
sched_req_id = f"{base}#{suffix}"
|
||||
suffix += 1
|
||||
return sched_req_id
|
||||
|
||||
@abstractmethod
|
||||
def initialize(self, od_config: OmniDiffusionConfig) -> None:
|
||||
"""Initialize or reset scheduler state."""
|
||||
@@ -183,7 +153,7 @@ class SchedulerInterface(ABC):
|
||||
"""Update scheduler state from executor output."""
|
||||
|
||||
@abstractmethod
|
||||
def get_request_state(self, sched_req_id: str) -> DiffusionRequestState | None:
|
||||
def get_request_state(self, request_id: str) -> DiffusionRequestState | None:
|
||||
"""Return request state if present."""
|
||||
|
||||
@abstractmethod
|
||||
@@ -191,19 +161,15 @@ class SchedulerInterface(ABC):
|
||||
"""Return whether the scheduler still owns runnable requests."""
|
||||
|
||||
@abstractmethod
|
||||
def get_sched_req_id(self, request_id: str) -> str | None:
|
||||
"""Resolve a public request_id to the active scheduler request id."""
|
||||
|
||||
@abstractmethod
|
||||
def pop_request_state(self, sched_req_id: str) -> DiffusionRequestState | None:
|
||||
def pop_request_state(self, request_id: str) -> DiffusionRequestState | None:
|
||||
"""Remove and return request state if present."""
|
||||
|
||||
@abstractmethod
|
||||
def preempt_request(self, sched_req_id: str) -> bool:
|
||||
def preempt_request(self, request_id: str) -> bool:
|
||||
"""Preempt a running request back to waiting."""
|
||||
|
||||
@abstractmethod
|
||||
def finish_requests(self, sched_req_ids: str | list[str], status: DiffusionRequestStatus) -> None:
|
||||
def finish_requests(self, request_ids: str | list[str], status: DiffusionRequestStatus) -> None:
|
||||
"""Mark one or more requests finished."""
|
||||
|
||||
@abstractmethod
|
||||
|
||||
@@ -26,26 +26,26 @@ class RequestScheduler(_BaseScheduler):
|
||||
return super().schedule()
|
||||
|
||||
def update_from_output(self, sched_output: DiffusionSchedulerOutput, output: RunnerOutput) -> set[str]:
|
||||
scheduled_req_ids = sched_output.scheduled_req_ids
|
||||
if not scheduled_req_ids:
|
||||
scheduled_request_ids = sched_output.scheduled_request_ids
|
||||
if not scheduled_request_ids:
|
||||
return set()
|
||||
|
||||
terminal_statuses: dict[str, DiffusionRequestStatus] = {}
|
||||
terminal_errors: dict[str, str | None] = {}
|
||||
for sched_req_id in scheduled_req_ids:
|
||||
state = self._request_states.get(sched_req_id)
|
||||
for request_id in scheduled_request_ids:
|
||||
state = self._request_states.get(request_id)
|
||||
if state is None or state.is_finished():
|
||||
continue
|
||||
req_output = output.get_req_output(sched_req_id)
|
||||
req_output = output.get_request_output(request_id)
|
||||
result = req_output.result if req_output is not None else None
|
||||
if result is None:
|
||||
terminal_statuses[sched_req_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[sched_req_id] = "No output result"
|
||||
terminal_statuses[request_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[request_id] = "No output result"
|
||||
elif result.error:
|
||||
terminal_statuses[sched_req_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[sched_req_id] = result.error
|
||||
terminal_statuses[request_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[request_id] = result.error
|
||||
else:
|
||||
terminal_statuses[sched_req_id] = DiffusionRequestStatus.FINISHED_COMPLETED
|
||||
terminal_errors[sched_req_id] = None
|
||||
terminal_statuses[request_id] = DiffusionRequestStatus.FINISHED_COMPLETED
|
||||
terminal_errors[request_id] = None
|
||||
|
||||
return self._finalize_update_from_output(sched_output, terminal_statuses, terminal_errors)
|
||||
@@ -38,84 +38,84 @@ class StepScheduler(_BaseScheduler):
|
||||
self._request_progress.clear()
|
||||
|
||||
def add_request(self, request: OmniDiffusionRequest) -> str:
|
||||
sched_req_id = self._make_sched_req_id(request)
|
||||
request_id = request.request_id
|
||||
total_steps = self._get_total_steps(request)
|
||||
if total_steps <= 0:
|
||||
raise ValueError(f"Diffusion request {sched_req_id} must have positive total_steps, got {total_steps}")
|
||||
raise ValueError(f"Diffusion request {request_id} must have positive total_steps, got {total_steps}")
|
||||
|
||||
current_step = request.sampling_params.step_index or 0
|
||||
if current_step < 0 or current_step >= total_steps:
|
||||
raise ValueError(
|
||||
f"Diffusion request {sched_req_id} has invalid initial step_index {current_step} "
|
||||
f"Diffusion request {request_id} has invalid initial step_index {current_step} "
|
||||
f"for total_steps={total_steps}"
|
||||
)
|
||||
|
||||
request.sampling_params.step_index = current_step
|
||||
sched_req_id = self._add_request_with_sched_req_id(sched_req_id, request)
|
||||
self._request_progress[sched_req_id] = _StepProgress(current_step=current_step, total_steps=total_steps)
|
||||
request_id = self._add_request_with_request_id(request_id, request)
|
||||
self._request_progress[request_id] = _StepProgress(current_step=current_step, total_steps=total_steps)
|
||||
logger.debug(
|
||||
"StepScheduler add_request: %s (step=%d/%d, waiting=%d)",
|
||||
sched_req_id,
|
||||
request_id,
|
||||
current_step,
|
||||
total_steps,
|
||||
len(self._waiting),
|
||||
)
|
||||
return sched_req_id
|
||||
return request_id
|
||||
|
||||
def schedule(self) -> DiffusionSchedulerOutput:
|
||||
return super().schedule()
|
||||
|
||||
def update_from_output(self, sched_output: DiffusionSchedulerOutput, output: RunnerOutput) -> set[str]:
|
||||
scheduled_req_ids = sched_output.scheduled_req_ids
|
||||
if not scheduled_req_ids:
|
||||
scheduled_request_ids = sched_output.scheduled_request_ids
|
||||
if not scheduled_request_ids:
|
||||
return set()
|
||||
|
||||
terminal_statuses: dict[str, DiffusionRequestStatus] = {}
|
||||
terminal_errors: dict[str, str | None] = {}
|
||||
for sched_req_id in scheduled_req_ids:
|
||||
state = self._request_states.get(sched_req_id)
|
||||
progress = self._request_progress.get(sched_req_id)
|
||||
for request_id in scheduled_request_ids:
|
||||
state = self._request_states.get(request_id)
|
||||
progress = self._request_progress.get(request_id)
|
||||
if state is None or progress is None or state.is_finished():
|
||||
continue
|
||||
req_output = output.get_req_output(sched_req_id)
|
||||
req_output = output.get_request_output(request_id)
|
||||
if req_output is None:
|
||||
logger.warning(
|
||||
"No RunnerOutput for request %s, treating as error",
|
||||
sched_req_id,
|
||||
request_id,
|
||||
)
|
||||
terminal_statuses[sched_req_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[sched_req_id] = "No output for request"
|
||||
terminal_statuses[request_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[request_id] = "No output for request"
|
||||
continue
|
||||
|
||||
req_result = req_output.result
|
||||
output_error = req_result.error if req_result is not None else None
|
||||
if output_error is not None:
|
||||
terminal_statuses[sched_req_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[sched_req_id] = output_error
|
||||
terminal_statuses[request_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[request_id] = output_error
|
||||
continue
|
||||
|
||||
if req_output.step_index is None:
|
||||
logger.warning(
|
||||
"Received RunnerOutput with no step_index for request %s, treating as error",
|
||||
sched_req_id,
|
||||
request_id,
|
||||
)
|
||||
terminal_statuses[sched_req_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[sched_req_id] = "Missing step_index in RunnerOutput"
|
||||
terminal_statuses[request_id] = DiffusionRequestStatus.FINISHED_ERROR
|
||||
terminal_errors[request_id] = "Missing step_index in RunnerOutput"
|
||||
continue
|
||||
|
||||
# We assume that the decoding stage is executed immediately after the denoising stage completes.
|
||||
progress.current_step = req_output.step_index
|
||||
state.req.sampling_params.step_index = req_output.step_index
|
||||
if req_output.finished:
|
||||
terminal_statuses[sched_req_id] = DiffusionRequestStatus.FINISHED_COMPLETED
|
||||
terminal_errors[sched_req_id] = None
|
||||
terminal_statuses[request_id] = DiffusionRequestStatus.FINISHED_COMPLETED
|
||||
terminal_errors[request_id] = None
|
||||
else:
|
||||
state.error = None
|
||||
|
||||
return self._finalize_update_from_output(sched_output, terminal_statuses, terminal_errors)
|
||||
|
||||
def _pop_extra_request_state(self, sched_req_id: str) -> None:
|
||||
self._request_progress.pop(sched_req_id, None)
|
||||
def _pop_extra_request_state(self, request_id: str) -> None:
|
||||
self._request_progress.pop(request_id, None)
|
||||
|
||||
def _get_total_steps(self, request: OmniDiffusionRequest) -> int:
|
||||
sampling = request.sampling_params
|
||||
|
||||
@@ -32,6 +32,7 @@ from vllm_omni.distributed.omni_connectors.utils.serialization import (
|
||||
OmniMsgpackEncoder,
|
||||
)
|
||||
from vllm_omni.distributed.omni_coordinator import OmniCoordClientForStage
|
||||
from vllm_omni.engine.stage_init_utils import set_death_signal
|
||||
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
@@ -41,6 +42,14 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
_SIGNAL_EXIT_BASE = 128
|
||||
|
||||
|
||||
def _signal_exit_code(signum: int) -> int:
|
||||
"""Return the conventional process exit code for signal-driven exits."""
|
||||
return _SIGNAL_EXIT_BASE + signum
|
||||
|
||||
|
||||
class StageDiffusionProc:
|
||||
"""Subprocess entry point for diffusion inference.
|
||||
|
||||
@@ -150,7 +159,6 @@ class StageDiffusionProc:
|
||||
request = OmniDiffusionRequest(
|
||||
prompts=[prompt],
|
||||
sampling_params=sampling_params,
|
||||
request_ids=[request_id],
|
||||
request_id=request_id,
|
||||
kv_sender_info=kv_sender_info,
|
||||
)
|
||||
@@ -180,7 +188,6 @@ class StageDiffusionProc:
|
||||
request = OmniDiffusionRequest(
|
||||
prompts=prompts,
|
||||
sampling_params=sampling_params,
|
||||
request_ids=[f"{request_id}-{i}" for i in range(len(prompts))],
|
||||
request_id=request_id,
|
||||
kv_sender_info=kv_sender_info,
|
||||
)
|
||||
@@ -624,11 +631,13 @@ class StageDiffusionProc:
|
||||
"""
|
||||
shutdown_requested = False
|
||||
|
||||
set_death_signal(signal.SIGTERM)
|
||||
|
||||
def signal_handler(signum: int, frame: Any) -> None:
|
||||
nonlocal shutdown_requested
|
||||
if not shutdown_requested:
|
||||
shutdown_requested = True
|
||||
raise SystemExit(128 + signum)
|
||||
raise SystemExit(_signal_exit_code(signum))
|
||||
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
@@ -23,6 +23,10 @@ from vllm.logger import init_logger
|
||||
from vllm.utils.mem_utils import DeviceMemoryProfiler, GiB_bytes
|
||||
|
||||
from vllm_omni.diffusion.cache.cache_dit_backend import cache_summary
|
||||
from vllm_omni.diffusion.cache.prompt_embed_cache import (
|
||||
install_prompt_embed_cache,
|
||||
resolve_prompt_embed_cache_config,
|
||||
)
|
||||
from vllm_omni.diffusion.cache.selector import get_cache_backend
|
||||
from vllm_omni.diffusion.compile import regionally_compile
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
@@ -71,6 +75,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
self.pipeline = None
|
||||
self.cache_backend = None
|
||||
self.offload_backend = None
|
||||
self.prompt_embed_cache = None
|
||||
|
||||
# Cache for per-request stepwise state.
|
||||
self.state_cache: dict[str, DiffusionRequestState] = {}
|
||||
@@ -97,7 +102,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
self,
|
||||
memory_pool_context_fn: callable | None = None,
|
||||
load_format: str | None = None,
|
||||
custom_pipeline_name: str | None = None,
|
||||
custom_pipeline_name: str | type | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Load the diffusion model, apply compilation and offloading.
|
||||
@@ -187,12 +192,38 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
else:
|
||||
self.cache_backend.enable(self.pipeline)
|
||||
|
||||
# Install prompt-embedding cache (transparent wrapper around
|
||||
# ``pipeline.encode_prompt``). Enabled via config or env var; a no-op
|
||||
# when the pipeline does not expose ``encode_prompt``.
|
||||
enable_pec, pec_size = resolve_prompt_embed_cache_config(
|
||||
enable=getattr(self.od_config, "enable_prompt_embed_cache", False),
|
||||
max_size=getattr(self.od_config, "prompt_embed_cache_size", 32),
|
||||
)
|
||||
if enable_pec:
|
||||
self.prompt_embed_cache = install_prompt_embed_cache(
|
||||
self.pipeline,
|
||||
max_size=pec_size,
|
||||
enabled=True,
|
||||
model_tag=self.od_config.model_class_name,
|
||||
)
|
||||
|
||||
logger.info("Model runner: Initialization complete.")
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load weights into the pipeline."""
|
||||
return self.pipeline.load_weights(weights)
|
||||
|
||||
def clear_prompt_embed_cache(self) -> None:
|
||||
"""Evict all cached text-encoder outputs (e.g. between training epochs)."""
|
||||
if self.prompt_embed_cache is not None:
|
||||
self.prompt_embed_cache.clear()
|
||||
|
||||
def get_prompt_embed_cache_stats(self) -> dict | None:
|
||||
"""Return hit/miss statistics for the prompt-embedding cache, if enabled."""
|
||||
if self.prompt_embed_cache is None:
|
||||
return None
|
||||
return self.prompt_embed_cache.stats()
|
||||
|
||||
def _record_peak_memory(self, output: DiffusionOutput) -> None:
|
||||
"""Record peak GPU memory for the current forward pass into output.
|
||||
|
||||
@@ -299,6 +330,10 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
if is_primary:
|
||||
self._record_peak_memory(output)
|
||||
|
||||
# Log prompt-embed cache activity (hits/misses accumulate across requests).
|
||||
if is_primary and self.prompt_embed_cache is not None:
|
||||
logger.debug("prompt-embed cache: %s", self.prompt_embed_cache.stats())
|
||||
|
||||
# NOTE:
|
||||
if (
|
||||
self.cache_backend is not None
|
||||
@@ -322,50 +357,44 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
self, scheduler_output: DiffusionSchedulerOutput
|
||||
) -> tuple[list[DiffusionRequestState], list[str]]:
|
||||
"""Step-before update: cleanup finished requests and get/create one running state."""
|
||||
for req_id in scheduler_output.finished_req_ids:
|
||||
self.state_cache.pop(req_id, None)
|
||||
for request_id in scheduler_output.finished_req_ids:
|
||||
self.state_cache.pop(request_id, None)
|
||||
|
||||
resolved: list[DiffusionRequestState] = []
|
||||
new_req_id: list[str] = []
|
||||
new_request_ids: list[str] = []
|
||||
try:
|
||||
# process new requests
|
||||
for sched_new_req in scheduler_output.scheduled_new_reqs:
|
||||
# new_req_data = scheduler_output.scheduled_new_reqs[0]
|
||||
req_id = sched_new_req.sched_req_id
|
||||
request_id = sched_new_req.request_id
|
||||
req = sched_new_req.req
|
||||
new_req_id.append(req_id)
|
||||
if req_id in self.state_cache:
|
||||
raise ValueError(f"Received duplicate new-request payload for cached request {req_id}.")
|
||||
request_ids = req.request_ids or [req_id]
|
||||
if len(request_ids) != len(req.prompts):
|
||||
raise ValueError(
|
||||
f"request_ids length ({len(request_ids)}) does not match prompts length ({len(req.prompts)})"
|
||||
)
|
||||
new_request_ids.append(request_id)
|
||||
if request_id in self.state_cache:
|
||||
raise ValueError(f"Received duplicate new-request payload for cached request {request_id}.")
|
||||
new_state = DiffusionRequestState(
|
||||
req_id=req_id,
|
||||
request_id=request_id,
|
||||
sampling=copy.deepcopy(req.sampling_params),
|
||||
prompts=req.prompts,
|
||||
)
|
||||
self.state_cache[req_id] = new_state
|
||||
self.state_cache[request_id] = new_state
|
||||
resolved.append(new_state)
|
||||
|
||||
# process cached requests
|
||||
for req_id in scheduler_output.scheduled_cached_reqs.sched_req_ids:
|
||||
state = self.state_cache.get(req_id)
|
||||
for request_id in scheduler_output.scheduled_cached_reqs.request_ids:
|
||||
state = self.state_cache.get(request_id)
|
||||
if state is None:
|
||||
raise ValueError(f"Missing cached state for request {req_id}.")
|
||||
raise ValueError(f"Missing cached state for request {request_id}.")
|
||||
resolved.append(state)
|
||||
except Exception:
|
||||
for req_id in new_req_id:
|
||||
self.state_cache.pop(req_id, None)
|
||||
for request_id in new_request_ids:
|
||||
self.state_cache.pop(request_id, None)
|
||||
raise
|
||||
|
||||
return resolved, new_req_id
|
||||
return resolved, new_request_ids
|
||||
|
||||
def _prepare_batch_inputs(self, states: list[DiffusionRequestState], new_request_ids: list[str]) -> InputBatch:
|
||||
# process new reqs
|
||||
for state in states:
|
||||
if state.req_id in new_request_ids:
|
||||
if state.request_id in new_request_ids:
|
||||
# set generator
|
||||
if state.sampling.generator is None and state.sampling.seed is not None:
|
||||
if state.sampling.generator_device is not None:
|
||||
@@ -407,7 +436,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
|
||||
for state in states:
|
||||
if interrupted or state.denoise_completed:
|
||||
self.state_cache.pop(state.req_id, None)
|
||||
self.state_cache.pop(state.request_id, None)
|
||||
|
||||
def _prepare_attn_metadata(self, input_batch: InputBatch) -> Any:
|
||||
model_state = getattr(self, "model_state", None)
|
||||
@@ -449,7 +478,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
for state in states:
|
||||
runner_output_list.append(
|
||||
RunnerOutput(
|
||||
req_id=state.req_id,
|
||||
request_id=state.request_id,
|
||||
step_index=state.step_index,
|
||||
finished=True,
|
||||
result=DiffusionOutput(error="stepwise denoise interrupted"),
|
||||
@@ -470,7 +499,7 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
|
||||
result = None
|
||||
runner_output_list.append(
|
||||
RunnerOutput(
|
||||
req_id=req.req_id,
|
||||
request_id=req.request_id,
|
||||
step_index=req.step_index,
|
||||
finished=req.denoise_completed,
|
||||
result=result,
|
||||
|
||||
@@ -11,6 +11,7 @@ to DiffusionModelRunner.
|
||||
import gc
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import signal
|
||||
from collections.abc import Iterable, Iterator
|
||||
from contextlib import AbstractContextManager, contextmanager, nullcontext
|
||||
from dataclasses import dataclass
|
||||
@@ -46,6 +47,7 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.sched.interface import DiffusionSchedulerOutput
|
||||
from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunner
|
||||
from vllm_omni.diffusion.worker.utils import BaseRunnerOutput
|
||||
from vllm_omni.engine.stage_init_utils import set_death_signal
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
from vllm_omni.profiler import OmniTorchProfilerWrapper, create_omni_profiler
|
||||
@@ -187,7 +189,7 @@ class DiffusionWorker:
|
||||
self.lora_manager: DiffusionLoRAManager | None = None
|
||||
# Worker-side cache of (lora_request, lora_scale) per scheduled
|
||||
# request id. Used by step mode to recover LoRA identity for cached
|
||||
# requests, which only carry their sched_req_id in subsequent ticks.
|
||||
# requests, which only carry their request_id in subsequent ticks.
|
||||
self._step_lora_state: dict[str, tuple[LoRARequest | None, float]] = {}
|
||||
self.stage_id = getattr(od_config, "stage_id", 0)
|
||||
self.init_device()
|
||||
@@ -389,12 +391,12 @@ class DiffusionWorker:
|
||||
homogeneity is enforced by the scheduler via ``SamplingParamsKey``,
|
||||
so any scheduled request id resolves to the active LoRA identity.
|
||||
"""
|
||||
for sched_req_id in scheduler_output.finished_req_ids:
|
||||
self._step_lora_state.pop(sched_req_id, None)
|
||||
for request_id in scheduler_output.finished_req_ids:
|
||||
self._step_lora_state.pop(request_id, None)
|
||||
|
||||
for new_req in scheduler_output.scheduled_new_reqs:
|
||||
sampling = new_req.req.sampling_params
|
||||
self._step_lora_state[new_req.sched_req_id] = (
|
||||
self._step_lora_state[new_req.request_id] = (
|
||||
sampling.lora_request,
|
||||
sampling.lora_scale,
|
||||
)
|
||||
@@ -404,8 +406,8 @@ class DiffusionWorker:
|
||||
|
||||
lora_request: LoRARequest | None = None
|
||||
lora_scale = 1.0
|
||||
for sched_req_id in scheduler_output.scheduled_req_ids:
|
||||
entry = self._step_lora_state.get(sched_req_id)
|
||||
for request_id in scheduler_output.scheduled_request_ids:
|
||||
entry = self._step_lora_state.get(request_id)
|
||||
if entry is not None:
|
||||
lora_request, lora_scale = entry
|
||||
break
|
||||
@@ -520,11 +522,11 @@ class DiffusionWorker:
|
||||
logger.info(f"[Worker {self.rank}] Handshake Received: Task {task.task_id}")
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
usage_before = current_omni_platform.get_current_memory_usage(self.device)
|
||||
free_before = current_omni_platform.get_free_memory(self.device)
|
||||
self.sleep(level=task.level)
|
||||
current_omni_platform.synchronize()
|
||||
usage_after = current_omni_platform.get_current_memory_usage(self.device)
|
||||
real_freed = max(0, usage_before - usage_after)
|
||||
free_after = current_omni_platform.get_free_memory(self.device)
|
||||
real_freed = max(0, free_after - free_before)
|
||||
logger.info(f"[Worker {self.rank}] Preparing ACK: freed_bytes={real_freed / GiB_bytes:.2f} GiB.")
|
||||
|
||||
# Ensure all ranks have completed sleep before measuring memory and sending ACK
|
||||
@@ -536,6 +538,11 @@ class DiffusionWorker:
|
||||
if self.rank != 0:
|
||||
return None
|
||||
|
||||
try:
|
||||
total_mem = current_omni_platform.get_device_total_memory()
|
||||
except (NotImplementedError, AttributeError):
|
||||
total_mem = torch.cuda.get_device_properties(self.device).total_memory
|
||||
residual_gib = (total_mem - free_after) / GiB_bytes
|
||||
ack = OmniACK(
|
||||
task_id=task.task_id,
|
||||
status="SUCCESS",
|
||||
@@ -546,7 +553,7 @@ class DiffusionWorker:
|
||||
metadata={
|
||||
"source": f"Platform_{current_omni_platform.get_device_name()}",
|
||||
"total_freed_gib": f"{real_freed / GiB_bytes:.2f}",
|
||||
"rank_residual_gib": f"{usage_after / GiB_bytes:.2f}",
|
||||
"rank_residual_gib": f"{residual_gib:.2f}",
|
||||
},
|
||||
)
|
||||
logger.info(f"[Worker {self.rank}] ACK emitted. Freed {real_freed / GiB_bytes:.2f} GiB.")
|
||||
@@ -574,8 +581,12 @@ class DiffusionWorker:
|
||||
torch.distributed.barrier()
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
usage_now = current_omni_platform.get_current_memory_usage(self.device)
|
||||
current_used_gib = usage_now / (1024**3)
|
||||
free_now = current_omni_platform.get_free_memory(self.device)
|
||||
try:
|
||||
total_mem = current_omni_platform.get_device_total_memory()
|
||||
except (NotImplementedError, AttributeError):
|
||||
total_mem = torch.cuda.get_device_properties(self.device).total_memory
|
||||
current_used_gib = (total_mem - free_now) / (1024**3)
|
||||
|
||||
if self.rank != 0:
|
||||
return None
|
||||
@@ -812,11 +823,6 @@ class WorkerProc:
|
||||
continue
|
||||
|
||||
logger.info("event loop terminated.")
|
||||
try:
|
||||
self.worker.shutdown()
|
||||
except Exception as exc:
|
||||
logger.warning("Worker %s: Shutdown encountered an error: %s", self.gpu_id, exc)
|
||||
self.context.term()
|
||||
|
||||
@staticmethod
|
||||
def worker_main(
|
||||
@@ -831,32 +837,62 @@ class WorkerProc:
|
||||
"""Worker initialization and execution loops."""
|
||||
from vllm_omni.plugins import load_omni_general_plugins
|
||||
|
||||
shutdown_triggered = False
|
||||
|
||||
def signal_handler(signum: int, frame) -> None:
|
||||
nonlocal shutdown_triggered
|
||||
if not shutdown_triggered:
|
||||
shutdown_triggered = True
|
||||
raise SystemExit(128 + signum)
|
||||
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
set_death_signal(signal.SIGTERM)
|
||||
|
||||
# Set process title for visibility in nvidia-smi / htop (optional, non-fatal)
|
||||
try:
|
||||
import setproctitle
|
||||
|
||||
setproctitle.setproctitle(f"vLLM-Omni::StageDiffusionProc-{rank}")
|
||||
setproctitle.setproctitle(f"vLLM-Omni::DiffusionWorker-{rank}")
|
||||
except ImportError:
|
||||
pass # setproctitle not installed, skip process title setting
|
||||
|
||||
load_omni_general_plugins()
|
||||
worker_proc = WorkerProc(
|
||||
od_config,
|
||||
gpu_id=rank,
|
||||
broadcast_handle=broadcast_handle,
|
||||
wake_event=wake_event,
|
||||
worker_extension_cls=worker_extension_cls,
|
||||
custom_pipeline_args=custom_pipeline_args,
|
||||
)
|
||||
logger.info(f"Worker {rank}: Scheduler loop started.")
|
||||
pipe_writer.send(
|
||||
{
|
||||
"status": "ready",
|
||||
"result_handle": worker_proc.result_mq_handle if rank == 0 else None,
|
||||
}
|
||||
)
|
||||
worker_proc.worker_busy_loop()
|
||||
logger.info(f"Worker {rank}: Shutdown complete.")
|
||||
worker_proc = None
|
||||
try:
|
||||
worker_proc = WorkerProc(
|
||||
od_config,
|
||||
gpu_id=rank,
|
||||
broadcast_handle=broadcast_handle,
|
||||
wake_event=wake_event,
|
||||
worker_extension_cls=worker_extension_cls,
|
||||
custom_pipeline_args=custom_pipeline_args,
|
||||
)
|
||||
logger.info(f"Worker {rank}: Scheduler loop started.")
|
||||
pipe_writer.send(
|
||||
{
|
||||
"status": "ready",
|
||||
"result_handle": worker_proc.result_mq_handle if rank == 0 else None,
|
||||
}
|
||||
)
|
||||
worker_proc.worker_busy_loop()
|
||||
except SystemExit:
|
||||
logger.info("Worker %d: Shutdown signal received, starting cleanup.", rank)
|
||||
raise
|
||||
finally:
|
||||
if worker_proc is not None:
|
||||
try:
|
||||
worker_proc.worker.shutdown()
|
||||
except Exception as exc:
|
||||
logger.warning("Worker %d: Shutdown encountered an error: %s", rank, exc)
|
||||
worker_proc.context.term()
|
||||
else:
|
||||
# In case of signal interrupting worker_proc initialization
|
||||
# where distributed env is initialized but worker_proc is still None
|
||||
destroy_distributed_env()
|
||||
|
||||
logger.info("Worker %d: Shutdown complete.", rank)
|
||||
|
||||
|
||||
class WorkerWrapperBase:
|
||||
|
||||
@@ -81,8 +81,8 @@ def _select_states(
|
||||
return selected_states, idx_mapping, idx_mapping.detach().cpu().numpy()
|
||||
|
||||
|
||||
def _prepare_req_ids(states: Sequence[DiffusionRequestState]) -> list[str]:
|
||||
return [state.req_id for state in states]
|
||||
def _prepare_request_ids(states: Sequence[DiffusionRequestState]) -> list[str]:
|
||||
return [state.request_id for state in states]
|
||||
|
||||
|
||||
def _prepare_prompt_field_on_state(
|
||||
@@ -192,11 +192,13 @@ def _get_request_prompt_seq_lens(
|
||||
mask_attr=mask_attr,
|
||||
)
|
||||
if embeds is None:
|
||||
raise ValueError(f"{embeds_attr} is not initialized on request {state.req_id}.")
|
||||
raise ValueError(f"{embeds_attr} is not initialized on request {state.request_id}.")
|
||||
|
||||
if mask is not None:
|
||||
if mask.shape[0] != embeds.shape[0]:
|
||||
raise ValueError(f"{mask_attr} batch dimension does not match {embeds_attr} for request {state.req_id}.")
|
||||
raise ValueError(
|
||||
f"{mask_attr} batch dimension does not match {embeds_attr} for request {state.request_id}."
|
||||
)
|
||||
return _get_seq_lens_from_mask(mask)
|
||||
|
||||
seq_lens = getattr(state, seq_lens_attr)
|
||||
@@ -220,7 +222,7 @@ def _prepare_request_prompt_field(
|
||||
mask_attr=mask_attr,
|
||||
)
|
||||
if embeds is None:
|
||||
raise ValueError(f"{embeds_attr} is not initialized on request {state.req_id}.")
|
||||
raise ValueError(f"{embeds_attr} is not initialized on request {state.request_id}.")
|
||||
|
||||
actual_seq_lens = _get_request_prompt_seq_lens(
|
||||
state,
|
||||
@@ -248,7 +250,7 @@ def _prepare_request_prompt_field(
|
||||
if current_seq_len > target_seq_len:
|
||||
if max_actual_seq_len > target_seq_len:
|
||||
raise ValueError(
|
||||
f"{embeds_attr} for request {state.req_id} requires seq_len "
|
||||
f"{embeds_attr} for request {state.request_id} requires seq_len "
|
||||
f"{max_actual_seq_len}, got target {target_seq_len}."
|
||||
)
|
||||
return embeds[:, :target_seq_len], None if mask is None else mask[:, :target_seq_len]
|
||||
@@ -349,7 +351,7 @@ def _require_state_latents(
|
||||
) -> torch.Tensor:
|
||||
latents = state.latents
|
||||
if latents is None:
|
||||
raise ValueError(f"Request {state.req_id} has no latents while preparing {for_field}.")
|
||||
raise ValueError(f"Request {state.request_id} has no latents while preparing {for_field}.")
|
||||
return latents
|
||||
|
||||
|
||||
@@ -526,12 +528,12 @@ def _prepare_negative_prompt_embeds(
|
||||
|
||||
def _same_composition(
|
||||
cached_batch: InputBatch | None,
|
||||
req_ids: list[str],
|
||||
request_ids: list[str],
|
||||
idx_mapping_np: np.ndarray,
|
||||
) -> bool:
|
||||
if cached_batch is None:
|
||||
return False
|
||||
if cached_batch.req_ids != req_ids:
|
||||
if cached_batch.request_ids != request_ids:
|
||||
return False
|
||||
return np.array_equal(cached_batch.idx_mapping_np, idx_mapping_np)
|
||||
|
||||
@@ -581,7 +583,7 @@ class InputBatch:
|
||||
unchanged.
|
||||
"""
|
||||
|
||||
req_ids: list[str]
|
||||
request_ids: list[str]
|
||||
num_reqs: int
|
||||
num_reqs_after_padding: int
|
||||
idx_mapping: torch.Tensor
|
||||
@@ -604,9 +606,9 @@ class InputBatch:
|
||||
negative_txt_seq_lens: list[int] | None = None
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if len(self.req_ids) != int(self.idx_mapping.numel()):
|
||||
raise ValueError("`req_ids` and `idx_mapping` must have the same length.")
|
||||
if self.num_reqs != len(self.req_ids):
|
||||
if len(self.request_ids) != int(self.idx_mapping.numel()):
|
||||
raise ValueError("`request_ids` and `idx_mapping` must have the same length.")
|
||||
if self.num_reqs != len(self.request_ids):
|
||||
raise ValueError("`num_reqs` must match the number of request ids.")
|
||||
if self.num_reqs_after_padding < self.num_reqs:
|
||||
raise ValueError("`num_reqs_after_padding` must be >= `num_reqs`.")
|
||||
@@ -653,11 +655,11 @@ class InputBatch:
|
||||
selected_states: Sequence[DiffusionRequestState],
|
||||
idx_mapping: torch.Tensor,
|
||||
idx_mapping_np: np.ndarray,
|
||||
req_ids: list[str],
|
||||
request_ids: list[str],
|
||||
) -> InputBatch:
|
||||
self.req_ids = req_ids
|
||||
self.num_reqs = len(req_ids)
|
||||
self.num_reqs_after_padding = len(req_ids)
|
||||
self.request_ids = request_ids
|
||||
self.num_reqs = len(request_ids)
|
||||
self.num_reqs_after_padding = len(request_ids)
|
||||
self.idx_mapping = idx_mapping
|
||||
self.idx_mapping_np = idx_mapping_np
|
||||
self.latents = _prepare_latents(selected_states, out=self.latents)
|
||||
@@ -675,9 +677,9 @@ class InputBatch:
|
||||
) -> InputBatch:
|
||||
"""Build a temporary step-local batch view from request states."""
|
||||
selected_states, idx_mapping, idx_mapping_np = _select_states(states, idx_mapping)
|
||||
req_ids = _prepare_req_ids(selected_states)
|
||||
request_ids = _prepare_request_ids(selected_states)
|
||||
|
||||
if _same_composition(cached_batch, req_ids, idx_mapping_np):
|
||||
if _same_composition(cached_batch, request_ids, idx_mapping_np):
|
||||
assert cached_batch is not None
|
||||
cached_batch._repack_dynamic_fields(selected_states)
|
||||
return cached_batch
|
||||
@@ -687,14 +689,14 @@ class InputBatch:
|
||||
selected_states,
|
||||
idx_mapping,
|
||||
idx_mapping_np,
|
||||
req_ids,
|
||||
request_ids,
|
||||
)
|
||||
|
||||
prompt_embeds, prompt_embeds_mask = _prepare_prompt_embeds(selected_states)
|
||||
negative_prompt_embeds, negative_prompt_embeds_mask = _prepare_negative_prompt_embeds(selected_states)
|
||||
do_true_cfg, true_cfg_scale, cfg_normalize = _prepare_cfg_scalars(selected_states)
|
||||
return cls(
|
||||
req_ids=req_ids,
|
||||
request_ids=request_ids,
|
||||
num_reqs=len(selected_states),
|
||||
num_reqs_after_padding=len(selected_states),
|
||||
idx_mapping=idx_mapping,
|
||||
|
||||
@@ -38,7 +38,7 @@ class DiffusionRequestState:
|
||||
"""
|
||||
|
||||
# ── Identity / request-level inputs ──
|
||||
req_id: str
|
||||
request_id: str
|
||||
sampling: OmniDiffusionSamplingParams
|
||||
prompts: list[OmniPromptType] | None = None
|
||||
|
||||
@@ -112,7 +112,7 @@ class DiffusionRequestState:
|
||||
|
||||
class BaseRunnerOutput(ABC):
|
||||
@abstractmethod
|
||||
def get_req_output(self, sched_req_id: str) -> RunnerOutput | None:
|
||||
def get_request_output(self, request_id: str) -> RunnerOutput | None:
|
||||
pass
|
||||
|
||||
|
||||
@@ -125,13 +125,13 @@ class RunnerOutput(BaseRunnerOutput):
|
||||
_request_state_cache.
|
||||
"""
|
||||
|
||||
req_id: str
|
||||
request_id: str
|
||||
step_index: int | None = None
|
||||
finished: bool = False
|
||||
result: DiffusionOutput | None = None
|
||||
|
||||
def get_req_output(self, sched_req_id: str) -> RunnerOutput | None:
|
||||
return self if self.req_id == sched_req_id else None
|
||||
def get_request_output(self, request_id: str) -> RunnerOutput | None:
|
||||
return self if self.request_id == request_id else None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -140,18 +140,18 @@ class BatchRunnerOutput(BaseRunnerOutput):
|
||||
_id_to_idx: dict[str, int] = field(init=False, repr=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._id_to_idx = {out.req_id: i for i, out in enumerate(self.runner_outputs)}
|
||||
self._id_to_idx = {out.request_id: i for i, out in enumerate(self.runner_outputs)}
|
||||
|
||||
def __getitem__(self, req_id: str) -> RunnerOutput | None:
|
||||
"""access single RunnerOutput by req_id"""
|
||||
idx = self._id_to_idx.get(req_id)
|
||||
def __getitem__(self, request_id: str) -> RunnerOutput | None:
|
||||
"""access single RunnerOutput by request_id"""
|
||||
idx = self._id_to_idx.get(request_id)
|
||||
return self.runner_outputs[idx] if idx is not None else None
|
||||
|
||||
def get_req_output(self, sched_req_id: str) -> RunnerOutput | None:
|
||||
return self[sched_req_id]
|
||||
def get_request_output(self, request_id: str) -> RunnerOutput | None:
|
||||
return self[request_id]
|
||||
|
||||
@property
|
||||
def req_ids(self) -> list[str]:
|
||||
def request_ids(self) -> list[str]:
|
||||
return list(self._id_to_idx.keys())
|
||||
|
||||
def __len__(self) -> int:
|
||||
|
||||
Reference in new issue
Block a user