phi.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # coding=utf-8
  2. # Adapted from
  3. # https://huggingface.co/microsoft/phi-1_5/blob/main/modeling_phi.py
  4. # Copyright 2023 The vLLM team.
  5. # Copyright (c) Microsoft Corporation.
  6. # Licensed under the MIT license.
  7. #
  8. # BSD 3-Clause License
  9. #
  10. # Copyright (c) 2022, Tri Dao, trid@cs.stanford.edu.
  11. # All rights reserved.
  12. #
  13. # Redistribution and use in source and binary forms, with or without
  14. # modification, are permitted provided that the following conditions are met:
  15. #
  16. # * Redistributions of source code must retain the above copyright notice, this
  17. # list of conditions and the following disclaimer.
  18. #
  19. # * Redistributions in binary form must reproduce the above copyright notice,
  20. # this list of conditions and the following disclaimer in the documentation
  21. # and/or other materials provided with the distribution.
  22. #
  23. # * Neither the name of the copyright holder nor the names of its
  24. # contributors may be used to endorse or promote products derived from
  25. # this software without specific prior written permission.
  26. #
  27. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  28. # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  29. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  30. # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  31. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  32. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  33. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  34. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  35. # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  36. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  37. """Inference-only Phi-1.5 model compatible with HuggingFace weights."""
  38. from typing import Iterable, List, Optional, Tuple
  39. import torch
  40. from torch import nn
  41. from transformers import PretrainedConfig
  42. from aphrodite.attention import Attention, AttentionMetadata
  43. from aphrodite.common.config import CacheConfig, LoRAConfig
  44. from aphrodite.common.sequence import SamplerOutput
  45. from aphrodite.distributed import get_tensor_model_parallel_world_size
  46. from aphrodite.modeling.layers.activation import get_act_fn
  47. from aphrodite.modeling.layers.linear import (ColumnParallelLinear,
  48. QKVParallelLinear,
  49. RowParallelLinear)
  50. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  51. from aphrodite.modeling.layers.rotary_embedding import get_rope
  52. from aphrodite.modeling.layers.sampler import Sampler
  53. from aphrodite.modeling.layers.vocab_parallel_embedding import (
  54. ParallelLMHead, VocabParallelEmbedding)
  55. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  56. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  57. from aphrodite.quantization.base_config import QuantizationConfig
  58. class PhiAttention(nn.Module):
  59. def __init__(self,
  60. config: PretrainedConfig,
  61. cache_config: Optional[CacheConfig] = None,
  62. quant_config: Optional[QuantizationConfig] = None):
  63. super().__init__()
  64. self.total_num_heads = config.num_attention_heads
  65. self.hidden_size = config.hidden_size
  66. self.head_size = self.hidden_size // self.total_num_heads
  67. tensor_model_parallel_world_size = (
  68. get_tensor_model_parallel_world_size())
  69. assert self.total_num_heads % tensor_model_parallel_world_size == 0
  70. self.num_heads = (self.total_num_heads //
  71. tensor_model_parallel_world_size)
  72. # pylint: disable=C0103
  73. self.qkv_proj = QKVParallelLinear(
  74. self.hidden_size,
  75. self.head_size,
  76. self.total_num_heads,
  77. bias=True,
  78. quant_config=quant_config,
  79. )
  80. self.dense = RowParallelLinear(
  81. self.hidden_size,
  82. self.hidden_size,
  83. quant_config=quant_config,
  84. )
  85. scaling = self.head_size**-0.5
  86. rotary_dim = int(config.partial_rotary_factor *
  87. (config.hidden_size // config.num_attention_heads))
  88. assert rotary_dim % 2 == 0
  89. # pylint: disable=C0301
  90. # Refer to:
  91. # https://huggingface.co/microsoft/phi-1_5/blob/d212a789620c380ff32ca1d1ee9943a777360987/modeling_phi.py#L518
  92. rope_theta = 10000
  93. max_position_embeddings = getattr(config, "n_positions", 2048)
  94. self.rotary_emb = get_rope(
  95. self.head_size,
  96. rotary_dim=rotary_dim,
  97. max_position=max_position_embeddings,
  98. base=rope_theta,
  99. )
  100. self.attn = Attention(self.num_heads,
  101. self.head_size,
  102. scaling,
  103. cache_config=cache_config,
  104. quant_config=quant_config)
  105. def forward(
  106. self,
  107. position_ids: torch.Tensor,
  108. hidden_states: torch.Tensor,
  109. kv_cache: torch.Tensor,
  110. attn_metadata: AttentionMetadata,
  111. ) -> torch.Tensor:
  112. qkv, _ = self.qkv_proj(hidden_states)
  113. q, k, v = qkv.chunk(chunks=3, dim=-1)
  114. q, k = self.rotary_emb(position_ids, q, k)
  115. attn_output = self.attn(q, k, v, kv_cache, attn_metadata)
  116. output, _ = self.dense(attn_output)
  117. return output
  118. class PhiMLP(nn.Module):
  119. def __init__(self,
  120. config: PretrainedConfig,
  121. quant_config: Optional[QuantizationConfig] = None):
  122. super().__init__()
  123. n_inner = getattr(config, "n_inner", None)
  124. n_inner = n_inner if n_inner is not None else 4 * config.hidden_size
  125. self.fc1 = ColumnParallelLinear(
  126. config.hidden_size,
  127. n_inner,
  128. quant_config=quant_config,
  129. )
  130. self.fc2 = RowParallelLinear(
  131. n_inner,
  132. config.hidden_size,
  133. quant_config=quant_config,
  134. )
  135. self.act = get_act_fn(config.hidden_act, quant_config, n_inner)
  136. def forward(self, hidden_states):
  137. hidden_states, _ = self.fc1(hidden_states)
  138. hidden_states = self.act(hidden_states)
  139. hidden_states, _ = self.fc2(hidden_states)
  140. return hidden_states
  141. class PhiLayer(nn.Module):
  142. def __init__(self,
  143. config: PretrainedConfig,
  144. cache_config: Optional[CacheConfig] = None,
  145. quant_config: Optional[QuantizationConfig] = None):
  146. super().__init__()
  147. self.input_layernorm = nn.LayerNorm(config.hidden_size,
  148. eps=config.layer_norm_eps)
  149. self.self_attn = PhiAttention(config, cache_config, quant_config)
  150. self.mlp = PhiMLP(config, quant_config)
  151. def forward(
  152. self,
  153. position_ids: torch.Tensor,
  154. hidden_states: torch.Tensor,
  155. kv_cache: torch.Tensor,
  156. attn_metadata: AttentionMetadata,
  157. ) -> torch.Tensor:
  158. residual = hidden_states
  159. hidden_states = self.input_layernorm(hidden_states)
  160. attn_outputs = self.self_attn(
  161. position_ids=position_ids,
  162. hidden_states=hidden_states,
  163. kv_cache=kv_cache,
  164. attn_metadata=attn_metadata,
  165. )
  166. feed_forward_hidden_states = self.mlp(hidden_states)
  167. hidden_states = attn_outputs + feed_forward_hidden_states + residual
  168. return hidden_states
  169. class PhiModel(nn.Module):
  170. def __init__(self,
  171. config: PretrainedConfig,
  172. cache_config: Optional[CacheConfig] = None,
  173. quant_config: Optional[QuantizationConfig] = None):
  174. super().__init__()
  175. self.config = config
  176. self.quant_config = quant_config
  177. self.embed_tokens = VocabParallelEmbedding(config.vocab_size,
  178. config.hidden_size)
  179. self.layers = nn.ModuleList([
  180. PhiLayer(config, cache_config, quant_config)
  181. for _ in range(config.num_hidden_layers)
  182. ])
  183. self.final_layernorm = nn.LayerNorm(config.hidden_size,
  184. eps=config.layer_norm_eps)
  185. def forward(
  186. self,
  187. input_ids: torch.Tensor,
  188. positions: torch.Tensor,
  189. kv_caches: List[torch.Tensor],
  190. attn_metadata: AttentionMetadata,
  191. ) -> torch.Tensor:
  192. hidden_states = self.embed_tokens(input_ids)
  193. for i in range(self.config.num_hidden_layers):
  194. layer = self.layers[i]
  195. hidden_states = layer(
  196. positions,
  197. hidden_states,
  198. kv_caches[i],
  199. attn_metadata,
  200. )
  201. hidden_states = self.final_layernorm(hidden_states)
  202. return hidden_states
  203. class PhiForCausalLM(nn.Module):
  204. packed_modules_mapping = {
  205. "qkv_proj": [
  206. "q_proj",
  207. "k_proj",
  208. "v_proj",
  209. ]
  210. }
  211. # LoRA specific attributes
  212. supported_lora_modules = [
  213. "qkv_proj",
  214. "dense",
  215. "fc1",
  216. "fc2",
  217. ]
  218. embedding_modules = {}
  219. embedding_padding_modules = []
  220. def __init__(
  221. self,
  222. config: PretrainedConfig,
  223. cache_config: Optional[CacheConfig] = None,
  224. quant_config: Optional[QuantizationConfig] = None,
  225. lora_config: Optional[LoRAConfig] = None,
  226. ):
  227. del lora_config # Unused.
  228. super().__init__()
  229. self.config = config
  230. self.quant_config = quant_config
  231. self.model = PhiModel(config, cache_config, quant_config)
  232. self.lm_head = ParallelLMHead(config.vocab_size,
  233. config.hidden_size,
  234. bias=True)
  235. self.logits_processor = LogitsProcessor(config.vocab_size)
  236. self.sampler = Sampler()
  237. def forward(
  238. self,
  239. input_ids: torch.Tensor,
  240. positions: torch.Tensor,
  241. kv_caches: List[torch.Tensor],
  242. attn_metadata: AttentionMetadata,
  243. ) -> torch.Tensor:
  244. hidden_states = self.model(input_ids, positions, kv_caches,
  245. attn_metadata)
  246. return hidden_states
  247. def compute_logits(self, hidden_states: torch.Tensor,
  248. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  249. logits = self.logits_processor(self.lm_head.weight, hidden_states,
  250. sampling_metadata, self.lm_head.bias)
  251. return logits
  252. def sample(
  253. self,
  254. logits: torch.Tensor,
  255. sampling_metadata: SamplingMetadata,
  256. ) -> Optional[SamplerOutput]:
  257. next_tokens = self.sampler(logits, sampling_metadata)
  258. return next_tokens
  259. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  260. stacked_params_mapping = [
  261. # (param_name, shard_name, shard_id)
  262. ("qkv_proj", "q_proj", "q"),
  263. ("qkv_proj", "k_proj", "k"),
  264. ("qkv_proj", "v_proj", "v")
  265. ]
  266. params_dict = dict(self.named_parameters())
  267. for name, loaded_weight in weights:
  268. if "rotary_emb.inv_freq" in name:
  269. continue
  270. for (param_name, weight_name, shard_id) in stacked_params_mapping:
  271. if weight_name not in name:
  272. continue
  273. name = name.replace(weight_name, param_name)
  274. # Skip loading extra bias for GPTQ models.
  275. if name.endswith(".bias") and name not in params_dict:
  276. continue
  277. param = params_dict[name]
  278. weight_loader = param.weight_loader
  279. weight_loader(param, loaded_weight, shard_id)
  280. break
  281. else:
  282. # Skip loading extra bias for GPTQ models.
  283. if name.endswith(".bias") and name not in params_dict:
  284. continue
  285. # pylint: disable=E1136
  286. param = params_dict[name]
  287. weight_loader = getattr(param, "weight_loader",
  288. default_weight_loader)
  289. weight_loader(param, loaded_weight)