mike1210 commited on
Commit
1b72735
·
verified ·
1 Parent(s): 874dbc4

Upload model_minimind.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model_minimind.py +474 -0
model_minimind.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
2
+ # MiniMind Config
3
+ # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
4
+
5
+ from transformers import PretrainedConfig
6
+
7
+
8
+ class MiniMindConfig(PretrainedConfig):
9
+ model_type = "minimind"
10
+
11
+ def __init__(
12
+ self,
13
+ dropout: float = 0.1,
14
+ bos_token_id: int = 1,
15
+ eos_token_id: int = 2,
16
+ pad_token_id: int = 0,
17
+ tie_word_embeddings: bool = True,
18
+ hidden_act: str = 'silu',
19
+ hidden_size: int = 512,
20
+ intermediate_size: int = None,
21
+ max_position_embeddings: int = 32768,
22
+ num_attention_heads: int = 8,
23
+ num_hidden_layers: int = 8,
24
+ num_key_value_heads: int = 2,
25
+ vocab_size: int = 6400,
26
+ rms_norm_eps: float = 1e-05,
27
+ rope_theta: float = 1000000.0,
28
+ inference_rope_scaling: bool = False,
29
+ flash_attn: bool = True,
30
+ ####################################################
31
+ # Here are the specific configurations of MOE
32
+ # When use_moe is false, the following is invalid
33
+ ####################################################
34
+ use_moe: bool = False,
35
+ num_experts_per_tok: int = 2,
36
+ n_routed_experts: int = 8,
37
+ n_shared_experts: int = 1,
38
+ scoring_func: str = 'softmax',
39
+ aux_loss_alpha: float = 0.01,
40
+ seq_aux: bool = True,
41
+ norm_topk_prob: bool = True,
42
+ **kwargs
43
+ ):
44
+ super().__init__(**kwargs)
45
+ self.dropout = dropout
46
+ self.bos_token_id = bos_token_id
47
+ self.eos_token_id = eos_token_id
48
+ self.pad_token_id = pad_token_id
49
+ self.tie_word_embeddings = tie_word_embeddings
50
+ self.hidden_act = hidden_act
51
+ self.hidden_size = hidden_size
52
+ self.intermediate_size = intermediate_size
53
+ self.max_position_embeddings = max_position_embeddings
54
+ self.num_attention_heads = num_attention_heads
55
+ self.num_hidden_layers = num_hidden_layers
56
+ self.num_key_value_heads = num_key_value_heads
57
+ self.vocab_size = vocab_size
58
+ self.rms_norm_eps = rms_norm_eps
59
+ self.rope_theta = rope_theta
60
+ self.inference_rope_scaling = inference_rope_scaling
61
+ # 外推长度 = factor * original_max_position_embeddings
62
+ self.rope_scaling = {
63
+ "beta_fast": 4,
64
+ "beta_slow": 1,
65
+ "factor": 4,
66
+ "original_max_position_embeddings": 2048,
67
+ "type": "yarn"
68
+ } if self.inference_rope_scaling else None
69
+ self.flash_attn = flash_attn
70
+ ####################################################
71
+ # Here are the specific configurations of MOE
72
+ # When use_moe is false, the following is invalid
73
+ ####################################################
74
+ self.use_moe = use_moe
75
+ self.num_experts_per_tok = num_experts_per_tok # 每个token选择的专家数量
76
+ self.n_routed_experts = n_routed_experts # 总的专家数量
77
+ self.n_shared_experts = n_shared_experts # 共享专家
78
+ self.scoring_func = scoring_func # 评分函数,默认为'softmax'
79
+ self.aux_loss_alpha = aux_loss_alpha # 辅助损失的alpha参数
80
+ self.seq_aux = seq_aux # 是否在序列级别上计算辅助损失
81
+ self.norm_topk_prob = norm_topk_prob # 是否标准化top-k概率
82
+
83
+
84
+ # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
85
+ # MiniMind Model
86
+ # 📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘📘
87
+
88
+ import math
89
+ import torch
90
+ import torch.nn.init as init
91
+ import torch.nn.functional as F
92
+ from torch import nn
93
+ from transformers.activations import ACT2FN
94
+ from typing import Optional, Tuple, List, Union
95
+ from transformers import PreTrainedModel, GenerationMixin, PretrainedConfig
96
+ from transformers.modeling_outputs import CausalLMOutputWithPast
97
+
98
+
99
+ class RMSNorm(torch.nn.Module):
100
+ def __init__(self, dim: int, eps: float = 1e-5):
101
+ super().__init__()
102
+ self.eps = eps
103
+ self.weight = nn.Parameter(torch.ones(dim))
104
+
105
+ def _norm(self, x):
106
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
107
+
108
+ def forward(self, x):
109
+ return self.weight * self._norm(x.float()).type_as(x)
110
+
111
+
112
+ def precompute_freqs_cis(dim: int, end: int = int(32 * 1024), rope_base: float = 1e6,
113
+ rope_scaling: Optional[dict] = None):
114
+ freqs = 1.0 / (rope_base ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
115
+ if rope_scaling is not None:
116
+ orig_max, factor, beta_fast, beta_slow = (
117
+ rope_scaling.get("original_max_position_embeddings", 2048), rope_scaling.get("factor", 4),
118
+ rope_scaling.get("beta_fast", 4.0), rope_scaling.get("beta_slow", 1.0)
119
+ )
120
+ if end / orig_max > 1.0:
121
+ corr_dim = next((i for i in range(dim // 2) if 2 * math.pi / freqs[i] > orig_max), dim // 2)
122
+ power = torch.arange(0, dim // 2, device=freqs.device).float() / max(dim // 2 - 1, 1)
123
+ beta = beta_slow + (beta_fast - beta_slow) * power
124
+ # λ = (β·α - β + 1)/(β·α) YaRN标准公式
125
+ scale = torch.where(torch.arange(dim // 2, device=freqs.device) < corr_dim, (beta * factor - beta + 1) / (beta * factor), 1.0 / factor)
126
+ freqs = freqs * scale
127
+
128
+ t = torch.arange(end, device=freqs.device)
129
+ freqs = torch.outer(t, freqs).float()
130
+ freqs_cos = torch.cat([torch.cos(freqs), torch.cos(freqs)], dim=-1)
131
+ freqs_sin = torch.cat([torch.sin(freqs), torch.sin(freqs)], dim=-1)
132
+ return freqs_cos, freqs_sin
133
+
134
+
135
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
136
+ def rotate_half(x):
137
+ return torch.cat((-x[..., x.shape[-1] // 2:], x[..., : x.shape[-1] // 2]), dim=-1)
138
+
139
+ q_embed = (q * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(q) * sin.unsqueeze(unsqueeze_dim))
140
+ k_embed = (k * cos.unsqueeze(unsqueeze_dim)) + (rotate_half(k) * sin.unsqueeze(unsqueeze_dim))
141
+ return q_embed, k_embed
142
+
143
+
144
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
145
+ """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
146
+ bs, slen, num_key_value_heads, head_dim = x.shape
147
+ if n_rep == 1:
148
+ return x
149
+ return (
150
+ x[:, :, :, None, :].expand(bs, slen, num_key_value_heads, n_rep, head_dim).reshape(bs, slen, num_key_value_heads * n_rep, head_dim)
151
+ )
152
+
153
+
154
+ class Attention(nn.Module):
155
+ def __init__(self, args: MiniMindConfig):
156
+ super().__init__()
157
+ self.num_key_value_heads = args.num_attention_heads if args.num_key_value_heads is None else args.num_key_value_heads
158
+ assert args.num_attention_heads % self.num_key_value_heads == 0
159
+ self.n_local_heads = args.num_attention_heads
160
+ self.n_local_kv_heads = self.num_key_value_heads
161
+ self.n_rep = self.n_local_heads // self.n_local_kv_heads
162
+ self.head_dim = args.hidden_size // args.num_attention_heads
163
+ self.q_proj = nn.Linear(args.hidden_size, args.num_attention_heads * self.head_dim, bias=False)
164
+ self.k_proj = nn.Linear(args.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
165
+ self.v_proj = nn.Linear(args.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
166
+ self.o_proj = nn.Linear(args.num_attention_heads * self.head_dim, args.hidden_size, bias=False)
167
+ self.attn_dropout = nn.Dropout(args.dropout)
168
+ self.resid_dropout = nn.Dropout(args.dropout)
169
+ self.dropout = args.dropout
170
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
171
+ # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
172
+
173
+ def forward(self,
174
+ x: torch.Tensor,
175
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor], # 修改为接收cos和sin
176
+ past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
177
+ use_cache=False,
178
+ attention_mask: Optional[torch.Tensor] = None):
179
+ bsz, seq_len, _ = x.shape
180
+ xq, xk, xv = self.q_proj(x), self.k_proj(x), self.v_proj(x)
181
+ xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
182
+ xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
183
+ xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
184
+
185
+ cos, sin = position_embeddings
186
+ xq, xk = apply_rotary_pos_emb(xq, xk, cos[:seq_len], sin[:seq_len])
187
+
188
+ # kv_cache实现
189
+ if past_key_value is not None:
190
+ xk = torch.cat([past_key_value[0], xk], dim=1)
191
+ xv = torch.cat([past_key_value[1], xv], dim=1)
192
+ past_kv = (xk, xv) if use_cache else None
193
+
194
+ xq, xk, xv = (
195
+ xq.transpose(1, 2),
196
+ repeat_kv(xk, self.n_rep).transpose(1, 2),
197
+ repeat_kv(xv, self.n_rep).transpose(1, 2)
198
+ )
199
+
200
+ if self.flash and seq_len > 1 and (attention_mask is None or torch.all(attention_mask == 1)):
201
+ attn_mask = (
202
+ None
203
+ if attention_mask is None
204
+ else attention_mask.view(bsz, 1, 1, -1).expand(bsz, self.n_local_heads, seq_len, -1).bool()
205
+ )
206
+
207
+ output = F.scaled_dot_product_attention(xq, xk, xv, attn_mask=attn_mask, dropout_p=self.dropout if self.training else 0.0, is_causal=True)
208
+ else:
209
+ scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
210
+ scores = scores + torch.triu(
211
+ torch.full((seq_len, seq_len), float("-inf"), device=scores.device),
212
+ diagonal=1
213
+ ).unsqueeze(0).unsqueeze(0) # scores+mask
214
+
215
+ if attention_mask is not None:
216
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
217
+ extended_attention_mask = (1.0 - extended_attention_mask) * -1e9
218
+ scores = scores + extended_attention_mask
219
+
220
+ scores = F.softmax(scores.float(), dim=-1).type_as(xq)
221
+ scores = self.attn_dropout(scores)
222
+ output = scores @ xv
223
+
224
+ output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
225
+ output = self.resid_dropout(self.o_proj(output))
226
+ return output, past_kv
227
+
228
+
229
+ class FeedForward(nn.Module):
230
+ def __init__(self, config: MiniMindConfig):
231
+ super().__init__()
232
+ if config.intermediate_size is None:
233
+ intermediate_size = int(config.hidden_size * 8 / 3)
234
+ config.intermediate_size = 64 * ((intermediate_size + 64 - 1) // 64)
235
+ self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
236
+ self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
237
+ self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
238
+ self.dropout = nn.Dropout(config.dropout)
239
+ self.act_fn = ACT2FN[config.hidden_act]
240
+
241
+ def forward(self, x):
242
+ return self.dropout(self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)))
243
+
244
+
245
+ class MoEGate(nn.Module):
246
+ def __init__(self, config: MiniMindConfig):
247
+ super().__init__()
248
+ self.config = config
249
+ self.top_k = config.num_experts_per_tok
250
+ self.n_routed_experts = config.n_routed_experts
251
+
252
+ self.scoring_func = config.scoring_func
253
+ self.alpha = config.aux_loss_alpha
254
+ self.seq_aux = config.seq_aux
255
+
256
+ self.norm_topk_prob = config.norm_topk_prob
257
+ self.gating_dim = config.hidden_size
258
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
259
+ self.reset_parameters()
260
+
261
+ def reset_parameters(self) -> None:
262
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
263
+
264
+ def forward(self, hidden_states):
265
+ bsz, seq_len, h = hidden_states.shape
266
+ hidden_states = hidden_states.view(-1, h)
267
+ logits = F.linear(hidden_states, self.weight, None)
268
+ if self.scoring_func == 'softmax':
269
+ scores = logits.softmax(dim=-1)
270
+ else:
271
+ raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
272
+
273
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
274
+
275
+ if self.top_k > 1 and self.norm_topk_prob:
276
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
277
+ topk_weight = topk_weight / denominator
278
+
279
+ if self.training and self.alpha > 0.0:
280
+ scores_for_aux = scores
281
+ aux_topk = self.top_k
282
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
283
+ if self.seq_aux:
284
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
285
+ ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
286
+ ce.scatter_add_(1, topk_idx_for_aux_loss,
287
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
288
+ seq_len * aux_topk / self.n_routed_experts)
289
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
290
+ else:
291
+ mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
292
+ ce = mask_ce.float().mean(0)
293
+ Pi = scores_for_aux.mean(0)
294
+ fi = ce * self.n_routed_experts
295
+ aux_loss = (Pi * fi).sum() * self.alpha
296
+ else:
297
+ aux_loss = 0
298
+ return topk_idx, topk_weight, aux_loss
299
+
300
+
301
+ class MOEFeedForward(nn.Module):
302
+ def __init__(self, config: MiniMindConfig):
303
+ super().__init__()
304
+ self.config = config
305
+ self.experts = nn.ModuleList([
306
+ FeedForward(config)
307
+ for _ in range(config.n_routed_experts)
308
+ ])
309
+ self.gate = MoEGate(config)
310
+ if config.n_shared_experts > 0:
311
+ self.shared_experts = nn.ModuleList([
312
+ FeedForward(config)
313
+ for _ in range(config.n_shared_experts)
314
+ ])
315
+
316
+ def forward(self, x):
317
+ identity = x
318
+ orig_shape = x.shape
319
+ bsz, seq_len, _ = x.shape
320
+ # 使用门控机制选择专家
321
+ topk_idx, topk_weight, aux_loss = self.gate(x)
322
+ x = x.view(-1, x.shape[-1])
323
+ flat_topk_idx = topk_idx.view(-1)
324
+ if self.training:
325
+ x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
326
+ y = torch.empty_like(x, dtype=torch.float16)
327
+ for i, expert in enumerate(self.experts):
328
+ y[flat_topk_idx == i] = expert(x[flat_topk_idx == i]).to(y.dtype) # 确保类型一致
329
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
330
+ y = y.view(*orig_shape)
331
+ else:
332
+ y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
333
+ if self.config.n_shared_experts > 0:
334
+ for expert in self.shared_experts:
335
+ y = y + expert(identity)
336
+ self.aux_loss = aux_loss
337
+ return y
338
+
339
+ @torch.no_grad()
340
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
341
+ expert_cache = torch.zeros_like(x)
342
+ idxs = flat_expert_indices.argsort()
343
+ tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
344
+ token_idxs = idxs // self.config.num_experts_per_tok
345
+ # 当tokens_per_expert = [6, 15, 20, 26],tokens_per_expert.shape[0]即为专家数量(此时为4)
346
+ # 且token_idxs = [3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...] 时
347
+ # 意味token_idxs[:6] -> [3, 7, 19, 21, 24, 25]这6个位置属于专家0处理的token(每个token有可能被多个专家处理,这取决于num_experts_per_tok)
348
+ # 接下来9个位置token_idxs[6:15] -> [4, 5, 6, 10, 11, 12...]属于专家1处理的token...依此类推
349
+ for i, end_idx in enumerate(tokens_per_expert):
350
+ start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
351
+ if start_idx == end_idx:
352
+ continue
353
+ expert = self.experts[i]
354
+ exp_token_idx = token_idxs[start_idx:end_idx]
355
+ expert_tokens = x[exp_token_idx]
356
+ expert_out = expert(expert_tokens).to(expert_cache.dtype)
357
+ expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
358
+ expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
359
+
360
+ return expert_cache
361
+
362
+
363
+ class MiniMindBlock(nn.Module):
364
+ def __init__(self, layer_id: int, config: MiniMindConfig):
365
+ super().__init__()
366
+ self.num_attention_heads = config.num_attention_heads
367
+ self.hidden_size = config.hidden_size
368
+ self.head_dim = config.hidden_size // config.num_attention_heads
369
+ self.self_attn = Attention(config)
370
+
371
+ self.layer_id = layer_id
372
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
373
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
374
+ self.mlp = FeedForward(config) if not config.use_moe else MOEFeedForward(config)
375
+
376
+ def forward(self, hidden_states, position_embeddings, past_key_value=None, use_cache=False, attention_mask=None):
377
+ residual = hidden_states
378
+ hidden_states, present_key_value = self.self_attn(
379
+ self.input_layernorm(hidden_states), position_embeddings,
380
+ past_key_value, use_cache, attention_mask
381
+ )
382
+ hidden_states += residual
383
+ hidden_states = hidden_states + self.mlp(self.post_attention_layernorm(hidden_states))
384
+ return hidden_states, present_key_value
385
+
386
+
387
+ class MiniMindModel(nn.Module):
388
+ def __init__(self, config: MiniMindConfig):
389
+ super().__init__()
390
+ self.config = config
391
+ self.vocab_size, self.num_hidden_layers = config.vocab_size, config.num_hidden_layers
392
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
393
+ self.dropout = nn.Dropout(config.dropout)
394
+ self.layers = nn.ModuleList([MiniMindBlock(l, config) for l in range(self.num_hidden_layers)])
395
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
396
+
397
+ freqs_cos, freqs_sin = precompute_freqs_cis(dim=config.hidden_size // config.num_attention_heads,
398
+ end=config.max_position_embeddings, rope_base=config.rope_theta,
399
+ rope_scaling=config.rope_scaling)
400
+ self.register_buffer("freqs_cos", freqs_cos, persistent=False)
401
+ self.register_buffer("freqs_sin", freqs_sin, persistent=False)
402
+
403
+ def forward(self,
404
+ input_ids: Optional[torch.Tensor] = None,
405
+ attention_mask: Optional[torch.Tensor] = None,
406
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
407
+ use_cache: bool = False,
408
+ **kwargs):
409
+ batch_size, seq_length = input_ids.shape
410
+ if hasattr(past_key_values, 'layers'): past_key_values = None
411
+ past_key_values = past_key_values or [None] * len(self.layers)
412
+ start_pos = past_key_values[0][0].shape[1] if past_key_values[0] is not None else 0
413
+
414
+ hidden_states = self.dropout(self.embed_tokens(input_ids))
415
+
416
+ position_embeddings = (
417
+ self.freqs_cos[start_pos:start_pos + seq_length],
418
+ self.freqs_sin[start_pos:start_pos + seq_length]
419
+ )
420
+
421
+ presents = []
422
+ for layer_idx, (layer, past_key_value) in enumerate(zip(self.layers, past_key_values)):
423
+ hidden_states, present = layer(
424
+ hidden_states,
425
+ position_embeddings,
426
+ past_key_value=past_key_value,
427
+ use_cache=use_cache,
428
+ attention_mask=attention_mask
429
+ )
430
+ presents.append(present)
431
+
432
+ hidden_states = self.norm(hidden_states)
433
+
434
+ aux_loss = sum(
435
+ layer.mlp.aux_loss
436
+ for layer in self.layers
437
+ if isinstance(layer.mlp, MOEFeedForward)
438
+ )
439
+
440
+ return hidden_states, presents, aux_loss
441
+
442
+
443
+ class MiniMindForCausalLM(PreTrainedModel, GenerationMixin):
444
+ config_class = MiniMindConfig
445
+
446
+ def __init__(self, config: MiniMindConfig = None):
447
+ self.config = config or MiniMindConfig()
448
+ super().__init__(self.config)
449
+ self.model = MiniMindModel(self.config)
450
+ self.lm_head = nn.Linear(self.config.hidden_size, self.config.vocab_size, bias=False)
451
+ self.model.embed_tokens.weight = self.lm_head.weight
452
+ self.OUT = CausalLMOutputWithPast()
453
+
454
+ def forward(self,
455
+ input_ids: Optional[torch.Tensor] = None,
456
+ attention_mask: Optional[torch.Tensor] = None,
457
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
458
+ use_cache: bool = False,
459
+ logits_to_keep: Union[int, torch.Tensor] = 0,
460
+ **args):
461
+ h, past_kvs, aux_loss = self.model(
462
+ input_ids=input_ids,
463
+ attention_mask=attention_mask,
464
+ past_key_values=past_key_values,
465
+ use_cache=use_cache,
466
+ **args
467
+ )
468
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
469
+ logits = self.lm_head(h[:, slice_indices, :])
470
+ self.OUT.__setitem__('last_hidden_state', h)
471
+ self.OUT.__setitem__('logits', logits)
472
+ self.OUT.__setitem__('aux_loss', aux_loss)
473
+ self.OUT.__setitem__('past_key_values', past_kvs)
474
+ return self.OUT