yi.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 Yi model compatible with HuggingFace weights."""
  25. from typing import Any, Dict, List, Optional, Tuple
  26. import torch
  27. from torch import nn
  28. from aphrodite.transformers_utils.configs.yi import YiConfig
  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)
  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. KVCache = Tuple[torch.Tensor, torch.Tensor]
  49. class YiMLP(nn.Module):
  50. def __init__(
  51. self,
  52. hidden_size: int,
  53. intermediate_size: int,
  54. hidden_act: str,
  55. linear_method: Optional[LinearMethodBase] = None,
  56. ) -> None:
  57. super().__init__()
  58. if linear_method is not None and not linear_method.quant_config.merge_weight(
  59. ):
  60. self.merge_weight = False
  61. self.gate_proj = ColumnParallelLinear(hidden_size,
  62. intermediate_size,
  63. bias=False,
  64. linear_method=linear_method)
  65. self.up_proj = ColumnParallelLinear(hidden_size,
  66. intermediate_size,
  67. bias=False,
  68. linear_method=linear_method)
  69. else:
  70. self.merge_weight = True
  71. self.gate_up_proj = MergedColumnParallelLinear(
  72. hidden_size, [intermediate_size] * 2,
  73. bias=False,
  74. linear_method=linear_method)
  75. self.down_proj = RowParallelLinear(intermediate_size,
  76. hidden_size,
  77. bias=False,
  78. linear_method=linear_method)
  79. if hidden_act != "silu":
  80. raise ValueError(f"Unsupported activation: {hidden_act}. "
  81. "Only silu is supported for now.")
  82. self.act_fn = SiluAndMul()
  83. def forward(self, x):
  84. if self.merge_weight:
  85. gate_up, _ = self.gate_up_proj(x)
  86. else:
  87. up, _ = self.up_proj(x)
  88. gate, _ = self.gate_proj(x)
  89. gate_up = torch.cat([gate, up], dim=-1)
  90. x = self.act_fn(gate_up)
  91. x, _ = self.down_proj(x)
  92. return x
  93. class YiAttention(nn.Module):
  94. def __init__(
  95. self,
  96. hidden_size: int,
  97. num_heads: int,
  98. num_kv_heads: int,
  99. rope_theta: float = 10000,
  100. rope_scaling: Optional[Dict[str, Any]] = None,
  101. max_position_embeddings: int = 8192,
  102. linear_method: Optional[LinearMethodBase] = None,
  103. ) -> 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.max_position_embeddings = max_position_embeddings
  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=False,
  132. linear_method=linear_method)
  133. self.k_proj = ColumnParallelLinear(hidden_size,
  134. self.kv_size,
  135. bias=False,
  136. linear_method=linear_method)
  137. self.v_proj = ColumnParallelLinear(hidden_size,
  138. self.kv_size,
  139. bias=False,
  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=False,
  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. is_neox_style = True if linear_method is None or linear_method.quant_config.rope_style(
  158. ) is None else linear_method.quant_config.rope_style()
  159. self.rotary_emb = get_rope(
  160. self.head_dim,
  161. rotary_dim=self.head_dim,
  162. max_position=max_position_embeddings,
  163. base=self.rope_theta,
  164. rope_scaling=rope_scaling,
  165. is_neox_style=is_neox_style,
  166. )
  167. self.attn = PagedAttention(self.num_heads,
  168. self.head_dim,
  169. self.scaling,
  170. num_kv_heads=self.num_kv_heads)
  171. def forward(
  172. self,
  173. positions: torch.Tensor,
  174. hidden_states: torch.Tensor,
  175. kv_cache: KVCache,
  176. input_metadata: InputMetadata,
  177. ) -> torch.Tensor:
  178. if self.merge_weight:
  179. qkv, _ = self.qkv_proj(hidden_states)
  180. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size],
  181. dim=-1)
  182. else:
  183. q, _ = self.q_proj(hidden_states)
  184. k, _ = self.k_proj(hidden_states)
  185. v, _ = self.v_proj(hidden_states)
  186. q, k = self.rotary_emb(positions, q, k)
  187. k_cache, v_cache = kv_cache
  188. attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata)
  189. output, _ = self.o_proj(attn_output)
  190. return output
  191. class YiDecoderLayer(nn.Module):
  192. def __init__(
  193. self,
  194. config: YiConfig,
  195. linear_method: Optional[LinearMethodBase] = None,
  196. ) -> None:
  197. super().__init__()
  198. self.hidden_size = config.hidden_size
  199. rope_theta = getattr(config, "rope_theta", 10000)
  200. rope_scaling = getattr(config, "rope_scaling", None)
  201. max_position_embeddings = getattr(config, "max_position_embeddings",
  202. 8192)
  203. self.self_attn = YiAttention(
  204. hidden_size=self.hidden_size,
  205. num_heads=config.num_attention_heads,
  206. num_kv_heads=config.num_key_value_heads,
  207. rope_theta=rope_theta,
  208. rope_scaling=rope_scaling,
  209. max_position_embeddings=max_position_embeddings,
  210. linear_method=linear_method,
  211. )
  212. self.mlp = YiMLP(
  213. hidden_size=self.hidden_size,
  214. intermediate_size=config.intermediate_size,
  215. hidden_act=config.hidden_act,
  216. linear_method=linear_method,
  217. )
  218. self.ln1 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  219. self.ln2 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  220. def forward(
  221. self,
  222. positions: torch.Tensor,
  223. hidden_states: torch.Tensor,
  224. kv_cache: KVCache,
  225. input_metadata: InputMetadata,
  226. residual: Optional[torch.Tensor],
  227. ) -> Tuple[torch.Tensor, torch.Tensor]:
  228. # Self Attention
  229. if residual is None:
  230. residual = hidden_states
  231. hidden_states = self.ln1(hidden_states)
  232. else:
  233. hidden_states, residual = self.ln1(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.ln2(hidden_states, residual)
  242. hidden_states = self.mlp(hidden_states)
  243. return hidden_states, residual
  244. class YiModel(nn.Module):
  245. def __init__(
  246. self,
  247. config: YiConfig,
  248. linear_method: Optional[LinearMethodBase] = None,
  249. ) -> None:
  250. super().__init__()
  251. self.config = config
  252. self.padding_idx = config.pad_token_id
  253. self.vocab_size = config.vocab_size
  254. self.embed_tokens = VocabParallelEmbedding(config.vocab_size,
  255. config.hidden_size,
  256. linear_method=linear_method)
  257. self.layers = nn.ModuleList([
  258. YiDecoderLayer(config, linear_method)
  259. for _ in range(config.num_hidden_layers)
  260. ])
  261. self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  262. def forward(
  263. self,
  264. input_ids: torch.Tensor,
  265. positions: torch.Tensor,
  266. kv_caches: List[KVCache],
  267. input_metadata: InputMetadata,
  268. ) -> torch.Tensor:
  269. hidden_states = self.embed_tokens(input_ids)
  270. residual = None
  271. for i in range(len(self.layers)):
  272. layer = self.layers[i]
  273. hidden_states, residual = layer(
  274. positions,
  275. hidden_states,
  276. kv_caches[i],
  277. input_metadata,
  278. residual,
  279. )
  280. hidden_states, _ = self.norm(hidden_states, residual)
  281. return hidden_states
  282. class YiForCausalLM(nn.Module):
  283. def __init__(
  284. self,
  285. config: YiConfig,
  286. linear_method: Optional[LinearMethodBase] = None,
  287. ) -> None:
  288. super().__init__()
  289. self.config = config
  290. self.linear_method = linear_method
  291. self.model = YiModel(config, linear_method)
  292. self.lm_head = ParallelLMHead(config.vocab_size,
  293. config.hidden_size,
  294. linear_method=linear_method)
  295. self.sampler = Sampler(config.vocab_size)
  296. def forward(
  297. self,
  298. input_ids: torch.Tensor,
  299. positions: torch.Tensor,
  300. kv_caches: List[KVCache],
  301. input_metadata: InputMetadata,
  302. ) -> torch.Tensor:
  303. hidden_states = self.model(input_ids, positions, kv_caches,
  304. input_metadata)
  305. return hidden_states
  306. def sample(
  307. self,
  308. hidden_states: torch.Tensor,
  309. sampling_metadata: SamplingMetadata,
  310. ) -> Optional[SamplerOutput]:
  311. next_tokens = self.sampler(self.lm_head(hidden_states),
  312. sampling_metadata)
  313. return next_tokens
  314. def load_weights(self,
  315. model_name_or_path: str,
  316. cache_dir: Optional[str] = None,
  317. load_format: str = "auto",
  318. revision: Optional[str] = None):
  319. stacked_params_mapping = [
  320. # (param_name, shard_name, shard_id)
  321. ("qkv_proj", "q_proj", "q"),
  322. ("qkv_proj", "k_proj", "k"),
  323. ("qkv_proj", "v_proj", "v"),
  324. ("gate_up_proj", "gate_proj", 0),
  325. ("gate_up_proj", "up_proj", 1),
  326. ]
  327. if self.linear_method is not None and not self.linear_method.quant_config.merge_weight(
  328. ):
  329. stacked_params_mapping = []
  330. params_dict = dict(self.named_parameters())
  331. for name, loaded_weight in hf_model_weights_iterator(
  332. model_name_or_path, cache_dir, load_format, revision):
  333. if "rotary_emb.inv_freq" in name:
  334. continue
  335. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  336. if weight_name not in name:
  337. continue
  338. name = name.replace(weight_name, param_name)
  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 = param.weight_loader
  344. weight_loader(param, loaded_weight, shard_id)
  345. break
  346. else:
  347. # Skip loading extra bias for GPTQ models.
  348. if name.endswith(".bias") and name not in params_dict:
  349. continue
  350. param = params_dict[name]
  351. weight_loader = getattr(param, "weight_loader",
  352. default_weight_loader)
  353. weight_loader(param, loaded_weight)