qwen2.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 2023 The PygmalionAI team.
  5. # Copyright 2024 The Qwen team.
  6. # Copyright 2023 The vLLM team.
  7. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  8. #
  9. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  10. # and OPT implementations in this library. It has been modified from its
  11. # original forms to accommodate minor architectural differences compared
  12. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. """Inference-only Qwen2 model compatible with HuggingFace weights."""
  26. from typing import List, Optional, Tuple
  27. import torch
  28. from torch import nn
  29. from transformers import Qwen2Config
  30. from aphrodite.modeling.metadata import InputMetadata
  31. from aphrodite.modeling.layers.activation import SiluAndMul
  32. from aphrodite.modeling.layers.attention import PagedAttention
  33. from aphrodite.modeling.layers.layernorm import RMSNorm
  34. from aphrodite.modeling.layers.linear import (LinearMethodBase,
  35. ColumnParallelLinear,
  36. MergedColumnParallelLinear,
  37. QKVParallelLinear,
  38. RowParallelLinear)
  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. VocabParallelEmbedding, ParallelLMHead)
  43. from aphrodite.modeling.megatron.parallel_state import (
  44. get_tensor_model_parallel_world_size)
  45. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  46. from aphrodite.modeling.hf_downloader import (default_weight_loader,
  47. hf_model_weights_iterator)
  48. from aphrodite.common.sequence import SamplerOutput
  49. KVCache = Tuple[torch.Tensor, torch.Tensor]
  50. class Qwen2MLP(nn.Module):
  51. def __init__(
  52. self,
  53. hidden_size: int,
  54. intermediate_size: int,
  55. hidden_act: str,
  56. linear_method: Optional[LinearMethodBase] = None,
  57. ) -> None:
  58. super().__init__()
  59. if linear_method is not None and not linear_method.quant_config.merge_weight(
  60. ):
  61. self.merge_weight = False
  62. self.gate_proj = ColumnParallelLinear(hidden_size,
  63. intermediate_size,
  64. bias=False,
  65. linear_method=linear_method)
  66. self.up_proj = ColumnParallelLinear(hidden_size,
  67. intermediate_size,
  68. bias=False,
  69. linear_method=linear_method)
  70. else:
  71. self.merge_weight = True
  72. self.gate_up_proj = MergedColumnParallelLinear(
  73. hidden_size, [intermediate_size] * 2,
  74. bias=False,
  75. linear_method=linear_method)
  76. self.down_proj = RowParallelLinear(intermediate_size,
  77. hidden_size,
  78. bias=False,
  79. linear_method=linear_method)
  80. if hidden_act != "silu":
  81. raise ValueError(f"Unsupported activation: {hidden_act}. "
  82. "Only silu is supported for now.")
  83. self.act_fn = SiluAndMul()
  84. def forward(self, x):
  85. if self.merge_weight:
  86. gate_up, _ = self.gate_up_proj(x)
  87. else:
  88. up, _ = self.up_proj(x)
  89. gate, _ = self.gate_proj(x)
  90. gate_up = torch.cat([gate, up], dim=-1)
  91. x = self.act_fn(gate_up)
  92. x, _ = self.down_proj(x)
  93. return x
  94. class Qwen2Attention(nn.Module):
  95. def __init__(self,
  96. hidden_size: int,
  97. num_heads: int,
  98. num_kv_heads: int,
  99. max_position: int = 4096 * 32,
  100. rope_theta: float = 10000,
  101. use_sliding_window: bool = False,
  102. linear_method: Optional[LinearMethodBase] = None,
  103. sliding_window: Optional[int] = None) -> None:
  104. super().__init__()
  105. self.hidden_size = hidden_size
  106. tp_size = get_tensor_model_parallel_world_size()
  107. self.total_num_heads = num_heads
  108. assert self.total_num_heads % tp_size == 0
  109. self.num_heads = self.total_num_heads // tp_size
  110. self.total_num_kv_heads = num_kv_heads
  111. if self.total_num_kv_heads >= tp_size:
  112. # Number of KV heads is greater than TP size, so we partition
  113. # the KV heads across multiple tensor parallel GPUs.
  114. assert self.total_num_kv_heads % tp_size == 0
  115. else:
  116. # Number of KV heads is less than TP size, so we replicate
  117. # the KV heads across multiple tensor parallel GPUs.
  118. assert tp_size % self.total_num_kv_heads == 0
  119. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  120. self.head_dim = hidden_size // self.total_num_heads
  121. self.q_size = self.num_heads * self.head_dim
  122. self.kv_size = self.num_kv_heads * self.head_dim
  123. self.scaling = self.head_dim**-0.5
  124. self.rope_theta = rope_theta
  125. self.sliding_window = sliding_window if use_sliding_window else None
  126. if linear_method is not None and not linear_method.quant_config.merge_weight(
  127. ):
  128. self.merge_weight = False
  129. self.q_proj = ColumnParallelLinear(hidden_size,
  130. self.q_size,
  131. bias=True,
  132. linear_method=linear_method)
  133. self.k_proj = ColumnParallelLinear(hidden_size,
  134. self.kv_size,
  135. bias=True,
  136. linear_method=linear_method)
  137. self.v_proj = ColumnParallelLinear(hidden_size,
  138. self.kv_size,
  139. bias=True,
  140. linear_method=linear_method)
  141. else:
  142. self.merge_weight = True
  143. self.qkv_proj = QKVParallelLinear(
  144. hidden_size,
  145. self.head_dim,
  146. self.total_num_heads,
  147. self.total_num_kv_heads,
  148. bias=True,
  149. linear_method=linear_method,
  150. )
  151. self.o_proj = RowParallelLinear(
  152. self.total_num_heads * self.head_dim,
  153. hidden_size,
  154. bias=False,
  155. linear_method=linear_method,
  156. )
  157. self.rotary_emb = get_rope(
  158. self.head_dim,
  159. rotary_dim=self.head_dim,
  160. max_position=max_position,
  161. base=self.rope_theta,
  162. )
  163. self.attn = PagedAttention(self.num_heads,
  164. self.head_dim,
  165. self.scaling,
  166. num_kv_heads=self.num_kv_heads,
  167. sliding_window=self.sliding_window)
  168. def forward(
  169. self,
  170. positions: torch.Tensor,
  171. hidden_states: torch.Tensor,
  172. kv_cache: KVCache,
  173. input_metadata: InputMetadata,
  174. ) -> torch.Tensor:
  175. if self.merge_weight:
  176. qkv, _ = self.qkv_proj(hidden_states)
  177. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size],
  178. dim=-1)
  179. else:
  180. q, _ = self.q_proj(hidden_states)
  181. k, _ = self.k_proj(hidden_states)
  182. v, _ = self.v_proj(hidden_states)
  183. q, k = self.rotary_emb(positions, q, k)
  184. k_cache, v_cache = kv_cache
  185. attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata)
  186. output, _ = self.o_proj(attn_output)
  187. return output
  188. class Qwen2DecoderLayer(nn.Module):
  189. def __init__(
  190. self,
  191. config: Qwen2Config,
  192. layer_idx: int,
  193. linear_method: Optional[LinearMethodBase] = None,
  194. ) -> None:
  195. super().__init__()
  196. self.hidden_size = config.hidden_size
  197. # Requires transformers > 4.32.0
  198. rope_theta = getattr(config, "rope_theta", 1000000)
  199. use_sliding_window = config.use_sliding_window and layer_idx < config.max_window_layers
  200. self.self_attn = Qwen2Attention(
  201. hidden_size=self.hidden_size,
  202. num_heads=config.num_attention_heads,
  203. max_position=config.max_position_embeddings,
  204. num_kv_heads=config.num_key_value_heads,
  205. rope_theta=rope_theta,
  206. use_sliding_window=use_sliding_window,
  207. linear_method=linear_method,
  208. sliding_window=config.sliding_window)
  209. self.mlp = Qwen2MLP(
  210. hidden_size=self.hidden_size,
  211. intermediate_size=config.intermediate_size,
  212. hidden_act=config.hidden_act,
  213. linear_method=linear_method,
  214. )
  215. self.input_layernorm = RMSNorm(config.hidden_size,
  216. eps=config.rms_norm_eps)
  217. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  218. eps=config.rms_norm_eps)
  219. def forward(
  220. self,
  221. positions: torch.Tensor,
  222. hidden_states: torch.Tensor,
  223. kv_cache: KVCache,
  224. input_metadata: InputMetadata,
  225. residual: Optional[torch.Tensor],
  226. ) -> Tuple[torch.Tensor, torch.Tensor]:
  227. # Self Attention
  228. if residual is None:
  229. residual = hidden_states
  230. hidden_states = self.input_layernorm(hidden_states)
  231. else:
  232. hidden_states, residual = self.input_layernorm(
  233. hidden_states, residual)
  234. hidden_states = self.self_attn(
  235. positions=positions,
  236. hidden_states=hidden_states,
  237. kv_cache=kv_cache,
  238. input_metadata=input_metadata,
  239. )
  240. # Fully Connected
  241. hidden_states, residual = self.post_attention_layernorm(
  242. hidden_states, residual)
  243. hidden_states = self.mlp(hidden_states)
  244. return hidden_states, residual
  245. class Qwen2Model(nn.Module):
  246. def __init__(
  247. self,
  248. config: Qwen2Config,
  249. linear_method: Optional[LinearMethodBase] = None,
  250. ) -> None:
  251. super().__init__()
  252. self.config = config
  253. self.padding_idx = config.pad_token_id
  254. self.vocab_size = config.vocab_size
  255. self.embed_tokens = VocabParallelEmbedding(
  256. config.vocab_size,
  257. config.hidden_size,
  258. linear_method=linear_method,
  259. )
  260. self.layers = nn.ModuleList([
  261. Qwen2DecoderLayer(config, layer_idx, linear_method)
  262. for layer_idx in range(config.num_hidden_layers)
  263. ])
  264. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  265. def forward(
  266. self,
  267. input_ids: torch.Tensor,
  268. positions: torch.Tensor,
  269. kv_caches: List[KVCache],
  270. input_metadata: InputMetadata,
  271. ) -> torch.Tensor:
  272. hidden_states = self.embed_tokens(input_ids)
  273. residual = None
  274. for i in range(len(self.layers)):
  275. layer = self.layers[i]
  276. hidden_states, residual = layer(
  277. positions,
  278. hidden_states,
  279. kv_caches[i],
  280. input_metadata,
  281. residual,
  282. )
  283. hidden_states, _ = self.norm(hidden_states, residual)
  284. return hidden_states
  285. class Qwen2ForCausalLM(nn.Module):
  286. def __init__(
  287. self,
  288. config: Qwen2Config,
  289. linear_method: Optional[LinearMethodBase] = None,
  290. ) -> None:
  291. super().__init__()
  292. self.config = config
  293. self.linear_method = linear_method
  294. self.model = Qwen2Model(config, linear_method)
  295. self.lm_head = ParallelLMHead(
  296. config.vocab_size,
  297. config.hidden_size,
  298. linear_method=linear_method,
  299. )
  300. self.sampler = Sampler(config.vocab_size)
  301. def forward(
  302. self,
  303. input_ids: torch.Tensor,
  304. positions: torch.Tensor,
  305. kv_caches: List[KVCache],
  306. input_metadata: InputMetadata,
  307. ) -> torch.Tensor:
  308. hidden_states = self.model(input_ids, positions, kv_caches,
  309. input_metadata)
  310. return hidden_states
  311. def sample(
  312. self,
  313. hidden_states: torch.Tensor,
  314. sampling_metadata: SamplingMetadata,
  315. ) -> Optional[SamplerOutput]:
  316. next_tokens = self.sampler(self.lm_head(hidden_states),
  317. sampling_metadata)
  318. return next_tokens
  319. def load_weights(self,
  320. model_name_or_path: str,
  321. cache_dir: Optional[str] = None,
  322. load_format: str = "auto",
  323. revision: Optional[str] = None):
  324. stacked_params_mapping = [
  325. # (param_name, shard_name, shard_id)
  326. ("qkv_proj", "q_proj", "q"),
  327. ("qkv_proj", "k_proj", "k"),
  328. ("qkv_proj", "v_proj", "v"),
  329. ("gate_up_proj", "gate_proj", 0),
  330. ("gate_up_proj", "up_proj", 1),
  331. ]
  332. if self.linear_method is not None and not self.linear_method.quant_config.merge_weight(
  333. ):
  334. stacked_params_mapping = []
  335. params_dict = dict(self.named_parameters())
  336. for name, loaded_weight in hf_model_weights_iterator(
  337. model_name_or_path, cache_dir, load_format, revision):
  338. if "rotary_emb.inv_freq" in name:
  339. continue
  340. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  341. if weight_name not in name:
  342. continue
  343. name = name.replace(weight_name, param_name)
  344. # Skip loading extra bias for GPTQ models.
  345. if name.endswith(".bias") and name not in params_dict:
  346. continue
  347. param = params_dict[name]
  348. weight_loader = param.weight_loader
  349. weight_loader(param, loaded_weight, shard_id)
  350. break
  351. else:
  352. # Skip loading extra bias for GPTQ models.
  353. if name.endswith(".bias") and name not in params_dict:
  354. continue
  355. param = params_dict[name]
  356. weight_loader = getattr(param, "weight_loader",
  357. default_weight_loader)
  358. weight_loader(param, loaded_weight)