Prompt48 commited on
Commit
ca4231e
·
verified ·
1 Parent(s): e62769e

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//granitemoeshared//modular_granitemoeshared.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 IBM and the HuggingFace Inc. team. 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
+ from typing import Optional, TypedDict
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ...activations import ACT2FN
22
+ from ...cache_utils import Cache
23
+ from ...processing_utils import Unpack
24
+ from ...utils import logging
25
+ from ...utils.deprecation import deprecate_kwarg
26
+ from ..granitemoe.modeling_granitemoe import (
27
+ GraniteMoeDecoderLayer,
28
+ GraniteMoeForCausalLM,
29
+ GraniteMoeModel,
30
+ GraniteMoePreTrainedModel,
31
+ )
32
+ from .configuration_granitemoeshared import GraniteMoeSharedConfig
33
+
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+
38
+ class GraniteFlashAttentionKwargs(TypedDict, total=False):
39
+ """
40
+ Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
41
+ Use cases include padding-free training and fewer `torch.compile` graph breaks.
42
+
43
+ Attributes:
44
+ cu_seq_lens_q (`torch.LongTensor`)
45
+ Gets cumulative sequence length for query state.
46
+ cu_seq_lens_k (`torch.LongTensor`)
47
+ Gets cumulative sequence length for key state.
48
+ max_length_q (`int`):
49
+ Maximum sequence length for query state.
50
+ max_length_k (`int`):
51
+ Maximum sequence length for key state.
52
+ seq_idx (`torch.IntTensor):
53
+ Index of each packed sequence.
54
+ """
55
+
56
+ cu_seq_lens_q: torch.LongTensor
57
+ cu_seq_lens_k: torch.LongTensor
58
+ max_length_q: int
59
+ max_length_k: int
60
+ seq_idx: torch.IntTensor
61
+
62
+
63
+ class GraniteMoeSharedMLP(nn.Module):
64
+ """
65
+ MLP layer for shared experts
66
+
67
+ Args:
68
+ config:
69
+ Configuration object with model hyperparameters.
70
+ """
71
+
72
+ def __init__(self, config: GraniteMoeSharedConfig):
73
+ super().__init__()
74
+
75
+ self.input_size = config.hidden_size
76
+ self.hidden_size = config.shared_intermediate_size
77
+ self.activation = ACT2FN[config.hidden_act]
78
+ self.input_linear = nn.Linear(self.input_size, self.hidden_size * 2, bias=False)
79
+ self.output_linear = nn.Linear(self.hidden_size, self.input_size, bias=False)
80
+
81
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
82
+ hidden_states = self.input_linear(hidden_states)
83
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
84
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
85
+ hidden_states = self.output_linear(hidden_states)
86
+ return hidden_states
87
+
88
+
89
+ class GraniteMoeSharedDecoderLayer(GraniteMoeDecoderLayer):
90
+ def __init__(self, config: GraniteMoeSharedConfig, layer_idx: int):
91
+ super().__init__(config, layer_idx)
92
+ self.shared_mlp = None if config.shared_intermediate_size == 0 else GraniteMoeSharedMLP(config)
93
+
94
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
95
+ def forward(
96
+ self,
97
+ hidden_states: torch.Tensor,
98
+ attention_mask: Optional[torch.Tensor] = None,
99
+ position_ids: Optional[torch.LongTensor] = None,
100
+ past_key_values: Optional[Cache] = None,
101
+ output_attentions: Optional[bool] = False,
102
+ use_cache: Optional[bool] = False,
103
+ cache_position: Optional[torch.LongTensor] = None,
104
+ output_router_logits: Optional[bool] = False,
105
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
106
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
107
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
108
+ """
109
+ Args:
110
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
111
+ attention_mask (`torch.FloatTensor`, *optional*):
112
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
113
+ query_sequence_length, key_sequence_length)` if default attention is used.
114
+ output_attentions (`bool`, *optional*):
115
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
116
+ returned tensors for more detail.
117
+ use_cache (`bool`, *optional*):
118
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
119
+ (see `past_key_values`).
120
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
121
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
122
+ Indices depicting the position of the input sequence tokens in the sequence
123
+ output_router_logits (`bool`, *optional*):
124
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
125
+ should not be returned during inference.
126
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
127
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
128
+ with `head_dim` being the embedding dimension of each attention head.
129
+ kwargs (`dict`, *optional*):
130
+ Arbitrary kwargs. Can be used to provide `GraniteFlashAttentionKwargs` for
131
+ padding-free training and/or improve torch.compile performance.
132
+ """
133
+ residual = hidden_states
134
+
135
+ hidden_states = self.input_layernorm(hidden_states)
136
+
137
+ # Self Attention
138
+ hidden_states, self_attn_weights = self.self_attn(
139
+ hidden_states=hidden_states,
140
+ attention_mask=attention_mask,
141
+ position_ids=position_ids,
142
+ past_key_values=past_key_values,
143
+ output_attentions=output_attentions,
144
+ use_cache=use_cache,
145
+ cache_position=cache_position,
146
+ position_embeddings=position_embeddings,
147
+ **kwargs,
148
+ )
149
+
150
+ hidden_states = residual + hidden_states * self.residual_multiplier
151
+
152
+ # Fully Connected
153
+ residual = hidden_states
154
+ hidden_states = self.post_attention_layernorm(hidden_states)
155
+ moe_hidden_states, router_logits = self.block_sparse_moe(hidden_states)
156
+
157
+ if self.shared_mlp is None:
158
+ hidden_states = moe_hidden_states
159
+ else:
160
+ hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
161
+
162
+ del moe_hidden_states
163
+
164
+ hidden_states = residual + hidden_states * self.residual_multiplier
165
+
166
+ outputs = (hidden_states,)
167
+
168
+ if output_attentions:
169
+ outputs += (self_attn_weights,)
170
+
171
+ if output_router_logits:
172
+ outputs += (router_logits,)
173
+
174
+ return outputs
175
+
176
+
177
+ class GraniteMoeSharedPreTrainedModel(GraniteMoePreTrainedModel):
178
+ config: GraniteMoeSharedConfig
179
+ _no_split_modules = ["GraniteMoeSharedDecoderLayer"]
180
+
181
+
182
+ class GraniteMoeSharedModel(GraniteMoeModel):
183
+ def __init__(self, config: GraniteMoeSharedConfig):
184
+ super().__init__(config)
185
+ self.layers = nn.ModuleList(
186
+ [GraniteMoeSharedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
187
+ )
188
+
189
+
190
+ class GraniteMoeSharedForCausalLM(GraniteMoeForCausalLM):
191
+ _tied_weights_keys = ["lm_head.weight"]
192
+
193
+ def __init__(self, config: GraniteMoeSharedConfig):
194
+ super().__init__(config)
195
+ self.model = GraniteMoeSharedModel(config)
196
+ # Initialize weights and apply final processing
197
+ self.post_init()
198
+
199
+
200
+ __all__ = ["GraniteMoeSharedForCausalLM", "GraniteMoeSharedModel", "GraniteMoeSharedPreTrainedModel"]