|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. |
| 3 | +# Copyright 2023 The vLLM team. |
| 4 | +# Copyright 2023 DeepSeek-AI and the HuggingFace Inc. team. All rights reserved. |
| 5 | +# |
| 6 | +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX |
| 7 | +# and OPT implementations in this library. It has been modified from its |
| 8 | +# original forms to accommodate minor architectural differences compared |
| 9 | +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. |
| 10 | +# |
| 11 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 12 | +# you may not use this file except in compliance with the License. |
| 13 | +# You may obtain a copy of the License at |
| 14 | +# |
| 15 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 16 | +# |
| 17 | +# Unless required by applicable law or agreed to in writing, software |
| 18 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 19 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 20 | +# See the License for the specific language governing permissions and |
| 21 | +# limitations under the License. |
| 22 | +from dataclasses import dataclass |
| 23 | +from typing import Optional |
| 24 | + |
| 25 | +import torch |
| 26 | +from torch import nn |
| 27 | +from vllm.attention import Attention, AttentionMetadata |
| 28 | +from vllm.config import CacheConfig |
| 29 | +from vllm.forward_context import get_forward_context |
| 30 | +from vllm.model_executor.layers.mla import MultiHeadLatentAttention |
| 31 | +from vllm.model_executor.layers.quantization import QuantizationConfig |
| 32 | + |
| 33 | + |
| 34 | +@dataclass |
| 35 | +class AscendMLAModules: |
| 36 | + q_a_proj: Optional[torch.nn.Module] |
| 37 | + q_a_layernorm: Optional[torch.nn.Module] |
| 38 | + q_proj: Optional[torch.nn.Module] |
| 39 | + kv_a_proj_with_mqa: torch.nn.Module |
| 40 | + kv_a_layernorm: torch.nn.Module |
| 41 | + kv_b_proj: torch.nn.Module |
| 42 | + o_proj: torch.nn.Module |
| 43 | + rotary_emb: torch.nn.Module |
| 44 | + |
| 45 | + |
| 46 | +class AscendMultiHeadLatentAttention(MultiHeadLatentAttention): |
| 47 | + |
| 48 | + def __init__( |
| 49 | + self, |
| 50 | + hidden_size: int, |
| 51 | + enable_shared_expert_dp: bool, |
| 52 | + debug_layer_idx: int, |
| 53 | + first_k_dense_replace: int, |
| 54 | + tp_size: int, |
| 55 | + mla_modules: AscendMLAModules, |
| 56 | + num_local_heads: int, |
| 57 | + scaling: float, |
| 58 | + layers: int, |
| 59 | + kv_lora_rank: int, |
| 60 | + qk_rope_head_dim: int, |
| 61 | + q_lora_rank: Optional[int], |
| 62 | + qk_nope_head_dim: int, |
| 63 | + qk_head_dim: int, |
| 64 | + v_head_dim: int, |
| 65 | + cache_config: Optional[CacheConfig] = None, |
| 66 | + quant_config: Optional[QuantizationConfig] = None, |
| 67 | + prefix: str = "", |
| 68 | + ) -> None: |
| 69 | + nn.Module.__init__(self) |
| 70 | + self.hidden_size = hidden_size |
| 71 | + self.enable_shared_expert_dp = enable_shared_expert_dp |
| 72 | + self.debug_layer_idx = debug_layer_idx |
| 73 | + self.first_k_dense_replace = first_k_dense_replace |
| 74 | + self.tp_size = tp_size |
| 75 | + self.num_local_heads = num_local_heads |
| 76 | + self.layers = layers |
| 77 | + self.kv_lora_rank = kv_lora_rank |
| 78 | + self.qk_rope_head_dim = qk_rope_head_dim |
| 79 | + self.q_lora_rank = q_lora_rank |
| 80 | + self.qk_nope_head_dim = qk_nope_head_dim |
| 81 | + self.qk_head_dim = qk_head_dim |
| 82 | + self.v_head_dim = v_head_dim |
| 83 | + |
| 84 | + self.mla_attn = Attention( |
| 85 | + num_heads=self.num_local_heads, |
| 86 | + head_size=self.kv_lora_rank + self.qk_rope_head_dim, |
| 87 | + scale=scaling, |
| 88 | + num_kv_heads=1, |
| 89 | + cache_config=cache_config, |
| 90 | + quant_config=quant_config, |
| 91 | + prefix=f"{prefix}.attn", |
| 92 | + use_mla=True, |
| 93 | + # MLA Args |
| 94 | + q_lora_rank=self.q_lora_rank, |
| 95 | + kv_lora_rank=self.kv_lora_rank, |
| 96 | + qk_nope_head_dim=self.qk_nope_head_dim, |
| 97 | + qk_rope_head_dim=self.qk_rope_head_dim, |
| 98 | + qk_head_dim=self.qk_head_dim, |
| 99 | + v_head_dim=self.v_head_dim, |
| 100 | + rotary_emb=mla_modules.rotary_emb, |
| 101 | + q_a_proj=mla_modules.q_a_proj, |
| 102 | + q_a_layernorm=mla_modules.q_a_layernorm, |
| 103 | + q_proj=mla_modules.q_proj, |
| 104 | + kv_a_proj_with_mqa=mla_modules.kv_a_proj_with_mqa, |
| 105 | + kv_a_layernorm=mla_modules.kv_a_layernorm, |
| 106 | + kv_b_proj=mla_modules.kv_b_proj, |
| 107 | + o_proj=mla_modules.o_proj, |
| 108 | + ) |
| 109 | + |
| 110 | + def forward( |
| 111 | + self, |
| 112 | + positions: torch.Tensor, |
| 113 | + hidden_states: torch.Tensor, |
| 114 | + kv_cache: Optional[torch.Tensor] = None, |
| 115 | + attn_metadata: Optional[AttentionMetadata] = None) -> torch.Tensor: |
| 116 | + forward_context = get_forward_context() |
| 117 | + if kv_cache is None: |
| 118 | + kv_cache = self.mla_attn.kv_cache[forward_context.virtual_engine] |
| 119 | + num_tokens = hidden_states.shape[0] |
| 120 | + need_gather_q_kv = False |
| 121 | + if self.enable_shared_expert_dp and self.debug_layer_idx > self.first_k_dense_replace and self.debug_layer_idx < self.layers: |
| 122 | + # Simulate all gather to calculate output shape |
| 123 | + num_tokens = num_tokens * self.tp_size |
| 124 | + need_gather_q_kv = True |
| 125 | + if not self.enable_shared_expert_dp or self.debug_layer_idx < self.first_k_dense_replace: |
| 126 | + output_shape = hidden_states.shape |
| 127 | + else: |
| 128 | + rows = num_tokens // self.tp_size |
| 129 | + if num_tokens % self.tp_size: |
| 130 | + rows += 1 |
| 131 | + output_shape = (rows, hidden_states.shape[1]) |
| 132 | + output = torch.empty(output_shape, |
| 133 | + dtype=hidden_states.dtype, |
| 134 | + device=hidden_states.device) |
| 135 | + output = self.mla_attn.impl.forward(hidden_states, kv_cache, |
| 136 | + forward_context.attn_metadata, |
| 137 | + need_gather_q_kv, output) |
| 138 | + output = output.view(-1, output_shape[-1]) |
| 139 | + return output |
0 commit comments