starcoder2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. # coding=utf-8
  2. # Copyright 2024 BigCode and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  5. # and OPT implementations in this library. It has been modified from its
  6. # original forms to accommodate minor architectural differences compared
  7. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  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. """ PyTorch Starcoder2 model."""
  21. from typing import Iterable, List, Optional, Tuple
  22. import torch
  23. from torch import nn
  24. from transformers import Starcoder2Config
  25. from aphrodite.attention import Attention, AttentionMetadata
  26. from aphrodite.common.config import CacheConfig
  27. from aphrodite.common.sequence import SamplerOutput
  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.rotary_embedding import get_rope
  35. from aphrodite.modeling.layers.sampler import Sampler
  36. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  37. DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
  38. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  39. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  40. from aphrodite.quantization.base_config import QuantizationConfig
  41. class Starcoder2Attention(nn.Module):
  42. def __init__(self,
  43. config: Starcoder2Config,
  44. cache_config: Optional[CacheConfig] = None,
  45. quant_config: Optional[QuantizationConfig] = None):
  46. super().__init__()
  47. self.config = config
  48. self.hidden_size = config.hidden_size
  49. tp_size = get_tensor_model_parallel_world_size()
  50. self.total_num_heads = config.num_attention_heads
  51. assert self.total_num_heads % tp_size == 0
  52. self.num_heads = self.total_num_heads // tp_size
  53. self.total_num_kv_heads = config.num_key_value_heads
  54. if self.total_num_kv_heads >= tp_size:
  55. # Number of KV heads is greater than TP size, so we partition
  56. # the KV heads across multiple tensor parallel GPUs.
  57. assert self.total_num_kv_heads % tp_size == 0
  58. else:
  59. # Number of KV heads is less than TP size, so we replicate
  60. # the KV heads across multiple tensor parallel GPUs.
  61. assert tp_size % self.total_num_kv_heads == 0
  62. self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
  63. self.head_dim = self.hidden_size // self.total_num_heads
  64. self.q_size = self.num_heads * self.head_dim
  65. self.kv_size = self.num_kv_heads * self.head_dim
  66. self.scaling = self.head_dim**-0.5
  67. self.rope_theta = config.rope_theta
  68. self.max_position_embeddings = config.max_position_embeddings
  69. self.use_bias = config.use_bias
  70. self.sliding_window = config.sliding_window
  71. self.qkv_proj = QKVParallelLinear(
  72. self.hidden_size,
  73. self.head_dim,
  74. self.total_num_heads,
  75. self.total_num_kv_heads,
  76. bias=self.use_bias,
  77. quant_config=quant_config,
  78. )
  79. self.o_proj = RowParallelLinear(
  80. self.total_num_heads * self.head_dim,
  81. self.hidden_size,
  82. bias=self.use_bias,
  83. quant_config=quant_config,
  84. )
  85. self.rotary_emb = get_rope(
  86. self.head_dim,
  87. rotary_dim=self.head_dim,
  88. max_position=self.max_position_embeddings,
  89. base=int(self.rope_theta),
  90. is_neox_style=True,
  91. )
  92. self.attn = Attention(self.num_heads,
  93. self.head_dim,
  94. self.scaling,
  95. num_kv_heads=self.num_kv_heads,
  96. sliding_window=self.sliding_window,
  97. cache_config=cache_config,
  98. quant_config=quant_config)
  99. def forward(
  100. self,
  101. positions: torch.Tensor,
  102. hidden_states: torch.Tensor,
  103. kv_cache: torch.Tensor,
  104. attn_metadata: AttentionMetadata,
  105. ) -> torch.Tensor:
  106. qkv, _ = self.qkv_proj(hidden_states)
  107. q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
  108. q, k = self.rotary_emb(positions, q, k)
  109. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  110. output, _ = self.o_proj(attn_output)
  111. return output
  112. class Starcoder2MLP(nn.Module):
  113. def __init__(self,
  114. config: Starcoder2Config,
  115. quant_config: Optional[QuantizationConfig] = None):
  116. super().__init__()
  117. self.c_fc = ColumnParallelLinear(
  118. config.hidden_size,
  119. config.intermediate_size,
  120. bias=config.use_bias,
  121. quant_config=quant_config,
  122. )
  123. self.c_proj = RowParallelLinear(
  124. config.intermediate_size,
  125. config.hidden_size,
  126. bias=config.use_bias,
  127. quant_config=quant_config,
  128. )
  129. self.act = get_act_fn(config.hidden_act, quant_config,
  130. config.intermediate_size)
  131. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  132. hidden_states, _ = self.c_fc(hidden_states)
  133. hidden_states = self.act(hidden_states)
  134. hidden_states, _ = self.c_proj(hidden_states)
  135. return hidden_states
  136. class Starcoder2DecoderLayer(nn.Module):
  137. def __init__(self,
  138. config: Starcoder2Config,
  139. cache_config: Optional[CacheConfig] = None,
  140. quant_config: Optional[QuantizationConfig] = None):
  141. super().__init__()
  142. self.hidden_size = config.hidden_size
  143. self.self_attn = Starcoder2Attention(config,
  144. cache_config,
  145. quant_config=quant_config)
  146. self.mlp = Starcoder2MLP(config, quant_config=quant_config)
  147. self.input_layernorm = nn.LayerNorm(config.hidden_size,
  148. eps=config.norm_epsilon)
  149. self.post_attention_layernorm = nn.LayerNorm(config.hidden_size,
  150. eps=config.norm_epsilon)
  151. def forward(
  152. self,
  153. positions: torch.Tensor,
  154. hidden_states: torch.Tensor,
  155. kv_cache: torch.Tensor,
  156. attn_metadata: AttentionMetadata,
  157. ) -> torch.Tensor:
  158. # Self Attention
  159. residual = hidden_states
  160. hidden_states = self.input_layernorm(hidden_states)
  161. hidden_states = self.self_attn(
  162. positions=positions,
  163. hidden_states=hidden_states,
  164. kv_cache=kv_cache,
  165. attn_metadata=attn_metadata,
  166. )
  167. hidden_states = residual + hidden_states
  168. # Fully Connected
  169. residual = hidden_states
  170. hidden_states = self.post_attention_layernorm(hidden_states)
  171. hidden_states = self.mlp(hidden_states)
  172. hidden_states = residual + hidden_states
  173. return hidden_states
  174. class Starcoder2Model(nn.Module):
  175. def __init__(self,
  176. config: Starcoder2Config,
  177. cache_config: Optional[CacheConfig] = None,
  178. quant_config: Optional[QuantizationConfig] = None):
  179. super().__init__()
  180. self.config = config
  181. self.padding_idx = config.pad_token_id
  182. self.vocab_size = config.vocab_size
  183. # TODO: consider padding_idx (currently removed)
  184. self.embed_tokens = VocabParallelEmbedding(config.vocab_size,
  185. config.hidden_size)
  186. self.layers = nn.ModuleList([
  187. Starcoder2DecoderLayer(config,
  188. cache_config,
  189. quant_config=quant_config)
  190. for _ in range(config.num_hidden_layers)
  191. ])
  192. self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_epsilon)
  193. def forward(
  194. self,
  195. input_ids: torch.Tensor,
  196. positions: torch.Tensor,
  197. kv_caches: List[torch.Tensor],
  198. attn_metadata: AttentionMetadata,
  199. ) -> torch.Tensor:
  200. hidden_states = self.embed_tokens(input_ids)
  201. for i in range(len(self.layers)):
  202. layer = self.layers[i]
  203. hidden_states = layer(positions, hidden_states, kv_caches[i],
  204. attn_metadata)
  205. hidden_states = self.norm(hidden_states)
  206. return hidden_states
  207. class Starcoder2ForCausalLM(nn.Module):
  208. def __init__(self,
  209. config: Starcoder2Config,
  210. cache_config: Optional[CacheConfig] = None,
  211. quant_config: Optional[QuantizationConfig] = None):
  212. super().__init__()
  213. self.config = config
  214. self.model = Starcoder2Model(config,
  215. cache_config,
  216. quant_config=quant_config)
  217. self.vocab_size = config.vocab_size
  218. self.unpadded_vocab_size = config.vocab_size
  219. if config.tie_word_embeddings:
  220. self.lm_head_weight = self.model.embed_tokens.weight
  221. else:
  222. self.unpadded_vocab_size = config.vocab_size
  223. self.lm_head = ParallelLMHead(
  224. self.unpadded_vocab_size,
  225. config.hidden_size,
  226. org_num_embeddings=config.vocab_size,
  227. padding_size=DEFAULT_VOCAB_PADDING_SIZE,
  228. )
  229. self.lm_head_weight = self.lm_head.weight
  230. self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
  231. config.vocab_size)
  232. self.sampler = Sampler()
  233. def forward(
  234. self,
  235. input_ids: torch.Tensor,
  236. positions: torch.Tensor,
  237. kv_caches: List[torch.Tensor],
  238. attn_metadata: AttentionMetadata,
  239. ) -> torch.Tensor:
  240. hidden_states = self.model(input_ids, positions, kv_caches,
  241. attn_metadata)
  242. return hidden_states
  243. def compute_logits(self, hidden_states: torch.Tensor,
  244. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  245. logits = self.logits_processor(self.lm_head_weight, hidden_states,
  246. sampling_metadata)
  247. return logits
  248. def sample(
  249. self,
  250. logits: Optional[torch.Tensor],
  251. sampling_metadata: SamplingMetadata,
  252. ) -> Optional[SamplerOutput]:
  253. next_tokens = self.sampler(logits, sampling_metadata)
  254. return next_tokens
  255. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  256. stacked_params_mapping = [
  257. # (param_name, shard_name, shard_id)
  258. ("qkv_proj", "q_proj", "q"),
  259. ("qkv_proj", "k_proj", "k"),
  260. ("qkv_proj", "v_proj", "v"),
  261. ]
  262. params_dict = dict(self.named_parameters(remove_duplicate=False))
  263. for name, loaded_weight in weights:
  264. if "rotary_emb.inv_freq" in name:
  265. continue
  266. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  267. if weight_name not in name:
  268. continue
  269. name = name.replace(weight_name, param_name)
  270. param = params_dict[name]
  271. weight_loader = param.weight_loader
  272. weight_loader(param, loaded_weight, shard_id)
  273. break
  274. else:
  275. if self.config.tie_word_embeddings and "lm_head.weight" in name:
  276. continue
  277. param = params_dict[name]
  278. weight_loader = getattr(param, "weight_loader",
  279. default_weight_loader)
  280. weight_loader(param, loaded_weight)