Signed-off-by: lyj-jjj <liuyingjun5@huawei.com> Signed-off-by: gcanlin <canlinguosdu@gmail.com> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: gcanlin <canlinguosdu@gmail.com>
This commit is contained in:
20 files changed
+823
-25
No files matched your search
@@ -67,6 +67,10 @@ class AttentionMetadata:
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
# Opaque backend-specific per-forward parameters (e.g. block masks, KV indices).
|
||||
# Backends MUST silently ignore unknown keys.
|
||||
#
|
||||
# Well-known optional keys (convention, not required on all forwards):
|
||||
# "kv_cache_dtype": str | None — quantized KV dtype (e.g. "fp8"); backends
|
||||
# decide whether/how to apply.
|
||||
|
||||
# Piecewise attention metadata (mixed causal/full masks).
|
||||
# full_attn_spans: per-sample [start, end) spans in global coordinates using full attention.
|
||||
@@ -77,6 +81,14 @@ T = TypeVar("T", bound=AttentionMetadata)
|
||||
|
||||
|
||||
class AttentionImpl(ABC, Generic[T]):
|
||||
# Per-platform kv_cache_dtype support. Maps OmniPlatformEnum value
|
||||
# (e.g. "cuda", "npu") to the set of quantized dtypes that platform
|
||||
# handles.
|
||||
#
|
||||
# To add FP8 support for a new platform in a subclass:
|
||||
# _supported_kv_cache_dtypes = {"cuda": {"fp8"}, "npu": {"fp8"}}
|
||||
_supported_kv_cache_dtypes: dict[str, set[str]] = {}
|
||||
|
||||
@abstractmethod
|
||||
def __init__(
|
||||
self,
|
||||
@@ -92,6 +104,12 @@ class AttentionImpl(ABC, Generic[T]):
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
@classmethod
|
||||
def supports_kv_cache_dtype(cls, kv_cache_dtype: str | None, platform_key: str) -> bool:
|
||||
if kv_cache_dtype is None:
|
||||
return True
|
||||
return kv_cache_dtype in cls._supported_kv_cache_dtypes.get(platform_key, set())
|
||||
|
||||
def forward(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
|
||||
@@ -39,6 +39,20 @@ class FlashAttentionBackend(AttentionBackend):
|
||||
|
||||
|
||||
class FlashAttentionImpl(AttentionImpl):
|
||||
# Per-platform FP8 KV quantization support.
|
||||
# To enable FP8 on a new platform, add its OmniPlatformEnum value here
|
||||
# and handle kv_cache_dtype in the corresponding forward_{platform}().
|
||||
#
|
||||
# TODO(quant-backend): The FP8 quant path currently lives inside
|
||||
# FlashAttentionImpl gated by ``attn_metadata.extra["kv_cache_dtype"]``.
|
||||
# Eventually extract it into a dedicated FlashAttentionQuantBackend so
|
||||
# backend selection (not metadata) decides quant. Until then, model
|
||||
# authors can opt a specific Attention layer out via
|
||||
# ``Attention(disable_kv_quant=True)``.
|
||||
_supported_kv_cache_dtypes = {
|
||||
"npu": {"fp8"},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
@@ -250,6 +264,39 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
attn_metadata: AttentionMetadata = None,
|
||||
) -> torch.Tensor:
|
||||
"""NPU attention implementation using mindiesd."""
|
||||
|
||||
kv_cache_dtype = attn_metadata.extra.get("kv_cache_dtype") if attn_metadata else None
|
||||
if kv_cache_dtype is not None:
|
||||
return self.forward_fa_quant_npu(query, key, value, attn_metadata)
|
||||
return self.forward_fa_npu(query, key, value, attn_metadata)
|
||||
|
||||
def forward_fa_quant_npu(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata = None,
|
||||
) -> torch.Tensor:
|
||||
from vllm_omni.platforms.npu.quant.kv_quant_npu import fp8_rotate_quant_fa
|
||||
|
||||
layout = self.qkv_layout or "BNSD"
|
||||
# Models pass (B, S, H, D); NPU fused op expects (B, N, S, D).
|
||||
out = fp8_rotate_quant_fa(
|
||||
query.transpose(1, 2),
|
||||
key.transpose(1, 2),
|
||||
value.transpose(1, 2),
|
||||
layout=layout,
|
||||
softmax_scale=self.softmax_scale,
|
||||
)
|
||||
return out.transpose(1, 2)
|
||||
|
||||
def forward_fa_npu(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata = None,
|
||||
) -> torch.Tensor:
|
||||
try:
|
||||
from mindiesd import attention_forward
|
||||
except ImportError:
|
||||
@@ -259,10 +306,9 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
"For installation details, see https://gitcode.com/Ascend/MindIE-SD"
|
||||
"Otherwise, use SDPA backend by setting DIFFUSION_ATTENTION_BACKEND=TORCH_SDPA"
|
||||
)
|
||||
|
||||
attention_mask = attn_metadata.attn_mask if attn_metadata else None
|
||||
layout = self.qkv_layout or "BNSD"
|
||||
output = attention_forward(
|
||||
return attention_forward(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
@@ -271,4 +317,3 @@ class FlashAttentionImpl(AttentionImpl):
|
||||
op_type="fused_attn_score",
|
||||
layout=layout,
|
||||
)
|
||||
return output
|
||||
@@ -7,9 +7,12 @@
|
||||
# https://github.com/feifeibear/long-context-attention/blob/main/yunchang/attention/layer.py
|
||||
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.models.utils import extract_layer_index
|
||||
|
||||
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
|
||||
from vllm_omni.diffusion.attention.backends.sdpa import SDPABackend
|
||||
@@ -20,10 +23,20 @@ from vllm_omni.diffusion.attention.selector import get_attn_backend_for_role
|
||||
from vllm_omni.diffusion.config import get_current_diffusion_config_or_none
|
||||
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
|
||||
from vllm_omni.diffusion.forward_context import get_forward_context, is_forward_context_available
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _try_extract_layer_index(prefix: str) -> int | None:
|
||||
if not prefix:
|
||||
return None
|
||||
try:
|
||||
return extract_layer_index(prefix)
|
||||
except (AssertionError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
class Attention(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
@@ -43,6 +56,11 @@ class Attention(nn.Module):
|
||||
gather_idx: int = 1,
|
||||
use_sync: bool = False,
|
||||
skip_sequence_parallel: bool = False,
|
||||
# Opt-out for KV-cache quantization at this specific attention layer.
|
||||
# Set by the model author when quant is known to degrade quality or
|
||||
# perf for this layer (e.g. Wan2.2 cross-attn has short sequences and
|
||||
# block-FP8 quant offers no win). Default False = follow global config.
|
||||
disable_kv_quant: bool = False,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -126,6 +144,15 @@ class Attention(nn.Module):
|
||||
# Fallback strategy when SP is not active (outside sharded regions)
|
||||
self._no_parallel_strategy = NoParallelAttention()
|
||||
|
||||
self.layer_idx: int | None = _try_extract_layer_index(prefix)
|
||||
|
||||
self._kv_cache_dtype: str | None = None
|
||||
self._kv_cache_skip_steps: set[int] | None = None
|
||||
self._kv_cache_skip_layers: set[int] | None = None
|
||||
# Per-layer opt-out from KV-cache quantization (set by model author).
|
||||
self._disable_kv_quant: bool = disable_kv_quant
|
||||
self._init_kv_cache_quantization(config)
|
||||
|
||||
def _get_active_parallel_strategy(self):
|
||||
"""Get the parallel strategy based on current SP active state.
|
||||
|
||||
@@ -141,12 +168,64 @@ class Attention(nn.Module):
|
||||
return self._no_parallel_strategy
|
||||
return self.parallel_strategy
|
||||
|
||||
def _init_kv_cache_quantization(self, config) -> None:
|
||||
if config is None:
|
||||
return
|
||||
dtype = config.kv_cache_dtype
|
||||
if dtype:
|
||||
if config.parallel_config.ring_degree > 1:
|
||||
raise ValueError(
|
||||
"KV quantization is not compatible with ring attention "
|
||||
"(ring_degree > 1). Ring kernels do not propagate quantization descale "
|
||||
"factors. Use Ulysses SP instead."
|
||||
)
|
||||
platform_key = current_omni_platform.device_name
|
||||
if not self.attention.supports_kv_cache_dtype(dtype, platform_key):
|
||||
logger.warning_once(
|
||||
"Attention backend %s does not support kv_cache_dtype='%s' on %s. "
|
||||
"KV quantization will be disabled.",
|
||||
self.attn_backend.get_name(),
|
||||
dtype,
|
||||
platform_key,
|
||||
)
|
||||
dtype = None
|
||||
self._kv_cache_dtype = dtype
|
||||
self._kv_cache_skip_steps = config.kv_cache_skip_step_indices
|
||||
self._kv_cache_skip_layers = config.kv_cache_skip_layer_indices
|
||||
|
||||
def _should_apply_kv_cache_quant(self) -> bool:
|
||||
skip_steps = self._kv_cache_skip_steps
|
||||
skip_layers = self._kv_cache_skip_layers
|
||||
if skip_steps is not None:
|
||||
step_idx = get_forward_context().denoise_step_idx if is_forward_context_available() else None
|
||||
if step_idx is not None and step_idx in skip_steps:
|
||||
return False
|
||||
if skip_layers is not None:
|
||||
if self.layer_idx is not None and self.layer_idx in skip_layers:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _with_kv_cache_dtype(self, attn_metadata: AttentionMetadata | None) -> AttentionMetadata | None:
|
||||
kv_cache_dtype = self._kv_cache_dtype
|
||||
if kv_cache_dtype is None or self._disable_kv_quant or not self._should_apply_kv_cache_quant():
|
||||
if attn_metadata is None or "kv_cache_dtype" not in attn_metadata.extra:
|
||||
return attn_metadata
|
||||
extra = dict(attn_metadata.extra)
|
||||
extra.pop("kv_cache_dtype", None)
|
||||
return replace(attn_metadata, extra=extra)
|
||||
|
||||
if attn_metadata is None:
|
||||
return AttentionMetadata(extra={"kv_cache_dtype": kv_cache_dtype})
|
||||
extra = dict(attn_metadata.extra)
|
||||
extra["kv_cache_dtype"] = kv_cache_dtype
|
||||
return replace(attn_metadata, extra=extra)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata = None,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
# Get the appropriate parallel strategy based on SP active state
|
||||
strategy = self._get_active_parallel_strategy()
|
||||
@@ -156,6 +235,8 @@ class Attention(nn.Module):
|
||||
# For Ring: Concat joint_q
|
||||
query, key, value, attn_metadata, ctx = strategy.pre_attention(query, key, value, attn_metadata)
|
||||
|
||||
attn_metadata = self._with_kv_cache_dtype(attn_metadata)
|
||||
|
||||
# 2. Kernel Execution (Computation)
|
||||
if self.use_ring and strategy is not self._no_parallel_strategy:
|
||||
out = self._run_ring_attention(query, key, value, attn_metadata)
|
||||
|
||||
@@ -32,6 +32,54 @@ if TYPE_CHECKING:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def parse_kv_cache_skip_selector(
|
||||
selector: str | list[int] | tuple[int, ...] | set[int] | None,
|
||||
) -> set[int] | None:
|
||||
"""Parse a non-negative index selector such as "0-9,20,25-30"."""
|
||||
if selector is None:
|
||||
return None
|
||||
if isinstance(selector, set):
|
||||
values = selector
|
||||
elif isinstance(selector, (list, tuple)):
|
||||
values = set(selector)
|
||||
elif isinstance(selector, str):
|
||||
text = selector.strip()
|
||||
if not text:
|
||||
return None
|
||||
values: set[int] = set()
|
||||
for chunk in text.split(","):
|
||||
token = chunk.strip()
|
||||
if not token:
|
||||
continue
|
||||
if "-" in token:
|
||||
start_str, end_str = token.split("-", 1)
|
||||
try:
|
||||
start = int(start_str.strip())
|
||||
end = int(end_str.strip())
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid range token '{token}' in selector '{selector}'.") from exc
|
||||
if start < 0 or end < 0 or start > end:
|
||||
raise ValueError(f"Invalid range token '{token}' in selector '{selector}'.")
|
||||
values.update(range(start, end + 1))
|
||||
else:
|
||||
try:
|
||||
index = int(token)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid index token '{token}' in selector '{selector}'.") from exc
|
||||
if index < 0:
|
||||
raise ValueError(f"Negative index '{index}' is not allowed in selector '{selector}'.")
|
||||
values.add(index)
|
||||
else:
|
||||
raise TypeError(f"Unsupported selector type: {type(selector)!r}")
|
||||
|
||||
for idx in values:
|
||||
if not isinstance(idx, int):
|
||||
raise TypeError(f"Selector index must be int, got {type(idx)!r}")
|
||||
if idx < 0:
|
||||
raise ValueError("Selector indices must be non-negative.")
|
||||
return values
|
||||
|
||||
|
||||
@config
|
||||
@dataclass
|
||||
class DiffusionParallelConfig:
|
||||
@@ -519,6 +567,19 @@ class OmniDiffusionConfig:
|
||||
# has already resolved to vLLM's ModelOpt FP8 linear method.
|
||||
force_cutlass_fp8: bool = False
|
||||
|
||||
# KV cache dtype for attention. Aligned with upstream vLLM's --kv-cache-dtype.
|
||||
# None = native dtype (no quantization).
|
||||
# "fp8" = dynamic FP8 (float8_e4m3fn) quantization per forward pass.
|
||||
# On Hopper+FA3: native FP8 attention (memory + compute savings).
|
||||
# On other backends: no benefit, backends skip quantization.
|
||||
kv_cache_dtype: str | None = None
|
||||
# Optional skip selectors for KV-cache quantization. Format: "0-9,20,25-30".
|
||||
# Listed steps/layers skip quantization; others keep quantized execution.
|
||||
kv_cache_skip_steps: str | None = None
|
||||
kv_cache_skip_layers: str | None = None
|
||||
kv_cache_skip_step_indices: set[int] | None = None
|
||||
kv_cache_skip_layer_indices: set[int] | None = None
|
||||
|
||||
# Diffusion pipeline Profiling config
|
||||
enable_diffusion_pipeline_profiler: bool = False
|
||||
|
||||
@@ -527,6 +588,7 @@ class OmniDiffusionConfig:
|
||||
|
||||
# sleep mode
|
||||
enable_sleep_mode: bool = False
|
||||
|
||||
# Maximum number of sequences to generate in a batch
|
||||
max_num_seqs: int = 1
|
||||
|
||||
@@ -656,6 +718,8 @@ class OmniDiffusionConfig:
|
||||
# Match vLLM's config flow: parse entrypoint shorthands before the
|
||||
# config object is built, and keep a single runtime truth source.
|
||||
self.diffusion_attention_config = build_attention_config(self.diffusion_attention_config)
|
||||
self.kv_cache_skip_step_indices = parse_kv_cache_skip_selector(self.kv_cache_skip_steps)
|
||||
self.kv_cache_skip_layer_indices = parse_kv_cache_skip_selector(self.kv_cache_skip_layers)
|
||||
|
||||
if self.max_cpu_loras is None:
|
||||
self.max_cpu_loras = 1
|
||||
|
||||
@@ -22,6 +22,7 @@ class ForwardContext:
|
||||
omni_diffusion_config: OmniDiffusionConfig | None = None
|
||||
attn_metadata: dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None = None
|
||||
split_text_embed_in_sp: bool = False
|
||||
denoise_step_idx: int | 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
|
||||
@@ -103,12 +104,14 @@ def create_forward_context(
|
||||
omni_diffusion_config: OmniDiffusionConfig | None = None,
|
||||
attn_metadata: dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None = None,
|
||||
split_text_embed_in_sp: bool = False,
|
||||
denoise_step_idx: int | None = None,
|
||||
):
|
||||
return ForwardContext(
|
||||
vllm_config=vllm_config,
|
||||
omni_diffusion_config=omni_diffusion_config,
|
||||
attn_metadata=attn_metadata,
|
||||
split_text_embed_in_sp=split_text_embed_in_sp,
|
||||
denoise_step_idx=denoise_step_idx,
|
||||
)
|
||||
|
||||
|
||||
@@ -133,6 +136,7 @@ def set_forward_context(
|
||||
omni_diffusion_config: OmniDiffusionConfig | None = None,
|
||||
attn_metadata: dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None = None,
|
||||
split_text_embed_in_sp: bool = False,
|
||||
denoise_step_idx: int | None = None,
|
||||
):
|
||||
"""A context manager that stores the current forward context,
|
||||
can be attention metadata, split_text_embed_in_sp, etc.
|
||||
@@ -143,6 +147,7 @@ def set_forward_context(
|
||||
omni_diffusion_config=omni_diffusion_config,
|
||||
attn_metadata=attn_metadata,
|
||||
split_text_embed_in_sp=split_text_embed_in_sp,
|
||||
denoise_step_idx=denoise_step_idx,
|
||||
)
|
||||
# vLLM CustomOp dispatch (e.g. QKVParallelLinear) requires a global
|
||||
# vLLM config set via set_current_vllm_config().
|
||||
@@ -160,3 +165,9 @@ def set_forward_context(
|
||||
vllm.ir.enable_torch_wrap(vllm_config.compilation_config.ir_enable_torch_wrap),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
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
|
||||
@@ -21,6 +21,7 @@ from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -403,9 +404,12 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipe
|
||||
latent_condition: torch.Tensor | None = None,
|
||||
first_frame_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if attention_kwargs is None:
|
||||
attention_kwargs = {}
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
for step_idx, t in enumerate(timesteps):
|
||||
self._current_timestep = t
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
|
||||
# Select model based on timestep and boundary_ratio
|
||||
# High noise stage (t >= boundary_timestep): use transformer
|
||||
|
||||
@@ -22,6 +22,7 @@ from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -282,8 +283,10 @@ class Wan22I2VPipeline(
|
||||
condition: torch.Tensor,
|
||||
first_frame_mask: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
if attention_kwargs is None:
|
||||
attention_kwargs = {}
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
for step_idx, t in enumerate(timesteps):
|
||||
self._current_timestep = t
|
||||
|
||||
# Select model and guidance scale based on timestep
|
||||
@@ -293,6 +296,8 @@ class Wan22I2VPipeline(
|
||||
current_model = self.transformer_2
|
||||
current_guidance_scale = guidance_high
|
||||
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
|
||||
# Prepare latent input
|
||||
if self.expand_timesteps:
|
||||
# TI2V-5B style: blend condition with latents using mask
|
||||
@@ -308,6 +313,7 @@ class Wan22I2VPipeline(
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
do_true_cfg = current_guidance_scale > 1.0 and negative_prompt_embeds is not None
|
||||
# Prepare kwargs for positive and negative predictions
|
||||
positive_kwargs = {
|
||||
"hidden_states": latent_model_input,
|
||||
"timestep": timestep,
|
||||
@@ -330,6 +336,7 @@ class Wan22I2VPipeline(
|
||||
else:
|
||||
negative_kwargs = None
|
||||
|
||||
# Predict noise with automatic CFG parallel handling
|
||||
noise_pred = self.predict_noise_maybe_with_cfg(
|
||||
do_true_cfg=do_true_cfg,
|
||||
true_cfg_scale=current_guidance_scale,
|
||||
@@ -338,7 +345,9 @@ class Wan22I2VPipeline(
|
||||
cfg_normalize=False,
|
||||
)
|
||||
|
||||
# Compute the previous noisy sample x_t -> x_t-1 with automatic CFG sync
|
||||
latents = self.scheduler_step_maybe_with_cfg(noise_pred, t, latents, do_true_cfg)
|
||||
|
||||
pbar.update()
|
||||
|
||||
return latents
|
||||
|
||||
@@ -33,6 +33,7 @@ from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import OmniAutoencoderKLWan
|
||||
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
@@ -246,9 +247,12 @@ class Wan22TI2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin, Progress
|
||||
latent_condition: torch.Tensor | None = None,
|
||||
first_frame_mask: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if attention_kwargs is None:
|
||||
attention_kwargs = {}
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
for step_idx, t in enumerate(timesteps):
|
||||
self._current_timestep = t
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
|
||||
# Prepare latent input
|
||||
if latent_condition is not None:
|
||||
|
||||
@@ -24,6 +24,7 @@ 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.forward_context import set_forward_context_denoise_step_idx
|
||||
from vllm_omni.diffusion.models.interface import SupportImageInput
|
||||
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
|
||||
Wan22Pipeline,
|
||||
@@ -188,9 +189,13 @@ class Wan22VACEPipeline(Wan22Pipeline, SupportImageInput):
|
||||
vace_context: torch.Tensor | None,
|
||||
vace_context_scale: float,
|
||||
) -> torch.Tensor:
|
||||
if attention_kwargs is None:
|
||||
attention_kwargs = {}
|
||||
with self.progress_bar(total=len(timesteps)) as pbar:
|
||||
for t in timesteps:
|
||||
for step_idx, t in enumerate(timesteps):
|
||||
self._current_timestep = t
|
||||
set_forward_context_denoise_step_idx(step_idx)
|
||||
|
||||
latent_model_input = latents.to(dtype)
|
||||
timestep = t.expand(latents.shape[0])
|
||||
|
||||
|
||||
@@ -329,6 +329,7 @@ class WanSelfAttention(nn.Module):
|
||||
head_dim: int,
|
||||
eps: float = 1e-5,
|
||||
dropout: float = 0.0,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -374,13 +375,14 @@ class WanSelfAttention(nn.Module):
|
||||
softmax_scale=1.0 / (head_dim**0.5),
|
||||
causal=False,
|
||||
role="self",
|
||||
prefix=prefix,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
rotary_emb: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
attn_mask: torch.Tensor | None = None,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
# Fused QKV projection
|
||||
qkv, _ = self.to_qkv(hidden_states)
|
||||
@@ -405,11 +407,6 @@ class WanSelfAttention(nn.Module):
|
||||
query = self.rotary_embedding(query, freqs_cos, freqs_sin)
|
||||
key = self.rotary_embedding(key, freqs_cos, freqs_sin)
|
||||
|
||||
# Create attention metadata if mask is provided
|
||||
attn_metadata = None
|
||||
if attn_mask is not None:
|
||||
attn_metadata = AttentionMetadata(attn_mask=attn_mask)
|
||||
|
||||
# Compute attention using unified attention layer
|
||||
hidden_states = self.attn(query, key, value, attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3)
|
||||
@@ -436,6 +433,7 @@ class WanCrossAttention(nn.Module):
|
||||
eps: float = 1e-5,
|
||||
dropout: float = 0.0,
|
||||
added_kv_proj_dim: int | None = None,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -528,13 +526,19 @@ class WanCrossAttention(nn.Module):
|
||||
causal=False,
|
||||
role="cross",
|
||||
qkv_layout="BSND",
|
||||
prefix=prefix,
|
||||
skip_sequence_parallel=True,
|
||||
# Wan2.2 cross-attn operates on short text-encoder sequences; per-block
|
||||
# FP8 quant offers no perf win and degrades quality. Opt out until a
|
||||
# dedicated quant backend handles this case.
|
||||
disable_kv_quant=True,
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
hidden_states: torch.Tensor,
|
||||
encoder_hidden_states: torch.Tensor,
|
||||
attn_metadata: AttentionMetadata | None = None,
|
||||
) -> torch.Tensor:
|
||||
# Handle I2V case where encoder_hidden_states contains both image and text
|
||||
encoder_hidden_states_img = None
|
||||
@@ -568,12 +572,12 @@ class WanCrossAttention(nn.Module):
|
||||
key_img = key_img.unflatten(2, (self.num_heads, self.head_dim))
|
||||
value_img = value_img.unflatten(2, (self.num_heads, self.head_dim))
|
||||
|
||||
hidden_states_img = self.attn(query, key_img, value_img)
|
||||
hidden_states_img = self.attn(query, key_img, value_img, attn_metadata)
|
||||
hidden_states_img = hidden_states_img.flatten(2, 3)
|
||||
hidden_states_img = hidden_states_img.type_as(query)
|
||||
|
||||
# Main cross-attention using unified attention layer
|
||||
hidden_states = self.attn(query, key, value)
|
||||
hidden_states = self.attn(query, key, value, attn_metadata)
|
||||
hidden_states = hidden_states.flatten(2, 3)
|
||||
hidden_states = hidden_states.type_as(query)
|
||||
|
||||
@@ -602,6 +606,7 @@ class WanTransformerBlock(nn.Module):
|
||||
eps: float = 1e-6,
|
||||
added_kv_proj_dim: int | None = None,
|
||||
cross_attn_norm: bool = False,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
@@ -614,6 +619,7 @@ class WanTransformerBlock(nn.Module):
|
||||
num_heads=num_heads,
|
||||
head_dim=head_dim,
|
||||
eps=eps,
|
||||
prefix=f"{prefix}.attn1",
|
||||
)
|
||||
|
||||
# 2. Cross-attention
|
||||
@@ -623,6 +629,7 @@ class WanTransformerBlock(nn.Module):
|
||||
head_dim=head_dim,
|
||||
eps=eps,
|
||||
added_kv_proj_dim=added_kv_proj_dim,
|
||||
prefix=f"{prefix}.attn2",
|
||||
)
|
||||
self.norm2 = LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
||||
|
||||
@@ -660,12 +667,13 @@ class WanTransformerBlock(nn.Module):
|
||||
|
||||
# 1. Self-attention
|
||||
norm_hidden_states = self.norm1(hidden_states, scale_msa, shift_msa).type_as(hidden_states)
|
||||
attn_output = self.attn1(norm_hidden_states, rotary_emb, hidden_states_mask)
|
||||
self_attn_metadata = AttentionMetadata(attn_mask=hidden_states_mask)
|
||||
attn_output = self.attn1(norm_hidden_states, rotary_emb, self_attn_metadata)
|
||||
hidden_states = (hidden_states + attn_output * gate_msa).type_as(hidden_states)
|
||||
|
||||
# 2. Cross-attention
|
||||
norm_hidden_states = self.norm2(hidden_states).type_as(hidden_states)
|
||||
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states)
|
||||
attn_output = self.attn2(norm_hidden_states, encoder_hidden_states, None)
|
||||
hidden_states = hidden_states + attn_output
|
||||
|
||||
# 3. Feed-forward
|
||||
@@ -834,8 +842,16 @@ class WanTransformer3DModel(nn.Module):
|
||||
# 3. Transformer blocks
|
||||
self.blocks = nn.ModuleList(
|
||||
[
|
||||
WanTransformerBlock(inner_dim, ffn_dim, num_attention_heads, eps, added_kv_proj_dim, cross_attn_norm)
|
||||
for _ in range(num_layers)
|
||||
WanTransformerBlock(
|
||||
inner_dim,
|
||||
ffn_dim,
|
||||
num_attention_heads,
|
||||
eps,
|
||||
added_kv_proj_dim,
|
||||
cross_attn_norm,
|
||||
prefix=f"blocks.{layer_idx}",
|
||||
)
|
||||
for layer_idx in range(num_layers)
|
||||
]
|
||||
)
|
||||
|
||||
@@ -929,7 +945,13 @@ class WanTransformer3DModel(nn.Module):
|
||||
|
||||
# Transformer blocks
|
||||
for block in self.blocks:
|
||||
hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, hidden_states_mask)
|
||||
hidden_states = block(
|
||||
hidden_states,
|
||||
encoder_hidden_states,
|
||||
timestep_proj,
|
||||
rotary_emb,
|
||||
hidden_states_mask,
|
||||
)
|
||||
|
||||
# Output norm, projection & unpatchify
|
||||
shift, scale = self.output_scale_shift_prepare(temb)
|
||||
|
||||
@@ -33,8 +33,17 @@ class VaceWanTransformerBlock(WanTransformerBlock):
|
||||
added_kv_proj_dim: int | None = None,
|
||||
cross_attn_norm: bool = False,
|
||||
block_id: int = 0,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__(dim, ffn_dim, num_heads, eps, added_kv_proj_dim, cross_attn_norm)
|
||||
super().__init__(
|
||||
dim,
|
||||
ffn_dim,
|
||||
num_heads,
|
||||
eps,
|
||||
added_kv_proj_dim,
|
||||
cross_attn_norm,
|
||||
prefix=prefix,
|
||||
)
|
||||
self.proj_in = nn.Linear(dim, dim) if block_id == 0 else None
|
||||
self.proj_out = nn.Linear(dim, dim)
|
||||
|
||||
@@ -118,6 +127,7 @@ class WanVACETransformer3DModel(WanTransformer3DModel):
|
||||
self.config.added_kv_proj_dim,
|
||||
self.config.cross_attn_norm,
|
||||
block_id=i,
|
||||
prefix=f"vace_blocks.{i}",
|
||||
)
|
||||
for i in range(len(vace_layers))
|
||||
]
|
||||
@@ -220,7 +230,7 @@ class WanVACETransformer3DModel(WanTransformer3DModel):
|
||||
full_seq_len = hidden_states.shape[1] * sp_size
|
||||
control_hidden_states = self.embed_vace_context(vace_context.to(hidden_states.dtype), full_seq_len, sp_size)
|
||||
vace_hints = []
|
||||
for block in self.vace_blocks:
|
||||
for i, block in enumerate(self.vace_blocks):
|
||||
conditioning_states, control_hidden_states = block(
|
||||
hidden_states,
|
||||
encoder_hidden_states,
|
||||
@@ -237,7 +247,13 @@ class WanVACETransformer3DModel(WanTransformer3DModel):
|
||||
|
||||
# Transformer blocks with VACE hint application
|
||||
for i, block in enumerate(self.blocks):
|
||||
hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, hidden_states_mask)
|
||||
hidden_states = block(
|
||||
hidden_states,
|
||||
encoder_hidden_states,
|
||||
timestep_proj,
|
||||
rotary_emb,
|
||||
hidden_states_mask,
|
||||
)
|
||||
if vace_hints is not None and self.vace_layers_mapping is not None and i in self.vace_layers_mapping:
|
||||
vace_idx = self.vace_layers_mapping[i]
|
||||
hidden_states = hidden_states + vace_hints[vace_idx] * vace_context_scale[vace_idx]
|
||||
|
||||
Reference in new issue
Block a user