1
0

mistral.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 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 Mistral model compatible with HuggingFace weights."""
  25. from typing import List, Optional, Tuple
  26. import torch
  27. from torch import nn
  28. from transformers import MistralConfig
  29. from aphrodite.modeling.metadata import InputMetadata
  30. from aphrodite.modeling.layers.activation import SiluAndMul
  31. from aphrodite.modeling.layers.attention import PagedAttention
  32. from aphrodite.modeling.layers.layernorm import RMSNorm
  33. from aphrodite.modeling.layers.linear import (LinearMethodBase,
  34. MergedColumnParallelLinear,
  35. QKVParallelLinear,
  36. RowParallelLinear,
  37. ColumnParallelLinear)
  38. from aphrodite.modeling.layers.rotary_embedding import get_rope
  39. from aphrodite.modeling.layers.sampler import Sampler
  40. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  41. VocabParallelEmbedding, ParallelLMHead, DEFAULT_VOCAB_PADDING_SIZE)
  42. from aphrodite.modeling.megatron.parallel_state import (
  43. get_tensor_model_parallel_world_size)
  44. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  45. from aphrodite.modeling.hf_downloader import (default_weight_loader,
  46. hf_model_weights_iterator)
  47. from aphrodite.common.sequence import SamplerOutput
  48. from aphrodite.common.config import LoRAConfig
  49. KVCache = Tuple[torch.Tensor, torch.Tensor]
  50. class MistralMLP(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 MistralAttention(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. linear_method: Optional[LinearMethodBase] = None,
  102. sliding_window: Optional[int] = None) -> None:
  103. super().__init__()
  104. self.hidden_size = hidden_size
  105. tp_size = get_tensor_model_parallel_world_size()
  106. self.total_num_heads = num_heads
  107. assert self.total_num_heads % tp_size == 0
  108. self.num_heads = self.total_num_heads // tp_size
  109. self.total_num_kv_heads = num_kv_heads
  110. if self.total_num_kv_heads >= tp_size:
  111. # Number of KV heads is greater than TP size, so we partition
  112. # the KV heads across multiple tensor parallel GPUs.
  113. assert self.total_num_kv_heads % tp_size == 0
  114. else:
  115. # Number of KV heads is less than TP size, so we replicate
  116. # the KV heads across multiple tensor parallel GPUs.
  117. assert tp_size % self.total_num_kv_heads == 0
  118. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  119. self.head_dim = hidden_size // self.total_num_heads
  120. self.q_size = self.num_heads * self.head_dim
  121. self.kv_size = self.num_kv_heads * self.head_dim
  122. self.scaling = self.head_dim**-0.5
  123. self.rope_theta = rope_theta
  124. self.sliding_window = sliding_window
  125. if linear_method is not None and not linear_method.quant_config.merge_weight(
  126. ):
  127. self.merge_weight = False
  128. self.q_proj = ColumnParallelLinear(hidden_size,
  129. self.q_size,
  130. bias=False,
  131. linear_method=linear_method)
  132. self.k_proj = ColumnParallelLinear(hidden_size,
  133. self.kv_size,
  134. bias=False,
  135. linear_method=linear_method)
  136. self.v_proj = ColumnParallelLinear(hidden_size,
  137. self.kv_size,
  138. bias=False,
  139. linear_method=linear_method)
  140. else:
  141. self.merge_weight = True
  142. self.qkv_proj = QKVParallelLinear(
  143. hidden_size,
  144. self.head_dim,
  145. self.total_num_heads,
  146. self.total_num_kv_heads,
  147. bias=False,
  148. linear_method=linear_method,
  149. )
  150. self.o_proj = RowParallelLinear(
  151. self.total_num_heads * self.head_dim,
  152. hidden_size,
  153. bias=False,
  154. linear_method=linear_method,
  155. )
  156. is_neox_style = True if linear_method is None or linear_method.quant_config.rope_style(
  157. ) is None else linear_method.quant_config.rope_style()
  158. self.rotary_emb = get_rope(
  159. self.head_dim,
  160. rotary_dim=self.head_dim,
  161. max_position=max_position,
  162. base=self.rope_theta,
  163. is_neox_style=is_neox_style,
  164. )
  165. self.attn = PagedAttention(self.num_heads,
  166. self.head_dim,
  167. self.scaling,
  168. num_kv_heads=self.num_kv_heads,
  169. sliding_window=self.sliding_window)
  170. def forward(
  171. self,
  172. positions: torch.Tensor,
  173. hidden_states: torch.Tensor,
  174. kv_cache: KVCache,
  175. input_metadata: InputMetadata,
  176. ) -> torch.Tensor:
  177. if self.merge_weight:
  178. qkv, _ = self.qkv_proj(hidden_states)
  179. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size],
  180. dim=-1)
  181. else:
  182. q, _ = self.q_proj(hidden_states)
  183. k, _ = self.k_proj(hidden_states)
  184. v, _ = self.v_proj(hidden_states)
  185. q, k = self.rotary_emb(positions, q, k)
  186. k_cache, v_cache = kv_cache
  187. attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata)
  188. output, _ = self.o_proj(attn_output)
  189. return output
  190. class MistralDecoderLayer(nn.Module):
  191. def __init__(
  192. self,
  193. config: MistralConfig,
  194. linear_method: Optional[LinearMethodBase] = None,
  195. ) -> None:
  196. super().__init__()
  197. self.hidden_size = config.hidden_size
  198. # Requires transformers > 4.32.0
  199. rope_theta = getattr(config, "rope_theta", 10000)
  200. self.self_attn = MistralAttention(
  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. linear_method=linear_method,
  207. sliding_window=config.sliding_window)
  208. self.mlp = MistralMLP(
  209. hidden_size=self.hidden_size,
  210. intermediate_size=config.intermediate_size,
  211. hidden_act=config.hidden_act,
  212. linear_method=linear_method,
  213. )
  214. self.input_layernorm = RMSNorm(config.hidden_size,
  215. eps=config.rms_norm_eps)
  216. self.post_attention_layernorm = RMSNorm(config.hidden_size,
  217. eps=config.rms_norm_eps)
  218. def forward(
  219. self,
  220. positions: torch.Tensor,
  221. hidden_states: torch.Tensor,
  222. kv_cache: KVCache,
  223. input_metadata: InputMetadata,
  224. residual: Optional[torch.Tensor],
  225. ) -> Tuple[torch.Tensor, torch.Tensor]:
  226. # Self Attention
  227. if residual is None:
  228. residual = hidden_states
  229. hidden_states = self.input_layernorm(hidden_states)
  230. else:
  231. hidden_states, residual = self.input_layernorm(
  232. hidden_states, residual)
  233. hidden_states = self.self_attn(
  234. positions=positions,
  235. hidden_states=hidden_states,
  236. kv_cache=kv_cache,
  237. input_metadata=input_metadata,
  238. )
  239. # Fully Connected
  240. hidden_states, residual = self.post_attention_layernorm(
  241. hidden_states, residual)
  242. hidden_states = self.mlp(hidden_states)
  243. return hidden_states, residual
  244. class MistralModel(nn.Module):
  245. def __init__(
  246. self,
  247. config: MistralConfig,
  248. linear_method: Optional[LinearMethodBase] = None,
  249. lora_config: Optional[LoRAConfig] = None,
  250. ) -> None:
  251. super().__init__()
  252. self.config = config
  253. self.padding_idx = config.pad_token_id
  254. lora_vocab = (lora_config.lora_extra_vocab_size *
  255. (lora_config.max_loras or 1)) if lora_config else 0
  256. self.vocab_size = config.vocab_size + lora_vocab
  257. self.org_vocab_size = config.vocab_size
  258. self.embed_tokens = VocabParallelEmbedding(
  259. self.vocab_size,
  260. config.hidden_size,
  261. linear_method=linear_method,
  262. org_num_embeddings=config.vocab_size,
  263. )
  264. self.layers = nn.ModuleList([
  265. MistralDecoderLayer(config, linear_method)
  266. for _ in range(config.num_hidden_layers)
  267. ])
  268. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  269. def forward(
  270. self,
  271. input_ids: torch.Tensor,
  272. positions: torch.Tensor,
  273. kv_caches: List[KVCache],
  274. input_metadata: InputMetadata,
  275. ) -> torch.Tensor:
  276. hidden_states = self.embed_tokens(input_ids)
  277. residual = None
  278. for i in range(len(self.layers)):
  279. layer = self.layers[i]
  280. hidden_states, residual = layer(
  281. positions,
  282. hidden_states,
  283. kv_caches[i],
  284. input_metadata,
  285. residual,
  286. )
  287. hidden_states, _ = self.norm(hidden_states, residual)
  288. return hidden_states
  289. class MistralForCausalLM(nn.Module):
  290. supports_lora = True
  291. def __init__(
  292. self,
  293. config: MistralConfig,
  294. linear_method: Optional[LinearMethodBase] = None,
  295. lora_config: Optional[LoRAConfig] = None,
  296. ) -> None:
  297. super().__init__()
  298. self.config = config
  299. self.linear_method = linear_method
  300. self.model = MistralModel(config,
  301. linear_method,
  302. lora_config=lora_config)
  303. unpadded_vocab_size = config.vocab_size
  304. if lora_config:
  305. unpadded_vocab_size += lora_config.lora_extra_vocab_size
  306. self.lm_head = ParallelLMHead(
  307. unpadded_vocab_size,
  308. config.hidden_size,
  309. linear_method=linear_method,
  310. org_num_embeddings=config.vocab_size,
  311. padding_size=DEFAULT_VOCAB_PADDING_SIZE
  312. # We need bigger padding if using lora for kernel
  313. # compatibility
  314. if not lora_config else lora_config.lora_vocab_padding_size,
  315. )
  316. self.sampler = Sampler(unpadded_vocab_size, config.vocab_size)
  317. def forward(
  318. self,
  319. input_ids: torch.Tensor,
  320. positions: torch.Tensor,
  321. kv_caches: List[KVCache],
  322. input_metadata: InputMetadata,
  323. ) -> torch.Tensor:
  324. hidden_states = self.model(input_ids, positions, kv_caches,
  325. input_metadata)
  326. return hidden_states
  327. def sample(
  328. self,
  329. hidden_states: torch.Tensor,
  330. sampling_metadata: SamplingMetadata,
  331. ) -> Optional[SamplerOutput]:
  332. next_tokens = self.sampler(self.lm_head(hidden_states),
  333. sampling_metadata)
  334. return next_tokens
  335. def load_weights(self,
  336. model_name_or_path: str,
  337. cache_dir: Optional[str] = None,
  338. load_format: str = "auto",
  339. revision: Optional[str] = None):
  340. stacked_params_mapping = [
  341. # (param_name, shard_name, shard_id)
  342. ("qkv_proj", "q_proj", "q"),
  343. ("qkv_proj", "k_proj", "k"),
  344. ("qkv_proj", "v_proj", "v"),
  345. ("gate_up_proj", "gate_proj", 0),
  346. ("gate_up_proj", "up_proj", 1),
  347. ]
  348. if self.linear_method is not None and not self.linear_method.quant_config.merge_weight(
  349. ):
  350. stacked_params_mapping = []
  351. params_dict = dict(self.named_parameters())
  352. for name, loaded_weight in hf_model_weights_iterator(
  353. model_name_or_path, cache_dir, load_format, revision):
  354. if "rotary_emb.inv_freq" in name:
  355. continue
  356. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  357. if weight_name not in name:
  358. continue
  359. name = name.replace(weight_name, param_name)
  360. # Skip loading extra bias for GPTQ models.
  361. if name.endswith(".bias") and name not in params_dict:
  362. continue
  363. param = params_dict[name]
  364. weight_loader = param.weight_loader
  365. weight_loader(param, loaded_weight, shard_id)
  366. break
  367. else:
  368. # Skip loading extra bias for GPTQ models.
  369. if name.endswith(".bias") and name not in params_dict:
  370. continue
  371. param = params_dict[name]
  372. weight_loader = getattr(param, "weight_loader",
  373. default_weight_loader)
  374. weight_loader(param, loaded_weight)