gpt_neox.py 12 KB

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