-
Notifications
You must be signed in to change notification settings - Fork 48
feat(npu): add MindIE-SD compile fusion and MINDIE attention backend #259
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Chitandaaaaa
wants to merge
6
commits into
modelscope:v1
Choose a base branch
from
Chitandaaaaa:feat/npu-compile-rebased
base: v1
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d2ad4d8
feat(npu): add MindIE-SD compile fusion and MINDIE attention backend
e94848c
fix(npu): apply MindIE-SD compile in Pipeline.init_transformer
0b6dff2
fix(npu): disable MindIE-SD fast GELU fusion in compile backend
49ade03
refactor(npu): drop redundant MindIE compile from DiffusionModel
30aa278
fix(npu): auto-detect device and attention backend
7553f93
fix(npu): compile repeated blocks individually to avoid graph break
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import torch | ||
|
|
||
| from diffsynth_engine.layers.attention.backends.abstract import ( | ||
| AttentionBackend, | ||
| AttentionImpl, | ||
| AttentionMetadata, | ||
| AttentionType, | ||
| ) | ||
| from diffsynth_engine.utils import logging | ||
| from diffsynth_engine.utils.platform import is_npu_available | ||
|
|
||
| logger = logging.get_logger(__name__) | ||
|
|
||
| try: | ||
| from mindiesd.layers.flash_attn.attention_forward import attention_forward | ||
|
|
||
| MINDIESD_ATTN_AVAILABLE = is_npu_available() | ||
| except ImportError: | ||
| MINDIESD_ATTN_AVAILABLE = False | ||
|
|
||
| class MindieAttentionBackend(AttentionBackend): | ||
| @staticmethod | ||
| def check_availability() -> None: | ||
| if not MINDIESD_ATTN_AVAILABLE: | ||
| error_msg = "MindiesdAttention backend is not available. Please visit https://gitcode.com/Ascend/MindIE-SD/blob/dev/docs/zh/features/core_layers.md and follow the installation instructions." | ||
| logger.error(error_msg) | ||
| raise RuntimeError(error_msg) | ||
|
|
||
| @staticmethod | ||
| def get_type() -> str: | ||
| return str(AttentionType.MINDIE) | ||
|
|
||
| @staticmethod | ||
| def get_impl_cls() -> type["AttentionImpl"]: | ||
| return MindieAttentionImpl | ||
|
|
||
| @staticmethod | ||
| def get_supported_head_sizes() -> list[int]: | ||
| return [] | ||
|
|
||
|
|
||
| class MindieAttentionImpl(AttentionImpl): | ||
| def __init__( | ||
| self, | ||
| num_heads: int, | ||
| head_size: int, | ||
| softmax_scale: float | None = None, | ||
| causal: bool = False, | ||
| num_kv_heads: int | None = None, | ||
| **extra_impl_args, | ||
| ) -> None: | ||
| self.scale = softmax_scale or (head_size**-0.5) | ||
|
|
||
| def forward( | ||
| self, | ||
| query: torch.Tensor, | ||
| key: torch.Tensor, | ||
| value: torch.Tensor, | ||
| attn_mask: torch.Tensor | None = None, | ||
| attn_metadata: AttentionMetadata | None = None, | ||
| **kwargs, | ||
| ) -> torch.Tensor: | ||
| return attention_forward( | ||
| query=query, | ||
| key=key, | ||
| value=value, | ||
| attn_mask=attn_mask, | ||
| scale=self.scale, | ||
| fused=True, | ||
| head_first=False, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| from diffsynth_engine.utils.platform import is_mindie_sd_available | ||
|
|
||
| from .compilation import apply_mindie_sd_compile | ||
|
|
||
| __all__ = [ | ||
| "apply_mindie_sd_compile", | ||
| "is_mindie_sd_available", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import os | ||
| import torch | ||
|
|
||
| from diffsynth_engine.utils.platform import is_mindie_sd_available | ||
|
|
||
|
|
||
| def apply_mindie_sd_compile(model: torch.nn.Module) -> torch.nn.Module: | ||
| """Apply MindIE-SD torch.compile backend fusion patterns. | ||
|
|
||
| Enables RMSNorm, RoPE, AdaLayerNorm, and MulAdd op fusion for NPU execution. | ||
| FastGELU fusion is disabled (npu_fast_gelu was slower than native GELU in practice). | ||
| On non-NPU devices or when mindiesd is unavailable, returns the model unchanged. | ||
|
|
||
| Compilation strategy: | ||
| If the model defines ``_repeated_blocks`` (e.g. ``["QwenImageTransformerBlock"]``), | ||
| compiles only the repeated submodules individually to reduce compilation time | ||
| and graph break risk. Otherwise falls back to full-model ``torch.compile``. | ||
| Set ``DIFFSYNTH_DISABLE_COMPILE=1`` to disable. | ||
| """ | ||
| if not is_mindie_sd_available() or os.environ.get("DIFFSYNTH_DISABLE_COMPILE", "0") == "1": | ||
| return model | ||
|
|
||
| from mindiesd.compilation import CompilationConfig, MindieSDBackend | ||
|
|
||
| CompilationConfig.fusion_patterns.enable_fast_gelu = False | ||
|
|
||
| repeated_blocks = getattr(model, "_repeated_blocks", None) | ||
| if repeated_blocks: | ||
| paths = [ | ||
| name | ||
| for name, submodule in model.named_modules() | ||
| if submodule.__class__.__name__ in repeated_blocks | ||
| ] | ||
| # Sort by depth in descending order (submodules before parent modules) | ||
| paths.sort(key=lambda p: len(p.split(".")), reverse=True) | ||
|
|
||
| backend = MindieSDBackend() | ||
| for name in paths: | ||
| parent_name, _, child_name = name.rpartition(".") | ||
| parent = model.get_submodule(parent_name) if parent_name else model | ||
| submodule = getattr(parent, child_name) | ||
| setattr(parent, child_name, torch.compile(submodule, backend=backend)) | ||
|
|
||
| return model | ||
|
|
||
| # Fall back to full-model compilation for models without `_repeated_blocks` defined. | ||
| return torch.compile(model, backend=MindieSDBackend()) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 这里整体torch.compile不会有graph break问题吗?一般实践中我们只compile repeated blocks |
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| import torch | ||
| from functools import cache | ||
|
|
||
|
|
||
| def _is_cuda() -> bool: | ||
|
|
@@ -12,8 +13,28 @@ def _is_rocm() -> bool: | |
| def _is_mps() -> bool: | ||
| return torch.backends.mps.is_available() | ||
|
|
||
| @cache | ||
| def is_npu_available() -> bool: | ||
| try: | ||
| import torch_npu | ||
|
|
||
| return torch_npu.npu.is_available() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 建议改成类似FLASH_ATTN_3_AVAILABLE的环境变量而不是每次try import |
||
| except ImportError: | ||
| return False | ||
|
|
||
| @cache | ||
| def is_mindie_sd_available() -> bool: | ||
| try: | ||
| import mindiesd # noqa: F401 | ||
|
|
||
| return is_npu_available() | ||
| except ImportError: | ||
| return False | ||
|
|
||
|
|
||
| def get_device(local_rank: int) -> torch.device: | ||
| if is_npu_available(): | ||
| return torch.device("npu", local_rank) | ||
| if _is_cuda() or _is_rocm(): | ||
| return torch.device("cuda", local_rank) | ||
| if _is_mps(): | ||
|
|
@@ -23,6 +44,8 @@ def get_device(local_rank: int) -> torch.device: | |
|
|
||
|
|
||
| def get_device_type() -> str: | ||
| if is_npu_available(): | ||
| return "npu" | ||
| if _is_cuda() or _is_rocm(): | ||
| return "cuda" | ||
| if _is_mps(): | ||
|
|
@@ -32,6 +55,8 @@ def get_device_type() -> str: | |
|
|
||
|
|
||
| def get_torch_distributed_backend() -> str: | ||
| if is_npu_available(): | ||
| return "hccl" | ||
| if _is_cuda() or _is_rocm(): | ||
| return "nccl" | ||
| if _is_mps(): | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Forcing
torch.compileviaapply_mindie_sd_compilewheneveris_mindie_sd_available()is True leaves no option for the user to run in eager mode. This can be problematic for debugging, avoiding compilation overhead, or handling models that are incompatible with compilation. Consider adding an opt-out mechanism, such as checking an environment variable (e.g.,DIFFSYNTH_DISABLE_COMPILE).