123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370 |
- # coding=utf-8
- # Adapted from
- # https://huggingface.co/microsoft/phi-1_5/blob/main/modeling_phi.py
- # Copyright 2023 The PygmalionAI team.
- # Copyright 2023 The vLLM team.
- # Copyright (c) Microsoft Corporation.
- # Licensed under the MIT license.
- #
- # BSD 3-Clause License
- #
- # Copyright (c) 2022, Tri Dao, trid@cs.stanford.edu.
- # All rights reserved.
- #
- # Redistribution and use in source and binary forms, with or without
- # modification, are permitted provided that the following conditions are met:
- #
- # * Redistributions of source code must retain the above copyright notice, this
- # list of conditions and the following disclaimer.
- #
- # * Redistributions in binary form must reproduce the above copyright notice,
- # this list of conditions and the following disclaimer in the documentation
- # and/or other materials provided with the distribution.
- #
- # * Neither the name of the copyright holder nor the names of its
- # contributors may be used to endorse or promote products derived from
- # this software without specific prior written permission.
- #
- # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- """Inference-only Phi model compatible with HuggingFace weights."""
- from typing import List, Optional, Tuple
- import torch
- from torch import nn
- from transformers import PretrainedConfig
- from aphrodite.modeling.metadata import InputMetadata
- from aphrodite.modeling.layers.activation import get_act_fn
- from aphrodite.modeling.layers.attention import PagedAttention
- from aphrodite.modeling.layers.linear import (
- ColumnParallelLinear,
- LinearMethodBase,
- QKVParallelLinear,
- RowParallelLinear,
- )
- from aphrodite.modeling.layers.rotary_embedding import get_rope
- from aphrodite.modeling.layers.sampler import Sampler, QuantSampler
- from aphrodite.modeling.layers.vocab_parallel_embedding import (
- VocabParallelEmbedding,
- ParallelLMHead,
- )
- from aphrodite.modeling.megatron.parallel_state import (
- get_tensor_model_parallel_world_size, )
- from aphrodite.modeling.sampling_metadata import SamplingMetadata
- from aphrodite.modeling.hf_downloader import (
- default_weight_loader,
- hf_model_weights_iterator,
- )
- from aphrodite.common.sequence import SamplerOutput
- KVCache = Tuple[torch.Tensor, torch.Tensor]
- class PhiAttention(nn.Module):
- def __init__(
- self,
- config: PretrainedConfig,
- linear_method: Optional[LinearMethodBase] = None,
- ):
- super().__init__()
- self.total_num_heads = config.num_attention_heads
- self.hidden_size = config.hidden_size
- self.head_size = self.hidden_size // self.total_num_heads
- tensor_model_parallel_world_size = (
- get_tensor_model_parallel_world_size())
- assert self.total_num_heads % tensor_model_parallel_world_size == 0
- self.num_heads = (self.total_num_heads //
- tensor_model_parallel_world_size)
- # pylint: disable=C0103
- if (linear_method is not None
- and not linear_method.quant_config.merge_weight()):
- self.merge_weight = False
- self.q_proj = ColumnParallelLinear(
- self.hidden_size,
- self.hidden_size,
- bias=True,
- linear_method=linear_method,
- )
- self.k_proj = ColumnParallelLinear(
- self.hidden_size,
- self.hidden_size,
- bias=True,
- linear_method=linear_method,
- )
- self.v_proj = ColumnParallelLinear(
- self.hidden_size,
- self.hidden_size,
- bias=True,
- linear_method=linear_method,
- )
- else:
- self.merge_weight = True
- self.qkv_proj = QKVParallelLinear(
- self.hidden_size,
- self.head_size,
- self.total_num_heads,
- bias=True,
- linear_method=linear_method,
- )
- self.dense = RowParallelLinear(
- self.hidden_size,
- self.hidden_size,
- linear_method=linear_method,
- )
- scaling = self.head_size**-0.5
- rotary_dim = int(config.partial_rotary_factor *
- (config.hidden_size // config.num_attention_heads))
- assert rotary_dim % 2 == 0
- # pylint: disable=C0301
- # Refer to:
- # https://huggingface.co/microsoft/phi-1_5/blob/d212a789620c380ff32ca1d1ee9943a777360987/modeling_phi.py#L518
- rope_theta = 10000
- max_position_embeddings = getattr(config, "n_positions", 2048)
- is_neox_style = (True if linear_method is None
- or linear_method.quant_config.rope_style() is None
- else linear_method.quant_config.rope_style())
- self.rotary_emb = get_rope(
- self.head_size,
- rotary_dim=rotary_dim,
- max_position=max_position_embeddings,
- base=rope_theta,
- is_neox_style=is_neox_style,
- )
- self.attn = PagedAttention(self.num_heads, self.head_size, scaling)
- def forward(
- self,
- position_ids: torch.Tensor,
- hidden_states: torch.Tensor,
- kv_cache: KVCache,
- input_metadata: InputMetadata,
- ) -> torch.Tensor:
- if self.merge_weight:
- qkv, _ = self.qkv_proj(hidden_states)
- q, k, v = qkv.chunk(chunks=3, dim=-1)
- else:
- q, _ = self.q_proj(hidden_states)
- k, _ = self.k_proj(hidden_states)
- v, _ = self.v_proj(hidden_states)
- q, k = self.rotary_emb(position_ids, q, k)
- k_cache, v_cache = kv_cache
- attn_output = self.attn(q, k, v, k_cache, v_cache, input_metadata)
- output, _ = self.dense(attn_output)
- return output
- class PhiMLP(nn.Module):
- def __init__(
- self,
- config: PretrainedConfig,
- linear_method: Optional[LinearMethodBase] = None,
- ):
- super().__init__()
- n_inner = getattr(config, "n_inner", None)
- n_inner = n_inner if n_inner is not None else 4 * config.hidden_size
- self.fc1 = ColumnParallelLinear(
- config.hidden_size,
- n_inner,
- linear_method=linear_method,
- )
- self.fc2 = RowParallelLinear(
- n_inner,
- config.hidden_size,
- linear_method=linear_method,
- )
- quant_config = getattr(linear_method, "quant_config", None)
- self.act = get_act_fn(config.hidden_act, quant_config, n_inner)
- def forward(self, hidden_states):
- hidden_states, _ = self.fc1(hidden_states)
- hidden_states = self.act(hidden_states)
- hidden_states, _ = self.fc2(hidden_states)
- return hidden_states
- class PhiLayer(nn.Module):
- def __init__(
- self,
- config: PretrainedConfig,
- linear_method: Optional[LinearMethodBase] = None,
- ):
- super().__init__()
- self.input_layernorm = nn.LayerNorm(config.hidden_size,
- eps=config.layer_norm_eps)
- self.self_attn = PhiAttention(config, linear_method)
- self.mlp = PhiMLP(config, linear_method)
- def forward(
- self,
- position_ids: torch.Tensor,
- hidden_states: torch.Tensor,
- kv_cache: KVCache,
- input_metadata: InputMetadata,
- ) -> torch.Tensor:
- residual = hidden_states
- hidden_states = self.input_layernorm(hidden_states)
- attn_outputs = self.self_attn(
- position_ids=position_ids,
- hidden_states=hidden_states,
- kv_cache=kv_cache,
- input_metadata=input_metadata,
- )
- feed_forward_hidden_states = self.mlp(hidden_states)
- hidden_states = attn_outputs + feed_forward_hidden_states + residual
- return hidden_states
- class PhiModel(nn.Module):
- def __init__(
- self,
- config: PretrainedConfig,
- linear_method: Optional[LinearMethodBase] = None,
- ):
- super().__init__()
- self.config = config
- self.linear_method = linear_method
- self.embed_tokens = VocabParallelEmbedding(config.vocab_size,
- config.hidden_size,
- linear_method=linear_method)
- self.layers = nn.ModuleList([
- PhiLayer(config, linear_method)
- for _ in range(config.num_hidden_layers)
- ])
- self.final_layernorm = nn.LayerNorm(config.hidden_size,
- eps=config.layer_norm_eps)
- def forward(
- self,
- input_ids: torch.Tensor,
- positions: torch.Tensor,
- kv_caches: List[KVCache],
- input_metadata: InputMetadata,
- ) -> torch.Tensor:
- hidden_states = self.embed_tokens(input_ids)
- for i in range(self.config.num_hidden_layers):
- layer = self.layers[i]
- hidden_states = layer(
- positions,
- hidden_states,
- kv_caches[i],
- input_metadata,
- )
- hidden_states = self.final_layernorm(hidden_states)
- return hidden_states
- class PhiForCausalLM(nn.Module):
- def __init__(
- self,
- config: PretrainedConfig,
- linear_method: Optional[LinearMethodBase] = None,
- ):
- super().__init__()
- self.config = config
- self.linear_method = linear_method
- self.model = PhiModel(config, linear_method)
- self.lm_head = ParallelLMHead(
- config.vocab_size,
- config.hidden_size,
- bias=True,
- linear_method=linear_method,
- )
- self.sampler = Sampler(config.vocab_size)
- self.quant_sampler = QuantSampler(config.vocab_size)
- def forward(
- self,
- input_ids: torch.Tensor,
- positions: torch.Tensor,
- kv_caches: List[KVCache],
- input_metadata: InputMetadata,
- ) -> torch.Tensor:
- hidden_states = self.model(input_ids, positions, kv_caches,
- input_metadata)
- return hidden_states
- def sample(
- self,
- hidden_states: torch.Tensor,
- sampling_metadata: SamplingMetadata,
- ) -> Optional[SamplerOutput]:
- if (self.linear_method is not None
- and not self.linear_method.quant_config.merge_weight()):
- next_tokens = self.quant_sampler(self.lm_head(hidden_states),
- sampling_metadata)
- else:
- next_tokens = self.sampler(self.lm_head.weight, hidden_states,
- sampling_metadata)
- return next_tokens
- def load_weights(
- self,
- model_name_or_path: str,
- cache_dir: Optional[str] = None,
- load_format: str = "auto",
- revision: Optional[str] = None,
- ):
- stacked_params_mapping = [
- # (param_name, shard_name, shard_id)
- ("qkv_proj", "q_proj", "q"),
- ("qkv_proj", "k_proj", "k"),
- ("qkv_proj", "v_proj", "v"),
- ]
- if (self.linear_method is not None
- and not self.linear_method.quant_config.merge_weight()):
- stacked_params_mapping = []
- params_dict = dict(self.named_parameters())
- for name, loaded_weight in hf_model_weights_iterator(
- model_name_or_path, cache_dir, load_format, revision,
- self.config):
- if "rotary_emb.inv_freq" in name:
- continue
- for param_name, weight_name, shard_id in stacked_params_mapping:
- if weight_name not in name:
- continue
- name = name.replace(weight_name, param_name)
- # Skip loading extra bias for GPTQ models.
- if name.endswith(".bias") and name not in params_dict:
- continue
- param = params_dict[name]
- weight_loader = param.weight_loader
- weight_loader(param, loaded_weight, shard_id)
- break
- else:
- # Skip loading extra bias for GPTQ models.
- if name.endswith(".bias") and name not in params_dict:
- continue
- # pylint: disable=E1136
- param = params_dict[name]
- weight_loader = getattr(param, "weight_loader",
- default_weight_loader)
- weight_loader(param, loaded_weight)
|