SAINTHALF commited on
Commit
707e4a2
·
verified ·
1 Parent(s): 485d132

Upload folder using huggingface_hub

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