manaestras commited on
Commit
fbf401f
·
verified ·
1 Parent(s): e92eea2

Upload ./modeling_hunyuan.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_hunyuan.py +1727 -0
modeling_hunyuan.py ADDED
@@ -0,0 +1,1727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
2
+ #
3
+ # Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://github.com/Tencent/Tencent-Hunyuan-Large/blob/main/License.docx
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ """ PyTorch HunYuan model."""
16
+
17
+ import math
18
+ import warnings
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import Tensor
23
+ import torch.nn.functional as F
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache
30
+ from transformers.modeling_attn_mask_utils import (
31
+ AttentionMaskConverter,
32
+ _prepare_4d_attention_mask,
33
+ _prepare_4d_causal_attention_mask,
34
+ _prepare_4d_causal_attention_mask_for_sdpa,
35
+ )
36
+ from transformers.modeling_outputs import (
37
+ BaseModelOutputWithPast,
38
+ CausalLMOutputWithPast,
39
+ SequenceClassifierOutputWithPast
40
+ )
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_2_available,
47
+ is_flash_attn_greater_or_equal_2_10,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from transformers.utils.import_utils import is_torch_fx_available
52
+ from .configuration_hunyuan import HunYuanConfig
53
+
54
+
55
+ if is_flash_attn_2_available():
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
58
+
59
+
60
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
61
+ # It means that the function will not be traced through and simply appear as a node in the graph.
62
+ if is_torch_fx_available():
63
+ if not is_torch_greater_or_equal_than_1_13:
64
+ import torch.fx
65
+
66
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
67
+
68
+
69
+ logger = logging.get_logger(__name__)
70
+
71
+ _CONFIG_FOR_DOC = "HunYuanConfig"
72
+
73
+
74
+ def topkgating(logits: Tensor, topk: int):
75
+ logits = logits.float()
76
+ gates = F.softmax(logits, dim=1)
77
+ expert_capacity = topk * gates.shape[0]
78
+ num_experts = int(gates.shape[1])
79
+ # Top-k router probability and corresponding expert indices for each token.
80
+ # Shape: [tokens_per_group, num_selected_experts].
81
+ expert_gate, expert_index = torch.topk(gates, topk)
82
+ expert_mask = F.one_hot(expert_index, num_experts)
83
+ # For a given token, determine if it was routed to a given expert.
84
+ # Shape: [tokens_per_group, num_experts]
85
+ expert_mask_aux = expert_mask.max(dim=-2)[0]
86
+ tokens_per_group_and_expert = torch.mean(expert_mask_aux.float(), dim=-2)
87
+ router_prob_per_group_and_expert = torch.mean(gates.float(), dim=-2)
88
+ l_aux = num_experts**2 * torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert)
89
+
90
+ gates_s = torch.clamp(
91
+ torch.matmul(expert_mask.float(), gates.unsqueeze(-1)).sum(dim=1), min=torch.finfo(gates.dtype).eps
92
+ )
93
+ router_probs = gates / gates_s
94
+ # Make num_selected_experts the leading axis to ensure that top-1 choices
95
+ # have priority over top-2 choices, which have priority over top-3 choices,
96
+ # etc.
97
+ expert_index = torch.transpose(expert_index, 0, 1)
98
+ # Shape: [num_selected_experts * tokens_per_group]
99
+ expert_index = expert_index.reshape(-1)
100
+
101
+ # Create mask out of indices.
102
+ # Shape: [tokens_per_group * num_selected_experts, num_experts].
103
+ expert_mask = F.one_hot(expert_index, num_experts).to(torch.int32)
104
+ exp_counts = torch.sum(expert_mask, dim=0).detach()
105
+
106
+ # Experts have a fixed capacity that we cannot exceed. A token's priority
107
+ # within the expert's buffer is given by the masked, cumulative capacity of
108
+ # its target expert.
109
+ # Shape: [tokens_per_group * num_selected_experts, num_experts].
110
+ token_priority = torch.cumsum(expert_mask, dim=0) * expert_mask - 1
111
+ # Shape: [num_selected_experts, tokens_per_group, num_experts].
112
+ token_priority = token_priority.reshape((topk, -1, num_experts))
113
+ # Shape: [tokens_per_group, num_selected_experts, num_experts].
114
+ token_priority = torch.transpose(token_priority, 0, 1)
115
+ # For each token, across all selected experts, select the only non-negative
116
+ # (unmasked) priority. Now, for group G routing to expert E, token T has
117
+ # non-negative priority (i.e. token_priority[G,T,E] >= 0) if and only if E
118
+ # is its targeted expert.
119
+ # Shape: [tokens_per_group, num_experts].
120
+ token_priority = torch.max(token_priority, dim=1)[0]
121
+
122
+ # Token T can only be routed to expert E if its priority is positive and
123
+ # less than the expert capacity. One-hot matrix will ignore indices outside
124
+ # the range [0, expert_capacity).
125
+ # Shape: [tokens_per_group, num_experts, expert_capacity].
126
+ valid_mask = torch.logical_and(token_priority >= 0, token_priority < expert_capacity)
127
+ token_priority = torch.masked_fill(token_priority, ~valid_mask, 0)
128
+ dispatch_mask = F.one_hot(token_priority, expert_capacity).to(torch.bool)
129
+ valid_mask = valid_mask.unsqueeze(-1).expand(-1, -1, expert_capacity)
130
+ dispatch_mask = torch.masked_fill(dispatch_mask, ~valid_mask, 0)
131
+
132
+ # The combine array will be used for combining expert outputs, scaled by the
133
+ # router probabilities. Shape: [num_groups, tokens_per_group, num_experts,
134
+ # expert_capacity].
135
+ combine_weights = torch.einsum("...te,...tec->...tec", router_probs, dispatch_mask)
136
+ exp_counts_capacity = torch.sum(dispatch_mask)
137
+ exp_capacity_rate = exp_counts_capacity / (logits.shape[0]*topk)
138
+
139
+ return [l_aux, exp_capacity_rate], combine_weights, dispatch_mask, exp_counts
140
+
141
+
142
+ def top1gating(logits: Tensor, random_routing_dropped_token: bool = False):
143
+ """Implements Top1Gating on logits."""
144
+ # everything is in fp32 in this function
145
+ logits = logits.float()
146
+ gates = F.softmax(logits, dim=1)
147
+ capacity = gates.shape[0]
148
+
149
+ # Create a mask for 1st's expert per token
150
+ # noisy gating
151
+ indices1_s = torch.argmax(gates, dim=1)
152
+ num_experts = int(gates.shape[1])
153
+ mask1 = F.one_hot(indices1_s, num_classes=num_experts)
154
+
155
+ # gating decisions
156
+ # exp_counts = torch.sum(mask1, dim=0).detach().to('cpu')
157
+ exp_counts = torch.sum(mask1, dim=0).detach()
158
+
159
+ # Compute l_aux
160
+ me = torch.mean(gates, dim=0)
161
+ ce = torch.mean(mask1.float(), dim=0)
162
+ l_aux = torch.sum(me * ce) * num_experts
163
+ mask1_rand = mask1
164
+
165
+ top_idx = torch.topk(mask1_rand, k=capacity, dim=0)[1]
166
+
167
+ new_mask1 = mask1 * torch.zeros_like(mask1).scatter_(0, top_idx, 1)
168
+ mask1 = new_mask1
169
+ mask1_bk = mask1
170
+ if random_routing_dropped_token:
171
+ not_full = capacity - new_mask1.sum(dim=0)
172
+ sorted_notfull, indices_notfull = torch.sort(not_full, descending=True)
173
+ sorted_notfull = sorted_notfull.to(torch.int64)
174
+ not_full_experts_ids = torch.repeat_interleave(indices_notfull, sorted_notfull)
175
+ shuffle_not_full_ids = torch.randperm(not_full_experts_ids.shape[0])
176
+ not_full_experts_ids = not_full_experts_ids[shuffle_not_full_ids]
177
+ indices1_s_after_drop = torch.argmax(new_mask1, dim=1)
178
+ # get drop idx
179
+ drop_mask = 1 - new_mask1.sum(dim=1)
180
+ drop_mask = drop_mask.bool()
181
+ drop_idx = drop_mask.nonzero().view(-1)
182
+ drop_num = drop_mask.sum().to(torch.int64)
183
+ indices1_s_after_drop.scatter_(0, drop_idx, not_full_experts_ids[:drop_num])
184
+ nodrop_mask1 = F.one_hot(indices1_s_after_drop, num_classes=num_experts)
185
+ mask1 = nodrop_mask1
186
+
187
+ # Compute locations in capacity buffer
188
+ locations1 = torch.cumsum(mask1, dim=0) - 1
189
+
190
+ # Store the capacity location for each token
191
+ locations1_s = torch.sum(locations1 * mask1, dim=1)
192
+
193
+ # Normalize gate probabilities
194
+ mask1_float = mask1.float()
195
+ gates = gates * mask1_float
196
+
197
+ locations1_sc = F.one_hot(locations1_s, num_classes=capacity).float() # one hot to float
198
+ combine_weights = torch.einsum("se,sc->sec", gates, locations1_sc)
199
+
200
+ dispatch_mask = combine_weights.bool()
201
+
202
+ exp_counts_capacity = torch.sum(mask1_bk)
203
+ exp_capacity_rate = exp_counts_capacity / (logits.shape[0])
204
+ return [l_aux, exp_capacity_rate], combine_weights, dispatch_mask, exp_counts
205
+
206
+
207
+ def _get_unpad_data(attention_mask):
208
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
209
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
210
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
211
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
212
+ return (
213
+ indices,
214
+ cu_seqlens,
215
+ max_seqlen_in_batch,
216
+ )
217
+
218
+
219
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
220
+ warnings.warn(
221
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be "
222
+ "removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
223
+ )
224
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
225
+
226
+
227
+ def _make_causal_mask(
228
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
229
+ ):
230
+ warnings.warn(
231
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in "
232
+ "v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
233
+ )
234
+ return AttentionMaskConverter._make_causal_mask(
235
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
236
+ )
237
+
238
+
239
+ class HunYuanRMSNorm(nn.Module):
240
+ def __init__(self, hidden_size, eps=1e-6):
241
+ """
242
+ HunYuanRMSNorm is equivalent to T5LayerNorm
243
+ """
244
+ super().__init__()
245
+ self.weight = nn.Parameter(torch.ones(hidden_size))
246
+ self.variance_epsilon = eps
247
+
248
+ def forward(self, hidden_states):
249
+ input_dtype = hidden_states.dtype
250
+ hidden_states = hidden_states.to(torch.float32)
251
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
252
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
253
+ return self.weight * hidden_states.to(input_dtype)
254
+
255
+
256
+ ALL_LAYERNORM_LAYERS.append(HunYuanRMSNorm)
257
+
258
+
259
+ class HunYuanRotaryEmbedding(nn.Module):
260
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
261
+ super().__init__()
262
+
263
+ self.dim = dim
264
+ self.max_position_embeddings = max_position_embeddings
265
+ self.base = base
266
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
267
+ # inv_freq = inv_freq.bfloat16()
268
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
269
+
270
+ # Build here to make `torch.jit.trace` work.
271
+ self._set_cos_sin_cache(
272
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
273
+ )
274
+
275
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
276
+ self.max_seq_len_cached = seq_len
277
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
278
+
279
+ self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
280
+ freqs = torch.outer(t, self.inv_freq)
281
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
282
+ emb = torch.cat((freqs, freqs), dim=-1).float()
283
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
284
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
285
+
286
+ def forward(self, x, seq_len=None):
287
+ # x: [bs, num_attention_heads, seq_len, head_size]
288
+ if seq_len > self.max_seq_len_cached or self.inv_freq.dtype != torch.float32:
289
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
290
+
291
+ return (
292
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
293
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
294
+ )
295
+
296
+
297
+ class HunYuanLinearScalingRotaryEmbedding(HunYuanRotaryEmbedding):
298
+ """HunYuanRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
299
+
300
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
301
+ self.scaling_factor = scaling_factor
302
+ super().__init__(dim, max_position_embeddings, base, device)
303
+
304
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
305
+ self.max_seq_len_cached = seq_len
306
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
307
+ t = t / self.scaling_factor
308
+
309
+ freqs = torch.outer(t, self.inv_freq)
310
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
311
+ emb = torch.cat((freqs, freqs), dim=-1)
312
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
313
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
314
+
315
+
316
+ class HunYuanDynamicNTKScalingRotaryEmbedding(HunYuanRotaryEmbedding):
317
+ """
318
+ HunYuanRotaryEmbedding extended with Dynamic NTK scaling.
319
+ Credits to the Reddit users /u/bloc97 and /u/emozilla
320
+ """
321
+
322
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
323
+ self.scaling_factor = scaling_factor
324
+ super().__init__(dim, max_position_embeddings, base, device)
325
+
326
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
327
+ self.max_seq_len_cached = seq_len
328
+
329
+ if seq_len > self.max_position_embeddings:
330
+ base = self.base * (
331
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
332
+ ) ** (self.dim / (self.dim - 2))
333
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
334
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
335
+
336
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
337
+
338
+ freqs = torch.outer(t, self.inv_freq)
339
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
340
+ emb = torch.cat((freqs, freqs), dim=-1)
341
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
342
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
343
+
344
+
345
+ class HunYuanDynamicNTKAlphaRotaryEmbedding(HunYuanRotaryEmbedding):
346
+ """
347
+ HunYuanRotaryEmbedding extended with Dynamic NTK scaling.
348
+ Credits to the Reddit users /u/bloc97 and /u/emozilla
349
+ """
350
+
351
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_alpha=1.0):
352
+ self.scaling_alpha = scaling_alpha
353
+ super().__init__(dim, max_position_embeddings, base, device)
354
+
355
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
356
+ self.max_seq_len_cached = seq_len
357
+ base = self.base * self.scaling_alpha ** (self.dim / (self.dim-2))
358
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
359
+
360
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
361
+
362
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
363
+
364
+ freqs = torch.outer(t, self.inv_freq)
365
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
366
+ emb = torch.cat((freqs, freqs), dim=-1)
367
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
368
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
369
+
370
+
371
+ def rotate_half(x):
372
+ """Rotates half the hidden dims of the input."""
373
+ x1 = x[..., : x.shape[-1] // 2]
374
+ x2 = x[..., x.shape[-1] // 2:]
375
+ return torch.cat((-x2, x1), dim=-1)
376
+
377
+
378
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
379
+ """Applies Rotary Position Embedding to the query and key tensors.
380
+
381
+ Args:
382
+ q (`torch.Tensor`): The query tensor.
383
+ k (`torch.Tensor`): The key tensor.
384
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
385
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
386
+ position_ids (`torch.Tensor`):
387
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
388
+ used to pass offsetted position ids when working with a KV-cache.
389
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
390
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
391
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
392
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
393
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
394
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
395
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
396
+ Returns:
397
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
398
+ """
399
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
400
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
401
+ q_embed = (q * cos) + (rotate_half(q) * sin)
402
+ k_embed = (k * cos) + (rotate_half(k) * sin)
403
+ return q_embed, k_embed
404
+
405
+
406
+ class HunYuanMLP(nn.Module):
407
+ def __init__(self, config: HunYuanConfig, layer_idx=None, is_shared_mlp=False):
408
+ super().__init__()
409
+ self.config = config
410
+ self.layer_idx = layer_idx
411
+ self.hidden_size = config.hidden_size
412
+ if is_shared_mlp:
413
+ self.intermediate_size = config.intermediate_size * config.num_shared_expert[0]
414
+ else:
415
+ self.intermediate_size = config.intermediate_size
416
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
417
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
418
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
419
+ self.act_fn = ACT2FN[config.hidden_act]
420
+
421
+ def forward(self, x):
422
+ if self.config.pretraining_tp > 1:
423
+ slice = self.intermediate_size // self.config.pretraining_tp
424
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
425
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
426
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
427
+
428
+ gate_proj = torch.cat(
429
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
430
+ )
431
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
432
+
433
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
434
+ down_proj = [
435
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
436
+ ]
437
+ down_proj = sum(down_proj)
438
+ else:
439
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
440
+
441
+ return down_proj
442
+
443
+
444
+ class HunYuanTopKGate(nn.Module):
445
+ def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):
446
+ super().__init__()
447
+ self.config = config
448
+ self.layer_idx = layer_idx
449
+ self.moe_topk = config.moe_topk
450
+ self.drop_tokens = config.moe_drop_tokens
451
+ self.min_capacity = 8
452
+ self.random_routing_dropped_token = config.moe_random_routing_dropped_token
453
+ self.wg = nn.Linear(config.hidden_size, config.num_experts, bias=False, dtype=torch.float32)
454
+
455
+ def forward(self, hidden_states):
456
+ bsz, seq_len, hidden_size = hidden_states.shape
457
+ hidden_states = hidden_states.reshape(-1, hidden_size)
458
+ if self.wg.weight.dtype == torch.float32:
459
+ hidden_states = hidden_states.float()
460
+ logits = self.wg(hidden_states)
461
+ if self.moe_topk == 1:
462
+ gate_output = top1gating(logits, random_routing_dropped_token=self.random_routing_dropped_token)
463
+ else:
464
+ gate_output = topkgating(logits, self.moe_topk[0])
465
+
466
+ return gate_output
467
+
468
+
469
+ class HunYuanMoE(nn.Module):
470
+ def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):
471
+ super().__init__()
472
+ self.config = config
473
+ self.layer_idx = layer_idx
474
+ self.moe_topk = config.moe_topk
475
+ self.num_experts = config.num_experts
476
+ if config.use_mixed_mlp_moe:
477
+ self.shared_mlp = HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=True)
478
+ self.gate = HunYuanTopKGate(config, layer_idx=layer_idx)
479
+ self.experts = nn.ModuleList(
480
+ [HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=False) for _ in range(config.num_experts)]
481
+ )
482
+
483
+ def forward(self, hidden_states):
484
+ bsz, seq_len, hidden_size = hidden_states.shape
485
+
486
+ if self.config.use_mixed_mlp_moe:
487
+ hidden_states_mlp = self.shared_mlp(hidden_states)
488
+
489
+ l_moe, combine_weights, dispatch_mask, exp_counts = self.gate(hidden_states)
490
+
491
+ reshaped_input = hidden_states.reshape(-1, hidden_size)
492
+
493
+ dispatched_input = torch.einsum("sec,sm->ecm", dispatch_mask.type_as(hidden_states), reshaped_input)
494
+
495
+ chunks = dispatched_input.chunk(self.num_experts, dim=0)
496
+ expert_outputs = []
497
+ for chunk, expert in zip(chunks, self.experts):
498
+ expert_outputs.append(expert(chunk))
499
+
500
+ expert_output = torch.cat(expert_outputs, dim=0)
501
+ combined_output = torch.einsum("sec,ecm->sm", combine_weights.type_as(hidden_states), expert_output)
502
+ combined_output = combined_output.reshape(bsz, seq_len, hidden_size)
503
+
504
+ if self.config.use_mixed_mlp_moe:
505
+ output = hidden_states_mlp + combined_output
506
+ else:
507
+ output = combined_output
508
+
509
+ return output
510
+
511
+
512
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
513
+ """
514
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
515
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
516
+ """
517
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
518
+ if n_rep == 1:
519
+ return hidden_states
520
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
521
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
522
+
523
+
524
+ class HunYuanAttention(nn.Module):
525
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
526
+
527
+ def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):
528
+ super().__init__()
529
+ self.config = config
530
+ self.layer_idx = layer_idx
531
+ # layer_idx 从 0 开始
532
+ self.attention_type = 'cross' if config.use_cla and layer_idx % config.cla_share_factor != 0 else 'self'
533
+ if layer_idx is None:
534
+ logger.warning_once(
535
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
536
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
537
+ "when creating this class."
538
+ )
539
+
540
+ self.attention_dropout = config.attention_dropout
541
+ self.hidden_size = config.hidden_size
542
+ self.num_heads = config.num_attention_heads
543
+ self.head_dim = self.hidden_size // self.num_heads
544
+ self.num_key_value_heads = config.num_key_value_heads
545
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
546
+ self.max_position_embeddings = config.max_position_embeddings
547
+ self.rope_theta = config.rope_theta
548
+ self.is_causal = True
549
+ self.use_qk_norm = config.use_qk_norm
550
+
551
+ if (self.head_dim * self.num_heads) != self.hidden_size:
552
+ raise ValueError(
553
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
554
+ f" and `num_heads`: {self.num_heads})."
555
+ )
556
+
557
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
558
+ if self.attention_type == 'self':
559
+ self.k_proj = nn.Linear(
560
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
561
+ )
562
+ self.v_proj = nn.Linear(
563
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
564
+ )
565
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
566
+ if self.use_qk_norm:
567
+ self.query_layernorm = HunYuanRMSNorm(self.head_dim, eps=config.rms_norm_eps)
568
+ self.key_layernorm = HunYuanRMSNorm(self.head_dim, eps=config.rms_norm_eps)
569
+ self._init_rope()
570
+
571
+ def _init_rope(self):
572
+ if self.config.rope_scaling is None:
573
+ self.rotary_emb = HunYuanRotaryEmbedding(
574
+ self.head_dim,
575
+ max_position_embeddings=self.max_position_embeddings,
576
+ base=self.rope_theta,
577
+ )
578
+ else:
579
+ scaling_type = self.config.rope_scaling["type"]
580
+ scaling_factor = self.config.rope_scaling["factor"]
581
+ scaling_alpha = self.config.rope_scaling["alpha"]
582
+ if scaling_type == "linear":
583
+ self.rotary_emb = HunYuanLinearScalingRotaryEmbedding(
584
+ self.head_dim,
585
+ max_position_embeddings=self.max_position_embeddings,
586
+ scaling_factor=scaling_factor,
587
+ base=self.rope_theta,
588
+ )
589
+ elif scaling_type == "dynamic":
590
+ if scaling_alpha:
591
+ self.rotary_emb = HunYuanDynamicNTKAlphaRotaryEmbedding(
592
+ self.head_dim,
593
+ max_position_embeddings=self.max_position_embeddings,
594
+ scaling_alpha=scaling_alpha,
595
+ base=self.rope_theta,
596
+ )
597
+ else:
598
+ self.rotary_emb = HunYuanDynamicNTKScalingRotaryEmbedding(
599
+ self.head_dim,
600
+ max_position_embeddings=self.max_position_embeddings,
601
+ scaling_factor=scaling_factor,
602
+ base=self.rope_theta,
603
+ )
604
+ else:
605
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
606
+
607
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
608
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
609
+
610
+ def forward(
611
+ self,
612
+ hidden_states: torch.Tensor,
613
+ attention_mask: Optional[torch.Tensor] = None,
614
+ position_ids: Optional[torch.LongTensor] = None,
615
+ past_key_value: Optional[Cache] = None,
616
+ output_attentions: bool = False,
617
+ use_cache: bool = False,
618
+ kv_states: torch.Tensor = None,
619
+ **kwargs,
620
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
621
+ if "padding_mask" in kwargs:
622
+ warnings.warn(
623
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use "
624
+ "`attention_mask` instead.`"
625
+ )
626
+
627
+ bsz, q_len, _ = hidden_states.size()
628
+
629
+ if self.config.pretraining_tp > 1:
630
+ query_slices = self.q_proj.weight.split(
631
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
632
+ )
633
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
634
+ query_states = torch.cat(query_states, dim=-1)
635
+
636
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
637
+ orig_key_states, orig_value_states = kv_states
638
+ key_states, value_states = kv_states
639
+ else:
640
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
641
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
642
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
643
+
644
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
645
+ key_states = torch.cat(key_states, dim=-1)
646
+
647
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
648
+ value_states = torch.cat(value_states, dim=-1)
649
+ orig_key_states, orig_value_states = key_states, value_states
650
+
651
+ else:
652
+ query_states = self.q_proj(hidden_states)
653
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
654
+ orig_key_states, orig_value_states = kv_states
655
+ key_states, value_states = kv_states
656
+ else:
657
+ key_states = self.k_proj(hidden_states)
658
+ value_states = self.v_proj(hidden_states)
659
+ orig_key_states, orig_value_states = key_states, value_states
660
+
661
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
662
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
663
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
664
+
665
+ kv_seq_len = key_states.shape[-2]
666
+ if past_key_value is not None:
667
+ if self.layer_idx is None:
668
+ raise ValueError(
669
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
670
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
671
+ "with a layer index."
672
+ )
673
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
674
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
675
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
676
+
677
+ if self.use_qk_norm:
678
+ query_states = self.query_layernorm(query_states)
679
+ key_states = self.key_layernorm(key_states)
680
+
681
+ if past_key_value is not None:
682
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
683
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
684
+
685
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
686
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
687
+
688
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
689
+
690
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
691
+ raise ValueError(
692
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
693
+ f" {attn_weights.size()}"
694
+ )
695
+
696
+ if attention_mask is not None:
697
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
698
+ raise ValueError(
699
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
700
+ )
701
+ attn_weights = attn_weights + attention_mask
702
+
703
+ # upcast attention to fp32
704
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
705
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
706
+ attn_output = torch.matmul(attn_weights, value_states)
707
+
708
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
709
+ raise ValueError(
710
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
711
+ f" {attn_output.size()}"
712
+ )
713
+
714
+ attn_output = attn_output.transpose(1, 2).contiguous()
715
+
716
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
717
+
718
+ if self.config.pretraining_tp > 1:
719
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
720
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
721
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
722
+ else:
723
+ attn_output = self.o_proj(attn_output)
724
+
725
+ if not output_attentions:
726
+ attn_weights = None
727
+
728
+ return attn_output, attn_weights, past_key_value, (orig_key_states, orig_value_states)
729
+
730
+
731
+ class HunYuanFlashAttention2(HunYuanAttention):
732
+ """
733
+ HunYuan flash attention module. This module inherits from `HunYuanAttention` as the weights of the module stays
734
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
735
+ flash attention and deal with padding tokens in case the input contains any of them.
736
+ """
737
+
738
+ def __init__(self, *args, **kwargs):
739
+ super().__init__(*args, **kwargs)
740
+
741
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
742
+
743
+ def forward(
744
+ self,
745
+ hidden_states: torch.Tensor,
746
+ attention_mask: Optional[torch.LongTensor] = None,
747
+ position_ids: Optional[torch.LongTensor] = None,
748
+ past_key_value: Optional[Cache] = None,
749
+ output_attentions: bool = False,
750
+ use_cache: bool = False,
751
+ kv_states: torch.Tensor = None,
752
+ **kwargs,
753
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
754
+ # HunYuanFlashAttention2 attention does not support output_attentions
755
+ if "padding_mask" in kwargs:
756
+ warnings.warn(
757
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use "
758
+ "`attention_mask` instead.`"
759
+ )
760
+
761
+ # overwrite attention_mask with padding_mask
762
+ attention_mask = kwargs.pop("padding_mask")
763
+
764
+ bsz, q_len, _ = hidden_states.size()
765
+
766
+ query_states = self.q_proj(hidden_states)
767
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
768
+ orig_key_states, orig_value_states = kv_states
769
+ key_states, value_states = kv_states
770
+ else:
771
+ key_states = self.k_proj(hidden_states)
772
+ value_states = self.v_proj(hidden_states)
773
+ orig_key_states, orig_value_states = key_states, value_states
774
+
775
+ # Flash attention requires the input to have the shape
776
+ # batch_size x seq_length x head_dim x hidden_dim
777
+ # therefore we just need to keep the original shape
778
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
779
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
780
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
781
+
782
+ kv_seq_len = key_states.shape[-2]
783
+ if past_key_value is not None:
784
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
785
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
786
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
787
+
788
+ if self.use_qk_norm:
789
+ query_states = self.query_layernorm(query_states)
790
+ key_states = self.key_layernorm(key_states)
791
+
792
+ if past_key_value is not None:
793
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
794
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
795
+
796
+ query_states = query_states.transpose(1, 2)
797
+ key_states = key_states.transpose(1, 2)
798
+ value_states = value_states.transpose(1, 2)
799
+
800
+ dropout_rate = self.attention_dropout if self.training else 0.0
801
+
802
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
803
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
804
+ # cast them back in the correct dtype just to be sure everything works as expected.
805
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
806
+ # in fp32. (HunYuanRMSNorm handles it correctly)
807
+
808
+ input_dtype = query_states.dtype
809
+ if input_dtype == torch.float32:
810
+ # Handle the case where the model is quantized
811
+ if hasattr(self.config, "_pre_quantization_dtype"):
812
+ target_dtype = self.config._pre_quantization_dtype
813
+ else:
814
+ target_dtype = self.q_proj.weight.dtype
815
+
816
+ logger.warning_once(
817
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
818
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
819
+ f" {target_dtype}."
820
+ )
821
+
822
+ query_states = query_states.to(target_dtype)
823
+ key_states = key_states.to(target_dtype)
824
+ value_states = value_states.to(target_dtype)
825
+
826
+ attn_output = self._flash_attention_forward(
827
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
828
+ )
829
+
830
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
831
+ attn_output = self.o_proj(attn_output)
832
+
833
+ return attn_output, None, past_key_value, (orig_key_states, orig_value_states)
834
+
835
+ def _flash_attention_forward(
836
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
837
+ ):
838
+ """
839
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
840
+ first unpad the input, then computes the attention scores and pad the final attention scores.
841
+
842
+ Args:
843
+ query_states (`torch.Tensor`):
844
+ Input query states to be passed to Flash Attention API
845
+ key_states (`torch.Tensor`):
846
+ Input key states to be passed to Flash Attention API
847
+ value_states (`torch.Tensor`):
848
+ Input value states to be passed to Flash Attention API
849
+ attention_mask (`torch.Tensor`):
850
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
851
+ position of padding tokens and 1 for the position of non-padding tokens.
852
+ dropout (`int`, *optional*):
853
+ Attention dropout
854
+ softmax_scale (`float`, *optional*):
855
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
856
+ """
857
+ if not self._flash_attn_uses_top_left_mask:
858
+ causal = self.is_causal
859
+ else:
860
+ causal = self.is_causal and query_length != 1
861
+
862
+ # Contains at least one padding token in the sequence
863
+ if attention_mask is not None:
864
+ batch_size = query_states.shape[0]
865
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
866
+ query_states, key_states, value_states, attention_mask, query_length
867
+ )
868
+
869
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
870
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
871
+
872
+ attn_output_unpad = flash_attn_varlen_func(
873
+ query_states,
874
+ key_states,
875
+ value_states,
876
+ cu_seqlens_q=cu_seqlens_q,
877
+ cu_seqlens_k=cu_seqlens_k,
878
+ max_seqlen_q=max_seqlen_in_batch_q,
879
+ max_seqlen_k=max_seqlen_in_batch_k,
880
+ dropout_p=dropout,
881
+ softmax_scale=softmax_scale,
882
+ causal=causal,
883
+ )
884
+
885
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
886
+ else:
887
+ attn_output = flash_attn_func(
888
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
889
+ )
890
+
891
+ return attn_output
892
+
893
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
894
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
895
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
896
+
897
+ key_layer = index_first_axis(
898
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
899
+ )
900
+ value_layer = index_first_axis(
901
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
902
+ )
903
+ if query_length == kv_seq_len:
904
+ query_layer = index_first_axis(
905
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
906
+ )
907
+ cu_seqlens_q = cu_seqlens_k
908
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
909
+ indices_q = indices_k
910
+ elif query_length == 1:
911
+ max_seqlen_in_batch_q = 1
912
+ cu_seqlens_q = torch.arange(
913
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
914
+ ) # There is a memcpy here, that is very bad.
915
+ indices_q = cu_seqlens_q[:-1]
916
+ query_layer = query_layer.squeeze(1)
917
+ else:
918
+ # The -q_len: slice assumes left padding.
919
+ attention_mask = attention_mask[:, -query_length:]
920
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
921
+
922
+ return (
923
+ query_layer,
924
+ key_layer,
925
+ value_layer,
926
+ indices_q,
927
+ (cu_seqlens_q, cu_seqlens_k),
928
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
929
+ )
930
+
931
+
932
+ class HunYuanSdpaAttention(HunYuanAttention):
933
+ """
934
+ HunYuan attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
935
+ `HunYuanAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt
936
+ to SDPA API.
937
+ """
938
+
939
+ # Adapted from HunYuanAttention.forward
940
+ def forward(
941
+ self,
942
+ hidden_states: torch.Tensor,
943
+ attention_mask: Optional[torch.Tensor] = None,
944
+ position_ids: Optional[torch.LongTensor] = None,
945
+ past_key_value: Optional[Cache] = None,
946
+ output_attentions: bool = False,
947
+ use_cache: bool = False,
948
+ kv_states: torch.Tensor = None,
949
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
950
+ if output_attentions:
951
+ logger.warning_once(
952
+ 'HunYuanModel is using HunYuanSdpaAttention,'
953
+ 'but `torch.nn.functional.scaled_dot_product_attention`'
954
+ 'does not support `output_attentions=True`. Falling back to the manual attention implementation, '
955
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. '
956
+ 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
957
+ )
958
+ return super().forward(
959
+ hidden_states=hidden_states,
960
+ attention_mask=attention_mask,
961
+ position_ids=position_ids,
962
+ past_key_value=past_key_value,
963
+ output_attentions=output_attentions,
964
+ use_cache=use_cache,
965
+ )
966
+
967
+ bsz, q_len, _ = hidden_states.size()
968
+
969
+ query_states = self.q_proj(hidden_states)
970
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
971
+ orig_key_states, orig_value_states = kv_states
972
+ key_states, value_states = kv_states
973
+ else:
974
+ key_states = self.k_proj(hidden_states)
975
+ value_states = self.v_proj(hidden_states)
976
+ orig_key_states, orig_value_states = key_states, value_states
977
+
978
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
979
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
980
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
981
+
982
+ kv_seq_len = key_states.shape[-2]
983
+ if past_key_value is not None:
984
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
985
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
986
+
987
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
988
+
989
+ if self.use_qk_norm:
990
+ query_states = self.query_layernorm(query_states)
991
+ key_states = self.key_layernorm(key_states)
992
+
993
+ if past_key_value is not None:
994
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
995
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
996
+
997
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
998
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
999
+
1000
+ if attention_mask is not None:
1001
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1002
+ raise ValueError(
1003
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1004
+ )
1005
+
1006
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with
1007
+ # custom attn_mask,
1008
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1009
+ if query_states.device.type == "cuda" and attention_mask is not None:
1010
+ query_states = query_states.contiguous()
1011
+ key_states = key_states.contiguous()
1012
+ value_states = value_states.contiguous()
1013
+
1014
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1015
+ query_states,
1016
+ key_states,
1017
+ value_states,
1018
+ attn_mask=attention_mask,
1019
+ dropout_p=self.attention_dropout if self.training else 0.0,
1020
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a
1021
+ # causal mask in case q_len == 1.
1022
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1023
+ )
1024
+
1025
+ attn_output = attn_output.transpose(1, 2).contiguous()
1026
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
1027
+
1028
+ attn_output = self.o_proj(attn_output)
1029
+
1030
+ return attn_output, None, past_key_value, (orig_key_states, orig_value_states)
1031
+
1032
+
1033
+ HUNYUAN_ATTENTION_CLASSES = {
1034
+ "eager": HunYuanAttention,
1035
+ "flash_attention_2": HunYuanFlashAttention2,
1036
+ "sdpa": HunYuanSdpaAttention,
1037
+ }
1038
+
1039
+
1040
+ class HunYuanDecoderLayer(nn.Module):
1041
+ def __init__(self, config: HunYuanConfig, layer_idx: int):
1042
+ super().__init__()
1043
+ self.hidden_size = config.hidden_size
1044
+ self.layer_idx = layer_idx
1045
+
1046
+ self.self_attn = HUNYUAN_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
1047
+
1048
+ if config.num_experts > 1:
1049
+ self.mlp = HunYuanMoE(config, layer_idx=layer_idx)
1050
+ else:
1051
+ self.mlp = HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=False)
1052
+ self.input_layernorm = HunYuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1053
+ self.post_attention_layernorm = HunYuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1054
+
1055
+ def forward(
1056
+ self,
1057
+ hidden_states: torch.Tensor,
1058
+ attention_mask: Optional[torch.Tensor] = None,
1059
+ position_ids: Optional[torch.LongTensor] = None,
1060
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1061
+ output_attentions: Optional[bool] = False,
1062
+ use_cache: Optional[bool] = False,
1063
+ kv_states: Optional[Tuple[torch.Tensor]] = None,
1064
+ **kwargs,
1065
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1066
+ """
1067
+ Args:
1068
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1069
+ attention_mask (`torch.FloatTensor`, *optional*):
1070
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1071
+ query_sequence_length, key_sequence_length)` if default attention is used.
1072
+ output_attentions (`bool`, *optional*):
1073
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1074
+ returned tensors for more detail.
1075
+ use_cache (`bool`, *optional*):
1076
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1077
+ (see `past_key_values`).
1078
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1079
+ kv_states (`Tuple(torch.FloatTensor)`, *optional*): Used when CLA is enabled,
1080
+ key and value states from past attention blocks
1081
+ """
1082
+ if "padding_mask" in kwargs:
1083
+ warnings.warn(
1084
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use "
1085
+ "`attention_mask` instead.`"
1086
+ )
1087
+
1088
+ residual = hidden_states
1089
+
1090
+ hidden_states = self.input_layernorm(hidden_states)
1091
+
1092
+ # Self Attention
1093
+ hidden_states, self_attn_weights, present_key_value, kv_states = self.self_attn(
1094
+ hidden_states=hidden_states,
1095
+ attention_mask=attention_mask,
1096
+ position_ids=position_ids,
1097
+ past_key_value=past_key_value,
1098
+ output_attentions=output_attentions,
1099
+ use_cache=use_cache,
1100
+ kv_states=kv_states,
1101
+ **kwargs,
1102
+ )
1103
+ hidden_states = residual + hidden_states
1104
+
1105
+ # Fully Connected
1106
+ residual = hidden_states
1107
+ hidden_states = self.post_attention_layernorm(hidden_states)
1108
+ hidden_states = self.mlp(hidden_states)
1109
+ hidden_states = residual + hidden_states
1110
+
1111
+ outputs = (hidden_states,)
1112
+
1113
+ if output_attentions:
1114
+ outputs += (self_attn_weights,)
1115
+
1116
+ if use_cache:
1117
+ outputs += (present_key_value,)
1118
+
1119
+ outputs += (kv_states,)
1120
+
1121
+ return outputs
1122
+
1123
+
1124
+ HUNYUAN_START_DOCSTRING = r"""
1125
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1126
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1127
+ etc.)
1128
+
1129
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1130
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1131
+ and behavior.
1132
+
1133
+ Parameters:
1134
+ config ([`HunYuanConfig`]):
1135
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1136
+ load the weights associated with the model, only the configuration. Check out the
1137
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1138
+ """
1139
+
1140
+
1141
+ @add_start_docstrings(
1142
+ "The bare HunYuan Model outputting raw hidden-states without any specific head on top.",
1143
+ HUNYUAN_START_DOCSTRING,
1144
+ )
1145
+ class HunYuanPreTrainedModel(PreTrainedModel):
1146
+ config_class = HunYuanConfig
1147
+ base_model_prefix = "model"
1148
+ supports_gradient_checkpointing = True
1149
+ _no_split_modules = ["HunYuanDecoderLayer"]
1150
+ _skip_keys_device_placement = "past_key_values"
1151
+ _supports_flash_attn_2 = True
1152
+ _supports_sdpa = True
1153
+ _supports_cache_class = True
1154
+
1155
+ def _init_weights(self, module):
1156
+ std = self.config.initializer_range
1157
+ if isinstance(module, nn.Linear):
1158
+ module.weight.data.normal_(mean=0.0, std=std)
1159
+ if module.bias is not None:
1160
+ module.bias.data.zero_()
1161
+ elif isinstance(module, nn.Embedding):
1162
+ module.weight.data.normal_(mean=0.0, std=std)
1163
+ if module.padding_idx is not None:
1164
+ module.weight.data[module.padding_idx].zero_()
1165
+
1166
+
1167
+ HUNYUAN_INPUTS_DOCSTRING = r"""
1168
+ Args:
1169
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1170
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1171
+ it.
1172
+
1173
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1174
+ [`PreTrainedTokenizer.__call__`] for details.
1175
+
1176
+ [What are input IDs?](../glossary#input-ids)
1177
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1178
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1179
+
1180
+ - 1 for tokens that are **not masked**,
1181
+ - 0 for tokens that are **masked**.
1182
+
1183
+ [What are attention masks?](../glossary#attention-mask)
1184
+
1185
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1186
+ [`PreTrainedTokenizer.__call__`] for details.
1187
+
1188
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1189
+ `past_key_values`).
1190
+
1191
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1192
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1193
+ information on the default strategy.
1194
+
1195
+ - 1 indicates the head is **not masked**,
1196
+ - 0 indicates the head is **masked**.
1197
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1198
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1199
+ config.n_positions - 1]`.
1200
+
1201
+ [What are position IDs?](../glossary#position-ids)
1202
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1203
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1204
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1205
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1206
+
1207
+ Two formats are allowed:
1208
+ - a [`~cache_utils.Cache`] instance;
1209
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1210
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1211
+ cache format.
1212
+
1213
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1214
+ legacy cache format will be returned.
1215
+
1216
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1217
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1218
+ of shape `(batch_size, sequence_length)`.
1219
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1220
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1221
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1222
+ model's internal embedding lookup matrix.
1223
+ use_cache (`bool`, *optional*):
1224
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1225
+ `past_key_values`).
1226
+ output_attentions (`bool`, *optional*):
1227
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1228
+ tensors for more detail.
1229
+ output_hidden_states (`bool`, *optional*):
1230
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1231
+ more detail.
1232
+ return_dict (`bool`, *optional*):
1233
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1234
+ """
1235
+
1236
+
1237
+ @add_start_docstrings(
1238
+ "The bare HunYuan Model outputting raw hidden-states without any specific head on top.",
1239
+ HUNYUAN_START_DOCSTRING,
1240
+ )
1241
+ class HunYuanModel(HunYuanPreTrainedModel):
1242
+ """
1243
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`HunYuanDecoderLayer`]
1244
+
1245
+ Args:
1246
+ config: HunYuanConfig
1247
+ """
1248
+
1249
+ def __init__(self, config: HunYuanConfig):
1250
+ super().__init__(config)
1251
+ self.padding_idx = config.pad_token_id
1252
+ self.vocab_size = config.vocab_size
1253
+
1254
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1255
+ self.layers = nn.ModuleList(
1256
+ [HunYuanDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1257
+ )
1258
+ self._use_sdpa = config._attn_implementation == "sdpa"
1259
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1260
+ self.norm = HunYuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1261
+
1262
+ self.cla = config.use_cla
1263
+ self.cla_share_factor = config.cla_share_factor
1264
+
1265
+ self.gradient_checkpointing = False
1266
+ # Initialize weights and apply final processing
1267
+ self.post_init()
1268
+
1269
+ def get_input_embeddings(self):
1270
+ return self.embed_tokens
1271
+
1272
+ def set_input_embeddings(self, value):
1273
+ self.embed_tokens = value
1274
+
1275
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
1276
+ def forward(
1277
+ self,
1278
+ input_ids: torch.LongTensor = None,
1279
+ attention_mask: Optional[torch.Tensor] = None,
1280
+ position_ids: Optional[torch.LongTensor] = None,
1281
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1282
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1283
+ use_cache: Optional[bool] = None,
1284
+ output_attentions: Optional[bool] = None,
1285
+ output_hidden_states: Optional[bool] = None,
1286
+ return_dict: Optional[bool] = None,
1287
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1288
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1289
+ output_hidden_states = (
1290
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1291
+ )
1292
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1293
+
1294
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1295
+
1296
+ # retrieve input_ids and inputs_embeds
1297
+ if input_ids is not None and inputs_embeds is not None:
1298
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1299
+ elif input_ids is not None:
1300
+ batch_size, seq_length = input_ids.shape[:2]
1301
+ elif inputs_embeds is not None:
1302
+ batch_size, seq_length = inputs_embeds.shape[:2]
1303
+ else:
1304
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1305
+
1306
+ if self.gradient_checkpointing and self.training:
1307
+ if use_cache:
1308
+ logger.warning_once(
1309
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1310
+ )
1311
+ use_cache = False
1312
+
1313
+ past_key_values_length = 0
1314
+ if use_cache:
1315
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1316
+ if use_legacy_cache:
1317
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1318
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1319
+
1320
+ if position_ids is None:
1321
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1322
+ position_ids = torch.arange(
1323
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1324
+ )
1325
+ position_ids = position_ids.unsqueeze(0)
1326
+
1327
+ if inputs_embeds is None:
1328
+ inputs_embeds = self.embed_tokens(input_ids)
1329
+
1330
+ # Fix lora with gradient checkpointing training
1331
+ if self.training and inputs_embeds.is_leaf:
1332
+ inputs_embeds.requires_grad = True
1333
+
1334
+ if self._use_flash_attention_2:
1335
+ # 2d mask is passed through the layers
1336
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1337
+ elif self._use_sdpa and not output_attentions:
1338
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1339
+ # the manual implementation that requires a 4D causal mask in all cases.
1340
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1341
+ attention_mask,
1342
+ (batch_size, seq_length),
1343
+ inputs_embeds,
1344
+ past_key_values_length,
1345
+ )
1346
+ else:
1347
+ # 4d mask is passed through the layers
1348
+ attention_mask = _prepare_4d_causal_attention_mask(
1349
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1350
+ )
1351
+
1352
+ # embed positions
1353
+ hidden_states = inputs_embeds
1354
+
1355
+ # decoder layers
1356
+ all_hidden_states = () if output_hidden_states else None
1357
+ all_self_attns = () if output_attentions else None
1358
+ next_decoder_cache = None
1359
+
1360
+ prev_kv_states = None
1361
+ for layer_idx, decoder_layer in enumerate(self.layers):
1362
+ if output_hidden_states:
1363
+ all_hidden_states += (hidden_states,)
1364
+
1365
+ if self.gradient_checkpointing and self.training:
1366
+ layer_outputs = self._gradient_checkpointing_func(
1367
+ decoder_layer.__call__,
1368
+ hidden_states,
1369
+ attention_mask,
1370
+ position_ids,
1371
+ past_key_values,
1372
+ output_attentions,
1373
+ use_cache,
1374
+ prev_kv_states,
1375
+ )
1376
+ else:
1377
+ layer_outputs = decoder_layer(
1378
+ hidden_states,
1379
+ attention_mask=attention_mask,
1380
+ position_ids=position_ids,
1381
+ past_key_value=past_key_values,
1382
+ output_attentions=output_attentions,
1383
+ use_cache=use_cache,
1384
+ kv_states=prev_kv_states
1385
+ )
1386
+
1387
+ hidden_states = layer_outputs[0]
1388
+
1389
+ if use_cache:
1390
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1391
+
1392
+ if output_attentions:
1393
+ all_self_attns += (layer_outputs[1],)
1394
+
1395
+ kv_states = layer_outputs[-1]
1396
+
1397
+ if self.cla and layer_idx % self.cla_share_factor == 0:
1398
+ prev_kv_states = kv_states
1399
+
1400
+ hidden_states = self.norm(hidden_states)
1401
+
1402
+ # add hidden states from the last decoder layer
1403
+ if output_hidden_states:
1404
+ all_hidden_states += (hidden_states,)
1405
+
1406
+ next_cache = None
1407
+ if use_cache:
1408
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1409
+ if not return_dict:
1410
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1411
+ return BaseModelOutputWithPast(
1412
+ last_hidden_state=hidden_states,
1413
+ past_key_values=next_cache,
1414
+ hidden_states=all_hidden_states,
1415
+ attentions=all_self_attns,
1416
+ )
1417
+
1418
+
1419
+ class HunYuanMoEV1ForCausalLM(HunYuanPreTrainedModel):
1420
+ _tied_weights_keys = ["lm_head.weight"]
1421
+
1422
+ def __init__(self, config: HunYuanConfig):
1423
+ super().__init__(config)
1424
+ self.model = HunYuanModel(config)
1425
+ self.vocab_size = config.vocab_size
1426
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1427
+
1428
+ # Initialize weights and apply final processing
1429
+ self.post_init()
1430
+
1431
+ def get_input_embeddings(self):
1432
+ return self.model.embed_tokens
1433
+
1434
+ def set_input_embeddings(self, value):
1435
+ self.model.embed_tokens = value
1436
+
1437
+ def get_output_embeddings(self):
1438
+ return self.lm_head
1439
+
1440
+ def set_output_embeddings(self, new_embeddings):
1441
+ self.lm_head = new_embeddings
1442
+
1443
+ def set_decoder(self, decoder):
1444
+ self.model = decoder
1445
+
1446
+ def get_decoder(self):
1447
+ return self.model
1448
+
1449
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
1450
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1451
+ def forward(
1452
+ self,
1453
+ input_ids: torch.LongTensor = None,
1454
+ attention_mask: Optional[torch.Tensor] = None,
1455
+ position_ids: Optional[torch.LongTensor] = None,
1456
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1457
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1458
+ labels: Optional[torch.LongTensor] = None,
1459
+ use_cache: Optional[bool] = None,
1460
+ output_attentions: Optional[bool] = None,
1461
+ output_hidden_states: Optional[bool] = None,
1462
+ return_dict: Optional[bool] = None,
1463
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1464
+ r"""
1465
+ Args:
1466
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1467
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1468
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1469
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1470
+
1471
+ Returns:
1472
+
1473
+ Example:
1474
+
1475
+ ```python
1476
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
1477
+
1478
+ >>> model = AutoModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1479
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1480
+
1481
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1482
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1483
+
1484
+ >>> # Generate
1485
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1486
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1487
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1488
+ ```"""
1489
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1490
+ output_hidden_states = (
1491
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1492
+ )
1493
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1494
+
1495
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1496
+ outputs = self.model(
1497
+ input_ids=input_ids,
1498
+ attention_mask=attention_mask,
1499
+ position_ids=position_ids,
1500
+ past_key_values=past_key_values,
1501
+ inputs_embeds=inputs_embeds,
1502
+ use_cache=use_cache,
1503
+ output_attentions=output_attentions,
1504
+ output_hidden_states=output_hidden_states,
1505
+ return_dict=return_dict,
1506
+ )
1507
+
1508
+ hidden_states = outputs[0]
1509
+ if self.config.pretraining_tp > 1:
1510
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1511
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1512
+ logits = torch.cat(logits, dim=-1)
1513
+ else:
1514
+ logits = self.lm_head(hidden_states)
1515
+ logits = logits.float()
1516
+
1517
+ loss = None
1518
+ if labels is not None:
1519
+ # Shift so that tokens < n predict n
1520
+ shift_logits = logits[..., :-1, :].contiguous()
1521
+ shift_labels = labels[..., 1:].contiguous()
1522
+ # Flatten the tokens
1523
+ loss_fct = CrossEntropyLoss()
1524
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1525
+ shift_labels = shift_labels.view(-1)
1526
+ # Enable model parallelism
1527
+ shift_labels = shift_labels.to(shift_logits.device)
1528
+ loss = loss_fct(shift_logits, shift_labels)
1529
+
1530
+ if not return_dict:
1531
+ output = (logits,) + outputs[1:]
1532
+ return (loss,) + output if loss is not None else output
1533
+
1534
+ return CausalLMOutputWithPast(
1535
+ loss=loss,
1536
+ logits=logits,
1537
+ past_key_values=outputs.past_key_values,
1538
+ hidden_states=outputs.hidden_states,
1539
+ attentions=outputs.attentions,
1540
+ )
1541
+
1542
+ def prepare_inputs_for_generation(
1543
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1544
+ ):
1545
+ if past_key_values is not None:
1546
+ if isinstance(past_key_values, Cache):
1547
+ cache_length = past_key_values.get_seq_length()
1548
+ past_length = past_key_values.seen_tokens
1549
+ max_cache_length = past_key_values.get_max_length()
1550
+ else:
1551
+ cache_length = past_length = past_key_values[0][0].shape[2]
1552
+ max_cache_length = None
1553
+
1554
+ # Keep only the unprocessed tokens:
1555
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1556
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1557
+ # input)
1558
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1559
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1560
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1561
+ # input_ids based on the past_length.
1562
+ elif past_length < input_ids.shape[1]:
1563
+ input_ids = input_ids[:, past_length:]
1564
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1565
+
1566
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1567
+ if (
1568
+ max_cache_length is not None
1569
+ and attention_mask is not None
1570
+ and cache_length + input_ids.shape[1] > max_cache_length
1571
+ ):
1572
+ attention_mask = attention_mask[:, -max_cache_length:]
1573
+
1574
+ position_ids = kwargs.get("position_ids", None)
1575
+ if attention_mask is not None and position_ids is None:
1576
+ # create position_ids on the fly for batch generation
1577
+ position_ids = attention_mask.long().cumsum(-1) - 1
1578
+ position_ids.masked_fill_(attention_mask == 0, 1)
1579
+ if past_key_values:
1580
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1581
+
1582
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1583
+ if inputs_embeds is not None and past_key_values is None:
1584
+ model_inputs = {"inputs_embeds": inputs_embeds}
1585
+ else:
1586
+ model_inputs = {"input_ids": input_ids}
1587
+
1588
+ model_inputs.update(
1589
+ {
1590
+ "position_ids": position_ids,
1591
+ "past_key_values": past_key_values,
1592
+ "use_cache": kwargs.get("use_cache"),
1593
+ "attention_mask": attention_mask,
1594
+ }
1595
+ )
1596
+ return model_inputs
1597
+
1598
+ @staticmethod
1599
+ def _reorder_cache(past_key_values, beam_idx):
1600
+ reordered_past = ()
1601
+ for layer_past in past_key_values:
1602
+ reordered_past += (
1603
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1604
+ )
1605
+ return reordered_past
1606
+
1607
+
1608
+ @add_start_docstrings(
1609
+ """
1610
+ The HunYuan Model transformer with a sequence classification head on top (linear layer).
1611
+
1612
+ [`HunYuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1613
+ (e.g. GPT-2) do.
1614
+
1615
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1616
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1617
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1618
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1619
+ each row of the batch).
1620
+ """,
1621
+ HUNYUAN_START_DOCSTRING,
1622
+ )
1623
+ class HunYuanForSequenceClassification(HunYuanPreTrainedModel):
1624
+ def __init__(self, config):
1625
+ super().__init__(config)
1626
+ self.num_labels = config.num_labels
1627
+ self.model = HunYuanModel(config)
1628
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1629
+
1630
+ # Initialize weights and apply final processing
1631
+ self.post_init()
1632
+
1633
+ def get_input_embeddings(self):
1634
+ return self.model.embed_tokens
1635
+
1636
+ def set_input_embeddings(self, value):
1637
+ self.model.embed_tokens = value
1638
+
1639
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
1640
+ def forward(
1641
+ self,
1642
+ input_ids: torch.LongTensor = None,
1643
+ attention_mask: Optional[torch.Tensor] = None,
1644
+ position_ids: Optional[torch.LongTensor] = None,
1645
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1646
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1647
+ labels: Optional[torch.LongTensor] = None,
1648
+ use_cache: Optional[bool] = None,
1649
+ output_attentions: Optional[bool] = None,
1650
+ output_hidden_states: Optional[bool] = None,
1651
+ return_dict: Optional[bool] = None,
1652
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1653
+ r"""
1654
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1655
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1656
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1657
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1658
+ """
1659
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1660
+
1661
+ transformer_outputs = self.model(
1662
+ input_ids,
1663
+ attention_mask=attention_mask,
1664
+ position_ids=position_ids,
1665
+ past_key_values=past_key_values,
1666
+ inputs_embeds=inputs_embeds,
1667
+ use_cache=use_cache,
1668
+ output_attentions=output_attentions,
1669
+ output_hidden_states=output_hidden_states,
1670
+ return_dict=return_dict,
1671
+ )
1672
+ hidden_states = transformer_outputs[0]
1673
+ logits = self.score(hidden_states)
1674
+
1675
+ if input_ids is not None:
1676
+ batch_size = input_ids.shape[0]
1677
+ else:
1678
+ batch_size = inputs_embeds.shape[0]
1679
+
1680
+ if self.config.pad_token_id is None and batch_size != 1:
1681
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1682
+ if self.config.pad_token_id is None:
1683
+ sequence_lengths = -1
1684
+ else:
1685
+ if input_ids is not None:
1686
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1687
+ logits.device
1688
+ )
1689
+ else:
1690
+ sequence_lengths = -1
1691
+
1692
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1693
+
1694
+ loss = None
1695
+ if labels is not None:
1696
+ labels = labels.to(logits.device)
1697
+ if self.config.problem_type is None:
1698
+ if self.num_labels == 1:
1699
+ self.config.problem_type = "regression"
1700
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1701
+ self.config.problem_type = "single_label_classification"
1702
+ else:
1703
+ self.config.problem_type = "multi_label_classification"
1704
+
1705
+ if self.config.problem_type == "regression":
1706
+ loss_fct = MSELoss()
1707
+ if self.num_labels == 1:
1708
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1709
+ else:
1710
+ loss = loss_fct(pooled_logits, labels)
1711
+ elif self.config.problem_type == "single_label_classification":
1712
+ loss_fct = CrossEntropyLoss()
1713
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1714
+ elif self.config.problem_type == "multi_label_classification":
1715
+ loss_fct = BCEWithLogitsLoss()
1716
+ loss = loss_fct(pooled_logits, labels)
1717
+ if not return_dict:
1718
+ output = (pooled_logits,) + transformer_outputs[1:]
1719
+ return ((loss,) + output) if loss is not None else output
1720
+
1721
+ return SequenceClassifierOutputWithPast(
1722
+ loss=loss,
1723
+ logits=pooled_logits,
1724
+ past_key_values=transformer_outputs.past_key_values,
1725
+ hidden_states=transformer_outputs.hidden_states,
1726
+ attentions=transformer_outputs.attentions,
1727
+ )