openpangu/openPangu-R-7B-Diffusion
023
1# coding=utf-82# Copyright (c) 2025 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-NeoX6# and OPT implementations in this library. It has been modified from its7# original forms to accommodate minor architectural differences compared8# 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 at13#14# http://www.apache.org/licenses/LICENSE-2.015#16# Unless required by applicable law or agreed to in writing, software17# 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 and20# limitations under the License.21 22from typing import Callable, Optional, Tuple23 24import torch25from torch import nn26 27import torch_npu28from torch_npu.contrib import transfer_to_npu29if "910" in torch.npu.get_device_name():30 NPU_ATTN_INFR = True31 print("[INFO] torch_npu detected. Using NPU fused infer attention.")32else:33 NPU_ATTN_INFR = False34 35from transformers.cache_utils import Cache36from transformers.modeling_flash_attention_utils import FlashAttentionKwargs37from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS38from transformers.processing_utils import Unpack39from transformers.utils import logging40from 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)50from .configuration_openpangu_dense import PanguEmbeddedConfig51 52 53logger = logging.get_logger(__name__)54 55 56class 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 64class PanguEmbeddedAttention(LlamaAttention):65 def __init__(self, config: PanguEmbeddedConfig, layer_idx: int):66 super().__init__()67 self.config = config68 self.layer_idx = layer_idx69 self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)70 self.num_heads = config.num_attention_heads71 self.num_key_value_heads = config.num_key_value_heads72 self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads73 self.scaling = self.head_dim**-0.574 self.attention_dropout = config.attention_dropout75 self.is_causal = True76 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_embeddings99 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 cache103 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_forward107 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 = None123 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_weights138 139 140class PanguEmbeddedDecoderLayer(LlamaDecoderLayer):141 pass142 143 144class PanguEmbeddedModel(LlamaModel):145 pass146 147 148class PanguEmbeddedForCausalLM(LlamaForCausalLM):149 pass