Prompt48 commited on
Commit
4634141
·
verified ·
1 Parent(s): bf06593

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

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