Adding `safetensors` variant of this model

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