|
| 1 | +# Copyright (c) 2025, BAAI. All rights reserved. |
| 2 | +# |
| 3 | +# See LICENSE for license information. |
| 4 | + |
| 5 | +from contextlib import nullcontext |
| 6 | +from typing import Any, Callable, Dict, List, Optional, Tuple, Union |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +from transformer_engine.plugin.core.ops import FlashAttentionBase |
| 11 | + |
| 12 | + |
| 13 | +class FlashAttentionMUSA(FlashAttentionBase): |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + softmax_scale: float, |
| 17 | + attention_dropout: float = 0.0, |
| 18 | + attention_dropout_ctx: Optional[Callable] = None, |
| 19 | + attention_type: str = "self", |
| 20 | + layer_number: Optional[int] = None, |
| 21 | + deterministic: bool = False, |
| 22 | + ) -> None: |
| 23 | + super().__init__( |
| 24 | + softmax_scale=softmax_scale, |
| 25 | + attention_dropout=attention_dropout, |
| 26 | + attention_dropout_ctx=attention_dropout_ctx, |
| 27 | + attention_type=attention_type, |
| 28 | + layer_number=layer_number, |
| 29 | + deterministic=deterministic, |
| 30 | + ) |
| 31 | + |
| 32 | + # Store initialization parameters for lazy loading |
| 33 | + self._init_params = { |
| 34 | + "softmax_scale": softmax_scale, |
| 35 | + "attention_dropout": attention_dropout, |
| 36 | + "attention_dropout_ctx": attention_dropout_ctx or nullcontext, |
| 37 | + "attention_type": attention_type, |
| 38 | + "layer_number": layer_number, |
| 39 | + "deterministic": deterministic, |
| 40 | + } |
| 41 | + self._musa_flash_attn = None |
| 42 | + |
| 43 | + def _ensure_musa_flash_attn(self): |
| 44 | + """Lazy initialization of musa FlashAttention.""" |
| 45 | + if self._musa_flash_attn is not None: |
| 46 | + return |
| 47 | + |
| 48 | + try: |
| 49 | + # Import here to avoid circular dependency issues |
| 50 | + # transformer_engine_torch must be registered before this import |
| 51 | + from transformer_engine_musa.pytorch.attention import ( |
| 52 | + FlashAttention as FlashAttentionMusa, |
| 53 | + ) |
| 54 | + |
| 55 | + if FlashAttentionMusa is None: |
| 56 | + raise RuntimeError( |
| 57 | + "FlashAttention class is None - flash-attn may not be installed correctly" |
| 58 | + ) |
| 59 | + |
| 60 | + self._musa_flash_attn = FlashAttentionMusa(**self._init_params) |
| 61 | + |
| 62 | + except ImportError as e: |
| 63 | + raise RuntimeError( |
| 64 | + f"Failed to import musa FlashAttention: {e}. " |
| 65 | + "Please ensure flash-attn is installed and transformer_engine_torch is available." |
| 66 | + ) |
| 67 | + except Exception as e: |
| 68 | + raise RuntimeError( |
| 69 | + f"Failed to initialize musa FlashAttention: {e}. Init params: {self._init_params}" |
| 70 | + ) |
| 71 | + |
| 72 | + @property |
| 73 | + def backend_name(self) -> str: |
| 74 | + return "musa" |
| 75 | + |
| 76 | + def _forward_impl( |
| 77 | + self, |
| 78 | + query_layer: torch.Tensor, |
| 79 | + key_layer: torch.Tensor, |
| 80 | + value_layer: torch.Tensor, |
| 81 | + attention_mask: Optional[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]] = None, |
| 82 | + qkv_layout: str = "sbh3d", |
| 83 | + cu_seqlens_q: Optional[torch.Tensor] = None, |
| 84 | + cu_seqlens_kv: Optional[torch.Tensor] = None, |
| 85 | + max_seqlen_q: Optional[int] = None, |
| 86 | + max_seqlen_kv: Optional[int] = None, |
| 87 | + attn_mask_type: str = "causal", |
| 88 | + window_size: Optional[Tuple[int, int]] = None, |
| 89 | + alibi_slopes: Optional[torch.Tensor] = None, |
| 90 | + cp_group: Optional[Any] = None, |
| 91 | + cp_global_ranks: Optional[List[int]] = None, |
| 92 | + cp_stream: Optional[torch.musa.Stream] = None, |
| 93 | + cp_comm_type: str = "p2p", |
| 94 | + fp8: bool = False, |
| 95 | + fp8_meta: Optional[Dict[str, Any]] = None, |
| 96 | + quantizers: Optional[Any] = None, |
| 97 | + inference_params: Optional[Any] = None, |
| 98 | + flash_attention_backend: Optional[Any] = None, |
| 99 | + fp8_output: bool = False, |
| 100 | + ) -> torch.Tensor: |
| 101 | + # Ensure musa flash attention is initialized |
| 102 | + self._ensure_musa_flash_attn() |
| 103 | + |
| 104 | + return self._musa_flash_attn( |
| 105 | + query_layer=query_layer, |
| 106 | + key_layer=key_layer, |
| 107 | + value_layer=value_layer, |
| 108 | + attention_mask=attention_mask, |
| 109 | + qkv_layout=qkv_layout, |
| 110 | + cu_seqlens_q=cu_seqlens_q, |
| 111 | + cu_seqlens_kv=cu_seqlens_kv, |
| 112 | + max_seqlen_q=max_seqlen_q, |
| 113 | + max_seqlen_kv=max_seqlen_kv, |
| 114 | + attn_mask_type=attn_mask_type, |
| 115 | + window_size=window_size, |
| 116 | + alibi_slopes=alibi_slopes, |
| 117 | + cp_group=cp_group, |
| 118 | + cp_global_ranks=cp_global_ranks, |
| 119 | + cp_stream=cp_stream, |
| 120 | + cp_comm_type=cp_comm_type, |
| 121 | + fp8=fp8, |
| 122 | + fp8_meta=fp8_meta, |
| 123 | + quantizers=quantizers, |
| 124 | + inference_params=inference_params, |
| 125 | + flash_attention_backend=flash_attention_backend, |
| 126 | + fp8_output=fp8_output, |
| 127 | + ) |
0 commit comments