gpt_neox.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/gpt_neox/modeling_gpt_neox.py
  4. # Copyright 2023 The PygmalionAI team.
  5. # Copyright 2023 The vLLM team.
  6. # Copyright 2022 EleutherAI The HuggingFace Inc. team. All rights reserved.
  7. #
  8. # Licensed under the Apache License, Version 2.0 (the "License");
  9. # you may not use this file except in compliance with the License.
  10. # You may obtain a copy of the License at
  11. #
  12. # http://www.apache.org/licenses/LICENSE-2.0
  13. #
  14. # Unless required by applicable law or agreed to in writing, software
  15. # distributed under the License is distributed on an "AS IS" BASIS,
  16. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. # See the License for the specific language governing permissions and
  18. # limitations under the License.
  19. """Inference-only GPT-NeoX model compatible with HuggingFace weights."""
  20. from typing import List, Optional
  21. import torch
  22. from torch import nn
  23. from transformers import GPTNeoXConfig
  24. from aphrodite.attention import Attention, AttentionMetadata
  25. from aphrodite.modeling.layers.activation import get_act_fn
  26. from aphrodite.modeling.layers.linear import (
  27. ColumnParallelLinear,
  28. LinearMethodBase,
  29. QKVParallelLinear,
  30. RowParallelLinear,
  31. )
  32. from aphrodite.modeling.layers.rotary_embedding import get_rope
  33. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  34. from aphrodite.modeling.layers.sampler import Sampler
  35. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  36. VocabParallelEmbedding,
  37. ParallelLMHead,
  38. )
  39. from aphrodite.distributed import (
  40. get_tensor_model_parallel_world_size, )
  41. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  42. from aphrodite.modeling.hf_downloader import (
  43. default_weight_loader,
  44. hf_model_weights_iterator,
  45. )
  46. from aphrodite.common.sequence import SamplerOutput
  47. class GPTNeoXAttention(nn.Module):
  48. def __init__(
  49. self,
  50. config: GPTNeoXConfig,
  51. linear_method: Optional[LinearMethodBase] = None,
  52. ):
  53. super().__init__()
  54. self.total_num_heads = config.num_attention_heads
  55. self.hidden_size = config.hidden_size
  56. self.head_size = self.hidden_size // self.total_num_heads
  57. self.bias = getattr(config, "attention_bias", True)
  58. tensor_model_parallel_world_size = (
  59. get_tensor_model_parallel_world_size())
  60. assert self.total_num_heads % tensor_model_parallel_world_size == 0
  61. self.num_heads = (self.total_num_heads //
  62. tensor_model_parallel_world_size)
  63. self.query_key_value = QKVParallelLinear(
  64. config.hidden_size,
  65. self.head_size,
  66. self.total_num_heads,
  67. bias=self.bias,
  68. linear_method=linear_method,
  69. )
  70. self.dense = RowParallelLinear(
  71. config.hidden_size,
  72. config.hidden_size,
  73. bias=self.bias,
  74. linear_method=linear_method,
  75. )
  76. scaling = self.head_size**-0.5
  77. rotary_dim = int(self.head_size * config.rotary_pct)
  78. assert rotary_dim % 2 == 0
  79. rope_theta = getattr(config, "rope_theta", 10000)
  80. max_position_embeddings = getattr(config, "max_position_embeddings",
  81. 8192)
  82. self.rotary_emb = get_rope(
  83. self.head_size,
  84. rotary_dim=rotary_dim,
  85. max_position=max_position_embeddings,
  86. base=rope_theta,
  87. is_neox_style=True,
  88. )
  89. self.attn = Attention(self.num_heads, self.head_size, scaling)
  90. def forward(
  91. self,
  92. position_ids: torch.Tensor,
  93. hidden_states: torch.Tensor,
  94. kv_cache: torch.Tensor,
  95. attn_metadata: AttentionMetadata,
  96. ) -> torch.Tensor:
  97. qkv, _ = self.query_key_value(hidden_states)
  98. q, k, v = qkv.chunk(chunks=3, dim=-1)
  99. q, k = self.rotary_emb(position_ids, q, k)
  100. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  101. output, _ = self.dense(attn_output)
  102. return output
  103. class GPTNeoXMLP(nn.Module):
  104. def __init__(
  105. self,
  106. config: GPTNeoXConfig,
  107. linear_method: Optional[LinearMethodBase] = None,
  108. ):
  109. super().__init__()
  110. self.dense_h_to_4h = ColumnParallelLinear(
  111. config.hidden_size,
  112. config.intermediate_size,
  113. linear_method=linear_method,
  114. )
  115. self.dense_4h_to_h = RowParallelLinear(
  116. config.intermediate_size,
  117. config.hidden_size,
  118. linear_method=linear_method,
  119. )
  120. quant_config = getattr(linear_method, "quant_config", None)
  121. self.act = get_act_fn(config.hidden_act, quant_config,
  122. config.intermediate_size)
  123. def forward(self, hidden_states):
  124. hidden_states, _ = self.dense_h_to_4h(hidden_states)
  125. hidden_states = self.act(hidden_states)
  126. hidden_states, _ = self.dense_4h_to_h(hidden_states)
  127. return hidden_states
  128. class GPTNeoXLayer(nn.Module):
  129. def __init__(
  130. self,
  131. config: GPTNeoXConfig,
  132. linear_method: Optional[LinearMethodBase] = None,
  133. ):
  134. super().__init__()
  135. self.use_parallel_residual = config.use_parallel_residual
  136. self.input_layernorm = nn.LayerNorm(config.hidden_size,
  137. eps=config.layer_norm_eps)
  138. self.post_attention_layernorm = nn.LayerNorm(config.hidden_size,
  139. eps=config.layer_norm_eps)
  140. self.attention = GPTNeoXAttention(config, linear_method)
  141. self.mlp = GPTNeoXMLP(config, linear_method)
  142. def forward(
  143. self,
  144. position_ids: torch.Tensor,
  145. hidden_states: torch.Tensor,
  146. kv_cache: torch.Tensor,
  147. attn_metadata: AttentionMetadata,
  148. ) -> torch.Tensor:
  149. attn_input = self.input_layernorm(hidden_states)
  150. attn_output = self.attention(
  151. position_ids=position_ids,
  152. hidden_states=attn_input,
  153. kv_cache=kv_cache,
  154. attn_metadata=attn_metadata,
  155. )
  156. if self.use_parallel_residual:
  157. # pseudocode:
  158. # x = x + attn(ln1(x)) + mlp(ln2(x))
  159. mlp_input = self.post_attention_layernorm(hidden_states)
  160. mlp_output = self.mlp(mlp_input)
  161. hidden_states = mlp_output + attn_output + hidden_states
  162. else:
  163. # pseudocode:
  164. # x = x + attn(ln1(x))
  165. # x = x + mlp(ln2(x))
  166. attn_output = attn_output + hidden_states
  167. mlp_input = self.post_attention_layernorm(attn_output)
  168. mlp_output = self.mlp(mlp_input)
  169. hidden_states = mlp_output + attn_output
  170. return hidden_states
  171. class GPTNeoXModel(nn.Module):
  172. def __init__(
  173. self,
  174. config: GPTNeoXConfig,
  175. linear_method: Optional[LinearMethodBase] = None,
  176. ):
  177. super().__init__()
  178. self.config = config
  179. self.embed_in = VocabParallelEmbedding(config.vocab_size,
  180. config.hidden_size,
  181. linear_method=linear_method)
  182. self.layers = nn.ModuleList([
  183. GPTNeoXLayer(config, linear_method)
  184. for _ in range(config.num_hidden_layers)
  185. ])
  186. self.final_layer_norm = nn.LayerNorm(config.hidden_size,
  187. eps=config.layer_norm_eps)
  188. def forward(
  189. self,
  190. input_ids: torch.Tensor,
  191. position_ids: torch.Tensor,
  192. kv_caches: List[torch.Tensor],
  193. attn_metadata: AttentionMetadata,
  194. ) -> torch.Tensor:
  195. hidden_states = self.embed_in(input_ids)
  196. for i in range(len(self.layers)):
  197. layer = self.layers[i]
  198. hidden_states = layer(
  199. position_ids,
  200. hidden_states,
  201. kv_caches[i],
  202. attn_metadata,
  203. )
  204. hidden_states = self.final_layer_norm(hidden_states)
  205. return hidden_states
  206. class GPTNeoXForCausalLM(nn.Module):
  207. def __init__(
  208. self,
  209. config,
  210. linear_method: Optional[LinearMethodBase] = None,
  211. ):
  212. super().__init__()
  213. self.config = config
  214. self.linear_method = linear_method
  215. self.gpt_neox = GPTNeoXModel(config, linear_method)
  216. self.embed_out = ParallelLMHead(config.vocab_size,
  217. config.hidden_size,
  218. linear_method=linear_method)
  219. self.logits_processor = LogitsProcessor(config.vocab_size)
  220. self.sampler = Sampler()
  221. def forward(
  222. self,
  223. input_ids: torch.Tensor,
  224. positions: torch.Tensor,
  225. kv_caches: List[torch.Tensor],
  226. attn_metadata: AttentionMetadata,
  227. ) -> torch.Tensor:
  228. hidden_states = self.gpt_neox(input_ids, positions, kv_caches,
  229. attn_metadata)
  230. return hidden_states
  231. def compute_logits(self, hidden_states: torch.Tensor,
  232. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  233. logits = self.logits_processor(self.embed_out, hidden_states,
  234. sampling_metadata)
  235. return logits
  236. def sample(
  237. self,
  238. logits: torch.Tensor,
  239. sampling_metadata: SamplingMetadata,
  240. ) -> Optional[SamplerOutput]:
  241. next_tokens = self.sampler(logits, sampling_metadata)
  242. return next_tokens
  243. def load_weights(
  244. self,
  245. model_name_or_path: str,
  246. cache_dir: Optional[str] = None,
  247. load_format: str = "auto",
  248. revision: Optional[str] = None,
  249. ):
  250. params_dict = dict(self.named_parameters())
  251. for name, loaded_weight in hf_model_weights_iterator(
  252. model_name_or_path, cache_dir, load_format, revision,
  253. self.config):
  254. if ("attention.bias" in name or "attention.masked_bias" in name
  255. or "rotary_emb.inv_freq" in name):
  256. continue
  257. if ("rotary_emb.cos_cached" in name
  258. or "rotary_emb.sin_cached" in name):
  259. # Models trained using OpenRLHF may include
  260. # these tensors in the checkpoint. Skip them.
  261. continue
  262. param = params_dict[name]
  263. if "query_key_value" in name:
  264. # NOTE: GPT-NeoX's fused QKV's output_dim has the shape of
  265. # (num_heads * 3 * head_size), while the
  266. # required shape is (3 * num_heads * head_size).
  267. # Thus, we need weight conversion.
  268. output_dim = getattr(param, "output_dim", None)
  269. num_heads = self.config.num_attention_heads
  270. if output_dim is not None:
  271. loaded_weight_shape = loaded_weight.shape
  272. loaded_weight = loaded_weight.view(
  273. loaded_weight_shape[:output_dim] + (num_heads, 3, -1) +
  274. loaded_weight_shape[output_dim + 1:])
  275. loaded_weight = loaded_weight.transpose(
  276. output_dim, output_dim + 1)
  277. loaded_weight = loaded_weight.reshape(loaded_weight_shape)
  278. weight_loader = getattr(param, "weight_loader",
  279. default_weight_loader)
  280. weight_loader(param, loaded_weight)