model.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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, Union
  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 = 1e-6):
  15. super().__init__()
  16. self.eps = eps
  17. self.weight = nn.Parameter(torch.ones(dim))
  18. def _norm(self, x):
  19. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
  20. def forward(self, x):
  21. return self.weight * self._norm(x.float()).type_as(x)
  22. def precompute_pos_cis(dim: int, end: int = int(32 * 1024), theta: float = 1e6):
  23. freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
  24. t = torch.arange(end, device=freqs.device) # type: ignore
  25. freqs = torch.outer(t, freqs).float() # type: ignore
  26. pos_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
  27. return pos_cis
  28. def apply_rotary_emb(xq, xk, pos_cis):
  29. def unite_shape(pos_cis, x):
  30. ndim = x.ndim
  31. assert 0 <= 1 < ndim
  32. assert pos_cis.shape == (x.shape[1], x.shape[-1])
  33. shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
  34. return pos_cis.view(*shape)
  35. xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
  36. xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
  37. pos_cis = unite_shape(pos_cis, xq_)
  38. xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
  39. xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
  40. return xq_out.type_as(xq), xk_out.type_as(xk)
  41. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  42. """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
  43. bs, slen, n_kv_heads, head_dim = x.shape
  44. if n_rep == 1:
  45. return x
  46. return (
  47. x[:, :, :, None, :]
  48. .expand(bs, slen, n_kv_heads, n_rep, head_dim)
  49. .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
  50. )
  51. class Attention(nn.Module):
  52. def __init__(self, args: LMConfig):
  53. super().__init__()
  54. self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
  55. assert args.n_heads % self.n_kv_heads == 0
  56. self.n_local_heads = args.n_heads
  57. self.n_local_kv_heads = self.n_kv_heads
  58. self.n_rep = self.n_local_heads // self.n_local_kv_heads
  59. self.head_dim = args.dim // args.n_heads
  60. self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
  61. self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  62. self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  63. self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
  64. self.attn_dropout = nn.Dropout(args.dropout)
  65. self.resid_dropout = nn.Dropout(args.dropout)
  66. self.dropout = args.dropout
  67. self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
  68. # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
  69. mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
  70. mask = torch.triu(mask, diagonal=1)
  71. self.register_buffer("mask", mask, persistent=False)
  72. def forward(self,
  73. x: torch.Tensor,
  74. pos_cis: torch.Tensor,
  75. past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
  76. use_cache=False):
  77. bsz, seq_len, _ = x.shape
  78. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
  79. xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
  80. xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
  81. xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
  82. xq, xk = apply_rotary_emb(xq, xk, pos_cis)
  83. # kv_cache实现
  84. if past_key_value is not None:
  85. xk = torch.cat([past_key_value[0], xk], dim=1)
  86. xv = torch.cat([past_key_value[1], xv], dim=1)
  87. past_kv = (xk, xv) if use_cache else None
  88. xq, xk, xv = (
  89. xq.transpose(1, 2),
  90. repeat_kv(xk, self.n_rep).transpose(1, 2),
  91. repeat_kv(xv, self.n_rep).transpose(1, 2)
  92. )
  93. if self.flash and seq_len != 1:
  94. dropout_p = self.dropout if self.training else 0.0
  95. output = F.scaled_dot_product_attention(
  96. xq, xk, xv,
  97. attn_mask=None,
  98. dropout_p=dropout_p,
  99. is_causal=True
  100. )
  101. else:
  102. scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)
  103. scores += self.mask[:, :, :seq_len, :seq_len]
  104. scores = F.softmax(scores.float(), dim=-1).type_as(xq)
  105. scores = self.attn_dropout(scores)
  106. output = scores @ xv
  107. output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
  108. output = self.resid_dropout(self.wo(output))
  109. return output, past_kv
  110. class FeedForward(nn.Module):
  111. def __init__(self, config: LMConfig):
  112. super().__init__()
  113. if config.hidden_dim is None:
  114. hidden_dim = 4 * config.dim
  115. hidden_dim = int(2 * hidden_dim / 3)
  116. config.hidden_dim = config.multiple_of * ((hidden_dim + config.multiple_of - 1) // config.multiple_of)
  117. self.w1 = nn.Linear(config.dim, config.hidden_dim, bias=False)
  118. self.w2 = nn.Linear(config.hidden_dim, config.dim, bias=False)
  119. self.w3 = nn.Linear(config.dim, config.hidden_dim, bias=False)
  120. self.dropout = nn.Dropout(config.dropout)
  121. def forward(self, x):
  122. return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
  123. class MoEGate(nn.Module):
  124. def __init__(self, config: LMConfig):
  125. super().__init__()
  126. self.config = config
  127. self.top_k = config.num_experts_per_tok
  128. self.n_routed_experts = config.n_routed_experts
  129. self.scoring_func = config.scoring_func
  130. self.alpha = config.aux_loss_alpha
  131. self.seq_aux = config.seq_aux
  132. self.norm_topk_prob = config.norm_topk_prob
  133. self.gating_dim = config.dim
  134. self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
  135. self.reset_parameters()
  136. def reset_parameters(self) -> None:
  137. import torch.nn.init as init
  138. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  139. def forward(self, hidden_states):
  140. bsz, seq_len, h = hidden_states.shape
  141. hidden_states = hidden_states.view(-1, h)
  142. logits = F.linear(hidden_states, self.weight, None)
  143. if self.scoring_func == 'softmax':
  144. scores = logits.softmax(dim=-1)
  145. else:
  146. raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
  147. topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
  148. if self.top_k > 1 and self.norm_topk_prob:
  149. denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
  150. topk_weight = topk_weight / denominator
  151. if self.training and self.alpha > 0.0:
  152. scores_for_aux = scores
  153. aux_topk = self.top_k
  154. topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
  155. if self.seq_aux:
  156. scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
  157. ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
  158. ce.scatter_add_(1, topk_idx_for_aux_loss,
  159. torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
  160. seq_len * aux_topk / self.n_routed_experts)
  161. aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
  162. else:
  163. mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
  164. ce = mask_ce.float().mean(0)
  165. Pi = scores_for_aux.mean(0)
  166. fi = ce * self.n_routed_experts
  167. aux_loss = (Pi * fi).sum() * self.alpha
  168. else:
  169. aux_loss = 0
  170. return topk_idx, topk_weight, aux_loss
  171. class MOEFeedForward(nn.Module):
  172. def __init__(self, config: LMConfig):
  173. super().__init__()
  174. self.config = config
  175. self.experts = nn.ModuleList([
  176. FeedForward(config)
  177. for _ in range(config.n_routed_experts)
  178. ])
  179. self.gate = MoEGate(config)
  180. if config.n_shared_experts is not None:
  181. self.shared_experts = FeedForward(config)
  182. def forward(self, x):
  183. identity = x
  184. orig_shape = x.shape
  185. bsz, seq_len, _ = x.shape
  186. # 使用门控机制选择专家
  187. topk_idx, topk_weight, aux_loss = self.gate(x)
  188. x = x.view(-1, x.shape[-1])
  189. flat_topk_idx = topk_idx.view(-1)
  190. if self.training:
  191. x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
  192. y = torch.empty_like(x, dtype=torch.float16)
  193. for i, expert in enumerate(self.experts):
  194. y[flat_topk_idx == i] = expert(x[flat_topk_idx == i]).to(y.dtype) # 确保类型一致
  195. y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
  196. y = y.view(*orig_shape)
  197. else:
  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],tokens_per_expert.shape[0]即为专家数量(此时为4)
  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]这6个位置属于专家0处理的token(每个token有可能被多个专家处理,这取决于num_experts_per_tok)
  212. # 接下来9个位置token_idxs[6:15] -> [4, 5, 6, 10, 11, 12...]属于专家1处理的token...依此类推
  213. for i, end_idx in enumerate(tokens_per_expert):
  214. start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
  215. if start_idx == end_idx:
  216. continue
  217. expert = self.experts[i]
  218. exp_token_idx = token_idxs[start_idx:end_idx]
  219. expert_tokens = x[exp_token_idx]
  220. expert_out = expert(expert_tokens).to(expert_cache.dtype)
  221. expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
  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. logits_to_keep: Union[int, torch.Tensor] = 0,
  266. **args):
  267. past_key_values = past_key_values or [None] * len(self.layers)
  268. start_pos = args.get('start_pos', 0)
  269. h = self.dropout(self.tok_embeddings(input_ids))
  270. pos_cis = self.pos_cis[start_pos:start_pos + input_ids.size(1)]
  271. past_kvs = []
  272. for l, layer in enumerate(self.layers):
  273. h, past_kv = layer(
  274. h, pos_cis,
  275. past_key_value=past_key_values[l],
  276. use_cache=use_cache
  277. )
  278. past_kvs.append(past_kv)
  279. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  280. logits = self.output(self.norm(h)[:, slice_indices, :])
  281. aux_loss = sum(l.feed_forward.aux_loss for l in self.layers if isinstance(l.feed_forward, MOEFeedForward))
  282. self.OUT.__setitem__('last_hidden_state', h)
  283. self.OUT.__setitem__('logits', logits)
  284. self.OUT.__setitem__('aux_loss', aux_loss)
  285. self.OUT.__setitem__('past_key_values', past_kvs)
  286. return self.OUT
  287. @torch.inference_mode()
  288. def generate(self, input_ids, eos_token_id=2, max_new_tokens=1024, temperature=0.75, top_p=0.90,
  289. stream=False, rp=1., use_cache=True, pad_token_id=0, num_return_sequences=1, **args):
  290. # 流式生成
  291. if stream:
  292. return self._stream(input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args)
  293. # 直接生成
  294. generated = []
  295. for i in range(input_ids.size(0)):
  296. non_pad = input_ids[i][input_ids[i] != pad_token_id].unsqueeze(0)
  297. for _ in range(num_return_sequences):
  298. out = self._stream(non_pad, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args)
  299. tokens_list = [tokens[:, -1:] for tokens in out]
  300. gen = torch.cat(tokens_list, dim=-1) if tokens_list else non_pad
  301. full_sequence = torch.cat([non_pad, gen], dim=-1)
  302. generated.append(full_sequence)
  303. max_length = max(seq.size(1) for seq in generated)
  304. generated = [
  305. torch.cat(
  306. [seq, torch.full((1, max_length - seq.size(1)), pad_token_id, dtype=seq.dtype, device=seq.device)],
  307. dim=-1)
  308. for seq in generated
  309. ]
  310. output = torch.cat(generated, dim=0)
  311. res = output.view(input_ids.size(0) * num_return_sequences, -1)
  312. return res
  313. def _stream(self, input_ids, eos_token_id, max_new_tokens, temperature, top_p, rp, use_cache, **args):
  314. start, first_seq, past_kvs = input_ids.shape[1], True, None
  315. while input_ids.shape[1] < max_new_tokens - 1:
  316. if first_seq or not use_cache:
  317. out, first_seq = self(input_ids, past_key_values=past_kvs, use_cache=use_cache, **args), False
  318. else:
  319. out = self(input_ids[:, -1:], past_key_values=past_kvs, use_cache=use_cache,
  320. start_pos=input_ids.shape[1] - 1, **args)
  321. logits, past_kvs = out.logits[:, -1, :], out.past_key_values
  322. logits[:, list(set(input_ids.tolist()[0]))] /= rp
  323. logits /= (temperature + 1e-9)
  324. if top_p is not None and top_p < 1.0:
  325. sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
  326. sorted_probs = F.softmax(sorted_logits, dim=-1)
  327. cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
  328. sorted_indices_to_remove = cumulative_probs > top_p
  329. sorted_indices_to_remove[:, 1:] = sorted_indices_to_remove[:, :-1].clone()
  330. sorted_indices_to_remove[:, 0] = False
  331. indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
  332. logits[indices_to_remove] = -float('Inf')
  333. input_ids_next = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
  334. input_ids = torch.cat((input_ids, input_ids_next), dim=1)
  335. yield input_ids[:, start:]
  336. if input_ids_next.item() == eos_token_id:
  337. break