model.py 17 KB

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