cullinangetter commited on
Commit
ab29c18
·
verified ·
1 Parent(s): 53ee5f9

Upload 9 files

Browse files
LMConfig.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+ from typing import List
3
+
4
+
5
+ class LMConfig(PretrainedConfig):
6
+ model_type = "minimind"
7
+
8
+ def __init__(
9
+ self,
10
+ dim: int = 512,
11
+ n_layers: int = 8,
12
+ n_heads: int = 8,
13
+ n_kv_heads: int = 2,
14
+ vocab_size: int = 6400,
15
+ hidden_dim: int = None,
16
+ multiple_of: int = 64,
17
+ norm_eps: float = 1e-5,
18
+ max_seq_len: int = 8192,
19
+ rope_theta: int = 1e6,
20
+ dropout: float = 0.0,
21
+ flash_attn: bool = True,
22
+ ####################################################
23
+ # Here are the specific configurations of MOE
24
+ # When use_moe is false, the following is invalid
25
+ ####################################################
26
+ use_moe: bool = False,
27
+ ####################################################
28
+ num_experts_per_tok: int = 2,
29
+ n_routed_experts: int = 4,
30
+ n_shared_experts: bool = True,
31
+ scoring_func: str = 'softmax',
32
+ aux_loss_alpha: float = 0.1,
33
+ seq_aux: bool = True,
34
+ norm_topk_prob: bool = True,
35
+ **kwargs,
36
+ ):
37
+ self.dim = dim
38
+ self.n_layers = n_layers
39
+ self.n_heads = n_heads
40
+ self.n_kv_heads = n_kv_heads
41
+ self.vocab_size = vocab_size
42
+ self.hidden_dim = hidden_dim
43
+ self.multiple_of = multiple_of
44
+ self.norm_eps = norm_eps
45
+ self.max_seq_len = max_seq_len
46
+ self.rope_theta = rope_theta
47
+ self.dropout = dropout
48
+ self.flash_attn = flash_attn
49
+ ####################################################
50
+ # Here are the specific configurations of MOE
51
+ # When use_moe is false, the following is invalid
52
+ ####################################################
53
+ self.use_moe = use_moe
54
+ self.num_experts_per_tok = num_experts_per_tok # 每个token选择的专家数量
55
+ self.n_routed_experts = n_routed_experts # 总的专家数量
56
+ self.n_shared_experts = n_shared_experts # 共享专家
57
+ self.scoring_func = scoring_func # 评分函数,默认为'softmax'
58
+ self.aux_loss_alpha = aux_loss_alpha # 辅助损失的alpha参数
59
+ self.seq_aux = seq_aux # 是否在序列级别上计算辅助损失
60
+ self.norm_topk_prob = norm_topk_prob # 是否标准化top-k概率
61
+ super().__init__(**kwargs)
README.md CHANGED
@@ -1,3 +1,199 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "../miniUSE-tw-v1",
3
+ "architectures": [
4
+ "MiniMindLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "LMConfig.LMConfig",
8
+ "AutoModelForCausalLM": "model.MiniMindLM"
9
+ },
10
+ "aux_loss_alpha": 0.1,
11
+ "dim": 768,
12
+ "dropout": 0.0,
13
+ "flash_attn": true,
14
+ "hidden_dim": 2048,
15
+ "max_seq_len": 8192,
16
+ "model_type": "minimind",
17
+ "multiple_of": 64,
18
+ "n_heads": 8,
19
+ "n_kv_heads": 2,
20
+ "n_layers": 16,
21
+ "n_routed_experts": 4,
22
+ "n_shared_experts": true,
23
+ "norm_eps": 1e-05,
24
+ "norm_topk_prob": true,
25
+ "num_experts_per_tok": 2,
26
+ "rope_theta": 1000000.0,
27
+ "scoring_func": "softmax",
28
+ "seq_aux": true,
29
+ "torch_dtype": "float32",
30
+ "transformers_version": "4.48.0",
31
+ "use_moe": false,
32
+ "vocab_size": 6400
33
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.48.0"
4
+ }
model.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import struct
3
+ import inspect
4
+ import time
5
+
6
+ from .LMConfig import LMConfig
7
+ from typing import Any, Optional, Tuple, List
8
+ import numpy as np
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from torch import nn
12
+ from transformers import PreTrainedModel
13
+ from transformers.modeling_outputs import CausalLMOutputWithPast
14
+
15
+
16
+ class RMSNorm(torch.nn.Module):
17
+ def __init__(self, dim: int, eps: float):
18
+ super().__init__()
19
+ self.eps = eps
20
+ self.weight = nn.Parameter(torch.ones(dim))
21
+
22
+ def forward(self, x):
23
+ return self.weight * (x.float() * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x)
24
+
25
+
26
+ def precompute_pos_cis(dim: int, end: int = int(32 * 1024), theta: float = 1e6):
27
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
28
+ t = torch.arange(end, device=freqs.device) # type: ignore
29
+ freqs = torch.outer(t, freqs).float() # type: ignore
30
+ pos_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
31
+ return pos_cis
32
+
33
+
34
+ def apply_rotary_emb(xq, xk, pos_cis):
35
+ def unite_shape(pos_cis, x):
36
+ ndim = x.ndim
37
+ assert 0 <= 1 < ndim
38
+ assert pos_cis.shape == (x.shape[1], x.shape[-1])
39
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
40
+ return pos_cis.view(*shape)
41
+
42
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
43
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
44
+ pos_cis = unite_shape(pos_cis, xq_)
45
+ xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
46
+ xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
47
+ return xq_out.type_as(xq), xk_out.type_as(xk)
48
+
49
+
50
+ def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
51
+ """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
52
+ bs, slen, n_kv_heads, head_dim = x.shape
53
+ if n_rep == 1:
54
+ return x
55
+ return (
56
+ x[:, :, :, None, :]
57
+ .expand(bs, slen, n_kv_heads, n_rep, head_dim)
58
+ .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
59
+ )
60
+
61
+
62
+ class Attention(nn.Module):
63
+ def __init__(self, args: LMConfig):
64
+ super().__init__()
65
+ self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
66
+ assert args.n_heads % self.n_kv_heads == 0
67
+ self.n_local_heads = args.n_heads
68
+ self.n_local_kv_heads = self.n_kv_heads
69
+ self.n_rep = self.n_local_heads // self.n_local_kv_heads
70
+ self.head_dim = args.dim // args.n_heads
71
+ self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
72
+ self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
73
+ self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
74
+ self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
75
+ self.attn_dropout = nn.Dropout(args.dropout)
76
+ self.resid_dropout = nn.Dropout(args.dropout)
77
+ self.dropout = args.dropout
78
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
79
+ # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
80
+ mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
81
+ mask = torch.triu(mask, diagonal=1)
82
+ self.register_buffer("mask", mask, persistent=False)
83
+
84
+ def forward(self,
85
+ x: torch.Tensor,
86
+ pos_cis: torch.Tensor,
87
+ past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
88
+ use_cache=False):
89
+ bsz, seq_len, _ = x.shape
90
+ xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
91
+ xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
92
+ xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
93
+ xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
94
+
95
+ xq, xk = apply_rotary_emb(xq, xk, pos_cis)
96
+ # kv_cache实现
97
+ if past_key_value is not None:
98
+ xk = torch.cat([past_key_value[0], xk], dim=1)
99
+ xv = torch.cat([past_key_value[1], xv], dim=1)
100
+ past_kv = (xk, xv) if use_cache else None
101
+
102
+ xq, xk, xv = (
103
+ xq.transpose(1, 2),
104
+ repeat_kv(xk, self.n_rep).transpose(1, 2),
105
+ repeat_kv(xv, self.n_rep).transpose(1, 2)
106
+ )
107
+ if self.flash and seq_len != 1:
108
+ dropout_p = self.dropout if self.training else 0.0
109
+ output = F.scaled_dot_product_attention(
110
+ xq, xk, xv,
111
+ attn_mask=None,
112
+ dropout_p=dropout_p,
113
+ is_causal=True
114
+ )
115
+ else:
116
+ scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
117
+ scores += self.mask[:, :, :seq_len, :seq_len]
118
+ scores = F.softmax(scores.float(), dim=-1).type_as(xq)
119
+ scores = self.attn_dropout(scores)
120
+ output = scores @ xv
121
+
122
+ output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
123
+ output = self.resid_dropout(self.wo(output))
124
+ return output, past_kv
125
+
126
+
127
+ class FeedForward(nn.Module):
128
+ def __init__(self, config: LMConfig):
129
+ super().__init__()
130
+ if config.hidden_dim is None:
131
+ hidden_dim = 4 * config.dim
132
+ hidden_dim = int(2 * hidden_dim / 3)
133
+ config.hidden_dim = config.multiple_of * ((hidden_dim + config.multiple_of - 1) // config.multiple_of)
134
+ self.w1 = nn.Linear(config.dim, config.hidden_dim, bias=False)
135
+ self.w2 = nn.Linear(config.hidden_dim, config.dim, bias=False)
136
+ self.w3 = nn.Linear(config.dim, config.hidden_dim, bias=False)
137
+ self.dropout = nn.Dropout(config.dropout)
138
+
139
+ def forward(self, x):
140
+ return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
141
+
142
+
143
+ class MoEGate(nn.Module):
144
+ def __init__(self, config: LMConfig):
145
+ super().__init__()
146
+ self.config = config
147
+ self.top_k = config.num_experts_per_tok
148
+ self.n_routed_experts = config.n_routed_experts
149
+
150
+ self.scoring_func = config.scoring_func
151
+ self.alpha = config.aux_loss_alpha
152
+ self.seq_aux = config.seq_aux
153
+
154
+ self.norm_topk_prob = config.norm_topk_prob
155
+ self.gating_dim = config.dim
156
+ self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
157
+ self.reset_parameters()
158
+
159
+ def reset_parameters(self) -> None:
160
+ import torch.nn.init as init
161
+ init.kaiming_uniform_(self.weight, a=math.sqrt(5))
162
+
163
+ def forward(self, hidden_states):
164
+ bsz, seq_len, h = hidden_states.shape
165
+ hidden_states = hidden_states.view(-1, h)
166
+ logits = F.linear(hidden_states, self.weight, None)
167
+ if self.scoring_func == 'softmax':
168
+ scores = logits.softmax(dim=-1)
169
+ else:
170
+ raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
171
+
172
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
173
+
174
+ if self.top_k > 1 and self.norm_topk_prob:
175
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
176
+ topk_weight = topk_weight / denominator
177
+
178
+ if self.training and self.alpha > 0.0:
179
+ scores_for_aux = scores
180
+ aux_topk = self.top_k
181
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
182
+ if self.seq_aux:
183
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
184
+ ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
185
+ ce.scatter_add_(1, topk_idx_for_aux_loss,
186
+ torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
187
+ seq_len * aux_topk / self.n_routed_experts)
188
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
189
+ else:
190
+ mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
191
+ ce = mask_ce.float().mean(0)
192
+ Pi = scores_for_aux.mean(0)
193
+ fi = ce * self.n_routed_experts
194
+ aux_loss = (Pi * fi).sum() * self.alpha
195
+ else:
196
+ aux_loss = 0
197
+ return topk_idx, topk_weight, aux_loss
198
+
199
+
200
+ class MOEFeedForward(nn.Module):
201
+ def __init__(self, config: LMConfig):
202
+ super().__init__()
203
+ self.config = config
204
+ self.experts = nn.ModuleList([
205
+ FeedForward(config)
206
+ for _ in range(config.n_routed_experts)
207
+ ])
208
+ self.gate = MoEGate(config)
209
+ if config.n_shared_experts is not None:
210
+ self.shared_experts = FeedForward(config)
211
+
212
+ def forward(self, x):
213
+ identity = x
214
+ orig_shape = x.shape
215
+ bsz, seq_len, _ = x.shape
216
+ # 使用门控机制选择专家
217
+ topk_idx, topk_weight, aux_loss = self.gate(x)
218
+ x = x.view(-1, x.shape[-1])
219
+ flat_topk_idx = topk_idx.view(-1)
220
+ if self.training:
221
+ # 训练模式下,重复输入数据
222
+ x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
223
+ y = torch.empty_like(x, dtype=torch.float16)
224
+ for i, expert in enumerate(self.experts):
225
+ y[flat_topk_idx == i] = expert(x[flat_topk_idx == i]).to(y.dtype) # 确保类型一致
226
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
227
+ y = y.view(*orig_shape)
228
+ else:
229
+ # 推理模式下,只选择最优专家
230
+ y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
231
+ if self.config.n_shared_experts is not None:
232
+ y = y + self.shared_experts(identity)
233
+ self.aux_loss = aux_loss
234
+ return y
235
+
236
+ @torch.no_grad()
237
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
238
+ expert_cache = torch.zeros_like(x)
239
+ idxs = flat_expert_indices.argsort()
240
+ tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
241
+ token_idxs = idxs // self.config.num_experts_per_tok
242
+ # 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
243
+ # 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
244
+ # 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
245
+ for i, end_idx in enumerate(tokens_per_expert):
246
+ start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
247
+ if start_idx == end_idx:
248
+ continue
249
+ expert = self.experts[i]
250
+ exp_token_idx = token_idxs[start_idx:end_idx]
251
+ expert_tokens = x[exp_token_idx]
252
+ expert_out = expert(expert_tokens).to(expert_cache.dtype)
253
+ expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
254
+ # 使用 scatter_add_ 进行 sum 操作
255
+ expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
256
+
257
+ return expert_cache
258
+
259
+
260
+ class MiniMindBlock(nn.Module):
261
+ def __init__(self, layer_id: int, config: LMConfig):
262
+ super().__init__()
263
+ self.n_heads = config.n_heads
264
+ self.dim = config.dim
265
+ self.head_dim = config.dim // config.n_heads
266
+ self.attention = Attention(config)
267
+
268
+ self.layer_id = layer_id
269
+ self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps)
270
+ self.ffn_norm = RMSNorm(config.dim, eps=config.norm_eps)
271
+ self.feed_forward = FeedForward(config) if not config.use_moe else MOEFeedForward(config)
272
+
273
+ def forward(self, x, pos_cis, past_key_value=None, use_cache=False):
274
+ h_attn, past_kv = self.attention(
275
+ self.attention_norm(x),
276
+ pos_cis,
277
+ past_key_value=past_key_value,
278
+ use_cache=use_cache
279
+ )
280
+ h = x + h_attn
281
+ out = h + self.feed_forward(self.ffn_norm(h))
282
+ return out, past_kv
283
+
284
+
285
+ class MiniMindLM(PreTrainedModel):
286
+ config_class = LMConfig
287
+
288
+ def __init__(self, params: LMConfig = None):
289
+ self.params = params or LMConfig()
290
+ super().__init__(self.params)
291
+ self.vocab_size, self.n_layers = params.vocab_size, params.n_layers
292
+ self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
293
+ self.dropout = nn.Dropout(params.dropout)
294
+ self.layers = nn.ModuleList([MiniMindBlock(l, params) for l in range(self.n_layers)])
295
+ self.norm = RMSNorm(params.dim, eps=params.norm_eps)
296
+ self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
297
+ self.tok_embeddings.weight = self.output.weight
298
+ self.register_buffer("pos_cis",
299
+ precompute_pos_cis(dim=params.dim // params.n_heads, theta=params.rope_theta),
300
+ persistent=False)
301
+ self.OUT = CausalLMOutputWithPast()
302
+
303
+ def forward(self,
304
+ input_ids: Optional[torch.Tensor] = None,
305
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
306
+ use_cache: bool = False,
307
+ **args):
308
+ past_key_values = past_key_values or [None] * len(self.layers)
309
+ start_pos = args.get('start_pos', 0)
310
+ h = self.dropout(self.tok_embeddings(input_ids))
311
+ pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)]
312
+ past_kvs = []
313
+ for l, layer in enumerate(self.layers):
314
+ h, past_kv = layer(
315
+ h, pos_cis,
316
+ past_key_value=past_key_values[l],
317
+ use_cache=use_cache
318
+ )
319
+ past_kvs.append(past_kv)
320
+ logits = self.output(self.norm(h))
321
+ aux_loss = sum(l.feed_forward.aux_loss for l in self.layers if isinstance(l.feed_forward, MOEFeedForward))
322
+ self.OUT.__setitem__('logits', logits)
323
+ self.OUT.__setitem__('aux_loss', aux_loss)
324
+ self.OUT.__setitem__('past_key_values', past_kvs)
325
+ return self.OUT
326
+
327
+ @torch.inference_mode()
328
+ def generate(self, input_ids, eos_token_id=2, max_new_tokens=1024, temperature=0.75, top_p=0.90,
329
+ stream=False, rp=1., use_cache=True, pad_token_id=0, **args):
330
+ # 流式生成
331
+ if stream:
332
+ return self._stream(input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args)
333
+
334
+ # 直接生成
335
+ generated = []
336
+ for i in range(input_ids.size(0)):
337
+ non_pad = input_ids[i][input_ids[i] != pad_token_id].unsqueeze(0)
338
+ out = self._stream(non_pad, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args)
339
+ tokens_list = [tokens[:, -1:] for tokens in out]
340
+ gen = torch.cat(tokens_list, dim=-1) if tokens_list else non_pad
341
+ full_sequence = torch.cat([non_pad, gen], dim=-1)
342
+ generated.append(full_sequence)
343
+ max_length = max(seq.size(1) for seq in generated)
344
+ generated = [
345
+ torch.cat(
346
+ [seq, torch.full((1, max_length - seq.size(1)), pad_token_id, dtype=seq.dtype, device=seq.device)],
347
+ dim=-1)
348
+ for seq in generated
349
+ ]
350
+ return torch.cat(generated, dim=0)
351
+
352
+ def _stream(self, input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args):
353
+ start, first_seq, past_kvs = input_ids.shape[1], True, None
354
+ while input_ids.shape[1] < max_new_tokens - 1:
355
+ if first_seq or not use_cache:
356
+ out, first_seq = self(input_ids, past_key_values=past_kvs, use_cache=use_cache, **args), False
357
+ else:
358
+ out = self(input_ids[:, -1:], past_key_values=past_kvs, use_cache=use_cache,
359
+ start_pos=input_ids.shape[1] - 1, **args)
360
+ logits, past_kvs = out.logits[:, -1, :], out.past_key_values
361
+ logits[:, list(set(input_ids.tolist()[0]))] /= rp
362
+ logits /= (temperature + 1e-9)
363
+ if top_p is not None and top_p < 1.0:
364
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
365
+ sorted_probs = F.softmax(sorted_logits, dim=-1)
366
+ cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
367
+ sorted_indices_to_remove = cumulative_probs > top_p
368
+ sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
369
+ sorted_indices_to_remove[:, 0] = False
370
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
371
+ logits[indices_to_remove] = -float('Inf')
372
+ input_ids_next = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
373
+ input_ids = torch.cat((input_ids, input_ids_next), dim=1)
374
+ yield input_ids[:, start:]
375
+ if input_ids_next.item() == eos_token_id:
376
+ break
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ca588c3fcd84ec0101d9c0e38a28ab2179792277c55597f63da2ae2b76e4144
3
+ size 529
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "pad_token": {
17
+ "content": "<unk>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_eos_token": false,
4
+ "add_prefix_space": false,
5
+ "added_tokens_decoder": {
6
+ "0": {
7
+ "content": "<unk>",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false,
12
+ "special": true
13
+ },
14
+ "1": {
15
+ "content": "<s>",
16
+ "lstrip": false,
17
+ "normalized": false,
18
+ "rstrip": false,
19
+ "single_word": false,
20
+ "special": true
21
+ },
22
+ "2": {
23
+ "content": "</s>",
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": "<s>",
33
+ "chat_template": "{% if messages[0]['role'] == 'system' %}{% set system_message = messages[0]['content'] %}{{ '<s>system\\n' + system_message + '</s>\\n' }}{% else %}{{ '<s>system\\n你是 MiniMind,是一个有用的人工智能助手。</s>\\n' }}{% endif %}{% for message in messages %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{{ '<s>user\\n' + content + '</s>\\n<s>assistant\\n' }}{% elif message['role'] == 'assistant' %}{{ content + '</s>' + '\\n' }}{% endif %}{% endfor %}",
34
+ "clean_up_tokenization_spaces": false,
35
+ "eos_token": "</s>",
36
+ "extra_special_tokens": {},
37
+ "legacy": true,
38
+ "model_max_length": 32768,
39
+ "pad_token": "<unk>",
40
+ "sp_model_kwargs": {},
41
+ "spaces_between_special_tokens": false,
42
+ "tokenizer_class": "PreTrainedTokenizerFast",
43
+ "unk_token": "<unk>"
44
+ }