Prompt48 commited on
Commit
365b498
·
verified ·
1 Parent(s): 3812072

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

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