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

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

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//granitemoeshared//modeling_granitemoeshared.py ADDED
@@ -0,0 +1,1059 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/granitemoeshared/modular_granitemoeshared.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_granitemoeshared.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 IBM and the HuggingFace Inc. team. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ from typing import Callable, Optional, TypedDict, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ from torch import nn
27
+
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache, DynamicCache
30
+ from ...generation import GenerationMixin
31
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
32
+ from ...modeling_layers import GradientCheckpointingLayer
33
+ from ...modeling_outputs import BaseModelOutputWithPast, MoeCausalLMOutputWithPast, MoeModelOutputWithPast
34
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
35
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
36
+ from ...processing_utils import Unpack
37
+ from ...utils import auto_docstring, is_torch_flex_attn_available, logging
38
+ from ...utils.deprecation import deprecate_kwarg
39
+ from .configuration_granitemoeshared import GraniteMoeSharedConfig
40
+
41
+
42
+ if is_torch_flex_attn_available():
43
+ from torch.nn.attention.flex_attention import BlockMask
44
+
45
+ from ...integrations.flex_attention import make_flex_block_causal_mask
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+
51
+ class GraniteFlashAttentionKwargs(TypedDict, total=False):
52
+ """
53
+ Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
54
+ Use cases include padding-free training and fewer `torch.compile` graph breaks.
55
+
56
+ Attributes:
57
+ cu_seq_lens_q (`torch.LongTensor`)
58
+ Gets cumulative sequence length for query state.
59
+ cu_seq_lens_k (`torch.LongTensor`)
60
+ Gets cumulative sequence length for key state.
61
+ max_length_q (`int`):
62
+ Maximum sequence length for query state.
63
+ max_length_k (`int`):
64
+ Maximum sequence length for key state.
65
+ seq_idx (`torch.IntTensor):
66
+ Index of each packed sequence.
67
+ """
68
+
69
+ cu_seq_lens_q: torch.LongTensor
70
+ cu_seq_lens_k: torch.LongTensor
71
+ max_length_q: int
72
+ max_length_k: int
73
+ seq_idx: torch.IntTensor
74
+
75
+
76
+ class GraniteMoeSharedMLP(nn.Module):
77
+ """
78
+ MLP layer for shared experts
79
+
80
+ Args:
81
+ config:
82
+ Configuration object with model hyperparameters.
83
+ """
84
+
85
+ def __init__(self, config: GraniteMoeSharedConfig):
86
+ super().__init__()
87
+
88
+ self.input_size = config.hidden_size
89
+ self.hidden_size = config.shared_intermediate_size
90
+ self.activation = ACT2FN[config.hidden_act]
91
+ self.input_linear = nn.Linear(self.input_size, self.hidden_size * 2, bias=False)
92
+ self.output_linear = nn.Linear(self.hidden_size, self.input_size, bias=False)
93
+
94
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
95
+ hidden_states = self.input_linear(hidden_states)
96
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
97
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
98
+ hidden_states = self.output_linear(hidden_states)
99
+ return hidden_states
100
+
101
+
102
+ class GraniteMoeSharedRMSNorm(nn.Module):
103
+ def __init__(self, hidden_size, eps=1e-6):
104
+ """
105
+ GraniteMoeSharedRMSNorm is equivalent to T5LayerNorm
106
+ """
107
+ super().__init__()
108
+ self.weight = nn.Parameter(torch.ones(hidden_size))
109
+ self.variance_epsilon = eps
110
+
111
+ def forward(self, hidden_states):
112
+ input_dtype = hidden_states.dtype
113
+ hidden_states = hidden_states.to(torch.float32)
114
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
115
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
116
+ return self.weight * hidden_states.to(input_dtype)
117
+
118
+ def extra_repr(self):
119
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
120
+
121
+
122
+ class GraniteMoeSharedParallelExperts(nn.Module):
123
+ def __init__(self, num_experts: int, input_size: int, output_size: int) -> None:
124
+ """
125
+ Initialize the GraniteMoeSharedParallelExperts module.
126
+ The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
127
+ many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
128
+ [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
129
+ [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
130
+ used in vllm.
131
+
132
+ Args:
133
+ num_experts (int):
134
+ Number of experts.
135
+ input_size (int):
136
+ Size of the input.
137
+ output_size (int):
138
+ Size of the output.
139
+ """
140
+ super().__init__()
141
+ self.weight = nn.Parameter(torch.empty(num_experts, output_size, input_size))
142
+ self.num_experts = num_experts
143
+ self.input_size = input_size
144
+ self.output_size = output_size
145
+
146
+ def forward(self, inputs, expert_size):
147
+ """
148
+ Forward pass of the GraniteMoeSharedParallelExperts module.
149
+
150
+ Args:
151
+ inputs (Tensor):
152
+ Input tensor.
153
+ expert_size:
154
+ Expert size information.
155
+
156
+ Returns:
157
+ Tensor: Output tensor.
158
+ """
159
+ input_list = inputs.split(expert_size, dim=0)
160
+ output_list = []
161
+ for i in range(self.num_experts):
162
+ output_list.append(F.linear(input_list[i], self.weight[i]))
163
+ results = torch.cat(output_list, dim=0)
164
+ return results
165
+
166
+
167
+ class GraniteMoeSharedTopKGating(nn.Module):
168
+ def __init__(self, input_size: int, num_experts: int, top_k: int):
169
+ """
170
+ Initialize the top-k gating mechanism.
171
+ Args:
172
+ input_size (`int`):
173
+ Size of the input.
174
+ num_experts (`int`):
175
+ Number of experts.
176
+ top_k (`int`):
177
+ Number of top experts to select.
178
+ """
179
+ super().__init__()
180
+
181
+ self.num_experts = num_experts
182
+ self.input_size = input_size
183
+ self.top_k = top_k
184
+
185
+ self.layer = nn.Linear(input_size, num_experts, bias=False)
186
+
187
+ def forward(self, hidden_states):
188
+ # compute the top_k routing decision
189
+ logits = self.layer(hidden_states).float() # [batch_size x seq_len, num_experts]
190
+ top_k_logits, top_k_indices = logits.topk(self.top_k, dim=1) # [num_tokens, top_k]
191
+ top_k_gates = torch.softmax(top_k_logits, dim=1).type_as(hidden_states) # [num_tokens, top_k]
192
+
193
+ # compute number of input given to each expert
194
+ zeros = torch.zeros(
195
+ [top_k_gates.size(0), self.num_experts], dtype=top_k_gates.dtype, device=top_k_gates.device
196
+ ) # [num_tokens, num_experts]
197
+ gates = zeros.scatter(1, top_k_indices, 1) # [num_tokens, num_experts]
198
+ expert_size = gates.long().sum(0) # [num_experts,]
199
+ # (This cause torch.compile to fail with `torch._dynamo.exc.Unsupported: Backend compiler failed with a fake tensor exception at`)
200
+ # (and `DataDependentOutputException`)
201
+ expert_size = expert_size.tolist()
202
+
203
+ # sort and group input tokens according to expert assignment
204
+ top_k_experts = top_k_indices.flatten() # [num_tokens * top_k]
205
+ _, index_sorted_experts = top_k_experts.sort(0) # [num_tokens * top_k]
206
+ batch_index = index_sorted_experts.div(self.top_k, rounding_mode="trunc") # [num_tokens * top_k]
207
+
208
+ # gather the gate values for grouped input tokens
209
+ top_k_gates = top_k_gates.flatten() # [num_tokens * top_k]
210
+ batch_gates = top_k_gates[index_sorted_experts] # [num_tokens * top_k]
211
+
212
+ return index_sorted_experts, batch_index, batch_gates, expert_size, logits
213
+
214
+
215
+ class GraniteMoeSharedMoE(nn.Module):
216
+ """
217
+ A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.
218
+
219
+ Args:
220
+ config:
221
+ Configuration object with model hyperparameters.
222
+ """
223
+
224
+ def __init__(self, config: GraniteMoeSharedConfig):
225
+ super().__init__()
226
+
227
+ self.input_size = config.hidden_size
228
+ self.hidden_size = config.intermediate_size
229
+ self.activation = ACT2FN[config.hidden_act]
230
+ self.input_linear = GraniteMoeSharedParallelExperts(
231
+ config.num_local_experts, self.input_size, self.hidden_size * 2
232
+ )
233
+ self.output_linear = GraniteMoeSharedParallelExperts(
234
+ config.num_local_experts, self.hidden_size, self.input_size
235
+ )
236
+
237
+ self.router = GraniteMoeSharedTopKGating(
238
+ input_size=self.input_size,
239
+ num_experts=config.num_local_experts,
240
+ top_k=config.num_experts_per_tok,
241
+ )
242
+
243
+ def forward(self, layer_input):
244
+ """
245
+ Forward pass of the mixture of experts layer.
246
+
247
+ Args:
248
+ layer_input (Tensor):
249
+ Input tensor.
250
+
251
+ Returns:
252
+ Tensor:
253
+ Output tensor.
254
+ Tensor:
255
+ Router logits.
256
+ """
257
+ bsz, length, emb_size = layer_input.size()
258
+ layer_input = layer_input.reshape(-1, emb_size)
259
+ _, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input)
260
+
261
+ expert_inputs = layer_input[batch_index]
262
+ hidden_states = self.input_linear(expert_inputs, expert_size)
263
+ chunked_hidden_states = hidden_states.chunk(2, dim=-1)
264
+ hidden_states = self.activation(chunked_hidden_states[0]) * chunked_hidden_states[1]
265
+ expert_outputs = self.output_linear(hidden_states, expert_size)
266
+
267
+ expert_outputs = expert_outputs * batch_gates[:, None]
268
+
269
+ zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device)
270
+ layer_output = zeros.index_add(0, batch_index, expert_outputs)
271
+ layer_output = layer_output.view(bsz, length, self.input_size)
272
+ return layer_output, router_logits
273
+
274
+
275
+ def rotate_half(x):
276
+ """Rotates half the hidden dims of the input."""
277
+ x1 = x[..., : x.shape[-1] // 2]
278
+ x2 = x[..., x.shape[-1] // 2 :]
279
+ return torch.cat((-x2, x1), dim=-1)
280
+
281
+
282
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
283
+ """Applies Rotary Position Embedding to the query and key tensors.
284
+
285
+ Args:
286
+ q (`torch.Tensor`): The query tensor.
287
+ k (`torch.Tensor`): The key tensor.
288
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
289
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
290
+ position_ids (`torch.Tensor`, *optional*):
291
+ Deprecated and unused.
292
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
293
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
294
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
295
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
296
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
297
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
298
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
299
+ Returns:
300
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
301
+ """
302
+ cos = cos.unsqueeze(unsqueeze_dim)
303
+ sin = sin.unsqueeze(unsqueeze_dim)
304
+ q_embed = (q * cos) + (rotate_half(q) * sin)
305
+ k_embed = (k * cos) + (rotate_half(k) * sin)
306
+ return q_embed, k_embed
307
+
308
+
309
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
310
+ """
311
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
312
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
313
+ """
314
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
315
+ if n_rep == 1:
316
+ return hidden_states
317
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
318
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
319
+
320
+
321
+ def eager_attention_forward(
322
+ module: nn.Module,
323
+ query: torch.Tensor,
324
+ key: torch.Tensor,
325
+ value: torch.Tensor,
326
+ attention_mask: Optional[torch.Tensor],
327
+ scaling: float,
328
+ dropout: float = 0.0,
329
+ **kwargs,
330
+ ):
331
+ key_states = repeat_kv(key, module.num_key_value_groups)
332
+ value_states = repeat_kv(value, module.num_key_value_groups)
333
+
334
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
335
+ if attention_mask is not None:
336
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
337
+ attn_weights = attn_weights + causal_mask
338
+
339
+ # upcast attention to fp32
340
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
341
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
342
+ attn_output = torch.matmul(attn_weights, value_states)
343
+ attn_output = attn_output.transpose(1, 2).contiguous()
344
+
345
+ return attn_output, attn_weights
346
+
347
+
348
+ # copied from transformers.models.granite.modeling_granite.GraniteAttention with Granite->GraniteMoeShared
349
+ # no longer copied after attention refactors
350
+ class GraniteMoeSharedAttention(nn.Module):
351
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
352
+
353
+ def __init__(self, config: GraniteMoeSharedConfig, layer_idx: Optional[int] = None):
354
+ super().__init__()
355
+ self.config = config
356
+ self.layer_idx = layer_idx
357
+ if layer_idx is None:
358
+ logger.warning_once(
359
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
360
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
361
+ "when creating this class."
362
+ )
363
+
364
+ self.attention_dropout = config.attention_dropout
365
+ self.hidden_size = config.hidden_size
366
+ self.num_heads = config.num_attention_heads
367
+ self.head_dim = self.hidden_size // self.num_heads
368
+ self.num_key_value_heads = config.num_key_value_heads
369
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
370
+ self.is_causal = True
371
+
372
+ self.scaling = config.attention_multiplier
373
+
374
+ if (self.head_dim * self.num_heads) != self.hidden_size:
375
+ raise ValueError(
376
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
377
+ f" and `num_heads`: {self.num_heads})."
378
+ )
379
+
380
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
381
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
382
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
383
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
384
+
385
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
386
+ def forward(
387
+ self,
388
+ hidden_states: torch.Tensor,
389
+ attention_mask: Optional[torch.Tensor] = None,
390
+ position_ids: Optional[torch.LongTensor] = None,
391
+ past_key_values: Optional[Cache] = None,
392
+ use_cache: bool = False,
393
+ cache_position: Optional[torch.LongTensor] = None,
394
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # None or rope embeddings
395
+ **kwargs,
396
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
397
+ bsz, q_len, _ = hidden_states.size()
398
+
399
+ query_states = self.q_proj(hidden_states)
400
+ key_states = self.k_proj(hidden_states)
401
+ value_states = self.v_proj(hidden_states)
402
+
403
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
404
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
405
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
406
+
407
+ cos, sin = position_embeddings if position_embeddings is not None else (None, None)
408
+ if position_embeddings is not None:
409
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
410
+
411
+ if past_key_values is not None:
412
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
413
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
414
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
415
+
416
+ attention_interface: Callable = eager_attention_forward
417
+ if self.config._attn_implementation != "eager":
418
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
419
+
420
+ attn_output, attn_weights = attention_interface(
421
+ self,
422
+ query_states,
423
+ key_states,
424
+ value_states,
425
+ attention_mask,
426
+ dropout=0.0 if not self.training else self.attention_dropout,
427
+ scaling=self.scaling,
428
+ **kwargs,
429
+ )
430
+
431
+ attn_output = attn_output.view(bsz, q_len, -1)
432
+ attn_output = self.o_proj(attn_output)
433
+
434
+ return attn_output, attn_weights
435
+
436
+
437
+ class GraniteMoeSharedDecoderLayer(GradientCheckpointingLayer):
438
+ def __init__(self, config: GraniteMoeSharedConfig, layer_idx: int):
439
+ super().__init__()
440
+ self.hidden_size = config.hidden_size
441
+
442
+ self.self_attn = GraniteMoeSharedAttention(config=config, layer_idx=layer_idx)
443
+ if config.num_local_experts > 0:
444
+ self.block_sparse_moe = GraniteMoeSharedMoE(config)
445
+ self.input_layernorm = GraniteMoeSharedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
446
+ self.post_attention_layernorm = GraniteMoeSharedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
447
+
448
+ self.residual_multiplier = config.residual_multiplier
449
+ self.shared_mlp = None if config.shared_intermediate_size == 0 else GraniteMoeSharedMLP(config)
450
+
451
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
452
+ def forward(
453
+ self,
454
+ hidden_states: torch.Tensor,
455
+ attention_mask: Optional[torch.Tensor] = None,
456
+ position_ids: Optional[torch.LongTensor] = None,
457
+ past_key_values: Optional[Cache] = None,
458
+ output_attentions: Optional[bool] = False,
459
+ use_cache: Optional[bool] = False,
460
+ cache_position: Optional[torch.LongTensor] = None,
461
+ output_router_logits: Optional[bool] = False,
462
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
463
+ **kwargs: Unpack[GraniteFlashAttentionKwargs],
464
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
465
+ """
466
+ Args:
467
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
468
+ attention_mask (`torch.FloatTensor`, *optional*):
469
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
470
+ query_sequence_length, key_sequence_length)` if default attention is used.
471
+ output_attentions (`bool`, *optional*):
472
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
473
+ returned tensors for more detail.
474
+ use_cache (`bool`, *optional*):
475
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
476
+ (see `past_key_values`).
477
+ past_key_values (`Cache`, *optional*): cached past key and value projection states
478
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
479
+ Indices depicting the position of the input sequence tokens in the sequence
480
+ output_router_logits (`bool`, *optional*):
481
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
482
+ should not be returned during inference.
483
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
484
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
485
+ with `head_dim` being the embedding dimension of each attention head.
486
+ kwargs (`dict`, *optional*):
487
+ Arbitrary kwargs. Can be used to provide `GraniteFlashAttentionKwargs` for
488
+ padding-free training and/or improve torch.compile performance.
489
+ """
490
+ residual = hidden_states
491
+
492
+ hidden_states = self.input_layernorm(hidden_states)
493
+
494
+ # Self Attention
495
+ hidden_states, self_attn_weights = self.self_attn(
496
+ hidden_states=hidden_states,
497
+ attention_mask=attention_mask,
498
+ position_ids=position_ids,
499
+ past_key_values=past_key_values,
500
+ output_attentions=output_attentions,
501
+ use_cache=use_cache,
502
+ cache_position=cache_position,
503
+ position_embeddings=position_embeddings,
504
+ **kwargs,
505
+ )
506
+
507
+ hidden_states = residual + hidden_states * self.residual_multiplier
508
+
509
+ # Fully Connected
510
+ residual = hidden_states
511
+ hidden_states = self.post_attention_layernorm(hidden_states)
512
+ moe_hidden_states, router_logits = self.block_sparse_moe(hidden_states)
513
+
514
+ if self.shared_mlp is None:
515
+ hidden_states = moe_hidden_states
516
+ else:
517
+ hidden_states = moe_hidden_states + self.shared_mlp(hidden_states)
518
+
519
+ del moe_hidden_states
520
+
521
+ hidden_states = residual + hidden_states * self.residual_multiplier
522
+
523
+ outputs = (hidden_states,)
524
+
525
+ if output_attentions:
526
+ outputs += (self_attn_weights,)
527
+
528
+ if output_router_logits:
529
+ outputs += (router_logits,)
530
+
531
+ return outputs
532
+
533
+
534
+ @auto_docstring
535
+ class GraniteMoeSharedPreTrainedModel(PreTrainedModel):
536
+ config: GraniteMoeSharedConfig
537
+ base_model_prefix = "model"
538
+ supports_gradient_checkpointing = True
539
+ _no_split_modules = ["GraniteMoeSharedDecoderLayer"]
540
+ _skip_keys_device_placement = ["past_key_values"]
541
+ _supports_flash_attn = True
542
+ _supports_sdpa = True
543
+
544
+ _can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
545
+
546
+ def _init_weights(self, module):
547
+ super()._init_weights(module)
548
+ if isinstance(module, GraniteMoeSharedParallelExperts):
549
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
550
+
551
+
552
+ class GraniteMoeSharedRotaryEmbedding(nn.Module):
553
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
554
+
555
+ def __init__(self, config: GraniteMoeSharedConfig, device=None):
556
+ super().__init__()
557
+ # BC: "rope_type" was originally "type"
558
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
559
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
560
+ else:
561
+ self.rope_type = "default"
562
+ self.max_seq_len_cached = config.max_position_embeddings
563
+ self.original_max_seq_len = config.max_position_embeddings
564
+
565
+ self.config = config
566
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
567
+
568
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
569
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
570
+ self.original_inv_freq = self.inv_freq
571
+
572
+ @torch.no_grad()
573
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
574
+ def forward(self, x, position_ids):
575
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
576
+ position_ids_expanded = position_ids[:, None, :].float()
577
+
578
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
579
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
580
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
581
+ emb = torch.cat((freqs, freqs), dim=-1)
582
+ cos = emb.cos() * self.attention_scaling
583
+ sin = emb.sin() * self.attention_scaling
584
+
585
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
586
+
587
+
588
+ @auto_docstring
589
+ class GraniteMoeSharedModel(GraniteMoeSharedPreTrainedModel):
590
+ def __init__(self, config: GraniteMoeSharedConfig):
591
+ super().__init__(config)
592
+ self.padding_idx = config.pad_token_id
593
+ self.vocab_size = config.vocab_size
594
+
595
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
596
+ self.layers = nn.ModuleList(
597
+ [GraniteMoeSharedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
598
+ )
599
+ self.norm = GraniteMoeSharedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
600
+ self.gradient_checkpointing = False
601
+
602
+ self.embedding_multiplier = config.embedding_multiplier
603
+ self.hidden_size = config.hidden_size
604
+ self.num_heads = config.num_attention_heads
605
+ self.head_dim = self.hidden_size // self.num_heads
606
+ self.max_position_embeddings = config.max_position_embeddings
607
+ self.rope_theta = config.rope_theta
608
+
609
+ self.position_embedding_type = config.position_embedding_type
610
+ self.rotary_emb = GraniteMoeSharedRotaryEmbedding(config) if self.position_embedding_type == "rope" else None
611
+
612
+ # Initialize weights and apply final processing
613
+ self.post_init()
614
+
615
+ @auto_docstring
616
+ def forward(
617
+ self,
618
+ input_ids: Optional[torch.LongTensor] = None,
619
+ attention_mask: Optional[torch.Tensor] = None,
620
+ position_ids: Optional[torch.LongTensor] = None,
621
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
622
+ inputs_embeds: Optional[torch.FloatTensor] = None,
623
+ use_cache: Optional[bool] = None,
624
+ output_attentions: Optional[bool] = None,
625
+ output_hidden_states: Optional[bool] = None,
626
+ output_router_logits: Optional[bool] = None,
627
+ return_dict: Optional[bool] = None,
628
+ cache_position: Optional[torch.LongTensor] = None,
629
+ **kwargs,
630
+ ) -> Union[tuple, BaseModelOutputWithPast]:
631
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
632
+ output_hidden_states = (
633
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
634
+ )
635
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
636
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
637
+
638
+ if (input_ids is None) ^ (inputs_embeds is not None):
639
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
640
+
641
+ if self.gradient_checkpointing and self.training and use_cache:
642
+ logger.warning_once(
643
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
644
+ )
645
+ use_cache = False
646
+
647
+ if inputs_embeds is None:
648
+ inputs_embeds = self.embed_tokens(input_ids)
649
+
650
+ inputs_embeds = inputs_embeds * self.embedding_multiplier
651
+
652
+ if use_cache and past_key_values is None:
653
+ past_key_values = DynamicCache(config=self.config)
654
+
655
+ if cache_position is None:
656
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
657
+ cache_position = torch.arange(
658
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
659
+ )
660
+ if position_ids is None:
661
+ position_ids = cache_position.unsqueeze(0)
662
+
663
+ causal_mask = self._update_causal_mask(
664
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
665
+ )
666
+
667
+ # embed positions
668
+ hidden_states = inputs_embeds
669
+
670
+ position_embeddings = None
671
+ # create position embeddings to be shared across the decoder layers
672
+ if self.rotary_emb is not None:
673
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
674
+
675
+ # decoder layers
676
+ all_hidden_states = () if output_hidden_states else None
677
+ all_self_attns = () if output_attentions else None
678
+ all_router_logits = () if output_router_logits else None
679
+
680
+ for decoder_layer in self.layers:
681
+ if output_hidden_states:
682
+ all_hidden_states += (hidden_states,)
683
+
684
+ layer_outputs = decoder_layer(
685
+ hidden_states,
686
+ attention_mask=causal_mask,
687
+ position_ids=position_ids,
688
+ past_key_values=past_key_values,
689
+ output_attentions=output_attentions,
690
+ use_cache=use_cache,
691
+ cache_position=cache_position,
692
+ output_router_logits=output_router_logits,
693
+ position_embeddings=position_embeddings,
694
+ )
695
+
696
+ hidden_states = layer_outputs[0]
697
+
698
+ if output_attentions:
699
+ all_self_attns += (layer_outputs[1],)
700
+
701
+ if output_router_logits:
702
+ all_router_logits += (layer_outputs[-1],)
703
+
704
+ hidden_states = self.norm(hidden_states)
705
+
706
+ # add hidden states from the last decoder layer
707
+ if output_hidden_states:
708
+ all_hidden_states += (hidden_states,)
709
+
710
+ if not return_dict:
711
+ return tuple(
712
+ v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns] if v is not None
713
+ )
714
+ return MoeModelOutputWithPast(
715
+ last_hidden_state=hidden_states,
716
+ past_key_values=past_key_values,
717
+ hidden_states=all_hidden_states,
718
+ attentions=all_self_attns,
719
+ router_logits=all_router_logits,
720
+ )
721
+
722
+ def _update_causal_mask(
723
+ self,
724
+ attention_mask: Union[torch.Tensor, "BlockMask"],
725
+ input_tensor: torch.Tensor,
726
+ cache_position: torch.Tensor,
727
+ past_key_values: Cache,
728
+ output_attentions: bool = False,
729
+ ):
730
+ if self.config._attn_implementation == "flash_attention_2":
731
+ if attention_mask is not None and (attention_mask == 0.0).any():
732
+ return attention_mask
733
+ return None
734
+ if self.config._attn_implementation == "flex_attention":
735
+ if isinstance(attention_mask, torch.Tensor):
736
+ attention_mask = make_flex_block_causal_mask(attention_mask)
737
+ return attention_mask
738
+
739
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
740
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
741
+ # to infer the attention mask.
742
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
743
+ using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
744
+
745
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
746
+ if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
747
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
748
+ attention_mask,
749
+ inputs_embeds=input_tensor,
750
+ past_key_values_length=past_seen_tokens,
751
+ is_training=self.training,
752
+ ):
753
+ return None
754
+
755
+ dtype = input_tensor.dtype
756
+ sequence_length = input_tensor.shape[1]
757
+ if using_compilable_cache:
758
+ target_length = past_key_values.get_max_cache_shape()
759
+ else:
760
+ target_length = (
761
+ attention_mask.shape[-1]
762
+ if isinstance(attention_mask, torch.Tensor)
763
+ else past_seen_tokens + sequence_length + 1
764
+ )
765
+
766
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
767
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
768
+ attention_mask,
769
+ sequence_length=sequence_length,
770
+ target_length=target_length,
771
+ dtype=dtype,
772
+ cache_position=cache_position,
773
+ batch_size=input_tensor.shape[0],
774
+ )
775
+
776
+ if (
777
+ self.config._attn_implementation == "sdpa"
778
+ and attention_mask is not None
779
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
780
+ and not output_attentions
781
+ ):
782
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
783
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
784
+ # Details: https://github.com/pytorch/pytorch/issues/110213
785
+ min_dtype = torch.finfo(dtype).min
786
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
787
+
788
+ return causal_mask
789
+
790
+ @staticmethod
791
+ def _prepare_4d_causal_attention_mask_with_cache_position(
792
+ attention_mask: torch.Tensor,
793
+ sequence_length: int,
794
+ target_length: int,
795
+ dtype: torch.dtype,
796
+ cache_position: torch.Tensor,
797
+ batch_size: int,
798
+ **kwargs,
799
+ ):
800
+ """
801
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
802
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
803
+
804
+ Args:
805
+ attention_mask (`torch.Tensor`):
806
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
807
+ `(batch_size, 1, query_length, key_value_length)`.
808
+ sequence_length (`int`):
809
+ The sequence length being processed.
810
+ target_length (`int`):
811
+ The target length: when generating with static cache, the mask should be as long as the static cache,
812
+ to account for the 0 padding, the part of the cache that is not filled yet.
813
+ dtype (`torch.dtype`):
814
+ The dtype to use for the 4D attention mask.
815
+ cache_position (`torch.Tensor`):
816
+ Indices depicting the position of the input sequence tokens in the sequence.
817
+ batch_size (`torch.Tensor`):
818
+ Batch size.
819
+ """
820
+ if attention_mask is not None and attention_mask.dim() == 4:
821
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
822
+ causal_mask = attention_mask
823
+ else:
824
+ min_dtype = torch.finfo(dtype).min
825
+ causal_mask = torch.full(
826
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
827
+ )
828
+ if sequence_length != 1:
829
+ causal_mask = torch.triu(causal_mask, diagonal=1)
830
+ causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
831
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
832
+ if attention_mask is not None:
833
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
834
+ mask_length = attention_mask.shape[-1]
835
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
836
+ causal_mask.device
837
+ )
838
+ padding_mask = padding_mask == 0
839
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
840
+ padding_mask, min_dtype
841
+ )
842
+
843
+ return causal_mask
844
+
845
+
846
+ def load_balancing_loss_func(
847
+ gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
848
+ num_experts: Optional[int] = None,
849
+ top_k=2,
850
+ attention_mask: Optional[torch.Tensor] = None,
851
+ ) -> Union[torch.Tensor, int]:
852
+ r"""
853
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
854
+
855
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
856
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
857
+ experts is too unbalanced.
858
+
859
+ Args:
860
+ gate_logits:
861
+ Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
862
+ shape [batch_size X sequence_length, num_experts].
863
+ num_experts:
864
+ Number of experts
865
+ top_k:
866
+ The number of experts to route per-token, can be also interpreted as the `top-k` routing
867
+ parameter.
868
+ attention_mask (`torch.Tensor`, *optional*):
869
+ The attention_mask used in forward function
870
+ shape [batch_size X sequence_length] if not None.
871
+
872
+ Returns:
873
+ The auxiliary loss.
874
+ """
875
+ if gate_logits is None or not isinstance(gate_logits, tuple):
876
+ return 0
877
+
878
+ if isinstance(gate_logits, tuple):
879
+ compute_device = gate_logits[0].device
880
+ concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
881
+
882
+ routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
883
+
884
+ _, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
885
+
886
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
887
+
888
+ if attention_mask is None:
889
+ # Compute the percentage of tokens routed to each experts
890
+ tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
891
+
892
+ # Compute the average probability of routing to these experts
893
+ router_prob_per_expert = torch.mean(routing_weights, dim=0)
894
+ else:
895
+ batch_size, sequence_length = attention_mask.shape
896
+ num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
897
+
898
+ # Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
899
+ expert_attention_mask = (
900
+ attention_mask[None, :, :, None, None]
901
+ .expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
902
+ .reshape(-1, top_k, num_experts)
903
+ .to(compute_device)
904
+ )
905
+
906
+ # Compute the percentage of tokens routed to each experts
907
+ tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
908
+ expert_attention_mask, dim=0
909
+ )
910
+
911
+ # Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
912
+ router_per_expert_attention_mask = (
913
+ attention_mask[None, :, :, None]
914
+ .expand((num_hidden_layers, batch_size, sequence_length, routing_weights.shape[1]))
915
+ .reshape(-1, routing_weights.shape[1])
916
+ .to(compute_device)
917
+ )
918
+
919
+ # Compute the average probability of routing to these experts
920
+ router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
921
+ router_per_expert_attention_mask, dim=0
922
+ )
923
+
924
+ device_index = routing_weights.device.index if routing_weights.device.index is not None else 0
925
+ rank = routing_weights.shape[1] * int(device_index)
926
+ overall_loss = torch.sum(
927
+ tokens_per_expert[:, rank : rank + routing_weights.shape[1]] * router_prob_per_expert.unsqueeze(0)
928
+ )
929
+ return overall_loss * num_experts
930
+
931
+
932
+ class GraniteMoeSharedForCausalLM(GraniteMoeSharedPreTrainedModel, GenerationMixin):
933
+ _tied_weights_keys = ["lm_head.weight"]
934
+
935
+ def __init__(self, config: GraniteMoeSharedConfig):
936
+ super().__init__(config)
937
+ self.model = GraniteMoeSharedModel(config)
938
+ self.vocab_size = config.vocab_size
939
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
940
+
941
+ self.router_aux_loss_coef = config.router_aux_loss_coef
942
+ self.num_experts = config.num_local_experts
943
+ self.num_experts_per_tok = config.num_experts_per_tok
944
+
945
+ # Initialize weights and apply final processing
946
+ self.post_init()
947
+
948
+ @auto_docstring
949
+ def forward(
950
+ self,
951
+ input_ids: Optional[torch.LongTensor] = None,
952
+ attention_mask: Optional[torch.Tensor] = None,
953
+ position_ids: Optional[torch.LongTensor] = None,
954
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
955
+ inputs_embeds: Optional[torch.FloatTensor] = None,
956
+ labels: Optional[torch.LongTensor] = None,
957
+ use_cache: Optional[bool] = None,
958
+ output_attentions: Optional[bool] = None,
959
+ output_hidden_states: Optional[bool] = None,
960
+ output_router_logits: Optional[bool] = None,
961
+ return_dict: Optional[bool] = None,
962
+ cache_position: Optional[torch.LongTensor] = None,
963
+ logits_to_keep: Union[int, torch.Tensor] = 0,
964
+ **kwargs,
965
+ ) -> Union[tuple, MoeCausalLMOutputWithPast]:
966
+ r"""
967
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
968
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
969
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
970
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
971
+
972
+ Example:
973
+
974
+ ```python
975
+ >>> from transformers import AutoTokenizer, GraniteMoeSharedForCausalLM
976
+
977
+ >>> model = GraniteMoeSharedForCausalLM.from_pretrained("ibm/PowerMoE-3b")
978
+ >>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")
979
+
980
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
981
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
982
+
983
+ >>> # Generate
984
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
985
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
986
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
987
+ ```"""
988
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
989
+ output_router_logits = (
990
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
991
+ )
992
+ output_hidden_states = (
993
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
994
+ )
995
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
996
+
997
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
998
+ outputs = self.model(
999
+ input_ids=input_ids,
1000
+ attention_mask=attention_mask,
1001
+ position_ids=position_ids,
1002
+ past_key_values=past_key_values,
1003
+ inputs_embeds=inputs_embeds,
1004
+ use_cache=use_cache,
1005
+ output_attentions=output_attentions,
1006
+ output_hidden_states=output_hidden_states,
1007
+ output_router_logits=output_router_logits,
1008
+ return_dict=return_dict,
1009
+ cache_position=cache_position,
1010
+ **kwargs,
1011
+ )
1012
+
1013
+ # Only compute necessary logits
1014
+ hidden_states = outputs[0]
1015
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
1016
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
1017
+ logits = logits / self.config.logits_scaling
1018
+
1019
+ loss = None
1020
+ if labels is not None:
1021
+ # Upcast to float if we need to compute the loss to avoid potential precision issues
1022
+ logits = logits.float()
1023
+ # Flatten the tokens
1024
+ loss = self.loss_function(
1025
+ logits,
1026
+ labels,
1027
+ vocab_size=self.config.vocab_size,
1028
+ **kwargs,
1029
+ )
1030
+
1031
+ aux_loss = None
1032
+ if output_router_logits:
1033
+ aux_loss = load_balancing_loss_func(
1034
+ outputs.router_logits if return_dict else outputs[-1],
1035
+ self.num_experts,
1036
+ self.num_experts_per_tok,
1037
+ attention_mask,
1038
+ )
1039
+ if labels is not None:
1040
+ loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
1041
+
1042
+ if not return_dict:
1043
+ output = (logits,) + outputs[1:]
1044
+ if output_router_logits:
1045
+ output = (aux_loss,) + output
1046
+ return (loss,) + output if loss is not None else output
1047
+
1048
+ return MoeCausalLMOutputWithPast(
1049
+ loss=loss,
1050
+ aux_loss=aux_loss,
1051
+ logits=logits,
1052
+ past_key_values=outputs.past_key_values,
1053
+ hidden_states=outputs.hidden_states,
1054
+ attentions=outputs.attentions,
1055
+ router_logits=outputs.router_logits,
1056
+ )
1057
+
1058
+
1059
+ __all__ = ["GraniteMoeSharedForCausalLM", "GraniteMoeSharedModel", "GraniteMoeSharedPreTrainedModel"]