1
0

phi.py 13 KB

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