Prompt48 commited on
Commit
d5cf860
·
verified ·
1 Parent(s): 8f7214a

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//helium//modular_helium.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
3
+ #
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ import math
17
+ from typing import Optional
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ...utils import logging
23
+ from ..gemma.modeling_gemma import GemmaForCausalLM, GemmaForSequenceClassification, GemmaForTokenClassification
24
+ from ..granite.modeling_granite import GraniteAttention
25
+ from ..llama.modeling_llama import LlamaDecoderLayer, LlamaMLP, LlamaModel, LlamaPreTrainedModel, LlamaRotaryEmbedding
26
+ from .configuration_helium import HeliumConfig
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ class HeliumRMSNorm(nn.Module):
33
+ def __init__(self, hidden_size, eps=1e-6):
34
+ super().__init__()
35
+ self.weight = nn.Parameter(torch.ones(hidden_size))
36
+ self.variance_epsilon = eps
37
+
38
+ def forward(self, hidden_states):
39
+ input_dtype = hidden_states.dtype
40
+ hidden_states = hidden_states.to(torch.float32)
41
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
42
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
43
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
44
+
45
+ def extra_repr(self):
46
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
47
+
48
+
49
+ class HeliumRotaryEmbedding(LlamaRotaryEmbedding):
50
+ pass
51
+
52
+
53
+ class HeliumMLP(LlamaMLP):
54
+ pass
55
+
56
+
57
+ def rotate_half(x):
58
+ """Rotates half the hidden dims of the input."""
59
+ x1 = x[..., 0::2]
60
+ x2 = x[..., 1::2]
61
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
62
+
63
+
64
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
65
+ """Applies Rotary Position Embedding to the query and key tensors.
66
+
67
+ Args:
68
+ q (`torch.Tensor`): The query tensor.
69
+ k (`torch.Tensor`): The key tensor.
70
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
71
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
72
+ position_ids (`torch.Tensor`, *optional*):
73
+ Deprecated and unused.
74
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
75
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
76
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
77
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
78
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
79
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
80
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
81
+ Returns:
82
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
83
+ """
84
+ cos = cos.unsqueeze(unsqueeze_dim)
85
+ sin = sin.unsqueeze(unsqueeze_dim)
86
+
87
+ # Interleave them instead of usual shape
88
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
89
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
90
+
91
+ q_embed = (q * cos) + (rotate_half(q) * sin)
92
+ k_embed = (k * cos) + (rotate_half(k) * sin)
93
+
94
+ return q_embed, k_embed
95
+
96
+
97
+ class HeliumAttention(GraniteAttention):
98
+ def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
99
+ super().__init__(config, layer_idx)
100
+ self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
101
+ self.scaling = 1 / math.sqrt(self.head_dim)
102
+
103
+
104
+ class HeliumDecoderLayer(LlamaDecoderLayer):
105
+ def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
106
+ super().__init__(config, layer_idx)
107
+
108
+ self.mlp = HeliumMLP(config)
109
+ self.input_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
110
+ self.post_attention_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
111
+
112
+
113
+ class HeliumPreTrainedModel(LlamaPreTrainedModel):
114
+ pass
115
+
116
+
117
+ class HeliumModel(HeliumPreTrainedModel, LlamaModel):
118
+ def __init__(self, config: HeliumConfig):
119
+ super().__init__(config)
120
+ self.layers = nn.ModuleList(
121
+ [HeliumDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
122
+ )
123
+ self.norm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
124
+ self.rotary_emb = HeliumRotaryEmbedding(config)
125
+ self.gradient_checkpointing = False
126
+
127
+ # Initialize weights and apply final processing
128
+ self.post_init()
129
+
130
+
131
+ class HeliumForCausalLM(GemmaForCausalLM):
132
+ pass
133
+
134
+
135
+ class HeliumForSequenceClassification(GemmaForSequenceClassification):
136
+ pass
137
+
138
+
139
+ class HeliumForTokenClassification(GemmaForTokenClassification):
140
+ pass
141
+
142
+
143
+ __all__ = [
144
+ "HeliumPreTrainedModel",
145
+ "HeliumModel",
146
+ "HeliumForCausalLM",
147
+ "HeliumForSequenceClassification",
148
+ "HeliumForTokenClassification",
149
+ ]