Spaces:
Running
Running
Commit
·
a90a5a4
1
Parent(s):
a551d94
update space
Browse files- MiniMind2-R1/LMConfig.py +61 -0
- MiniMind2-R1/config.json +32 -0
- MiniMind2-R1/generation_config.json +4 -0
- MiniMind2-R1/model.py +375 -0
- MiniMind2-R1/pytorch_model.bin +3 -0
- MiniMind2-R1/special_tokens_map.json +30 -0
- MiniMind2-R1/tokenizer.json +0 -0
- MiniMind2-R1/tokenizer_config.json +43 -0
- MiniMind2/LMConfig.py +61 -0
- MiniMind2/config.json +32 -0
- MiniMind2/generation_config.json +4 -0
- MiniMind2/model.py +375 -0
- MiniMind2/pytorch_model.bin +3 -0
- MiniMind2/special_tokens_map.json +30 -0
- MiniMind2/tokenizer.json +0 -0
- MiniMind2/tokenizer_config.json +44 -0
- app.py +288 -0
MiniMind2-R1/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)
|
MiniMind2-R1/config.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"MiniMindLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "LMConfig.LMConfig",
|
7 |
+
"AutoModelForCausalLM": "model.MiniMindLM"
|
8 |
+
},
|
9 |
+
"aux_loss_alpha": 0.1,
|
10 |
+
"dim": 768,
|
11 |
+
"dropout": 0.0,
|
12 |
+
"flash_attn": true,
|
13 |
+
"hidden_dim": 2048,
|
14 |
+
"max_seq_len": 8192,
|
15 |
+
"model_type": "minimind",
|
16 |
+
"multiple_of": 64,
|
17 |
+
"n_heads": 8,
|
18 |
+
"n_kv_heads": 2,
|
19 |
+
"n_layers": 16,
|
20 |
+
"n_routed_experts": 4,
|
21 |
+
"n_shared_experts": true,
|
22 |
+
"norm_eps": 1e-05,
|
23 |
+
"norm_topk_prob": true,
|
24 |
+
"num_experts_per_tok": 2,
|
25 |
+
"rope_theta": 1000000.0,
|
26 |
+
"scoring_func": "softmax",
|
27 |
+
"seq_aux": true,
|
28 |
+
"torch_dtype": "float32",
|
29 |
+
"transformers_version": "4.44.0",
|
30 |
+
"use_moe": false,
|
31 |
+
"vocab_size": 6400
|
32 |
+
}
|
MiniMind2-R1/generation_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"transformers_version": "4.44.0"
|
4 |
+
}
|
MiniMind2-R1/model.py
ADDED
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, theta: float = 1e4):
|
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", precompute_pos_cis(params.dim // params.n_heads, params.max_seq_len,
|
299 |
+
theta=params.rope_theta), persistent=False)
|
300 |
+
self.OUT = CausalLMOutputWithPast()
|
301 |
+
|
302 |
+
def forward(self,
|
303 |
+
input_ids: Optional[torch.Tensor] = None,
|
304 |
+
past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
|
305 |
+
use_cache: bool = False,
|
306 |
+
**args):
|
307 |
+
past_key_values = past_key_values or [None] * len(self.layers)
|
308 |
+
start_pos = args.get('start_pos', 0)
|
309 |
+
h = self.dropout(self.tok_embeddings(input_ids))
|
310 |
+
pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)]
|
311 |
+
past_kvs = []
|
312 |
+
for l, layer in enumerate(self.layers):
|
313 |
+
h, past_kv = layer(
|
314 |
+
h, pos_cis,
|
315 |
+
past_key_value=past_key_values[l],
|
316 |
+
use_cache=use_cache
|
317 |
+
)
|
318 |
+
past_kvs.append(past_kv)
|
319 |
+
logits = self.output(self.norm(h))
|
320 |
+
aux_loss = sum(l.feed_forward.aux_loss for l in self.layers if isinstance(l.feed_forward, MOEFeedForward))
|
321 |
+
self.OUT.__setitem__('logits', logits)
|
322 |
+
self.OUT.__setitem__('aux_loss', aux_loss)
|
323 |
+
self.OUT.__setitem__('past_key_values', past_kvs)
|
324 |
+
return self.OUT
|
325 |
+
|
326 |
+
@torch.inference_mode()
|
327 |
+
def generate(self, input_ids, eos_token_id=2, max_new_tokens=1024, temperature=0.75, top_p=0.90,
|
328 |
+
stream=False, rp=1., use_cache=True, pad_token_id=0, **args):
|
329 |
+
# 流式生成
|
330 |
+
if stream:
|
331 |
+
return self._generate_stream(input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache)
|
332 |
+
|
333 |
+
# 直接生成
|
334 |
+
generated = []
|
335 |
+
for i in range(input_ids.size(0)):
|
336 |
+
non_pad = input_ids[i][input_ids[i] != pad_token_id].unsqueeze(0)
|
337 |
+
out = self._generate_stream(non_pad, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache)
|
338 |
+
tokens_list = [tokens[:, -1:] for tokens in out]
|
339 |
+
gen = torch.cat(tokens_list, dim=-1) if tokens_list else non_pad
|
340 |
+
full_sequence = torch.cat([non_pad, gen], dim=-1)
|
341 |
+
generated.append(full_sequence)
|
342 |
+
max_length = max(seq.size(1) for seq in generated)
|
343 |
+
generated = [
|
344 |
+
torch.cat(
|
345 |
+
[seq, torch.full((1, max_length - seq.size(1)), pad_token_id, dtype=seq.dtype, device=seq.device)],
|
346 |
+
dim=-1)
|
347 |
+
for seq in generated
|
348 |
+
]
|
349 |
+
return torch.cat(generated, dim=0)
|
350 |
+
|
351 |
+
def _generate_stream(self, input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args):
|
352 |
+
start, first_seq, past_kvs = input_ids.shape[1], True, None
|
353 |
+
while input_ids.shape[1] < max_new_tokens - 1:
|
354 |
+
if first_seq or not use_cache:
|
355 |
+
out, first_seq = self(input_ids, past_key_values=past_kvs, use_cache=use_cache), False
|
356 |
+
else:
|
357 |
+
out = self(input_ids[:, -1:], past_key_values=past_kvs, use_cache=use_cache,
|
358 |
+
start_pos=input_ids.shape[1] - 1)
|
359 |
+
logits, past_kvs = out.logits[:, -1, :], out.past_key_values
|
360 |
+
logits[:, list(set(input_ids.tolist()[0]))] /= rp
|
361 |
+
logits /= (temperature + 1e-9)
|
362 |
+
if top_p is not None and top_p < 1.0:
|
363 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
364 |
+
sorted_probs = F.softmax(sorted_logits, dim=-1)
|
365 |
+
cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
|
366 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
367 |
+
sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
|
368 |
+
sorted_indices_to_remove[:, 0] = False
|
369 |
+
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
370 |
+
logits[indices_to_remove] = -float('Inf')
|
371 |
+
input_ids_next = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
|
372 |
+
input_ids = torch.cat((input_ids, input_ids_next), dim=1)
|
373 |
+
yield input_ids[:, start:]
|
374 |
+
if input_ids_next.item() == eos_token_id:
|
375 |
+
break
|
MiniMind2-R1/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a6023c329a68fab023195a61d53bb0d642eedba94a5f70ee24d139204e127351
|
3 |
+
size 416170002
|
MiniMind2-R1/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 |
+
}
|
MiniMind2-R1/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
MiniMind2-R1/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": "<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 |
+
"legacy": true,
|
37 |
+
"model_max_length": 32768,
|
38 |
+
"pad_token": "<unk>",
|
39 |
+
"sp_model_kwargs": {},
|
40 |
+
"spaces_between_special_tokens": false,
|
41 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
42 |
+
"unk_token": "<unk>"
|
43 |
+
}
|
MiniMind2/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)
|
MiniMind2/config.json
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"MiniMindLM"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "LMConfig.LMConfig",
|
7 |
+
"AutoModelForCausalLM": "model.MiniMindLM"
|
8 |
+
},
|
9 |
+
"aux_loss_alpha": 0.1,
|
10 |
+
"dim": 768,
|
11 |
+
"dropout": 0.0,
|
12 |
+
"flash_attn": true,
|
13 |
+
"hidden_dim": 2048,
|
14 |
+
"max_seq_len": 8192,
|
15 |
+
"model_type": "minimind",
|
16 |
+
"multiple_of": 64,
|
17 |
+
"n_heads": 8,
|
18 |
+
"n_kv_heads": 2,
|
19 |
+
"n_layers": 16,
|
20 |
+
"n_routed_experts": 4,
|
21 |
+
"n_shared_experts": true,
|
22 |
+
"norm_eps": 1e-05,
|
23 |
+
"norm_topk_prob": true,
|
24 |
+
"num_experts_per_tok": 2,
|
25 |
+
"rope_theta": 1000000.0,
|
26 |
+
"scoring_func": "softmax",
|
27 |
+
"seq_aux": true,
|
28 |
+
"torch_dtype": "float32",
|
29 |
+
"transformers_version": "4.47.1",
|
30 |
+
"use_moe": false,
|
31 |
+
"vocab_size": 6400
|
32 |
+
}
|
MiniMind2/generation_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_from_model_config": true,
|
3 |
+
"transformers_version": "4.47.1"
|
4 |
+
}
|
MiniMind2/model.py
ADDED
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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, theta: float = 1e4):
|
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", precompute_pos_cis(params.dim // params.n_heads, params.max_seq_len,
|
299 |
+
theta=params.rope_theta), persistent=False)
|
300 |
+
self.OUT = CausalLMOutputWithPast()
|
301 |
+
|
302 |
+
def forward(self,
|
303 |
+
input_ids: Optional[torch.Tensor] = None,
|
304 |
+
past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
|
305 |
+
use_cache: bool = False,
|
306 |
+
**args):
|
307 |
+
past_key_values = past_key_values or [None] * len(self.layers)
|
308 |
+
start_pos = args.get('start_pos', 0)
|
309 |
+
h = self.dropout(self.tok_embeddings(input_ids))
|
310 |
+
pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)]
|
311 |
+
past_kvs = []
|
312 |
+
for l, layer in enumerate(self.layers):
|
313 |
+
h, past_kv = layer(
|
314 |
+
h, pos_cis,
|
315 |
+
past_key_value=past_key_values[l],
|
316 |
+
use_cache=use_cache
|
317 |
+
)
|
318 |
+
past_kvs.append(past_kv)
|
319 |
+
logits = self.output(self.norm(h))
|
320 |
+
aux_loss = sum(l.feed_forward.aux_loss for l in self.layers if isinstance(l.feed_forward, MOEFeedForward))
|
321 |
+
self.OUT.__setitem__('logits', logits)
|
322 |
+
self.OUT.__setitem__('aux_loss', aux_loss)
|
323 |
+
self.OUT.__setitem__('past_key_values', past_kvs)
|
324 |
+
return self.OUT
|
325 |
+
|
326 |
+
@torch.inference_mode()
|
327 |
+
def generate(self, input_ids, eos_token_id=2, max_new_tokens=1024, temperature=0.75, top_p=0.90,
|
328 |
+
stream=False, rp=1., use_cache=True, pad_token_id=0, **args):
|
329 |
+
# 流式生成
|
330 |
+
if stream:
|
331 |
+
return self._generate_stream(input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache)
|
332 |
+
|
333 |
+
# 直接生成
|
334 |
+
generated = []
|
335 |
+
for i in range(input_ids.size(0)):
|
336 |
+
non_pad = input_ids[i][input_ids[i] != pad_token_id].unsqueeze(0)
|
337 |
+
out = self._generate_stream(non_pad, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache)
|
338 |
+
tokens_list = [tokens[:, -1:] for tokens in out]
|
339 |
+
gen = torch.cat(tokens_list, dim=-1) if tokens_list else non_pad
|
340 |
+
full_sequence = torch.cat([non_pad, gen], dim=-1)
|
341 |
+
generated.append(full_sequence)
|
342 |
+
max_length = max(seq.size(1) for seq in generated)
|
343 |
+
generated = [
|
344 |
+
torch.cat(
|
345 |
+
[seq, torch.full((1, max_length - seq.size(1)), pad_token_id, dtype=seq.dtype, device=seq.device)],
|
346 |
+
dim=-1)
|
347 |
+
for seq in generated
|
348 |
+
]
|
349 |
+
return torch.cat(generated, dim=0)
|
350 |
+
|
351 |
+
def _generate_stream(self, input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args):
|
352 |
+
start, first_seq, past_kvs = input_ids.shape[1], True, None
|
353 |
+
while input_ids.shape[1] < max_new_tokens - 1:
|
354 |
+
if first_seq or not use_cache:
|
355 |
+
out, first_seq = self(input_ids, past_key_values=past_kvs, use_cache=use_cache), False
|
356 |
+
else:
|
357 |
+
out = self(input_ids[:, -1:], past_key_values=past_kvs, use_cache=use_cache,
|
358 |
+
start_pos=input_ids.shape[1] - 1)
|
359 |
+
logits, past_kvs = out.logits[:, -1, :], out.past_key_values
|
360 |
+
logits[:, list(set(input_ids.tolist()[0]))] /= rp
|
361 |
+
logits /= (temperature + 1e-9)
|
362 |
+
if top_p is not None and top_p < 1.0:
|
363 |
+
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
364 |
+
sorted_probs = F.softmax(sorted_logits, dim=-1)
|
365 |
+
cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
|
366 |
+
sorted_indices_to_remove = cumulative_probs > top_p
|
367 |
+
sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
|
368 |
+
sorted_indices_to_remove[:, 0] = False
|
369 |
+
indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
|
370 |
+
logits[indices_to_remove] = -float('Inf')
|
371 |
+
input_ids_next = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
|
372 |
+
input_ids = torch.cat((input_ids, input_ids_next), dim=1)
|
373 |
+
yield input_ids[:, start:]
|
374 |
+
if input_ids_next.item() == eos_token_id:
|
375 |
+
break
|
MiniMind2/pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ec3524299d4353b30a999f74c7cdb3c0f7e5d137a1565dbd716150bbb374db79
|
3 |
+
size 416170002
|
MiniMind2/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 |
+
}
|
MiniMind2/tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
MiniMind2/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 |
+
}
|
app.py
ADDED
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
import re
|
3 |
+
import time
|
4 |
+
|
5 |
+
import numpy as np
|
6 |
+
import streamlit as st
|
7 |
+
import torch
|
8 |
+
|
9 |
+
st.set_page_config(page_title="MiniMind", initial_sidebar_state="collapsed")
|
10 |
+
|
11 |
+
# 在文件开头的 CSS 样式中修改按钮样式
|
12 |
+
st.markdown("""
|
13 |
+
<style>
|
14 |
+
/* 添加操作按钮样式 */
|
15 |
+
.stButton button {
|
16 |
+
border-radius: 50% !important; /* 改为圆形 */
|
17 |
+
width: 32px !important; /* 固定宽度 */
|
18 |
+
height: 32px !important; /* 固定高度 */
|
19 |
+
padding: 0 !important; /* 移除内边距 */
|
20 |
+
background-color: transparent !important;
|
21 |
+
border: 1px solid #ddd !important;
|
22 |
+
display: flex !important;
|
23 |
+
align-items: center !important;
|
24 |
+
justify-content: center !important;
|
25 |
+
font-size: 14px !important;
|
26 |
+
color: #666 !important; /* 更柔和的颜色 */
|
27 |
+
margin: 5px 10px 5px 0 !important; /* 调整按钮间距 */
|
28 |
+
}
|
29 |
+
.stButton button:hover {
|
30 |
+
border-color: #999 !important;
|
31 |
+
color: #333 !important;
|
32 |
+
background-color: #f5f5f5 !important;
|
33 |
+
}
|
34 |
+
.stMainBlockContainer > div:first-child {
|
35 |
+
margin-top: -50px !important;
|
36 |
+
}
|
37 |
+
.stApp > div:last-child {
|
38 |
+
margin-bottom: -35px !important;
|
39 |
+
}
|
40 |
+
|
41 |
+
/* 重置按钮基础样式 */
|
42 |
+
.stButton > button {
|
43 |
+
all: unset !important; /* 重置所有默认样式 */
|
44 |
+
box-sizing: border-box !important;
|
45 |
+
border-radius: 50% !important;
|
46 |
+
width: 18px !important;
|
47 |
+
height: 18px !important;
|
48 |
+
min-width: 18px !important;
|
49 |
+
min-height: 18px !important;
|
50 |
+
max-width: 18px !important;
|
51 |
+
max-height: 18px !important;
|
52 |
+
padding: 0 !important;
|
53 |
+
background-color: transparent !important;
|
54 |
+
border: 1px solid #ddd !important;
|
55 |
+
display: flex !important;
|
56 |
+
align-items: center !important;
|
57 |
+
justify-content: center !important;
|
58 |
+
font-size: 14px !important;
|
59 |
+
color: #888 !important;
|
60 |
+
cursor: pointer !important;
|
61 |
+
transition: all 0.2s ease !important;
|
62 |
+
margin: 0 2px !important; /* 调整这里的 margin 值 */
|
63 |
+
}
|
64 |
+
|
65 |
+
</style>
|
66 |
+
""", unsafe_allow_html=True)
|
67 |
+
|
68 |
+
system_prompt = []
|
69 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
70 |
+
|
71 |
+
|
72 |
+
def process_assistant_content(content):
|
73 |
+
if 'R1' not in MODEL_PATHS[selected_model][1]:
|
74 |
+
return content
|
75 |
+
|
76 |
+
if '<think>' in content and '</think>' in content:
|
77 |
+
content = re.sub(r'(<think>)(.*?)(</think>)',
|
78 |
+
r'<details style="font-style: italic; background: rgba(222, 222, 222, 0.5); padding: 10px; border-radius: 10px;"><summary style="font-weight:bold;">推理内容(展开)</summary>\2</details>',
|
79 |
+
content,
|
80 |
+
flags=re.DOTALL)
|
81 |
+
|
82 |
+
if '<think>' in content and '</think>' not in content:
|
83 |
+
content = re.sub(r'<think>(.*?)$',
|
84 |
+
r'<details open style="font-style: italic; background: rgba(222, 222, 222, 0.5); padding: 10px; border-radius: 10px;"><summary style="font-weight:bold;">推理中...</summary>\1</details>',
|
85 |
+
content,
|
86 |
+
flags=re.DOTALL)
|
87 |
+
|
88 |
+
if '<think>' not in content and '</think>' in content:
|
89 |
+
content = re.sub(r'(.*?)</think>',
|
90 |
+
r'<details style="font-style: italic; background: rgba(222, 222, 222, 0.5); padding: 10px; border-radius: 10px;"><summary style="font-weight:bold;">推理内容(展开)</summary>\1</details>',
|
91 |
+
content,
|
92 |
+
flags=re.DOTALL)
|
93 |
+
|
94 |
+
return content
|
95 |
+
|
96 |
+
|
97 |
+
@st.cache_resource
|
98 |
+
def load_model_tokenizer(model_path):
|
99 |
+
model = AutoModelForCausalLM.from_pretrained(
|
100 |
+
model_path,
|
101 |
+
trust_remote_code=True
|
102 |
+
)
|
103 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
104 |
+
model_path,
|
105 |
+
use_fast=False,
|
106 |
+
trust_remote_code=True
|
107 |
+
)
|
108 |
+
model = model.eval().to(device)
|
109 |
+
return model, tokenizer
|
110 |
+
|
111 |
+
|
112 |
+
def clear_chat_messages():
|
113 |
+
del st.session_state.messages
|
114 |
+
del st.session_state.chat_messages
|
115 |
+
|
116 |
+
|
117 |
+
def init_chat_messages():
|
118 |
+
if "messages" in st.session_state:
|
119 |
+
for i, message in enumerate(st.session_state.messages):
|
120 |
+
if message["role"] == "assistant":
|
121 |
+
with st.chat_message("assistant", avatar=image_url):
|
122 |
+
st.markdown(process_assistant_content(message["content"]), unsafe_allow_html=True)
|
123 |
+
# 在消息内容下方添加按钮
|
124 |
+
if st.button("🗑", key=f"delete_{i}"):
|
125 |
+
st.session_state.messages.pop(i)
|
126 |
+
st.session_state.messages.pop(i - 1)
|
127 |
+
st.session_state.chat_messages.pop(i)
|
128 |
+
st.session_state.chat_messages.pop(i - 1)
|
129 |
+
st.rerun()
|
130 |
+
else:
|
131 |
+
st.markdown(
|
132 |
+
f'<div style="display: flex; justify-content: flex-end;"><div style="display: inline-block; margin: 10px 0; padding: 8px 12px 8px 12px; background-color: #ddd; border-radius: 10px; color: black;">{message["content"]}</div></div>',
|
133 |
+
unsafe_allow_html=True)
|
134 |
+
|
135 |
+
else:
|
136 |
+
st.session_state.messages = []
|
137 |
+
st.session_state.chat_messages = []
|
138 |
+
|
139 |
+
return st.session_state.messages
|
140 |
+
|
141 |
+
|
142 |
+
# 添加这两个辅助函数
|
143 |
+
def regenerate_answer(index):
|
144 |
+
st.session_state.messages.pop()
|
145 |
+
st.session_state.chat_messages.pop()
|
146 |
+
st.rerun()
|
147 |
+
|
148 |
+
|
149 |
+
def delete_conversation(index):
|
150 |
+
st.session_state.messages.pop(index)
|
151 |
+
st.session_state.messages.pop(index - 1)
|
152 |
+
st.session_state.chat_messages.pop(index)
|
153 |
+
st.session_state.chat_messages.pop(index - 1)
|
154 |
+
st.rerun()
|
155 |
+
|
156 |
+
|
157 |
+
# 侧边栏模型选择
|
158 |
+
st.sidebar.title("模型设定调整")
|
159 |
+
|
160 |
+
st.sidebar.text("【注】训练数据偏差,增加上下文记忆时\n多轮对话(较单轮)容易出现能力衰减")
|
161 |
+
st.session_state.history_chat_num = st.sidebar.slider("Number of Historical Dialogues", 0, 6, 0, step=2)
|
162 |
+
# st.session_state.history_chat_num = 0
|
163 |
+
st.session_state.max_new_tokens = st.sidebar.slider("Max Sequence Length", 256, 8192, 8192, step=1)
|
164 |
+
st.session_state.top_p = st.sidebar.slider("Top-P", 0.8, 0.99, 0.85, step=0.01)
|
165 |
+
st.session_state.temperature = st.sidebar.slider("Temperature", 0.6, 1.2, 0.85, step=0.01)
|
166 |
+
|
167 |
+
# 模型路径映射
|
168 |
+
MODEL_PATHS = {
|
169 |
+
"MiniMind2-R1 (0.1B)": ["./MiniMind2-R1", "MiniMind2-R1"],
|
170 |
+
"MiniMind2 (0.1B)": ["./MiniMind2", "MiniMind2"],
|
171 |
+
}
|
172 |
+
|
173 |
+
selected_model = st.sidebar.selectbox('Models', list(MODEL_PATHS.keys()), index=0) # 默认选择 MiniMind2
|
174 |
+
model_path = MODEL_PATHS[selected_model][0]
|
175 |
+
|
176 |
+
slogan = f"Hi, I'm {MODEL_PATHS[selected_model][1]}"
|
177 |
+
|
178 |
+
image_url = "https://www.modelscope.cn/api/v1/studio/gongjy/MiniMind/repo?Revision=master&FilePath=images%2Flogo2.png&View=true"
|
179 |
+
|
180 |
+
st.markdown(
|
181 |
+
f'<div style="display: flex; flex-direction: column; align-items: center; text-align: center; margin: 0; padding: 0;">'
|
182 |
+
'<div style="font-style: italic; font-weight: 900; margin: 0; padding-top: 4px; display: flex; align-items: center; justify-content: center; flex-wrap: wrap; width: 100%;">'
|
183 |
+
f'<img src="{image_url}" style="width: 45px; height: 45px; "> '
|
184 |
+
f'<span style="font-size: 26px; margin-left: 10px;">{slogan}</span>'
|
185 |
+
'</div>'
|
186 |
+
'<span style="color: #bbb; font-style: italic; margin-top: 6px; margin-bottom: 10px;">内容完全由AI生成,请务必仔细甄别<br>Content AI-generated, please discern with care</span>'
|
187 |
+
'</div>',
|
188 |
+
unsafe_allow_html=True
|
189 |
+
)
|
190 |
+
|
191 |
+
|
192 |
+
def setup_seed(seed):
|
193 |
+
random.seed(seed)
|
194 |
+
np.random.seed(seed)
|
195 |
+
torch.manual_seed(seed)
|
196 |
+
torch.cuda.manual_seed(seed)
|
197 |
+
torch.cuda.manual_seed_all(seed)
|
198 |
+
torch.backends.cudnn.deterministic = True
|
199 |
+
torch.backends.cudnn.benchmark = False
|
200 |
+
|
201 |
+
|
202 |
+
def main():
|
203 |
+
model, tokenizer = load_model_tokenizer(model_path)
|
204 |
+
|
205 |
+
# 初始化消息列表
|
206 |
+
if "messages" not in st.session_state:
|
207 |
+
st.session_state.messages = []
|
208 |
+
st.session_state.chat_messages = []
|
209 |
+
|
210 |
+
# Use session state messages
|
211 |
+
messages = st.session_state.messages
|
212 |
+
|
213 |
+
# 在显示历史消息的循环中
|
214 |
+
for i, message in enumerate(messages):
|
215 |
+
if message["role"] == "assistant":
|
216 |
+
with st.chat_message("assistant", avatar=image_url):
|
217 |
+
st.markdown(process_assistant_content(message["content"]), unsafe_allow_html=True)
|
218 |
+
if st.button("×", key=f"delete_{i}"):
|
219 |
+
# 删除当前消息及其之后的所有消息
|
220 |
+
st.session_state.messages = st.session_state.messages[:i - 1]
|
221 |
+
st.session_state.chat_messages = st.session_state.chat_messages[:i - 1]
|
222 |
+
st.rerun()
|
223 |
+
else:
|
224 |
+
st.markdown(
|
225 |
+
f'<div style="display: flex; justify-content: flex-end;"><div style="display: inline-block; margin: 10px 0; padding: 8px 12px 8px 12px; background-color: gray; border-radius: 10px; color:white; ">{message["content"]}</div></div>',
|
226 |
+
unsafe_allow_html=True)
|
227 |
+
|
228 |
+
# 处理新的输入或重新生成
|
229 |
+
prompt = st.chat_input(key="input", placeholder="给 MiniMind 发送消息")
|
230 |
+
|
231 |
+
# 检查是否需要重新生成
|
232 |
+
if hasattr(st.session_state, 'regenerate') and st.session_state.regenerate:
|
233 |
+
prompt = st.session_state.last_user_message
|
234 |
+
regenerate_index = st.session_state.regenerate_index # 获取重新生成的位置
|
235 |
+
# 清除所有重新生成相关的状态
|
236 |
+
delattr(st.session_state, 'regenerate')
|
237 |
+
delattr(st.session_state, 'last_user_message')
|
238 |
+
delattr(st.session_state, 'regenerate_index')
|
239 |
+
|
240 |
+
if prompt:
|
241 |
+
st.markdown(
|
242 |
+
f'<div style="display: flex; justify-content: flex-end;"><div style="display: inline-block; margin: 10px 0; padding: 8px 12px 8px 12px; background-color: gray; border-radius: 10px; color:white; ">{prompt}</div></div>',
|
243 |
+
unsafe_allow_html=True)
|
244 |
+
messages.append({"role": "user", "content": prompt})
|
245 |
+
st.session_state.chat_messages.append({"role": "user", "content": prompt})
|
246 |
+
|
247 |
+
with st.chat_message("assistant", avatar=image_url):
|
248 |
+
placeholder = st.empty()
|
249 |
+
random_seed = random.randint(0, 2 ** 32 - 1)
|
250 |
+
setup_seed(random_seed)
|
251 |
+
|
252 |
+
st.session_state.chat_messages = system_prompt + st.session_state.chat_messages[
|
253 |
+
-(st.session_state.history_chat_num + 1):]
|
254 |
+
new_prompt = tokenizer.apply_chat_template(
|
255 |
+
st.session_state.chat_messages,
|
256 |
+
tokenize=False,
|
257 |
+
add_generation_prompt=True
|
258 |
+
)[-(st.session_state.max_new_tokens - 1):]
|
259 |
+
|
260 |
+
x = torch.tensor(tokenizer(new_prompt)['input_ids'], device=device).unsqueeze(0)
|
261 |
+
with torch.no_grad():
|
262 |
+
res_y = model.generate(x, tokenizer.eos_token_id, max_new_tokens=st.session_state.max_new_tokens,
|
263 |
+
temperature=st.session_state.temperature,
|
264 |
+
top_p=st.session_state.top_p, stream=True)
|
265 |
+
try:
|
266 |
+
for y in res_y:
|
267 |
+
answer = tokenizer.decode(y[0].tolist(), skip_special_tokens=True)
|
268 |
+
if (answer and answer[-1] == '�') or not answer:
|
269 |
+
continue
|
270 |
+
placeholder.markdown(process_assistant_content(answer), unsafe_allow_html=True)
|
271 |
+
except StopIteration:
|
272 |
+
print("No answer")
|
273 |
+
|
274 |
+
assistant_answer = answer.replace(new_prompt, "")
|
275 |
+
messages.append({"role": "assistant", "content": assistant_answer})
|
276 |
+
st.session_state.chat_messages.append({"role": "assistant", "content": assistant_answer})
|
277 |
+
|
278 |
+
with st.empty():
|
279 |
+
if st.button("×", key=f"delete_{len(messages) - 1}"):
|
280 |
+
st.session_state.messages = st.session_state.messages[:-2]
|
281 |
+
st.session_state.chat_messages = st.session_state.chat_messages[:-2]
|
282 |
+
st.rerun()
|
283 |
+
|
284 |
+
|
285 |
+
if __name__ == "__main__":
|
286 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
287 |
+
|
288 |
+
main()
|