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Huawei Technologies Co., Ltd. All Rights Reserved.
|
| 3 |
+
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All Rights Reserved.
|
| 4 |
+
#
|
| 5 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 6 |
+
# and OPT implementations in this library. It has been modified from its
|
| 7 |
+
# original forms to accommodate minor architectural differences compared
|
| 8 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
from typing import Callable, Optional, Tuple
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from torch import nn
|
| 26 |
+
|
| 27 |
+
import torch_npu
|
| 28 |
+
from torch_npu.contrib import transfer_to_npu
|
| 29 |
+
if "910" in torch.npu.get_device_name():
|
| 30 |
+
NPU_ATTN_INFR = True
|
| 31 |
+
print("[INFO] torch_npu detected. Using NPU fused infer attention.")
|
| 32 |
+
else:
|
| 33 |
+
NPU_ATTN_INFR = False
|
| 34 |
+
|
| 35 |
+
from transformers.cache_utils import Cache
|
| 36 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 37 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS
|
| 38 |
+
from transformers.processing_utils import Unpack
|
| 39 |
+
from transformers.utils import logging
|
| 40 |
+
from transformers.models.llama.modeling_llama import (
|
| 41 |
+
LlamaAttention,
|
| 42 |
+
LlamaDecoderLayer,
|
| 43 |
+
LlamaForCausalLM,
|
| 44 |
+
LlamaForSequenceClassification,
|
| 45 |
+
LlamaMLP,
|
| 46 |
+
LlamaModel,
|
| 47 |
+
apply_rotary_pos_emb,
|
| 48 |
+
eager_attention_forward,
|
| 49 |
+
)
|
| 50 |
+
from .configuration_openpangu_dense import PanguEmbeddedConfig
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
logger = logging.get_logger(__name__)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class PanguEmbeddedMLP(LlamaMLP):
|
| 57 |
+
def __init__(self, config):
|
| 58 |
+
super().__init__(config)
|
| 59 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 60 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 61 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PanguEmbeddedAttention(LlamaAttention):
|
| 65 |
+
def __init__(self, config: PanguEmbeddedConfig, layer_idx: int):
|
| 66 |
+
super().__init__()
|
| 67 |
+
self.config = config
|
| 68 |
+
self.layer_idx = layer_idx
|
| 69 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 70 |
+
self.num_heads = config.num_attention_heads
|
| 71 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 72 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 73 |
+
self.scaling = self.head_dim**-0.5
|
| 74 |
+
self.attention_dropout = config.attention_dropout
|
| 75 |
+
self.is_causal = True
|
| 76 |
+
|
| 77 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.bias)
|
| 78 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.bias)
|
| 79 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.bias)
|
| 80 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.bias)
|
| 81 |
+
|
| 82 |
+
def forward(
|
| 83 |
+
self,
|
| 84 |
+
hidden_states: torch.Tensor,
|
| 85 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 86 |
+
attention_mask: Optional[torch.Tensor],
|
| 87 |
+
past_key_value: Optional[Cache] = None,
|
| 88 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 89 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 90 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
|
| 91 |
+
input_shape = hidden_states.shape[:-1]
|
| 92 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 93 |
+
|
| 94 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 95 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 96 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 97 |
+
|
| 98 |
+
cos, sin = position_embeddings
|
| 99 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 100 |
+
|
| 101 |
+
if past_key_value is not None:
|
| 102 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 103 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 104 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 105 |
+
|
| 106 |
+
attention_interface: Callable = eager_attention_forward
|
| 107 |
+
if self.config._attn_implementation != "eager":
|
| 108 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 109 |
+
|
| 110 |
+
if not self.training and NPU_ATTN_INFR:
|
| 111 |
+
q_len = input_shape[1]
|
| 112 |
+
if attention_mask is not None:
|
| 113 |
+
attention_mask = ~attention_mask.bool()
|
| 114 |
+
elif q_len > 1:
|
| 115 |
+
attention_mask = torch.triu(torch.ones([q_len, q_len]), diagonal=1).bool().unsqueeze(0).unsqueeze(0).to(query_states.device)
|
| 116 |
+
|
| 117 |
+
attn_output, _ = torch_npu.npu_fused_infer_attention_score(
|
| 118 |
+
query_states, key_states, value_states,
|
| 119 |
+
num_heads=self.num_heads, num_key_value_heads=self.num_key_value_heads,
|
| 120 |
+
input_layout="BNSD", atten_mask=attention_mask, scale=self.scaling)
|
| 121 |
+
attn_output = attn_output.transpose(1, 2)
|
| 122 |
+
attn_weights = None
|
| 123 |
+
else:
|
| 124 |
+
attn_output, attn_weights = attention_interface(
|
| 125 |
+
self,
|
| 126 |
+
query_states,
|
| 127 |
+
key_states,
|
| 128 |
+
value_states,
|
| 129 |
+
attention_mask,
|
| 130 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 131 |
+
scaling=self.scaling,
|
| 132 |
+
**kwargs,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 136 |
+
attn_output = self.o_proj(attn_output)
|
| 137 |
+
return attn_output, attn_weights
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class PanguEmbeddedDecoderLayer(LlamaDecoderLayer):
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class PanguEmbeddedModel(LlamaModel):
|
| 145 |
+
pass
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class PanguEmbeddedForCausalLM(LlamaForCausalLM):
|
| 149 |
+
pass
|