model.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import math
  2. import struct
  3. import inspect
  4. import time
  5. from .LMConfig import LMConfig
  6. from typing import Any, Optional, Tuple, List
  7. import numpy as np
  8. import torch
  9. import torch.nn.functional as F
  10. from torch import nn
  11. from transformers import PreTrainedModel
  12. from transformers.modeling_outputs import CausalLMOutputWithPast
  13. class RMSNorm(torch.nn.Module):
  14. def __init__(self, dim: int, eps: float):
  15. super().__init__()
  16. self.eps = eps
  17. self.weight = nn.Parameter(torch.ones(dim))
  18. def forward(self, x):
  19. return self.weight * (x.float() * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)).type_as(x)
  20. def precompute_pos_cis(dim: int, end: int = int(32 * 1024), theta: float = 1e6):
  21. freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
  22. t = torch.arange(end, device=freqs.device) # type: ignore
  23. freqs = torch.outer(t, freqs).float() # type: ignore
  24. pos_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
  25. return pos_cis
  26. def apply_rotary_emb(xq, xk, pos_cis):
  27. def unite_shape(pos_cis, x):
  28. ndim = x.ndim
  29. assert 0 <= 1 < ndim
  30. assert pos_cis.shape == (x.shape[1], x.shape[-1])
  31. shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
  32. return pos_cis.view(*shape)
  33. xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
  34. xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
  35. pos_cis = unite_shape(pos_cis, xq_)
  36. xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
  37. xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
  38. return xq_out.type_as(xq), xk_out.type_as(xk)
  39. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  40. """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
  41. bs, slen, n_kv_heads, head_dim = x.shape
  42. if n_rep == 1:
  43. return x
  44. return (
  45. x[:, :, :, None, :]
  46. .expand(bs, slen, n_kv_heads, n_rep, head_dim)
  47. .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
  48. )
  49. class Attention(nn.Module):
  50. def __init__(self, args: LMConfig):
  51. super().__init__()
  52. self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
  53. assert args.n_heads % self.n_kv_heads == 0
  54. self.n_local_heads = args.n_heads
  55. self.n_local_kv_heads = self.n_kv_heads
  56. self.n_rep = self.n_local_heads // self.n_local_kv_heads
  57. self.head_dim = args.dim // args.n_heads
  58. self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
  59. self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  60. self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  61. self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
  62. self.attn_dropout = nn.Dropout(args.dropout)
  63. self.resid_dropout = nn.Dropout(args.dropout)
  64. self.dropout = args.dropout
  65. self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
  66. # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
  67. mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
  68. mask = torch.triu(mask, diagonal=1)
  69. self.register_buffer("mask", mask, persistent=False)
  70. def forward(self,
  71. x: torch.Tensor,
  72. pos_cis: torch.Tensor,
  73. past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
  74. use_cache=False):
  75. bsz, seq_len, _ = x.shape
  76. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
  77. xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
  78. xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
  79. xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
  80. xq, xk = apply_rotary_emb(xq, xk, pos_cis)
  81. # kv_cache实现
  82. if past_key_value is not None:
  83. xk = torch.cat([past_key_value[0], xk], dim=1)
  84. xv = torch.cat([past_key_value[1], xv], dim=1)
  85. past_kv = (xk, xv) if use_cache else None
  86. xq, xk, xv = (
  87. xq.transpose(1, 2),
  88. repeat_kv(xk, self.n_rep).transpose(1, 2),
  89. repeat_kv(xv, self.n_rep).transpose(1, 2)
  90. )
  91. if self.flash and seq_len != 1:
  92. dropout_p = self.dropout if self.training else 0.0
  93. output = F.scaled_dot_product_attention(
  94. xq, xk, xv,
  95. attn_mask=None,
  96. dropout_p=dropout_p,
  97. is_causal=True
  98. )
  99. else:
  100. scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
  101. scores += self.mask[:, :, :seq_len, :seq_len]
  102. scores = F.softmax(scores.float(), dim=-1).type_as(xq)
  103. scores = self.attn_dropout(scores)
  104. output = scores @ xv
  105. output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
  106. output = self.resid_dropout(self.wo(output))
  107. return output, past_kv
  108. class FeedForward(nn.Module):
  109. def __init__(self, config: LMConfig):
  110. super().__init__()
  111. if config.hidden_dim is None:
  112. hidden_dim = 4 * config.dim
  113. hidden_dim = int(2 * hidden_dim / 3)
  114. config.hidden_dim = config.multiple_of * ((hidden_dim + config.multiple_of - 1) // config.multiple_of)
  115. self.w1 = nn.Linear(config.dim, config.hidden_dim, bias=False)
  116. self.w2 = nn.Linear(config.hidden_dim, config.dim, bias=False)
  117. self.w3 = nn.Linear(config.dim, config.hidden_dim, bias=False)
  118. self.dropout = nn.Dropout(config.dropout)
  119. def forward(self, x):
  120. return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
  121. class MoEGate(nn.Module):
  122. def __init__(self, config: LMConfig):
  123. super().__init__()
  124. self.config = config
  125. self.top_k = config.num_experts_per_tok
  126. self.n_routed_experts = config.n_routed_experts
  127. self.scoring_func = config.scoring_func
  128. self.alpha = config.aux_loss_alpha
  129. self.seq_aux = config.seq_aux
  130. self.norm_topk_prob = config.norm_topk_prob
  131. self.gating_dim = config.dim
  132. self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
  133. self.reset_parameters()
  134. def reset_parameters(self) -> None:
  135. import torch.nn.init as init
  136. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  137. def forward(self, hidden_states):
  138. bsz, seq_len, h = hidden_states.shape
  139. hidden_states = hidden_states.view(-1, h)
  140. logits = F.linear(hidden_states, self.weight, None)
  141. if self.scoring_func == 'softmax':
  142. scores = logits.softmax(dim=-1)
  143. else:
  144. raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
  145. topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
  146. if self.top_k > 1 and self.norm_topk_prob:
  147. denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
  148. topk_weight = topk_weight / denominator
  149. if self.training and self.alpha > 0.0:
  150. scores_for_aux = scores
  151. aux_topk = self.top_k
  152. topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
  153. if self.seq_aux:
  154. scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
  155. ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
  156. ce.scatter_add_(1, topk_idx_for_aux_loss,
  157. torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
  158. seq_len * aux_topk / self.n_routed_experts)
  159. aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
  160. else:
  161. mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
  162. ce = mask_ce.float().mean(0)
  163. Pi = scores_for_aux.mean(0)
  164. fi = ce * self.n_routed_experts
  165. aux_loss = (Pi * fi).sum() * self.alpha
  166. else:
  167. aux_loss = 0
  168. return topk_idx, topk_weight, aux_loss
  169. class MOEFeedForward(nn.Module):
  170. def __init__(self, config: LMConfig):
  171. super().__init__()
  172. self.config = config
  173. self.experts = nn.ModuleList([
  174. FeedForward(config)
  175. for _ in range(config.n_routed_experts)
  176. ])
  177. self.gate = MoEGate(config)
  178. if config.n_shared_experts is not None:
  179. self.shared_experts = FeedForward(config)
  180. def forward(self, x):
  181. identity = x
  182. orig_shape = x.shape
  183. bsz, seq_len, _ = x.shape
  184. # 使用门控机制选择专家
  185. topk_idx, topk_weight, aux_loss = self.gate(x)
  186. x = x.view(-1, x.shape[-1])
  187. flat_topk_idx = topk_idx.view(-1)
  188. if self.training:
  189. # 训练模式下,重复输入数据
  190. x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
  191. y = torch.empty_like(x, dtype=torch.float16)
  192. for i, expert in enumerate(self.experts):
  193. y[flat_topk_idx == i] = expert(x[flat_topk_idx == i]).to(y.dtype) # 确保类型一致
  194. y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
  195. y = y.view(*orig_shape)
  196. else:
  197. # 推理模式下,只选择最优专家
  198. y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
  199. if self.config.n_shared_experts is not None:
  200. y = y + self.shared_experts(identity)
  201. self.aux_loss = aux_loss
  202. return y
  203. @torch.no_grad()
  204. def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
  205. expert_cache = torch.zeros_like(x)
  206. idxs = flat_expert_indices.argsort()
  207. tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
  208. token_idxs = idxs // self.config.num_experts_per_tok
  209. # 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
  210. # 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
  211. # 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
  212. for i, end_idx in enumerate(tokens_per_expert):
  213. start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
  214. if start_idx == end_idx:
  215. continue
  216. expert = self.experts[i]
  217. exp_token_idx = token_idxs[start_idx:end_idx]
  218. expert_tokens = x[exp_token_idx]
  219. expert_out = expert(expert_tokens).to(expert_cache.dtype)
  220. expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
  221. # 使用 scatter_add_ 进行 sum 操作
  222. expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
  223. return expert_cache
  224. class MiniMindBlock(nn.Module):
  225. def __init__(self, layer_id: int, config: LMConfig):
  226. super().__init__()
  227. self.n_heads = config.n_heads
  228. self.dim = config.dim
  229. self.head_dim = config.dim // config.n_heads
  230. self.attention = Attention(config)
  231. self.layer_id = layer_id
  232. self.attention_norm = RMSNorm(config.dim, eps=config.norm_eps)
  233. self.ffn_norm = RMSNorm(config.dim, eps=config.norm_eps)
  234. self.feed_forward = FeedForward(config) if not config.use_moe else MOEFeedForward(config)
  235. def forward(self, x, pos_cis, past_key_value=None, use_cache=False):
  236. h_attn, past_kv = self.attention(
  237. self.attention_norm(x),
  238. pos_cis,
  239. past_key_value=past_key_value,
  240. use_cache=use_cache
  241. )
  242. h = x + h_attn
  243. out = h + self.feed_forward(self.ffn_norm(h))
  244. return out, past_kv
  245. class MiniMindLM(PreTrainedModel):
  246. config_class = LMConfig
  247. def __init__(self, params: LMConfig = None):
  248. self.params = params or LMConfig()
  249. super().__init__(self.params)
  250. self.vocab_size, self.n_layers = params.vocab_size, params.n_layers
  251. self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
  252. self.dropout = nn.Dropout(params.dropout)
  253. self.layers = nn.ModuleList([MiniMindBlock(l, params) for l in range(self.n_layers)])
  254. self.norm = RMSNorm(params.dim, eps=params.norm_eps)
  255. self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
  256. self.tok_embeddings.weight = self.output.weight
  257. self.register_buffer("pos_cis",
  258. precompute_pos_cis(dim=params.dim // params.n_heads, theta=params.rope_theta),
  259. persistent=False)
  260. self.OUT = CausalLMOutputWithPast()
  261. def forward(self,
  262. input_ids: Optional[torch.Tensor] = None,
  263. past_key_values: Optional[List[Tuple[torch.Tensor, torch.Tensor]]] = None,
  264. use_cache: bool = False,
  265. **args):
  266. past_key_values = past_key_values or [None] * len(self.layers)
  267. start_pos = args.get('start_pos', 0)
  268. h = self.dropout(self.tok_embeddings(input_ids))
  269. pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)]
  270. past_kvs = []
  271. for l, layer in enumerate(self.layers):
  272. h, past_kv = layer(
  273. h, pos_cis,
  274. past_key_value=past_key_values[l],
  275. use_cache=use_cache
  276. )
  277. past_kvs.append(past_kv)
  278. logits = self.output(self.norm(h))
  279. aux_loss = sum(l.feed_forward.aux_loss for l in self.layers if isinstance(l.feed_forward, MOEFeedForward))
  280. self.OUT.__setitem__('logits', logits)
  281. self.OUT.__setitem__('aux_loss', aux_loss)
  282. self.OUT.__setitem__('past_key_values', past_kvs)
  283. return self.OUT
  284. @torch.inference_mode()
  285. def generate(self, input_ids, eos_token_id=2, max_new_tokens=1024, temperature=0.75, top_p=0.90,
  286. stream=False, rp=1., use_cache=True, pad_token_id=0, **args):
  287. # 流式生成
  288. if stream:
  289. return self._generate_stream(input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache)
  290. # 直接生成
  291. generated = []
  292. for i in range(input_ids.size(0)):
  293. non_pad = input_ids[i][input_ids[i] != pad_token_id].unsqueeze(0)
  294. out = self._generate_stream(non_pad, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache)
  295. tokens_list = [tokens[:, -1:] for tokens in out]
  296. gen = torch.cat(tokens_list, dim=-1) if tokens_list else non_pad
  297. full_sequence = torch.cat([non_pad, gen], dim=-1)
  298. generated.append(full_sequence)
  299. max_length = max(seq.size(1) for seq in generated)
  300. generated = [
  301. torch.cat(
  302. [seq, torch.full((1, max_length - seq.size(1)), pad_token_id, dtype=seq.dtype, device=seq.device)],
  303. dim=-1)
  304. for seq in generated
  305. ]
  306. return torch.cat(generated, dim=0)
  307. def _generate_stream(self, input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args):
  308. start, first_seq, past_kvs = input_ids.shape[1], True, None
  309. while input_ids.shape[1] < max_new_tokens - 1:
  310. if first_seq or not use_cache:
  311. out, first_seq = self(input_ids, past_key_values=past_kvs, use_cache=use_cache), False
  312. else:
  313. out = self(input_ids[:, -1:], past_key_values=past_kvs, use_cache=use_cache,
  314. start_pos=input_ids.shape[1] - 1)
  315. logits, past_kvs = out.logits[:, -1, :], out.past_key_values
  316. logits[:, list(set(input_ids.tolist()[0]))] /= rp
  317. logits /= (temperature + 1e-9)
  318. if top_p is not None and top_p < 1.0:
  319. sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
  320. sorted_probs = F.softmax(sorted_logits, dim=-1)
  321. cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
  322. sorted_indices_to_remove = cumulative_probs > top_p
  323. sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
  324. sorted_indices_to_remove[:, 0] = False
  325. indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
  326. logits[indices_to_remove] = -float('Inf')
  327. input_ids_next = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
  328. input_ids = torch.cat((input_ids, input_ids_next), dim=1)
  329. yield input_ids[:, start:]
  330. if input_ids_next.item() == eos_token_id:
  331. break