Jtapsa commited on
Commit
63bfa48
·
verified ·
1 Parent(s): 33f8318

Add moe.py

Browse files
Files changed (1) hide show
  1. moe.py +558 -0
moe.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+ from typing import Optional, Tuple, List, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ from transformers import PreTrainedModel, PretrainedConfig
10
+ from transformers import AutoConfig, AutoModelForCausalLM
11
+
12
+
13
+ from transformers.modeling_outputs import (
14
+ BaseModelOutput,
15
+ CausalLMOutput,
16
+ )
17
+
18
+
19
+ @dataclass
20
+ class BaseModelOutputWithAux(BaseModelOutput):
21
+ aux_loss: Optional[torch.Tensor] = None
22
+
23
+
24
+ def create_causal_mask(seq_len: int, device=None, dtype=torch.float32):
25
+ mask = torch.full((seq_len, seq_len), torch.finfo(dtype).min, device=device, dtype=dtype)
26
+ mask = torch.triu(mask, diagonal=1)
27
+ return mask
28
+
29
+
30
+ def create_sw_mask(seq_len: int, window_size: Optional[int], device=None, dtype=torch.float32):
31
+ if not window_size:
32
+ return None
33
+ i = torch.arange(seq_len, device=device)
34
+ j = torch.arange(seq_len, device=device)
35
+ allowed = (j[None, :] <= i[:, None]) & (j[None, :] >= i[:, None] - (window_size - 1))
36
+ mask = torch.zeros((seq_len, seq_len), device=device, dtype=dtype)
37
+ mask = mask.masked_fill(~allowed, torch.finfo(dtype).min)
38
+ return mask
39
+
40
+
41
+ class Linear(nn.Module):
42
+ def __init__(self, in_dim: int, out_dim: int, b: bool = True):
43
+ super().__init__()
44
+ self.linear = nn.Linear(in_dim, out_dim, bias=b)
45
+
46
+ def forward(self, x: torch.Tensor):
47
+ return self.linear(x)
48
+
49
+
50
+ class Layer_norm(nn.Module):
51
+ def __init__(self, dim: int, eps: float = 1e-5, b: bool = True):
52
+ super().__init__()
53
+ self.layer_norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=b)
54
+
55
+ def forward(self, x: torch.Tensor):
56
+ return self.layer_norm(x)
57
+
58
+
59
+ class MLP(nn.Module):
60
+ def __init__(self, in_dim: int, hidden_dim: int, dim_out: Optional[int] = None, b: bool = True):
61
+ super().__init__()
62
+ self.linear1 = nn.Linear(in_dim, hidden_dim, bias=b)
63
+ out_dim = in_dim if dim_out is None else dim_out
64
+ self.linear2 = nn.Linear(hidden_dim, out_dim, bias=b)
65
+
66
+ @staticmethod
67
+ def gelu_new(x: torch.Tensor):
68
+ return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * x ** 3)))
69
+
70
+ def forward(self, x: torch.Tensor):
71
+ x = self.linear1(x)
72
+ x = self.gelu_new(x)
73
+ x = self.linear2(x)
74
+ return x
75
+
76
+
77
+ class SelfAttention(nn.Module):
78
+ def __init__(self, dim: int, n_heads: int, attn_dropout: float = 0.1):
79
+ super().__init__()
80
+ assert dim % n_heads == 0, "dim must be divisible by n_heads"
81
+ self.dim = dim
82
+ self.n_heads = n_heads
83
+ self.head_dim = dim // n_heads
84
+ self.Q = nn.Linear(dim, dim, bias=True)
85
+ self.K = nn.Linear(dim, dim, bias=True)
86
+ self.V = nn.Linear(dim, dim, bias=True)
87
+ self.O = nn.Linear(dim, dim, bias=True)
88
+ self.attn_dropout = nn.Dropout(attn_dropout)
89
+
90
+ def forward(self, x: torch.Tensor, *, causal_mask: Optional[torch.Tensor] = None, key_padding_mask: Optional[torch.Tensor] = None):
91
+ # x: [B,S,D]
92
+ B, S, D = x.shape
93
+ H = self.n_heads
94
+ Dh = self.head_dim
95
+
96
+ q = self.Q(x).view(B, S, H, Dh).transpose(1, 2) # [B,H,S,Dh]
97
+ k = self.K(x).view(B, S, H, Dh).transpose(1, 2)
98
+ v = self.V(x).view(B, S, H, Dh).transpose(1, 2)
99
+
100
+ attn = (q @ k.transpose(-2, -1)) / math.sqrt(Dh) # [B,H,S,S]
101
+ neg_inf = torch.finfo(attn.dtype).min
102
+
103
+ if causal_mask is not None:
104
+ attn = attn + causal_mask[None, None, :, :]
105
+
106
+ if key_padding_mask is not None: # True at PAD keys
107
+ attn = attn.masked_fill(key_padding_mask[:, None, None, :], neg_inf)
108
+
109
+ attn = F.softmax(attn, dim=-1)
110
+ attn = self.attn_dropout(attn)
111
+ out = (attn @ v).transpose(1, 2).contiguous().view(B, S, D)
112
+
113
+ if key_padding_mask is not None:
114
+ query_mask = (~key_padding_mask).to(out.dtype).unsqueeze(-1) # [B,S,1]
115
+ out = out * query_mask
116
+
117
+ return self.O(out)
118
+
119
+
120
+ class Layer_Block(nn.Module):
121
+ def __init__(self, dim: int, n_heads: int, ffn_multp: int, dropout: float = 0.1, attn_dropout: float = 0.1):
122
+ super().__init__()
123
+ self.norm_1 = Layer_norm(dim)
124
+ self.norm_2 = Layer_norm(dim)
125
+ self.attention = SelfAttention(dim, n_heads, attn_dropout)
126
+
127
+ ###
128
+ self.feedforward = MLP(dim, dim * ffn_multp)
129
+
130
+ ####
131
+ self.dropout1 = nn.Dropout(dropout)
132
+ self.dropout2 = nn.Dropout(dropout)
133
+
134
+ def forward(self, x: torch.Tensor, *, causal_mask=None, key_padding_mask=None):
135
+ residual = x
136
+ x = self.norm_1(x)
137
+ x = self.attention(x, causal_mask=causal_mask, key_padding_mask=key_padding_mask)
138
+ x = self.dropout1(x)
139
+ x = residual + x
140
+
141
+ residual = x
142
+ x = self.norm_2(x)
143
+ x = self.feedforward(x)
144
+ x = self.dropout2(x)
145
+ x = residual + x
146
+ return x
147
+
148
+
149
+ class Top_k_Router(nn.Module):
150
+ def __init__(self, dim: int, n_experts: int, k: int):
151
+ super().__init__()
152
+ self.n_experts = n_experts
153
+ self.k = k
154
+ self.router = Linear(dim, n_experts)
155
+
156
+ def forward(self, x: torch.Tensor):
157
+ # x: [T, D]
158
+ logits = self.router(x)
159
+ probs = F.softmax(logits, dim=-1)
160
+ topk_prob, topk_idx = torch.topk(probs, k=self.k, dim=-1)
161
+ topk_prob = topk_prob / (topk_prob.sum(dim=-1, keepdim=True) + 1e-9)
162
+
163
+ p_mean = probs.mean(dim=0)
164
+ T, E = probs.size()
165
+ one_hot = F.one_hot(topk_idx, num_classes=E).sum(dim=1)
166
+ f_mean = one_hot.float().mean(dim=0) / float(self.k)
167
+ aux_loss = (E * (p_mean * f_mean).sum())
168
+
169
+ return topk_idx, topk_prob, aux_loss
170
+
171
+ class MoE_Block(nn.Module):
172
+ def __init__(self, dim_in: int, n_experts: int, k: int, dim_hidden: int, dim_out: Optional[int] = None):
173
+ super().__init__()
174
+ self.n_experts = n_experts
175
+ self.k = k
176
+ self.dim_out = dim_in if dim_out is None else dim_out
177
+ self.router = Top_k_Router(dim_in, n_experts, k)
178
+ self.experts = nn.ModuleList([nn.Linear(dim_in, self.dim_out, bias=True) for _ in range(n_experts)])
179
+
180
+ def forward(self, x: torch.Tensor):
181
+ # x: [B,S,D]
182
+ B, S, D = x.shape
183
+ T = B * S
184
+ x_flat = x.view(T, D)
185
+
186
+ topk_idx, topk_prob, aux_loss = self.router(x_flat) # [T,k], [T,k]
187
+ y_flat = x_flat.new_zeros((T, self.dim_out))
188
+
189
+ for slot in range(self.k):
190
+ e_ids = topk_idx[:, slot]
191
+ e_prob = topk_prob[:, slot].unsqueeze(-1) # [T,1]
192
+ for e in range(self.n_experts):
193
+ idx = (e_ids == e).nonzero(as_tuple=False).squeeze(1)
194
+ if idx.numel() == 0:
195
+ continue
196
+ y_e = self.experts[e](x_flat.index_select(0, idx)) # [Ne, dim_out]
197
+ y_flat.index_add_(0, idx, y_e * e_prob.index_select(0, idx))
198
+
199
+ return y_flat.view(B, S, self.dim_out), aux_loss
200
+
201
+
202
+
203
+ class MoELayer(nn.Module):
204
+ def __init__(self, dim: int, n_heads: int, n_blocks: int, k: int, ffn_multp: int, dropout: float = 0.1, attn_dropout: float = 0.1):
205
+ super().__init__()
206
+
207
+ self.norm_1 = Layer_norm(dim)
208
+ self.norm_2 = Layer_norm(dim)
209
+ self.attention = SelfAttention(dim, n_heads, attn_dropout)
210
+
211
+ self.feedforward = nn.ModuleList([MLP(dim, dim * ffn_multp) for _ in range(n_blocks)])
212
+
213
+ self.dropout1 = nn.Dropout(dropout)
214
+ self.dropout2 = nn.Dropout(dropout)
215
+
216
+ self.dim = dim
217
+ self.n_blocks = n_blocks
218
+
219
+ self.router = Top_k_Router(dim, n_blocks, k)
220
+
221
+ def forward(self, x: torch.Tensor, *, causal_mask=None, key_padding_mask=None):
222
+ B, S, D = x.shape
223
+ T = B * S
224
+
225
+ residual = x
226
+ x = self.norm_1(x)
227
+ x = self.attention(x, causal_mask=causal_mask, key_padding_mask=key_padding_mask)
228
+ x = self.dropout1(x)
229
+ x = residual + x
230
+
231
+ residual = x
232
+ x = self.norm_2(x)
233
+
234
+ outs = [blk(x) for blk in self.feedforward]
235
+
236
+ Y = torch.stack([y.view(T, D) for y in outs], dim=1) # [T, n_blocks, D]
237
+
238
+ x_flat = x.view(T, D)
239
+ topk_idx, topk_prob, aux_loss = self.router(x_flat) # [T,k], [T,k]
240
+
241
+ gather_idx = topk_idx.unsqueeze(-1).expand(-1, -1, D) # [T,k,D]
242
+ Y_topk = torch.gather(Y, dim=1, index=gather_idx) # [T,k,D]
243
+ y_flat = (Y_topk * topk_prob.unsqueeze(-1)).sum(dim=1) # [T,D]
244
+
245
+ y = y_flat.view(B, S, D)
246
+
247
+ x = self.dropout2(y)
248
+ x = residual + x
249
+
250
+ return x, aux_loss
251
+
252
+
253
+ class MoELMConfig(PretrainedConfig):
254
+ model_type = "moe_lm"
255
+
256
+ def __init__(
257
+ self,
258
+ vocab_size: int = 16384,
259
+ bos_token_id = 1,
260
+ eos_token_id = 2,
261
+ pad_token_id = 3,
262
+ mask_token_id = 4,
263
+ max_position_embeddings: int = 1024,
264
+ n_layers: int = 12,
265
+ ffn_multp: int = 4,
266
+ dim: int = 348,
267
+ n_heads: int = 6,
268
+ # Parallel specifics
269
+ n_parallel_blocks: int = 4,
270
+ parallel_dim: int = 192,
271
+ parallel_n_heads: int = 3,
272
+ parallel_k: int = 2,
273
+ sliding_window: Optional[int] = None,
274
+ # MoE specifics
275
+ n_experts: int = 4,
276
+ moe_k: int = 2,
277
+ # Dropouts / norms
278
+ attn_pdrop: float = 0.1,
279
+ embd_pdrop: float = 0.1,
280
+ resid_pdrop: float = 0.1,
281
+ layer_norm_epsilon: float = 1e-5,
282
+ tie_word_embeddings: bool = True,
283
+ **kwargs,
284
+ ):
285
+ super().__init__(
286
+ vocab_size=vocab_size,
287
+ pad_token_id=pad_token_id,
288
+ bos_token_id=bos_token_id,
289
+ eos_token_id=eos_token_id,
290
+ **kwargs,
291
+ )
292
+
293
+ # Special tokens
294
+ self.mask_token_id = mask_token_id
295
+
296
+ # Core dims
297
+ self.vocab_size = vocab_size
298
+ self.max_position_embeddings = max_position_embeddings
299
+ self.n_layers = n_layers
300
+ self.ffn_multp = ffn_multp
301
+ self.dim = dim
302
+ self.n_heads = n_heads
303
+
304
+ # Parallel specifics
305
+ self.n_parallel_blocks = n_parallel_blocks
306
+ self.parallel_dim = parallel_dim
307
+ self.parallel_n_heads = parallel_n_heads
308
+ self.parallel_k = parallel_k
309
+ self.sliding_window = sliding_window
310
+
311
+ # MoE specifics
312
+ self.n_experts = n_experts
313
+ self.moe_k = moe_k
314
+
315
+ # Dropouts / norms
316
+ self.attn_pdrop = attn_pdrop
317
+ self.embd_pdrop = embd_pdrop
318
+ self.resid_pdrop = resid_pdrop
319
+ self.layer_norm_epsilon = layer_norm_epsilon
320
+
321
+ # Tying
322
+ self.tie_word_embeddings = tie_word_embeddings
323
+
324
+ class MoEModel(PreTrainedModel):
325
+ config_class = MoELMConfig
326
+
327
+ def __init__(self, config: MoELMConfig):
328
+ super().__init__(config)
329
+ self.config = config
330
+
331
+ # --- embeddings ---
332
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
333
+ self.embed_positions = nn.Embedding(config.max_position_embeddings, config.dim)
334
+ self.embd_dropout = nn.Dropout(config.embd_pdrop)
335
+
336
+
337
+ self.layers = nn.ModuleList()
338
+
339
+ # Large Layer
340
+ self.layers.append(Layer_Block(config.dim,
341
+ config.n_heads,
342
+ config.ffn_multp,
343
+ dropout=config.resid_pdrop,
344
+ attn_dropout=config.attn_pdrop))
345
+
346
+ # MoE Linear
347
+ self.layers.append(MoE_Block(config.dim,
348
+ config.n_experts,
349
+ config.moe_k,
350
+ dim_hidden=config.dim,
351
+ dim_out=config.parallel_dim))
352
+
353
+ # Parallel Layers
354
+ for _ in range(config.n_layers - 2):
355
+ self.layers.append(MoELayer(config.parallel_dim,
356
+ config.parallel_n_heads,
357
+ config.n_parallel_blocks,
358
+ config.parallel_k,
359
+ config.ffn_multp,
360
+ dropout=config.resid_pdrop,
361
+ attn_dropout=config.attn_pdrop))
362
+
363
+ # MoE Linear
364
+ self.layers.append(MoE_Block(config.parallel_dim,
365
+ config.n_experts,
366
+ config.moe_k,
367
+ dim_hidden=config.parallel_dim,
368
+ dim_out=config.dim))
369
+
370
+ # Large Layer
371
+ self.layers.append(Layer_Block(config.dim,
372
+ config.n_heads,
373
+ config.ffn_multp,
374
+ dropout=config.resid_pdrop,
375
+ attn_dropout=config.attn_pdrop))
376
+
377
+ self.norm = Layer_norm(config.dim)
378
+ self.post_init()
379
+
380
+ def get_input_embeddings(self):
381
+ return self.embed_tokens
382
+
383
+ def set_input_embeddings(self, new_embeddings):
384
+ self.embed_tokens = new_embeddings
385
+
386
+ def _init_weights(self, module):
387
+ if isinstance(module, (nn.Linear, nn.Embedding)):
388
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
389
+ if isinstance(module, nn.Linear) and module.bias is not None:
390
+ nn.init.zeros_(module.bias)
391
+
392
+ def forward(
393
+ self,
394
+ input_ids: torch.LongTensor,
395
+ attention_mask: Optional[torch.Tensor] = None,
396
+ return_dict: bool = True,
397
+ return_aux: Optional[bool] = False,
398
+ return_aux_dict: Optional[bool] = False,
399
+ **unused,
400
+ ) -> Union[BaseModelOutputWithAux, BaseModelOutput, Tuple]:
401
+
402
+ device = input_ids.device
403
+ B, S = input_ids.shape
404
+
405
+ key_padding = input_ids.eq(self.config.pad_token_id) if attention_mask is None else (attention_mask == 0)
406
+
407
+ # embeddings
408
+ x = self.embed_tokens(input_ids)
409
+
410
+ mask_dtype = x.dtype
411
+ causal = create_causal_mask(S, device=device, dtype=mask_dtype)
412
+ sw = create_sw_mask(S, self.config.sliding_window, device=device, dtype=mask_dtype)
413
+ sw_mask = causal if sw is None else torch.minimum(causal, sw)
414
+
415
+
416
+ pos = torch.arange(S, device=device)
417
+ pos = pos.unsqueeze(0).expand(B, S)
418
+ x = x + self.embed_positions(pos)
419
+ x = self.embd_dropout(x)
420
+
421
+ aux_total = None
422
+
423
+
424
+ # First large
425
+ x = self.layers[0](x, causal_mask=causal, key_padding_mask=key_padding)
426
+
427
+ # MoE shrink
428
+ x, aux = self.layers[1](x)
429
+
430
+ if aux is not None:
431
+ aux_total = aux
432
+
433
+ idx = 2
434
+ for i in range(self.config.n_layers - 2):
435
+ use_sw = (self.config.sliding_window is not None) and (i % 2 == 1)
436
+ mask = sw_mask if use_sw else causal
437
+ x, aux = self.layers[idx](x, causal_mask=mask, key_padding_mask=key_padding)
438
+ if aux is not None:
439
+ aux_total += aux
440
+ idx += 1
441
+
442
+ # MoE grow
443
+ x, aux = self.layers[idx](x)
444
+
445
+ if aux is not None:
446
+ aux_total += aux
447
+
448
+ idx += 1
449
+
450
+ # Second large
451
+ x = self.layers[idx](x, causal_mask=causal, key_padding_mask=key_padding)
452
+
453
+ last_hidden = self.norm(x)
454
+
455
+ if not return_dict:
456
+ return (last_hidden, aux_total) if return_aux else (last_hidden,)
457
+
458
+ if return_aux_dict:
459
+ return BaseModelOutputWithAux(
460
+ last_hidden_state=last_hidden,
461
+ hidden_states=None,
462
+ attentions=None,
463
+ aux_loss=aux_total,
464
+ )
465
+ else:
466
+ return BaseModelOutput(
467
+ last_hidden_state=last_hidden,
468
+ hidden_states=None,
469
+ attentions=None,
470
+ )
471
+
472
+
473
+ class MoEForCausalLM(PreTrainedModel):
474
+ config_class = MoELMConfig
475
+
476
+ def __init__(self, config: MoELMConfig):
477
+ super().__init__(config)
478
+ self.config = config
479
+ self.model = MoEModel(config)
480
+ self.lm_head = nn.Linear(config.dim, config.vocab_size, bias=False)
481
+ if config.tie_word_embeddings:
482
+ self.lm_head.weight = self.model.embed_tokens.weight
483
+ self.post_init()
484
+
485
+ def get_input_embeddings(self):
486
+ return self.model.get_input_embeddings()
487
+
488
+ def set_input_embeddings(self, new_embeddings):
489
+ self.model.set_input_embeddings(new_embeddings)
490
+ if self.config.tie_word_embeddings:
491
+ self.lm_head.weight = self.model.embed_tokens.weight
492
+
493
+ def _init_weights(self, module):
494
+ if isinstance(module, (nn.Linear, nn.Embedding)):
495
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
496
+ if isinstance(module, nn.Linear) and module.bias is not None:
497
+ nn.init.zeros_(module.bias)
498
+
499
+ def forward(
500
+ self,
501
+ input_ids: torch.LongTensor,
502
+ attention_mask: Optional[torch.Tensor] = None,
503
+ labels: Optional[torch.LongTensor] = None,
504
+ return_dict: bool = True,
505
+ return_aux: Optional[bool] = False,
506
+ aux_loss_weight: Optional[float] = 0.2,
507
+ **unused,
508
+ ) -> Union[CausalLMOutput, Tuple]:
509
+
510
+
511
+ if return_aux:
512
+ base_out = self.model(input_ids=input_ids,
513
+ attention_mask=attention_mask,
514
+ return_aux_dict=True,
515
+ return_aux=True)
516
+ else:
517
+ base_out = self.model(input_ids=input_ids,
518
+ attention_mask=attention_mask)
519
+
520
+ logits = self.lm_head(base_out.last_hidden_state).float()
521
+
522
+ loss = None
523
+
524
+ if labels is not None:
525
+
526
+ shift_logits = logits[:, :-1, :].contiguous()
527
+ shift_labels = labels[:, 1:].contiguous()
528
+
529
+ pad_id = self.config.pad_token_id
530
+ if pad_id is not None:
531
+ shift_labels = shift_labels.masked_fill(shift_labels == pad_id, -100)
532
+
533
+ loss = F.cross_entropy(
534
+ shift_logits.view(-1, shift_logits.size(-1)),
535
+ shift_labels.view(-1),
536
+ ignore_index=-100,
537
+ )
538
+
539
+
540
+ aux = getattr(base_out, "aux_loss", None)
541
+ if aux is not None:
542
+ loss = loss + aux_loss_weight * aux
543
+
544
+ if not return_dict:
545
+ return (loss, logits) if loss is not None else (logits,)
546
+
547
+ return CausalLMOutput(
548
+ loss=loss,
549
+ logits=logits,
550
+ hidden_states=base_out.hidden_states,
551
+ attentions=base_out.attentions,
552
+ )
553
+
554
+ AutoConfig.register("moe_lm", MoELMConfig)
555
+ AutoModelForCausalLM.register(MoELMConfig, MoEForCausalLM)
556
+
557
+
558
+