qwen2_moe.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/qwen2_moe/modeling_qwen2_moe.py
  4. # Copyright 2024 The Qwen team.
  5. # Copyright 2023 The vLLM team.
  6. # Copyright 2022 EleutherAI 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 Qwen2MoE model compatible with HuggingFace weights."""
  25. from typing import Any, Dict, Iterable, List, Optional, Tuple
  26. import torch
  27. import torch.nn.functional as F
  28. from torch import nn
  29. from transformers import PretrainedConfig
  30. from aphrodite.attention import Attention, AttentionMetadata
  31. from aphrodite.common.config import CacheConfig
  32. from aphrodite.common.sequence import IntermediateTensors, SamplerOutput
  33. from aphrodite.common.utils import print_warning_once
  34. from aphrodite.distributed import (get_tensor_model_parallel_world_size,
  35. tensor_model_parallel_all_reduce)
  36. from aphrodite.modeling.layers.activation import SiluAndMul
  37. from aphrodite.modeling.layers.fused_moe import FusedMoE
  38. from aphrodite.modeling.layers.layernorm import RMSNorm
  39. from aphrodite.modeling.layers.linear import (MergedColumnParallelLinear,
  40. QKVParallelLinear,
  41. ReplicatedLinear,
  42. RowParallelLinear)
  43. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  44. from aphrodite.modeling.layers.rotary_embedding import get_rope
  45. from aphrodite.modeling.layers.sampler import Sampler
  46. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  47. ParallelLMHead, VocabParallelEmbedding)
  48. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  49. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  50. from aphrodite.quantization.base_config import QuantizationConfig
  51. class Qwen2MoeMLP(nn.Module):
  52. def __init__(
  53. self,
  54. hidden_size: int,
  55. intermediate_size: int,
  56. hidden_act: str,
  57. quant_config: Optional[QuantizationConfig] = None,
  58. reduce_results: bool = True,
  59. ) -> None:
  60. super().__init__()
  61. self.gate_up_proj = MergedColumnParallelLinear(
  62. hidden_size, [intermediate_size] * 2,
  63. bias=False,
  64. quant_config=quant_config)
  65. self.down_proj = RowParallelLinear(intermediate_size,
  66. hidden_size,
  67. bias=False,
  68. quant_config=quant_config,
  69. reduce_results=reduce_results)
  70. if hidden_act != "silu":
  71. raise ValueError(f"Unsupported activation: {hidden_act}. "
  72. "Only silu is supported for now.")
  73. self.act_fn = SiluAndMul()
  74. def forward(self, x):
  75. gate_up, _ = self.gate_up_proj(x)
  76. x = self.act_fn(gate_up)
  77. x, _ = self.down_proj(x)
  78. return x
  79. class Qwen2MoeSparseMoeBlock(nn.Module):
  80. def __init__(
  81. self,
  82. config: PretrainedConfig,
  83. quant_config: Optional[QuantizationConfig] = None,
  84. ):
  85. super().__init__()
  86. self.tp_size = get_tensor_model_parallel_world_size()
  87. if self.tp_size > config.num_experts:
  88. raise ValueError(
  89. f"Tensor parallel size {self.tp_size} is greater than "
  90. f"the number of experts {config.num_experts}.")
  91. self.experts = FusedMoE(num_experts=config.num_experts,
  92. top_k=config.num_experts_per_tok,
  93. hidden_size=config.hidden_size,
  94. intermediate_size=config.moe_intermediate_size,
  95. reduce_results=False,
  96. renormalize=config.norm_topk_prob,
  97. quant_config=quant_config)
  98. self.gate = ReplicatedLinear(config.hidden_size,
  99. config.num_experts,
  100. bias=False,
  101. quant_config=None)
  102. if config.shared_expert_intermediate_size > 0:
  103. self.shared_expert = Qwen2MoeMLP(
  104. hidden_size=config.hidden_size,
  105. intermediate_size=config.shared_expert_intermediate_size,
  106. hidden_act=config.hidden_act,
  107. quant_config=quant_config,
  108. reduce_results=False,
  109. )
  110. else:
  111. self.shared_expert = None
  112. self.shared_expert_gate = torch.nn.Linear(config.hidden_size,
  113. 1,
  114. bias=False)
  115. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  116. # NOTE: hidden_states can have either 1D or 2D shape.
  117. orig_shape = hidden_states.shape
  118. hidden_dim = hidden_states.shape[-1]
  119. hidden_states = hidden_states.view(-1, hidden_dim)
  120. shared_output = None
  121. if self.shared_expert is not None:
  122. shared_output = self.shared_expert(hidden_states)
  123. if self.shared_expert_gate is not None:
  124. shared_output = F.sigmoid(
  125. self.shared_expert_gate(hidden_states)) * shared_output
  126. # router_logits: (num_tokens, n_experts)
  127. router_logits, _ = self.gate(hidden_states)
  128. final_hidden_states = self.experts(hidden_states=hidden_states,
  129. router_logits=router_logits)
  130. if shared_output is not None:
  131. final_hidden_states = final_hidden_states + shared_output
  132. if self.tp_size > 1:
  133. final_hidden_states = tensor_model_parallel_all_reduce(
  134. final_hidden_states)
  135. return final_hidden_states.view(orig_shape)
  136. class Qwen2MoeAttention(nn.Module):
  137. def __init__(
  138. self,
  139. hidden_size: int,
  140. num_heads: int,
  141. num_kv_heads: int,
  142. rope_theta: float = 10000,
  143. rope_scaling: Optional[Dict[str, Any]] = None,
  144. max_position_embeddings: int = 8192,
  145. cache_config: Optional[CacheConfig] = None,
  146. quant_config: Optional[QuantizationConfig] = None,
  147. ) -> None:
  148. super().__init__()
  149. self.hidden_size = hidden_size
  150. tp_size = get_tensor_model_parallel_world_size()
  151. self.total_num_heads = num_heads
  152. assert self.total_num_heads % tp_size == 0
  153. self.num_heads = self.total_num_heads // tp_size
  154. self.total_num_kv_heads = num_kv_heads
  155. if self.total_num_kv_heads >= tp_size:
  156. # Number of KV heads is greater than TP size, so we partition
  157. # the KV heads across multiple tensor parallel GPUs.
  158. assert self.total_num_kv_heads % tp_size == 0
  159. else:
  160. # Number of KV heads is less than TP size, so we replicate
  161. # the KV heads across multiple tensor parallel GPUs.
  162. assert tp_size % self.total_num_kv_heads == 0
  163. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  164. self.head_dim = hidden_size // self.total_num_heads
  165. self.q_size = self.num_heads * self.head_dim
  166. self.kv_size = self.num_kv_heads * self.head_dim
  167. self.scaling = self.head_dim**-0.5
  168. self.rope_theta = rope_theta
  169. self.max_position_embeddings = max_position_embeddings
  170. self.qkv_proj = QKVParallelLinear(
  171. hidden_size,
  172. self.head_dim,
  173. self.total_num_heads,
  174. self.total_num_kv_heads,
  175. bias=True,
  176. quant_config=quant_config,
  177. )
  178. self.o_proj = RowParallelLinear(
  179. self.total_num_heads * self.head_dim,
  180. hidden_size,
  181. bias=False,
  182. quant_config=quant_config,
  183. )
  184. self.rotary_emb = get_rope(
  185. self.head_dim,
  186. rotary_dim=self.head_dim,
  187. max_position=max_position_embeddings,
  188. base=rope_theta,
  189. rope_scaling=rope_scaling,
  190. )
  191. self.attn = Attention(self.num_heads,
  192. self.head_dim,
  193. self.scaling,
  194. num_kv_heads=self.num_kv_heads,
  195. cache_config=cache_config,
  196. quant_config=quant_config)
  197. def forward(
  198. self,
  199. positions: torch.Tensor,
  200. hidden_states: torch.Tensor,
  201. kv_cache: torch.Tensor,
  202. attn_metadata: AttentionMetadata,
  203. ) -> torch.Tensor:
  204. qkv, _ = self.qkv_proj(hidden_states)
  205. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  206. q, k = self.rotary_emb(positions, q, k)
  207. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  208. output, _ = self.o_proj(attn_output)
  209. return output
  210. class Qwen2MoeDecoderLayer(nn.Module):
  211. def __init__(
  212. self,
  213. config: PretrainedConfig,
  214. layer_idx: int,
  215. cache_config: Optional[CacheConfig] = None,
  216. quant_config: Optional[QuantizationConfig] = None,
  217. ) -> None:
  218. super().__init__()
  219. self.hidden_size = config.hidden_size
  220. rope_theta = getattr(config, "rope_theta", 10000)
  221. rope_scaling = getattr(config, "rope_scaling", None)
  222. max_position_embeddings = getattr(config, "max_position_embeddings",
  223. 8192)
  224. self.self_attn = Qwen2MoeAttention(
  225. hidden_size=self.hidden_size,
  226. num_heads=config.num_attention_heads,
  227. num_kv_heads=config.num_key_value_heads,
  228. rope_theta=rope_theta,
  229. rope_scaling=rope_scaling,
  230. max_position_embeddings=max_position_embeddings,
  231. cache_config=cache_config,
  232. quant_config=quant_config,
  233. )
  234. # Note: Qwen/Qwen2-57B-A14B-Instruct does not have
  235. # `mlp_only_layers` in the config.
  236. mlp_only_layers = ([] if not hasattr(config, "mlp_only_layers") else
  237. config.mlp_only_layers)
  238. if (layer_idx not in mlp_only_layers) and (
  239. config.num_experts > 0 and
  240. (layer_idx + 1) % config.decoder_sparse_step == 0):
  241. self.mlp = Qwen2MoeSparseMoeBlock(config=config,
  242. quant_config=quant_config)
  243. else:
  244. self.mlp = Qwen2MoeMLP(
  245. hidden_size=config.hidden_size,
  246. intermediate_size=config.intermediate_size,
  247. hidden_act=config.hidden_act,
  248. quant_config=quant_config,
  249. )
  250. self.input_layernorm = RMSNorm(config.hidden_size,
  251. eps=config.rms_norm_eps)
  252. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  253. eps=config.rms_norm_eps)
  254. def forward(
  255. self,
  256. positions: torch.Tensor,
  257. hidden_states: torch.Tensor,
  258. kv_cache: torch.Tensor,
  259. attn_metadata: AttentionMetadata,
  260. residual: Optional[torch.Tensor],
  261. ) -> torch.Tensor:
  262. # Self Attention
  263. if residual is None:
  264. residual = hidden_states
  265. hidden_states = self.input_layernorm(hidden_states)
  266. else:
  267. hidden_states, residual = self.input_layernorm(
  268. hidden_states, residual)
  269. hidden_states = self.self_attn(
  270. positions=positions,
  271. hidden_states=hidden_states,
  272. kv_cache=kv_cache,
  273. attn_metadata=attn_metadata,
  274. )
  275. # Fully Connected
  276. hidden_states, residual = self.post_attention_layernorm(
  277. hidden_states, residual)
  278. hidden_states = self.mlp(hidden_states)
  279. return hidden_states, residual
  280. class Qwen2MoeModel(nn.Module):
  281. def __init__(
  282. self,
  283. config: PretrainedConfig,
  284. cache_config: Optional[CacheConfig] = None,
  285. quant_config: Optional[QuantizationConfig] = None,
  286. ) -> None:
  287. super().__init__()
  288. self.padding_idx = config.pad_token_id
  289. self.vocab_size = config.vocab_size
  290. self.embed_tokens = VocabParallelEmbedding(
  291. config.vocab_size,
  292. config.hidden_size,
  293. )
  294. self.layers = nn.ModuleList([
  295. Qwen2MoeDecoderLayer(config,
  296. layer_idx,
  297. cache_config,
  298. quant_config=quant_config)
  299. for layer_idx in range(config.num_hidden_layers)
  300. ])
  301. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  302. def forward(
  303. self,
  304. input_ids: torch.Tensor,
  305. positions: torch.Tensor,
  306. kv_caches: List[torch.Tensor],
  307. attn_metadata: AttentionMetadata,
  308. ) -> torch.Tensor:
  309. hidden_states = self.embed_tokens(input_ids)
  310. residual = None
  311. for i in range(len(self.layers)):
  312. layer = self.layers[i]
  313. hidden_states, residual = layer(positions, hidden_states,
  314. kv_caches[i], attn_metadata,
  315. residual)
  316. hidden_states, _ = self.norm(hidden_states, residual)
  317. return hidden_states
  318. class Qwen2MoeForCausalLM(nn.Module):
  319. fall_back_to_pt_during_load = False
  320. def __init__(
  321. self,
  322. config: PretrainedConfig,
  323. cache_config: Optional[CacheConfig] = None,
  324. quant_config: Optional[QuantizationConfig] = None,
  325. ) -> None:
  326. super().__init__()
  327. self.config = config
  328. self.quant_config = quant_config
  329. self.model = Qwen2MoeModel(config, cache_config, quant_config)
  330. self.lm_head = ParallelLMHead(config.vocab_size,
  331. config.hidden_size,
  332. quant_config=quant_config)
  333. self.logits_processor = LogitsProcessor(config.vocab_size)
  334. self.sampler = Sampler()
  335. def forward(
  336. self,
  337. input_ids: torch.Tensor,
  338. positions: torch.Tensor,
  339. kv_caches: List[torch.Tensor],
  340. attn_metadata: AttentionMetadata,
  341. intermediate_tensors: Optional[IntermediateTensors] = None,
  342. ) -> torch.Tensor:
  343. hidden_states = self.model(input_ids, positions, kv_caches,
  344. attn_metadata)
  345. return hidden_states
  346. def compute_logits(self, hidden_states: torch.Tensor,
  347. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  348. logits = self.logits_processor(self.lm_head, hidden_states,
  349. sampling_metadata)
  350. return logits
  351. def sample(
  352. self,
  353. logits: Optional[torch.Tensor],
  354. sampling_metadata: SamplingMetadata,
  355. ) -> Optional[SamplerOutput]:
  356. next_tokens = self.sampler(logits, sampling_metadata)
  357. return next_tokens
  358. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  359. stacked_params_mapping = [
  360. # (param_name, shard_name, shard_id)
  361. ("qkv_proj", "q_proj", "q"),
  362. ("qkv_proj", "k_proj", "k"),
  363. ("qkv_proj", "v_proj", "v"),
  364. ("gate_up_proj", "gate_proj", 0),
  365. ("gate_up_proj", "up_proj", 1),
  366. ]
  367. # Params for weights, fp8 weight scales, fp8 activation scales
  368. # (param_name, weight_name, expert_id, shard_id)
  369. expert_params_mapping = FusedMoE.make_expert_params_mapping(
  370. ckpt_gate_proj_name="gate_proj",
  371. ckpt_down_proj_name="down_proj",
  372. ckpt_up_proj_name="up_proj",
  373. num_experts=self.config.num_experts)
  374. params_dict = dict(self.named_parameters())
  375. for name, loaded_weight in weights:
  376. if "rotary_emb.inv_freq" in name:
  377. continue
  378. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  379. # Skip non-stacked layers and experts (experts handled below).
  380. if weight_name not in name:
  381. continue
  382. # We have mlp.experts[0].gate_proj in the checkpoint.
  383. # Since we handle the experts below in expert_params_mapping,
  384. # we need to skip here BEFORE we update the name, otherwise
  385. # name will be updated to mlp.experts[0].gate_up_proj, which
  386. # will then be updated below in expert_params_mapping
  387. # for mlp.experts[0].gate_gate_up_proj, which breaks load.
  388. if "mlp.experts" in name:
  389. continue
  390. name = name.replace(weight_name, param_name)
  391. # Skip loading extra bias for GPTQ models.
  392. if name.endswith(".bias") and name not in params_dict:
  393. continue
  394. if name not in params_dict:
  395. continue
  396. param = params_dict[name]
  397. weight_loader = param.weight_loader
  398. weight_loader(param, loaded_weight, shard_id)
  399. break
  400. else:
  401. for mapping in expert_params_mapping:
  402. param_name, weight_name, expert_id, shard_id = mapping
  403. if weight_name not in name:
  404. continue
  405. name = name.replace(weight_name, param_name)
  406. param = params_dict[name]
  407. weight_loader = param.weight_loader
  408. weight_loader(param,
  409. loaded_weight,
  410. weight_name,
  411. shard_id=shard_id,
  412. expert_id=expert_id)
  413. break
  414. else:
  415. # Skip loading extra bias for GPTQ models.
  416. if name.endswith(".bias") and name not in params_dict:
  417. continue
  418. # Remapping the name of FP8 kv-scale.
  419. if name.endswith("kv_scale"):
  420. remapped_kv_scale_name = name.replace(
  421. ".kv_scale", ".attn.kv_scale")
  422. if remapped_kv_scale_name not in params_dict:
  423. print_warning_once(
  424. "Found kv scale in the checkpoint "
  425. f"(e.g. {name}), but not found the expected "
  426. f"name in the model "
  427. f"(e.g. {remapped_kv_scale_name}). "
  428. "kv-scale is not loaded.")
  429. continue
  430. else:
  431. name = remapped_kv_scale_name
  432. param = params_dict[name]
  433. weight_loader = getattr(param, "weight_loader",
  434. default_weight_loader)
  435. weight_loader(param, loaded_weight)