Prompt48 commited on
Commit
f143d86
·
verified ·
1 Parent(s): 030afd5

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//granitemoehybrid//modular_granitemoehybrid.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ...cache_utils import Cache
22
+ from ...modeling_outputs import BaseModelOutputWithPast, MoeModelOutputWithPast
23
+ from ...processing_utils import Unpack
24
+ from ...utils import auto_docstring, can_return_tuple, logging
25
+ from ...utils.deprecation import deprecate_kwarg
26
+ from ..bamba.configuration_bamba import BambaConfig
27
+ from ..bamba.modeling_bamba import BambaMixer, BambaRMSNormGated, HybridMambaAttentionDynamicCache
28
+ from ..granitemoeshared.modeling_granitemoeshared import (
29
+ GraniteFlashAttentionKwargs,
30
+ GraniteMoeSharedAttention,
31
+ GraniteMoeSharedDecoderLayer,
32
+ GraniteMoeSharedForCausalLM,
33
+ GraniteMoeSharedMLP,
34
+ GraniteMoeSharedModel,
35
+ GraniteMoeSharedPreTrainedModel,
36
+ )
37
+ from .configuration_granitemoehybrid import GraniteMoeHybridConfig
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ class GraniteMoeHybridAttention(GraniteMoeSharedAttention):
44
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
45
+ super().__init__(config, layer_idx)
46
+
47
+
48
+ class GraniteMoeHybridMambaLayer(BambaMixer):
49
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
50
+ super().__init__(BambaConfig(config), layer_idx)
51
+
52
+
53
+ class GraniteMoeHybridRMSNormGated(BambaRMSNormGated):
54
+ def __init__(self, hidden_size, eps=1e-6):
55
+ super().__init__(hidden_size, eps)
56
+
57
+
58
+ class GraniteMoeHybridMLP(GraniteMoeSharedMLP):
59
+ def __init__(self, config: GraniteMoeHybridConfig):
60
+ super().__init__(config)
61
+
62
+
63
+ class GraniteMoeHybridDecoderLayer(GraniteMoeSharedDecoderLayer):
64
+ def __init__(self, config: GraniteMoeHybridConfig, layer_idx: int):
65
+ super().__init__(config, layer_idx)
66
+ self.shared_mlp = GraniteMoeHybridMLP(config)
67
+ # Either attention or mamba will be initialized, depending on the layer type.
68
+ self.self_attn = None
69
+ self.mamba = None
70
+
71
+ if config.layers_block_type[layer_idx] == "mamba":
72
+ self.mamba = GraniteMoeHybridMambaLayer(config, layer_idx)
73
+ else:
74
+ self.self_attn = GraniteMoeHybridAttention(config, layer_idx)
75
+ self.layer_type = config.layers_block_type[layer_idx]
76
+
77
+ # Accept 0 experts: skip MoE if num_local_experts == 0
78
+ self.has_experts = getattr(config, "num_local_experts", 0) > 0
79
+
80
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
81
+ def forward(
82
+ self,
83
+ hidden_states: torch.Tensor,
84
+ attention_mask: Optional[torch.Tensor] = None,
85
+ past_key_values: Optional[Cache] = None,
86
+ output_attentions: Optional[bool] = False,
87
+ use_cache: Optional[bool] = False,
88
+ cache_position: Optional[torch.LongTensor] = None,
89
+ output_router_logits: Optional[bool] = False,
90
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
91
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
92
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
93
+ """
94
+ Args:
95
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
96
+ attention_mask (`torch.FloatTensor`, *optional*):
97
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
98
+ query_sequence_length, key_sequence_length)` if default attention is used.
99
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
100
+ output_attentions (`bool`, *optional*):
101
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
102
+ returned tensors for more detail.
103
+ use_cache (`bool`, *optional*):
104
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
105
+ (see `past_key_values`).
106
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
107
+ Indices depicting the position of the input sequence tokens in the sequence
108
+ output_router_logits (`bool`, *optional*):
109
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
110
+ should not be returned during inference.
111
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
112
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
113
+ with `head_dim` being the embedding dimension of each attention head.
114
+ kwargs (`dict`, *optional*):
115
+ Arbitrary kwargs.Can be used to provide `GraniteFlashAttentionKwargs` for
116
+ padding-free training and/or improve torch.compile performance.
117
+ """
118
+ residual = hidden_states
119
+ hidden_states = self.input_layernorm(hidden_states)
120
+
121
+ if self.mamba is not None:
122
+ hidden_states = self.mamba(
123
+ hidden_states=hidden_states,
124
+ cache_position=cache_position,
125
+ cache_params=past_key_values,
126
+ attention_mask=attention_mask,
127
+ **kwargs,
128
+ )
129
+ # No attention weights for state space layers
130
+ self_attn_weights = None
131
+ else:
132
+ hidden_states, self_attn_weights = self.self_attn(
133
+ hidden_states=hidden_states,
134
+ attention_mask=attention_mask,
135
+ past_key_values=past_key_values,
136
+ output_attentions=output_attentions,
137
+ use_cache=use_cache,
138
+ cache_position=cache_position,
139
+ position_embeddings=position_embeddings,
140
+ **kwargs,
141
+ )
142
+
143
+ hidden_states = residual + hidden_states * self.residual_multiplier
144
+
145
+ # Fully Connected
146
+ residual = hidden_states
147
+ hidden_states = self.post_attention_layernorm(hidden_states)
148
+
149
+ if self.has_experts:
150
+ moe_hidden_states, router_logits = self.block_sparse_moe(hidden_states)
151
+ hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
152
+ else:
153
+ hidden_states = self.shared_mlp(hidden_states)
154
+ router_logits = None
155
+
156
+ hidden_states = residual + hidden_states * self.residual_multiplier
157
+
158
+ outputs = (hidden_states,)
159
+
160
+ if output_attentions:
161
+ outputs += (self_attn_weights,)
162
+
163
+ if output_router_logits:
164
+ outputs += (router_logits,)
165
+
166
+ return outputs
167
+
168
+
169
+ class GraniteMoeHybridPreTrainedModel(GraniteMoeSharedPreTrainedModel):
170
+ config: GraniteMoeHybridConfig
171
+ _no_split_modules = ["GraniteMoeHybridDecoderLayer"]
172
+ _is_stateful = True
173
+
174
+ def _init_weights(self, module):
175
+ super()._init_weights(module)
176
+ if isinstance(module, GraniteMoeHybridMambaLayer):
177
+ module.dt_bias.data.fill_(1.0)
178
+ module.A_log.data = torch.log(torch.arange(1, module.num_heads + 1))
179
+ module.D.data.fill_(1.0)
180
+ elif isinstance(module, GraniteMoeHybridRMSNormGated):
181
+ module.weight.data.fill_(1.0)
182
+
183
+
184
+ class GraniteMoeHybridModel(GraniteMoeSharedModel):
185
+ def __init__(self, config: GraniteMoeHybridConfig):
186
+ super().__init__(config)
187
+ self.layers = nn.ModuleList(
188
+ [GraniteMoeHybridDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
189
+ )
190
+
191
+ @can_return_tuple
192
+ @auto_docstring
193
+ def forward(
194
+ self,
195
+ input_ids: Optional[torch.LongTensor] = None,
196
+ attention_mask: Optional[torch.Tensor] = None,
197
+ position_ids: Optional[torch.LongTensor] = None,
198
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
199
+ inputs_embeds: Optional[torch.FloatTensor] = None,
200
+ use_cache: Optional[bool] = None,
201
+ output_attentions: Optional[bool] = None,
202
+ output_hidden_states: Optional[bool] = None,
203
+ output_router_logits: Optional[bool] = None,
204
+ return_dict: Optional[bool] = None,
205
+ cache_position: Optional[torch.LongTensor] = None,
206
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
207
+ ) -> Union[tuple, BaseModelOutputWithPast]:
208
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
209
+ output_hidden_states = (
210
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
211
+ )
212
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
213
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
214
+
215
+ if (input_ids is None) ^ (inputs_embeds is not None):
216
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
217
+
218
+ if self.gradient_checkpointing and self.training and use_cache:
219
+ logger.warning_once(
220
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
221
+ )
222
+ use_cache = False
223
+
224
+ if inputs_embeds is None:
225
+ inputs_embeds = self.embed_tokens(input_ids)
226
+
227
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
228
+
229
+ ## overwritten because `HybridMambaAttentionDynamicCache` is needed
230
+ if use_cache and past_key_values is None:
231
+ logger.warning_once(
232
+ "GraniteMoeHybrid requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. "
233
+ "Because one was not provided, no cache will be returned."
234
+ )
235
+
236
+ if cache_position is None:
237
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
238
+ cache_position = torch.arange(
239
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
240
+ )
241
+ if position_ids is None:
242
+ position_ids = cache_position.unsqueeze(0)
243
+
244
+ causal_mask = self._update_causal_mask(
245
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
246
+ )
247
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
248
+
249
+ # embed positions
250
+ hidden_states = inputs_embeds
251
+
252
+ position_embeddings = None
253
+ # create position embeddings to be shared across the decoder layers
254
+ if self.rotary_emb is not None:
255
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
256
+
257
+ # decoder layers
258
+ all_hidden_states = () if output_hidden_states else None
259
+ all_self_attns = () if output_attentions else None
260
+ all_router_logits = () if output_router_logits else None
261
+
262
+ for decoder_layer in self.layers:
263
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
264
+ layer_mask = mamba_mask if decoder_layer.layer_type == "mamba" else causal_mask
265
+
266
+ if output_hidden_states:
267
+ all_hidden_states += (hidden_states,)
268
+
269
+ layer_outputs = decoder_layer(
270
+ hidden_states,
271
+ attention_mask=layer_mask,
272
+ past_key_values=past_key_values,
273
+ output_attentions=output_attentions,
274
+ use_cache=use_cache,
275
+ cache_position=cache_position,
276
+ output_router_logits=output_router_logits,
277
+ position_embeddings=position_embeddings,
278
+ **kwargs,
279
+ )
280
+
281
+ hidden_states = layer_outputs[0]
282
+
283
+ if output_attentions:
284
+ if layer_outputs[1] is not None:
285
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
286
+ all_self_attns += (layer_outputs[1],)
287
+
288
+ if output_router_logits:
289
+ if layer_outputs[-1] is not None:
290
+ # append router logits only of expert layers. Regular MLP layers return `None` as the router logits
291
+ all_router_logits += (layer_outputs[-1],)
292
+
293
+ hidden_states = self.norm(hidden_states)
294
+
295
+ # add hidden states from the last decoder layer
296
+ if output_hidden_states:
297
+ all_hidden_states += (hidden_states,)
298
+
299
+ if past_key_values and not past_key_values.has_previous_state:
300
+ past_key_values.has_previous_state = True
301
+
302
+ return MoeModelOutputWithPast(
303
+ last_hidden_state=hidden_states,
304
+ past_key_values=past_key_values,
305
+ hidden_states=all_hidden_states,
306
+ attentions=all_self_attns,
307
+ router_logits=all_router_logits,
308
+ )
309
+
310
+ def _update_mamba_mask(self, attention_mask, cache_position):
311
+ """
312
+ No need for zeroing states when
313
+ 1. Cached forward
314
+ 2. Attending to all inputs
315
+ """
316
+ mamba_mask = attention_mask
317
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
318
+ mamba_mask = None
319
+ return mamba_mask
320
+
321
+
322
+ class GraniteMoeHybridForCausalLM(GraniteMoeSharedForCausalLM):
323
+ _tied_weights_keys = ["lm_head.weight"]
324
+
325
+ def __init__(self, config: GraniteMoeHybridConfig):
326
+ super().__init__(config)
327
+ self.model = GraniteMoeHybridModel(config)
328
+ # Initialize weights and apply final processing
329
+ self.post_init()
330
+
331
+ def prepare_inputs_for_generation(
332
+ self,
333
+ input_ids,
334
+ past_key_values=None,
335
+ attention_mask=None,
336
+ inputs_embeds=None,
337
+ cache_position=None,
338
+ position_ids=None,
339
+ use_cache=True,
340
+ **kwargs,
341
+ ):
342
+ # Overwritten -- has a unique cache type, `HybridMambaAttentionDynamicCache`
343
+
344
+ empty_past_kv = past_key_values is None
345
+
346
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
347
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
348
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
349
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
350
+ # (we can't check exception 3 while compiling)
351
+ if not empty_past_kv:
352
+ if (
353
+ inputs_embeds is not None # Exception 1
354
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
355
+ ):
356
+ input_ids = input_ids[:, -cache_position.shape[0] :]
357
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
358
+ input_ids = input_ids[:, cache_position]
359
+ elif use_cache:
360
+ past_key_values = HybridMambaAttentionDynamicCache(
361
+ self.config, input_ids.shape[0], self.dtype, device=self.device
362
+ )
363
+
364
+ if attention_mask is not None and position_ids is None:
365
+ # create position_ids on the fly for batch generation
366
+ position_ids = attention_mask.long().cumsum(-1) - 1
367
+ position_ids.masked_fill_(attention_mask == 0, 1)
368
+ if not empty_past_kv:
369
+ position_ids = position_ids[:, -input_ids.shape[1] :]
370
+
371
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
372
+ if inputs_embeds is not None and empty_past_kv:
373
+ model_inputs = {"inputs_embeds": inputs_embeds}
374
+ else:
375
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
376
+
377
+ model_inputs.update(
378
+ {
379
+ "position_ids": position_ids,
380
+ "past_key_values": past_key_values,
381
+ "use_cache": use_cache,
382
+ "attention_mask": attention_mask,
383
+ "cache_position": cache_position,
384
+ }
385
+ )
386
+
387
+ # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
388
+ for key, value in kwargs.items():
389
+ if key not in model_inputs:
390
+ model_inputs[key] = value
391
+
392
+ return model_inputs
393
+
394
+
395
+ __all__ = ["GraniteMoeHybridForCausalLM", "GraniteMoeHybridModel", "GraniteMoeHybridPreTrainedModel"]