model.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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, train_len: int = 512):
  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. # # 计算缩放因子
  29. # scale = train_len / end
  30. # # 缩放旋转嵌入,实现线性的长度外推(注释掉不用是因为小模型依赖pos_cis拟合严重,直接做线性外推效果并不好)
  31. # pos_cis = pos_cis * scale
  32. return pos_cis
  33. def apply_rotary_emb(xq, xk, pos_cis):
  34. def unite_shape(pos_cis, x):
  35. ndim = x.ndim
  36. assert 0 <= 1 < ndim
  37. assert pos_cis.shape == (x.shape[1], x.shape[-1])
  38. shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
  39. return pos_cis.view(*shape)
  40. xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
  41. xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
  42. pos_cis = unite_shape(pos_cis, xq_)
  43. xq_out = torch.view_as_real(xq_ * pos_cis).flatten(3)
  44. xk_out = torch.view_as_real(xk_ * pos_cis).flatten(3)
  45. return xq_out.type_as(xq), xk_out.type_as(xk)
  46. def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
  47. """torch.repeat_interleave(x, dim=2, repeats=n_rep)"""
  48. bs, slen, n_kv_heads, head_dim = x.shape
  49. if n_rep == 1:
  50. return x
  51. return (
  52. x[:, :, :, None, :]
  53. .expand(bs, slen, n_kv_heads, n_rep, head_dim)
  54. .reshape(bs, slen, n_kv_heads * n_rep, head_dim)
  55. )
  56. class Attention(nn.Module):
  57. def __init__(self, args: LMConfig):
  58. super().__init__()
  59. self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
  60. assert args.n_heads % self.n_kv_heads == 0
  61. self.n_local_heads = args.n_heads
  62. self.n_local_kv_heads = self.n_kv_heads
  63. self.n_rep = self.n_local_heads // self.n_local_kv_heads
  64. self.head_dim = args.dim // args.n_heads
  65. self.wq = nn.Linear(args.dim, args.n_heads * self.head_dim, bias=False)
  66. self.wk = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  67. self.wv = nn.Linear(args.dim, self.n_kv_heads * self.head_dim, bias=False)
  68. self.wo = nn.Linear(args.n_heads * self.head_dim, args.dim, bias=False)
  69. self.k_cache, self.v_cache = None, None
  70. self.attn_dropout = nn.Dropout(args.dropout)
  71. self.resid_dropout = nn.Dropout(args.dropout)
  72. self.dropout = args.dropout
  73. self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and args.flash_attn
  74. # print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
  75. mask = torch.full((1, 1, args.max_seq_len, args.max_seq_len), float("-inf"))
  76. mask = torch.triu(mask, diagonal=1)
  77. self.register_buffer("mask", mask, persistent=False)
  78. def forward(self, x: torch.Tensor, pos_cis: torch.Tensor, kv_cache=False):
  79. bsz, seqlen, _ = x.shape
  80. xq, xk, xv = self.wq(x), self.wk(x), self.wv(x)
  81. xq = xq.view(bsz, seqlen, self.n_local_heads, self.head_dim)
  82. xk = xk.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  83. xv = xv.view(bsz, seqlen, self.n_local_kv_heads, self.head_dim)
  84. xq, xk = apply_rotary_emb(xq, xk, pos_cis)
  85. # 更高效的kv_cache实现
  86. if kv_cache and self.eval():
  87. if seqlen == 1 and all(cache is not None for cache in (self.k_cache, self.v_cache)):
  88. xk = torch.cat((self.k_cache, xk), dim=1)
  89. xv = torch.cat((self.v_cache, xv), dim=1)
  90. self.k_cache, self.v_cache = xk, xv
  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 and seqlen != 1:
  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. scores = scores + self.mask[:, :, :seqlen, :seqlen] # (bs, n_local_heads, seqlen, cache_len + seqlen)
  103. scores = F.softmax(scores.float(), dim=-1).type_as(xq)
  104. scores = self.attn_dropout(scores)
  105. output = torch.matmul(scores, xv) # (bs, n_local_heads, seqlen, head_dim)
  106. output = output.transpose(1, 2).contiguous().view(bsz, seqlen, -1)
  107. output = self.wo(output)
  108. output = self.resid_dropout(output)
  109. return output
  110. class FeedForward(nn.Module):
  111. def __init__(self, dim: int, hidden_dim: int, multiple_of: int, dropout: float):
  112. super().__init__()
  113. if hidden_dim is None:
  114. hidden_dim = 4 * dim
  115. hidden_dim = int(2 * hidden_dim / 3)
  116. hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  117. self.w1 = nn.Linear(dim, hidden_dim, bias=False)
  118. self.w2 = nn.Linear(hidden_dim, dim, bias=False)
  119. self.w3 = nn.Linear(dim, hidden_dim, bias=False)
  120. self.dropout = nn.Dropout(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 = None
  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(
  177. dim=config.dim,
  178. hidden_dim=config.hidden_dim,
  179. multiple_of=config.multiple_of,
  180. dropout=config.dropout,
  181. )
  182. for _ in range(config.n_routed_experts)
  183. ])
  184. self.gate = MoEGate(config)
  185. if config.n_shared_experts is not None:
  186. self.shared_experts = FeedForward(
  187. dim=config.dim,
  188. hidden_dim=config.hidden_dim,
  189. multiple_of=config.multiple_of,
  190. dropout=config.dropout,
  191. )
  192. def forward(self, x):
  193. identity = x
  194. orig_shape = x.shape
  195. bsz, seq_len, _ = x.shape
  196. # 使用门控机制选择专家
  197. topk_idx, topk_weight, aux_loss = self.gate(x)
  198. x = x.view(-1, x.shape[-1])
  199. flat_topk_idx = topk_idx.view(-1)
  200. if self.training:
  201. # 训练模式下,重复输入数据
  202. x = x.repeat_interleave(self.config.num_experts_per_tok, dim=0)
  203. y = torch.empty_like(x, dtype=torch.float16)
  204. for i, expert in enumerate(self.experts):
  205. y[flat_topk_idx == i] = expert(x[flat_topk_idx == i])
  206. y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
  207. y = y.view(*orig_shape)
  208. else:
  209. # 推理模式下,只选择最优专家
  210. y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
  211. if self.config.n_shared_experts is not None:
  212. y = y + self.shared_experts(identity)
  213. return y
  214. @torch.no_grad()
  215. def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
  216. expert_cache = torch.zeros_like(x)
  217. idxs = flat_expert_indices.argsort()
  218. tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
  219. token_idxs = idxs // self.config.num_experts_per_tok
  220. # 例如当tokens_per_expert=[6, 15, 20, 26, 33, 38, 46, 52]
  221. # 当token_idxs=[3, 7, 19, 21, 24, 25, 4, 5, 6, 10, 11, 12...]
  222. # 意味着当token_idxs[:6] -> [3, 7, 19, 21, 24, 25, 4]位置的token都由专家0处理,token_idxs[6:15]位置的token都由专家1处理......
  223. for i, end_idx in enumerate(tokens_per_expert):
  224. start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
  225. if start_idx == end_idx:
  226. continue
  227. expert = self.experts[i]
  228. exp_token_idx = token_idxs[start_idx:end_idx]
  229. expert_tokens = x[exp_token_idx]
  230. expert_out = expert(expert_tokens)
  231. expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
  232. # 使用 scatter_add_ 进行 sum 操作
  233. expert_cache.scatter_add_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out)
  234. return expert_cache
  235. class TransformerBlock(nn.Module):
  236. def __init__(self, layer_id: int, args: LMConfig):
  237. super().__init__()
  238. self.n_heads = args.n_heads
  239. self.dim = args.dim
  240. self.head_dim = args.dim // args.n_heads
  241. self.attention = Attention(args)
  242. self.layer_id = layer_id
  243. self.attention_norm = RMSNorm(args.dim, eps=args.norm_eps)
  244. self.ffn_norm = RMSNorm(args.dim, eps=args.norm_eps)
  245. if args.use_moe:
  246. self.feed_forward = MOEFeedForward(args)
  247. else:
  248. self.feed_forward = FeedForward(
  249. dim=args.dim,
  250. hidden_dim=args.hidden_dim,
  251. multiple_of=args.multiple_of,
  252. dropout=args.dropout,
  253. )
  254. def forward(self, x, pos_cis, kv_cache=False):
  255. h = x + self.attention(self.attention_norm(x), pos_cis, kv_cache)
  256. out = h + self.feed_forward(self.ffn_norm(h))
  257. return out
  258. class Transformer(PreTrainedModel):
  259. config_class = LMConfig
  260. last_loss: Optional[torch.Tensor]
  261. def __init__(self, params: LMConfig = None):
  262. super().__init__(params)
  263. if not params:
  264. params = LMConfig()
  265. self.params = params
  266. self.vocab_size = params.vocab_size
  267. self.n_layers = params.n_layers
  268. self.tok_embeddings = nn.Embedding(params.vocab_size, params.dim)
  269. self.dropout = nn.Dropout(params.dropout)
  270. self.layers = torch.nn.ModuleList()
  271. for layer_id in range(self.n_layers):
  272. self.layers.append(TransformerBlock(layer_id, params))
  273. self.norm = RMSNorm(params.dim, eps=params.norm_eps)
  274. self.output = nn.Linear(params.dim, params.vocab_size, bias=False)
  275. self.tok_embeddings.weight = self.output.weight
  276. pos_cis = precompute_pos_cis(self.params.dim // self.params.n_heads, self.params.max_seq_len)
  277. self.register_buffer("pos_cis", pos_cis, persistent=False)
  278. self.apply(self._init_weights)
  279. for pn, p in self.named_parameters():
  280. if pn.endswith('w3.weight') or pn.endswith('wo.weight'):
  281. torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * params.n_layers))
  282. self.last_loss = None
  283. self.OUT = CausalLMOutputWithPast()
  284. self._no_split_modules = [name for name, _ in self.named_modules()]
  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. kv_cache=False, **keyargs):
  294. current_idx = 0
  295. if 'input_ids' in keyargs:
  296. tokens = keyargs['input_ids']
  297. if 'attention_mask' in keyargs:
  298. targets = keyargs['attention_mask']
  299. if 'current_idx' in keyargs:
  300. current_idx = int(keyargs['current_idx'])
  301. _bsz, seqlen = tokens.shape
  302. h = self.tok_embeddings(tokens)
  303. h = self.dropout(h)
  304. pos_cis = self.pos_cis[current_idx:current_idx + seqlen]
  305. for idx, layer in enumerate(self.layers):
  306. h = layer(h, pos_cis, kv_cache)
  307. h = self.norm(h)
  308. if targets is not None:
  309. logits = self.output(h)
  310. self.last_loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1),
  311. ignore_index=0, reduction='none')
  312. else:
  313. logits = self.output(h[:, [-1], :])
  314. self.last_loss = None
  315. self.OUT.__setitem__('logits', logits)
  316. self.OUT.__setitem__('last_loss', self.last_loss)
  317. return self.OUT
  318. @torch.inference_mode()
  319. def generate(self, idx, eos, max_new_tokens, temperature=0.7, top_k=8, stream=True, rp=1., kv_cache=True):
  320. # rp: repetition_penalty
  321. index = idx.shape[1]
  322. init_inference = True
  323. while idx.shape[1] < max_new_tokens - 1:
  324. if init_inference or not kv_cache:
  325. inference_res, init_inference = self(idx, kv_cache=kv_cache), False
  326. else:
  327. inference_res = self(idx[:, -1:], kv_cache=kv_cache, current_idx=idx.shape[1] - 1)
  328. logits = inference_res.logits
  329. logits = logits[:, -1, :]
  330. for token in set(idx.tolist()[0]):
  331. logits[:, token] /= rp
  332. if temperature == 0.0:
  333. _, idx_next = torch.topk(logits, k=1, dim=-1)
  334. else:
  335. logits = logits / temperature
  336. if top_k is not None:
  337. v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
  338. logits[logits < v[:, [-1]]] = -float('Inf')
  339. probs = F.softmax(logits, dim=-1)
  340. idx_next = torch.multinomial(probs, num_samples=1, generator=None)
  341. if idx_next == eos:
  342. break
  343. idx = torch.cat((idx, idx_next), dim=1)
  344. if stream:
  345. yield idx[:, index:]
  346. if not stream:
  347. yield idx[:, index:]
  348. @torch.inference_mode()
  349. def eval_answer(self, idx):
  350. idx_cond = idx if idx.size(1) <= self.params.max_seq_len else idx[:, -self.params.max_seq_len:]
  351. inference_res = self(idx_cond)
  352. logits = inference_res.logits
  353. logits = logits[:, -1, :]
  354. return logits