[NPU][HunyuanImage3] Adapt diffusion FusedMoE for vLLM >= 0.24.0 (#5167)

Signed-off-by: betta18 <jiangmengyu1@huawei.com>
Signed-off-by: jiangmengyu18 <56633611+jiangmengyu18@users.noreply.github.com>
Co-authored-by: betta18 <jiangmengyu1@huawei.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-07-27 22:41:34 +08:00
1 parent 82172b112d
commit e108cbb510
12 files changed
+379 -318

No files matched your search

@@ -312,7 +312,6 @@ def get_allgather_parallel_rank():
def get_expert_parallel_group_ranks() -> list[list[int]]:
assert vllm_parallel_state._EP is not None, "expert parallel group is not initialized"
assert _EXPERT_PARALLEL_GROUP_RANKS is not None, "expert parallel group ranks are not initialized"
return _EXPERT_PARALLEL_GROUP_RANKS
@@ -948,16 +947,14 @@ def initialize_model_parallel(
parallel_mode="fully_shard",
)
_EXPERT_PARALLEL_GROUP_RANKS = None
_EXPERT_PARALLEL_GROUP_RANKS = rank_generator.get_ranks("tp-sp-cfg-dp")
if use_moe_parallel_mapping:
ep_group_ranks = rank_generator.get_ranks("tp-sp-cfg-dp")
vllm_parallel_state._EP = init_vllm_model_parallel_group(
group_ranks=ep_group_ranks,
group_ranks=_EXPERT_PARALLEL_GROUP_RANKS,
local_rank=get_world_group().local_rank,
backend=backend,
group_name="ep",
)
_EXPERT_PARALLEL_GROUP_RANKS = ep_group_ranks
init_dit_group(dit_parallel_size, backend)
@@ -6,7 +6,6 @@ from typing import Any
import torch
import vllm.distributed.parallel_state as _vllm_ps
import vllm.forward_context as _vllm_fc
from vllm.utils.import_utils import resolve_obj_by_qualname
from vllm_omni.platforms import current_omni_platform
@@ -50,18 +49,18 @@ def _set_forward_context_dp_metadata(num_tokens: int) -> None:
forward_context.dp_metadata = _vllm_fc.DPMetadata(torch.tensor(gathered_num_tokens, dtype=torch.int64))
class HunyuanFusedMoEDefault:
"""Adapter that configures the upstream FusedMoE ``MoERunner`` for HunyuanImage3.
class FusedMoE:
"""Adapter that configures the upstream FusedMoE ``MoERunner`` for diffusion models.
Upstream commit dc68bd8c41 refactored FusedMoE from a class (``nn.Module``)
into a factory function that returns a ``MoERunner`` instance, whose expert
weights live in a ``routed_experts`` submodule
(``...experts.routed_experts.w13_weight`` / ``...w2_weight``).
This adapter builds that runner, installs the omni-specific forward-context
setup and one-shot kernel-initialisation hook, and returns the runner
*directly* from ``__new__`` so the parent MoE block registers it as a real
``nn.Module`` submodule.
This adapter builds that runner, installs the diffusion forward-context
setup and additional platform hooks, and returns the runner *directly* from
``__new__`` so the parent MoE block registers it as a real ``nn.Module``
submodule.
Returning the runner (rather than wrapping it in a plain object that holds it
in an attribute) is required for correctness: a non-Module wrapper hides the
@@ -71,9 +70,11 @@ class HunyuanFusedMoEDefault:
"""
def __new__(cls, *, prefix: str = "", **kwargs: Any) -> Any:
current_omni_platform.prepare_diffusion_op_runtime("fused_moe")
# Current vLLM FusedMoE handles output reduction internally.
kwargs.pop("reduce_results", None)
# FusedMoE is now a factory function — call it to get a MoERunner.
# FusedMoE is now a factory function; call it to get a MoERunner.
from vllm.model_executor.layers.fused_moe import FusedMoE as _FusedMoE
moe_runner = _FusedMoE(prefix=prefix, **kwargs)
@@ -91,21 +92,7 @@ class HunyuanFusedMoEDefault:
_set_forward_context_dp_metadata(hidden_states.shape[0])
moe_runner.register_forward_pre_hook(_num_tokens_pre_hook, with_kwargs=True)
# One-shot lazy kernel initialisation on the first forward (no-op unless
# the runner exposes an uninitialised quant_method). Mirrors the prior
# wrapper behaviour exactly, just bound to the runner module.
init_handle: Any = None
def _kernel_init_pre_hook(module: Any, args: Any, kwargs: Any) -> None:
nonlocal init_handle
quant_method = getattr(module, "quant_method", None)
if quant_method is not None and getattr(quant_method, "moe_kernel", None) is None:
quant_method.process_weights_after_loading(module)
if init_handle is not None:
init_handle.remove()
init_handle = moe_runner.register_forward_pre_hook(_kernel_init_pre_hook, with_kwargs=True)
current_omni_platform.register_additional_diffusion_fused_moe_hooks(moe_runner)
return moe_runner
@@ -138,35 +125,3 @@ class HunyuanFusedMoEDefault:
num_experts=num_experts,
num_redundant_experts=num_redundant_experts,
)
class HunyuanFusedMoE:
def __new__(cls, *, prefix: str = "", **kwargs: Any) -> Any:
op_name = "hunyuan_fused_moe"
current_omni_platform.prepare_diffusion_op_runtime(op_name)
impl = resolve_obj_by_qualname(
current_omni_platform.get_diffusion_model_impl_qualname(op_name),
)
return impl(prefix=prefix, **kwargs)
@classmethod
def make_expert_params_mapping(
cls,
model: Any,
ckpt_gate_proj_name: str,
ckpt_down_proj_name: str,
ckpt_up_proj_name: str,
num_experts: int,
num_redundant_experts: int = 0,
) -> list[tuple[str, str, int, str]]:
impl = resolve_obj_by_qualname(
current_omni_platform.get_diffusion_model_impl_qualname("hunyuan_fused_moe"),
)
return impl.make_expert_params_mapping(
model,
ckpt_gate_proj_name=ckpt_gate_proj_name,
ckpt_down_proj_name=ckpt_down_proj_name,
ckpt_up_proj_name=ckpt_up_proj_name,
num_experts=num_experts,
num_redundant_experts=num_redundant_experts,
)
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Hunyuan Image 3 diffusion model components."""
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_fused_moe import HunyuanFusedMoE
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_image3_transformer import (
HunyuanImage3Model,
HunyuanImage3Text2ImagePipeline,
@@ -11,4 +10,4 @@ from vllm_omni.diffusion.models.hunyuan_image3.pipeline_hunyuan_image3 import (
HunyuanImage3Pipeline,
)
__all__ = ["HunyuanImage3Pipeline", "HunyuanImage3Model", "HunyuanImage3Text2ImagePipeline", "HunyuanFusedMoE"]
__all__ = ["HunyuanImage3Pipeline", "HunyuanImage3Model", "HunyuanImage3Text2ImagePipeline"]
@@ -76,11 +76,12 @@ from vllm_omni.diffusion.distributed.sp_plan import (
)
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.layers.fused_moe import FusedMoE
from vllm_omni.diffusion.layers.norm import RMSNorm
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_fused_moe import HunyuanFusedMoE
from vllm_omni.diffusion.utils.kv_utils import repeat_kv
from vllm_omni.model_executor.layers.timestep_embedding import timestep_embedding
from vllm_omni.platforms import current_omni_platform
logger = logging.getLogger(__name__)
@@ -1620,7 +1621,7 @@ class HunYuanSparseMoeBlock(nn.Module):
self.shared_mlp = None
enable_expert_parallel = get_current_vllm_config().parallel_config.enable_expert_parallel
self.experts = HunyuanFusedMoE(
self.experts = FusedMoE(
shared_experts=self.shared_mlp,
num_experts=self.n_routed_experts,
top_k=top_k,
@@ -2100,7 +2101,7 @@ class HunyuanImage3Model(nn.Module):
if _is_moe(self.config):
# Params for weights, fp8 weight scales, fp8 activation scales
# (param_name, weight_name, expert_id, shard_id)
fused_moe_expert_mapping = HunyuanFusedMoE.make_expert_params_mapping(
fused_moe_expert_mapping = FusedMoE.make_expert_params_mapping(
self,
ckpt_gate_proj_name="gate_proj",
ckpt_down_proj_name="down_proj",
@@ -2381,6 +2382,8 @@ class HunyuanImage3Model(nn.Module):
ar_kv_reuse_len: int = 0,
full_attn_spans: list[list[tuple[int, int]]] | None = None,
) -> tuple | BaseModelOutputWithPast:
current_omni_platform.reset_diffusion_fused_moe_forward_context()
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
@@ -205,6 +205,12 @@ class DiffusionModelRunner(OmniConnectorModelRunnerMixin):
if load_format == "dummy":
return
current_omni_platform.init_diffusion_model_runner_runtime(
vllm_config=self.vllm_config,
od_config=self.od_config,
device=self.device,
)
load_device = (
"cpu" if self.od_config.enable_cpu_offload or self.od_config.enable_layerwise_offload else str(self.device)
)