Perf/minimax h3 dit swiglu rope cache npu (#6410)

Signed-off-by: Wenjia Li <wjialish@gmail.com>
Co-authored-by: WeiQing Chen <40507679+david6666666@users.noreply.github.com>
This commit is contained in:
Wenjia LiandWeiQing Chen authored and GitHub committed 2026-08-29 09:14:52 +00:00
1 parent bb5bf8fd0a
commit d9980c75e8
11 files changed
+920 -33

No files matched your search

+84 -17
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
Model-specific extractors for TeaCache.
@@ -13,6 +13,7 @@ all model-specific information needed for generic caching, including preprocessi
transformer execution, and postprocessing logic.
"""
import math
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
@@ -1263,7 +1264,6 @@ def extract_minimax_h3_context(
from vllm_omni.diffusion.models.minimax_h3.minimax_h3_transformer import (
_FORWARD_SUPPORTED_KWARGS,
MINIMAX_H3_ADALN_MODALITY_NUM,
_build_rope_table,
_required_kwarg,
)
@@ -1320,8 +1320,20 @@ def extract_minimax_h3_context(
if inverse_indices.shape[0] != seq_len:
raise ValueError(f"inverse_indices must be [{seq_len}], got {list(inverse_indices.shape)}")
device = x.device
rope_table = _build_rope_table(module.rope(img_position_ids).to(device))
local_span = module._rope_local_span(seq_len)
local_start, local_len = local_span
rope_table = kwargs.get("rope_table")
if rope_table is None:
rope_table = module.prepare_rope_table(
img_position_ids,
seq_len=seq_len,
)
else:
module._validate_prepared_rope_table(
rope_table,
local_len=local_len,
device=device,
)
decoder_input, t_emb = module._embed(
x=x,
@@ -1336,28 +1348,59 @@ def extract_minimax_h3_context(
num_requests=num_requests,
seq_len=seq_len,
device=device,
local_span=(0, seq_len),
local_span=local_span,
)
combined_indices = (inverse_indices * MINIMAX_H3_ADALN_MODALITY_NUM + token_tags.clamp(min=0)).to(device)
inverse_indices = inverse_indices.to(device)
cu_seqlens = cu_seqlens.to(device)
# In strict SP, _embed already returns this rank's packed rows while
# combined_indices still describes the full packed sequence. TeaCache uses
# the first block's modulation as part of its rank-local cache state, so
# the modulation indices must be sliced to the same local layout. Keep the
# full indices below: local_sp_prepare owns the global-to-local conversion
# for transformer-block inputs.
state_combined_indices = combined_indices.narrow(0, local_start, local_len)
if local_len == seq_len:
state_combined_indices = combined_indices
shift_msa, scale_msa, *_ = module.blocks[0].adaln_proj(t_emb)
modulated_input = module.blocks[0].norm1(decoder_input)
modulated_input = indexed_scale_shift_(
modulated_input,
shift_msa,
scale_msa,
combined_indices,
state_combined_indices,
)
def run_transformer_blocks() -> tuple[torch.Tensor, ...]:
hidden, block_rope, block_combined = module.sp_prepare(
decoder_input,
rope_table,
combined_indices,
def synchronize_cache_decision(local_should_compute: bool) -> bool:
if local_len == seq_len:
return local_should_compute
from vllm_omni.diffusion.distributed.parallel_state import get_sp_group
decision = torch.tensor(
int(local_should_compute),
dtype=torch.int32,
device=device,
)
get_sp_group().all_reduce(decision, op=torch.distributed.ReduceOp.MAX)
return bool(decision.item())
def run_transformer_blocks() -> tuple[torch.Tensor, ...]:
if local_len == seq_len:
hidden, block_rope, block_combined = module.sp_prepare(
decoder_input,
rope_table,
combined_indices,
)
else:
hidden, block_rope, block_combined = module.local_sp_prepare(
decoder_input,
rope_table,
combined_indices,
)
for block in module.blocks:
hidden = block(
hidden,
@@ -1369,15 +1412,36 @@ def extract_minimax_h3_context(
packed_total=seq_len,
video_layout=video_layout,
)
hidden = module.sp_gather(hidden)
# TeaCache stores residuals as block_output - decoder_input. Strict SP
# must keep both tensors rank-local until postprocess projects local
# rows to compact logits and gathers them exactly once.
if local_len == seq_len:
hidden = module.sp_gather(hidden)
return (hidden,)
def postprocess(hidden: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
video_logits, audio_logits = module.final_layer(
hidden,
t_emb=t_emb,
inverse_indices=inverse_indices,
)
if local_len == seq_len:
video_logits, audio_logits = module.final_layer(
hidden,
t_emb=t_emb,
inverse_indices=inverse_indices,
)
else:
local_inverse_indices = inverse_indices.narrow(
0,
local_start,
local_len,
)
video_logits, audio_logits = module.final_layer(
hidden,
t_emb=t_emb,
inverse_indices=local_inverse_indices,
)
compact_logits = torch.cat((video_logits, audio_logits), dim=-1)
compact_logits = module.sp_gather(compact_logits)
video_width = module.arch.latents_dim * math.prod(module.arch.patch_size)
video_logits = compact_logits[..., :video_width]
audio_logits = compact_logits[..., video_width:]
video_logits = video_logits.index_select(0, infer_out_pos.to(device))
audio_logits = audio_logits.index_select(0, audio_pos.to(device))
if not skip_mask_out_condition:
@@ -1396,6 +1460,9 @@ def extract_minimax_h3_context(
temb=t_emb,
run_transformer_blocks=run_transformer_blocks,
postprocess=postprocess,
extra_states={
"synchronize_cache_decision": synchronize_cache_decision,
},
)
+10 -1
View File
@@ -138,7 +138,16 @@ class TeaCacheHook(ModelHook):
state = self.state_manager.get_state()
# Decide whether to compute or cache based on modulated input similarity
should_compute = self._should_compute_full_transformer(state, ctx.modulated_input)
local_should_compute = self._should_compute_full_transformer(state, ctx.modulated_input)
sync_cache_decision = (ctx.extra_states or {}).get("synchronize_cache_decision")
if sync_cache_decision is not None:
should_compute = sync_cache_decision(local_should_compute)
# A rank that locally chose the cache path must reset its counter
# when another SP rank requires a full collective block execution.
if should_compute and not local_should_compute:
state.accumulated_rel_l1_distance = 0.0
else:
should_compute = local_should_compute
if not should_compute and state.previous_residual is not None:
# ============================================================================
+4 -1
View File
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Custom activation functions for diffusion models."""
import torch
@@ -31,7 +32,9 @@ class SiluAndMul(CustomOp):
return out
def forward_npu(self, x: torch.Tensor) -> torch.Tensor:
return self.forward_native(x)
import torch_npu
return torch_npu.npu_swiglu(x, dim=-1)
def forward_xpu(self, x: torch.Tensor) -> torch.Tensor:
return self.forward_native(x)
@@ -11,11 +11,14 @@ The public contract is shared by diffusion attention implementations:
``[cos(theta), sin(theta)]`` with ``theta`` of width ``rotary_dim // 2``.
The CUDA fast path fuses RMSNorm and RoPE without materializing normalized Q/K
or rotary-product intermediates. Unsupported inputs use the eager reference.
or rotary-product intermediates. Ascend composes its RMSNorm and rotary fused
primitives; unsupported inputs use the eager reference.
"""
from __future__ import annotations
from importlib.util import find_spec
import torch
import torch.nn.functional as F
from torch.library import Library
@@ -23,6 +26,8 @@ from vllm.platforms import current_platform
from vllm.triton_utils import HAS_TRITON, tl, triton
from vllm.utils.torch_utils import direct_register_custom_op
from vllm_omni.platforms import current_omni_platform
_FUSED_HEAD_DIM = 128
_FUSED_ROTARY_DIM = 96
_HEADS_PER_PROGRAM = 8
@@ -130,6 +135,72 @@ def _eager_qk_norm_rope(
)
def _npu_apply_rope_table(
x: torch.Tensor,
rope_table: torch.Tensor,
rotary_dim: int,
) -> torch.Tensor:
"""Apply H3's rotary dimensions through Ascend's fused rotary kernel.
``mindiesd.rotary_position_embedding`` takes a 4-D BSND tensor, whereas
MiniMax-H3 keeps packed activations as ``[tokens, heads, head_dim]``.
The shared MindIE-SD wrapper normalizes this 3-D layout to BSND and
restores it afterwards. It receives the half-width cos/sin values from
the packed table; the wrapper expands them to H3's non-interleaved 96-D
rotary layout. The 32 non-rotary head dimensions bypass the kernel.
Some CANN environments package ``torch_npu`` without MindIE-SD. Keep
those deployments on the same Ascend fused rotary primitive rather than
silently falling back to eager elementwise RoPE.
"""
import torch_npu
half = rotary_dim // 2
x_rot, x_pass = x[..., :rotary_dim], x[..., rotary_dim:]
cos = rope_table[..., :half]
sin = rope_table[..., half:]
if find_spec("mindiesd") is not None:
from vllm_omni.diffusion.layers.rope import apply_rotary_emb_mindiesd
x_rot = apply_rotary_emb_mindiesd(
x_rot,
cos,
sin,
interleaved=False,
half_head_dim=True,
)
else:
# npu_rotary_mul uses BSND and full rotary-width cos/sin. H3 uses
# NeoX/rotated-half ordering, so duplicate rather than interleave the
# half-width table along the final dimension.
cos = cos.unsqueeze(0).unsqueeze(2).repeat(1, 1, 1, 2)
sin = sin.unsqueeze(0).unsqueeze(2).repeat(1, 1, 1, 2)
x_rot = torch_npu.npu_rotary_mul(x_rot.unsqueeze(0), cos, sin).squeeze(0)
return torch.cat((x_rot, x_pass), dim=-1)
def _npu_qk_norm_rope(
q: torch.Tensor,
k: torch.Tensor,
q_weight: torch.Tensor,
k_weight: torch.Tensor,
rope_table: torch.Tensor,
eps: float,
rotary_dim: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Use Ascend RMSNorm and RoPE fused primitives for MiniMax-H3 DiT."""
import torch_npu
q_norm = torch_npu.npu_rms_norm(q, q_weight, epsilon=eps)[0]
k_norm = torch_npu.npu_rms_norm(k, k_weight, epsilon=eps)[0]
return (
_npu_apply_rope_table(q_norm, rope_table, rotary_dim),
_npu_apply_rope_table(k_norm, rope_table, rotary_dim),
)
def _fused_cuda_supported(
q: torch.Tensor,
k: torch.Tensor,
@@ -148,6 +219,24 @@ def _fused_cuda_supported(
)
def _fused_npu_supported(
q: torch.Tensor,
k: torch.Tensor,
head_dim: int,
rotary_dim: int,
) -> bool:
"""Return whether the MiniMax-H3 Ascend fused-op contract is satisfied."""
return (
current_omni_platform.is_npu()
and q.device.type == "npu"
and k.device.type == "npu"
and q.dtype == torch.bfloat16
and k.dtype == torch.bfloat16
and head_dim == _FUSED_HEAD_DIM
and rotary_dim == _FUSED_ROTARY_DIM
)
def _launch_fused_rms_norm_rope(
x: torch.Tensor,
weight: torch.Tensor,
@@ -192,6 +281,16 @@ def _fused_qk_norm_rope_impl(
head_dim: int,
rotary_dim: int,
) -> tuple[torch.Tensor, torch.Tensor]:
if _fused_npu_supported(q, k, head_dim, rotary_dim):
return _npu_qk_norm_rope(
q,
k,
q_weight,
k_weight,
rope_table,
eps,
rotary_dim,
)
if not _fused_cuda_supported(q, k, head_dim, rotary_dim):
return _eager_qk_norm_rope(
q,
@@ -273,6 +372,16 @@ def fused_qk_norm_rope(
q_weight = q_weight.contiguous()
k_weight = k_weight.contiguous()
rope_table = rope_table.contiguous()
if _fused_npu_supported(q, k, head_dim, rotary_dim):
return _npu_qk_norm_rope(
q,
k,
q_weight,
k_weight,
rope_table,
eps,
rotary_dim,
)
if not _fused_cuda_supported(q, k, head_dim, rotary_dim):
return _fused_qk_norm_rope_impl(
q,
@@ -1,4 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""MiniMax H3 cfg-distilled full denoise loop.
Per step, the positive presentation is forwarded exactly once. Video and audio
@@ -19,6 +20,7 @@ from vllm_omni.diffusion.forward_context import (
set_forward_context_denoise_step_idx,
set_forward_context_denoise_timestep,
)
from vllm_omni.platforms import current_omni_platform
from .scheduling_minimax_h3_euler_ancestral import (
minimax_h3_euler_eta0_step,
@@ -137,6 +139,22 @@ class MiniMaxH3DenoiseBranch:
latent_grid=(int(grid[0]), int(grid[1]), int(grid[2])),
)
def prepare_rope_table(self, model: Any) -> None:
"""Materialize the branch-local DiT RoPE table once per denoise run.
``img_position_ids`` is immutable for this branch while latents and
timesteps change every scheduler step. Keeping the table in
``static_kwargs`` makes every model call reuse the exact same BF16
tensor without extending its lifetime beyond this request branch.
"""
prepare = getattr(model, "prepare_rope_table", None)
if not callable(prepare):
return
self.static_kwargs["rope_table"] = prepare(
self.static_kwargs["img_position_ids"],
seq_len=self.seq_len,
)
def forward_kwargs(
self,
*,
@@ -253,6 +271,11 @@ def minimax_h3_denoise_loop(
raise ValueError("video/audio sigma schedules must have equal length")
if len(sigmas_video) < 2:
raise ValueError("sigma schedules need at least 2 entries")
# Keep CUDA/CPU on the reference path: its accuracy CI compares the
# generated video against the official artifact. The table reuse is an
# Ascend-specific performance optimization and must not alter that path.
if current_omni_platform.is_npu():
positive.prepare_rope_table(model)
video_rows, audio_rows, cond_anchor, audio_anchor = minimax_h3_prepare_denoise_rows(
positive=positive,
initial_video_rows=initial_video_rows,
@@ -49,6 +49,7 @@ from vllm_omni.diffusion.layers.fused_qk_norm_rope import fused_qk_norm_rope
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
from vllm_omni.diffusion.models.host_weight_contract import FinalLayoutModelContract
from vllm_omni.platforms import current_omni_platform
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import (
@@ -179,6 +180,7 @@ _FORWARD_SUPPORTED_KWARGS = frozenset(
"packed_seq_params",
"refiner_packed_seq_params",
"video_token_layout",
"rope_table",
}
)
@@ -1139,6 +1141,54 @@ class MiniMaxH3DiTModel(nn.Module):
for _, param in self.named_parameters():
param.missing_param_init = "error"
def _rope_local_span(self, seq_len: int) -> tuple[int, int]:
"""Return the sequence-parallel rows owned by this DiT rank."""
local_sp_registry = getattr(self.local_sp_prepare, "_hook_registry", None)
hooks_applied = local_sp_registry is not None
if local_sp_registry is not None:
local_sp_hook = local_sp_registry.get_hook(_LOCAL_SP_PREPARE_HOOK)
hooks_applied = local_sp_hook is not None
return _sequence_parallel_local_span(
seq_len,
hooks_applied=hooks_applied,
)
def prepare_rope_table(
self,
img_position_ids: torch.Tensor,
*,
seq_len: int,
) -> torch.Tensor:
"""Build the static local RoPE table once for one denoise branch.
A MiniMax-H3 denoise branch reuses its packed position IDs at every
scheduler step. The returned table is local to the current sequence-
parallel rank, and therefore must be built by the model that will
consume it rather than cached globally across requests or ranks.
"""
local_start, local_len = self._rope_local_span(seq_len)
rope_position_ids = img_position_ids.narrow(1, local_start, local_len)
return _build_rope_table(self.rope(rope_position_ids).to(img_position_ids.device))
def _validate_prepared_rope_table(
self,
rope_table: torch.Tensor,
*,
local_len: int,
device: torch.device,
) -> None:
expected_width = 6 * self.arch.rope_inv_freq_len
if rope_table.dim() != 2 or tuple(rope_table.shape) != (local_len, expected_width):
raise ValueError(
"rope_table must be [local_seq_len, rotary_dim] for the current "
f"sequence-parallel rank, got {list(rope_table.shape)}; expected "
f"[{local_len}, {expected_width}]."
)
if rope_table.device != device:
raise ValueError(f"rope_table device {rope_table.device} must match x device {device}.")
if rope_table.dtype != _BF16_DTYPE:
raise ValueError(f"rope_table must be {_BF16_DTYPE}, got {rope_table.dtype}.")
def post_load_weights(self) -> None:
for name, param in self.named_parameters():
if name in MINIMAX_H3_FP32_PARAM_NAMES and param.dtype != _FP32_DTYPE:
@@ -1362,18 +1412,26 @@ class MiniMaxH3DiTModel(nn.Module):
if inverse_indices.shape[0] != seq_len:
raise ValueError(f"inverse_indices must be [{seq_len}], got {list(inverse_indices.shape)}")
device = x.device
local_sp_registry = getattr(self.local_sp_prepare, "_hook_registry", None)
hooks_applied = local_sp_registry is not None
if local_sp_registry is not None:
local_sp_hook = local_sp_registry.get_hook(_LOCAL_SP_PREPARE_HOOK)
hooks_applied = local_sp_hook is not None
local_span = _sequence_parallel_local_span(
seq_len,
hooks_applied=hooks_applied,
)
local_span = self._rope_local_span(seq_len)
local_start, local_len = local_span
rope_position_ids = img_position_ids.narrow(1, local_start, local_len)
rope_table = _build_rope_table(self.rope(rope_position_ids).to(device))
rope_table = kwargs.get("rope_table")
if rope_table is None:
if current_omni_platform.is_npu():
rope_table = self.prepare_rope_table(
img_position_ids,
seq_len=seq_len,
)
else:
# Keep CUDA/CPU numerically and structurally identical to the
# main-branch reference path used by the H100 accuracy suite.
rope_position_ids = img_position_ids.narrow(1, local_start, local_len)
rope_table = _build_rope_table(self.rope(rope_position_ids).to(device))
else:
self._validate_prepared_rope_table(
rope_table,
local_len=local_len,
device=device,
)
decoder_input, t_emb = self._embed(
x=x,