Prompt48 commited on
Commit
4a05117
·
verified ·
1 Parent(s): 2a93a0f

Upload edit\Qwen3-TTS-test\.venv\Lib\site-packages\transformers\models\hunyuan_v1_moe\modular_hunyuan_v1_moe.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hunyuan_v1_moe//modular_hunyuan_v1_moe.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (C) 2025 THL A29 Limited, a Tencent company and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch HunYuanMoEV1 model."""
16
+
17
+ from typing import Callable, Optional
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+ from torch import nn
22
+
23
+ from transformers.cache_utils import Cache
24
+ from transformers.utils import (
25
+ logging,
26
+ )
27
+
28
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
29
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
30
+ from ...processing_utils import Unpack
31
+ from ...utils import TransformersKwargs
32
+ from ..llama.modeling_llama import (
33
+ LlamaAttention,
34
+ LlamaDecoderLayer,
35
+ LlamaForCausalLM,
36
+ LlamaForSequenceClassification,
37
+ LlamaMLP,
38
+ LlamaModel,
39
+ LlamaPreTrainedModel,
40
+ LlamaRMSNorm,
41
+ apply_rotary_pos_emb,
42
+ eager_attention_forward,
43
+ )
44
+ from .configuration_hunyuan_v1_moe import HunYuanMoEV1Config
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ class HunYuanMoEV1RMSNorm(LlamaRMSNorm):
51
+ pass
52
+
53
+
54
+ class HunYuanMoEV1MLP(LlamaMLP):
55
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx=None, is_shared_mlp=False):
56
+ super().__init__(config)
57
+ self.layer_idx = layer_idx
58
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
59
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
60
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
61
+
62
+
63
+ class HunYuanMoEV1Attention(LlamaAttention):
64
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: int):
65
+ super().__init__(config, layer_idx)
66
+ self.query_layernorm = HunYuanMoEV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
67
+ self.key_layernorm = HunYuanMoEV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
68
+
69
+ def forward(
70
+ self,
71
+ hidden_states: torch.Tensor,
72
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
73
+ attention_mask: Optional[torch.Tensor],
74
+ past_key_values: Optional[Cache] = None,
75
+ cache_position: Optional[torch.LongTensor] = None,
76
+ **kwargs: Unpack[TransformersKwargs],
77
+ ) -> tuple[torch.Tensor, torch.Tensor]:
78
+ input_shape = hidden_states.shape[:-1]
79
+ hidden_shape = (*input_shape, -1, self.head_dim)
80
+
81
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
82
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
83
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
84
+
85
+ cos, sin = position_embeddings
86
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
87
+ query_states = self.query_layernorm(query_states)
88
+ key_states = self.key_layernorm(key_states)
89
+
90
+ if past_key_values is not None:
91
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
92
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
93
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
94
+
95
+ attention_interface: Callable = eager_attention_forward
96
+ if self.config._attn_implementation != "eager":
97
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
98
+
99
+ attn_output, attn_weights = attention_interface(
100
+ self,
101
+ query_states,
102
+ key_states,
103
+ value_states,
104
+ attention_mask,
105
+ dropout=0.0 if not self.training else self.attention_dropout,
106
+ scaling=self.scaling,
107
+ **kwargs,
108
+ )
109
+
110
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
111
+ attn_output = self.o_proj(attn_output)
112
+ return attn_output, attn_weights
113
+
114
+
115
+ class HunYuanMoEV1Gate(nn.Module):
116
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: Optional[int] = None):
117
+ super().__init__()
118
+ self.config = config
119
+ self.layer_idx = layer_idx
120
+ num_experts = config.num_experts if isinstance(config.num_experts, int) else config.num_experts[layer_idx]
121
+ self.wg = nn.Linear(config.hidden_size, num_experts, bias=False, dtype=torch.float32)
122
+
123
+ def forward(self, hidden_states):
124
+ bsz, seq_len, hidden_size = hidden_states.shape
125
+ hidden_states = hidden_states.reshape(-1, hidden_size)
126
+ if self.wg.weight.dtype == torch.float32:
127
+ hidden_states = hidden_states.float()
128
+ logits = self.wg(hidden_states)
129
+ return logits
130
+
131
+
132
+ class HunYuanMoEV1Moe(nn.Module):
133
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: Optional[int] = None):
134
+ super().__init__()
135
+ self.config = config
136
+ self.layer_idx = layer_idx
137
+ self.num_experts = config.num_experts if isinstance(config.num_experts, int) else config.num_experts[layer_idx]
138
+ self.top_k = config.moe_topk if isinstance(config.moe_topk, int) else config.moe_topk[layer_idx]
139
+ self.gate = HunYuanMoEV1Gate(config, layer_idx=layer_idx)
140
+ # self.wg = nn.Linear(config.hidden_size, config.num_experts, bias=False, dtype=torch.float32)
141
+ self.experts = nn.ModuleList(
142
+ [HunYuanMoEV1MLP(config, layer_idx=layer_idx, is_shared_mlp=False) for _ in range(self.num_experts)]
143
+ )
144
+
145
+ self.shared_mlp = HunYuanMoEV1MLP(config, layer_idx=layer_idx, is_shared_mlp=True)
146
+
147
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
148
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
149
+ hidden_states_mlp = self.shared_mlp(hidden_states)
150
+ router_logits = self.gate(hidden_states)
151
+ hidden_states = hidden_states.view(-1, hidden_dim)
152
+ # router_logits: (batch * sequence_length, n_experts)
153
+
154
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
155
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
156
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
157
+ # we cast back to the input dtype
158
+ routing_weights = routing_weights.to(hidden_states.dtype)
159
+
160
+ final_hidden_states = torch.zeros(
161
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
162
+ )
163
+
164
+ # One hot encode the selected experts to create an expert mask
165
+ # this will be used to easily index which expert is going to be sollicitated
166
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
167
+
168
+ # Loop over all available experts in the model and perform the computation on each expert
169
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
170
+ for expert_idx in expert_hit:
171
+ expert_layer = self.experts[expert_idx]
172
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
173
+
174
+ # Index the correct hidden states and compute the expert hidden state for
175
+ # the current expert. We need to make sure to multiply the output hidden
176
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
177
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
178
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
179
+
180
+ # However `index_add_` only support torch tensors for indexing so we'll use
181
+ # the `top_x` tensor here.
182
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
183
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
184
+ return final_hidden_states + hidden_states_mlp
185
+
186
+
187
+ class HunYuanMoEV1DecoderLayer(LlamaDecoderLayer):
188
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: int):
189
+ super().__init__(config, layer_idx)
190
+ self.hidden_size = config.hidden_size
191
+ self.self_attn = HunYuanMoEV1Attention(config=config, layer_idx=layer_idx)
192
+ self.mlp = HunYuanMoEV1Moe(config, layer_idx=layer_idx)
193
+ self.input_layernorm = HunYuanMoEV1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
194
+ self.post_attention_layernorm = HunYuanMoEV1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
195
+ self.layer_idx = layer_idx
196
+
197
+
198
+ class HunYuanMoEV1PreTrainedModel(LlamaPreTrainedModel):
199
+ _can_compile_fullgraph = False
200
+
201
+ def _init_weights(self, module):
202
+ std = self.config.initializer_range
203
+ if isinstance(module, nn.Linear):
204
+ module.weight.data.normal_(mean=0.0, std=std)
205
+ if module.bias is not None:
206
+ module.bias.data.zero_()
207
+ elif isinstance(module, nn.Embedding):
208
+ module.weight.data.normal_(mean=0.0, std=std)
209
+ if module.padding_idx is not None:
210
+ module.weight.data[module.padding_idx].zero_()
211
+
212
+
213
+ class HunYuanMoEV1RotaryEmbedding(nn.Module):
214
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
215
+
216
+ def __init__(self, config: HunYuanMoEV1Config, device=None):
217
+ super().__init__()
218
+ # BC: "rope_type" was originally "type"
219
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
220
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
221
+ else:
222
+ self.rope_type = "default"
223
+ self.max_seq_len_cached = config.max_position_embeddings
224
+ self.original_max_seq_len = config.max_position_embeddings
225
+
226
+ self.config = config
227
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
228
+ if self.rope_type == "dynamic" and config.rope_scaling["alpha"]:
229
+ # DynamicNTKAlphaRotary
230
+ self.dim = config.head_dim
231
+ base = config.rope_theta * config.rope_scaling.get("alpha") ** (self.dim / (self.dim - 2))
232
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
233
+ self.attention_scaling = 1.0
234
+ else:
235
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
236
+
237
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
238
+ self.original_inv_freq = self.inv_freq
239
+
240
+ @torch.no_grad()
241
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
242
+ def forward(self, x, position_ids):
243
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
244
+ position_ids_expanded = position_ids[:, None, :].float()
245
+
246
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
247
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
248
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
249
+ emb = torch.cat((freqs, freqs), dim=-1)
250
+ cos = emb.cos() * self.attention_scaling
251
+ sin = emb.sin() * self.attention_scaling
252
+
253
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
254
+
255
+
256
+ class HunYuanMoEV1Model(LlamaModel):
257
+ pass
258
+
259
+
260
+ class HunYuanMoEV1ForCausalLM(LlamaForCausalLM):
261
+ pass
262
+
263
+
264
+ class HunYuanMoEV1ForSequenceClassification(LlamaForSequenceClassification):
265
+ pass
266
+
267
+
268
+ __all__ = [
269
+ "HunYuanMoEV1ForCausalLM",
270
+ "HunYuanMoEV1Model",
271
+ "HunYuanMoEV1PreTrainedModel",
272
+ "HunYuanMoEV1ForSequenceClassification",
273
+ ]