ngxson HF Staff commited on
Commit
bae8e8d
·
verified ·
1 Parent(s): 4c24553

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ model.gguf filter=lfs diff=lfs merge=lfs -text
config.json ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_classification_head": false,
3
+ "anyres_pooling_size": 2,
4
+ "anyres_vit_max_image_size": null,
5
+ "anyres_vit_two_views": false,
6
+ "architectures": [
7
+ "HunYuanMoEV1ForCausalLM"
8
+ ],
9
+ "attention_bias": false,
10
+ "attention_dropout": 0.1,
11
+ "attention_head_dim": 128,
12
+ "auto_map": {
13
+ "AutoConfig": "configuration_hunyuan.HunYuanConfig",
14
+ "AutoModel": "hunyuan.HunYuanModel",
15
+ "AutoModelForCausalLM": "hunyuan.HunYuanMoEV1ForCausalLM"
16
+ },
17
+ "bos_token_id": 1,
18
+ "cla_share_factor": 2,
19
+ "class_num": 0,
20
+ "dense_list": [
21
+ 4096,
22
+ 0
23
+ ],
24
+ "eod_token_id": 127967,
25
+ "eos_token_id": 127960,
26
+ "group_limited_greedy": false,
27
+ "hidden_act": "silu",
28
+ "hidden_size": 4096,
29
+ "im_end_id": 6,
30
+ "im_newline_id": 12,
31
+ "im_start_id": 5,
32
+ "image_token_id": 9,
33
+ "initializer_range": 0.02,
34
+ "intermediate_size": 3072,
35
+ "kv_lora_rank": null,
36
+ "mask_init_id": 13,
37
+ "max_position_embeddings": 32768,
38
+ "mlp_bias": false,
39
+ "model_type": "hunyuan",
40
+ "moe_drop_tokens": false,
41
+ "moe_intermediate_size": [
42
+ 3072,
43
+ 3072,
44
+ 3072,
45
+ 3072
46
+ ],
47
+ "moe_layer_num_skipped": 0,
48
+ "moe_random_routing_dropped_token": false,
49
+ "moe_topk": [
50
+ 2,
51
+ 2,
52
+ 2,
53
+ 2
54
+ ],
55
+ "n_group": null,
56
+ "norm_topk_prob": true,
57
+ "norm_type": "rms",
58
+ "num_attention_heads": 32,
59
+ "num_experts": 4,
60
+ "num_hidden_layers": 4,
61
+ "num_key_value_heads": 8,
62
+ "num_media_embeds": 257,
63
+ "num_shared_expert": [
64
+ 1,
65
+ 1,
66
+ 1,
67
+ 1
68
+ ],
69
+ "org_vocab_size": 128167,
70
+ "pad_id": 127961,
71
+ "pad_token_id": 127961,
72
+ "pool_type": "last",
73
+ "position_embedding_xdrope": false,
74
+ "pretraining_tp": 1,
75
+ "q_lora_rank": null,
76
+ "qk_nope_head_dim": null,
77
+ "qk_rope_head_dim": null,
78
+ "rms_norm_eps": 1e-05,
79
+ "rope_scaling": {
80
+ "alpha": 1000.0,
81
+ "beta_fast": 32,
82
+ "beta_slow": 1,
83
+ "factor": 1.0,
84
+ "mscale": 1.0,
85
+ "mscale_all_dim": 1.0,
86
+ "type": "dynamic"
87
+ },
88
+ "rope_theta": 10000.0,
89
+ "routed_scaling_factor": 1.0,
90
+ "sep_token_id": 127962,
91
+ "skip_cls_token": false,
92
+ "text_end_id": 8,
93
+ "text_start_id": 7,
94
+ "tie_word_embeddings": true,
95
+ "topk_group": null,
96
+ "torch_dtype": "float32",
97
+ "transformers_version": "4.51.3",
98
+ "use_cache": true,
99
+ "use_cla": false,
100
+ "use_mixed_mlp_moe": true,
101
+ "use_mla": false,
102
+ "use_qk_norm": true,
103
+ "use_rotary_pos_emb": true,
104
+ "v_head_dim": null,
105
+ "video_end_id": 11,
106
+ "video_start_id": 10,
107
+ "vit_add_patchemb_bias": false,
108
+ "vit_input_resolution": 224,
109
+ "vit_mapping_type": "resampler",
110
+ "vit_norm_type": "fused",
111
+ "vit_patch": 1,
112
+ "vit_path": null,
113
+ "vit_remove_prenorm": false,
114
+ "vit_token": 64,
115
+ "vit_type": null,
116
+ "vit_used_rms_norm": false,
117
+ "vocab_size": 128167,
118
+ "xdrope_section": null
119
+ }
configuration_hunyuan.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
3
+ """ HunYuan model configuration"""
4
+ from torch import nn
5
+ from transformers.configuration_utils import PretrainedConfig
6
+ from transformers.utils import logging
7
+ from typing import List, Union, Optional
8
+
9
+
10
+ logger = logging.get_logger(__name__)
11
+
12
+
13
+ class HunYuanConfig(PretrainedConfig):
14
+ r"""
15
+ This is the configuration class to store the configuration of a [`HunYuanModel`]. It is used to instantiate an
16
+ HunYuan model according to the specified arguments, defining the model architecture. Instantiating a configuration
17
+ with the defaults will yield a similar configuration to that of the HunYuan-7B.
18
+
19
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
20
+ documentation from [`PretrainedConfig`] for more information.
21
+
22
+
23
+ Args:
24
+ vocab_size (`int`, *optional*, defaults to 32000):
25
+ Vocabulary size of the HunYuan model. Defines the number of different tokens that can be represented by the
26
+ `inputs_ids` passed when calling [`HunYuanModel`]
27
+ hidden_size (`int`, *optional*, defaults to 4096):
28
+ Dimension of the hidden representations.
29
+ intermediate_size (`int`, *optional*, defaults to 11008):
30
+ Dimension of the MLP representations or shared MLP representations.
31
+ moe_intermediate_size (`int` or `List`, *optional*, defaults to 11008):
32
+ Dimension of the MLP representations in MoE. Use a list if you want a different size per layer.
33
+ num_hidden_layers (`int`, *optional*, defaults to 32):
34
+ Number of hidden layers in the Transformer decoder.
35
+ num_attention_heads (`int`, *optional*, defaults to 32):
36
+ Number of attention heads for each attention layer in the Transformer decoder.
37
+ num_key_value_heads (`int`, *optional*):
38
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
39
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
40
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
41
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
42
+ by meanpooling all the original heads within that group. For more details checkout [this
43
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
44
+ `num_attention_heads`.
45
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
46
+ The non-linear activation function (function or string) in the decoder.
47
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
48
+ The maximum sequence length that this model might ever be used with.
49
+ initializer_range (`float`, *optional*, defaults to 0.02):
50
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
51
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
52
+ The epsilon used by the rms normalization layers.
53
+ use_cache (`bool`, *optional*, defaults to `True`):
54
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
55
+ relevant if `config.is_decoder=True`.
56
+ pad_token_id (`int`, *optional*):
57
+ Padding token id.
58
+ bos_token_id (`int`, *optional*, defaults to 1):
59
+ Beginning of stream token id.
60
+ eos_token_id (`int`, *optional*, defaults to 2):
61
+ End of stream token id.
62
+ pretraining_tp (`int`, *optional*, defaults to 1):
63
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
64
+ document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
65
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
66
+ issue](https://github.com/pytorch/pytorch/issues/76232).
67
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
68
+ Whether to tie weight embeddings
69
+ rope_theta (`float`, *optional*, defaults to 10000.0):
70
+ The base period of the RoPE embeddings.
71
+ rope_scaling (`Dict`, *optional*):
72
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
73
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
74
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
75
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
76
+ these scaling strategies behave:
77
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
78
+ experimental feature, subject to breaking API changes in future versions.
79
+ attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
80
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
81
+ attention_dropout (`float`, *optional*, defaults to 0.0):
82
+ The dropout ratio for the attention probabilities.
83
+ use_qk_norm (`bool`, *optional*, defaults to `False`):
84
+ Whether query and key in attention use norm
85
+ use_cla (`bool`, *optional*, defaults to `False`):
86
+ Whether to use CLA in attention
87
+ cla_share_factor (`int`, *optional*, defaults to 1):
88
+ The share factor of CLA
89
+ num_experts (`int` or `List`, *optional*, defaults to 1):
90
+ The number of experts for moe. If it is a list, it will be used as the number of experts for each layer.
91
+ num_shared_expert (`int` or `List`, *optional*, defaults to 1):
92
+ The number of shared experts for moe. If it is a list, it will be used as the number of shared experts for each layer.
93
+ moe_topk (`int` or `List`, *optional*, defaults to 1):
94
+ The topk value for moe. If it is a list, it will be used as the topk value for each layer.
95
+ capacity_factor (Not used) (`float` or `List`, *optional*, defaults to 1.0):
96
+ The capacity factor for moe. If it is a list, it will be used as the capacity factor for each layer.
97
+ moe_layer_num_skipped (`int`, *optional*, defaults to 0):
98
+ First moe_layer_num_skipped layers do not use MoE.
99
+ """
100
+
101
+ model_type = "hunyuan"
102
+ keys_to_ignore_at_inference = ["past_key_values"]
103
+
104
+ def __init__(
105
+ self,
106
+ vocab_size=290943,
107
+ org_vocab_size=290943,
108
+ hidden_size=4096,
109
+ intermediate_size: int=11008,
110
+ moe_intermediate_size: Union[int, List]=None,
111
+ num_hidden_layers=32,
112
+ num_attention_heads=32,
113
+ num_key_value_heads=None,
114
+ attention_head_dim=None,
115
+ hidden_act="silu",
116
+ max_position_embeddings=2048,
117
+ initializer_range=0.02,
118
+ rms_norm_eps=1e-5,
119
+ use_cache=True,
120
+ pad_token_id=0,
121
+ bos_token_id=1,
122
+ eos_token_id=2,
123
+ eod_token_id=3,
124
+ sep_token_id=4,
125
+ im_start_id=5,
126
+ im_end_id=6,
127
+ text_start_id=7,
128
+ text_end_id=8,
129
+ image_token_id=9,
130
+ video_start_id=10,
131
+ video_end_id=11,
132
+ im_newline_id=12,
133
+ mask_init_id=13,
134
+ pretraining_tp=1,
135
+ tie_word_embeddings=False,
136
+ rope_theta=10000.0,
137
+ rope_scaling=None,
138
+ attention_bias=False,
139
+ mlp_bias=False,
140
+ attention_dropout=0.0,
141
+ use_qk_norm=False,
142
+ use_rotary_pos_emb=True,
143
+ use_cla=False,
144
+ cla_share_factor=1,
145
+ norm_type="hf_rms",
146
+ num_experts: Union[int, List]=1,
147
+ use_mixed_mlp_moe=False,
148
+ num_shared_expert: Union[int, List]=1,
149
+ moe_topk: Union[int, List]=1,
150
+ # capacity_factor: Union[int, List]=1.0,
151
+ moe_drop_tokens=False,
152
+ moe_random_routing_dropped_token=False,
153
+ use_mla=False,
154
+ kv_lora_rank=512,
155
+ q_lora_rank=1536,
156
+ qk_rope_head_dim=64,
157
+ v_head_dim=128,
158
+ qk_nope_head_dim=128,
159
+ moe_layer_num_skipped=0,
160
+ norm_topk_prob=True,
161
+ routed_scaling_factor=1.0,
162
+ group_limited_greedy=False,
163
+ n_group=None,
164
+ topk_group=None,
165
+ vit_path=None,
166
+ num_media_embeds=257,
167
+ vit_type="AnyResVit",
168
+ vit_input_resolution=224,
169
+ vit_token=64,
170
+ vit_patch=1,
171
+ vit_mapping_type="simple_conv_mlp",
172
+ vit_norm_type="fused",
173
+ vit_used_rms_norm=True,
174
+ vit_remove_prenorm=True,
175
+ vit_add_patchemb_bias=True,
176
+ anyres_vit_max_image_size=2048,
177
+ anyres_pooling_size=2,
178
+ anyres_vit_two_views=False,
179
+ skip_cls_token=False,
180
+ position_embedding_xdrope=False,
181
+ xdrope_section=None,
182
+ add_classification_head=False,
183
+ class_num=0,
184
+ pool_type="last",
185
+ pad_id=-1,
186
+ **kwargs,
187
+ ):
188
+ self.vocab_size = vocab_size
189
+ self.org_vocab_size = org_vocab_size
190
+ self.max_position_embeddings = max_position_embeddings
191
+ self.hidden_size = hidden_size
192
+ self.intermediate_size = intermediate_size
193
+ self.moe_intermediate_size = moe_intermediate_size
194
+ self.num_hidden_layers = num_hidden_layers
195
+ self.num_attention_heads = num_attention_heads
196
+ self.num_experts = num_experts
197
+ self.use_mixed_mlp_moe = use_mixed_mlp_moe
198
+ self.num_shared_expert = num_shared_expert
199
+ self.moe_topk = moe_topk
200
+ # self.capacity_factor = capacity_factor
201
+ self.moe_drop_tokens = moe_drop_tokens
202
+ self.moe_random_routing_dropped_token = moe_random_routing_dropped_token
203
+
204
+ if attention_head_dim is not None:
205
+ self.attention_head_dim = attention_head_dim
206
+ else:
207
+ self.attention_head_dim = self.hidden_size // num_attention_heads
208
+
209
+ # for backward compatibility
210
+ if num_key_value_heads is None:
211
+ num_key_value_heads = num_attention_heads
212
+
213
+ self.num_key_value_heads = num_key_value_heads
214
+ self.hidden_act = hidden_act
215
+ self.initializer_range = initializer_range
216
+ self.rms_norm_eps = rms_norm_eps
217
+ self.pretraining_tp = pretraining_tp
218
+ self.use_cache = use_cache
219
+ self.rope_theta = rope_theta
220
+ self.rope_scaling = rope_scaling
221
+ # self._rope_scaling_validation() # TODO: Need validation?
222
+ self.attention_bias = attention_bias
223
+ self.mlp_bias = mlp_bias
224
+ self.attention_dropout = attention_dropout
225
+ self.use_qk_norm = use_qk_norm
226
+ self.use_rotary_pos_emb = use_rotary_pos_emb
227
+ self.use_cla = use_cla
228
+ self.cla_share_factor = cla_share_factor
229
+ self.norm_type = norm_type
230
+ # MLA args
231
+ self.use_mla = use_mla
232
+ self.kv_lora_rank = kv_lora_rank
233
+ self.q_lora_rank = q_lora_rank
234
+ self.qk_rope_head_dim = qk_rope_head_dim
235
+ self.qk_nope_head_dim = qk_nope_head_dim
236
+ self.v_head_dim = v_head_dim
237
+
238
+ # DeepSeek related args
239
+ self.moe_layer_num_skipped = moe_layer_num_skipped
240
+ self.norm_topk_prob = norm_topk_prob
241
+ self.routed_scaling_factor = routed_scaling_factor
242
+ self.group_limited_greedy = group_limited_greedy
243
+ self.n_group = n_group
244
+ self.topk_group = topk_group
245
+ self.add_classification_head = add_classification_head
246
+ self.class_num = class_num
247
+ self.pool_type = pool_type
248
+ self.pad_id = pad_id
249
+
250
+ if self.class_num is not None:
251
+ self.dense_list = [self.hidden_size, self.class_num]
252
+
253
+ # Vit args
254
+ self.vit_path = vit_path
255
+ self.num_media_embeds = num_media_embeds
256
+ self.vit_type = vit_type
257
+ self.vit_input_resolution = vit_input_resolution
258
+ self.vit_token = vit_token
259
+ self.vit_patch = vit_patch
260
+ self.vit_mapping_type = vit_mapping_type
261
+ self.vit_norm_type = vit_norm_type
262
+ self.vit_used_rms_norm = vit_used_rms_norm
263
+ self.vit_remove_prenorm = vit_remove_prenorm
264
+ self.vit_add_patchemb_bias = vit_add_patchemb_bias
265
+ self.anyres_vit_max_image_size = anyres_vit_max_image_size
266
+ self.anyres_pooling_size = anyres_pooling_size
267
+ self.anyres_vit_two_views = anyres_vit_two_views
268
+ self.skip_cls_token = skip_cls_token
269
+ self.position_embedding_xdrope = position_embedding_xdrope
270
+ self.xdrope_section = xdrope_section
271
+
272
+ # token id
273
+ self.eod_token_id = eod_token_id
274
+ self.im_start_id = im_start_id
275
+ self.im_end_id = im_end_id
276
+ self.text_start_id = text_start_id
277
+ self.text_end_id = text_end_id
278
+ self.image_token_id = image_token_id
279
+ self.video_start_id = video_start_id
280
+ self.video_end_id = video_end_id
281
+ self.im_newline_id = im_newline_id
282
+ self.mask_init_id = mask_init_id
283
+
284
+ super().__init__(
285
+ pad_token_id=pad_token_id,
286
+ bos_token_id=bos_token_id,
287
+ eos_token_id=eos_token_id,
288
+ sep_token_id=sep_token_id,
289
+ tie_word_embeddings=tie_word_embeddings,
290
+ **kwargs,
291
+ )
292
+
293
+ def _rope_scaling_validation(self):
294
+ """
295
+ Validate the `rope_scaling` configuration.
296
+ """
297
+ if self.rope_scaling is None:
298
+ return
299
+
300
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
301
+ raise ValueError(
302
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor` or `type` and `alpha`, "
303
+ f"got {self.rope_scaling}"
304
+ )
305
+ rope_scaling_type = self.rope_scaling.get("type", None)
306
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
307
+ rope_scaling_alpha = self.rope_scaling.get("alpha", None)
308
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
309
+ raise ValueError(
310
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
311
+ )
312
+ if rope_scaling_factor is None and rope_scaling_alpha is None:
313
+ raise ValueError("`rope_scaling`'s factor or alpha field must be have one, got both of none")
314
+ if rope_scaling_factor is not None:
315
+ if not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
316
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1.0, got {rope_scaling_factor}")
317
+ if rope_scaling_alpha is not None:
318
+ if not isinstance(rope_scaling_alpha, float) or rope_scaling_alpha <= 1.0:
319
+ raise ValueError(f"`rope_scaling`'s alpha field must be a float > 1.0, got {rope_scaling_alpha}")
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 127960,
5
+ "pad_token_id": 127961,
6
+ "transformers_version": "4.51.3"
7
+ }
hunyuan.py ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (C) 2024 THL A29 Limited, a Tencent company. 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 transformers.generation.utils import GenerateOutput
42
+ from .configuration_hunyuan import HunYuanConfig
43
+ from .modeling_hunyuan import HunYuanDecoderLayer, HunYuanRMSNorm
44
+ from .vit_model import NaVitForward, VitForward, Vit
45
+
46
+
47
+ if is_flash_attn_2_available():
48
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
49
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
50
+
51
+
52
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
53
+ # It means that the function will not be traced through and simply appear as a node in the graph.
54
+ if is_torch_fx_available():
55
+ if not is_torch_greater_or_equal_than_1_13:
56
+ import torch.fx
57
+
58
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
59
+
60
+
61
+
62
+ _CONFIG_FOR_DOC = "HunYuanConfig"
63
+
64
+
65
+ HUNYUAN_START_DOCSTRING = r"""
66
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
67
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
68
+ etc.)
69
+
70
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
71
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
72
+ and behavior.
73
+
74
+ Parameters:
75
+ config ([`HunYuanConfig`]):
76
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
77
+ load the weights associated with the model, only the configuration. Check out the
78
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
79
+ """
80
+
81
+
82
+ @add_start_docstrings(
83
+ "The bare HunYuan Model outputting raw hidden-states without any specific head on top.",
84
+ HUNYUAN_START_DOCSTRING,
85
+ )
86
+ class HunYuanPreTrainedModel(PreTrainedModel):
87
+ config_class = HunYuanConfig
88
+ base_model_prefix = "model"
89
+ supports_gradient_checkpointing = True
90
+ _no_split_modules = ["HunYuanDecoderLayer"]
91
+ _skip_keys_device_placement = "past_key_values"
92
+ _supports_flash_attn_2 = True
93
+ _supports_sdpa = True
94
+ _supports_cache_class = True
95
+
96
+ def _init_weights(self, module):
97
+ std = self.config.initializer_range
98
+ if isinstance(module, nn.Linear):
99
+ module.weight.data.normal_(mean=0.0, std=std)
100
+ if module.bias is not None:
101
+ module.bias.data.zero_()
102
+ elif isinstance(module, nn.Embedding):
103
+ module.weight.data.normal_(mean=0.0, std=std)
104
+ if module.padding_idx is not None:
105
+ module.weight.data[module.padding_idx].zero_()
106
+
107
+
108
+ HUNYUAN_INPUTS_DOCSTRING = r"""
109
+ Args:
110
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
111
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
112
+ it.
113
+
114
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
115
+ [`PreTrainedTokenizer.__call__`] for details.
116
+
117
+ [What are input IDs?](../glossary#input-ids)
118
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
119
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
120
+
121
+ - 1 for tokens that are **not masked**,
122
+ - 0 for tokens that are **masked**.
123
+
124
+ [What are attention masks?](../glossary#attention-mask)
125
+
126
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
127
+ [`PreTrainedTokenizer.__call__`] for details.
128
+
129
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
130
+ `past_key_values`).
131
+
132
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
133
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
134
+ information on the default strategy.
135
+
136
+ - 1 indicates the head is **not masked**,
137
+ - 0 indicates the head is **masked**.
138
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
139
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
140
+ config.n_positions - 1]`.
141
+
142
+ [What are position IDs?](../glossary#position-ids)
143
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
144
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
145
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
146
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
147
+
148
+ Two formats are allowed:
149
+ - a [`~cache_utils.Cache`] instance;
150
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
151
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
152
+ cache format.
153
+
154
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
155
+ legacy cache format will be returned.
156
+
157
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
158
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
159
+ of shape `(batch_size, sequence_length)`.
160
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
161
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
162
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
163
+ model's internal embedding lookup matrix.
164
+ use_cache (`bool`, *optional*):
165
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
166
+ `past_key_values`).
167
+ output_attentions (`bool`, *optional*):
168
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
169
+ tensors for more detail.
170
+ output_hidden_states (`bool`, *optional*):
171
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
172
+ more detail.
173
+ return_dict (`bool`, *optional*):
174
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
175
+ """
176
+
177
+
178
+ @add_start_docstrings(
179
+ "The bare HunYuan Model outputting raw hidden-states without any specific head on top.",
180
+ HUNYUAN_START_DOCSTRING,
181
+ )
182
+ class HunYuanModel(HunYuanPreTrainedModel):
183
+ """
184
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`HunYuanDecoderLayer`]
185
+
186
+ Args:
187
+ config: HunYuanConfig
188
+ """
189
+
190
+ def __init__(self, config: HunYuanConfig):
191
+ super().__init__(config)
192
+ self.padding_idx = config.pad_token_id
193
+ self.vocab_size = config.vocab_size
194
+ self.add_classification_head = config.add_classification_head
195
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
196
+ self.layers = nn.ModuleList(
197
+ [HunYuanDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
198
+ )
199
+ self._use_sdpa = config._attn_implementation == "sdpa"
200
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
201
+ if not config.add_classification_head:
202
+ self.norm = HunYuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
203
+
204
+ self.cla = config.use_cla
205
+ self.cla_share_factor = config.cla_share_factor
206
+
207
+ self.gradient_checkpointing = False
208
+ # Initialize weights and apply final processing
209
+ self.post_init()
210
+
211
+ def get_input_embeddings(self):
212
+ return self.embed_tokens
213
+
214
+ def set_input_embeddings(self, value):
215
+ self.embed_tokens = value
216
+
217
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
218
+ def forward(
219
+ self,
220
+ input_ids: torch.LongTensor = None,
221
+ attention_mask: Optional[torch.Tensor] = None,
222
+ position_ids: Optional[torch.LongTensor] = None,
223
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
224
+ inputs_embeds: Optional[torch.FloatTensor] = None,
225
+ use_cache: Optional[bool] = None,
226
+ output_attentions: Optional[bool] = None,
227
+ output_hidden_states: Optional[bool] = None,
228
+ return_dict: Optional[bool] = None,
229
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
230
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
231
+ output_hidden_states = (
232
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
233
+ )
234
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
235
+
236
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
237
+
238
+ # retrieve input_ids and inputs_embeds
239
+ # if input_ids is not None and inputs_embeds is not None:
240
+ # raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
241
+ if input_ids is not None:
242
+ batch_size, seq_length = input_ids.shape[:2]
243
+ elif inputs_embeds is not None:
244
+ batch_size, seq_length = inputs_embeds.shape[:2]
245
+ else:
246
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
247
+
248
+ if self.gradient_checkpointing and self.training:
249
+ if use_cache:
250
+ logger.warning_once(
251
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
252
+ )
253
+ use_cache = False
254
+
255
+ past_key_values_length = 0
256
+ if use_cache:
257
+ use_legacy_cache = not isinstance(past_key_values, Cache)
258
+ if use_legacy_cache:
259
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
260
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
261
+
262
+ if position_ids is None:
263
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
264
+ position_ids = torch.arange(
265
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
266
+ )
267
+ position_ids = position_ids.unsqueeze(0)
268
+
269
+ if inputs_embeds is None:
270
+ inputs_embeds = self.embed_tokens(input_ids)
271
+
272
+ # Fix lora with gradient checkpointing training
273
+ if self.training and inputs_embeds.is_leaf:
274
+ inputs_embeds.requires_grad = True
275
+
276
+ if self._use_flash_attention_2:
277
+ # 2d mask is passed through the layers
278
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
279
+ elif self._use_sdpa and not output_attentions:
280
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
281
+ # the manual implementation that requires a 4D causal mask in all cases.
282
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
283
+ attention_mask,
284
+ (batch_size, seq_length),
285
+ inputs_embeds,
286
+ past_key_values_length,
287
+ )
288
+ else:
289
+ # 4d mask is passed through the layers
290
+ attention_mask = _prepare_4d_causal_attention_mask(
291
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
292
+ )
293
+
294
+ # embed positions
295
+ hidden_states = inputs_embeds
296
+
297
+ # decoder layers
298
+ all_hidden_states = () if output_hidden_states else None
299
+ all_self_attns = () if output_attentions else None
300
+ next_decoder_cache = None
301
+
302
+ prev_kv_states = None
303
+ for layer_idx, decoder_layer in enumerate(self.layers):
304
+ if output_hidden_states:
305
+ all_hidden_states += (hidden_states,)
306
+
307
+ if self.gradient_checkpointing and self.training:
308
+ layer_outputs = self._gradient_checkpointing_func(
309
+ decoder_layer.__call__,
310
+ hidden_states,
311
+ attention_mask,
312
+ position_ids,
313
+ past_key_values,
314
+ output_attentions,
315
+ use_cache,
316
+ prev_kv_states,
317
+ )
318
+ else:
319
+ layer_outputs = decoder_layer(
320
+ hidden_states,
321
+ attention_mask=attention_mask,
322
+ position_ids=position_ids,
323
+ past_key_value=past_key_values,
324
+ output_attentions=output_attentions,
325
+ use_cache=use_cache,
326
+ kv_states=prev_kv_states
327
+ )
328
+
329
+ hidden_states = layer_outputs[0]
330
+
331
+ if use_cache:
332
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
333
+
334
+ if output_attentions:
335
+ all_self_attns += (layer_outputs[1],)
336
+
337
+ kv_states = layer_outputs[-1]
338
+
339
+ if self.cla and layer_idx % self.cla_share_factor == 0:
340
+ prev_kv_states = kv_states
341
+ if not self.add_classification_head:
342
+ hidden_states = self.norm(hidden_states)
343
+
344
+ # add hidden states from the last decoder layer
345
+ if output_hidden_states:
346
+ all_hidden_states += (hidden_states,)
347
+
348
+ next_cache = None
349
+ if use_cache:
350
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
351
+ if not return_dict:
352
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
353
+ return BaseModelOutputWithPast(
354
+ last_hidden_state=hidden_states,
355
+ past_key_values=next_cache,
356
+ hidden_states=all_hidden_states,
357
+ attentions=all_self_attns,
358
+ )
359
+
360
+
361
+ class HunYuanMoEV1ForCausalLM(HunYuanPreTrainedModel):
362
+ _tied_weights_keys = ["lm_head.weight"]
363
+
364
+ def __init__(self, config: HunYuanConfig):
365
+ super().__init__(config)
366
+ if config.vit_path is not None:
367
+ if "-tp" in config.vit_type:
368
+ config.vit_type = config.vit_type.replace("-tp", "")
369
+ self.vit_type = config.vit_type
370
+ if self.vit_type not in ['NaVit', 'EvaVit']:
371
+ if config.vit_mapping_type == 'mlp':
372
+ self.vit_linear_encoder = torch.nn.Linear(config.hidden_size, config.hidden_size)
373
+ self.vit = Vit(config)
374
+ else:
375
+ self.vit = None
376
+ self.config = config
377
+ self.model = HunYuanModel(config)
378
+ self.add_classification_head = config.add_classification_head
379
+ self.pad_id = config.pad_id
380
+ self.vocab_size = config.vocab_size
381
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
382
+ if config.add_classification_head:
383
+ self.pool_head = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
384
+ self.pool_head2 = nn.Linear(config.hidden_size, config.class_num, bias=False)
385
+ # Initialize weights and apply final processing
386
+ self.post_init()
387
+
388
+ def get_input_embeddings(self):
389
+ return self.model.embed_tokens
390
+
391
+ def set_input_embeddings(self, value):
392
+ self.model.embed_tokens = value
393
+
394
+ def get_output_embeddings(self):
395
+ return self.lm_head
396
+
397
+ def set_output_embeddings(self, new_embeddings):
398
+ self.lm_head = new_embeddings
399
+
400
+ def set_decoder(self, decoder):
401
+ self.model = decoder
402
+
403
+ def get_decoder(self):
404
+ return self.model
405
+
406
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
407
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
408
+ def forward(
409
+ self,
410
+ input_ids: torch.LongTensor = None,
411
+ attention_mask: Optional[torch.Tensor] = None,
412
+ position_ids: Optional[torch.LongTensor] = None,
413
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
414
+ inputs_embeds: Optional[torch.FloatTensor] = None,
415
+ labels: Optional[torch.LongTensor] = None,
416
+ use_cache: Optional[bool] = None,
417
+ output_attentions: Optional[bool] = None,
418
+ output_hidden_states: Optional[bool] = None,
419
+ return_dict: Optional[bool] = None,
420
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
421
+ r"""
422
+ Args:
423
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
424
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
425
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
426
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
427
+
428
+ Returns:
429
+
430
+ Example:
431
+
432
+ ```python
433
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
434
+
435
+ >>> model = AutoModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
436
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
437
+
438
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
439
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
440
+
441
+ >>> # Generate
442
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
443
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
444
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
445
+ ```"""
446
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
447
+ output_hidden_states = (
448
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
449
+ )
450
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
451
+
452
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
453
+ outputs = self.model(
454
+ input_ids=input_ids,
455
+ attention_mask=attention_mask,
456
+ position_ids=position_ids,
457
+ past_key_values=past_key_values,
458
+ inputs_embeds=inputs_embeds,
459
+ use_cache=use_cache,
460
+ output_attentions=output_attentions,
461
+ output_hidden_states=output_hidden_states,
462
+ return_dict=return_dict,
463
+ )
464
+
465
+ hidden_states = outputs[0]
466
+
467
+ if not self.add_classification_head:
468
+ if self.config.pretraining_tp > 1:
469
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
470
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
471
+ logits = torch.cat(logits, dim=-1)
472
+ else:
473
+ logits = self.lm_head(hidden_states)
474
+ logits = logits.float()
475
+ else:
476
+ logits = hidden_states
477
+ logits = logits.float()
478
+ pooled_output = self.pool_head(logits)
479
+ pooled_output = torch.tanh(pooled_output)
480
+ pooled_output = self.pool_head2(pooled_output).contiguous() # bs * class_num
481
+ if len(pooled_output.shape) < 2:
482
+ raise ValueError("pooled_output does not have enough dimensions for transpose")
483
+
484
+ if self.config.pool_type == "mean":
485
+ reward = pooled_output.mean(dim=1).squeeze(-1)
486
+ elif self.config.pool_type == "last":
487
+ # bs * hidden_size
488
+ seq_length = (input_ids != self.pad_id).long().sum(dim=1) - 1
489
+ batch_size = input_ids.size(0)
490
+ reward = pooled_output[torch.arange(batch_size, device=pooled_output.device), seq_length].squeeze(-1)
491
+ else:
492
+ reward = pooled_output[:, 0].squeeze(-1)
493
+
494
+ loss = None
495
+ if labels is not None:
496
+ # Shift so that tokens < n predict n
497
+ shift_logits = logits[..., :-1, :].contiguous()
498
+ shift_labels = labels[..., 1:].contiguous()
499
+ # Flatten the tokens
500
+ loss_fct = CrossEntropyLoss()
501
+ shift_logits = shift_logits.reshape(-1, self.config.vocab_size)
502
+ shift_labels = shift_labels.reshape(-1)
503
+ # Enable model parallelism
504
+ shift_labels = shift_labels.to(shift_logits.device)
505
+ loss = loss_fct(shift_logits, shift_labels)
506
+
507
+ if not return_dict:
508
+ output = (logits,) + outputs[1:]
509
+ return (loss,) + output if loss is not None else output
510
+
511
+ output = CausalLMOutputWithPast(
512
+ loss=loss,
513
+ logits=logits,
514
+ past_key_values=outputs.past_key_values,
515
+ hidden_states=outputs.hidden_states,
516
+ attentions=outputs.attentions,
517
+ )
518
+ if self.add_classification_head:
519
+ output['reward'] = reward
520
+
521
+ return output
522
+
523
+ def prepare_inputs_for_generation(
524
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
525
+ ):
526
+ if past_key_values is not None:
527
+ if isinstance(past_key_values, Cache):
528
+ cache_length = past_key_values.get_seq_length()
529
+ past_length = past_key_values.seen_tokens
530
+ max_cache_length = past_key_values.get_max_cache_shape()
531
+ else:
532
+ cache_length = past_length = past_key_values[0][0].shape[2]
533
+ max_cache_length = None
534
+
535
+ # Keep only the unprocessed tokens:
536
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
537
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
538
+ # input)
539
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
540
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
541
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
542
+ # input_ids based on the past_length.
543
+ elif past_length < input_ids.shape[1]:
544
+ input_ids = input_ids[:, past_length:]
545
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
546
+
547
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
548
+ if (
549
+ max_cache_length is not None
550
+ and attention_mask is not None
551
+ and cache_length + input_ids.shape[1] > max_cache_length
552
+ ):
553
+ attention_mask = attention_mask[:, -max_cache_length:]
554
+
555
+ position_ids = kwargs.get("position_ids", None)
556
+ if attention_mask is not None and position_ids is None:
557
+ # create position_ids on the fly for batch generation
558
+ position_ids = attention_mask.long().cumsum(-1) - 1
559
+ position_ids.masked_fill_(attention_mask == 0, 1)
560
+ if past_key_values:
561
+ position_ids = position_ids[:, -input_ids.shape[1]:]
562
+
563
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
564
+ if inputs_embeds is not None and past_key_values is None:
565
+ model_inputs = {"inputs_embeds": inputs_embeds}
566
+ else:
567
+ model_inputs = {"input_ids": input_ids}
568
+
569
+ model_inputs.update(
570
+ {
571
+ "position_ids": position_ids,
572
+ "past_key_values": past_key_values,
573
+ "use_cache": kwargs.get("use_cache"),
574
+ "attention_mask": attention_mask,
575
+ }
576
+ )
577
+ return model_inputs
578
+
579
+ @staticmethod
580
+ def _reorder_cache(past_key_values, beam_idx):
581
+ reordered_past = ()
582
+ for layer_past in past_key_values:
583
+ reordered_past += (
584
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
585
+ )
586
+ return reordered_past
587
+
588
+
589
+ class MultimodelHunYuanForCausalLM(HunYuanMoEV1ForCausalLM):
590
+ _tied_weights_keys = ["lm_head.weight"]
591
+
592
+ def __init__(self, config: HunYuanConfig):
593
+ super().__init__(config)
594
+
595
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
596
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
597
+ def forward(
598
+ self,
599
+ input_ids: torch.LongTensor = None,
600
+ attention_mask: Optional[torch.Tensor] = None,
601
+ position_ids: Optional[torch.LongTensor] = None,
602
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
603
+ inputs_embeds: Optional[torch.FloatTensor] = None,
604
+ labels: Optional[torch.LongTensor] = None,
605
+ imgs: Optional[List[torch.FloatTensor]] = None,
606
+ imgs_pos: Optional[List[int]] = None,
607
+ use_cache: Optional[bool] = None,
608
+ output_attentions: Optional[bool] = None,
609
+ output_hidden_states: Optional[bool] = None,
610
+ return_dict: Optional[bool] = None,
611
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
612
+ r"""
613
+ Args:
614
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
615
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
616
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
617
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
618
+
619
+ Returns:
620
+
621
+ Example:
622
+
623
+ ```python
624
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
625
+
626
+ >>> model = AutoModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
627
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
628
+
629
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
630
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
631
+
632
+ >>> # Generate
633
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
634
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
635
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
636
+ ```"""
637
+ mask_init_id = self.config.mask_init_id
638
+ pad_id = self.config.pad_token_id
639
+ eod_id = self.config.eod_token_id
640
+ image_token_id = self.config.image_token_id
641
+ im_start_id = self.config.im_start_id
642
+ im_end_id = self.config.im_end_id
643
+ video_start_id = self.config.video_start_id
644
+ video_end_id = self.config.video_end_id
645
+
646
+ if self.vit is not None and imgs is not None:
647
+ encoder_input = self.model.embed_tokens(input_ids)
648
+ if self.vit_type in ['NaVit', 'EvaVit', 'AnyResVit']:
649
+ inputs_embeds, input_ids = NaVitForward(input_ids, encoder_input, self.vit, imgs, imgs_pos, self.config.vit_input_resolution, \
650
+ im_start_id, im_end_id, image_token_id, self.config.anyres_vit_two_views, self.config.torch_dtype)
651
+ else:
652
+ inputs_embeds, input_ids = VitForward(input_ids, encoder_input, self.vit, self.vit_linear_encoder, imgs, imgs_pos, \
653
+ self.config.vit_input_resolution, self.config.vit_mapping_type, self.config.vit_patch, self.config.vit_token)
654
+
655
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
656
+ output_hidden_states = (
657
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
658
+ )
659
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
660
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
661
+
662
+ outputs = self.model(
663
+ input_ids=input_ids,
664
+ attention_mask=attention_mask,
665
+ position_ids=position_ids,
666
+ past_key_values=past_key_values,
667
+ inputs_embeds=inputs_embeds,
668
+ use_cache=use_cache,
669
+ output_attentions=output_attentions,
670
+ output_hidden_states=output_hidden_states,
671
+ return_dict=return_dict,
672
+ )
673
+
674
+ hidden_states = outputs[0]
675
+ if self.config.pretraining_tp > 1:
676
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
677
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
678
+ logits = torch.cat(logits, dim=-1)
679
+ else:
680
+ logits = self.lm_head(hidden_states)
681
+ logits = logits.float()
682
+
683
+ loss = None
684
+ if labels is not None:
685
+ labels = labels.to(logits.device)
686
+ # Shift so that tokens < n predict n
687
+ shift_logits = logits
688
+ shift_labels = labels
689
+ # Flatten the tokens
690
+ loss_fct = CrossEntropyLoss()
691
+ shift_logits = shift_logits.reshape(-1, self.config.vocab_size)
692
+ shift_labels = shift_labels.reshape(-1)
693
+ shift_tokens = input_ids.reshape(-1)
694
+ # compute loss
695
+ mask = (shift_labels < mask_init_id) & (shift_labels != pad_id) & (shift_labels != image_token_id) & (shift_labels != im_start_id) \
696
+ & (shift_labels != im_end_id) & (shift_labels != video_start_id) & (shift_labels != video_end_id) & (shift_tokens != pad_id) & (shift_tokens != eod_id)
697
+ shift_logits = shift_logits[mask, :]
698
+ shift_labels = shift_labels[mask]
699
+ loss = loss_fct(shift_logits, shift_labels)
700
+
701
+ if not return_dict:
702
+ output = (logits,) + outputs[1:]
703
+ return (loss,) + output if loss is not None else output
704
+
705
+ return CausalLMOutputWithPast(
706
+ loss=loss,
707
+ logits=logits,
708
+ past_key_values=outputs.past_key_values,
709
+ hidden_states=outputs.hidden_states,
710
+ attentions=outputs.attentions,
711
+ )
712
+
713
+ def prepare_inputs_for_generation(
714
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
715
+ ):
716
+ imgs = kwargs.pop("imgs", None)
717
+ imgs_pos = kwargs.pop("imgs_pos", None)
718
+ inputs = super().prepare_inputs_for_generation(
719
+ input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, **kwargs
720
+ )
721
+
722
+ if imgs is not None:
723
+ inputs['imgs'] = imgs
724
+ if imgs_pos is not None:
725
+ inputs['imgs_pos'] = imgs_pos
726
+ return inputs
727
+
728
+ @torch.no_grad()
729
+ def generate(
730
+ self,
731
+ inputs: Optional[torch.Tensor] = None,
732
+ attention_mask: Optional[torch.Tensor] = None,
733
+ position_ids: Optional[torch.LongTensor] = None,
734
+ imgs: Optional[List[torch.FloatTensor]] = None,
735
+ imgs_pos: Optional[List[int]] = None,
736
+ **kwargs,
737
+ ) -> Union[GenerateOutput, torch.LongTensor]:
738
+ if "inputs_embeds" in kwargs:
739
+ raise NotImplementedError("`inputs_embeds` is not supported")
740
+
741
+ if self.vit is not None:
742
+ encoder_input = self.model.embed_tokens(inputs)
743
+ if self.vit_type in ['NaVit', 'EvaVit', 'AnyResVit']:
744
+ inputs_embeds, input_ids = NaVitForward(inputs, encoder_input, self.vit, imgs, imgs_pos, self.config.vit_input_resolution, \
745
+ self.config.im_start_id, self.config.im_end_id, self.config.image_token_id, self.config.anyres_vit_two_views, self.config.torch_dtype)
746
+ else:
747
+ inputs_embeds, input_ids = VitForward(inputs, encoder_input, self.vit, self.vit_linear_encoder, imgs, imgs_pos, \
748
+ self.config.vit_input_resolution, self.config.vit_mapping_type, self.config.vit_patch, self.config.vit_token)
749
+
750
+ return super().generate(
751
+ inputs=input_ids,
752
+ position_ids=position_ids,
753
+ attention_mask=attention_mask,
754
+ inputs_embeds=inputs_embeds,
755
+ eos_token_id=self.config.eod_token_id,
756
+ **kwargs
757
+ )
758
+
759
+
760
+ @add_start_docstrings(
761
+ """
762
+ The HunYuan Model transformer with a sequence classification head on top (linear layer).
763
+
764
+ [`HunYuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models
765
+ (e.g. GPT-2) do.
766
+
767
+ Since it does classification on the last token, it requires to know the position of the last token. If a
768
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
769
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
770
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
771
+ each row of the batch).
772
+ """,
773
+ HUNYUAN_START_DOCSTRING,
774
+ )
775
+ class HunYuanForSequenceClassification(HunYuanPreTrainedModel):
776
+ def __init__(self, config):
777
+ super().__init__(config)
778
+ self.num_labels = config.num_labels
779
+ self.model = HunYuanModel(config)
780
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
781
+
782
+ # Initialize weights and apply final processing
783
+ self.post_init()
784
+
785
+ def get_input_embeddings(self):
786
+ return self.model.embed_tokens
787
+
788
+ def set_input_embeddings(self, value):
789
+ self.model.embed_tokens = value
790
+
791
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
792
+ def forward(
793
+ self,
794
+ input_ids: torch.LongTensor = None,
795
+ attention_mask: Optional[torch.Tensor] = None,
796
+ position_ids: Optional[torch.LongTensor] = None,
797
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
798
+ inputs_embeds: Optional[torch.FloatTensor] = None,
799
+ labels: Optional[torch.LongTensor] = None,
800
+ use_cache: Optional[bool] = None,
801
+ output_attentions: Optional[bool] = None,
802
+ output_hidden_states: Optional[bool] = None,
803
+ return_dict: Optional[bool] = None,
804
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
805
+ r"""
806
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
807
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
808
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
809
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
810
+ """
811
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
812
+
813
+ transformer_outputs = self.model(
814
+ input_ids,
815
+ attention_mask=attention_mask,
816
+ position_ids=position_ids,
817
+ past_key_values=past_key_values,
818
+ inputs_embeds=inputs_embeds,
819
+ use_cache=use_cache,
820
+ output_attentions=output_attentions,
821
+ output_hidden_states=output_hidden_states,
822
+ return_dict=return_dict,
823
+ )
824
+ hidden_states = transformer_outputs[0]
825
+ logits = self.score(hidden_states)
826
+
827
+ if input_ids is not None:
828
+ batch_size = input_ids.shape[0]
829
+ else:
830
+ batch_size = inputs_embeds.shape[0]
831
+
832
+ if self.config.pad_token_id is None and batch_size != 1:
833
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
834
+ if self.config.pad_token_id is None:
835
+ sequence_lengths = -1
836
+ else:
837
+ if input_ids is not None:
838
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
839
+ logits.device
840
+ )
841
+ else:
842
+ sequence_lengths = -1
843
+
844
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
845
+
846
+ loss = None
847
+ if labels is not None:
848
+ labels = labels.to(logits.device)
849
+ if self.config.problem_type is None:
850
+ if self.num_labels == 1:
851
+ self.config.problem_type = "regression"
852
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
853
+ self.config.problem_type = "single_label_classification"
854
+ else:
855
+ self.config.problem_type = "multi_label_classification"
856
+
857
+ if self.config.problem_type == "regression":
858
+ loss_fct = MSELoss()
859
+ if self.num_labels == 1:
860
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
861
+ else:
862
+ loss = loss_fct(pooled_logits, labels)
863
+ elif self.config.problem_type == "single_label_classification":
864
+ loss_fct = CrossEntropyLoss()
865
+ loss = loss_fct(pooled_logits.reshape(-1, self.num_labels), labels.reshape(-1))
866
+ elif self.config.problem_type == "multi_label_classification":
867
+ loss_fct = BCEWithLogitsLoss()
868
+ loss = loss_fct(pooled_logits, labels)
869
+ if not return_dict:
870
+ output = (pooled_logits,) + transformer_outputs[1:]
871
+ return ((loss,) + output) if loss is not None else output
872
+
873
+ return SequenceClassifierOutputWithPast(
874
+ loss=loss,
875
+ logits=pooled_logits,
876
+ past_key_values=transformer_outputs.past_key_values,
877
+ hidden_states=transformer_outputs.hidden_states,
878
+ attentions=transformer_outputs.attentions,
879
+ )
hy.tiktoken ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0403737be8ae02a16247b7c8e74b06256d82e86393bea8934fd4d4c7ccccf360
3
+ size 4969099160
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:999509aca71a5ed94988cbd91253e125e4bcaaffed1b2119e268801ebee176b7
3
+ size 822201896
model.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29ea5aaff3b1c520c12042af37db7ae48cc413a741026d787f8c736e5920199c
3
+ size 2900447776
model.safetensors.index.json ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 5791289344
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.mlp.experts.0.down_proj.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.experts.0.gate_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.experts.0.up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.mlp.experts.1.down_proj.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.mlp.experts.1.gate_proj.weight": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.mlp.experts.1.up_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.mlp.experts.2.down_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.mlp.experts.2.gate_proj.weight": "model-00001-of-00002.safetensors",
16
+ "model.layers.0.mlp.experts.2.up_proj.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.0.mlp.experts.3.down_proj.weight": "model-00001-of-00002.safetensors",
18
+ "model.layers.0.mlp.experts.3.gate_proj.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.0.mlp.experts.3.up_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.0.mlp.gate.wg.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.0.mlp.shared_mlp.down_proj.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.0.mlp.shared_mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.0.mlp.shared_mlp.up_proj.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.0.self_attn.key_layernorm.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.0.self_attn.query_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
31
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.1.mlp.experts.0.down_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.1.mlp.experts.0.gate_proj.weight": "model-00001-of-00002.safetensors",
34
+ "model.layers.1.mlp.experts.0.up_proj.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.1.mlp.experts.1.down_proj.weight": "model-00001-of-00002.safetensors",
36
+ "model.layers.1.mlp.experts.1.gate_proj.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.1.mlp.experts.1.up_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.1.mlp.experts.2.down_proj.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.1.mlp.experts.2.gate_proj.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.1.mlp.experts.2.up_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.1.mlp.experts.3.down_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.1.mlp.experts.3.gate_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.1.mlp.experts.3.up_proj.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.1.mlp.gate.wg.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.1.mlp.shared_mlp.down_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.1.mlp.shared_mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.1.mlp.shared_mlp.up_proj.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
49
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.1.self_attn.key_layernorm.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
52
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.1.self_attn.query_layernorm.weight": "model-00001-of-00002.safetensors",
54
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.2.mlp.experts.0.down_proj.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.2.mlp.experts.0.gate_proj.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.2.mlp.experts.0.up_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.2.mlp.experts.1.down_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.2.mlp.experts.1.gate_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.2.mlp.experts.1.up_proj.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.2.mlp.experts.2.down_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.2.mlp.experts.2.gate_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.2.mlp.experts.2.up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.2.mlp.experts.3.down_proj.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.2.mlp.experts.3.gate_proj.weight": "model-00001-of-00002.safetensors",
67
+ "model.layers.2.mlp.experts.3.up_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.2.mlp.gate.wg.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.2.mlp.shared_mlp.down_proj.weight": "model-00001-of-00002.safetensors",
70
+ "model.layers.2.mlp.shared_mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.2.mlp.shared_mlp.up_proj.weight": "model-00001-of-00002.safetensors",
72
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.2.self_attn.key_layernorm.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.2.self_attn.query_layernorm.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.3.input_layernorm.weight": "model-00002-of-00002.safetensors",
80
+ "model.layers.3.mlp.experts.0.down_proj.weight": "model-00002-of-00002.safetensors",
81
+ "model.layers.3.mlp.experts.0.gate_proj.weight": "model-00002-of-00002.safetensors",
82
+ "model.layers.3.mlp.experts.0.up_proj.weight": "model-00002-of-00002.safetensors",
83
+ "model.layers.3.mlp.experts.1.down_proj.weight": "model-00002-of-00002.safetensors",
84
+ "model.layers.3.mlp.experts.1.gate_proj.weight": "model-00002-of-00002.safetensors",
85
+ "model.layers.3.mlp.experts.1.up_proj.weight": "model-00002-of-00002.safetensors",
86
+ "model.layers.3.mlp.experts.2.down_proj.weight": "model-00002-of-00002.safetensors",
87
+ "model.layers.3.mlp.experts.2.gate_proj.weight": "model-00002-of-00002.safetensors",
88
+ "model.layers.3.mlp.experts.2.up_proj.weight": "model-00002-of-00002.safetensors",
89
+ "model.layers.3.mlp.experts.3.down_proj.weight": "model-00002-of-00002.safetensors",
90
+ "model.layers.3.mlp.experts.3.gate_proj.weight": "model-00002-of-00002.safetensors",
91
+ "model.layers.3.mlp.experts.3.up_proj.weight": "model-00002-of-00002.safetensors",
92
+ "model.layers.3.mlp.gate.wg.weight": "model-00002-of-00002.safetensors",
93
+ "model.layers.3.mlp.shared_mlp.down_proj.weight": "model-00002-of-00002.safetensors",
94
+ "model.layers.3.mlp.shared_mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
95
+ "model.layers.3.mlp.shared_mlp.up_proj.weight": "model-00002-of-00002.safetensors",
96
+ "model.layers.3.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
97
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.3.self_attn.key_layernorm.weight": "model-00002-of-00002.safetensors",
99
+ "model.layers.3.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
100
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.3.self_attn.query_layernorm.weight": "model-00002-of-00002.safetensors",
102
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
103
+ "model.norm.weight": "model-00002-of-00002.safetensors"
104
+ }
105
+ }
modeling_hunyuan.py ADDED
@@ -0,0 +1,1756 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ print(f"logits\n", logits)
78
+ print(f"gates\n", gates)
79
+ # expert_capacity = topk * gates.shape[0]
80
+ expert_capacity = max(topk, topk * gates.shape[0] // gates.shape[1])
81
+ num_experts = int(gates.shape[1])
82
+ # Top-k router probability and corresponding expert indices for each token.
83
+ # Shape: [tokens_per_group, num_selected_experts].
84
+ expert_gate, expert_index = torch.topk(gates, topk)
85
+ expert_mask = F.one_hot(expert_index, num_experts)
86
+ # For a given token, determine if it was routed to a given expert.
87
+ # Shape: [tokens_per_group, num_experts]
88
+ expert_mask_aux = expert_mask.max(dim=-2)[0]
89
+ tokens_per_group_and_expert = torch.mean(expert_mask_aux.float(), dim=-2)
90
+ router_prob_per_group_and_expert = torch.mean(gates.float(), dim=-2)
91
+ l_aux = num_experts**2 * torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert)
92
+ print(f"l_aux\n", l_aux)
93
+
94
+ gates_s = torch.clamp(
95
+ torch.matmul(expert_mask.float(), gates.unsqueeze(-1)).sum(dim=1), min=torch.finfo(gates.dtype).eps
96
+ )
97
+ print(f"gates_s\n", gates_s)
98
+ router_probs = gates / gates_s
99
+ print(f"router_probs\n", router_probs)
100
+ # Make num_selected_experts the leading axis to ensure that top-1 choices
101
+ # have priority over top-2 choices, which have priority over top-3 choices,
102
+ # etc.
103
+ expert_index = torch.transpose(expert_index, 0, 1)
104
+ # Shape: [num_selected_experts * tokens_per_group]
105
+ expert_index = expert_index.reshape(-1)
106
+
107
+ # Create mask out of indices.
108
+ # Shape: [tokens_per_group * num_selected_experts, num_experts].
109
+ expert_mask = F.one_hot(expert_index, num_experts).to(torch.int32)
110
+ exp_counts = torch.sum(expert_mask, dim=0).detach()
111
+
112
+ # Experts have a fixed capacity that we cannot exceed. A token's priority
113
+ # within the expert's buffer is given by the masked, cumulative capacity of
114
+ # its target expert.
115
+ # Shape: [tokens_per_group * num_selected_experts, num_experts].
116
+ token_priority = torch.cumsum(expert_mask, dim=0) * expert_mask - 1
117
+ # Shape: [num_selected_experts, tokens_per_group, num_experts].
118
+ token_priority = token_priority.reshape((topk, -1, num_experts))
119
+ # Shape: [tokens_per_group, num_selected_experts, num_experts].
120
+ token_priority = torch.transpose(token_priority, 0, 1)
121
+ # For each token, across all selected experts, select the only non-negative
122
+ # (unmasked) priority. Now, for group G routing to expert E, token T has
123
+ # non-negative priority (i.e. token_priority[G,T,E] >= 0) if and only if E
124
+ # is its targeted expert.
125
+ # Shape: [tokens_per_group, num_experts].
126
+ token_priority = torch.max(token_priority, dim=1)[0]
127
+ print(f"token_priority\n", token_priority)
128
+
129
+ # Token T can only be routed to expert E if its priority is positive and
130
+ # less than the expert capacity. One-hot matrix will ignore indices outside
131
+ # the range [0, expert_capacity).
132
+ # Shape: [tokens_per_group, num_experts, expert_capacity].
133
+ valid_mask = torch.logical_and(token_priority >= 0, token_priority < expert_capacity)
134
+ token_priority = torch.masked_fill(token_priority, ~valid_mask, 0)
135
+ dispatch_mask = F.one_hot(token_priority, expert_capacity).to(torch.bool)
136
+ valid_mask = valid_mask.unsqueeze(-1).expand(-1, -1, expert_capacity)
137
+ dispatch_mask = torch.masked_fill(dispatch_mask, ~valid_mask, 0)
138
+
139
+ # The combine array will be used for combining expert outputs, scaled by the
140
+ # router probabilities. Shape: [num_groups, tokens_per_group, num_experts,
141
+ # expert_capacity].
142
+ combine_weights = torch.einsum("...te,...tec->...tec", router_probs, dispatch_mask)
143
+ exp_counts_capacity = torch.sum(dispatch_mask)
144
+ exp_capacity_rate = exp_counts_capacity / (logits.shape[0]*topk)
145
+
146
+ return [l_aux, exp_capacity_rate], combine_weights, dispatch_mask, exp_counts
147
+
148
+
149
+ def top1gating(logits: Tensor, random_routing_dropped_token: bool = False):
150
+ """Implements Top1Gating on logits."""
151
+ # everything is in fp32 in this function
152
+ logits = logits.float()
153
+ gates = F.softmax(logits, dim=1)
154
+ capacity = gates.shape[0]
155
+
156
+ # Create a mask for 1st's expert per token
157
+ # noisy gating
158
+ indices1_s = torch.argmax(gates, dim=1)
159
+ num_experts = int(gates.shape[1])
160
+ mask1 = F.one_hot(indices1_s, num_classes=num_experts)
161
+
162
+ # gating decisions
163
+ # exp_counts = torch.sum(mask1, dim=0).detach().to('cpu')
164
+ exp_counts = torch.sum(mask1, dim=0).detach()
165
+
166
+ # Compute l_aux
167
+ me = torch.mean(gates, dim=0)
168
+ ce = torch.mean(mask1.float(), dim=0)
169
+ l_aux = torch.sum(me * ce) * num_experts
170
+ mask1_rand = mask1
171
+
172
+ top_idx = torch.topk(mask1_rand, k=capacity, dim=0)[1]
173
+
174
+ new_mask1 = mask1 * torch.zeros_like(mask1).scatter_(0, top_idx, 1)
175
+ mask1 = new_mask1
176
+ mask1_bk = mask1
177
+ if random_routing_dropped_token:
178
+ not_full = capacity - new_mask1.sum(dim=0)
179
+ sorted_notfull, indices_notfull = torch.sort(not_full, descending=True)
180
+ sorted_notfull = sorted_notfull.to(torch.int64)
181
+ not_full_experts_ids = torch.repeat_interleave(indices_notfull, sorted_notfull)
182
+ shuffle_not_full_ids = torch.randperm(not_full_experts_ids.shape[0])
183
+ not_full_experts_ids = not_full_experts_ids[shuffle_not_full_ids]
184
+ indices1_s_after_drop = torch.argmax(new_mask1, dim=1)
185
+ # get drop idx
186
+ drop_mask = 1 - new_mask1.sum(dim=1)
187
+ drop_mask = drop_mask.bool()
188
+ drop_idx = drop_mask.nonzero().view(-1)
189
+ drop_num = drop_mask.sum().to(torch.int64)
190
+ indices1_s_after_drop.scatter_(0, drop_idx, not_full_experts_ids[:drop_num])
191
+ nodrop_mask1 = F.one_hot(indices1_s_after_drop, num_classes=num_experts)
192
+ mask1 = nodrop_mask1
193
+
194
+ # Compute locations in capacity buffer
195
+ locations1 = torch.cumsum(mask1, dim=0) - 1
196
+
197
+ # Store the capacity location for each token
198
+ locations1_s = torch.sum(locations1 * mask1, dim=1)
199
+
200
+ # Normalize gate probabilities
201
+ mask1_float = mask1.float()
202
+ gates = gates * mask1_float
203
+
204
+ locations1_sc = F.one_hot(locations1_s, num_classes=capacity).float() # one hot to float
205
+ combine_weights = torch.einsum("se,sc->sec", gates, locations1_sc)
206
+
207
+ dispatch_mask = combine_weights.bool()
208
+
209
+ exp_counts_capacity = torch.sum(mask1_bk)
210
+ exp_capacity_rate = exp_counts_capacity / (logits.shape[0])
211
+ return [l_aux, exp_capacity_rate], combine_weights, dispatch_mask, exp_counts
212
+
213
+
214
+ def _get_unpad_data(attention_mask):
215
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
216
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
217
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
218
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
219
+ return (
220
+ indices,
221
+ cu_seqlens,
222
+ max_seqlen_in_batch,
223
+ )
224
+
225
+
226
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
227
+ warnings.warn(
228
+ "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be "
229
+ "removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
230
+ )
231
+ return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
232
+
233
+
234
+ def _make_causal_mask(
235
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
236
+ ):
237
+ warnings.warn(
238
+ "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in "
239
+ "v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
240
+ )
241
+ return AttentionMaskConverter._make_causal_mask(
242
+ input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
243
+ )
244
+
245
+
246
+ class HunYuanRMSNorm(nn.Module):
247
+ def __init__(self, hidden_size, eps=1e-6):
248
+ """
249
+ HunYuanRMSNorm is equivalent to T5LayerNorm
250
+ """
251
+ super().__init__()
252
+ self.weight = nn.Parameter(torch.ones(hidden_size))
253
+ self.variance_epsilon = eps
254
+
255
+ def forward(self, hidden_states):
256
+ input_dtype = hidden_states.dtype
257
+ hidden_states = hidden_states.to(torch.float32)
258
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
259
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
260
+ return self.weight * hidden_states.to(input_dtype)
261
+
262
+
263
+ ALL_LAYERNORM_LAYERS.append(HunYuanRMSNorm)
264
+
265
+
266
+ class HunYuanRotaryEmbedding(nn.Module):
267
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
268
+ super().__init__()
269
+
270
+ self.dim = dim
271
+ self.max_position_embeddings = max_position_embeddings
272
+ self.base = base
273
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
274
+ # inv_freq = inv_freq.bfloat16()
275
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
276
+
277
+ # Build here to make `torch.jit.trace` work.
278
+ self._set_cos_sin_cache(
279
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
280
+ )
281
+
282
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
283
+ self.max_seq_len_cached = seq_len
284
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
285
+
286
+ self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
287
+ freqs = torch.outer(t, self.inv_freq)
288
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
289
+ emb = torch.cat((freqs, freqs), dim=-1).float()
290
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
291
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
292
+
293
+ def forward(self, x, seq_len=None):
294
+ # x: [bs, num_attention_heads, seq_len, head_size]
295
+ if seq_len > self.max_seq_len_cached or self.inv_freq.dtype != torch.float32:
296
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
297
+
298
+ return (
299
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
300
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
301
+ )
302
+
303
+
304
+ class HunYuanLinearScalingRotaryEmbedding(HunYuanRotaryEmbedding):
305
+ """HunYuanRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
306
+
307
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
308
+ self.scaling_factor = scaling_factor
309
+ super().__init__(dim, max_position_embeddings, base, device)
310
+
311
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
312
+ self.max_seq_len_cached = seq_len
313
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
314
+ t = t / self.scaling_factor
315
+
316
+ freqs = torch.outer(t, self.inv_freq)
317
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
318
+ emb = torch.cat((freqs, freqs), dim=-1)
319
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
320
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
321
+
322
+
323
+ class HunYuanDynamicNTKScalingRotaryEmbedding(HunYuanRotaryEmbedding):
324
+ """
325
+ HunYuanRotaryEmbedding extended with Dynamic NTK scaling.
326
+ Credits to the Reddit users /u/bloc97 and /u/emozilla
327
+ """
328
+
329
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
330
+ self.scaling_factor = scaling_factor
331
+ super().__init__(dim, max_position_embeddings, base, device)
332
+
333
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
334
+ self.max_seq_len_cached = seq_len
335
+
336
+ if seq_len > self.max_position_embeddings:
337
+ base = self.base * (
338
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
339
+ ) ** (self.dim / (self.dim - 2))
340
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
341
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
342
+
343
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
344
+
345
+ freqs = torch.outer(t, self.inv_freq)
346
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
347
+ emb = torch.cat((freqs, freqs), dim=-1)
348
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
349
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
350
+
351
+
352
+ class HunYuanDynamicNTKAlphaRotaryEmbedding(HunYuanRotaryEmbedding):
353
+ """
354
+ HunYuanRotaryEmbedding extended with Dynamic NTK scaling.
355
+ Credits to the Reddit users /u/bloc97 and /u/emozilla
356
+ """
357
+
358
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_alpha=1.0):
359
+ self.scaling_alpha = scaling_alpha
360
+ super().__init__(dim, max_position_embeddings, base, device)
361
+
362
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
363
+ self.max_seq_len_cached = seq_len
364
+ base = self.base * self.scaling_alpha ** (self.dim / (self.dim-2))
365
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
366
+
367
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
368
+
369
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
370
+
371
+ freqs = torch.outer(t, self.inv_freq)
372
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
373
+ emb = torch.cat((freqs, freqs), dim=-1)
374
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
375
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
376
+
377
+
378
+ def rotate_half(x):
379
+ """Rotates half the hidden dims of the input."""
380
+ x1 = x[..., : x.shape[-1] // 2]
381
+ x2 = x[..., x.shape[-1] // 2:]
382
+ return torch.cat((-x2, x1), dim=-1)
383
+
384
+
385
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
386
+ """Applies Rotary Position Embedding to the query and key tensors.
387
+
388
+ Args:
389
+ q (`torch.Tensor`): The query tensor.
390
+ k (`torch.Tensor`): The key tensor.
391
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
392
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
393
+ position_ids (`torch.Tensor`):
394
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
395
+ used to pass offsetted position ids when working with a KV-cache.
396
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
397
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
398
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
399
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
400
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
401
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
402
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
403
+ Returns:
404
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
405
+ """
406
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
407
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
408
+ q_embed = (q * cos) + (rotate_half(q) * sin)
409
+ k_embed = (k * cos) + (rotate_half(k) * sin)
410
+ return q_embed, k_embed
411
+
412
+
413
+ class HunYuanMLP(nn.Module):
414
+ def __init__(self, config: HunYuanConfig, layer_idx=None, is_shared_mlp=False):
415
+ super().__init__()
416
+ self.config = config
417
+ self.layer_idx = layer_idx
418
+ self.hidden_size = config.hidden_size
419
+ if is_shared_mlp:
420
+ self.intermediate_size = config.intermediate_size * config.num_shared_expert[0]
421
+ else:
422
+ self.intermediate_size = config.intermediate_size
423
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
424
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
425
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
426
+ self.act_fn = ACT2FN[config.hidden_act]
427
+
428
+ def forward(self, x):
429
+ if self.config.pretraining_tp > 1:
430
+ slice = self.intermediate_size // self.config.pretraining_tp
431
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
432
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
433
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
434
+
435
+ gate_proj = torch.cat(
436
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
437
+ )
438
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
439
+
440
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
441
+ down_proj = [
442
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
443
+ ]
444
+ down_proj = sum(down_proj)
445
+ else:
446
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
447
+
448
+ return down_proj
449
+
450
+
451
+ class HunYuanTopKGate(nn.Module):
452
+ def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):
453
+ super().__init__()
454
+ self.config = config
455
+ self.layer_idx = layer_idx
456
+ self.moe_topk = config.moe_topk
457
+ self.drop_tokens = config.moe_drop_tokens
458
+ self.min_capacity = 8
459
+ self.random_routing_dropped_token = config.moe_random_routing_dropped_token
460
+ self.wg = nn.Linear(config.hidden_size, config.num_experts, bias=False, dtype=torch.float32)
461
+
462
+ def forward(self, hidden_states):
463
+ bsz, seq_len, hidden_size = hidden_states.shape
464
+ hidden_states = hidden_states.reshape(-1, hidden_size)
465
+ if self.wg.weight.dtype == torch.float32:
466
+ hidden_states = hidden_states.float()
467
+ logits = self.wg(hidden_states)
468
+ if self.moe_topk == 1:
469
+ gate_output = top1gating(logits, random_routing_dropped_token=self.random_routing_dropped_token)
470
+ else:
471
+ gate_output = topkgating(logits, self.moe_topk[0])
472
+
473
+ return gate_output
474
+
475
+
476
+ class HunYuanMoE(nn.Module):
477
+ def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):
478
+ super().__init__()
479
+ self.config = config
480
+ self.layer_idx = layer_idx
481
+ self.moe_topk = config.moe_topk
482
+ self.num_experts = config.num_experts
483
+ if config.use_mixed_mlp_moe:
484
+ self.shared_mlp = HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=True)
485
+ self.gate = HunYuanTopKGate(config, layer_idx=layer_idx)
486
+ self.experts = nn.ModuleList(
487
+ [HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=False) for _ in range(config.num_experts)]
488
+ )
489
+
490
+ def forward(self, hidden_states):
491
+ bsz, seq_len, hidden_size = hidden_states.shape
492
+
493
+ if self.config.use_mixed_mlp_moe:
494
+ hidden_states_mlp = self.shared_mlp(hidden_states)
495
+
496
+ l_moe, combine_weights, dispatch_mask, exp_counts = self.gate(hidden_states)
497
+
498
+ reshaped_input = hidden_states.reshape(-1, hidden_size)
499
+
500
+ dispatched_input = torch.einsum("sec,sm->ecm", dispatch_mask.type_as(hidden_states), reshaped_input)
501
+ print(f"combine_weights\n", combine_weights)
502
+ print(f"dispatch_mask\n", dispatch_mask)
503
+ print(f"dispatched_input\n", dispatched_input)
504
+
505
+ chunks = dispatched_input.chunk(self.num_experts, dim=0)
506
+ expert_outputs = []
507
+ for chunk, expert in zip(chunks, self.experts):
508
+ expert_outputs.append(expert(chunk))
509
+
510
+ expert_output = torch.cat(expert_outputs, dim=0)
511
+ combined_output = torch.einsum("sec,ecm->sm", combine_weights.type_as(hidden_states), expert_output)
512
+ combined_output = combined_output.reshape(bsz, seq_len, hidden_size)
513
+
514
+ if self.config.use_mixed_mlp_moe:
515
+ print(f"mlp out\n", hidden_states_mlp)
516
+ print(f"moe out\n", combined_output)
517
+ output = hidden_states_mlp + combined_output
518
+ else:
519
+ output = combined_output
520
+
521
+ return output
522
+
523
+
524
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
525
+ """
526
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
527
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
528
+ """
529
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
530
+ if n_rep == 1:
531
+ return hidden_states
532
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
533
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
534
+
535
+
536
+ class HunYuanAttention(nn.Module):
537
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
538
+
539
+ def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):
540
+ super().__init__()
541
+ self.config = config
542
+ self.layer_idx = layer_idx
543
+ # layer_idx 从 0 开始
544
+ self.attention_type = 'cross' if config.use_cla and layer_idx % config.cla_share_factor != 0 else 'self'
545
+ if layer_idx is None:
546
+ logger.warning_once(
547
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
548
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
549
+ "when creating this class."
550
+ )
551
+
552
+ self.attention_dropout = config.attention_dropout
553
+ self.hidden_size = config.hidden_size
554
+ self.num_heads = config.num_attention_heads
555
+ self.head_dim = self.hidden_size // self.num_heads
556
+ self.num_key_value_heads = config.num_key_value_heads
557
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
558
+ self.max_position_embeddings = config.max_position_embeddings
559
+ self.rope_theta = config.rope_theta
560
+ self.is_causal = True
561
+ self.use_qk_norm = config.use_qk_norm
562
+
563
+ if (self.head_dim * self.num_heads) != self.hidden_size:
564
+ raise ValueError(
565
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
566
+ f" and `num_heads`: {self.num_heads})."
567
+ )
568
+
569
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
570
+ if self.attention_type == 'self':
571
+ self.k_proj = nn.Linear(
572
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
573
+ )
574
+ self.v_proj = nn.Linear(
575
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias
576
+ )
577
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
578
+ if self.use_qk_norm:
579
+ self.query_layernorm = HunYuanRMSNorm(self.head_dim, eps=config.rms_norm_eps)
580
+ self.key_layernorm = HunYuanRMSNorm(self.head_dim, eps=config.rms_norm_eps)
581
+ self._init_rope()
582
+
583
+ def _init_rope(self):
584
+ if self.config.rope_scaling is None:
585
+ self.rotary_emb = HunYuanRotaryEmbedding(
586
+ self.head_dim,
587
+ max_position_embeddings=self.max_position_embeddings,
588
+ base=self.rope_theta,
589
+ )
590
+ else:
591
+ scaling_type = self.config.rope_scaling["type"]
592
+ scaling_factor = self.config.rope_scaling["factor"]
593
+ scaling_alpha = self.config.rope_scaling["alpha"]
594
+ if scaling_type == "linear":
595
+ self.rotary_emb = HunYuanLinearScalingRotaryEmbedding(
596
+ self.head_dim,
597
+ max_position_embeddings=self.max_position_embeddings,
598
+ scaling_factor=scaling_factor,
599
+ base=self.rope_theta,
600
+ )
601
+ elif scaling_type == "dynamic":
602
+ if scaling_alpha:
603
+ self.rotary_emb = HunYuanDynamicNTKAlphaRotaryEmbedding(
604
+ self.head_dim,
605
+ max_position_embeddings=self.max_position_embeddings,
606
+ scaling_alpha=scaling_alpha,
607
+ base=self.rope_theta,
608
+ )
609
+ else:
610
+ self.rotary_emb = HunYuanDynamicNTKScalingRotaryEmbedding(
611
+ self.head_dim,
612
+ max_position_embeddings=self.max_position_embeddings,
613
+ scaling_factor=scaling_factor,
614
+ base=self.rope_theta,
615
+ )
616
+ else:
617
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
618
+
619
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
620
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
621
+
622
+ def forward(
623
+ self,
624
+ hidden_states: torch.Tensor,
625
+ attention_mask: Optional[torch.Tensor] = None,
626
+ position_ids: Optional[torch.LongTensor] = None,
627
+ past_key_value: Optional[Cache] = None,
628
+ output_attentions: bool = False,
629
+ use_cache: bool = False,
630
+ kv_states: torch.Tensor = None,
631
+ **kwargs,
632
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
633
+ if "padding_mask" in kwargs:
634
+ warnings.warn(
635
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use "
636
+ "`attention_mask` instead.`"
637
+ )
638
+
639
+ bsz, q_len, _ = hidden_states.size()
640
+
641
+ if self.config.pretraining_tp > 1:
642
+ query_slices = self.q_proj.weight.split(
643
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
644
+ )
645
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
646
+ query_states = torch.cat(query_states, dim=-1)
647
+
648
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
649
+ orig_key_states, orig_value_states = kv_states
650
+ key_states, value_states = kv_states
651
+ else:
652
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
653
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
654
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
655
+
656
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
657
+ key_states = torch.cat(key_states, dim=-1)
658
+
659
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
660
+ value_states = torch.cat(value_states, dim=-1)
661
+ orig_key_states, orig_value_states = key_states, value_states
662
+
663
+ else:
664
+ query_states = self.q_proj(hidden_states)
665
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
666
+ orig_key_states, orig_value_states = kv_states
667
+ key_states, value_states = kv_states
668
+ else:
669
+ key_states = self.k_proj(hidden_states)
670
+ value_states = self.v_proj(hidden_states)
671
+ orig_key_states, orig_value_states = key_states, value_states
672
+
673
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
674
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
675
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
676
+
677
+ kv_seq_len = key_states.shape[-2]
678
+ if past_key_value is not None:
679
+ if self.layer_idx is None:
680
+ raise ValueError(
681
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
682
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
683
+ "with a layer index."
684
+ )
685
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
686
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
687
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
688
+
689
+ print(f"query_states\n", query_states)
690
+ print(f"key_states\n", key_states)
691
+
692
+ if self.use_qk_norm:
693
+ query_states = self.query_layernorm(query_states)
694
+ key_states = self.key_layernorm(key_states)
695
+
696
+ print(f"query_states_normed\n", query_states)
697
+ print(f"key_states_normed\n", key_states)
698
+
699
+ if past_key_value is not None:
700
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
701
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
702
+
703
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
704
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
705
+
706
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
707
+
708
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
709
+ raise ValueError(
710
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
711
+ f" {attn_weights.size()}"
712
+ )
713
+
714
+ if attention_mask is not None:
715
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
716
+ raise ValueError(
717
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
718
+ )
719
+ attn_weights = attn_weights + attention_mask
720
+
721
+ # upcast attention to fp32
722
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
723
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
724
+ attn_output = torch.matmul(attn_weights, value_states)
725
+
726
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
727
+ raise ValueError(
728
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
729
+ f" {attn_output.size()}"
730
+ )
731
+
732
+ attn_output = attn_output.transpose(1, 2).contiguous()
733
+
734
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
735
+
736
+ if self.config.pretraining_tp > 1:
737
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
738
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
739
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
740
+ else:
741
+ attn_output = self.o_proj(attn_output)
742
+
743
+ if not output_attentions:
744
+ attn_weights = None
745
+
746
+ return attn_output, attn_weights, past_key_value, (orig_key_states, orig_value_states)
747
+
748
+
749
+ class HunYuanFlashAttention2(HunYuanAttention):
750
+ """
751
+ HunYuan flash attention module. This module inherits from `HunYuanAttention` as the weights of the module stays
752
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
753
+ flash attention and deal with padding tokens in case the input contains any of them.
754
+ """
755
+
756
+ def __init__(self, *args, **kwargs):
757
+ super().__init__(*args, **kwargs)
758
+
759
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
760
+
761
+ def forward(
762
+ self,
763
+ hidden_states: torch.Tensor,
764
+ attention_mask: Optional[torch.LongTensor] = None,
765
+ position_ids: Optional[torch.LongTensor] = None,
766
+ past_key_value: Optional[Cache] = None,
767
+ output_attentions: bool = False,
768
+ use_cache: bool = False,
769
+ kv_states: torch.Tensor = None,
770
+ **kwargs,
771
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
772
+ # HunYuanFlashAttention2 attention does not support output_attentions
773
+ if "padding_mask" in kwargs:
774
+ warnings.warn(
775
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use "
776
+ "`attention_mask` instead.`"
777
+ )
778
+
779
+ # overwrite attention_mask with padding_mask
780
+ attention_mask = kwargs.pop("padding_mask")
781
+
782
+ bsz, q_len, _ = hidden_states.size()
783
+
784
+ query_states = self.q_proj(hidden_states)
785
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
786
+ orig_key_states, orig_value_states = kv_states
787
+ key_states, value_states = kv_states
788
+ else:
789
+ key_states = self.k_proj(hidden_states)
790
+ value_states = self.v_proj(hidden_states)
791
+ orig_key_states, orig_value_states = key_states, value_states
792
+
793
+ # Flash attention requires the input to have the shape
794
+ # batch_size x seq_length x head_dim x hidden_dim
795
+ # therefore we just need to keep the original shape
796
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
797
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
798
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
799
+
800
+ kv_seq_len = key_states.shape[-2]
801
+ if past_key_value is not None:
802
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
803
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
804
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
805
+
806
+ if self.use_qk_norm:
807
+ query_states = self.query_layernorm(query_states)
808
+ key_states = self.key_layernorm(key_states)
809
+
810
+ if past_key_value is not None:
811
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
812
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
813
+
814
+ query_states = query_states.transpose(1, 2)
815
+ key_states = key_states.transpose(1, 2)
816
+ value_states = value_states.transpose(1, 2)
817
+
818
+ dropout_rate = self.attention_dropout if self.training else 0.0
819
+
820
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
821
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
822
+ # cast them back in the correct dtype just to be sure everything works as expected.
823
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
824
+ # in fp32. (HunYuanRMSNorm handles it correctly)
825
+
826
+ input_dtype = query_states.dtype
827
+ if input_dtype == torch.float32:
828
+ # Handle the case where the model is quantized
829
+ if hasattr(self.config, "_pre_quantization_dtype"):
830
+ target_dtype = self.config._pre_quantization_dtype
831
+ else:
832
+ target_dtype = self.q_proj.weight.dtype
833
+
834
+ logger.warning_once(
835
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
836
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
837
+ f" {target_dtype}."
838
+ )
839
+
840
+ query_states = query_states.to(target_dtype)
841
+ key_states = key_states.to(target_dtype)
842
+ value_states = value_states.to(target_dtype)
843
+
844
+ attn_output = self._flash_attention_forward(
845
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
846
+ )
847
+
848
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
849
+ attn_output = self.o_proj(attn_output)
850
+
851
+ return attn_output, None, past_key_value, (orig_key_states, orig_value_states)
852
+
853
+ def _flash_attention_forward(
854
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
855
+ ):
856
+ """
857
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
858
+ first unpad the input, then computes the attention scores and pad the final attention scores.
859
+
860
+ Args:
861
+ query_states (`torch.Tensor`):
862
+ Input query states to be passed to Flash Attention API
863
+ key_states (`torch.Tensor`):
864
+ Input key states to be passed to Flash Attention API
865
+ value_states (`torch.Tensor`):
866
+ Input value states to be passed to Flash Attention API
867
+ attention_mask (`torch.Tensor`):
868
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
869
+ position of padding tokens and 1 for the position of non-padding tokens.
870
+ dropout (`int`, *optional*):
871
+ Attention dropout
872
+ softmax_scale (`float`, *optional*):
873
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
874
+ """
875
+ if not self._flash_attn_uses_top_left_mask:
876
+ causal = self.is_causal
877
+ else:
878
+ causal = self.is_causal and query_length != 1
879
+
880
+ # Contains at least one padding token in the sequence
881
+ if attention_mask is not None:
882
+ batch_size = query_states.shape[0]
883
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
884
+ query_states, key_states, value_states, attention_mask, query_length
885
+ )
886
+
887
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
888
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
889
+
890
+ attn_output_unpad = flash_attn_varlen_func(
891
+ query_states,
892
+ key_states,
893
+ value_states,
894
+ cu_seqlens_q=cu_seqlens_q,
895
+ cu_seqlens_k=cu_seqlens_k,
896
+ max_seqlen_q=max_seqlen_in_batch_q,
897
+ max_seqlen_k=max_seqlen_in_batch_k,
898
+ dropout_p=dropout,
899
+ softmax_scale=softmax_scale,
900
+ causal=causal,
901
+ )
902
+
903
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
904
+ else:
905
+ attn_output = flash_attn_func(
906
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
907
+ )
908
+
909
+ return attn_output
910
+
911
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
912
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
913
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
914
+
915
+ key_layer = index_first_axis(
916
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
917
+ )
918
+ value_layer = index_first_axis(
919
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
920
+ )
921
+ if query_length == kv_seq_len:
922
+ query_layer = index_first_axis(
923
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
924
+ )
925
+ cu_seqlens_q = cu_seqlens_k
926
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
927
+ indices_q = indices_k
928
+ elif query_length == 1:
929
+ max_seqlen_in_batch_q = 1
930
+ cu_seqlens_q = torch.arange(
931
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
932
+ ) # There is a memcpy here, that is very bad.
933
+ indices_q = cu_seqlens_q[:-1]
934
+ query_layer = query_layer.squeeze(1)
935
+ else:
936
+ # The -q_len: slice assumes left padding.
937
+ attention_mask = attention_mask[:, -query_length:]
938
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
939
+
940
+ return (
941
+ query_layer,
942
+ key_layer,
943
+ value_layer,
944
+ indices_q,
945
+ (cu_seqlens_q, cu_seqlens_k),
946
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
947
+ )
948
+
949
+
950
+ class HunYuanSdpaAttention(HunYuanAttention):
951
+ """
952
+ HunYuan attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
953
+ `HunYuanAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt
954
+ to SDPA API.
955
+ """
956
+
957
+ # Adapted from HunYuanAttention.forward
958
+ def forward(
959
+ self,
960
+ hidden_states: torch.Tensor,
961
+ attention_mask: Optional[torch.Tensor] = None,
962
+ position_ids: Optional[torch.LongTensor] = None,
963
+ past_key_value: Optional[Cache] = None,
964
+ output_attentions: bool = False,
965
+ use_cache: bool = False,
966
+ kv_states: torch.Tensor = None,
967
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
968
+ if output_attentions:
969
+ logger.warning_once(
970
+ 'HunYuanModel is using HunYuanSdpaAttention,'
971
+ 'but `torch.nn.functional.scaled_dot_product_attention`'
972
+ 'does not support `output_attentions=True`. Falling back to the manual attention implementation, '
973
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. '
974
+ 'This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
975
+ )
976
+ return super().forward(
977
+ hidden_states=hidden_states,
978
+ attention_mask=attention_mask,
979
+ position_ids=position_ids,
980
+ past_key_value=past_key_value,
981
+ output_attentions=output_attentions,
982
+ use_cache=use_cache,
983
+ )
984
+
985
+ bsz, q_len, _ = hidden_states.size()
986
+
987
+ query_states = self.q_proj(hidden_states)
988
+ if self.attention_type == "cross" and kv_states is not None and isinstance(kv_states, tuple):
989
+ orig_key_states, orig_value_states = kv_states
990
+ key_states, value_states = kv_states
991
+ else:
992
+ key_states = self.k_proj(hidden_states)
993
+ value_states = self.v_proj(hidden_states)
994
+ orig_key_states, orig_value_states = key_states, value_states
995
+
996
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
997
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
998
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
999
+
1000
+ kv_seq_len = key_states.shape[-2]
1001
+ if past_key_value is not None:
1002
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
1003
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
1004
+
1005
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
1006
+
1007
+ if self.use_qk_norm:
1008
+ query_states = self.query_layernorm(query_states)
1009
+ key_states = self.key_layernorm(key_states)
1010
+
1011
+ if past_key_value is not None:
1012
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
1013
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
1014
+
1015
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1016
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1017
+
1018
+ if attention_mask is not None:
1019
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
1020
+ raise ValueError(
1021
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
1022
+ )
1023
+
1024
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with
1025
+ # custom attn_mask,
1026
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1027
+ if query_states.device.type == "cuda" and attention_mask is not None:
1028
+ query_states = query_states.contiguous()
1029
+ key_states = key_states.contiguous()
1030
+ value_states = value_states.contiguous()
1031
+
1032
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1033
+ query_states,
1034
+ key_states,
1035
+ value_states,
1036
+ attn_mask=attention_mask,
1037
+ dropout_p=self.attention_dropout if self.training else 0.0,
1038
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a
1039
+ # causal mask in case q_len == 1.
1040
+ is_causal=self.is_causal and attention_mask is None and q_len > 1,
1041
+ )
1042
+
1043
+ attn_output = attn_output.transpose(1, 2).contiguous()
1044
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
1045
+
1046
+ attn_output = self.o_proj(attn_output)
1047
+
1048
+ return attn_output, None, past_key_value, (orig_key_states, orig_value_states)
1049
+
1050
+
1051
+ HUNYUAN_ATTENTION_CLASSES = {
1052
+ "eager": HunYuanAttention,
1053
+ "flash_attention_2": HunYuanFlashAttention2,
1054
+ "sdpa": HunYuanSdpaAttention,
1055
+ }
1056
+
1057
+
1058
+ class HunYuanDecoderLayer(nn.Module):
1059
+ def __init__(self, config: HunYuanConfig, layer_idx: int):
1060
+ super().__init__()
1061
+ self.hidden_size = config.hidden_size
1062
+ self.layer_idx = layer_idx
1063
+
1064
+ #self.self_attn = HUNYUAN_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
1065
+ self.self_attn = HunYuanAttention(config=config, layer_idx=layer_idx)
1066
+
1067
+ if config.num_experts > 1:
1068
+ self.mlp = HunYuanMoE(config, layer_idx=layer_idx)
1069
+ else:
1070
+ self.mlp = HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=False)
1071
+ self.input_layernorm = HunYuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1072
+ self.post_attention_layernorm = HunYuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1073
+
1074
+ def forward(
1075
+ self,
1076
+ hidden_states: torch.Tensor,
1077
+ attention_mask: Optional[torch.Tensor] = None,
1078
+ position_ids: Optional[torch.LongTensor] = None,
1079
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
1080
+ output_attentions: Optional[bool] = False,
1081
+ use_cache: Optional[bool] = False,
1082
+ kv_states: Optional[Tuple[torch.Tensor]] = None,
1083
+ **kwargs,
1084
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
1085
+ """
1086
+ Args:
1087
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1088
+ attention_mask (`torch.FloatTensor`, *optional*):
1089
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
1090
+ query_sequence_length, key_sequence_length)` if default attention is used.
1091
+ output_attentions (`bool`, *optional*):
1092
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1093
+ returned tensors for more detail.
1094
+ use_cache (`bool`, *optional*):
1095
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1096
+ (see `past_key_values`).
1097
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
1098
+ kv_states (`Tuple(torch.FloatTensor)`, *optional*): Used when CLA is enabled,
1099
+ key and value states from past attention blocks
1100
+ """
1101
+ if "padding_mask" in kwargs:
1102
+ warnings.warn(
1103
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use "
1104
+ "`attention_mask` instead.`"
1105
+ )
1106
+
1107
+ residual = hidden_states
1108
+
1109
+ hidden_states = self.input_layernorm(hidden_states)
1110
+
1111
+ print(f"Layer {self.layer_idx}\n", hidden_states)
1112
+
1113
+ # Self Attention
1114
+ hidden_states, self_attn_weights, present_key_value, kv_states = self.self_attn(
1115
+ hidden_states=hidden_states,
1116
+ attention_mask=attention_mask,
1117
+ position_ids=position_ids,
1118
+ past_key_value=past_key_value,
1119
+ output_attentions=output_attentions,
1120
+ use_cache=use_cache,
1121
+ kv_states=kv_states,
1122
+ **kwargs,
1123
+ )
1124
+ print(f"Layer {self.layer_idx} self_attn output\n", hidden_states)
1125
+ hidden_states = residual + hidden_states
1126
+
1127
+ # Fully Connected
1128
+ residual = hidden_states
1129
+ hidden_states = self.post_attention_layernorm(hidden_states)
1130
+ hidden_states = self.mlp(hidden_states)
1131
+ print(f"Layer {self.layer_idx} mlp output\n", hidden_states)
1132
+ hidden_states = residual + hidden_states
1133
+
1134
+ print(f"Layer {self.layer_idx} final output\n", hidden_states)
1135
+
1136
+ exit(0)
1137
+
1138
+ outputs = (hidden_states,)
1139
+
1140
+ if output_attentions:
1141
+ outputs += (self_attn_weights,)
1142
+
1143
+ if use_cache:
1144
+ outputs += (present_key_value,)
1145
+
1146
+ outputs += (kv_states,)
1147
+
1148
+ return outputs
1149
+
1150
+
1151
+ HUNYUAN_START_DOCSTRING = r"""
1152
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1153
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1154
+ etc.)
1155
+
1156
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1157
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1158
+ and behavior.
1159
+
1160
+ Parameters:
1161
+ config ([`HunYuanConfig`]):
1162
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
1163
+ load the weights associated with the model, only the configuration. Check out the
1164
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1165
+ """
1166
+
1167
+
1168
+ @add_start_docstrings(
1169
+ "The bare HunYuan Model outputting raw hidden-states without any specific head on top.",
1170
+ HUNYUAN_START_DOCSTRING,
1171
+ )
1172
+ class HunYuanPreTrainedModel(PreTrainedModel):
1173
+ config_class = HunYuanConfig
1174
+ base_model_prefix = "model"
1175
+ supports_gradient_checkpointing = True
1176
+ _no_split_modules = ["HunYuanDecoderLayer"]
1177
+ _skip_keys_device_placement = "past_key_values"
1178
+ _supports_flash_attn_2 = True
1179
+ _supports_sdpa = True
1180
+ _supports_cache_class = True
1181
+
1182
+ def _init_weights(self, module):
1183
+ std = self.config.initializer_range
1184
+ if isinstance(module, nn.Linear):
1185
+ module.weight.data.normal_(mean=0.0, std=std)
1186
+ if module.bias is not None:
1187
+ module.bias.data.zero_()
1188
+ elif isinstance(module, nn.Embedding):
1189
+ module.weight.data.normal_(mean=0.0, std=std)
1190
+ if module.padding_idx is not None:
1191
+ module.weight.data[module.padding_idx].zero_()
1192
+
1193
+
1194
+ HUNYUAN_INPUTS_DOCSTRING = r"""
1195
+ Args:
1196
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1197
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
1198
+ it.
1199
+
1200
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1201
+ [`PreTrainedTokenizer.__call__`] for details.
1202
+
1203
+ [What are input IDs?](../glossary#input-ids)
1204
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1205
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1206
+
1207
+ - 1 for tokens that are **not masked**,
1208
+ - 0 for tokens that are **masked**.
1209
+
1210
+ [What are attention masks?](../glossary#attention-mask)
1211
+
1212
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1213
+ [`PreTrainedTokenizer.__call__`] for details.
1214
+
1215
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
1216
+ `past_key_values`).
1217
+
1218
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
1219
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
1220
+ information on the default strategy.
1221
+
1222
+ - 1 indicates the head is **not masked**,
1223
+ - 0 indicates the head is **masked**.
1224
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1225
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1226
+ config.n_positions - 1]`.
1227
+
1228
+ [What are position IDs?](../glossary#position-ids)
1229
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
1230
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
1231
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
1232
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
1233
+
1234
+ Two formats are allowed:
1235
+ - a [`~cache_utils.Cache`] instance;
1236
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1237
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
1238
+ cache format.
1239
+
1240
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
1241
+ legacy cache format will be returned.
1242
+
1243
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
1244
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
1245
+ of shape `(batch_size, sequence_length)`.
1246
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1247
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1248
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1249
+ model's internal embedding lookup matrix.
1250
+ use_cache (`bool`, *optional*):
1251
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
1252
+ `past_key_values`).
1253
+ output_attentions (`bool`, *optional*):
1254
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
1255
+ tensors for more detail.
1256
+ output_hidden_states (`bool`, *optional*):
1257
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1258
+ more detail.
1259
+ return_dict (`bool`, *optional*):
1260
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1261
+ """
1262
+
1263
+
1264
+ @add_start_docstrings(
1265
+ "The bare HunYuan Model outputting raw hidden-states without any specific head on top.",
1266
+ HUNYUAN_START_DOCSTRING,
1267
+ )
1268
+ class HunYuanModel(HunYuanPreTrainedModel):
1269
+ """
1270
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`HunYuanDecoderLayer`]
1271
+
1272
+ Args:
1273
+ config: HunYuanConfig
1274
+ """
1275
+
1276
+ def __init__(self, config: HunYuanConfig):
1277
+ super().__init__(config)
1278
+ self.padding_idx = config.pad_token_id
1279
+ self.vocab_size = config.vocab_size
1280
+
1281
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
1282
+ self.layers = nn.ModuleList(
1283
+ [HunYuanDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
1284
+ )
1285
+ self._use_sdpa = config._attn_implementation == "sdpa"
1286
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1287
+ self.norm = HunYuanRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1288
+
1289
+ self.cla = config.use_cla
1290
+ self.cla_share_factor = config.cla_share_factor
1291
+
1292
+ self.gradient_checkpointing = False
1293
+ # Initialize weights and apply final processing
1294
+ self.post_init()
1295
+
1296
+ def get_input_embeddings(self):
1297
+ return self.embed_tokens
1298
+
1299
+ def set_input_embeddings(self, value):
1300
+ self.embed_tokens = value
1301
+
1302
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
1303
+ def forward(
1304
+ self,
1305
+ input_ids: torch.LongTensor = None,
1306
+ attention_mask: Optional[torch.Tensor] = None,
1307
+ position_ids: Optional[torch.LongTensor] = None,
1308
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1309
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1310
+ use_cache: Optional[bool] = None,
1311
+ output_attentions: Optional[bool] = None,
1312
+ output_hidden_states: Optional[bool] = None,
1313
+ return_dict: Optional[bool] = None,
1314
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1315
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1316
+ output_hidden_states = (
1317
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1318
+ )
1319
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1320
+
1321
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1322
+
1323
+ # retrieve input_ids and inputs_embeds
1324
+ if input_ids is not None and inputs_embeds is not None:
1325
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1326
+ elif input_ids is not None:
1327
+ batch_size, seq_length = input_ids.shape[:2]
1328
+ elif inputs_embeds is not None:
1329
+ batch_size, seq_length = inputs_embeds.shape[:2]
1330
+ else:
1331
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1332
+
1333
+ if self.gradient_checkpointing and self.training:
1334
+ if use_cache:
1335
+ logger.warning_once(
1336
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1337
+ )
1338
+ use_cache = False
1339
+
1340
+ past_key_values_length = 0
1341
+ if use_cache:
1342
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1343
+ if use_legacy_cache:
1344
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1345
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1346
+
1347
+ if position_ids is None:
1348
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1349
+ position_ids = torch.arange(
1350
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1351
+ )
1352
+ position_ids = position_ids.unsqueeze(0)
1353
+
1354
+ if inputs_embeds is None:
1355
+ inputs_embeds = self.embed_tokens(input_ids)
1356
+
1357
+ # Fix lora with gradient checkpointing training
1358
+ if self.training and inputs_embeds.is_leaf:
1359
+ inputs_embeds.requires_grad = True
1360
+
1361
+ if self._use_flash_attention_2:
1362
+ # 2d mask is passed through the layers
1363
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1364
+ elif self._use_sdpa and not output_attentions:
1365
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
1366
+ # the manual implementation that requires a 4D causal mask in all cases.
1367
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1368
+ attention_mask,
1369
+ (batch_size, seq_length),
1370
+ inputs_embeds,
1371
+ past_key_values_length,
1372
+ )
1373
+ else:
1374
+ # 4d mask is passed through the layers
1375
+ attention_mask = _prepare_4d_causal_attention_mask(
1376
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1377
+ )
1378
+
1379
+ # embed positions
1380
+ hidden_states = inputs_embeds
1381
+
1382
+ # decoder layers
1383
+ all_hidden_states = () if output_hidden_states else None
1384
+ all_self_attns = () if output_attentions else None
1385
+ next_decoder_cache = None
1386
+
1387
+ prev_kv_states = None
1388
+ for layer_idx, decoder_layer in enumerate(self.layers):
1389
+ if output_hidden_states:
1390
+ all_hidden_states += (hidden_states,)
1391
+
1392
+ if self.gradient_checkpointing and self.training:
1393
+ layer_outputs = self._gradient_checkpointing_func(
1394
+ decoder_layer.__call__,
1395
+ hidden_states,
1396
+ attention_mask,
1397
+ position_ids,
1398
+ past_key_values,
1399
+ output_attentions,
1400
+ use_cache,
1401
+ prev_kv_states,
1402
+ )
1403
+ else:
1404
+ layer_outputs = decoder_layer(
1405
+ hidden_states,
1406
+ attention_mask=attention_mask,
1407
+ position_ids=position_ids,
1408
+ past_key_value=past_key_values,
1409
+ output_attentions=output_attentions,
1410
+ use_cache=use_cache,
1411
+ kv_states=prev_kv_states
1412
+ )
1413
+
1414
+ hidden_states = layer_outputs[0]
1415
+
1416
+ if use_cache:
1417
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1418
+
1419
+ if output_attentions:
1420
+ all_self_attns += (layer_outputs[1],)
1421
+
1422
+ kv_states = layer_outputs[-1]
1423
+
1424
+ if self.cla and layer_idx % self.cla_share_factor == 0:
1425
+ prev_kv_states = kv_states
1426
+
1427
+ break # TEST
1428
+
1429
+ hidden_states = self.norm(hidden_states)
1430
+
1431
+ # add hidden states from the last decoder layer
1432
+ if output_hidden_states:
1433
+ all_hidden_states += (hidden_states,)
1434
+
1435
+ next_cache = None
1436
+ if use_cache:
1437
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1438
+ if not return_dict:
1439
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1440
+ return BaseModelOutputWithPast(
1441
+ last_hidden_state=hidden_states,
1442
+ past_key_values=next_cache,
1443
+ hidden_states=all_hidden_states,
1444
+ attentions=all_self_attns,
1445
+ )
1446
+
1447
+
1448
+ class HunYuanMoEV1ForCausalLM(HunYuanPreTrainedModel):
1449
+ _tied_weights_keys = ["lm_head.weight"]
1450
+
1451
+ def __init__(self, config: HunYuanConfig):
1452
+ super().__init__(config)
1453
+ self.model = HunYuanModel(config)
1454
+ self.vocab_size = config.vocab_size
1455
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1456
+
1457
+ # Initialize weights and apply final processing
1458
+ self.post_init()
1459
+
1460
+ def get_input_embeddings(self):
1461
+ return self.model.embed_tokens
1462
+
1463
+ def set_input_embeddings(self, value):
1464
+ self.model.embed_tokens = value
1465
+
1466
+ def get_output_embeddings(self):
1467
+ return self.lm_head
1468
+
1469
+ def set_output_embeddings(self, new_embeddings):
1470
+ self.lm_head = new_embeddings
1471
+
1472
+ def set_decoder(self, decoder):
1473
+ self.model = decoder
1474
+
1475
+ def get_decoder(self):
1476
+ return self.model
1477
+
1478
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
1479
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1480
+ def forward(
1481
+ self,
1482
+ input_ids: torch.LongTensor = None,
1483
+ attention_mask: Optional[torch.Tensor] = None,
1484
+ position_ids: Optional[torch.LongTensor] = None,
1485
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1486
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1487
+ labels: Optional[torch.LongTensor] = None,
1488
+ use_cache: Optional[bool] = None,
1489
+ output_attentions: Optional[bool] = None,
1490
+ output_hidden_states: Optional[bool] = None,
1491
+ return_dict: Optional[bool] = None,
1492
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1493
+ r"""
1494
+ Args:
1495
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1496
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1497
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1498
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1499
+
1500
+ Returns:
1501
+
1502
+ Example:
1503
+
1504
+ ```python
1505
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
1506
+
1507
+ >>> model = AutoModelForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1508
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1509
+
1510
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1511
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1512
+
1513
+ >>> # Generate
1514
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1515
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1516
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1517
+ ```"""
1518
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1519
+ output_hidden_states = (
1520
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1521
+ )
1522
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1523
+
1524
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1525
+ outputs = self.model(
1526
+ input_ids=input_ids,
1527
+ attention_mask=attention_mask,
1528
+ position_ids=position_ids,
1529
+ past_key_values=past_key_values,
1530
+ inputs_embeds=inputs_embeds,
1531
+ use_cache=use_cache,
1532
+ output_attentions=output_attentions,
1533
+ output_hidden_states=output_hidden_states,
1534
+ return_dict=return_dict,
1535
+ )
1536
+
1537
+ hidden_states = outputs[0]
1538
+ if self.config.pretraining_tp > 1:
1539
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1540
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1541
+ logits = torch.cat(logits, dim=-1)
1542
+ else:
1543
+ logits = self.lm_head(hidden_states)
1544
+ logits = logits.float()
1545
+
1546
+ loss = None
1547
+ if labels is not None:
1548
+ # Shift so that tokens < n predict n
1549
+ shift_logits = logits[..., :-1, :].contiguous()
1550
+ shift_labels = labels[..., 1:].contiguous()
1551
+ # Flatten the tokens
1552
+ loss_fct = CrossEntropyLoss()
1553
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1554
+ shift_labels = shift_labels.view(-1)
1555
+ # Enable model parallelism
1556
+ shift_labels = shift_labels.to(shift_logits.device)
1557
+ loss = loss_fct(shift_logits, shift_labels)
1558
+
1559
+ if not return_dict:
1560
+ output = (logits,) + outputs[1:]
1561
+ return (loss,) + output if loss is not None else output
1562
+
1563
+ return CausalLMOutputWithPast(
1564
+ loss=loss,
1565
+ logits=logits,
1566
+ past_key_values=outputs.past_key_values,
1567
+ hidden_states=outputs.hidden_states,
1568
+ attentions=outputs.attentions,
1569
+ )
1570
+
1571
+ def prepare_inputs_for_generation(
1572
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1573
+ ):
1574
+ if past_key_values is not None:
1575
+ if isinstance(past_key_values, Cache):
1576
+ cache_length = past_key_values.get_seq_length()
1577
+ past_length = past_key_values.seen_tokens
1578
+ max_cache_length = past_key_values.get_max_cache_shape()
1579
+ else:
1580
+ cache_length = past_length = past_key_values[0][0].shape[2]
1581
+ max_cache_length = None
1582
+
1583
+ # Keep only the unprocessed tokens:
1584
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1585
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1586
+ # input)
1587
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1588
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):]
1589
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1590
+ # input_ids based on the past_length.
1591
+ elif past_length < input_ids.shape[1]:
1592
+ input_ids = input_ids[:, past_length:]
1593
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1594
+
1595
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1596
+ if (
1597
+ max_cache_length is not None
1598
+ and attention_mask is not None
1599
+ and cache_length + input_ids.shape[1] > max_cache_length
1600
+ ):
1601
+ attention_mask = attention_mask[:, -max_cache_length:]
1602
+
1603
+ position_ids = kwargs.get("position_ids", None)
1604
+ if attention_mask is not None and position_ids is None:
1605
+ # create position_ids on the fly for batch generation
1606
+ position_ids = attention_mask.long().cumsum(-1) - 1
1607
+ position_ids.masked_fill_(attention_mask == 0, 1)
1608
+ if past_key_values:
1609
+ position_ids = position_ids[:, -input_ids.shape[1]:]
1610
+
1611
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1612
+ if inputs_embeds is not None and past_key_values is None:
1613
+ model_inputs = {"inputs_embeds": inputs_embeds}
1614
+ else:
1615
+ model_inputs = {"input_ids": input_ids}
1616
+
1617
+ model_inputs.update(
1618
+ {
1619
+ "position_ids": position_ids,
1620
+ "past_key_values": past_key_values,
1621
+ "use_cache": kwargs.get("use_cache"),
1622
+ "attention_mask": attention_mask,
1623
+ }
1624
+ )
1625
+ return model_inputs
1626
+
1627
+ @staticmethod
1628
+ def _reorder_cache(past_key_values, beam_idx):
1629
+ reordered_past = ()
1630
+ for layer_past in past_key_values:
1631
+ reordered_past += (
1632
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1633
+ )
1634
+ return reordered_past
1635
+
1636
+
1637
+ @add_start_docstrings(
1638
+ """
1639
+ The HunYuan Model transformer with a sequence classification head on top (linear layer).
1640
+
1641
+ [`HunYuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1642
+ (e.g. GPT-2) do.
1643
+
1644
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1645
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1646
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1647
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1648
+ each row of the batch).
1649
+ """,
1650
+ HUNYUAN_START_DOCSTRING,
1651
+ )
1652
+ class HunYuanForSequenceClassification(HunYuanPreTrainedModel):
1653
+ def __init__(self, config):
1654
+ super().__init__(config)
1655
+ self.num_labels = config.num_labels
1656
+ self.model = HunYuanModel(config)
1657
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1658
+
1659
+ # Initialize weights and apply final processing
1660
+ self.post_init()
1661
+
1662
+ def get_input_embeddings(self):
1663
+ return self.model.embed_tokens
1664
+
1665
+ def set_input_embeddings(self, value):
1666
+ self.model.embed_tokens = value
1667
+
1668
+ @add_start_docstrings_to_model_forward(HUNYUAN_INPUTS_DOCSTRING)
1669
+ def forward(
1670
+ self,
1671
+ input_ids: torch.LongTensor = None,
1672
+ attention_mask: Optional[torch.Tensor] = None,
1673
+ position_ids: Optional[torch.LongTensor] = None,
1674
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1675
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1676
+ labels: Optional[torch.LongTensor] = None,
1677
+ use_cache: Optional[bool] = None,
1678
+ output_attentions: Optional[bool] = None,
1679
+ output_hidden_states: Optional[bool] = None,
1680
+ return_dict: Optional[bool] = None,
1681
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1682
+ r"""
1683
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1684
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1685
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1686
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1687
+ """
1688
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1689
+
1690
+ transformer_outputs = self.model(
1691
+ input_ids,
1692
+ attention_mask=attention_mask,
1693
+ position_ids=position_ids,
1694
+ past_key_values=past_key_values,
1695
+ inputs_embeds=inputs_embeds,
1696
+ use_cache=use_cache,
1697
+ output_attentions=output_attentions,
1698
+ output_hidden_states=output_hidden_states,
1699
+ return_dict=return_dict,
1700
+ )
1701
+ hidden_states = transformer_outputs[0]
1702
+ logits = self.score(hidden_states)
1703
+
1704
+ if input_ids is not None:
1705
+ batch_size = input_ids.shape[0]
1706
+ else:
1707
+ batch_size = inputs_embeds.shape[0]
1708
+
1709
+ if self.config.pad_token_id is None and batch_size != 1:
1710
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1711
+ if self.config.pad_token_id is None:
1712
+ sequence_lengths = -1
1713
+ else:
1714
+ if input_ids is not None:
1715
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1716
+ logits.device
1717
+ )
1718
+ else:
1719
+ sequence_lengths = -1
1720
+
1721
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1722
+
1723
+ loss = None
1724
+ if labels is not None:
1725
+ labels = labels.to(logits.device)
1726
+ if self.config.problem_type is None:
1727
+ if self.num_labels == 1:
1728
+ self.config.problem_type = "regression"
1729
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1730
+ self.config.problem_type = "single_label_classification"
1731
+ else:
1732
+ self.config.problem_type = "multi_label_classification"
1733
+
1734
+ if self.config.problem_type == "regression":
1735
+ loss_fct = MSELoss()
1736
+ if self.num_labels == 1:
1737
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1738
+ else:
1739
+ loss = loss_fct(pooled_logits, labels)
1740
+ elif self.config.problem_type == "single_label_classification":
1741
+ loss_fct = CrossEntropyLoss()
1742
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1743
+ elif self.config.problem_type == "multi_label_classification":
1744
+ loss_fct = BCEWithLogitsLoss()
1745
+ loss = loss_fct(pooled_logits, labels)
1746
+ if not return_dict:
1747
+ output = (pooled_logits,) + transformer_outputs[1:]
1748
+ return ((loss,) + output) if loss is not None else output
1749
+
1750
+ return SequenceClassifierOutputWithPast(
1751
+ loss=loss,
1752
+ logits=pooled_logits,
1753
+ past_key_values=transformer_outputs.past_key_values,
1754
+ hidden_states=transformer_outputs.hidden_states,
1755
+ attentions=transformer_outputs.attentions,
1756
+ )
test_hunyuan.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM
2
+ import torch
3
+
4
+ model = AutoModelForCausalLM.from_pretrained("./.", trust_remote_code=True)
5
+ tokenizer = AutoTokenizer.from_pretrained("./.", trust_remote_code=True)
6
+
7
+ with torch.no_grad():
8
+ input_text = "Hi_"
9
+ inputs = tokenizer(text=input_text, return_tensors="pt")
10
+ del inputs["token_type_ids"]
11
+ print(inputs)
12
+ gen = model.generate(**inputs, max_new_tokens=1, do_sample=False)
13
+
14
+ decoded = tokenizer.batch_decode(gen, skip_special_tokens=True)
15
+ print(decoded)
16
+
17
+
18
+ """
19
+ from hunyuan.configuration_hunyuan import HunYuanConfig
20
+ from hunyuan.modeling_hunyuan import HunYuanMoEV1ForCausalLM
21
+ import torch
22
+
23
+ config = HunYuanConfig.from_pretrained("./Hunyuan-A13B-Instruct", trust_remote_code=True)
24
+ config.moe_intermediate_size = [3072, 3072]
25
+ config.num_experts = 4
26
+ config.num_shared_expert = [1, 1]
27
+ config.moe_topk = [2, 2]
28
+ config.num_hidden_layers = 4
29
+
30
+ model = HunYuanMoEV1ForCausalLM(config)
31
+ print(model)
32
+
33
+ torch.manual_seed(0)
34
+ state_dict = model.state_dict()
35
+ for key in state_dict:
36
+ state_dict[key].uniform_(-0.2, 0.2)
37
+ model.load_state_dict(state_dict)
38
+
39
+ model.save_pretrained("./hunyuan-tiny")
40
+ """
tokenization_hy.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import logging
3
+ import os
4
+ import unicodedata
5
+ from typing import Collection, Dict, List, Set, Tuple, Union
6
+
7
+ import tiktoken
8
+ from transformers import PreTrainedTokenizer, AddedToken
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ VOCAB_FILES_NAMES = {"vocab_file": "hy.tiktoken"}
14
+
15
+ PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
16
+ # PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
17
+ ENDOFTEXT = "<|endoftext|>"
18
+ STARTOFTEXT = "<|startoftext|>"
19
+ BOSTOKEN = "<|bos|>"
20
+ EOSTOKEN = "<|eos|>"
21
+ PADTOKEN = "<|pad|>"
22
+
23
+ # as the default behavior is changed to allow special tokens in
24
+ # regular texts, the surface forms of special tokens need to be
25
+ # as different as possible to minimize the impact
26
+ EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
27
+ # changed to use actual index to avoid misconfiguration with vocabulary expansion
28
+
29
+
30
+ SPECIAL_START_ID = 127957
31
+
32
+ def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
33
+ # with open(tiktoken_bpe_file, "rb", encoding="utf-8") as f:
34
+ # contents = f.read()
35
+ dic = {}
36
+ rank = 0
37
+ for line in open(tiktoken_bpe_file, "rb"):
38
+ if line:
39
+ token, _ = line.split()
40
+ if base64.b64decode(token) in dic:
41
+ continue
42
+ dic[base64.b64decode(token)] = int(rank)
43
+ rank += 1
44
+ global SPECIAL_START_ID
45
+ SPECIAL_START_ID=rank
46
+ return dic
47
+
48
+ # NOTE: Please use the code line to check `SPECIAL_START_ID` right, this will affect the SPECIAL_START_ID
49
+ # _load_tiktoken_bpe('/apdcephfs/share_1502809/shaneshu/tokenizer_exp/other_tokenizer_vocab/hy/' + VOCAB_FILES_NAMES['vocab_file'])
50
+ # print(SPECIAL_START_ID)
51
+
52
+ SPECIAL_TOKENS = tuple(
53
+ enumerate(
54
+ (
55
+ (
56
+ ENDOFTEXT,
57
+ STARTOFTEXT,
58
+ BOSTOKEN,
59
+ EOSTOKEN,
60
+ PADTOKEN,
61
+ )
62
+ + EXTRAS
63
+ ),
64
+ start=SPECIAL_START_ID,
65
+ )
66
+ )
67
+ # NOTE: Unused Token ID starts from 127962
68
+ SPECIAL_TOKENS_SET = set(t for i, t in SPECIAL_TOKENS)
69
+
70
+ class HYTokenizer(PreTrainedTokenizer):
71
+ """hunyuan tokenizer."""
72
+
73
+ vocab_files_names = VOCAB_FILES_NAMES
74
+
75
+ def __init__(
76
+ self,
77
+ vocab_file,
78
+ errors="replace",
79
+ extra_vocab_file=None,
80
+ **kwargs,
81
+ ):
82
+ super().__init__(**kwargs)
83
+
84
+ # how to handle errors in decoding UTF-8 byte sequences
85
+ # use ignore if you are in streaming inference
86
+ self.errors = errors
87
+
88
+ self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: Dict[bytes, int]
89
+ self.special_tokens = {
90
+ token: index
91
+ for index, token in SPECIAL_TOKENS
92
+ }
93
+
94
+ # try load extra vocab from file
95
+ if extra_vocab_file is not None:
96
+ used_ids = set(self.mergeable_ranks.values()) | set(self.special_tokens.values())
97
+ extra_mergeable_ranks = _load_tiktoken_bpe(extra_vocab_file)
98
+ for token, index in extra_mergeable_ranks.items():
99
+ if token in self.mergeable_ranks:
100
+ logger.info(f"extra token {token} exists, skipping")
101
+ continue
102
+ if index in used_ids:
103
+ logger.info(f'the index {index} for extra token {token} exists, skipping')
104
+ continue
105
+ self.mergeable_ranks[token] = index
106
+ # the index may be sparse after this, but don't worry tiktoken.Encoding will handle this
107
+
108
+ enc = tiktoken.Encoding(
109
+ "HunYuan",
110
+ pat_str=PAT_STR,
111
+ mergeable_ranks=self.mergeable_ranks,
112
+ special_tokens=self.special_tokens,
113
+ )
114
+ assert (
115
+ len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
116
+ ), f"{len(self.mergeable_ranks)} + {len(self.special_tokens)} != {enc.n_vocab} in encoding"
117
+
118
+ self.decoder = {
119
+ v: k for k, v in self.mergeable_ranks.items()
120
+ } # type: dict[int, bytes|str]
121
+ self.decoder.update({v: k for k, v in self.special_tokens.items()})
122
+
123
+ self.tokenizer = enc # type: tiktoken.Encoding
124
+
125
+ self.eod_id = self.tokenizer.eot_token
126
+ self.bod_id = self.special_tokens[STARTOFTEXT]
127
+ self.bos_id = self.special_tokens[BOSTOKEN]
128
+ self.eos_id = self.special_tokens[EOSTOKEN]
129
+ self.pad_id = self.special_tokens[PADTOKEN]
130
+
131
+ def __getstate__(self):
132
+ # for pickle lovers
133
+ state = self.__dict__.copy()
134
+ del state["tokenizer"]
135
+ return state
136
+
137
+ def __setstate__(self, state):
138
+ # tokenizer is not python native; don't pass it; rebuild it
139
+ self.__dict__.update(state)
140
+ enc = tiktoken.Encoding(
141
+ "HunYuan",
142
+ pat_str=PAT_STR,
143
+ mergeable_ranks=self.mergeable_ranks,
144
+ special_tokens=self.special_tokens,
145
+ )
146
+ self.tokenizer = enc
147
+
148
+ def __len__(self) -> int:
149
+ return self.tokenizer.n_vocab
150
+
151
+ def get_vocab(self) -> Dict[bytes, int]:
152
+ return self.mergeable_ranks
153
+
154
+ def convert_tokens_to_ids(
155
+ self, tokens: Union[bytes, str, List[Union[bytes, str]]]
156
+ ) -> List[int]:
157
+ ids = []
158
+ if isinstance(tokens, (str, bytes)):
159
+ if tokens in self.special_tokens:
160
+ return self.special_tokens[tokens]
161
+ else:
162
+ return self.mergeable_ranks.get(tokens)
163
+ for token in tokens:
164
+ if token in self.special_tokens:
165
+ ids.append(self.special_tokens[token])
166
+ else:
167
+ ids.append(self.mergeable_ranks.get(token))
168
+ return ids
169
+
170
+ def _add_tokens(
171
+ self,
172
+ new_tokens: Union[List[str], List[AddedToken]],
173
+ special_tokens: bool = False,
174
+ ) -> int:
175
+ if not special_tokens and new_tokens:
176
+ raise ValueError("Adding regular tokens is not supported")
177
+ for token in new_tokens:
178
+ surface_form = token.content if isinstance(token, AddedToken) else token
179
+ if surface_form not in SPECIAL_TOKENS_SET:
180
+ raise ValueError("Adding unknown special tokens is not supported")
181
+ return 0
182
+
183
+ def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
184
+ """
185
+ Save only the vocabulary of the tokenizer (vocabulary).
186
+ Returns:
187
+ `Tuple(str)`: Paths to the files saved.
188
+ """
189
+ file_path = os.path.join(save_directory, "hunyuan.tiktoken")
190
+ with open(file_path, "w", encoding="utf-8") as w:
191
+ for k, v in self.mergeable_ranks.items():
192
+ line = base64.b64encode(k).decode("utf-8") + " " + str(v) + "\n"
193
+ w.write(line)
194
+ return (file_path,)
195
+
196
+ def tokenize(
197
+ self,
198
+ text: str,
199
+ allowed_special: Union[Set, str] = "all",
200
+ disallowed_special: Union[Collection, str] = (),
201
+ **kwargs,
202
+ ) -> List[Union[bytes, str]]:
203
+ """
204
+ Converts a string in a sequence of tokens.
205
+ Args:
206
+ text (`str`):
207
+ The sequence to be encoded.
208
+ allowed_special (`Literal["all"]` or `set`):
209
+ The surface forms of the tokens to be encoded as special tokens in regular texts.
210
+ Default to "all".
211
+ disallowed_special (`Literal["all"]` or `Collection`):
212
+ The surface forms of the tokens that should not be in regular texts and trigger errors.
213
+ Default to an empty tuple.
214
+ kwargs (additional keyword arguments, *optional*):
215
+ Will be passed to the underlying model specific encode method.
216
+ Returns:
217
+ `List[bytes|str]`: The list of tokens.
218
+ """
219
+ tokens = []
220
+ text = unicodedata.normalize("NFC", text)
221
+
222
+ # this implementation takes a detour: text -> token id -> token surface forms
223
+ for t in self.tokenizer.encode(
224
+ text, allowed_special=allowed_special, disallowed_special=disallowed_special
225
+ ):
226
+ tokens.append(self.decoder[t])
227
+ return tokens
228
+
229
+ def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
230
+ """
231
+ Converts a sequence of tokens in a single string.
232
+ """
233
+ text = ""
234
+ temp = b""
235
+ for t in tokens:
236
+ if isinstance(t, str):
237
+ if temp:
238
+ text += temp.decode("utf-8", errors=self.errors)
239
+ temp = b""
240
+ text += t
241
+ elif isinstance(t, bytes):
242
+ temp += t
243
+ else:
244
+ raise TypeError("token should only be of type types or str")
245
+ if temp:
246
+ text += temp.decode("utf-8", errors=self.errors)
247
+ return text
248
+
249
+ @property
250
+ def vocab_size(self):
251
+ return self.tokenizer.n_vocab
252
+
253
+ def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
254
+ """Converts an id to a token, special tokens included"""
255
+ if index in self.decoder:
256
+ return self.decoder[index]
257
+ raise ValueError("unknown ids")
258
+
259
+ def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
260
+ """Converts a token to an id using the vocab, special tokens included"""
261
+ if token in self.special_tokens:
262
+ return self.special_tokens[token]
263
+ if token in self.mergeable_ranks:
264
+ return self.mergeable_ranks[token]
265
+ raise ValueError("unknown token")
266
+
267
+ def _tokenize(self, text: str, **kwargs):
268
+ """
269
+ Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
270
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
271
+ Do NOT take care of added tokens.
272
+ """
273
+ raise NotImplementedError
274
+
275
+ def _decode(
276
+ self,
277
+ token_ids: Union[int, List[int]],
278
+ skip_special_tokens: bool = False,
279
+ errors: str = None,
280
+ **kwargs,
281
+ ) -> str:
282
+ if isinstance(token_ids, int):
283
+ token_ids = [token_ids]
284
+ if skip_special_tokens:
285
+ token_ids = [i for i in token_ids if i < self.eod_id]
286
+ return self.tokenizer.decode(token_ids, errors=errors or self.errors)
287
+
288
+ # tests
289
+ if __name__ == "__main__":
290
+ tokenizer = HYTokenizer.from_pretrained('./hy')
291
+ text = '你好,世界'
292
+ tokens = tokenizer.tokenize(text)
293
+ print(tokens)
294
+ ids = tokenizer.convert_tokens_to_ids(tokens)
295
+ print(ids)
296
+ text2 = tokenizer.convert_tokens_to_string(tokens)
297
+ print(text2)
298
+ ids2 = tokenizer.convert_tokens_to_ids(tokens)
tokenizer_config.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GPT2LMHeadModel"
4
+ ],
5
+ "model_max_length": 1048576,
6
+ "tokenizer_class": "HYTokenizer",
7
+ "auto_map": {
8
+ "AutoTokenizer": [
9
+ "tokenization_hy.HYTokenizer",
10
+ null
11
+ ]
12
+ },
13
+ "eos_token": "<|eos|>",
14
+ "model_type": "gpt2",
15
+ "additional_special_tokens": ["<|startoftext|>", "<|extra_0|>", "<|extra_4|>", "<|extra_5|>", "<|eos|>"],
16
+ "pad_token": "<|pad|>",
17
+ "chat_template": "{% set loop_messages = messages %}\n{% if tools %}\n {% set weekday_map = {'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三', 'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期日'} %}\n {% set weekday_cn = weekday_map[strftime_now('%A')] %}\n {% set datetime_str = strftime_now('%Y-%m-%d %H:%M:%S') %}\n {% set datetime_str = datetime_str + ' ' + weekday_cn %}\n {% for message in loop_messages %}\n {% if 'content' in message %}\n {% set content = message['content'] %}\n {% else %}\n {% set content = '' %}\n {% endif %}\n {% if loop.index0 == 0 %}\n {% set content_tmp = '你是一位函数组合专家。你会得到一个问题和一组可能的函数。根据问题,你需要进行一个或多个函数/工具调用以实现目的。\n如果没有一个函数可以使用,请直接使用自然语言回复用户,以助手:开头。\n如果给定的问题缺少函数所需的参数,请使用自然语言进行提问,向用户询问必要信息,以助手:开头。\n如果调用结果已经足够回答用户问题,请对历史结果进行总结,使用自然语言回复用户,以助手:开头。\n你应该只在工具调用部分返回函数调用。如果你决定调用任何函数,你必须将其格式化为<tool_calls>[{\"name\": \"func_name1\", \"arguments\": {\"argument1\": \"value1\", \"argument2\": \"value2\"}},...]</tool_calls>。你不应该在回复中包含任何其他文本。以下是你可以调用的函数列表,格式为JSON。\n' %}\n {% set content_tmp = content_tmp + '\n' + tools | tojson + '\n' %}\n {% if message['role'] == 'system' %}\n {% set content_tmp = content_tmp + '\n额外要求:\n' + content + '\n\n如果你决定返回函数调用,请将其格式化为<tool_calls>[{\"name\": \"func_name1\", \"arguments\": {\"argument1\": \"value1\", \"argument2\": \"value2\"}},...]</tool_calls>,不得包含其他文本。如果额外要求里有格式要求,请忽略,以此处为准。\n否则,请参考开头说的三种情况,以助手:开头进行回复。\n\n如果额外要求里有时间信息,就以额外要求里的时间为准,否则,参考当前时间:' + datetime_str %}\n {% set content = '<|startoftext|>' + content_tmp + '<|extra_4|>' %}\n {% elif message['role'] == 'user' %}\n {% set content_tmp = content_tmp + '\n如果你决定返回函数调用,请将其格式化为<tool_calls>[{\"name\": \"func_name1\", \"arguments\": {\"argument1\": \"value1\", \"argument2\": \"value2\"}},...]</tool_calls>,不得包含其他文本。\n否则,请参考开头说的三种情况,以助手:开头进行回复。\n\n当前时间:' + datetime_str %}\n {% set content_tmp = '<|startoftext|>' + content_tmp + '<|extra_4|>'%}\n {% set content = content_tmp + '用户:' + content + '<|extra_0|>' %}\n {% endif %}\n {% else %}\n {% if message['role'] == 'user' %}\n {% set content = '用户:' + content + '<|extra_0|>' %}\n {% elif message['role'] == 'assistant' %}\n {% if 'tool_calls' in message %}\n {% set tool_calls = message['tool_calls'] %}\n {% set ns = namespace(tool_calls=\"[\") %}\n {% for tool_call in tool_calls %}\n {% set function = tool_call['function'] %}\n {% set name = function['name'] %}\n {% set ns.tool_calls = ns.tool_calls + '{\"name\": \"' + name + '\", '%}\n {% set arguments = function['arguments'] %}\n {% if arguments is not string %}\n {% set arguments = arguments | tojson %}\n {% endif %}\n {% set ns.tool_calls = ns.tool_calls + '\"arguments\": ' + arguments + '}' %}\n {% if not loop.last %}\n {% set ns.tool_calls = ns.tool_calls + ', '%}\n {% endif %}\n {% endfor %}\n {% set ns.tool_calls = ns.tool_calls + ']' %}\n {% set content = content + '<tool_calls>' + ns.tool_calls + '</tool_calls>' %}\n {% else %}\n {% set content = '助手:' + content %}\n {% endif %}\n {% set content = content + '<|eos|>' %}\n {% elif message['role'] == 'tool' %}\n {% if content is not string %}\n {set content = content | tojson }\n {% endif %}\n {% set content = '<tool_response>' + content + '</tool_response>' %}\n {% set content = content + '<|extra_0|>' %}\n {% endif %}\n {% endif %}\n {{- content -}}\n {% endfor %}\n{% else %}\n {% set context = {'has_head': true} %}\n {% for message in loop_messages %}\n {% if 'content' in message %}\n {% set content = message['content'] %}\n {% else %}\n {% set content = '' %}\n {% endif %}\n {% if loop.index0 == 0 %}\n {% if content == '' %}\n {% set _ = context.update({'has_head': false}) %}\n {% elif message['role'] == 'system' %}\n {% set content = '<|startoftext|>' + content + '<|extra_4|>' %}\n {% endif %}\n {% endif %}\n {% if message['role'] == 'user' %}\n {% if loop.index0 == 1 and not context.has_head %}\n {% set content = '<|startoftext|>' + content %}\n {% endif %}\n {% if loop.index0 == 1 and context.has_head %}\n {% set content = content + '<|extra_0|>' %}\n {% else %}\n {% set content = '<|startoftext|>' + content + '<|extra_0|>' %}\n {% endif %}\n {% elif message['role'] == 'assistant' %}\n {% set content = content + '<|eos|>' %}\n {% elif message['role'] == 'tool' %}\n {% set content = content + '<|extra_0|>' %}\n {% endif %}\n {{- content -}}\n {% endfor %}\n{% endif %}\n{%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n' }}\n{%- endif %}"
18
+ }
vit_model.py ADDED
@@ -0,0 +1,1083 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import types
3
+ import math
4
+ import torch
5
+ from torch import Tensor, nn
6
+ import torch.nn.functional as F
7
+ from typing import List, Tuple, Optional, Union
8
+ from contextlib import contextmanager
9
+ from transformers.modeling_attn_mask_utils import (
10
+ _prepare_4d_causal_attention_mask_for_sdpa,
11
+ _prepare_4d_causal_attention_mask_for_sdpa,
12
+ _prepare_4d_causal_attention_mask,
13
+ )
14
+ from transformers.models.clip.configuration_clip import CLIPVisionConfig
15
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
16
+ from .modeling_hunyuan import HunYuanDecoderLayer, HunYuanRMSNorm
17
+ from .configuration_hunyuan import HunYuanConfig
18
+
19
+
20
+ def NaVitForward(input_ids, encoder_input, vit, image_tensors, images_pos, vit_input_resolution, im_start_id, im_end_id, image_token_id, anyres_vit_two_views, dtype):
21
+ # input_ids: (B, L)
22
+ # encoder_input: (L, B, E)
23
+ # image_tensors [[Tensor],...,[Tensor]]
24
+ # image_pos [[Tensor],...,[Tensor]]
25
+ # tokenizer = get_tokenizer()
26
+ b = len(input_ids)
27
+ img_embs = None
28
+ all_nums = sum([len(tensors) for tensors in image_tensors]) if image_tensors else 0
29
+ if all_nums != 0:
30
+ img_embs, img_batch_pos = vit(image_tensors)
31
+ else:
32
+ # when no input image, initialize a fake tensor
33
+ pad_nums = 1
34
+ image_tensors = [[torch.rand(3, vit_input_resolution, vit_input_resolution, dtype=dtype, device=torch.cuda.current_device()) for _ in range(pad_nums)]]
35
+ img_embs, img_batch_pos = vit(image_tensors)
36
+
37
+ encoder_input = encoder_input.clone()
38
+ if all_nums > 0:
39
+ assert len(images_pos) == len(img_batch_pos), \
40
+ (len(images_pos), len(img_batch_pos))
41
+ start_token_id = im_start_id
42
+ end_token_id = im_end_id
43
+ placeholder_id = image_token_id
44
+ for idx in range(len(images_pos)):
45
+ assert len(images_pos[idx]) == len(img_batch_pos[idx]), \
46
+ (len(images_pos[idx]), len(img_batch_pos[idx]))
47
+ for p_img_pos_in_batch, p_batch_img_pos in zip(img_batch_pos[idx], images_pos[idx]):
48
+ # the positions to be filled [s_start, s_end)
49
+ s_idx, s_start, s_end = p_img_pos_in_batch
50
+ current_embs = img_embs[s_idx, s_start:s_end]
51
+ im_s, im_e = p_batch_img_pos
52
+ assert len(current_embs) == im_e - im_s, \
53
+ (img_embs.shape, (s_start, s_end, s_idx), current_embs.shape, (im_s, im_e, idx))
54
+ if not anyres_vit_two_views:
55
+ assert input_ids[idx, im_s - 1] == start_token_id, \
56
+ input_ids[idx, im_s - 1]
57
+ assert input_ids[idx, im_e] == end_token_id, \
58
+ input_ids[idx, im_e]
59
+ assert (input_ids[idx, im_s:im_e] == placeholder_id).all(), \
60
+ f'The tokens to be filled are not the placeholder_id {placeholder_id}: {(input_ids[idx, im_s:im_e] == placeholder_id).sum()} vs {im_e - im_s}'
61
+ encoder_input[idx, im_s:im_e] = current_embs
62
+ else:
63
+ # when no input image, to mask vit value
64
+ vit_mask = torch.zeros([1, img_embs.shape[0]], device=torch.cuda.current_device())
65
+ current_embs = img_embs[0, :]
66
+ encoder_input[0, 1:img_embs.shape[0] + 1] = encoder_input[0, 1:img_embs.shape[0] + 1] * (1 - vit_mask) + current_embs * vit_mask
67
+ return encoder_input, input_ids
68
+
69
+
70
+ def VitForward(input_ids, encoder_input, vit, vit_linear_encoder, image_tensors, images_pos, vit_input_resolution, vit_mapping_type, vit_patch, vit_token):
71
+ vit_patch_mlp = (vit_patch > 1 and vit_mapping_type == 'mlp') or vit_patch == 0
72
+
73
+ b = len(input_ids)
74
+ if images_pos is None:
75
+ images_pos = torch.ones([len(input_ids), 1, 3])
76
+ images_pos[:, :, 1] = images_pos[:, :, 1]*(vit_token + 1)
77
+ images_pos = images_pos.long()
78
+
79
+ real_image_nums = []
80
+ image_tensors = image_tensors.view(b, -1, 3, vit_input_resolution, vit_input_resolution)
81
+ real_images = []
82
+
83
+ all_nums = 0
84
+ img_index = []
85
+ for s in range(len(images_pos)):
86
+ real_image_num = 0
87
+ for (im_s, im_e,index) in images_pos[s]:
88
+ if im_s == -1:
89
+ break
90
+ real_image_num += 1
91
+ all_nums += 1
92
+ img_index.append(index)
93
+
94
+ real_image_nums.append(real_image_num)
95
+ real_images.append(image_tensors[s][:real_image_num])
96
+
97
+ if vit_patch == 1:
98
+ img_index = None
99
+
100
+ if all_nums == 0:
101
+ # when no input image, initialize a fake tensor
102
+ img_input = torch.rand(b, 3, vit_input_resolution, vit_input_resolution).cuda().type(image_tensors.dtype)
103
+ img_embs = vit(img_input)
104
+ img_embs = vit_linear_encoder(img_embs)
105
+ else:
106
+ img_input = torch.cat(real_images)
107
+ img_embs = vit(img_input, img_index = img_index)
108
+ img_embs = vit_linear_encoder(img_embs)
109
+
110
+ encoder_input = encoder_input.clone()
111
+ start = 0
112
+ if all_nums > 0:
113
+ for s, real_image_len in enumerate(real_image_nums):
114
+ current_embs = img_embs[start:start + real_image_len, :] #[30, 256, 4096]
115
+ for ss in range(current_embs.shape[0]):
116
+ im_s, im_e, index = images_pos[s, ss]
117
+ # 子图特征更少
118
+ if index > 0 and vit_patch_mlp:
119
+ encoder_input[s, im_s:im_e,] = current_embs[ss, :(im_e-im_s)]
120
+ else:
121
+ encoder_input[s, im_s:im_e] = current_embs[ss, :]
122
+ start = start + real_image_len
123
+ else:
124
+ # when no input image, to mask vit value
125
+ for s in range(b):
126
+ vit_mask = torch.zeros([vit_token, 1]).cuda()
127
+ current_embs = img_embs[:, start:start + 1]
128
+ encoder_input[1:vit_token + 1, s] = encoder_input[1:vit_token + 1, s] * (1 - vit_mask) + current_embs[:, 0, :] * vit_mask
129
+ start = start + 1
130
+ return encoder_input, input_ids
131
+
132
+
133
+ def group_images_by_max_seq_len(
134
+ images: List[List[Tensor]], patch_size: int,
135
+ max_seq_len: int, adaptor_patch_size: int,
136
+ add_cls_token: bool = False) -> List[List[Tensor]]:
137
+
138
+ groups = []
139
+ group = []
140
+ pos_groups = []
141
+ seq_len = 0
142
+ num_images = 0
143
+ for image_list in images:
144
+ pos_group = []
145
+ for image in image_list:
146
+ num_images += 1
147
+ assert isinstance(image, Tensor)
148
+
149
+ image_dims = image.shape[-2:]
150
+ ph, pw = map(lambda t: t // patch_size, image_dims)
151
+
152
+ image_seq_len = (ph * pw)
153
+ new_image_seq_len = image_seq_len
154
+ grouped_len = seq_len + image_seq_len
155
+ if add_cls_token:
156
+ new_image_seq_len += 1
157
+ grouped_len += num_images
158
+
159
+ assert new_image_seq_len <= max_seq_len, f'image with dimensions {image_dims} exceeds maximum sequence length'
160
+
161
+ if grouped_len > max_seq_len:
162
+ groups.append(group)
163
+ group = []
164
+ seq_len = 0
165
+ num_images = 1
166
+
167
+ group.append(image)
168
+ start = seq_len // (adaptor_patch_size * adaptor_patch_size)
169
+ end = start + image_seq_len//(adaptor_patch_size * adaptor_patch_size)
170
+ batch_idx = len(groups)
171
+ pos_group.append([batch_idx, start, end])
172
+ seq_len += image_seq_len
173
+ pos_groups.append(pos_group)
174
+
175
+ if len(group) > 0:
176
+ groups.append(group)
177
+
178
+ return groups, pos_groups
179
+
180
+
181
+ class AnyResCLIPVisionEmbeddings(nn.Module):
182
+ def __init__(self, config: CLIPVisionConfig):
183
+ super().__init__()
184
+
185
+ self.config = config
186
+ # self.sparse_attn_mask = args.sparse_attn_mask
187
+ # self.use_flash_attn = args.use_flash_attn
188
+ self.embed_dim = config.hidden_size
189
+ self.image_size = config.max_image_size
190
+ self.patch_size = config.patch_size
191
+ self.max_seq_len = config.max_vit_seq_len
192
+ self.adaptor_patch_size = config.adaptor_patch_size
193
+ self.anyres_vit_two_views = config.anyres_vit_two_views
194
+ self.vit_add_patchemb_bias = config.vit_add_patchemb_bias
195
+ self.vit_remove_prenorm = config.vit_remove_prenorm
196
+
197
+ self.patch_embedding = nn.Conv2d(
198
+ in_channels=config.num_channels,
199
+ out_channels=self.embed_dim,
200
+ kernel_size=self.patch_size,
201
+ stride=self.patch_size,
202
+ bias=self.vit_add_patchemb_bias,
203
+ )
204
+
205
+ self.num_patches = (self.image_size // self.patch_size) ** 2
206
+ self.skip_cls_token = True
207
+
208
+ # add interpolate_pos_encoding
209
+ if self.anyres_vit_two_views:
210
+ self.num_positions = self.num_patches
211
+ self.position_embedding = nn.Parameter(torch.randn(1, self.num_positions, self.embed_dim) * 0.02)
212
+ else:
213
+ self.num_positions = self.num_patches + 1
214
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)))
215
+ # self.position_ids = torch.arange(self.num_positions).expand((1, -1))
216
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
217
+
218
+ if not self.vit_remove_prenorm:
219
+ self.pre_layernorm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
220
+
221
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
222
+ """
223
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
224
+ resolution images.
225
+
226
+ Source:
227
+ https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
228
+ """
229
+ num_patches = embeddings.shape[1]
230
+ position_embeddings = self.position_embedding(self.position_ids)
231
+ patch_pos_embed = position_embeddings[:, 1:]
232
+ num_positions = position_embeddings.shape[1] - 1
233
+ if num_patches == num_positions and height == width:
234
+ return patch_pos_embed
235
+ # class_pos_embed = position_embeddings[:, 0]
236
+ dim = embeddings.shape[-1]
237
+ h0 = height // self.patch_size
238
+ w0 = width // self.patch_size
239
+ # we add a small number to avoid floating point error in the interpolation
240
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
241
+ h0, w0 = h0 + 0.1, w0 + 0.1
242
+ patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
243
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
244
+ raw_type = patch_pos_embed.dtype
245
+ patch_pos_embed = nn.functional.interpolate(
246
+ patch_pos_embed.to(torch.float32, non_blocking=True),
247
+ scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
248
+ mode="bilinear",
249
+ align_corners=False,
250
+ )
251
+ patch_pos_embed = patch_pos_embed.to(raw_type, non_blocking=True)
252
+ assert int(h0) == patch_pos_embed.shape[-2] and int(w0) == patch_pos_embed.shape[-1]
253
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
254
+ return patch_pos_embed
255
+
256
+ def rescale_positional_embedding(self, out_size):
257
+ h, w = out_size
258
+ pos_embed_shape = int((self.position_embedding.shape[1]) ** 0.5)
259
+ if (h, w) == (pos_embed_shape, pos_embed_shape):
260
+ return self.position_embedding
261
+ rescaled_positional_embedding = \
262
+ self.position_embedding.new_zeros(1, h*w, self.position_embedding.shape[2])
263
+ pe_2d = self.position_embedding[0].T.contiguous().view(1, -1, pos_embed_shape, pos_embed_shape)
264
+ pe_2d = F.interpolate(pe_2d, out_size, mode='bilinear', align_corners=False).view(-1, h*w)
265
+ rescaled_positional_embedding[0] = pe_2d.T.contiguous()
266
+ return rescaled_positional_embedding
267
+
268
+ def forward_single(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
269
+ if pixel_values.ndim == 3:
270
+ pixel_values = pixel_values[None]
271
+ batch_size, num_channels, height, width = pixel_values.shape
272
+
273
+ if self.anyres_vit_two_views:
274
+ # padding
275
+ pad_h = (self.patch_size - height % self.patch_size) % self.patch_size
276
+ pad_w = (self.patch_size - width % self.patch_size) % self.patch_size
277
+ pixel_values = F.pad(pixel_values, (0, pad_w, 0, pad_h))
278
+
279
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
280
+ b, c, h, w = patch_embeds.shape
281
+
282
+ # (b, hw, c)
283
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
284
+ if self.anyres_vit_two_views:
285
+ embeddings = patch_embeds + self.rescale_positional_embedding(out_size=(h, w))
286
+ else:
287
+ embeddings = patch_embeds + self.interpolate_pos_encoding(patch_embeds, height, width)
288
+ if not self.vit_remove_prenorm:
289
+ embeddings = self.pre_layernorm(embeddings)
290
+ return embeddings, (h, w)
291
+
292
+ def forward(self, images: List[List[Tensor]]):
293
+ '''
294
+ Input:
295
+ images: List[List[Tensor]]
296
+
297
+ Return:
298
+ embeddings: Tensor (B, L, E)
299
+ attn_mask: Tensor (B, L, 2)
300
+ pos_groups: List[List[(batch_idx, start, end)]]
301
+ '''
302
+ batched_images, pos_groups = group_images_by_max_seq_len(
303
+ images, self.patch_size, self.max_seq_len, self.adaptor_patch_size, add_cls_token=not self.skip_cls_token)
304
+ max_seq_len = self.max_seq_len
305
+
306
+ # batched_images is a list of a list
307
+ B = len(batched_images)
308
+ L = max_seq_len
309
+ E = self.embed_dim
310
+
311
+ embeddings = torch.zeros(B, L, E, dtype=self.config.torch_dtype, requires_grad=True).cuda(non_blocking=True)
312
+ attn_mask = embeddings.new_full((B, 1, L, L), False, dtype=torch.bool) # True presents compute
313
+ assert len(images) == len(pos_groups), (len(images), len(pos_groups))
314
+
315
+ batch_images = []
316
+ batch_pos = []
317
+ for images_i, pos_group in zip(images, pos_groups):
318
+ assert len(images_i) == len(pos_group), (len(images_i), len(pos_group))
319
+ for image, pos in zip(images_i, pos_group):
320
+ batch_idx, start, end = pos
321
+ a2 = self.adaptor_patch_size ** 2
322
+ # recover the real number of the input image tokens
323
+ start *= a2
324
+ end *= a2
325
+ emb, _ = self.forward_single(image)
326
+ assert emb.ndim == 3, '(B, L, E)'
327
+ embeddings[batch_idx, start:end] = emb
328
+ attn_mask[batch_idx, :, start:end, start:end] = True
329
+ return embeddings, attn_mask, pos_groups
330
+
331
+
332
+ class CLIPVisionEmbeddings(nn.Module):
333
+ def __init__(self, config: CLIPVisionConfig, add_pre_layernorm=False, skip_cls_token=True, vit_patch=1):
334
+ super().__init__()
335
+ self.config = config
336
+ self.embed_dim = config.hidden_size
337
+ self.image_size = config.image_size
338
+ self.image_size = config.vit_input_resolution
339
+ self.patch_size = config.patch_size
340
+
341
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
342
+
343
+ self.patch_embedding = nn.Conv2d(
344
+ in_channels=config.num_channels,
345
+ out_channels=self.embed_dim,
346
+ kernel_size=self.patch_size,
347
+ stride=self.patch_size,
348
+ bias=False,
349
+ )
350
+
351
+ self.num_patches = (self.image_size // self.patch_size) ** 2
352
+
353
+ self.skip_cls_token = skip_cls_token
354
+
355
+ self.num_positions = self.num_patches + 1
356
+
357
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)))
358
+ if vit_patch > 1:
359
+ self.position_embedding = nn.Embedding(self.num_patches * (vit_patch ** 2 + 1) + 1, self.embed_dim)
360
+ # 0 支持最大16张图,目前写死了,如需其他的需要额外定义参数
361
+ elif vit_patch == 0:
362
+ self.position_embedding = nn.Embedding(self.num_patches * (16 ** 2 + 1) + 1, self.embed_dim)
363
+ else:
364
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
365
+
366
+ if add_pre_layernorm:
367
+ self.pre_layernorm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
368
+ else:
369
+ self.pre_layernorm = None
370
+
371
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
372
+ """
373
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
374
+ resolution images.
375
+
376
+ Source:
377
+ https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
378
+ """
379
+ num_patches = embeddings.shape[1] - 1
380
+ position_embeddings = self.position_embedding(self.position_ids)
381
+ num_positions = position_embeddings.shape[1] - 1
382
+ if num_patches == num_positions and height == width:
383
+ return position_embeddings
384
+ class_pos_embed = position_embeddings[:, 0]
385
+ patch_pos_embed = position_embeddings[:, 1:]
386
+ dim = embeddings.shape[-1]
387
+ h0 = height // self.config.patch_size
388
+ w0 = width // self.config.patch_size
389
+ # we add a small number to avoid floating point error in the interpolation
390
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
391
+ h0, w0 = h0 + 0.1, w0 + 0.1
392
+ patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
393
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
394
+ raw_type = patch_pos_embed.dtype
395
+ patch_pos_embed = nn.functional.interpolate(
396
+ patch_pos_embed.float(),
397
+ scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
398
+ mode="bicubic",
399
+ align_corners=False,
400
+ )
401
+ # print(patch_pos_embed.shape)
402
+ patch_pos_embed = patch_pos_embed.to(raw_type)
403
+ assert int(h0) == patch_pos_embed.shape[-2] and int(w0) == patch_pos_embed.shape[-1]
404
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
405
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
406
+
407
+
408
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding: bool = False, img_index=None) -> torch.Tensor:
409
+ batch_size, num_channels, height, width = pixel_values.shape
410
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
411
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
412
+ if self.skip_cls_token:
413
+ embeddings = patch_embeds
414
+ if img_index is None:
415
+ position_ids = self.position_ids[:,1:]
416
+ embeddings = embeddings + self.position_embedding(position_ids)
417
+ else:
418
+ position_ids = (torch.tensor(img_index).cuda() * (self.num_positions - 1)).unsqueeze(1).repeat(1, self.num_positions - 1) \
419
+ + self.position_ids.expand(batch_size, -1)[:, 1:]
420
+ embeddings = embeddings + self.position_embedding(position_ids)
421
+ else:
422
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
423
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
424
+ if interpolate_pos_encoding:
425
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
426
+ else:
427
+ if img_index is None:
428
+ embeddings = embeddings + self.position_embedding(self.position_ids)
429
+ else:
430
+ position_ids = self.position_ids.expand(batch_size,-1)[:,0].unsqueeze(1)
431
+ new_position = (torch.tensor(img_index).cuda() * (self.num_positions -1)).unsqueeze(1).repeat(1,self.num_positions-1) + self.position_ids.expand(batch_size,-1)[:,1:]
432
+ position_ids = torch.cat([position_ids,new_position],dim=1)
433
+ embeddings = embeddings + self.position_embedding(position_ids)
434
+ if self.pre_layernorm is not None:
435
+ embeddings = self.pre_layernorm(embeddings)
436
+ return embeddings
437
+
438
+
439
+ class NaVitTransformer(nn.Module):
440
+ def __init__(self, config: HunYuanConfig, vit_config: CLIPVisionConfig):
441
+ super().__init__()
442
+ self.config = config
443
+ self.vit_config = vit_config
444
+ with self.prepare_args(config, vit_config):
445
+ self._use_sdpa = config._attn_implementation == "sdpa"
446
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
447
+ self.layers = nn.ModuleList(
448
+ [HunYuanDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
449
+ )
450
+
451
+ @contextmanager
452
+ def prepare_args(self, config, vit_config):
453
+ hidden_act = config.hidden_act
454
+ hidden_size = config.hidden_size
455
+ ffn_hidden_size = config.intermediate_size
456
+ num_attention_heads = config.num_attention_heads
457
+ num_key_value_heads = config.num_key_value_heads
458
+ attention_head_dim = config.attention_head_dim
459
+ use_qk_norm = config.use_qk_norm
460
+ use_rotary_pos_emb = config.use_rotary_pos_emb
461
+ num_hidden_layers = config.num_hidden_layers
462
+ rms_norm_eps = config.rms_norm_eps
463
+ attention_dropout = config.attention_dropout
464
+ # hidden_dropout = config.hidden_dropout
465
+ norm_type = config.norm_type
466
+ attention_bias = config.attention_bias
467
+ mlp_bias = config.mlp_bias
468
+ use_mla = config.use_mla
469
+ num_experts = config.num_experts
470
+ _attn_implementation = config._attn_implementation
471
+
472
+ config.hidden_act = vit_config.hidden_act
473
+ config.hidden_size = vit_config.hidden_size
474
+ config.intermediate_size = vit_config.intermediate_size
475
+ config.num_attention_heads = vit_config.num_attention_heads
476
+ config.num_key_value_heads = None
477
+ config.attention_head_dim = vit_config.hidden_size // vit_config.num_attention_heads
478
+ config.use_qk_norm = False
479
+ config.use_rotary_pos_emb = False
480
+ config.num_hidden_layers = vit_config.num_hidden_layers
481
+ config.rms_norm_eps = vit_config.layer_norm_eps
482
+ config.attention_dropout = vit_config.attention_dropout
483
+ # config.hidden_dropout = vit_config.hidden_dropout
484
+ config.norm_type = config.vit_norm_type
485
+ config.attention_bias = True
486
+ config.mlp_bias = True
487
+ config.use_mla = False
488
+ config.num_experts = 1
489
+ config._attn_implementation = "eager"
490
+
491
+ yield
492
+ config.hidden_act = hidden_act
493
+ config.hidden_size = hidden_size
494
+ config.intermediate_size = ffn_hidden_size
495
+ config.num_attention_heads = num_attention_heads
496
+ config.num_key_value_heads = num_key_value_heads
497
+ config.attention_head_dim = attention_head_dim
498
+ config.use_qk_norm = use_qk_norm
499
+ config.use_rotary_pos_emb = use_rotary_pos_emb
500
+ config.num_hidden_layers = num_hidden_layers
501
+ config.rms_norm_eps = rms_norm_eps
502
+ config.attention_dropout = attention_dropout
503
+ # config.hidden_dropout = hidden_dropout
504
+ config.attention_bias = attention_bias
505
+ config.mlp_bias = mlp_bias
506
+ config.norm_type = norm_type
507
+ config.use_mla = use_mla
508
+ config.num_experts = num_experts
509
+ config._attn_implementation = _attn_implementation
510
+
511
+ def forward(
512
+ self,
513
+ pixel_values: Optional[torch.FloatTensor] = None,
514
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
515
+
516
+ hidden_states, attention_mask, img_pos = self.embeddings(pixel_values)
517
+ attention_mask = attention_mask.int()
518
+ batch_size, seq_length, _ = hidden_states.shape
519
+ past_key_values_length = 0
520
+
521
+ if self._use_flash_attention_2:
522
+ # 2d mask is passed through the layers
523
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
524
+ elif self._use_sdpa:
525
+ # output_attentions=True can not be supported when using SDPA, and we fall back on
526
+ # the manual implementation that requires a 4D causal mask in all cases.
527
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
528
+ attention_mask,
529
+ (batch_size, seq_length),
530
+ hidden_states,
531
+ past_key_values_length,
532
+ )
533
+ else:
534
+ attention_mask = _prepare_4d_causal_attention_mask(
535
+ attention_mask,
536
+ (batch_size, seq_length),
537
+ hidden_states,
538
+ past_key_values_length,
539
+ )
540
+
541
+ for layer_idx, decoder_layer in enumerate(self.layers):
542
+ layer_outputs = decoder_layer(
543
+ hidden_states,
544
+ attention_mask=attention_mask
545
+ )
546
+ hidden_states = layer_outputs[0]
547
+
548
+ return hidden_states, img_pos
549
+
550
+
551
+ class AnyResVitTransformer(NaVitTransformer):
552
+ def __init__(self, config: HunYuanConfig, vit_config: CLIPVisionConfig, anyres_vit_max_image_size):
553
+ super().__init__(config, vit_config)
554
+ old_anyres_vit_max_image_size = vit_config.max_image_size
555
+ anyres_vit_max_image_size = anyres_vit_max_image_size or old_anyres_vit_max_image_size
556
+ vit_config.max_image_size = anyres_vit_max_image_size
557
+ vit_config.torch_dtype = config.torch_dtype
558
+ vit_config.anyres_vit_two_views = config.anyres_vit_two_views
559
+ vit_config.vit_remove_prenorm = config.vit_remove_prenorm
560
+ vit_config.vit_add_patchemb_bias = config.vit_add_patchemb_bias
561
+ self.embeddings = AnyResCLIPVisionEmbeddings(vit_config)
562
+ vit_config.max_image_size = old_anyres_vit_max_image_size
563
+
564
+ def fix_embeddings_fn(self, pixel_values):
565
+ # (B, L, E)
566
+ embeddings, hw = self.embeddings.forward_single(pixel_values)
567
+ embeddings = self.embeddings.pre_layernorm(embeddings)
568
+ return embeddings
569
+
570
+
571
+ class CLIPVisionTransformer(nn.Module):
572
+ def __init__(self, config: HunYuanConfig, vit_config: CLIPVisionConfig):
573
+ super().__init__()
574
+ embed_dim = vit_config.hidden_size
575
+
576
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=vit_config.layer_norm_eps)
577
+ self.embeddings = CLIPVisionEmbeddings(vit_config, skip_cls_token=config.skip_cls_token, vit_patch=config.vit_patch)
578
+
579
+ with self.prepare_args(config, vit_config):
580
+ self.layers = nn.ModuleList(
581
+ [HunYuanDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
582
+ )
583
+
584
+ @contextmanager
585
+ def prepare_args(self, config, vit_config):
586
+ hidden_act = config.hidden_act
587
+ hidden_size = config.hidden_size
588
+ ffn_hidden_size = config.intermediate_size
589
+ num_attention_heads = config.num_attention_heads
590
+ num_key_value_heads = config.num_key_value_heads
591
+ attention_head_dim = config.attention_head_dim
592
+ use_qk_norm = config.use_qk_norm
593
+ use_rotary_pos_emb = config.use_rotary_pos_emb
594
+ num_hidden_layers = config.num_hidden_layers
595
+ rms_norm_eps = config.rms_norm_eps
596
+ attention_dropout = config.attention_dropout
597
+ # hidden_dropout = config.hidden_dropout
598
+ norm_type = config.norm_type
599
+ attention_bias = config.attention_bias
600
+ mlp_bias = config.mlp_bias
601
+ use_mla = config.use_mla
602
+ num_experts = config.num_experts
603
+ _attn_implementation = config._attn_implementation
604
+
605
+ config.hidden_act = vit_config.hidden_act
606
+ config.hidden_size = vit_config.hidden_size
607
+ config.intermediate_size = vit_config.intermediate_size
608
+ config.num_attention_heads = vit_config.num_attention_heads
609
+ config.num_key_value_heads = None
610
+ config.attention_head_dim = vit_config.hidden_size // vit_config.num_attention_heads
611
+ config.use_qk_norm = False
612
+ config.use_rotary_pos_emb = False
613
+ config.num_hidden_layers = vit_config.num_hidden_layers
614
+ config.rms_norm_eps = vit_config.layer_norm_eps
615
+ config.attention_dropout = vit_config.attention_dropout
616
+ # config.hidden_dropout = 0.0
617
+ config.norm_type = "fused"
618
+ config.attention_bias = True
619
+ config.mlp_bias = True
620
+ config.use_mla = False
621
+ config.num_experts = 1
622
+ config._attn_implementation = "eager"
623
+
624
+ yield
625
+
626
+ config.hidden_act = hidden_act
627
+ config.hidden_size = hidden_size
628
+ config.intermediate_size = ffn_hidden_size
629
+ config.num_attention_heads = num_attention_heads
630
+ config.num_key_value_heads = num_key_value_heads
631
+ config.attention_head_dim = attention_head_dim
632
+ config.use_qk_norm = use_qk_norm
633
+ config.use_rotary_pos_emb = use_rotary_pos_emb
634
+ config.num_hidden_layers = num_hidden_layers
635
+ config.rms_norm_eps = rms_norm_eps
636
+ config.attention_dropout = attention_dropout
637
+ # config.hidden_dropout = hidden_dropout
638
+ config.norm_type = norm_type
639
+ config.attention_bias = attention_bias
640
+ config.mlp_bias = mlp_bias
641
+ config.use_mla = use_mla
642
+ config.num_experts = num_experts
643
+ config._attn_implementation = _attn_implementation
644
+
645
+ def forward(
646
+ self,
647
+ pixel_values: Optional[torch.FloatTensor] = None,
648
+ interpolate_pos_encoding: Optional[bool] = None,
649
+ img_index=None
650
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
651
+ r"""
652
+ Returns:
653
+
654
+ """
655
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, img_index=img_index)
656
+ hidden_states = self.pre_layrnorm(hidden_states)
657
+ batch = hidden_states.shape[0]
658
+ seq_len = hidden_states.shape[1]
659
+ device = hidden_states.device
660
+ attention_mask = torch.ones(batch, 1, seq_len, seq_len, dtype=torch.float32, device=device)
661
+
662
+ for layer_idx, decoder_layer in enumerate(self.layers):
663
+ layer_outputs = decoder_layer(
664
+ hidden_states,
665
+ attention_mask=attention_mask
666
+ )
667
+ hidden_states = layer_outputs[0]
668
+
669
+ return hidden_states
670
+
671
+
672
+ class Vit(torch.nn.Module):
673
+ def __init__(self, config, resampler_token=64, pool_rate=2):
674
+ super().__init__()
675
+ self.config = config
676
+ self.vit_mapping_type = config.vit_mapping_type
677
+ self.anyres_vit_max_image_size = config.anyres_vit_max_image_size
678
+ self.skip_cls_token = config.skip_cls_token
679
+ self.pool_rate = pool_rate
680
+ self.vit_type = self.config.vit_type
681
+ self.anyres_vit_two_views = self.config.anyres_vit_two_views
682
+ if self.vit_type in ['Vit-g', 'Vit-bigG', 'NaVit', 'EvaVit', 'AnyResVit']:
683
+ self.img_init(resampler_token, config.vit_input_resolution, config.vit_mapping_type, pool_rate)
684
+ else:
685
+ raise NotImplementedError(f"unsupported vit type: {self.vit_type}")
686
+
687
+ def img_init(self, resampler_token=64, vit_input_resolution=224, vit_mapping_type='resampler', pool_rate=2):
688
+ if self.vit_type == 'AnyResVit':
689
+ vit_config = json.load(open(f"{self.config.vit_path}/config.json"))
690
+ self.vit_config = types.SimpleNamespace(**vit_config["vision_config"])
691
+ self.vit_config.image_size = vit_input_resolution
692
+ self.vit = AnyResVitTransformer(self.config, self.vit_config, self.anyres_vit_max_image_size)
693
+ elif self.vit_type == 'Vit-g':
694
+ vit_config = json.load(open(f"{self.config.vit_path}/config.json"))
695
+ self.vit_config = types.SimpleNamespace(**{**vit_config["vision_config_dict"],**vit_config["vision_config"]})
696
+ self.vit_config.vit_input_resolution = vit_input_resolution
697
+ self.vit = CLIPVisionTransformer(self.config, self.vit_config)
698
+ else:
699
+ assert False, "other vit_types are not supported"
700
+
701
+ if self.vit_mapping_type == 'simple_conv_mlp':
702
+ self.perceive = SimpleConvMlp(self.vit_config.hidden_size, self.config.hidden_size, self.config.anyres_pooling_size, \
703
+ self.config.vit_used_rms_norm, self.config.rms_norm_eps, poolmlp=False, twoview=True)
704
+ elif self.vit_mapping_type == 'oryx_mlp':
705
+ self.perceive = OryxMLPv2(self.vit_config.hidden_size, self.config.hidden_size, twoview=True, use_pe=False)
706
+ elif self.vit_mapping_type == 'mlp':
707
+ self.mlp_depth = 2
708
+ # one mlp layer already in gpt_model.py
709
+ mlp_hidden_size = self.vit_config.hidden_size
710
+ if self.vit_type in ['NaVit', 'EvaVit']:
711
+ mlp_hidden_size *= self.vit_config.adaptor_patch_size **2
712
+ if self.mlp_depth > 1:
713
+ mlp_modules = [torch.nn.Linear(mlp_hidden_size, self.config.hidden_size), torch.nn.GELU()]
714
+ if self.vit_type in ['NaVit', 'EvaVit']:
715
+ for _ in range(1, self.mlp_depth):
716
+ mlp_modules.append(torch.nn.Linear(self.config.hidden_size, self.config.hidden_size))
717
+ mlp_modules.append(torch.nn.GELU())
718
+ self.perceive = torch.nn.Sequential(*mlp_modules)
719
+ else:
720
+ assert False, "other vit_mapping_types are not supported"
721
+
722
+ self.vit_patch_mlp = (self.config.vit_patch > 1 and self.vit_mapping_type == 'mlp') or self.config.vit_patch == 0
723
+ for name, param in self.named_parameters():
724
+ setattr(param, "is_vit_param", True)
725
+
726
+ def forward(self, images, img_index=None):
727
+ if self.vit_type in ['AnyResVit']:
728
+ dtype = self.config.torch_dtype
729
+ device = torch.cuda.current_device()
730
+
731
+ images_size = []
732
+ for i in range(len(images)):
733
+ images_size.append([])
734
+ for j in range(len(images[i])):
735
+ images_size[i].append((images[i][j].size()[1] // self.vit_config.patch_size, images[i][j].size()[2] // self.vit_config.patch_size))
736
+
737
+ images_feats, img_batch_pos = self.vit(pixel_values=images)
738
+ a2 = self.vit_config.adaptor_patch_size ** 2
739
+
740
+ if self.anyres_vit_two_views:
741
+ step = 2
742
+ else:
743
+ step = 1
744
+ perceive_fn = lambda x, img_size, is_video: self.perceive(x, img_size, is_video=is_video)
745
+ images_list = []
746
+ images_fix_i = 0
747
+ num_img_batch_pos = len(img_batch_pos)
748
+ for i in range(num_img_batch_pos): # batch_id
749
+ for j in range(0, len(img_batch_pos[i]), step):
750
+ if self.anyres_vit_two_views:
751
+ lower_idx, lower_begin, lower_end = img_batch_pos[i][j]
752
+ lower_begin = lower_begin * a2
753
+ lower_end = lower_end * a2
754
+ higher_idx, higher_begin, higher_end = img_batch_pos[i][j + 1]
755
+ higher_begin = higher_begin * a2
756
+ higher_end = higher_end * a2
757
+ lower_res_feat = images_feats[lower_idx, lower_begin:lower_end].unsqueeze(0)
758
+ higher_res_feat = images_feats[higher_idx, higher_begin:higher_end].unsqueeze(0)
759
+ lower_images_size = images_size[i][j]
760
+ higher_images_size = images_size[i][j + 1]
761
+ images_list.append(self.perceive(lower_res_feat, lower_images_size, higher_res_feat, higher_images_size))
762
+ else:
763
+ idx, begin, end = img_batch_pos[i][j]
764
+ begin = begin * a2
765
+ end = end * a2
766
+ is_video = hasattr(images[i][j],'_is_video') and images[i][j]._is_video
767
+ images_list.append(perceive_fn(images_feats[idx, begin:end].unsqueeze(0), images_size[i][j], is_video=is_video))
768
+
769
+ images = torch.cat(images_list, dim=1)
770
+
771
+ new_batch_pos = []
772
+ k = 0; cur_len = 0
773
+ for i in range(len(images_size)):
774
+ new_batch_pos.append([])
775
+ for j in range(0, len(images_size[i]), step):
776
+ new_pos = [0, cur_len, cur_len + images_list[k].size(1)]
777
+ cur_len += images_list[k].size(1)
778
+ k += 1
779
+ new_batch_pos[i].append(new_pos)
780
+ return images, new_batch_pos
781
+ elif self.vit_type == 'Vit-g':
782
+ images = self.vit(pixel_values=images, interpolate_pos_encoding=False, img_index=img_index)
783
+ else:
784
+ assert False, "other vit_types are not supported"
785
+
786
+ if self.vit_mapping_type == 'mlp':
787
+ if self.vit_type in ['Vit-g'] and not self.skip_cls_token:
788
+ images = images[:,1:,:]
789
+ b, v, d = images.shape
790
+ s = int(math.sqrt(v))
791
+ images = images.reshape(b, s, s, d)
792
+
793
+
794
+ if self.vit_patch_mlp and img_index is not None:
795
+ L_tensor = torch.tensor(img_index)
796
+ device = images.device
797
+ # 获取子图位置
798
+ nonzero_indices = torch.nonzero(L_tensor).squeeze().to(device)
799
+ # 获取主图位置
800
+ zero_indices = torch.nonzero(L_tensor == 0).squeeze().to(device)
801
+
802
+
803
+ images_nonzero = torch.index_select(images,0, nonzero_indices).to(device)
804
+ images_zero = torch.index_select(images, 0, zero_indices).to(device)
805
+
806
+ # 子图额外多pool一次
807
+ pool_rate = self.pool_rate * 2
808
+ images_nonzero = images_nonzero.reshape(-1, s // pool_rate, pool_rate, s // pool_rate, pool_rate, d)
809
+ images_nonzero = images_nonzero.permute(0, 1, 3, 5, 2, 4).reshape(-1, (s // pool_rate) * (s // pool_rate), d,
810
+ pool_rate*pool_rate).mean(-1)
811
+
812
+ # 为了组batch折衷方案
813
+ images_nonzero = F.pad(images_nonzero, (0, 0, 0, (s // self.pool_rate) * (s // self.pool_rate)- (s // pool_rate) * (s // pool_rate)))
814
+ images_zero = images_zero.reshape(-1, s // self.pool_rate, self.pool_rate, s // self.pool_rate, self.pool_rate, d)
815
+ images_zero = images_zero.permute(0, 1, 3, 5, 2, 4).reshape(-1, (s // self.pool_rate) * (s // self.pool_rate), d,
816
+ self.pool_rate*self.pool_rate).mean(-1)
817
+ # 组batch
818
+ images = torch.zeros(b, (s // self.pool_rate) * (s // self.pool_rate), d).to(device).to(images.dtype)
819
+ images.index_copy_(0, nonzero_indices, images_nonzero)
820
+ images.index_copy_(0, zero_indices, images_zero)
821
+
822
+ if self.mlp_depth >= 2:
823
+ images = self.perceive(images)
824
+ else:
825
+ if s % self.pool_rate == 0:
826
+ images = images.reshape(b, s//self.pool_rate, self.pool_rate, s//self.pool_rate, self.pool_rate, d)
827
+ images = images.permute(0, 1, 3, 5, 2, 4).reshape(b, (s//self.pool_rate) * (s//self.pool_rate), d, -1).mean(-1)
828
+ if self.mlp_depth >= 2:
829
+ images = self.perceive(images)
830
+ else:
831
+ raise ValueError
832
+ return images
833
+
834
+
835
+ class SimpleConvMlp(nn.Module):
836
+ def __init__(self, in_channels, out_channels, anyres_pooling_size, vit_used_rms_norm, rms_norm_eps, twoview=False, poolmlp=True, cat_extra_token=True):
837
+ super().__init__()
838
+
839
+ embed_std = 1 / math.sqrt(out_channels)
840
+ if poolmlp:
841
+ # if args.learnable_mlp_pooling_size is not None:
842
+ # in_channels *= args.learnable_mlp_pooling_size ** 2
843
+ self.proj = nn.Sequential(
844
+ nn.Linear(in_channels, out_channels),
845
+ nn.GELU()
846
+ )
847
+ self.vit_linear_encoder = nn.Linear(out_channels, out_channels)
848
+ self.image_newline = nn.Parameter(
849
+ torch.randn(out_channels) * embed_std
850
+ )
851
+ else:
852
+ self.proj = nn.Sequential(
853
+ nn.Conv2d(in_channels, in_channels * 2, kernel_size=anyres_pooling_size, stride=anyres_pooling_size),
854
+ nn.GELU(),
855
+ nn.Conv2d(in_channels * 2, in_channels * 4, kernel_size=1),
856
+ )
857
+ self.mlp = nn.Linear(in_channels * 4, out_channels)
858
+ self.image_newline = nn.Parameter(
859
+ torch.randn(in_channels * 4) * embed_std
860
+ )
861
+ self.poolmlp = poolmlp
862
+
863
+ self.image_begin = nn.Parameter(
864
+ torch.randn(out_channels) * embed_std
865
+ )
866
+ self.image_end = nn.Parameter(
867
+ torch.randn(out_channels) * embed_std
868
+ )
869
+
870
+ if twoview:
871
+ self.image_sep = nn.Parameter(
872
+ torch.randn(out_channels) * embed_std
873
+ )
874
+
875
+ self.cat_extra_token = cat_extra_token
876
+ self.use_rms_norm = vit_used_rms_norm
877
+ if self.use_rms_norm:
878
+ self.before_rms = HunYuanRMSNorm(in_channels, eps=rms_norm_eps)
879
+ self.after_rms = HunYuanRMSNorm(out_channels, eps=rms_norm_eps)
880
+
881
+ def forward(self, x, size=(16,16), x2=None, size2=(16, 16), is_video=False):
882
+ return self.single_forward(x=x, size=size, x2=x2, size2=size2, is_video=is_video)
883
+
884
+ def single_forward(self, x, size=(16,16), x2=None, size2=(16, 16), is_video=False):
885
+ remove_vit_special_tokens = False
886
+ learnable_mlp_pooling_size = None
887
+ if self.use_rms_norm:
888
+ x = self.before_rms(x)
889
+ h, w = size
890
+ dtype = x.dtype
891
+ x = x.permute(0, 2, 1).reshape(x.shape[0], -1, h, w)
892
+ if self.poolmlp:
893
+ if learnable_mlp_pooling_size is None:
894
+ x = F.avg_pool2d(x, anyres_pooling_size)
895
+ x = self.proj(x.permute(0, 2, 3, 1)) # b, h, w, c
896
+ else:
897
+ x = x.permute(0, 2, 3, 1) # b, h, w, c
898
+ x = x.reshape(x.shape[0], h // learnable_mlp_pooling_size, learnable_mlp_pooling_size,
899
+ w // learnable_mlp_pooling_size, learnable_mlp_pooling_size, -1)
900
+ x = x.permute(0, 1, 3, 2, 4, 5).reshape(x.shape[0], h // learnable_mlp_pooling_size, w // learnable_mlp_pooling_size, -1)
901
+ x = self.proj(x)
902
+ x = self.vit_linear_encoder(x)
903
+ b, h, w, c = x.shape
904
+ if not remove_vit_special_tokens:
905
+ x = torch.cat([
906
+ x,
907
+ self.image_newline.reshape(1, 1, 1, c).expand(b, h, 1, c).to(dtype, non_blocking=True)
908
+ ], dim=2)
909
+ x = x.reshape(b, -1, c)
910
+ else:
911
+ x = self.proj(x) #b,c,h,w
912
+ if is_video:
913
+ video_avgpool_size = 2
914
+ stride = 2
915
+ x = F.avg_pool2d(x, kernel_size = video_avgpool_size, stride = stride)
916
+ b, c, h, w = x.shape
917
+ if not remove_vit_special_tokens:
918
+ x = torch.cat([
919
+ x,
920
+ self.image_newline.reshape(1, c, 1, 1).expand(b, c, h, 1).to(dtype, non_blocking=True)
921
+ ], dim=-1)
922
+ x = x.reshape(b, c, -1).permute(0, 2, 1)
923
+ x = self.mlp(x)
924
+
925
+
926
+ if x2 is not None:
927
+ h2, w2 = size2
928
+ x2 = x2.permute(0, 2, 1).reshape(x2.shape[0], -1, h2, w2)
929
+ if self.poolmlp:
930
+ x2 = F.avg_pool2d(x2, 2)
931
+ x2 = self.proj(x2.permute(0, 2, 3, 1)) # b, h, w, c
932
+ x2 = self.vit_linear_encoder(x2)
933
+ b2, h2, w2, c2 = x2.shape
934
+ if not remove_vit_special_tokens:
935
+ x2 = torch.cat([
936
+ x2,
937
+ self.image_newline.reshape(1, 1, 1, c2).expand(b2, h2, 1, c2).to(dtype, non_blocking=True)
938
+ ], dim=2)
939
+ x2 = x2.reshape(b2, -1, c2)
940
+ else:
941
+ x2 = self.proj(x2)
942
+ b2, c2, h2, w2 = x2.shape
943
+ if not remove_vit_special_tokens:
944
+ x2 = torch.cat([
945
+ x2,
946
+ self.image_newline.reshape(1, c2, 1, 1).expand(b2, c2, h2, 1).to(dtype, non_blocking=True)
947
+ ], dim=-1)
948
+ x2 = x2.reshape(b2, c2, -1).permute(0, 2, 1) #b,n,c
949
+ x2 = self.mlp(x2)
950
+
951
+ sep = self.image_sep.reshape(1, 1, -1).expand(b2, 1, x2.shape[-1]).to(dtype, non_blocking=True)
952
+
953
+ x = torch.cat([x, sep, x2], dim=1)
954
+
955
+ if self.cat_extra_token:
956
+ begin = self.image_begin.reshape(1, 1, -1).expand(b, 1, x.shape[-1]).to(dtype, non_blocking=True)
957
+ end = self.image_end.reshape(1, 1, -1).expand(b, 1, x.shape[-1]).to(dtype, non_blocking=True)
958
+ x = torch.cat([begin, x, end], dim=1)
959
+
960
+ if self.use_rms_norm:
961
+ return self.after_rms(x)
962
+ else:
963
+ return x
964
+
965
+
966
+ class NormalizedDwPooler(nn.Module):
967
+ def __init__(self, dim):
968
+ super().__init__()
969
+ self.dim = dim
970
+ self.predictor = nn.Sequential(
971
+ nn.Linear(dim*2, dim),
972
+ nn.GELU(),
973
+ nn.Linear(dim, dim),
974
+ )
975
+
976
+ def forward(self, x, forward_type='2x'):
977
+ B, H, W, C = x.shape
978
+
979
+ if forward_type == '2x':
980
+ new_x = x.reshape(B, H//2, 2, W//2, 2, C).permute(0, 1, 3, 2, 4, 5).reshape(B, H//2, W//2, 4, C)
981
+ pooled_x = new_x.mean(-2, keepdim=True).expand(-1, -1, -1, 4, -1)
982
+ fused_x = torch.cat([new_x, pooled_x], dim=-1)
983
+ elif forward_type == '1x':
984
+ new_x = x.reshape(B, H, W, 1, C)
985
+ fused_x = torch.cat([new_x, new_x], dim=-1)
986
+ elif forward_type == '4x':
987
+ new_x = x.reshape(B, H//4, 4, W//4, 4, C).permute(0, 1, 3, 2, 4, 5).reshape(B, H//4, W//4, 16, C)
988
+ pooled_x = new_x.mean(-2, keepdim=True).expand(-1, -1, -1, 16, -1)
989
+ fused_x = torch.cat([new_x, pooled_x], dim=-1)
990
+
991
+ score = self.predictor(fused_x)
992
+ normalized_score = F.softmax(score, dim=-2)
993
+ new_x = (new_x * normalized_score).sum(dim=-2)
994
+ return new_x
995
+
996
+
997
+ class OryxMLPv2(nn.Module):
998
+ def __init__(self, in_channels, out_channels, twoview=False, use_pe=False):
999
+ super().__init__()
1000
+
1001
+ self.proj1 = nn.Linear(in_channels, out_channels)
1002
+ self.proj2 = nn.Linear(out_channels, out_channels)
1003
+ self.act = nn.GELU()
1004
+ self.pooler = NormalizedDwPooler(out_channels)
1005
+ embed_std = 1 / math.sqrt(out_channels)
1006
+
1007
+ self.use_pe = use_pe
1008
+ if not use_pe:
1009
+ self.image_newline = nn.Parameter(
1010
+ torch.randn(out_channels) * embed_std
1011
+ )
1012
+ self.image_begin = nn.Parameter(
1013
+ torch.randn(out_channels) * embed_std
1014
+ )
1015
+ self.image_end = nn.Parameter(
1016
+ torch.randn(out_channels) * embed_std
1017
+ )
1018
+
1019
+ if twoview:
1020
+ self.image_sep = nn.Parameter(
1021
+ torch.randn(out_channels) * embed_std
1022
+ )
1023
+
1024
+ def forward(self, x, size=(16,16), x2=None, size2=(16, 16), is_video=False):
1025
+ h, w = size
1026
+ dtype = x.dtype
1027
+ x = x.reshape(x.shape[0], h, w, -1)
1028
+ # x = self.pooler(x, forward_type=REGIONAL_POOL)
1029
+ # x = self.proj(x) #b,h,w, c
1030
+ x = self.proj1(x)
1031
+ x = self.pooler(x, forward_type='2x')
1032
+ x = self.act(x)
1033
+ x = self.proj2(x)
1034
+
1035
+
1036
+ b, h, w, c = x.shape
1037
+ if not self.use_pe:
1038
+ x = torch.cat([
1039
+ x,
1040
+ self.image_newline.reshape(1, 1, 1, c).expand(b, h, 1, c).to(dtype)
1041
+ ], dim=2)
1042
+ else:
1043
+ pe_h = torch.arange(h, dtype=torch.long, device=x.device).reshape(1, h, 1, 1).expand(b, h, w, 1).reshape(b, h*w, 1)
1044
+ pe_w = torch.arange(w, dtype=torch.long, device=x.device).reshape(1, 1, w, 1).expand(b, h, w, 1).reshape(b, h*w, 1)
1045
+ pe = torch.cat([pe_h, pe_w], dim=-1)
1046
+
1047
+ x = x.reshape(b, -1, c)
1048
+
1049
+ if x2 is not None:
1050
+ h2, w2 = size2
1051
+ x2 = x2.reshape(x2.shape[0], h2, w2, -1)
1052
+ # x2 = self.pooler(x2, forward_type=REGIONAL_POOL)
1053
+ ## x2 = self.proj(x2) #b,h,w, c
1054
+ x2 = self.proj1(x2)
1055
+ x2 = self.pooler(x2, forward_type='2x')
1056
+ x2 = self.act(x2)
1057
+ x2 = self.proj2(x2)
1058
+
1059
+ b2, h2, w2, c2 = x2.shape
1060
+ if not self.use_pe:
1061
+ x2 = torch.cat([
1062
+ x2,
1063
+ self.image_newline.reshape(1, 1, 1, c).expand(b, h2, 1, c).to(dtype)
1064
+ ], dim=2)
1065
+ x2 = x2.reshape(b, -1, c)
1066
+ sep = self.image_sep.reshape(1, 1, -1).expand(b, 1, c2).to(dtype)
1067
+ x = torch.cat([x, sep, x2], dim=1)
1068
+
1069
+ begin = self.image_begin.reshape(1, 1, -1).expand(b, 1, c).to(dtype)
1070
+ end = self.image_end.reshape(1, 1, -1).expand(b, 1, c).to(dtype)
1071
+ x = torch.cat([begin, x, end], dim=1)
1072
+ # print(x.shape, x2.shape, h, w, h2, w2)
1073
+ # print("vit rank = " + str(torch.distributed.get_rank()) +" x = " + str(x))
1074
+ if self.use_pe:
1075
+ zero_pad = torch.zeros(b, 1, 2, device=x.device, dtype=torch.long)
1076
+ pe = torch.cat([zero_pad, pe, zero_pad], dim=1)
1077
+ assert pe.shape[1] == x.shape[1]
1078
+ return x, pe
1079
+ else:
1080
+ nseq = x.shape[1]
1081
+ fake_pe = torch.zeros(b, nseq, 2, device=x.device, dtype=torch.long)
1082
+ return x #, fake_pe
1083
+