xverse.py 13 KB

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