[Hardware][Ascend] Integrate MindIE dense and sparse quantized attention for Wan2.2 T2V (#7561)

Signed-off-by: zqxu <xuzhenqiang3@huawei.com>
Co-authored-by: zqxu <xuzhenqiang3@huawei.com>
This commit is contained in:
Zhenqiang Xuandzqxu authored and GitHub committed 2026-09-18 01:28:27 +00:00
1 parent f8197e120f
commit 242c3cddeb
15 files changed
+853 -368

No files matched your search

@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import os
from collections.abc import Callable
from functools import cache, partial
import torch
@@ -75,18 +76,18 @@ class FlashAttentionBackend(AttentionBackend):
class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
# Per-platform FP8 KV quantization support.
# To enable FP8 on a new platform, add its OmniPlatformEnum value here
# Per-platform attention quantization support.
# To enable a method on a new platform, add its OmniPlatformEnum value here
# and handle kv_cache_dtype in the corresponding forward_{platform}().
#
# TODO(quant-backend): The FP8 quant path currently lives inside
# TODO(quant-backend): The quantized path currently lives inside
# FlashAttentionImpl gated by ``attn_metadata.extra["kv_cache_dtype"]``.
# Eventually extract it into a dedicated FlashAttentionQuantBackend so
# backend selection (not metadata) decides quant. Until then, model
# authors can opt a specific Attention layer out via
# backend selection decides quant.
# Until then, model authors can opt a specific Attention layer out via
# ``Attention(disable_kv_quant=True)``.
_supported_kv_cache_dtypes = {
"npu": {"fp8"},
"npu": {"fp8", "mxfp8", "mxfp4"},
}
def __init__(
@@ -526,11 +527,47 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
) -> torch.Tensor:
"""NPU attention implementation using mindiesd."""
kv_cache_dtype = attn_metadata.extra.get("kv_cache_dtype") if attn_metadata else None
if kv_cache_dtype is not None:
extra = attn_metadata.extra if attn_metadata else {}
method = extra.get("kv_cache_dtype")
if method not in (None, "float", "auto"):
return self.forward_fa_quant_npu(query, key, value, attn_metadata)
return self.forward_fa_npu(query, key, value, attn_metadata)
@staticmethod
def _load_quant_runtime(method: str) -> Callable[..., torch.Tensor]:
if method not in ("fp8", "mxfp8", "mxfp4"):
raise ValueError(f"Unsupported NPU attention quantization method {method!r}.")
from mindiesd import quant_attention
return quant_attention
def _validate_quant_request(
self,
method: str,
query: torch.Tensor,
attn_metadata: AttentionMetadata | None,
) -> None:
extra = attn_metadata.extra if attn_metadata else {}
reason = None
if self.causal:
reason = "causal quantized FA is not supported"
elif any(name in extra for name in ("cu_seqlens_q", "cu_seqlens_k")) or extra.get("npu_attn_varlen"):
reason = "packed/varlen metadata requires the float attention path"
elif attn_metadata is not None and attn_metadata.full_attn_spans is not None:
reason = "piecewise attention requires the float attention path"
elif attn_metadata is not None and attn_metadata.attn_mask is not None:
reason = "caller masks require the float attention path"
elif method in ("fp8", "mxfp8", "mxfp4") and (
query.ndim != 4 or query.shape[-1] <= 0 or query.shape[-1] & (query.shape[-1] - 1)
):
reason = "generated Hadamard rotations require a four-dimensional input and power-of-two head size"
if reason is not None:
raise ValueError(
f"NPU attention precision {method!r} is unavailable: {reason}. "
"Set diffusion_kv_cache_dtype to a supported method, or set it to "
"'auto'. Automatic precision fallback is not performed."
)
def forward_fa_quant_npu(
self,
query: torch.Tensor,
@@ -538,18 +575,29 @@ class FlashAttentionImpl(AttentionImpl[AttentionMetadata]):
value: torch.Tensor,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
from vllm_omni.platforms.npu.quant.kv_quant_npu import fp8_rotate_quant_fa
extra = attn_metadata.extra if attn_metadata else {}
method = extra.get("kv_cache_dtype", "fp8")
layout = self.qkv_layout or "BSND"
self._validate_quant_request(method, query, attn_metadata)
try:
runtime = self._load_quant_runtime(method)
except ImportError as exc:
raise ImportError(
f"NPU attention precision {method!r} requires a compatible MindIE-SD "
"quant Runtime. Install a compatible MindIE-SD build, select another "
"diffusion_kv_cache_dtype, or set it to 'auto'. Automatic precision "
"fallback is not performed."
) from exc
kwargs = dict(precision=method, layout=layout, scale=self.softmax_scale)
# Apply Omni's deterministic Q/K rotation before every Dense quantized path.
if method in ("fp8", "mxfp8", "mxfp4"):
from vllm_omni.platforms.npu.quant.kv_quant_npu import get_quant_attention_rotation
layout = self.qkv_layout or "BNSD"
# Models pass (B, S, H, D); NPU fused op expects (B, N, S, D).
out = fp8_rotate_quant_fa(
query.transpose(1, 2),
key.transpose(1, 2),
value.transpose(1, 2),
layout=layout,
softmax_scale=self.softmax_scale,
)
return out.transpose(1, 2)
rotation = get_quant_attention_rotation(query.device, query.dtype, query.shape[-1])
kwargs.update(q_rot=rotation, k_rot=rotation)
logger.info_once("NPU attention uses MindIE-SD %s Runtime, layout=%s.", method, layout)
# Execution errors propagate. Never retry with another precision.
return runtime(query, key, value, **kwargs)
def forward_fa_npu(
self,
@@ -146,8 +146,10 @@ class RainFusionAttentionBackend(AttentionBackend):
from mindiesd import sparse_attention
except ImportError as exc:
raise ValueError(_MISSING_MINDIESD) from exc
if not _supports_video_spans(sparse_attention):
raise ValueError(_INCOMPATIBLE_MINDIESD)
if not callable(sparse_attention):
raise ValueError(_MISSING_MINDIESD)
# Single-video Wan only needs the legacy geometry. Check video_spans
# when a forward actually carries multiple videos.
@staticmethod
def get_supported_head_sizes() -> list[int]:
@@ -174,6 +176,8 @@ class RainFusionAttentionImpl(AttentionImpl):
irregular video tail internally, retaining it outside the sparse blocks.
"""
_supported_kv_cache_dtypes = {"npu": {"fp8", "mxfp4"}}
def __init__(
self,
num_heads: int,
@@ -222,6 +226,8 @@ class RainFusionAttentionImpl(AttentionImpl):
def _validate_parallel_config(self) -> None:
config = get_current_diffusion_config_or_none()
parallel_config = getattr(config, "parallel_config", None)
if getattr(parallel_config, "allgather_degree", 1) > 1:
raise ValueError("RAINFUSION_ATTN requires full Q/K/V sequences; AllGather-KV SP is unsupported.")
ring_degree = getattr(parallel_config, "ring_degree", 1)
if ring_degree > 1:
# Ring gives each rank a slice of the sequence, so block selection
@@ -262,7 +268,9 @@ class RainFusionAttentionImpl(AttentionImpl):
plan = self._resolve_plan(attn_metadata)
if plan is None:
return self.dense_fallback.forward_npu(query, key, value, attn_metadata)
return self._forward_sparse_npu(query, key, value, plan)
if query.ndim != 4 or key.shape != query.shape or value.shape != query.shape or plan.used_len > query.shape[1]:
raise ValueError("RainFusion video geometry must fit identical full-sequence BSND Q/K/V tensors.")
return self._forward_sparse_npu(query, key, value, plan, attn_metadata)
def _resolve_plan(self, attn_metadata: AttentionMetadata | None) -> RainFusionPlan | None:
"""Return the rf_v2 geometry, or None when this forward must stay dense."""
@@ -271,18 +279,17 @@ class RainFusionAttentionImpl(AttentionImpl):
return None
if self.layer_idx is not None and self.layer_idx in rf.skip_layers:
return None
step_idx = total_steps = None
if is_forward_context_available():
step_idx = get_forward_context().denoise_step_idx
total_steps = get_forward_context().total_denoise_steps
if step_idx is not None and step_idx < rf.start_step:
if (rf.start_step and step_idx is None) or (rf.end_step and (step_idx is None or total_steps is None)):
return None
if step_idx is not None:
if step_idx < rf.start_step:
return None
# Tail fallback: keep the last ``end_step`` denoise steps dense.
if (
rf.end_step > 0
and step_idx is not None
and total_steps is not None
and step_idx >= total_steps - rf.end_step
):
if rf.end_step > 0 and total_steps is not None and step_idx >= total_steps - rf.end_step:
return None
if self.qkv_layout is None:
# The sparse path reads the sequence off dim 1, which the tensors alone
@@ -308,7 +315,16 @@ class RainFusionAttentionImpl(AttentionImpl):
"model must publish AttentionMetadata.video_layout for the sequence to be sparsified."
)
return None
max_seqlen_q = attn_metadata.extra.get("max_seqlen_q")
# The sparse Runtime constructs its own block mask. It cannot preserve
# an arbitrary caller-supplied mask or piecewise visibility constraints.
mask = attn_metadata.attn_mask
padding_only = layout.used_len is not None
if attn_metadata.full_attn_spans is not None or (
mask is not None and not (padding_only and mask.ndim == 2 and mask.dtype == torch.bool)
):
return None
max_seqlen_q = attn_metadata.extra.get("max_seqlen_q", layout.used_len)
if max_seqlen_q is None:
logger.warning_once(
"RAINFUSION_ATTN staying dense: attention metadata is missing max_seqlen_q, so the "
@@ -459,19 +475,39 @@ class RainFusionAttentionImpl(AttentionImpl):
key: torch.Tensor,
value: torch.Tensor,
plan: RainFusionPlan,
attn_metadata: AttentionMetadata | None = None,
) -> torch.Tensor:
try:
from mindiesd import sparse_attention
except ImportError:
raise ImportError(_MISSING_MINDIESD)
if self.rainfusion.precision != "bf16" and not _mindiesd_supports_precision():
raise RuntimeError(
f"block_sparse.precision={self.rainfusion.precision!r} requires MindIE-SD "
"with sparse_attention(precision=...) support; the installed mindiesd "
"silently ignores it and would run the BF16 path. Install a compatible "
"MindIE-SD release or use precision='bf16'."
if plan.video_spans is not None and not _supports_video_spans(sparse_attention):
raise ValueError(_INCOMPATIBLE_MINDIESD)
extra = attn_metadata.extra if attn_metadata else {}
requested = extra.get("kv_cache_dtype", self.rainfusion.precision)
reason = None
if requested in ("float", "bf16"):
precision = "bf16"
else:
precision = requested
if requested not in ("fp8", "mxfp4", "mix"):
reason = f"sparse {requested} is not supported"
elif not _mindiesd_supports_precision():
reason = "MindIE-SD sparse_attention must explicitly support precision"
elif plan.video_spans is not None:
reason = "quantized multi-video RainFusion is not supported"
elif requested in ("fp8", "mxfp4") and query.shape[0] != 1:
reason = "quantized Wan BSA requires batch size 1"
elif requested in ("fp8", "mxfp4") and (query.shape[-1] < 64 or query.shape[-1] & (query.shape[-1] - 1)):
reason = "BSA Hadamard rotations require a power-of-two head dimension of at least 64"
if reason is not None:
raise ValueError(
f"RainFusion precision {requested!r} is unavailable: {reason}. "
"Set diffusion_kv_cache_dtype or block_sparse.precision to a method supported by the installed "
"MindIE-SD, or disable attention quantization. Automatic precision fallback is not performed."
)
logger.info_once("RainFusion uses MindIE-SD sparse attention, precision=%s.", precision)
used = plan.used_len
q, k, v = (tensor[:, :used] for tensor in (query, key, value))
# Ulysses has already gathered the full sequence onto this rank and split
@@ -480,10 +516,10 @@ class RainFusionAttentionImpl(AttentionImpl):
"scale": self.softmax_scale,
"head_num": query.shape[-2],
"input_layout": _INPUT_LAYOUT,
"inner_precise": _INNER_PRECISE,
"inner_precise": 4 if precision != "bf16" else _INNER_PRECISE,
"block_size": _BLOCK_SIZE,
"sparsity": self.rainfusion.sparsity,
"precision": self.rainfusion.precision,
"precision": precision,
}
if plan.video_spans is not None:
out = sparse_attention(
@@ -497,7 +533,9 @@ class RainFusionAttentionImpl(AttentionImpl):
else:
assert plan.prefix_len is not None and plan.latent_shape is not None
common_kwargs.update(
sparse_type="rf_v2",
# rf_v2 ignores precision on non-A5 devices. Select the explicit
# quantized high-level path so mask/rearrangement remain in MindIE.
sparse_type="rf_v3" if precision != "bf16" else "rf_v2",
txt_len=plan.prefix_len,
latent_shape_q=plan.latent_shape,
latent_shape_k=plan.latent_shape,
+18 -13
View File
@@ -321,7 +321,7 @@ class Attention(nn.Module):
dtype = None
parallel_config = getattr(config, "parallel_config", None)
ring_degree = getattr(parallel_config, "ring_degree", 1)
if dtype:
if dtype and dtype != "float":
if ring_degree > 1:
raise ValueError(
"KV quantization is not compatible with ring attention "
@@ -338,13 +338,15 @@ class Attention(nn.Module):
self._kv_cache_dtype = dtype
self._kv_cache_skip_steps = getattr(config, "diffusion_kv_cache_skip_step_indices", None)
self._kv_cache_skip_layers = getattr(config, "diffusion_kv_cache_skip_layer_indices", None)
if self._kv_cache_skip_layers and self.layer_idx is None and not self._disable_kv_quant:
raise ValueError("Attention quantization skip_layers requires a parseable transformer block index.")
def _should_apply_kv_cache_quant(self) -> bool:
skip_steps = self._kv_cache_skip_steps
skip_layers = self._kv_cache_skip_layers
if skip_steps is not None:
step_idx = get_forward_context().denoise_step_idx if is_forward_context_available() else None
if step_idx is not None and step_idx in skip_steps:
if skip_steps and (step_idx is None or step_idx in skip_steps):
return False
if skip_layers is not None:
if self.layer_idx is not None and self.layer_idx in skip_layers:
@@ -352,18 +354,21 @@ class Attention(nn.Module):
return True
def _with_kv_cache_dtype(self, attn_metadata: AttentionMetadata | None) -> AttentionMetadata | None:
kv_cache_dtype = self._kv_cache_dtype
if kv_cache_dtype is None or self._disable_kv_quant or not self._should_apply_kv_cache_quant():
if attn_metadata is None or "kv_cache_dtype" not in attn_metadata.extra:
return attn_metadata
extra = dict(attn_metadata.extra)
extra.pop("kv_cache_dtype", None)
return replace(attn_metadata, extra=extra)
disabled = self._disable_kv_quant or not self._should_apply_kv_cache_quant()
dtype = self._kv_cache_dtype
if dtype in (None, "float"):
dtype = None
elif disabled:
dtype = "float"
if dtype is None and (attn_metadata is None or "kv_cache_dtype" not in attn_metadata.extra):
return attn_metadata
extra = dict(attn_metadata.extra) if attn_metadata is not None else {}
# Recompute per forward so shared metadata cannot retain another step's policy.
extra.pop("kv_cache_dtype", None)
if dtype is not None:
extra["kv_cache_dtype"] = dtype
if attn_metadata is None:
return AttentionMetadata(extra={"kv_cache_dtype": kv_cache_dtype})
extra = dict(attn_metadata.extra)
extra["kv_cache_dtype"] = kv_cache_dtype
return AttentionMetadata(extra=extra) if extra else None
return replace(attn_metadata, extra=extra)
def forward(
+2 -5
View File
@@ -1028,11 +1028,8 @@ class OmniDiffusionConfig:
# has already resolved to vLLM's ModelOpt FP8 linear method.
force_cutlass_fp8: bool = False
# Diffusion attention KV cache dtype (not vLLM's --kv-cache-dtype for AR models).
# None = native dtype (no quantization).
# "fp8" = dynamic FP8 (float8_e4m3fn) quantization per forward pass.
# On Hopper+FA3: native FP8 attention (memory + compute savings).
# On other backends: no benefit, backends skip quantization.
# Runtime diffusion attention method (not vLLM's --kv-cache-dtype for AR models).
# None/"auto" keeps native dtype; other values are validated by the selected backend.
diffusion_kv_cache_dtype: str | None = None
# Optional skip selectors for KV-cache quantization. Format: "0-9,20,25-30".
# Listed steps/layers skip quantization; others keep quantized execution.
@@ -29,7 +29,7 @@ from vllm.model_executor.models.utils import (
)
from vllm.sequence import IntermediateTensors
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata, VideoTokenLayout
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.distributed.parallel_state import (
get_pipeline_parallel_world_size,
@@ -417,6 +417,7 @@ class WanSelfAttention(nn.Module):
softmax_scale=1.0 / (head_dim**0.5),
causal=False,
role="self",
qkv_layout="BSND",
prefix=prefix,
)
@@ -609,8 +610,8 @@ class WanCrossAttention(nn.Module):
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
# Wan2.2 cross-attn operates on short text-encoder sequences; runtime
# Q/K/V quantization offers no perf win and degrades quality. Opt out until a
# dedicated quant backend handles this case.
disable_kv_quant=True,
)
@@ -764,7 +765,15 @@ class WanTransformerBlock(nn.Module):
self_attn_extra["vsa_dit_seq_shape"] = vsa_dit_seq_shape
if preserve_vsa_all_blocks:
self_attn_extra["preserve_vsa_all_blocks"] = True
self_attn_metadata = AttentionMetadata(attn_mask=hidden_states_mask, extra=self_attn_extra)
video_layout = None
if vsa_dit_seq_shape is not None:
grid = tuple(int(dim) for dim in vsa_dit_seq_shape)
# Publish geometry independently of backend selection. Do not add
# partial cu_seqlens/max_seqlen metadata to dense CUDA attention.
video_layout = VideoTokenLayout(prefix_len=0, latent_grid=grid, used_len=math.prod(grid))
self_attn_metadata = AttentionMetadata(
attn_mask=hidden_states_mask, extra=self_attn_extra, video_layout=video_layout
)
attn_output = self.attn1(norm_hidden_states, rotary_emb, self_attn_metadata)
hidden_states = (hidden_states + attn_output * gate_msa).type_as(hidden_states)