gpt_bigcode.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/gpt2/modeling_gpt2.py
  4. # Copyright 2023 The vLLM team.
  5. # Copyright 2023 CTranslate2, and Michael Feil
  6. # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
  7. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. """Inference-only GPTBigCode model compatible with HuggingFace weights."""
  21. from typing import Iterable, List, Optional, Tuple
  22. import torch
  23. from torch import nn
  24. from transformers import GPTBigCodeConfig
  25. from aphrodite.attention import Attention, AttentionMetadata
  26. from aphrodite.common.config import CacheConfig
  27. from aphrodite.common.sequence import IntermediateTensors
  28. from aphrodite.distributed import get_tensor_model_parallel_world_size
  29. from aphrodite.modeling.layers.activation import get_act_fn
  30. from aphrodite.modeling.layers.linear import (ColumnParallelLinear,
  31. QKVParallelLinear,
  32. RowParallelLinear)
  33. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  34. from aphrodite.modeling.layers.sampler import Sampler, SamplerOutput
  35. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  36. 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 GPTBigCodeAttention(nn.Module):
  41. def __init__(
  42. self,
  43. config: GPTBigCodeConfig,
  44. cache_config: Optional[CacheConfig] = None,
  45. quant_config: Optional[QuantizationConfig] = None,
  46. ):
  47. super().__init__()
  48. self.hidden_size = config.hidden_size
  49. total_num_heads = config.num_attention_heads
  50. self.tensor_model_parallel_world_size = (
  51. get_tensor_model_parallel_world_size())
  52. assert total_num_heads % self.tensor_model_parallel_world_size == 0
  53. self.num_heads = (total_num_heads //
  54. self.tensor_model_parallel_world_size)
  55. self.head_dim = self.hidden_size // total_num_heads
  56. self.scale = self.head_dim**-0.5
  57. self.multi_query = config.multi_query
  58. if self.multi_query:
  59. total_num_kv_heads = 1
  60. self.num_kv_heads = 1
  61. else:
  62. total_num_kv_heads = total_num_heads
  63. self.num_kv_heads = self.num_heads
  64. self.kv_dim = self.head_dim * self.num_kv_heads
  65. self.c_attn = QKVParallelLinear(
  66. self.hidden_size,
  67. self.head_dim,
  68. total_num_heads,
  69. total_num_kv_heads,
  70. bias=True,
  71. quant_config=quant_config,
  72. )
  73. self.c_proj = RowParallelLinear(
  74. self.hidden_size,
  75. self.hidden_size,
  76. bias=True,
  77. quant_config=quant_config,
  78. )
  79. self.attn = Attention(self.num_heads,
  80. self.head_dim,
  81. scale=self.scale,
  82. num_kv_heads=self.num_kv_heads,
  83. cache_config=cache_config,
  84. quant_config=quant_config)
  85. def forward(
  86. self,
  87. hidden_states: torch.Tensor,
  88. kv_cache: torch.Tensor,
  89. attn_metadata: AttentionMetadata,
  90. ) -> torch.Tensor:
  91. qkv, _ = self.c_attn(hidden_states)
  92. q, k, v = qkv.split(
  93. [
  94. self.hidden_size // self.tensor_model_parallel_world_size,
  95. self.kv_dim, self.kv_dim
  96. ],
  97. dim=-1,
  98. )
  99. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  100. attn_output, _ = self.c_proj(attn_output)
  101. return attn_output
  102. class GPTBigMLP(nn.Module):
  103. def __init__(
  104. self,
  105. intermediate_size: int,
  106. config: GPTBigCodeConfig,
  107. quant_config: Optional[QuantizationConfig] = None,
  108. ):
  109. super().__init__()
  110. hidden_size = config.hidden_size
  111. self.c_fc = ColumnParallelLinear(
  112. hidden_size,
  113. intermediate_size,
  114. bias=True,
  115. quant_config=quant_config,
  116. )
  117. self.c_proj = RowParallelLinear(
  118. intermediate_size,
  119. hidden_size,
  120. bias=True,
  121. quant_config=quant_config,
  122. )
  123. self.act = get_act_fn(config.activation_function, quant_config,
  124. intermediate_size)
  125. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  126. hidden_states, _ = self.c_fc(hidden_states)
  127. hidden_states = self.act(hidden_states)
  128. hidden_states, _ = self.c_proj(hidden_states)
  129. return hidden_states
  130. class GPTBigCodeBlock(nn.Module):
  131. def __init__(
  132. self,
  133. config: GPTBigCodeConfig,
  134. cache_config: Optional[CacheConfig] = None,
  135. quant_config: Optional[QuantizationConfig] = None,
  136. ):
  137. super().__init__()
  138. hidden_size = config.hidden_size
  139. inner_dim = (config.n_inner if config.n_inner is not None else 4 *
  140. hidden_size)
  141. self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  142. self.attn = GPTBigCodeAttention(config, cache_config, quant_config)
  143. self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
  144. self.mlp = GPTBigMLP(inner_dim, config, quant_config)
  145. def forward(
  146. self,
  147. hidden_states: torch.Tensor,
  148. kv_cache: torch.Tensor,
  149. attn_metadata: AttentionMetadata,
  150. ) -> torch.Tensor:
  151. residual = hidden_states
  152. hidden_states = self.ln_1(hidden_states)
  153. attn_output = self.attn(
  154. hidden_states=hidden_states,
  155. kv_cache=kv_cache,
  156. attn_metadata=attn_metadata,
  157. )
  158. # residual connection
  159. hidden_states = attn_output + residual
  160. residual = hidden_states
  161. hidden_states = self.ln_2(hidden_states)
  162. feed_forward_hidden_states = self.mlp(hidden_states)
  163. # residual connection
  164. hidden_states = residual + feed_forward_hidden_states
  165. return hidden_states
  166. class GPTBigCodeModel(nn.Module):
  167. def __init__(
  168. self,
  169. config: GPTBigCodeConfig,
  170. cache_config: Optional[CacheConfig] = None,
  171. quant_config: Optional[QuantizationConfig] = None,
  172. ):
  173. super().__init__()
  174. self.config = config
  175. assert not config.add_cross_attention
  176. self.embed_dim = config.hidden_size
  177. self.wte = VocabParallelEmbedding(config.vocab_size, self.embed_dim)
  178. self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
  179. self.h = nn.ModuleList([
  180. GPTBigCodeBlock(config, cache_config, quant_config)
  181. for _ in range(config.num_hidden_layers)
  182. ])
  183. self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
  184. def forward(
  185. self,
  186. input_ids: torch.Tensor,
  187. position_ids: torch.Tensor,
  188. kv_caches: List[torch.Tensor],
  189. attn_metadata: AttentionMetadata,
  190. ) -> torch.Tensor:
  191. inputs_embeds = self.wte(input_ids)
  192. position_embeds = self.wpe(position_ids)
  193. hidden_states = inputs_embeds + position_embeds
  194. for i in range(len(self.h)):
  195. layer = self.h[i]
  196. hidden_states = layer(hidden_states, kv_caches[i], attn_metadata)
  197. hidden_states = self.ln_f(hidden_states)
  198. return hidden_states
  199. class GPTBigCodeForCausalLM(nn.Module):
  200. def __init__(
  201. self,
  202. config: GPTBigCodeConfig,
  203. cache_config: Optional[CacheConfig] = None,
  204. quant_config: Optional[QuantizationConfig] = None,
  205. ):
  206. super().__init__()
  207. self.config = config
  208. self.quant_config = quant_config
  209. self.transformer = GPTBigCodeModel(config, cache_config, quant_config)
  210. self.lm_head = self.transformer.wte
  211. self.logits_processor = LogitsProcessor(config.vocab_size)
  212. self.sampler = Sampler()
  213. def forward(
  214. self,
  215. input_ids: torch.Tensor,
  216. positions: torch.Tensor,
  217. kv_caches: List[torch.Tensor],
  218. attn_metadata: AttentionMetadata,
  219. intermediate_tensors: Optional[IntermediateTensors] = None,
  220. ) -> torch.Tensor:
  221. hidden_states = self.transformer(input_ids, positions, kv_caches,
  222. attn_metadata)
  223. return hidden_states
  224. def compute_logits(
  225. self,
  226. hidden_states: torch.Tensor,
  227. sampling_metadata: SamplingMetadata,
  228. ) -> Optional[torch.Tensor]:
  229. logits = self.logits_processor(self.lm_head, hidden_states,
  230. sampling_metadata)
  231. return logits
  232. def sample(
  233. self,
  234. logits: torch.Tensor,
  235. sampling_metadata: SamplingMetadata,
  236. ) -> Optional[SamplerOutput]:
  237. next_tokens = self.sampler(logits, sampling_metadata)
  238. return next_tokens
  239. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  240. params_dict = dict(self.named_parameters(remove_duplicate=False))
  241. for name, loaded_weight in weights:
  242. if "lm_head.weight" in name:
  243. continue
  244. if ".attn.bias" in name:
  245. # Skip attention mask.
  246. # NOTE: "c_attn.bias" should not be skipped.
  247. continue
  248. param = params_dict[name]
  249. weight_loader = getattr(param, "weight_loader",
  250. default_weight_loader)
  251. weight_loader(param, loaded_weight)