deepseek_v2.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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 PygmalionAI team.
  5. # Copyright 2023 The vLLM team.
  6. # Copyright 2023 DeepSeek-AI and the HuggingFace Inc. team. All rights reserved.
  7. #
  8. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  9. # and OPT implementations in this library. It has been modified from its
  10. # original forms to accommodate minor architectural differences compared
  11. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  12. #
  13. # Licensed under the Apache License, Version 2.0 (the "License");
  14. # you may not use this file except in compliance with the License.
  15. # You may obtain a copy of the License at
  16. #
  17. # http://www.apache.org/licenses/LICENSE-2.0
  18. #
  19. # Unless required by applicable law or agreed to in writing, software
  20. # distributed under the License is distributed on an "AS IS" BASIS,
  21. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  22. # See the License for the specific language governing permissions and
  23. # limitations under the License.
  24. """Inference-only DeepseekV2 model."""
  25. from typing import Any, Dict, Iterable, List, Optional, Tuple
  26. import torch
  27. from torch import nn
  28. from transformers import PretrainedConfig
  29. from aphrodite.attention import Attention, AttentionMetadata
  30. from aphrodite.common.config import CacheConfig
  31. from aphrodite.common.sequence import IntermediateTensors
  32. from aphrodite.distributed import (get_tensor_model_parallel_world_size,
  33. tensor_model_parallel_all_reduce)
  34. from aphrodite.modeling.layers.activation import SiluAndMul
  35. from aphrodite.modeling.layers.fused_moe import FusedMoE
  36. from aphrodite.modeling.layers.layernorm import RMSNorm
  37. from aphrodite.modeling.layers.linear import (ColumnParallelLinear,
  38. MergedColumnParallelLinear,
  39. ReplicatedLinear,
  40. RowParallelLinear)
  41. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  42. from aphrodite.modeling.layers.rotary_embedding import get_rope
  43. from aphrodite.modeling.layers.sampler import Sampler, SamplerOutput
  44. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  45. ParallelLMHead, VocabParallelEmbedding)
  46. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  47. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  48. from aphrodite.quantization.base_config import QuantizationConfig
  49. class DeepseekV2MLP(nn.Module):
  50. def __init__(
  51. self,
  52. hidden_size: int,
  53. intermediate_size: int,
  54. hidden_act: str,
  55. quant_config: Optional[QuantizationConfig] = None,
  56. reduce_results: bool = True,
  57. ) -> None:
  58. super().__init__()
  59. self.gate_up_proj = MergedColumnParallelLinear(
  60. hidden_size, [intermediate_size] * 2,
  61. bias=False,
  62. quant_config=quant_config)
  63. self.down_proj = RowParallelLinear(intermediate_size,
  64. hidden_size,
  65. bias=False,
  66. quant_config=quant_config,
  67. reduce_results=reduce_results)
  68. if hidden_act != "silu":
  69. raise ValueError(f"Unsupported activation: {hidden_act}. "
  70. "Only silu is supported for now.")
  71. self.act_fn = SiluAndMul()
  72. def forward(self, x):
  73. gate_up, _ = self.gate_up_proj(x)
  74. x = self.act_fn(gate_up)
  75. x, _ = self.down_proj(x)
  76. return x
  77. class DeepseekV2MoE(nn.Module):
  78. def __init__(
  79. self,
  80. config: PretrainedConfig,
  81. quant_config: Optional[QuantizationConfig] = None,
  82. ):
  83. super().__init__()
  84. self.tp_size = get_tensor_model_parallel_world_size()
  85. self.routed_scaling_factor = config.routed_scaling_factor
  86. self.n_shared_experts = config.n_shared_experts
  87. self.routed_scaling_factor = config.routed_scaling_factor
  88. if self.tp_size > config.n_routed_experts:
  89. raise ValueError(
  90. f"Tensor parallel size {self.tp_size} is greater than "
  91. f"the number of experts {config.n_routed_experts}.")
  92. if config.hidden_act != "silu":
  93. raise ValueError(f"Unsupported activation: {config.hidden_act}. "
  94. "Only silu is supported for now.")
  95. self.experts = FusedMoE(num_experts=config.n_routed_experts,
  96. top_k=config.num_experts_per_tok,
  97. hidden_size=config.hidden_size,
  98. intermediate_size=config.moe_intermediate_size,
  99. reduce_results=False,
  100. renormalize=config.norm_topk_prob,
  101. quant_config=quant_config,
  102. use_grouped_topk=True,
  103. num_expert_group=config.n_group,
  104. topk_group=config.topk_group)
  105. self.gate = ReplicatedLinear(config.hidden_size,
  106. config.n_routed_experts,
  107. bias=False,
  108. quant_config=None)
  109. if config.n_shared_experts is not None:
  110. intermediate_size = (config.moe_intermediate_size *
  111. config.n_shared_experts)
  112. self.shared_experts = DeepseekV2MLP(
  113. hidden_size=config.hidden_size,
  114. intermediate_size=intermediate_size,
  115. hidden_act=config.hidden_act,
  116. quant_config=quant_config,
  117. reduce_results=False,
  118. )
  119. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  120. num_tokens, hidden_dim = hidden_states.shape
  121. hidden_states = hidden_states.view(-1, hidden_dim)
  122. if self.n_shared_experts is not None:
  123. shared_output = self.shared_experts(hidden_states)
  124. # router_logits: (num_tokens, n_experts)
  125. router_logits, _ = self.gate(hidden_states)
  126. final_hidden_states = self.experts(
  127. hidden_states=hidden_states,
  128. router_logits=router_logits) * self.routed_scaling_factor
  129. if shared_output is not None:
  130. final_hidden_states = final_hidden_states + shared_output
  131. if self.tp_size > 1:
  132. final_hidden_states = tensor_model_parallel_all_reduce(
  133. final_hidden_states)
  134. return final_hidden_states.view(num_tokens, hidden_dim)
  135. def yarn_get_mscale(scale: float = 1, mscale: float = 1) -> float:
  136. import math
  137. if scale <= 1:
  138. return 1.0
  139. return 0.1 * mscale * math.log(scale) + 1.0
  140. class DeepseekV2Attention(nn.Module):
  141. def __init__(
  142. self,
  143. config: PretrainedConfig,
  144. hidden_size: int,
  145. num_heads: int,
  146. qk_nope_head_dim: int,
  147. qk_rope_head_dim: int,
  148. v_head_dim: int,
  149. q_lora_rank: int,
  150. kv_lora_rank: int,
  151. rope_theta: float = 10000,
  152. rope_scaling: Optional[Dict[str, Any]] = None,
  153. max_position_embeddings: int = 8192,
  154. cache_config: Optional[CacheConfig] = None,
  155. quant_config: Optional[QuantizationConfig] = None,
  156. layer_idx=None,
  157. ) -> None:
  158. super().__init__()
  159. self.layer_idx = layer_idx
  160. self.hidden_size = hidden_size
  161. self.qk_nope_head_dim = qk_nope_head_dim
  162. self.qk_rope_head_dim = qk_rope_head_dim
  163. self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
  164. self.v_head_dim = v_head_dim
  165. self.q_lora_rank = q_lora_rank
  166. self.kv_lora_rank = kv_lora_rank
  167. self.num_heads = num_heads
  168. tp_size = get_tensor_model_parallel_world_size()
  169. assert num_heads % tp_size == 0
  170. self.num_local_heads = num_heads // tp_size
  171. self.scaling = self.qk_head_dim**-0.5
  172. self.rope_theta = rope_theta
  173. self.max_position_embeddings = max_position_embeddings
  174. if self.q_lora_rank is not None:
  175. self.q_a_proj = ReplicatedLinear(self.hidden_size,
  176. self.q_lora_rank,
  177. bias=False,
  178. quant_config=quant_config)
  179. self.q_a_layernorm = RMSNorm(self.q_lora_rank,
  180. eps=config.rms_norm_eps)
  181. self.q_b_proj = ColumnParallelLinear(q_lora_rank,
  182. self.num_heads *
  183. self.qk_head_dim,
  184. bias=False,
  185. quant_config=quant_config)
  186. else:
  187. self.q_proj = ColumnParallelLinear(self.hidden_size,
  188. self.num_heads *
  189. self.qk_head_dim,
  190. bias=False,
  191. quant_config=quant_config)
  192. self.kv_a_proj_with_mqa = ReplicatedLinear(self.hidden_size,
  193. self.kv_lora_rank +
  194. self.qk_rope_head_dim,
  195. bias=False,
  196. quant_config=quant_config)
  197. self.kv_a_layernorm = RMSNorm(self.kv_lora_rank,
  198. eps=config.rms_norm_eps)
  199. self.kv_b_proj = ColumnParallelLinear(
  200. self.kv_lora_rank,
  201. self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
  202. bias=False,
  203. quant_config=quant_config)
  204. # O projection.
  205. self.o_proj = RowParallelLinear(self.num_heads * self.v_head_dim,
  206. self.hidden_size,
  207. bias=False,
  208. quant_config=quant_config)
  209. rope_scaling['type'] = 'deepseek_yarn'
  210. self.rotary_emb = get_rope(qk_rope_head_dim,
  211. rotary_dim=qk_rope_head_dim,
  212. max_position=max_position_embeddings,
  213. base=rope_theta,
  214. rope_scaling=rope_scaling,
  215. is_neox_style=False)
  216. if rope_scaling:
  217. mscale_all_dim = rope_scaling.get("mscale_all_dim", False)
  218. scaling_factor = rope_scaling["factor"]
  219. mscale = yarn_get_mscale(scaling_factor, float(mscale_all_dim))
  220. self.scaling = self.scaling * mscale * mscale
  221. # self.attn = Attention(self.num_heads,
  222. # self.qk_head_dim,
  223. # self.scaling,
  224. # num_kv_heads=self.num_heads)
  225. # TODO, support head_size 192
  226. self.attn = Attention(self.num_local_heads,
  227. 256,
  228. self.scaling,
  229. num_kv_heads=self.num_local_heads,
  230. cache_config=cache_config,
  231. quant_config=quant_config)
  232. def forward(
  233. self,
  234. positions: torch.Tensor,
  235. hidden_states: torch.Tensor,
  236. kv_cache: torch.Tensor,
  237. attn_metadata: AttentionMetadata,
  238. ) -> torch.Tensor:
  239. if self.q_lora_rank is not None:
  240. q = self.q_a_proj(hidden_states)[0]
  241. q = self.q_a_layernorm(q)
  242. q = self.q_b_proj(q)[0].view(-1, self.num_local_heads,
  243. self.qk_head_dim)
  244. else:
  245. q = self.q_proj(hidden_states)[0].view(-1, self.num_local_heads,
  246. self.qk_head_dim)
  247. q_nope, q_pe = q.split([self.qk_nope_head_dim, self.qk_rope_head_dim],
  248. dim=-1)
  249. latent_cache = self.kv_a_proj_with_mqa(hidden_states)[0]
  250. kv_a, _ = latent_cache.split(
  251. [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
  252. latent_cache = latent_cache.unsqueeze(1)
  253. kv_a = self.kv_a_layernorm(kv_a.contiguous())
  254. kv = self.kv_b_proj(kv_a)[0]
  255. kv = kv.view(-1, self.num_local_heads,
  256. self.qk_nope_head_dim + self.v_head_dim)
  257. k_nope, v = kv.split([self.qk_nope_head_dim, self.v_head_dim], dim=-1)
  258. k_pe = latent_cache[:, :, self.kv_lora_rank:]
  259. q_pe, k_pe = self.rotary_emb(positions, q_pe, k_pe)
  260. q[..., self.qk_nope_head_dim:] = q_pe
  261. k = torch.empty_like(q)
  262. k[..., :self.qk_nope_head_dim] = k_nope
  263. k[..., self.qk_nope_head_dim:] = k_pe
  264. q = torch.nn.functional.pad(q, [0, 256 - self.qk_head_dim],
  265. value=0).view(-1,
  266. self.num_local_heads * 256)
  267. k = torch.nn.functional.pad(k, [0, 256 - self.qk_head_dim],
  268. value=0).view(-1,
  269. self.num_local_heads * 256)
  270. v = torch.nn.functional.pad(v, [0, 256 - self.v_head_dim],
  271. value=0).view(-1,
  272. self.num_local_heads * 256)
  273. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  274. attn_output = attn_output.view(
  275. -1, self.num_local_heads, 256)[..., :self.v_head_dim].reshape(
  276. -1, self.num_local_heads * self.v_head_dim)
  277. output, _ = self.o_proj(attn_output)
  278. return output
  279. class DeepseekV2DecoderLayer(nn.Module):
  280. def __init__(
  281. self,
  282. config: PretrainedConfig,
  283. layer_idx: int,
  284. cache_config: Optional[CacheConfig] = None,
  285. quant_config: Optional[QuantizationConfig] = None,
  286. ) -> None:
  287. super().__init__()
  288. self.hidden_size = config.hidden_size
  289. rope_theta = getattr(config, "rope_theta", 10000)
  290. rope_scaling = getattr(config, "rope_scaling", None)
  291. max_position_embeddings = getattr(config, "max_position_embeddings",
  292. 8192)
  293. self.self_attn = DeepseekV2Attention(
  294. config=config,
  295. hidden_size=self.hidden_size,
  296. num_heads=config.num_attention_heads,
  297. qk_nope_head_dim=config.qk_nope_head_dim,
  298. qk_rope_head_dim=config.qk_rope_head_dim,
  299. v_head_dim=config.v_head_dim,
  300. q_lora_rank=config.q_lora_rank
  301. if hasattr(config, "q_lora_rank") else None,
  302. kv_lora_rank=config.kv_lora_rank,
  303. rope_theta=rope_theta,
  304. rope_scaling=rope_scaling,
  305. max_position_embeddings=max_position_embeddings,
  306. cache_config=cache_config,
  307. quant_config=quant_config,
  308. layer_idx=layer_idx,
  309. )
  310. if (config.n_routed_experts is not None
  311. and layer_idx >= config.first_k_dense_replace
  312. and layer_idx % config.moe_layer_freq == 0):
  313. self.mlp = DeepseekV2MoE(config=config, quant_config=quant_config)
  314. else:
  315. self.mlp = DeepseekV2MLP(
  316. hidden_size=config.hidden_size,
  317. intermediate_size=config.intermediate_size,
  318. hidden_act=config.hidden_act,
  319. quant_config=quant_config,
  320. )
  321. self.input_layernorm = RMSNorm(config.hidden_size,
  322. eps=config.rms_norm_eps)
  323. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  324. eps=config.rms_norm_eps)
  325. def forward(
  326. self,
  327. positions: torch.Tensor,
  328. hidden_states: torch.Tensor,
  329. kv_cache: torch.Tensor,
  330. attn_metadata: AttentionMetadata,
  331. residual: Optional[torch.Tensor],
  332. ) -> torch.Tensor:
  333. # Self Attention
  334. if residual is None:
  335. residual = hidden_states
  336. hidden_states = self.input_layernorm(hidden_states)
  337. else:
  338. hidden_states, residual = self.input_layernorm(
  339. hidden_states, residual)
  340. hidden_states = self.self_attn(
  341. positions=positions,
  342. hidden_states=hidden_states,
  343. kv_cache=kv_cache,
  344. attn_metadata=attn_metadata,
  345. )
  346. # Fully Connected
  347. hidden_states, residual = self.post_attention_layernorm(
  348. hidden_states, residual)
  349. hidden_states = self.mlp(hidden_states)
  350. return hidden_states, residual
  351. class DeepseekV2Model(nn.Module):
  352. fall_back_to_pt_during_load = False
  353. def __init__(
  354. self,
  355. config: PretrainedConfig,
  356. cache_config: Optional[CacheConfig] = None,
  357. quant_config: Optional[QuantizationConfig] = None,
  358. ) -> None:
  359. super().__init__()
  360. self.padding_idx = config.pad_token_id
  361. self.vocab_size = config.vocab_size
  362. self.embed_tokens = VocabParallelEmbedding(
  363. config.vocab_size,
  364. config.hidden_size,
  365. )
  366. self.layers = nn.ModuleList([
  367. DeepseekV2DecoderLayer(config,
  368. layer_idx,
  369. cache_config=cache_config,
  370. quant_config=quant_config)
  371. for layer_idx in range(config.num_hidden_layers)
  372. ])
  373. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  374. def forward(
  375. self,
  376. input_ids: torch.Tensor,
  377. positions: torch.Tensor,
  378. kv_caches: List[torch.Tensor],
  379. attn_metadata: AttentionMetadata,
  380. ) -> torch.Tensor:
  381. hidden_states = self.embed_tokens(input_ids)
  382. residual = None
  383. for i in range(len(self.layers)):
  384. layer = self.layers[i]
  385. hidden_states, residual = layer(positions, hidden_states,
  386. kv_caches[i], attn_metadata,
  387. residual)
  388. hidden_states, _ = self.norm(hidden_states, residual)
  389. return hidden_states
  390. class DeepseekV2ForCausalLM(nn.Module):
  391. def __init__(
  392. self,
  393. config: PretrainedConfig,
  394. cache_config: Optional[CacheConfig] = None,
  395. quant_config: Optional[QuantizationConfig] = None,
  396. ) -> None:
  397. super().__init__()
  398. self.config = config
  399. self.quant_config = quant_config
  400. self.model = DeepseekV2Model(config, cache_config, quant_config)
  401. self.lm_head = ParallelLMHead(config.vocab_size,
  402. config.hidden_size,
  403. quant_config=quant_config)
  404. self.logits_processor = LogitsProcessor(config.vocab_size)
  405. self.sampler = Sampler()
  406. def forward(
  407. self,
  408. input_ids: torch.Tensor,
  409. positions: torch.Tensor,
  410. kv_caches: List[torch.Tensor],
  411. attn_metadata: AttentionMetadata,
  412. intermediate_tensors: Optional[IntermediateTensors] = None,
  413. ) -> torch.Tensor:
  414. hidden_states = self.model(input_ids, positions, kv_caches,
  415. attn_metadata)
  416. return hidden_states
  417. def compute_logits(
  418. self,
  419. hidden_states: torch.Tensor,
  420. sampling_metadata: SamplingMetadata,
  421. ) -> Optional[torch.Tensor]:
  422. logits = self.logits_processor(self.lm_head, hidden_states,
  423. sampling_metadata)
  424. return logits
  425. def sample(
  426. self,
  427. logits: Optional[torch.Tensor],
  428. sampling_metadata: SamplingMetadata,
  429. ) -> Optional[SamplerOutput]:
  430. next_tokens = self.sampler(logits, sampling_metadata)
  431. return next_tokens
  432. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  433. stacked_params_mapping = [
  434. # (param_name, shard_name, shard_id)
  435. ("gate_up_proj", "gate_proj", 0),
  436. ("gate_up_proj", "up_proj", 1),
  437. ]
  438. # Params for weights, fp8 weight scales, fp8 activation scales
  439. # (param_name, weight_name, expert_id, shard_id)
  440. expert_params_mapping = FusedMoE.make_expert_params_mapping(
  441. ckpt_gate_proj_name="gate_proj",
  442. ckpt_down_proj_name="down_proj",
  443. ckpt_up_proj_name="up_proj",
  444. num_experts=self.config.n_routed_experts)
  445. params_dict = dict(self.named_parameters())
  446. for name, loaded_weight in weights:
  447. if "rotary_emb.inv_freq" in name:
  448. continue
  449. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  450. # Skip non-stacked layers and experts (experts handled below).
  451. if weight_name not in name:
  452. continue
  453. # We have mlp.experts[0].gate_proj in the checkpoint.
  454. # Since we handle the experts below in expert_params_mapping,
  455. # we need to skip here BEFORE we update the name, otherwise
  456. # name will be updated to mlp.experts[0].gate_up_proj, which
  457. # will then be updated below in expert_params_mapping
  458. # for mlp.experts[0].gate_gate_up_proj, which breaks load.
  459. if (("mlp.experts." in name) and name not in params_dict):
  460. continue
  461. name = name.replace(weight_name, param_name)
  462. # Skip loading extra bias for GPTQ models.
  463. if name.endswith(".bias") and name not in params_dict:
  464. continue
  465. param = params_dict[name]
  466. weight_loader = param.weight_loader
  467. weight_loader(param, loaded_weight, shard_id)
  468. break
  469. else:
  470. for mapping in expert_params_mapping:
  471. param_name, weight_name, expert_id, shard_id = mapping
  472. if weight_name not in name:
  473. continue
  474. name = name.replace(weight_name, param_name)
  475. param = params_dict[name]
  476. weight_loader = param.weight_loader
  477. weight_loader(param,
  478. loaded_weight,
  479. name,
  480. shard_id=shard_id,
  481. expert_id=expert_id)
  482. break
  483. else:
  484. # Skip loading extra bias for GPTQ models.
  485. if name.endswith(".bias") and name not in params_dict:
  486. continue
  487. param = params_dict[name]
  488. weight_loader = getattr(param, "weight_loader",
  489. default_weight_loader)
  490. weight_loader(param, loaded_weight)