qwen2.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/qwen2/modeling_qwen2.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 Qwen2 model compatible with HuggingFace weights."""
  25. from typing import Iterable, List, Optional, Tuple
  26. import torch
  27. from torch import nn
  28. from transformers import Qwen2Config
  29. from aphrodite.attention import Attention, AttentionMetadata
  30. from aphrodite.common.config import CacheConfig, LoRAConfig
  31. from aphrodite.common.sequence import SamplerOutput
  32. from aphrodite.distributed import get_tensor_model_parallel_world_size
  33. from aphrodite.modeling.layers.activation import SiluAndMul
  34. from aphrodite.modeling.layers.layernorm import RMSNorm
  35. from aphrodite.modeling.layers.linear import (MergedColumnParallelLinear,
  36. QKVParallelLinear,
  37. RowParallelLinear)
  38. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  39. from aphrodite.modeling.layers.rotary_embedding import get_rope
  40. from aphrodite.modeling.layers.sampler import Sampler
  41. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  42. ParallelLMHead, VocabParallelEmbedding)
  43. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  44. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  45. from aphrodite.quantization.base_config import QuantizationConfig
  46. class Qwen2MLP(nn.Module):
  47. def __init__(
  48. self,
  49. hidden_size: int,
  50. intermediate_size: int,
  51. hidden_act: str,
  52. quant_config: Optional[QuantizationConfig] = None,
  53. ) -> None:
  54. super().__init__()
  55. self.gate_up_proj = MergedColumnParallelLinear(
  56. hidden_size, [intermediate_size] * 2,
  57. bias=False,
  58. quant_config=quant_config)
  59. self.down_proj = RowParallelLinear(intermediate_size,
  60. hidden_size,
  61. bias=False,
  62. quant_config=quant_config)
  63. if hidden_act != "silu":
  64. raise ValueError(f"Unsupported activation: {hidden_act}. "
  65. "Only silu is supported for now.")
  66. self.act_fn = SiluAndMul()
  67. def forward(self, x):
  68. gate_up, _ = self.gate_up_proj(x)
  69. x = self.act_fn(gate_up)
  70. x, _ = self.down_proj(x)
  71. return x
  72. class Qwen2Attention(nn.Module):
  73. def __init__(self,
  74. hidden_size: int,
  75. num_heads: int,
  76. num_kv_heads: int,
  77. max_position: int = 4096 * 32,
  78. rope_theta: float = 10000,
  79. use_sliding_window: bool = False,
  80. cache_config: Optional[CacheConfig] = None,
  81. quant_config: Optional[QuantizationConfig] = None,
  82. sliding_window: Optional[int] = None,
  83. rope_scaling: Optional[Tuple] = None) -> None:
  84. super().__init__()
  85. self.hidden_size = hidden_size
  86. tp_size = get_tensor_model_parallel_world_size()
  87. self.total_num_heads = num_heads
  88. assert self.total_num_heads % tp_size == 0
  89. self.num_heads = self.total_num_heads // tp_size
  90. self.total_num_kv_heads = num_kv_heads
  91. if self.total_num_kv_heads >= tp_size:
  92. # Number of KV heads is greater than TP size, so we partition
  93. # the KV heads across multiple tensor parallel GPUs.
  94. assert self.total_num_kv_heads % tp_size == 0
  95. else:
  96. # Number of KV heads is less than TP size, so we replicate
  97. # the KV heads across multiple tensor parallel GPUs.
  98. assert tp_size % self.total_num_kv_heads == 0
  99. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  100. self.head_dim = hidden_size // self.total_num_heads
  101. self.q_size = self.num_heads * self.head_dim
  102. self.kv_size = self.num_kv_heads * self.head_dim
  103. self.scaling = self.head_dim**-0.5
  104. self.rope_theta = rope_theta
  105. self.sliding_window = sliding_window if use_sliding_window else None
  106. self.qkv_proj = QKVParallelLinear(
  107. hidden_size,
  108. self.head_dim,
  109. self.total_num_heads,
  110. self.total_num_kv_heads,
  111. bias=True,
  112. quant_config=quant_config,
  113. )
  114. self.o_proj = RowParallelLinear(
  115. self.total_num_heads * self.head_dim,
  116. hidden_size,
  117. bias=False,
  118. quant_config=quant_config,
  119. )
  120. self.rotary_emb = get_rope(
  121. self.head_dim,
  122. rotary_dim=self.head_dim,
  123. max_position=max_position,
  124. base=self.rope_theta,
  125. rope_scaling=rope_scaling,
  126. )
  127. self.attn = Attention(self.num_heads,
  128. self.head_dim,
  129. self.scaling,
  130. num_kv_heads=self.num_kv_heads,
  131. sliding_window=self.sliding_window,
  132. cache_config=cache_config,
  133. quant_config=quant_config)
  134. def forward(
  135. self,
  136. positions: torch.Tensor,
  137. hidden_states: torch.Tensor,
  138. kv_cache: torch.Tensor,
  139. attn_metadata: AttentionMetadata,
  140. ) -> torch.Tensor:
  141. qkv, _ = self.qkv_proj(hidden_states)
  142. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  143. q, k = self.rotary_emb(positions, q, k)
  144. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  145. output, _ = self.o_proj(attn_output)
  146. return output
  147. class Qwen2DecoderLayer(nn.Module):
  148. def __init__(
  149. self,
  150. config: Qwen2Config,
  151. layer_idx: int,
  152. cache_config: Optional[CacheConfig] = None,
  153. quant_config: Optional[QuantizationConfig] = None,
  154. ) -> None:
  155. super().__init__()
  156. self.hidden_size = config.hidden_size
  157. # Requires transformers > 4.32.0
  158. rope_theta = getattr(config, "rope_theta", 1000000)
  159. rope_scaling = getattr(config, "rope_scaling", None)
  160. use_sliding_window = (config.use_sliding_window
  161. and layer_idx < config.max_window_layers)
  162. self.self_attn = Qwen2Attention(
  163. hidden_size=self.hidden_size,
  164. num_heads=config.num_attention_heads,
  165. max_position=config.max_position_embeddings,
  166. num_kv_heads=config.num_key_value_heads,
  167. rope_theta=rope_theta,
  168. use_sliding_window=use_sliding_window,
  169. cache_config=cache_config,
  170. quant_config=quant_config,
  171. sliding_window=config.sliding_window,
  172. rope_scaling=rope_scaling)
  173. self.mlp = Qwen2MLP(
  174. hidden_size=self.hidden_size,
  175. intermediate_size=config.intermediate_size,
  176. hidden_act=config.hidden_act,
  177. quant_config=quant_config,
  178. )
  179. self.input_layernorm = RMSNorm(config.hidden_size,
  180. eps=config.rms_norm_eps)
  181. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  182. eps=config.rms_norm_eps)
  183. def forward(
  184. self,
  185. positions: torch.Tensor,
  186. hidden_states: torch.Tensor,
  187. kv_cache: torch.Tensor,
  188. attn_metadata: AttentionMetadata,
  189. residual: Optional[torch.Tensor],
  190. ) -> Tuple[torch.Tensor, torch.Tensor]:
  191. # Self Attention
  192. if residual is None:
  193. residual = hidden_states
  194. hidden_states = self.input_layernorm(hidden_states)
  195. else:
  196. hidden_states, residual = self.input_layernorm(
  197. hidden_states, residual)
  198. hidden_states = self.self_attn(
  199. positions=positions,
  200. hidden_states=hidden_states,
  201. kv_cache=kv_cache,
  202. attn_metadata=attn_metadata,
  203. )
  204. # Fully Connected
  205. hidden_states, residual = self.post_attention_layernorm(
  206. hidden_states, residual)
  207. hidden_states = self.mlp(hidden_states)
  208. return hidden_states, residual
  209. class Qwen2Model(nn.Module):
  210. def __init__(
  211. self,
  212. config: Qwen2Config,
  213. cache_config: Optional[CacheConfig] = None,
  214. quant_config: Optional[QuantizationConfig] = None,
  215. ) -> None:
  216. super().__init__()
  217. self.config = config
  218. self.padding_idx = config.pad_token_id
  219. self.vocab_size = config.vocab_size
  220. self.embed_tokens = VocabParallelEmbedding(
  221. config.vocab_size,
  222. config.hidden_size,
  223. )
  224. self.layers = nn.ModuleList([
  225. Qwen2DecoderLayer(config, layer_idx, cache_config, quant_config)
  226. for layer_idx in range(config.num_hidden_layers)
  227. ])
  228. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  229. def forward(
  230. self,
  231. input_ids: torch.Tensor,
  232. positions: torch.Tensor,
  233. kv_caches: List[torch.Tensor],
  234. attn_metadata: AttentionMetadata,
  235. ) -> torch.Tensor:
  236. hidden_states = self.embed_tokens(input_ids)
  237. residual = None
  238. for i in range(len(self.layers)):
  239. layer = self.layers[i]
  240. hidden_states, residual = layer(
  241. positions,
  242. hidden_states,
  243. kv_caches[i],
  244. attn_metadata,
  245. residual,
  246. )
  247. hidden_states, _ = self.norm(hidden_states, residual)
  248. return hidden_states
  249. class Qwen2ForCausalLM(nn.Module):
  250. packed_modules_mapping = {
  251. "qkv_proj": [
  252. "q_proj",
  253. "k_proj",
  254. "v_proj",
  255. ],
  256. "gate_up_proj": [
  257. "gate_proj",
  258. "up_proj",
  259. ],
  260. }
  261. # LoRA specific attributes
  262. supported_lora_modules = [
  263. "qkv_proj",
  264. "o_proj",
  265. "gate_up_proj",
  266. "down_proj",
  267. ]
  268. embedding_modules = {}
  269. embedding_padding_modules = []
  270. def __init__(
  271. self,
  272. config: Qwen2Config,
  273. cache_config: Optional[CacheConfig] = None,
  274. quant_config: Optional[QuantizationConfig] = None,
  275. lora_config: Optional[LoRAConfig] = None,
  276. ) -> None:
  277. del lora_config
  278. super().__init__()
  279. self.config = config
  280. self.quant_config = quant_config
  281. self.model = Qwen2Model(config, cache_config, quant_config)
  282. if config.tie_word_embeddings:
  283. self.lm_head_weight = self.model.embed_tokens.weight
  284. else:
  285. self.lm_head = ParallelLMHead(config.vocab_size,
  286. config.hidden_size)
  287. self.lm_head_weight = self.lm_head.weight
  288. self.logits_processor = LogitsProcessor(config.vocab_size)
  289. self.sampler = Sampler()
  290. def forward(
  291. self,
  292. input_ids: torch.Tensor,
  293. positions: torch.Tensor,
  294. kv_caches: List[torch.Tensor],
  295. attn_metadata: AttentionMetadata,
  296. ) -> torch.Tensor:
  297. hidden_states = self.model(input_ids, positions, kv_caches,
  298. attn_metadata)
  299. return hidden_states
  300. def compute_logits(self, hidden_states: torch.Tensor,
  301. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  302. logits = self.logits_processor(self.lm_head_weight, hidden_states,
  303. sampling_metadata)
  304. return logits
  305. def sample(
  306. self,
  307. logits: torch.Tensor,
  308. sampling_metadata: SamplingMetadata,
  309. ) -> Optional[SamplerOutput]:
  310. next_tokens = self.sampler(logits, sampling_metadata)
  311. return next_tokens
  312. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  313. stacked_params_mapping = [
  314. # (param_name, shard_name, shard_id)
  315. ("qkv_proj", "q_proj", "q"),
  316. ("qkv_proj", "k_proj", "k"),
  317. ("qkv_proj", "v_proj", "v"),
  318. ("gate_up_proj", "gate_proj", 0),
  319. ("gate_up_proj", "up_proj", 1),
  320. ]
  321. params_dict = dict(self.named_parameters(remove_duplicate=False))
  322. for name, loaded_weight in weights:
  323. if "rotary_emb.inv_freq" in name:
  324. continue
  325. if self.config.tie_word_embeddings and "lm_head.weight" in name:
  326. continue
  327. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  328. if weight_name not in name:
  329. continue
  330. name = name.replace(weight_name, param_name)
  331. # Skip loading extra bias for GPTQ models.
  332. if name.endswith(".bias") and name not in params_dict:
  333. continue
  334. param = params_dict[name]
  335. weight_loader = param.weight_loader
  336. weight_loader(param, loaded_weight, shard_id)
  337. break
  338. else:
  339. # Skip loading extra bias for GPTQ models.
  340. if name.endswith(".bias") and name not in params_dict:
  341. continue
  342. param = params_dict[name]
  343. weight_loader = getattr(param, "weight_loader",
  344. default_weight_loader)
  345. weight_loader(param, loaded_weight)