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

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//hunyuan_v1_dense//modular_hunyuan_v1_dense.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (C) 2025 THL A29 Limited, a Tencent company and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch HunYuanDenseV1 model."""
16
+
17
+ from typing import Callable, Optional
18
+
19
+ import torch
20
+ from torch import nn
21
+
22
+ from transformers.cache_utils import Cache
23
+ from transformers.utils import (
24
+ logging,
25
+ )
26
+
27
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
28
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
29
+ from ...processing_utils import Unpack
30
+ from ...utils import TransformersKwargs
31
+ from ..llama.modeling_llama import (
32
+ LlamaAttention,
33
+ LlamaDecoderLayer,
34
+ LlamaForCausalLM,
35
+ LlamaForSequenceClassification,
36
+ LlamaMLP,
37
+ LlamaModel,
38
+ LlamaPreTrainedModel,
39
+ LlamaRMSNorm,
40
+ apply_rotary_pos_emb,
41
+ eager_attention_forward,
42
+ )
43
+ from .configuration_hunyuan_v1_dense import HunYuanDenseV1Config
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class HunYuanDenseV1RMSNorm(LlamaRMSNorm):
50
+ pass
51
+
52
+
53
+ class HunYuanDenseV1MLP(LlamaMLP):
54
+ def __init__(self, config: HunYuanDenseV1Config, layer_idx=None, is_shared_mlp=False):
55
+ super().__init__(config)
56
+ self.layer_idx = layer_idx
57
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
58
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
59
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
60
+
61
+
62
+ class HunYuanDenseV1Attention(LlamaAttention):
63
+ def __init__(self, config: HunYuanDenseV1Config, layer_idx: int):
64
+ super().__init__(config, layer_idx)
65
+ self.query_layernorm = HunYuanDenseV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
66
+ self.key_layernorm = HunYuanDenseV1RMSNorm(self.head_dim, eps=config.rms_norm_eps)
67
+
68
+ def forward(
69
+ self,
70
+ hidden_states: torch.Tensor,
71
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
72
+ attention_mask: Optional[torch.Tensor],
73
+ past_key_values: Optional[Cache] = None,
74
+ cache_position: Optional[torch.LongTensor] = None,
75
+ **kwargs: Unpack[TransformersKwargs],
76
+ ) -> tuple[torch.Tensor, torch.Tensor]:
77
+ input_shape = hidden_states.shape[:-1]
78
+ hidden_shape = (*input_shape, -1, self.head_dim)
79
+
80
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
81
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
82
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
83
+
84
+ cos, sin = position_embeddings
85
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
86
+ query_states = self.query_layernorm(query_states)
87
+ key_states = self.key_layernorm(key_states)
88
+
89
+ if past_key_values is not None:
90
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
91
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
92
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
93
+
94
+ attention_interface: Callable = eager_attention_forward
95
+ if self.config._attn_implementation != "eager":
96
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
97
+
98
+ attn_output, attn_weights = attention_interface(
99
+ self,
100
+ query_states,
101
+ key_states,
102
+ value_states,
103
+ attention_mask,
104
+ dropout=0.0 if not self.training else self.attention_dropout,
105
+ scaling=self.scaling,
106
+ **kwargs,
107
+ )
108
+
109
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
110
+ attn_output = self.o_proj(attn_output)
111
+ return attn_output, attn_weights
112
+
113
+
114
+ class HunYuanDenseV1DecoderLayer(LlamaDecoderLayer):
115
+ def __init__(self, config: HunYuanDenseV1Config, layer_idx: int):
116
+ super().__init__(config, layer_idx)
117
+ self.layer_idx = layer_idx
118
+
119
+
120
+ class HunYuanDenseV1PreTrainedModel(LlamaPreTrainedModel):
121
+ def _init_weights(self, module):
122
+ std = self.config.initializer_range
123
+ if isinstance(module, nn.Linear):
124
+ module.weight.data.normal_(mean=0.0, std=std)
125
+ if module.bias is not None:
126
+ module.bias.data.zero_()
127
+ elif isinstance(module, nn.Embedding):
128
+ module.weight.data.normal_(mean=0.0, std=std)
129
+ if module.padding_idx is not None:
130
+ module.weight.data[module.padding_idx].zero_()
131
+
132
+
133
+ class HunYuanDenseV1RotaryEmbedding(nn.Module):
134
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
135
+
136
+ def __init__(self, config: HunYuanDenseV1Config, device=None):
137
+ super().__init__()
138
+ # BC: "rope_type" was originally "type"
139
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
140
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
141
+ else:
142
+ self.rope_type = "default"
143
+ self.max_seq_len_cached = config.max_position_embeddings
144
+ self.original_max_seq_len = config.max_position_embeddings
145
+
146
+ self.config = config
147
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
148
+ if self.rope_type == "dynamic" and config.rope_scaling["alpha"]:
149
+ # DynamicNTKAlphaRotary
150
+ self.dim = config.head_dim
151
+ base = config.rope_theta * config.rope_scaling.get("alpha") ** (self.dim / (self.dim - 2))
152
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
153
+ self.attention_scaling = 1.0
154
+ else:
155
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
156
+
157
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
158
+ self.original_inv_freq = self.inv_freq
159
+
160
+ @torch.no_grad()
161
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
162
+ def forward(self, x, position_ids):
163
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
164
+ position_ids_expanded = position_ids[:, None, :].float()
165
+
166
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
167
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
168
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
169
+ emb = torch.cat((freqs, freqs), dim=-1)
170
+ cos = emb.cos() * self.attention_scaling
171
+ sin = emb.sin() * self.attention_scaling
172
+
173
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
174
+
175
+
176
+ class HunYuanDenseV1Model(LlamaModel):
177
+ pass
178
+
179
+
180
+ class HunYuanDenseV1ForCausalLM(LlamaForCausalLM):
181
+ pass
182
+
183
+
184
+ class HunYuanDenseV1ForSequenceClassification(LlamaForSequenceClassification):
185
+ pass
186
+
187
+
188
+ __all__ = [
189
+ "HunYuanDenseV1ForCausalLM",
190
+ "HunYuanDenseV1Model",
191
+ "HunYuanDenseV1PreTrainedModel",
192
+ "HunYuanDenseV1ForSequenceClassification",
193
+ ]