jingyaogong commited on
Commit
afe6a87
·
verified ·
1 Parent(s): 47738db

Upload 10 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)
VLMConfig.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .LMConfig import LMConfig
2
+ from typing import List
3
+
4
+
5
+ class VLMConfig(LMConfig):
6
+ model_type = "minimind-v"
7
+
8
+ def __init__(
9
+ self,
10
+ image_special_token: str = '@' * 196,
11
+ image_ids: List = [34] * 196,
12
+ **kwargs,
13
+ ):
14
+ self.image_special_token = image_special_token
15
+ self.image_ids = image_ids
16
+ super().__init__(**kwargs)
config.json ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MiniMindVLM"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "VLMConfig.VLMConfig",
7
+ "AutoModelForCausalLM": "model_vlm.MiniMindVLM"
8
+ },
9
+ "aux_loss_alpha": 0.1,
10
+ "dim": 768,
11
+ "dropout": 0.0,
12
+ "flash_attn": true,
13
+ "hidden_dim": 2048,
14
+ "image_ids": [
15
+ 34,
16
+ 34,
17
+ 34,
18
+ 34,
19
+ 34,
20
+ 34,
21
+ 34,
22
+ 34,
23
+ 34,
24
+ 34,
25
+ 34,
26
+ 34,
27
+ 34,
28
+ 34,
29
+ 34,
30
+ 34,
31
+ 34,
32
+ 34,
33
+ 34,
34
+ 34,
35
+ 34,
36
+ 34,
37
+ 34,
38
+ 34,
39
+ 34,
40
+ 34,
41
+ 34,
42
+ 34,
43
+ 34,
44
+ 34,
45
+ 34,
46
+ 34,
47
+ 34,
48
+ 34,
49
+ 34,
50
+ 34,
51
+ 34,
52
+ 34,
53
+ 34,
54
+ 34,
55
+ 34,
56
+ 34,
57
+ 34,
58
+ 34,
59
+ 34,
60
+ 34,
61
+ 34,
62
+ 34,
63
+ 34,
64
+ 34,
65
+ 34,
66
+ 34,
67
+ 34,
68
+ 34,
69
+ 34,
70
+ 34,
71
+ 34,
72
+ 34,
73
+ 34,
74
+ 34,
75
+ 34,
76
+ 34,
77
+ 34,
78
+ 34,
79
+ 34,
80
+ 34,
81
+ 34,
82
+ 34,
83
+ 34,
84
+ 34,
85
+ 34,
86
+ 34,
87
+ 34,
88
+ 34,
89
+ 34,
90
+ 34,
91
+ 34,
92
+ 34,
93
+ 34,
94
+ 34,
95
+ 34,
96
+ 34,
97
+ 34,
98
+ 34,
99
+ 34,
100
+ 34,
101
+ 34,
102
+ 34,
103
+ 34,
104
+ 34,
105
+ 34,
106
+ 34,
107
+ 34,
108
+ 34,
109
+ 34,
110
+ 34,
111
+ 34,
112
+ 34,
113
+ 34,
114
+ 34,
115
+ 34,
116
+ 34,
117
+ 34,
118
+ 34,
119
+ 34,
120
+ 34,
121
+ 34,
122
+ 34,
123
+ 34,
124
+ 34,
125
+ 34,
126
+ 34,
127
+ 34,
128
+ 34,
129
+ 34,
130
+ 34,
131
+ 34,
132
+ 34,
133
+ 34,
134
+ 34,
135
+ 34,
136
+ 34,
137
+ 34,
138
+ 34,
139
+ 34,
140
+ 34,
141
+ 34,
142
+ 34,
143
+ 34,
144
+ 34,
145
+ 34,
146
+ 34,
147
+ 34,
148
+ 34,
149
+ 34,
150
+ 34,
151
+ 34,
152
+ 34,
153
+ 34,
154
+ 34,
155
+ 34,
156
+ 34,
157
+ 34,
158
+ 34,
159
+ 34,
160
+ 34,
161
+ 34,
162
+ 34,
163
+ 34,
164
+ 34,
165
+ 34,
166
+ 34,
167
+ 34,
168
+ 34,
169
+ 34,
170
+ 34,
171
+ 34,
172
+ 34,
173
+ 34,
174
+ 34,
175
+ 34,
176
+ 34,
177
+ 34,
178
+ 34,
179
+ 34,
180
+ 34,
181
+ 34,
182
+ 34,
183
+ 34,
184
+ 34,
185
+ 34,
186
+ 34,
187
+ 34,
188
+ 34,
189
+ 34,
190
+ 34,
191
+ 34,
192
+ 34,
193
+ 34,
194
+ 34,
195
+ 34,
196
+ 34,
197
+ 34,
198
+ 34,
199
+ 34,
200
+ 34,
201
+ 34,
202
+ 34,
203
+ 34,
204
+ 34,
205
+ 34,
206
+ 34,
207
+ 34,
208
+ 34,
209
+ 34,
210
+ 34
211
+ ],
212
+ "image_special_token": "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@",
213
+ "max_seq_len": 8192,
214
+ "model_type": "minimind-v",
215
+ "multiple_of": 64,
216
+ "n_heads": 8,
217
+ "n_kv_heads": 2,
218
+ "n_layers": 16,
219
+ "n_routed_experts": 4,
220
+ "n_shared_experts": true,
221
+ "norm_eps": 1e-05,
222
+ "norm_topk_prob": true,
223
+ "num_experts_per_tok": 2,
224
+ "rope_theta": 1000000.0,
225
+ "scoring_func": "softmax",
226
+ "seq_aux": true,
227
+ "torch_dtype": "float32",
228
+ "transformers_version": "4.48.3",
229
+ "use_moe": false,
230
+ "vocab_size": 6400
231
+ }
generation_config.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "transformers_version": "4.48.3"
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
model_vlm.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .VLMConfig import VLMConfig
2
+ from .model import *
3
+ from typing import Optional, Tuple, List
4
+ from torch import nn
5
+ import warnings
6
+ from transformers import CLIPProcessor, CLIPModel
7
+ import torch
8
+
9
+ warnings.filterwarnings('ignore')
10
+
11
+
12
+ class VisionProj(nn.Module):
13
+ def __init__(self, ve_dim=768, lm_dim=512):
14
+ super().__init__()
15
+ self.ve_dim = ve_dim
16
+ self.lm_dim = lm_dim
17
+ self.vision_proj = nn.Sequential(
18
+ nn.Linear(self.ve_dim, self.lm_dim)
19
+ )
20
+
21
+ def forward(self, image_encoders):
22
+ vision_proj = self.vision_proj(image_encoders)
23
+ return vision_proj
24
+
25
+
26
+ # 继承自语言模型
27
+ class MiniMindVLM(MiniMindLM):
28
+ config_class = VLMConfig
29
+
30
+ def __init__(self, params: VLMConfig = None):
31
+ super().__init__(params)
32
+ if not params: params = VLMConfig()
33
+ self.params = params
34
+ self.vision_encoder, self.processor = self.__class__.get_vision_model()
35
+ self.vision_proj = VisionProj(lm_dim=params.dim)
36
+
37
+ @staticmethod
38
+ def get_vision_model(model_path="./model/vision_model/clip-vit-base-patch16"):
39
+ model = CLIPModel.from_pretrained(model_path)
40
+ processor = CLIPProcessor.from_pretrained(model_path)
41
+ # 冻结 vision_encoder 的所有参数
42
+ for param in model.parameters():
43
+ param.requires_grad = False
44
+ return model.eval(), processor
45
+
46
+ @staticmethod
47
+ def image2tensor(image, processor):
48
+ if image.mode in ['RGBA', 'LA']: image = image.convert('RGB')
49
+ inputs = processor(images=image, return_tensors="pt")['pixel_values']
50
+ return inputs
51
+
52
+ @staticmethod
53
+ def get_image_embeddings(image_tensors, vision_model):
54
+ with torch.no_grad():
55
+ outputs = vision_model.vision_model(pixel_values=image_tensors)
56
+ img_embedding = outputs.last_hidden_state[:, 1:, :].squeeze()
57
+ return img_embedding
58
+
59
+ def count_vision_proj(self, tokens, h, vision_tensors=None, seqlen=512):
60
+ def find_indices(tokens, image_ids):
61
+ image_ids_tensor = torch.tensor(image_ids).to(tokens.device)
62
+ len_image_ids = len(image_ids)
63
+ if len_image_ids > tokens.size(1):
64
+ return None
65
+ tokens_view = tokens.unfold(1, len_image_ids, 1)
66
+ matches = (tokens_view == image_ids_tensor).all(dim=2)
67
+ return {
68
+ batch_idx: [(idx.item(), idx.item() + len_image_ids - 1) for idx in
69
+ matches[batch_idx].nonzero(as_tuple=True)[0]]
70
+ for batch_idx in range(tokens.size(0)) if matches[batch_idx].any()
71
+ } or None
72
+
73
+ image_indices = find_indices(tokens, self.params.image_ids)
74
+ if vision_tensors is not None and image_indices:
75
+ vision_proj = self.vision_proj(vision_tensors)
76
+ if len(vision_proj.shape) == 3:
77
+ vision_proj = vision_proj.unsqueeze(1)
78
+ new_h = []
79
+ for i in range(h.size(0)):
80
+ if i in image_indices:
81
+ h_i = h[i]
82
+ img_idx = 0
83
+ for start_idx, end_idx in image_indices[i]:
84
+ if img_idx < vision_proj.size(1):
85
+ h_i = torch.cat((h_i[:start_idx], vision_proj[i][img_idx], h_i[end_idx + 1:]), dim=0)[
86
+ :seqlen]
87
+ img_idx += 1
88
+ new_h.append(h_i)
89
+ else:
90
+ new_h.append(h[i])
91
+ return torch.stack(new_h, dim=0)
92
+ return h
93
+
94
+ def forward(self,
95
+ input_ids: Optional[torch.Tensor] = None,
96
+ past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
97
+ use_cache: bool = False,
98
+ **args):
99
+ start_pos = args.get('start_pos', 0)
100
+ pixel_tensors = args.get('pixel_tensors', None)
101
+ h = self.tok_embeddings(input_ids)
102
+
103
+ if pixel_tensors is not None and start_pos == 0:
104
+ if len(pixel_tensors.shape) == 6:
105
+ pixel_tensors = pixel_tensors.squeeze(2)
106
+ bs, num, c, im_h, im_w = pixel_tensors.shape
107
+ stack_dim = 1 if bs > 1 else 0
108
+ vision_tensors = torch.stack([
109
+ MiniMindVLM.get_image_embeddings(pixel_tensors[:, i, :, :, :], self.vision_encoder)
110
+ for i in range(num)
111
+ ], dim=stack_dim)
112
+ h = self.count_vision_proj(tokens=input_ids, h=h, vision_tensors=vision_tensors, seqlen=input_ids.shape[1])
113
+
114
+ pos_cis = self.pos_cis[start_pos:start_pos + input_ids.shape[1]]
115
+ past_kvs = []
116
+ for l, layer in enumerate(self.layers):
117
+ h, past_kv = layer(
118
+ h, pos_cis,
119
+ past_key_value=past_key_values[l] if past_key_values else None,
120
+ use_cache=use_cache
121
+ )
122
+ past_kvs.append(past_kv)
123
+
124
+ logits = self.output(self.norm(h))
125
+ aux_loss = sum(l.feed_forward.aux_loss for l in self.layers if isinstance(l.feed_forward, MOEFeedForward))
126
+
127
+ self.OUT.__setitem__('logits', logits)
128
+ self.OUT.__setitem__('aux_loss', aux_loss)
129
+ self.OUT.__setitem__('past_key_values', past_kvs)
130
+ return self.OUT
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a088d398875eee778df0afe39d0e134ceaa6dbdac1ce5a4b3d44350fb976ba83
3
+ size 418532954
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
+ }