Prompt48 commited on
Commit
2a93a0f
·
verified ·
1 Parent(s): 19d8f15

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hunyuan_v1_moe//modeling_hunyuan_v1_moe.py ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/hunyuan_v1_moe/modular_hunyuan_v1_moe.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_hunyuan_v1_moe.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright (C) 2025 THL A29 Limited, a Tencent company and the HuggingFace Inc. team. All rights reserved.
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, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ from torch import nn
27
+
28
+ from transformers.cache_utils import Cache
29
+
30
+ from ...activations import ACT2FN
31
+ from ...cache_utils import DynamicCache
32
+ from ...generation import GenerationMixin
33
+ from ...integrations import use_kernel_forward_from_hub
34
+ from ...masking_utils import create_causal_mask
35
+ from ...modeling_layers import GenericForSequenceClassification, GradientCheckpointingLayer
36
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
37
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
38
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
39
+ from ...processing_utils import Unpack
40
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
41
+ from ...utils.deprecation import deprecate_kwarg
42
+ from ...utils.generic import check_model_inputs
43
+ from .configuration_hunyuan_v1_moe import HunYuanMoEV1Config
44
+
45
+
46
+ @use_kernel_forward_from_hub("RMSNorm")
47
+ class HunYuanMoEV1RMSNorm(nn.Module):
48
+ def __init__(self, hidden_size, eps=1e-6):
49
+ """
50
+ HunYuanMoEV1RMSNorm is equivalent to T5LayerNorm
51
+ """
52
+ super().__init__()
53
+ self.weight = nn.Parameter(torch.ones(hidden_size))
54
+ self.variance_epsilon = eps
55
+
56
+ def forward(self, hidden_states):
57
+ input_dtype = hidden_states.dtype
58
+ hidden_states = hidden_states.to(torch.float32)
59
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
60
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
61
+ return self.weight * hidden_states.to(input_dtype)
62
+
63
+ def extra_repr(self):
64
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
65
+
66
+
67
+ class HunYuanMoEV1MLP(nn.Module):
68
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx=None, is_shared_mlp=False):
69
+ super().__init__()
70
+ self.config = config
71
+ self.hidden_size = config.hidden_size
72
+ self.intermediate_size = config.intermediate_size
73
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
74
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
75
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
76
+ self.act_fn = ACT2FN[config.hidden_act]
77
+ self.layer_idx = layer_idx
78
+
79
+ def forward(self, x):
80
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
81
+ return down_proj
82
+
83
+
84
+ def rotate_half(x):
85
+ """Rotates half the hidden dims of the input."""
86
+ x1 = x[..., : x.shape[-1] // 2]
87
+ x2 = x[..., x.shape[-1] // 2 :]
88
+ return torch.cat((-x2, x1), dim=-1)
89
+
90
+
91
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
92
+ """Applies Rotary Position Embedding to the query and key tensors.
93
+
94
+ Args:
95
+ q (`torch.Tensor`): The query tensor.
96
+ k (`torch.Tensor`): The key tensor.
97
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
98
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
99
+ position_ids (`torch.Tensor`, *optional*):
100
+ Deprecated and unused.
101
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
102
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
103
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
104
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
105
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
106
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
107
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
108
+ Returns:
109
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
110
+ """
111
+ cos = cos.unsqueeze(unsqueeze_dim)
112
+ sin = sin.unsqueeze(unsqueeze_dim)
113
+ q_embed = (q * cos) + (rotate_half(q) * sin)
114
+ k_embed = (k * cos) + (rotate_half(k) * sin)
115
+ return q_embed, k_embed
116
+
117
+
118
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
119
+ """
120
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
121
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
122
+ """
123
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
124
+ if n_rep == 1:
125
+ return hidden_states
126
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
127
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
128
+
129
+
130
+ def eager_attention_forward(
131
+ module: nn.Module,
132
+ query: torch.Tensor,
133
+ key: torch.Tensor,
134
+ value: torch.Tensor,
135
+ attention_mask: Optional[torch.Tensor],
136
+ scaling: float,
137
+ dropout: float = 0.0,
138
+ **kwargs: Unpack[TransformersKwargs],
139
+ ):
140
+ key_states = repeat_kv(key, module.num_key_value_groups)
141
+ value_states = repeat_kv(value, module.num_key_value_groups)
142
+
143
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
144
+ if attention_mask is not None:
145
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
146
+ attn_weights = attn_weights + causal_mask
147
+
148
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
149
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
150
+ attn_output = torch.matmul(attn_weights, value_states)
151
+ attn_output = attn_output.transpose(1, 2).contiguous()
152
+
153
+ return attn_output, attn_weights
154
+
155
+
156
+ class HunYuanMoEV1Attention(nn.Module):
157
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
158
+
159
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: int):
160
+ super().__init__()
161
+ self.config = config
162
+ self.layer_idx = layer_idx
163
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
164
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
165
+ self.scaling = self.head_dim**-0.5
166
+ self.attention_dropout = config.attention_dropout
167
+ self.is_causal = True
168
+
169
+ self.q_proj = nn.Linear(
170
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
171
+ )
172
+ self.k_proj = nn.Linear(
173
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
174
+ )
175
+ self.v_proj = nn.Linear(
176
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
177
+ )
178
+ self.o_proj = nn.Linear(
179
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
180
+ )
181
+ self.query_layernorm = HunYuanMoEV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
182
+ self.key_layernorm = HunYuanMoEV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
183
+
184
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
185
+ def forward(
186
+ self,
187
+ hidden_states: torch.Tensor,
188
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
189
+ attention_mask: Optional[torch.Tensor],
190
+ past_key_values: Optional[Cache] = None,
191
+ cache_position: Optional[torch.LongTensor] = None,
192
+ **kwargs: Unpack[TransformersKwargs],
193
+ ) -> tuple[torch.Tensor, torch.Tensor]:
194
+ input_shape = hidden_states.shape[:-1]
195
+ hidden_shape = (*input_shape, -1, self.head_dim)
196
+
197
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
198
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
199
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
200
+
201
+ cos, sin = position_embeddings
202
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
203
+ query_states = self.query_layernorm(query_states)
204
+ key_states = self.key_layernorm(key_states)
205
+
206
+ if past_key_values is not None:
207
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
208
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
209
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
210
+
211
+ attention_interface: Callable = eager_attention_forward
212
+ if self.config._attn_implementation != "eager":
213
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
214
+
215
+ attn_output, attn_weights = attention_interface(
216
+ self,
217
+ query_states,
218
+ key_states,
219
+ value_states,
220
+ attention_mask,
221
+ dropout=0.0 if not self.training else self.attention_dropout,
222
+ scaling=self.scaling,
223
+ **kwargs,
224
+ )
225
+
226
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
227
+ attn_output = self.o_proj(attn_output)
228
+ return attn_output, attn_weights
229
+
230
+
231
+ class HunYuanMoEV1Gate(nn.Module):
232
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: Optional[int] = None):
233
+ super().__init__()
234
+ self.config = config
235
+ self.layer_idx = layer_idx
236
+ num_experts = config.num_experts if isinstance(config.num_experts, int) else config.num_experts[layer_idx]
237
+ self.wg = nn.Linear(config.hidden_size, num_experts, bias=False, dtype=torch.float32)
238
+
239
+ def forward(self, hidden_states):
240
+ bsz, seq_len, hidden_size = hidden_states.shape
241
+ hidden_states = hidden_states.reshape(-1, hidden_size)
242
+ if self.wg.weight.dtype == torch.float32:
243
+ hidden_states = hidden_states.float()
244
+ logits = self.wg(hidden_states)
245
+ return logits
246
+
247
+
248
+ class HunYuanMoEV1Moe(nn.Module):
249
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: Optional[int] = None):
250
+ super().__init__()
251
+ self.config = config
252
+ self.layer_idx = layer_idx
253
+ self.num_experts = config.num_experts if isinstance(config.num_experts, int) else config.num_experts[layer_idx]
254
+ self.top_k = config.moe_topk if isinstance(config.moe_topk, int) else config.moe_topk[layer_idx]
255
+ self.gate = HunYuanMoEV1Gate(config, layer_idx=layer_idx)
256
+ # self.wg = nn.Linear(config.hidden_size, config.num_experts, bias=False, dtype=torch.float32)
257
+ self.experts = nn.ModuleList(
258
+ [HunYuanMoEV1MLP(config, layer_idx=layer_idx, is_shared_mlp=False) for _ in range(self.num_experts)]
259
+ )
260
+
261
+ self.shared_mlp = HunYuanMoEV1MLP(config, layer_idx=layer_idx, is_shared_mlp=True)
262
+
263
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
264
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
265
+ hidden_states_mlp = self.shared_mlp(hidden_states)
266
+ router_logits = self.gate(hidden_states)
267
+ hidden_states = hidden_states.view(-1, hidden_dim)
268
+ # router_logits: (batch * sequence_length, n_experts)
269
+
270
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
271
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
272
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
273
+ # we cast back to the input dtype
274
+ routing_weights = routing_weights.to(hidden_states.dtype)
275
+
276
+ final_hidden_states = torch.zeros(
277
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
278
+ )
279
+
280
+ # One hot encode the selected experts to create an expert mask
281
+ # this will be used to easily index which expert is going to be sollicitated
282
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
283
+
284
+ # Loop over all available experts in the model and perform the computation on each expert
285
+ expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
286
+ for expert_idx in expert_hit:
287
+ expert_layer = self.experts[expert_idx]
288
+ idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
289
+
290
+ # Index the correct hidden states and compute the expert hidden state for
291
+ # the current expert. We need to make sure to multiply the output hidden
292
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
293
+ current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
294
+ current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
295
+
296
+ # However `index_add_` only support torch tensors for indexing so we'll use
297
+ # the `top_x` tensor here.
298
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
299
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
300
+ return final_hidden_states + hidden_states_mlp
301
+
302
+
303
+ class HunYuanMoEV1DecoderLayer(GradientCheckpointingLayer):
304
+ def __init__(self, config: HunYuanMoEV1Config, layer_idx: int):
305
+ super().__init__()
306
+ self.hidden_size = config.hidden_size
307
+ self.self_attn = HunYuanMoEV1Attention(config=config, layer_idx=layer_idx)
308
+ self.mlp = HunYuanMoEV1Moe(config, layer_idx=layer_idx)
309
+ self.input_layernorm = HunYuanMoEV1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
310
+ self.post_attention_layernorm = HunYuanMoEV1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
311
+ self.layer_idx = layer_idx
312
+
313
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
314
+ def forward(
315
+ self,
316
+ hidden_states: torch.Tensor,
317
+ attention_mask: Optional[torch.Tensor] = None,
318
+ position_ids: Optional[torch.LongTensor] = None,
319
+ past_key_values: Optional[Cache] = None,
320
+ use_cache: Optional[bool] = False,
321
+ cache_position: Optional[torch.LongTensor] = None,
322
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
323
+ **kwargs: Unpack[TransformersKwargs],
324
+ ) -> torch.Tensor:
325
+ residual = hidden_states
326
+ hidden_states = self.input_layernorm(hidden_states)
327
+ # Self Attention
328
+ hidden_states, _ = self.self_attn(
329
+ hidden_states=hidden_states,
330
+ attention_mask=attention_mask,
331
+ position_ids=position_ids,
332
+ past_key_values=past_key_values,
333
+ use_cache=use_cache,
334
+ cache_position=cache_position,
335
+ position_embeddings=position_embeddings,
336
+ **kwargs,
337
+ )
338
+ hidden_states = residual + hidden_states
339
+
340
+ # Fully Connected
341
+ residual = hidden_states
342
+ hidden_states = self.post_attention_layernorm(hidden_states)
343
+ hidden_states = self.mlp(hidden_states)
344
+ hidden_states = residual + hidden_states
345
+ return hidden_states
346
+
347
+
348
+ @auto_docstring
349
+ class HunYuanMoEV1PreTrainedModel(PreTrainedModel):
350
+ config: HunYuanMoEV1Config
351
+ base_model_prefix = "model"
352
+ supports_gradient_checkpointing = True
353
+ _no_split_modules = ["HunYuanMoEV1DecoderLayer"]
354
+ _skip_keys_device_placement = ["past_key_values"]
355
+ _supports_flash_attn = True
356
+ _supports_sdpa = True
357
+ _supports_flex_attn = True
358
+ _can_compile_fullgraph = False
359
+ _supports_attention_backend = True
360
+ _can_record_outputs = {
361
+ "hidden_states": HunYuanMoEV1DecoderLayer,
362
+ "attentions": HunYuanMoEV1Attention,
363
+ }
364
+
365
+ def _init_weights(self, module):
366
+ std = self.config.initializer_range
367
+ if isinstance(module, nn.Linear):
368
+ module.weight.data.normal_(mean=0.0, std=std)
369
+ if module.bias is not None:
370
+ module.bias.data.zero_()
371
+ elif isinstance(module, nn.Embedding):
372
+ module.weight.data.normal_(mean=0.0, std=std)
373
+ if module.padding_idx is not None:
374
+ module.weight.data[module.padding_idx].zero_()
375
+
376
+
377
+ class HunYuanMoEV1RotaryEmbedding(nn.Module):
378
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
379
+
380
+ def __init__(self, config: HunYuanMoEV1Config, device=None):
381
+ super().__init__()
382
+ # BC: "rope_type" was originally "type"
383
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
384
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
385
+ else:
386
+ self.rope_type = "default"
387
+ self.max_seq_len_cached = config.max_position_embeddings
388
+ self.original_max_seq_len = config.max_position_embeddings
389
+
390
+ self.config = config
391
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
392
+ if self.rope_type == "dynamic" and config.rope_scaling["alpha"]:
393
+ # DynamicNTKAlphaRotary
394
+ self.dim = config.head_dim
395
+ base = config.rope_theta * config.rope_scaling.get("alpha") ** (self.dim / (self.dim - 2))
396
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
397
+ self.attention_scaling = 1.0
398
+ else:
399
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
400
+
401
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
402
+ self.original_inv_freq = self.inv_freq
403
+
404
+ @torch.no_grad()
405
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
406
+ def forward(self, x, position_ids):
407
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
408
+ position_ids_expanded = position_ids[:, None, :].float()
409
+
410
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
411
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
412
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
413
+ emb = torch.cat((freqs, freqs), dim=-1)
414
+ cos = emb.cos() * self.attention_scaling
415
+ sin = emb.sin() * self.attention_scaling
416
+
417
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
418
+
419
+
420
+ @auto_docstring
421
+ class HunYuanMoEV1Model(HunYuanMoEV1PreTrainedModel):
422
+ def __init__(self, config: HunYuanMoEV1Config):
423
+ super().__init__(config)
424
+ self.padding_idx = config.pad_token_id
425
+ self.vocab_size = config.vocab_size
426
+
427
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
428
+ self.layers = nn.ModuleList(
429
+ [HunYuanMoEV1DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
430
+ )
431
+ self.norm = HunYuanMoEV1RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
432
+ self.rotary_emb = HunYuanMoEV1RotaryEmbedding(config=config)
433
+ self.gradient_checkpointing = False
434
+
435
+ # Initialize weights and apply final processing
436
+ self.post_init()
437
+
438
+ @check_model_inputs()
439
+ @auto_docstring
440
+ def forward(
441
+ self,
442
+ input_ids: Optional[torch.LongTensor] = None,
443
+ attention_mask: Optional[torch.Tensor] = None,
444
+ position_ids: Optional[torch.LongTensor] = None,
445
+ past_key_values: Optional[Cache] = None,
446
+ inputs_embeds: Optional[torch.FloatTensor] = None,
447
+ cache_position: Optional[torch.LongTensor] = None,
448
+ use_cache: Optional[bool] = None,
449
+ **kwargs: Unpack[TransformersKwargs],
450
+ ) -> BaseModelOutputWithPast:
451
+ if (input_ids is None) ^ (inputs_embeds is not None):
452
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
453
+
454
+ if inputs_embeds is None:
455
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
456
+
457
+ if use_cache and past_key_values is None:
458
+ past_key_values = DynamicCache(config=self.config)
459
+
460
+ if cache_position is None:
461
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
462
+ cache_position: torch.Tensor = torch.arange(
463
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
464
+ )
465
+
466
+ if position_ids is None:
467
+ position_ids = cache_position.unsqueeze(0)
468
+
469
+ causal_mask = create_causal_mask(
470
+ config=self.config,
471
+ input_embeds=inputs_embeds,
472
+ attention_mask=attention_mask,
473
+ cache_position=cache_position,
474
+ past_key_values=past_key_values,
475
+ position_ids=position_ids,
476
+ )
477
+
478
+ hidden_states = inputs_embeds
479
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
480
+
481
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
482
+ hidden_states = decoder_layer(
483
+ hidden_states,
484
+ attention_mask=causal_mask,
485
+ position_ids=position_ids,
486
+ past_key_values=past_key_values,
487
+ cache_position=cache_position,
488
+ position_embeddings=position_embeddings,
489
+ **kwargs,
490
+ )
491
+
492
+ hidden_states = self.norm(hidden_states)
493
+ return BaseModelOutputWithPast(
494
+ last_hidden_state=hidden_states,
495
+ past_key_values=past_key_values,
496
+ )
497
+
498
+
499
+ @auto_docstring
500
+ class HunYuanMoEV1ForCausalLM(HunYuanMoEV1PreTrainedModel, GenerationMixin):
501
+ _tied_weights_keys = ["lm_head.weight"]
502
+ _tp_plan = {"lm_head": "colwise_rep"}
503
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
504
+
505
+ def __init__(self, config):
506
+ super().__init__(config)
507
+ self.model = HunYuanMoEV1Model(config)
508
+ self.vocab_size = config.vocab_size
509
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
510
+
511
+ # Initialize weights and apply final processing
512
+ self.post_init()
513
+
514
+ @can_return_tuple
515
+ @auto_docstring
516
+ def forward(
517
+ self,
518
+ input_ids: Optional[torch.LongTensor] = None,
519
+ attention_mask: Optional[torch.Tensor] = None,
520
+ position_ids: Optional[torch.LongTensor] = None,
521
+ past_key_values: Optional[Cache] = None,
522
+ inputs_embeds: Optional[torch.FloatTensor] = None,
523
+ labels: Optional[torch.LongTensor] = None,
524
+ use_cache: Optional[bool] = None,
525
+ cache_position: Optional[torch.LongTensor] = None,
526
+ logits_to_keep: Union[int, torch.Tensor] = 0,
527
+ **kwargs: Unpack[TransformersKwargs],
528
+ ) -> CausalLMOutputWithPast:
529
+ r"""
530
+ Example:
531
+
532
+ ```python
533
+ >>> from transformers import AutoTokenizer, HunYuanMoEV1ForCausalLM
534
+
535
+ >>> model = HunYuanMoEV1ForCausalLM.from_pretrained("meta-hunyuan_v1_moe/HunYuanMoEV1-2-7b-hf")
536
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-hunyuan_v1_moe/HunYuanMoEV1-2-7b-hf")
537
+
538
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
539
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
540
+
541
+ >>> # Generate
542
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
543
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
544
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
545
+ ```"""
546
+ outputs: BaseModelOutputWithPast = self.model(
547
+ input_ids=input_ids,
548
+ attention_mask=attention_mask,
549
+ position_ids=position_ids,
550
+ past_key_values=past_key_values,
551
+ inputs_embeds=inputs_embeds,
552
+ use_cache=use_cache,
553
+ cache_position=cache_position,
554
+ **kwargs,
555
+ )
556
+
557
+ hidden_states = outputs.last_hidden_state
558
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
559
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
560
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
561
+
562
+ loss = None
563
+ if labels is not None:
564
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
565
+
566
+ return CausalLMOutputWithPast(
567
+ loss=loss,
568
+ logits=logits,
569
+ past_key_values=outputs.past_key_values,
570
+ hidden_states=outputs.hidden_states,
571
+ attentions=outputs.attentions,
572
+ )
573
+
574
+
575
+ class HunYuanMoEV1ForSequenceClassification(GenericForSequenceClassification, HunYuanMoEV1PreTrainedModel):
576
+ pass
577
+
578
+
579
+ __all__ = [
580
+ "HunYuanMoEV1ForCausalLM",
581
+ "HunYuanMoEV1Model",
582
+ "HunYuanMoEV1PreTrainedModel",
583
+ "HunYuanMoEV1ForSequenceClassification",
584
+ ]