manaestras commited on
Commit
df8f0e4
·
verified ·
1 Parent(s): 5808ae3

Upload ./modeling_hunyuan.py with huggingface_hub

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