1
0

deepseek.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
  4. # Copyright 2023 The vLLM team.
  5. # Copyright 2023 DeepSeek-AI and the HuggingFace Inc. team. All rights reserved.
  6. #
  7. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  8. # and OPT implementations in this library. It has been modified from its
  9. # original forms to accommodate minor architectural differences compared
  10. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. """Inference-only Deepseek model."""
  24. from typing import Any, Dict, Iterable, List, Optional, Tuple
  25. import torch
  26. from torch import nn
  27. from transformers import PretrainedConfig
  28. from aphrodite.attention import Attention, AttentionMetadata
  29. from aphrodite.common.sequence import SamplerOutput
  30. from aphrodite.distributed import (get_tensor_model_parallel_rank,
  31. get_tensor_model_parallel_world_size,
  32. tensor_model_parallel_all_reduce)
  33. from aphrodite.modeling.layers.activation import SiluAndMul
  34. from aphrodite.modeling.layers.fused_moe import fused_moe
  35. from aphrodite.modeling.layers.layernorm import RMSNorm
  36. from aphrodite.modeling.layers.linear import (MergedColumnParallelLinear,
  37. QKVParallelLinear,
  38. ReplicatedLinear,
  39. RowParallelLinear)
  40. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  41. from aphrodite.modeling.layers.rotary_embedding import get_rope
  42. from aphrodite.modeling.layers.sampler import Sampler
  43. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  44. ParallelLMHead, VocabParallelEmbedding)
  45. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  46. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  47. from aphrodite.quantization.base_config import QuantizationConfig
  48. class DeepseekMLP(nn.Module):
  49. def __init__(
  50. self,
  51. hidden_size: int,
  52. intermediate_size: int,
  53. hidden_act: str,
  54. quant_config: Optional[QuantizationConfig] = None,
  55. reduce_results: bool = True,
  56. ) -> None:
  57. super().__init__()
  58. self.gate_up_proj = MergedColumnParallelLinear(
  59. hidden_size, [intermediate_size] * 2,
  60. bias=False,
  61. quant_config=quant_config)
  62. self.down_proj = RowParallelLinear(intermediate_size,
  63. hidden_size,
  64. bias=False,
  65. quant_config=quant_config,
  66. reduce_results=reduce_results)
  67. if hidden_act != "silu":
  68. raise ValueError(f"Unsupported activation: {hidden_act}. "
  69. "Only silu is supported for now.")
  70. self.act_fn = SiluAndMul()
  71. def forward(self, x):
  72. gate_up, _ = self.gate_up_proj(x)
  73. x = self.act_fn(gate_up)
  74. x, _ = self.down_proj(x)
  75. return x
  76. class DeepseekMoE(nn.Module):
  77. def __init__(
  78. self,
  79. config: PretrainedConfig,
  80. quant_config: Optional[QuantizationConfig] = None,
  81. ):
  82. super().__init__()
  83. self.config = config
  84. self.rank = get_tensor_model_parallel_rank()
  85. self.tp_size = get_tensor_model_parallel_world_size()
  86. self.n_routed_experts = config.n_routed_experts
  87. self.top_k = config.num_experts_per_tok
  88. if self.tp_size > self.n_routed_experts:
  89. raise ValueError(
  90. f"Tensor parallel size {self.tp_size} is greater than "
  91. f"the number of experts {self.n_routed_experts}.")
  92. self.experts = nn.ModuleList([
  93. DeepseekMLP(hidden_size=config.hidden_size,
  94. intermediate_size=config.moe_intermediate_size,
  95. hidden_act=config.hidden_act,
  96. quant_config=quant_config,
  97. reduce_results=False)
  98. for idx in range(self.n_routed_experts)
  99. ])
  100. self.pack_params()
  101. self.gate = ReplicatedLinear(config.hidden_size,
  102. self.n_routed_experts,
  103. bias=False,
  104. quant_config=None)
  105. if config.n_shared_experts is not None:
  106. intermediate_size = (config.moe_intermediate_size *
  107. config.n_shared_experts)
  108. self.shared_experts = DeepseekMLP(
  109. hidden_size=config.hidden_size,
  110. intermediate_size=intermediate_size,
  111. hidden_act=config.hidden_act,
  112. quant_config=quant_config,
  113. reduce_results=False,
  114. )
  115. def pack_params(self):
  116. w1 = []
  117. w2 = []
  118. for expert in self.experts:
  119. w1.append(expert.gate_up_proj.weight)
  120. w2.append(expert.down_proj.weight)
  121. self.w1 = torch._utils._flatten_dense_tensors(w1)
  122. w1s = torch._utils._unflatten_dense_tensors(self.w1, w1)
  123. for data, param in zip(w1s, w1):
  124. param.data = data
  125. self.w1 = self.w1.view(len(w1), *w1s[0].shape)
  126. self.w2 = torch._utils._flatten_dense_tensors(w2)
  127. w2s = torch._utils._unflatten_dense_tensors(self.w2, w2)
  128. for data, param in zip(w2s, w2):
  129. param.data = data
  130. self.w2 = self.w2.view(len(w2), *w2s[0].shape)
  131. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  132. num_tokens, hidden_dim = hidden_states.shape
  133. hidden_states = hidden_states.view(-1, hidden_dim)
  134. if self.config.n_shared_experts is not None:
  135. shared_output = self.shared_experts(hidden_states)
  136. # router_logits: (num_tokens, n_experts)
  137. router_logits, _ = self.gate(hidden_states)
  138. final_hidden_states = fused_moe(hidden_states,
  139. self.w1,
  140. self.w2,
  141. router_logits,
  142. self.top_k,
  143. renormalize=self.config.norm_topk_prob,
  144. inplace=True)
  145. if self.config.n_shared_experts is not None:
  146. final_hidden_states = final_hidden_states + shared_output
  147. final_hidden_states = tensor_model_parallel_all_reduce(
  148. final_hidden_states)
  149. return final_hidden_states.view(num_tokens, hidden_dim)
  150. class DeepseekAttention(nn.Module):
  151. def __init__(
  152. self,
  153. hidden_size: int,
  154. num_heads: int,
  155. num_kv_heads: int,
  156. rope_theta: float = 10000,
  157. rope_scaling: Optional[Dict[str, Any]] = None,
  158. max_position_embeddings: int = 8192,
  159. quant_config: Optional[QuantizationConfig] = None,
  160. ) -> None:
  161. super().__init__()
  162. self.hidden_size = hidden_size
  163. tp_size = get_tensor_model_parallel_world_size()
  164. self.total_num_heads = num_heads
  165. assert self.total_num_heads % tp_size == 0
  166. self.num_heads = self.total_num_heads // tp_size
  167. self.total_num_kv_heads = num_kv_heads
  168. if self.total_num_kv_heads >= tp_size:
  169. # Number of KV heads is greater than TP size, so we partition
  170. # the KV heads across multiple tensor parallel GPUs.
  171. assert self.total_num_kv_heads % tp_size == 0
  172. else:
  173. # Number of KV heads is less than TP size, so we replicate
  174. # the KV heads across multiple tensor parallel GPUs.
  175. assert tp_size % self.total_num_kv_heads == 0
  176. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  177. self.head_dim = hidden_size // self.total_num_heads
  178. self.q_size = self.num_heads * self.head_dim
  179. self.kv_size = self.num_kv_heads * self.head_dim
  180. self.scaling = self.head_dim**-0.5
  181. self.rope_theta = rope_theta
  182. self.max_position_embeddings = max_position_embeddings
  183. self.qkv_proj = QKVParallelLinear(
  184. hidden_size,
  185. self.head_dim,
  186. self.total_num_heads,
  187. self.total_num_kv_heads,
  188. bias=False,
  189. quant_config=quant_config,
  190. )
  191. self.o_proj = RowParallelLinear(
  192. self.total_num_heads * self.head_dim,
  193. hidden_size,
  194. bias=False,
  195. quant_config=quant_config,
  196. )
  197. self.rotary_emb = get_rope(
  198. self.head_dim,
  199. rotary_dim=self.head_dim,
  200. max_position=max_position_embeddings,
  201. base=rope_theta,
  202. rope_scaling=rope_scaling,
  203. )
  204. self.attn = Attention(self.num_heads,
  205. self.head_dim,
  206. self.scaling,
  207. num_kv_heads=self.num_kv_heads)
  208. def forward(
  209. self,
  210. positions: torch.Tensor,
  211. hidden_states: torch.Tensor,
  212. kv_cache: torch.Tensor,
  213. attn_metadata: AttentionMetadata,
  214. ) -> torch.Tensor:
  215. qkv, _ = self.qkv_proj(hidden_states)
  216. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  217. q, k = self.rotary_emb(positions, q, k)
  218. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  219. output, _ = self.o_proj(attn_output)
  220. return output
  221. class DeepseekDecoderLayer(nn.Module):
  222. def __init__(
  223. self,
  224. config: PretrainedConfig,
  225. layer_idx: int,
  226. quant_config: Optional[QuantizationConfig] = None,
  227. ) -> None:
  228. super().__init__()
  229. self.hidden_size = config.hidden_size
  230. rope_theta = getattr(config, "rope_theta", 10000)
  231. rope_scaling = getattr(config, "rope_scaling", None)
  232. max_position_embeddings = getattr(config, "max_position_embeddings",
  233. 8192)
  234. self.self_attn = DeepseekAttention(
  235. hidden_size=self.hidden_size,
  236. num_heads=config.num_attention_heads,
  237. num_kv_heads=config.num_key_value_heads,
  238. rope_theta=rope_theta,
  239. rope_scaling=rope_scaling,
  240. max_position_embeddings=max_position_embeddings,
  241. quant_config=quant_config,
  242. )
  243. if (config.n_routed_experts is not None
  244. and layer_idx >= config.first_k_dense_replace
  245. and layer_idx % config.moe_layer_freq == 0):
  246. self.mlp = DeepseekMoE(config=config, quant_config=quant_config)
  247. else:
  248. self.mlp = DeepseekMLP(
  249. hidden_size=config.hidden_size,
  250. intermediate_size=config.intermediate_size,
  251. hidden_act=config.hidden_act,
  252. quant_config=quant_config,
  253. )
  254. self.input_layernorm = RMSNorm(config.hidden_size,
  255. eps=config.rms_norm_eps)
  256. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  257. eps=config.rms_norm_eps)
  258. def forward(
  259. self,
  260. positions: torch.Tensor,
  261. hidden_states: torch.Tensor,
  262. kv_cache: torch.Tensor,
  263. attn_metadata: AttentionMetadata,
  264. residual: Optional[torch.Tensor],
  265. ) -> torch.Tensor:
  266. # Self Attention
  267. if residual is None:
  268. residual = hidden_states
  269. hidden_states = self.input_layernorm(hidden_states)
  270. else:
  271. hidden_states, residual = self.input_layernorm(
  272. hidden_states, residual)
  273. hidden_states = self.self_attn(
  274. positions=positions,
  275. hidden_states=hidden_states,
  276. kv_cache=kv_cache,
  277. attn_metadata=attn_metadata,
  278. )
  279. # Fully Connected
  280. hidden_states, residual = self.post_attention_layernorm(
  281. hidden_states, residual)
  282. hidden_states = self.mlp(hidden_states)
  283. return hidden_states, residual
  284. class DeepseekModel(nn.Module):
  285. fall_back_to_pt_during_load = False
  286. def __init__(
  287. self,
  288. config: PretrainedConfig,
  289. quant_config: Optional[QuantizationConfig] = None,
  290. ) -> None:
  291. super().__init__()
  292. self.padding_idx = config.pad_token_id
  293. self.vocab_size = config.vocab_size
  294. self.embed_tokens = VocabParallelEmbedding(
  295. config.vocab_size,
  296. config.hidden_size,
  297. )
  298. self.layers = nn.ModuleList([
  299. DeepseekDecoderLayer(config, layer_idx, quant_config=quant_config)
  300. for layer_idx in range(config.num_hidden_layers)
  301. ])
  302. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  303. def forward(
  304. self,
  305. input_ids: torch.Tensor,
  306. positions: torch.Tensor,
  307. kv_caches: List[torch.Tensor],
  308. attn_metadata: AttentionMetadata,
  309. ) -> torch.Tensor:
  310. hidden_states = self.embed_tokens(input_ids)
  311. residual = None
  312. for i in range(len(self.layers)):
  313. layer = self.layers[i]
  314. hidden_states, residual = layer(positions, hidden_states,
  315. kv_caches[i], attn_metadata,
  316. residual)
  317. hidden_states, _ = self.norm(hidden_states, residual)
  318. return hidden_states
  319. class DeepseekForCausalLM(nn.Module):
  320. def __init__(
  321. self,
  322. config: PretrainedConfig,
  323. quant_config: Optional[QuantizationConfig] = None,
  324. ) -> None:
  325. super().__init__()
  326. self.config = config
  327. self.quant_config = quant_config
  328. self.model = DeepseekModel(config, quant_config)
  329. self.lm_head = ParallelLMHead(config.vocab_size, config.hidden_size)
  330. self.logits_processor = LogitsProcessor(config.vocab_size)
  331. self.sampler = Sampler()
  332. def forward(
  333. self,
  334. input_ids: torch.Tensor,
  335. positions: torch.Tensor,
  336. kv_caches: List[torch.Tensor],
  337. attn_metadata: AttentionMetadata,
  338. ) -> torch.Tensor:
  339. hidden_states = self.model(input_ids, positions, kv_caches,
  340. attn_metadata)
  341. return hidden_states
  342. def compute_logits(self, hidden_states: torch.Tensor,
  343. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  344. logits = self.logits_processor(self.lm_head.weight, hidden_states,
  345. sampling_metadata)
  346. return logits
  347. def sample(
  348. self,
  349. logits: Optional[torch.Tensor],
  350. sampling_metadata: SamplingMetadata,
  351. ) -> Optional[SamplerOutput]:
  352. next_tokens = self.sampler(logits, sampling_metadata)
  353. return next_tokens
  354. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  355. stacked_params_mapping = [
  356. # (param_name, shard_name, shard_id)
  357. ("qkv_proj", "q_proj", "q"),
  358. ("qkv_proj", "k_proj", "k"),
  359. ("qkv_proj", "v_proj", "v"),
  360. ("gate_up_proj", "gate_proj", 0),
  361. ("gate_up_proj", "up_proj", 1),
  362. ]
  363. params_dict = dict(self.named_parameters())
  364. for name, loaded_weight in weights:
  365. if "rotary_emb.inv_freq" in name:
  366. continue
  367. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  368. if weight_name not in name:
  369. continue
  370. name = name.replace(weight_name, param_name)
  371. # Skip loading extra bias for GPTQ models.
  372. if name.endswith(".bias") and name not in params_dict:
  373. continue
  374. # Skip experts that are not assigned to this worker.
  375. if (("mlp.experts." in name or "mlp.shared_experts." in name)
  376. and name not in params_dict):
  377. continue
  378. param = params_dict[name]
  379. weight_loader = param.weight_loader
  380. weight_loader(param, loaded_weight, shard_id)
  381. break
  382. else:
  383. # Skip loading extra bias for GPTQ models.
  384. if name.endswith(".bias") and name not in params_dict:
  385. continue
  386. # Skip experts that are not assigned to this worker.
  387. if (("mlp.experts." in name or "mlp.shared_experts." in name)
  388. and name not in params_dict):
  389. continue
  390. param = params_dict[name]
  391. weight_loader = getattr(param, "weight_loader",
  392. default_weight_loader)
  393. weight_loader(param, loaded_weight)