model.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. import math
  2. import struct
  3. import inspect
  4. from .LMConfig import LMConfig
  5. from typing import Any, Optional, Tuple
  6. import numpy as np
  7. import torch
  8. import torch.nn.functional as F
  9. from torch import nn
  10. from transformers import PreTrainedModel
  11. from transformers.modeling_outputs import CausalLMOutputWithPast
  12. class RMSNorm(torch.nn.Module):
  13. def __init__(self, dim: int, eps: float):
  14. super().__init__()
  15. self.eps = eps
  16. self.weight = nn.Parameter(torch.ones(dim))
  17. def _norm(self, x):
  18. return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
  19. def forward(self, x):
  20. output = self._norm(x.float()).type_as(x)
  21. return output * self.weight
  22. def precompute_pos_cis(dim: int, end: int, theta: float = 10000.0):
  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.k_cache, self.v_cache = None, None
  65. self.attn_dropout = nn.Dropout(args.dropout)
  66. self.resid_dropout = nn.Dropout(args.dropout)
  67. self.dropout = args.dropout
  68. self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
  69. if not self.flash:
  70. # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
  71. mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
  72. mask = torch.triu(mask, diagonal=1)
  73. self.register_buffer("mask", mask)
  74. def forward(self, x: torch.Tensor, pos_cis: torch.Tensor, use_kv_cache=False):
  75. bsz, seqlen, _ = x.shape
  76. if use_kv_cache and self.eval():
  77. if self.k_cache is None or self.k_cache.shape[1] != x.shape[1] - 1:
  78. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
  79. else:
  80. token = x[:, -1:, :]
  81. xq = torch.cat((torch.zeros_like(x[:, :-1, :]), self.wq(token)), dim=1)
  82. xk = torch.cat((self.k_cache, self.wk(token)), dim=1)
  83. xv = torch.cat((self.v_cache, self.wv(token)), dim=1)
  84. self.k_cache, self.v_cache = xk, xv
  85. else:
  86. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
  87. xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
  88. xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  89. xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  90. xq, xk = apply_rotary_emb(xq, xk, pos_cis)
  91. xk = repeat_kv(xk, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
  92. xv = repeat_kv(xv, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
  93. xq = xq.transpose(1, 2)
  94. xk = xk.transpose(1, 2)
  95. xv = xv.transpose(1, 2)
  96. if self.flash:
  97. output = torch.nn.functional.scaled_dot_product_attention(xq, xk, xv, attn_mask=None,
  98. dropout_p=self.dropout if self.training else 0.0,
  99. is_causal=True)
  100. else:
  101. scores = torch.matmul(xq, xk.transpose(2, 3)) / math.sqrt(self.head_dim)
  102. assert hasattr(self, 'mask')
  103. scores = scores + self.mask[:, :, :seqlen, :seqlen] # (bs, n_local_heads, seqlen, cache_len + seqlen)
  104. scores = F.softmax(scores.float(), dim=-1).type_as(xq)
  105. scores = self.attn_dropout(scores)
  106. output = torch.matmul(scores, xv) # (bs, n_local_heads, seqlen, head_dim)
  107. output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
  108. output = self.wo(output)
  109. output = self.resid_dropout(output)
  110. return output
  111. class FeedForward(nn.Module):
  112. def __init__(self, dim: int, hidden_dim: int, multiple_of: int, dropout: float):
  113. super().__init__()
  114. if hidden_dim is None:
  115. hidden_dim = 4 * dim
  116. hidden_dim = int(2 * hidden_dim / 3)
  117. hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  118. self.w1 = nn.Linear(dim, hidden_dim, bias=False)
  119. self.w2 = nn.Linear(hidden_dim, dim, bias=False)
  120. self.w3 = nn.Linear(dim, hidden_dim, bias=False)
  121. self.dropout = nn.Dropout(dropout)
  122. def forward(self, x):
  123. return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x)))
  124. class MoEGate(nn.Module):
  125. def __init__(self, config: LMConfig):
  126. super().__init__()
  127. self.config = config
  128. self.top_k = config.num_experts_per_tok
  129. self.n_routed_experts = config.n_routed_experts
  130. self.scoring_func = config.scoring_func
  131. self.alpha = config.aux_loss_alpha
  132. self.seq_aux = config.seq_aux
  133. self.norm_topk_prob = config.norm_topk_prob
  134. self.gating_dim = config.dim
  135. self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
  136. self.reset_parameters()
  137. def reset_parameters(self) -> None:
  138. import torch.nn.init as init
  139. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  140. def forward(self, hidden_states):
  141. bsz, seq_len, h = hidden_states.shape
  142. hidden_states = hidden_states.view(-1, h)
  143. logits = F.linear(hidden_states, self.weight, None)
  144. if self.scoring_func == 'softmax':
  145. scores = logits.softmax(dim=-1)
  146. else:
  147. raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
  148. topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
  149. if self.top_k > 1 and self.norm_topk_prob:
  150. denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
  151. topk_weight = topk_weight / denominator
  152. if self.training and self.alpha > 0.0:
  153. scores_for_aux = scores
  154. aux_topk = self.top_k
  155. topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
  156. if self.seq_aux:
  157. scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
  158. ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
  159. ce.scatter_add_(1, topk_idx_for_aux_loss,
  160. torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(
  161. seq_len * aux_topk / self.n_routed_experts)
  162. aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
  163. else:
  164. mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
  165. ce = mask_ce.float().mean(0)
  166. Pi = scores_for_aux.mean(0)
  167. fi = ce * self.n_routed_experts
  168. aux_loss = (Pi * fi).sum() * self.alpha
  169. else:
  170. aux_loss = None
  171. return topk_idx, topk_weight, aux_loss
  172. class MOEFeedForward(nn.Module):
  173. def __init__(self, config: LMConfig):
  174. super().__init__()
  175. self.config = config
  176. self.experts = nn.ModuleList([
  177. FeedForward(
  178. dim=config.dim,
  179. hidden_dim=config.hidden_dim,
  180. multiple_of=config.multiple_of,
  181. dropout=config.dropout,
  182. )
  183. for _ in range(config.n_routed_experts)
  184. ])
  185. self.gate = MoEGate(config)
  186. if config.n_shared_experts is not None:
  187. self.shared_experts = FeedForward(
  188. dim=config.dim,
  189. hidden_dim=config.hidden_dim,
  190. multiple_of=config.multiple_of,
  191. dropout=config.dropout,
  192. )
  193. def forward(self, x):
  194. identity = x
  195. orig_shape = x.shape
  196. bsz, seq_len, _ = x.shape
  197. # 使用门控机制选择专家
  198. topk_idx, topk_weight, aux_loss = self.gate(x)
  199. x = x.view(-1, x.shape[-1])
  200. flat_topk_idx = topk_idx.view(-1)
  201. if self.training:
  202. # 训练模式下,重复输入数据
  203. x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
  204. y = torch.empty_like(x, dtype=torch.float16)
  205. for i, expert in enumerate(self.experts):
  206. y[flat_topk_idx == i] = expert(x[flat_topk_idx == i])
  207. y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
  208. y = y.view(*orig_shape)
  209. else:
  210. # 推理模式下,只选择最优专家
  211. y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
  212. if self.config.n_shared_experts is not None:
  213. y = y + self.shared_experts(identity)
  214. return y
  215. @torch.no_grad()
  216. def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
  217. expert_cache = torch.zeros_like(x)
  218. idxs = flat_expert_indices.argsort()
  219. tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
  220. token_idxs = idxs // self.config.num_experts_per_tok
  221. # 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
  222. # 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
  223. # 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
  224. for i, end_idx in enumerate(tokens_per_expert):
  225. start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
  226. if start_idx == end_idx:
  227. continue
  228. expert = self.experts[i]
  229. exp_token_idx = token_idxs[start_idx:end_idx]
  230. expert_tokens = x[exp_token_idx]
  231. expert_out = expert(expert_tokens)
  232. expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
  233. # 使用 scatter_add_ 进行 sum 操作
  234. expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
  235. return expert_cache
  236. class TransformerBlock(nn.Module):
  237. def __init__(self, layer_id: int, args: LMConfig):
  238. super().__init__()
  239. self.n_heads = args.n_heads
  240. self.dim = args.dim
  241. self.head_dim = args.dim // args.n_heads
  242. self.attention = Attention(args)
  243. self.layer_id = layer_id
  244. self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
  245. self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
  246. if args.use_moe:
  247. self.feed_forward = MOEFeedForward(args)
  248. else:
  249. self.feed_forward = FeedForward(
  250. dim=args.dim,
  251. hidden_dim=args.hidden_dim,
  252. multiple_of=args.multiple_of,
  253. dropout=args.dropout,
  254. )
  255. def forward(self, x, pos_cis, use_kv_cache=False):
  256. h = x + self.attention(self.attention_norm(x), pos_cis, use_kv_cache)
  257. out = h + self.feed_forward(self.ffn_norm(h))
  258. return out
  259. class Transformer(PreTrainedModel):
  260. config_class = LMConfig
  261. last_loss: Optional[torch.Tensor]
  262. def __init__(self, params: LMConfig = None):
  263. super().__init__(params)
  264. if not params:
  265. params = LMConfig()
  266. self.params = params
  267. self.vocab_size = params.vocab_size
  268. self.n_layers = params.n_layers
  269. self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
  270. self.dropout = nn.Dropout(params.dropout)
  271. self.layers = torch.nn.ModuleList()
  272. for layer_id in range(self.n_layers):
  273. self.layers.append(TransformerBlock(layer_id, params))
  274. self.norm = RMSNorm(params.dim, eps=params.norm_eps)
  275. self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
  276. self.tok_embeddings.weight = self.output.weight
  277. pos_cis = precompute_pos_cis(self.params.dim // self.params.n_heads, self.params.max_seq_len)
  278. self.register_buffer("pos_cis", pos_cis, persistent=False)
  279. self.apply(self._init_weights)
  280. for pn, p in self.named_parameters():
  281. if pn.endswith('w3.weight') or pn.endswith('wo.weight'):
  282. torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * params.n_layers))
  283. self.last_loss = None
  284. self.OUT = CausalLMOutputWithPast()
  285. def _init_weights(self, module):
  286. if isinstance(module, nn.Linear):
  287. torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
  288. if module.bias is not None:
  289. torch.nn.init.zeros_(module.bias)
  290. elif isinstance(module, nn.Embedding):
  291. torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
  292. def forward(self, tokens: Optional[torch.Tensor] = None, targets: Optional[torch.Tensor] = None,
  293. use_kv_cache=False, **keyargs):
  294. if 'input_ids' in keyargs:
  295. tokens = keyargs['input_ids']
  296. if 'attention_mask' in keyargs:
  297. targets = keyargs['attention_mask']
  298. _bsz, seqlen = tokens.shape
  299. h = self.tok_embeddings(tokens)
  300. h = self.dropout(h)
  301. pos_cis = self.pos_cis[:seqlen]
  302. for idx, layer in enumerate(self.layers):
  303. h = layer(h, pos_cis, use_kv_cache)
  304. h = self.norm(h)
  305. if targets is not None:
  306. logits = self.output(h)
  307. self.last_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
  308. else:
  309. logits = self.output(h[:, [-1], :])
  310. self.last_loss = None
  311. self.OUT.__setitem__('logits', logits)
  312. self.OUT.__setitem__('last_loss', self.last_loss)
  313. return self.OUT
  314. @torch.inference_mode()
  315. def generate(self, idx, eos, max_new_tokens, temperature=0.7, top_k=None, stream=True, repetition_penalty=1.,
  316. use_kv_cache=True):
  317. index = idx.shape[1]
  318. while idx.shape[1] < max_new_tokens - 1:
  319. inference_res = self(idx, use_kv_cache=use_kv_cache)
  320. logits = inference_res.logits
  321. logits = logits[:, -1, :]
  322. for token in set(idx.tolist()[0]):
  323. logits[:, token] /= repetition_penalty
  324. if temperature == 0.0:
  325. _, idx_next = torch.topk(logits, k=1, dim=-1)
  326. else:
  327. logits = logits / temperature
  328. if top_k is not None:
  329. v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
  330. logits[logits < v[:, [-1]]] = -float('Inf')
  331. probs = F.softmax(logits, dim=-1)
  332. idx_next = torch.multinomial(probs, num_samples=1, generator=None)
  333. if idx_next == eos:
  334. break
  335. idx = torch.cat((idx, idx_next), dim=1)
  336. if stream:
  337. yield idx[:, index:]
  338. if not stream:
  339. yield idx[:, index:]
  340. @torch.inference_mode()
  341. def eval_answer(self, idx):
  342. idx_cond = idx if idx.size(1) <= self.params.max_seq_len else idx[:, -self.params.max_seq_len:]
  343. inference_res = self(idx_cond)
  344. logits = inference_res.logits
  345. logits = logits[:, -1, :]
  346. return logits