woodchen7 commited on
Commit
dec3a70
1 Parent(s): 1e42b34

Upload modeling_hunyuan.py with huggingface_hub

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