Files

364 lines
13 KiB
Python
Raw Permalink Normal View History

2026-01-19 10:38:50 +08:00
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
2026-01-09 13:34:11 +08:00
# Adapted from
# https://huggingface.co/microsoft/phi-1_5/blob/main/modeling_phi.py
# 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-1.5 model compatible with HuggingFace weights."""
2026-01-19 10:38:50 +08:00
from collections.abc import Iterable
from itertools import islice
2026-01-09 13:34:11 +08:00
import torch
from torch import nn
2026-01-19 10:38:50 +08:00
from transformers import PhiConfig
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
from vllm.attention.layer import Attention
from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
2026-01-09 13:34:11 +08:00
from vllm.model_executor.layers.activation import get_act_fn
2026-01-19 10:38:50 +08:00
from vllm.model_executor.layers.linear import (
ColumnParallelLinear,
QKVParallelLinear,
RowParallelLinear,
)
2026-01-09 13:34:11 +08:00
from vllm.model_executor.layers.logits_processor import LogitsProcessor
2026-01-19 10:38:50 +08:00
from vllm.model_executor.layers.quantization import QuantizationConfig
2026-01-09 13:34:11 +08:00
from vllm.model_executor.layers.rotary_embedding import get_rope
from vllm.model_executor.layers.vocab_parallel_embedding import (
2026-01-19 10:38:50 +08:00
ParallelLMHead,
VocabParallelEmbedding,
)
2026-01-09 13:34:11 +08:00
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
2026-01-19 10:38:50 +08:00
from vllm.sequence import IntermediateTensors
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
from .interfaces import SupportsLoRA, SupportsPP
from .utils import (
AutoWeightsLoader,
is_pp_missing_parameter,
make_empty_intermediate_tensors_factory,
make_layers,
maybe_prefix,
)
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
class PhiAttention(nn.Module):
def __init__(
self,
config: PhiConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
2026-01-09 13:34:11 +08:00
super().__init__()
self.hidden_size = config.hidden_size
2026-01-19 10:38:50 +08:00
self.head_size = self.hidden_size // config.num_attention_heads
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
tensor_model_parallel_world_size = get_tensor_model_parallel_world_size()
assert config.num_attention_heads % tensor_model_parallel_world_size == 0
self.num_heads = config.num_attention_heads // tensor_model_parallel_world_size
2026-01-09 13:34:11 +08:00
# pylint: disable=C0103
self.qkv_proj = QKVParallelLinear(
self.hidden_size,
self.head_size,
2026-01-19 10:38:50 +08:00
config.num_attention_heads,
2026-01-09 13:34:11 +08:00
bias=True,
quant_config=quant_config,
2026-01-19 10:38:50 +08:00
prefix=f"{prefix}.qkv_proj",
2026-01-09 13:34:11 +08:00
)
self.dense = RowParallelLinear(
self.hidden_size,
self.hidden_size,
quant_config=quant_config,
2026-01-19 10:38:50 +08:00
prefix=f"{prefix}.dense",
2026-01-09 13:34:11 +08:00
)
scaling = self.head_size**-0.5
2026-01-19 10:38:50 +08:00
max_position_embeddings = getattr(config, "max_position_embeddings", 2048)
2026-01-09 13:34:11 +08:00
self.rotary_emb = get_rope(
self.head_size,
max_position=max_position_embeddings,
2026-01-19 10:38:50 +08:00
rope_parameters=config.rope_parameters,
)
self.attn = Attention(
self.num_heads,
self.head_size,
scaling,
cache_config=cache_config,
quant_config=quant_config,
prefix=f"{prefix}.attn",
2026-01-09 13:34:11 +08:00
)
def forward(
self,
position_ids: torch.Tensor,
hidden_states: torch.Tensor,
) -> torch.Tensor:
qkv, _ = self.qkv_proj(hidden_states)
q, k, v = qkv.chunk(chunks=3, dim=-1)
q, k = self.rotary_emb(position_ids, q, k)
2026-01-19 10:38:50 +08:00
attn_output = self.attn(q, k, v)
2026-01-09 13:34:11 +08:00
output, _ = self.dense(attn_output)
return output
class PhiMLP(nn.Module):
2026-01-19 10:38:50 +08:00
def __init__(
self,
config: PhiConfig,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
2026-01-09 13:34:11 +08:00
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,
quant_config=quant_config,
2026-01-19 10:38:50 +08:00
prefix=f"{prefix}.fc1",
2026-01-09 13:34:11 +08:00
)
self.fc2 = RowParallelLinear(
n_inner,
config.hidden_size,
quant_config=quant_config,
2026-01-19 10:38:50 +08:00
prefix=f"{prefix}.fc2",
2026-01-09 13:34:11 +08:00
)
2026-01-19 10:38:50 +08:00
self.act = get_act_fn(config.hidden_act)
2026-01-09 13:34:11 +08:00
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):
2026-01-19 10:38:50 +08:00
def __init__(
self,
config: PhiConfig,
cache_config: CacheConfig | None = None,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
):
2026-01-09 13:34:11 +08:00
super().__init__()
2026-01-19 10:38:50 +08:00
self.input_layernorm = nn.LayerNorm(
config.hidden_size, eps=config.layer_norm_eps
)
self.self_attn = PhiAttention(
config, cache_config, quant_config, prefix=f"{prefix}.self_attn"
)
self.mlp = PhiMLP(config, quant_config, prefix=f"{prefix}.mlp")
2026-01-09 13:34:11 +08:00
def forward(
self,
position_ids: torch.Tensor,
hidden_states: torch.Tensor,
) -> 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,
)
feed_forward_hidden_states = self.mlp(hidden_states)
hidden_states = attn_outputs + feed_forward_hidden_states + residual
return hidden_states
2026-01-19 10:38:50 +08:00
@support_torch_compile
2026-01-09 13:34:11 +08:00
class PhiModel(nn.Module):
2026-01-19 10:38:50 +08:00
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
2026-01-09 13:34:11 +08:00
super().__init__()
2026-01-19 10:38:50 +08:00
config = vllm_config.model_config.hf_config
cache_config = vllm_config.cache_config
quant_config = vllm_config.quant_config
2026-01-09 13:34:11 +08:00
self.config = config
self.quant_config = quant_config
2026-01-19 10:38:50 +08:00
self.embed_tokens = VocabParallelEmbedding(
config.vocab_size, config.hidden_size
)
self.start_layer, self.end_layer, self.layers = make_layers(
config.num_hidden_layers,
lambda prefix: PhiLayer(config, cache_config, quant_config, prefix=prefix),
prefix=f"{prefix}.layers",
)
self.final_layernorm = nn.LayerNorm(
config.hidden_size, eps=config.layer_norm_eps
)
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
["hidden_states"], config.hidden_size
)
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.embed_tokens(input_ids)
2026-01-09 13:34:11 +08:00
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
2026-01-19 10:38:50 +08:00
intermediate_tensors: IntermediateTensors | None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
if get_pp_group().is_first_rank:
if inputs_embeds is not None:
hidden_states = inputs_embeds
else:
hidden_states = self.embed_input_ids(input_ids)
else:
assert intermediate_tensors is not None
hidden_states = intermediate_tensors["hidden_states"]
for layer in islice(self.layers, self.start_layer, self.end_layer):
hidden_states = layer(positions, hidden_states)
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
if not get_pp_group().is_last_rank:
return IntermediateTensors({"hidden_states": hidden_states})
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
hidden_states = self.final_layernorm(hidden_states)
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
return hidden_states
2026-01-09 13:34:11 +08:00
2026-01-19 10:38:50 +08:00
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
2026-01-09 13:34:11 +08:00
stacked_params_mapping = [
# (param_name, shard_name, shard_id)
("qkv_proj", "q_proj", "q"),
("qkv_proj", "k_proj", "k"),
2026-01-19 10:38:50 +08:00
("qkv_proj", "v_proj", "v"),
2026-01-09 13:34:11 +08:00
]
params_dict = dict(self.named_parameters())
2026-01-19 10:38:50 +08:00
loaded_params: set[str] = set()
2026-01-09 13:34:11 +08:00
for name, loaded_weight in weights:
if "rotary_emb.inv_freq" in name:
continue
2026-01-19 10:38:50 +08:00
for param_name, weight_name, shard_id in stacked_params_mapping:
2026-01-09 13:34:11 +08:00
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
2026-01-19 10:38:50 +08:00
if is_pp_missing_parameter(name, self):
continue
2026-01-09 13:34:11 +08:00
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
2026-01-19 10:38:50 +08:00
if is_pp_missing_parameter(name, self):
continue
2026-01-09 13:34:11 +08:00
param = params_dict[name]
2026-01-19 10:38:50 +08:00
weight_loader = getattr(param, "weight_loader", default_weight_loader)
2026-01-09 13:34:11 +08:00
weight_loader(param, loaded_weight)
2026-01-19 10:38:50 +08:00
loaded_params.add(name)
return loaded_params
class PhiForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
packed_modules_mapping = {
"qkv_proj": [
"q_proj",
"k_proj",
"v_proj",
]
}
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
config = vllm_config.model_config.hf_config
quant_config = vllm_config.quant_config
self.config = config
# lm_head use bias, cannot share word embeddings
assert not config.tie_word_embeddings
self.quant_config = quant_config
self.model = PhiModel(
vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
)
self.lm_head = ParallelLMHead(
config.vocab_size,
config.hidden_size,
bias=True,
quant_config=quant_config,
prefix=maybe_prefix(prefix, "lm_head"),
)
self.logits_processor = LogitsProcessor(config.vocab_size)
self.make_empty_intermediate_tensors = (
self.model.make_empty_intermediate_tensors
)
def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
return self.model.embed_input_ids(input_ids)
def forward(
self,
input_ids: torch.Tensor,
positions: torch.Tensor,
intermediate_tensors: IntermediateTensors | None = None,
inputs_embeds: torch.Tensor | None = None,
) -> torch.Tensor | IntermediateTensors:
hidden_states = self.model(
input_ids, positions, intermediate_tensors, inputs_embeds
)
return hidden_states
def compute_logits(
self,
hidden_states: torch.Tensor,
) -> torch.Tensor | None:
logits = self.logits_processor(self.lm_head, hidden_states, self.lm_head.bias)
return logits
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
loader = AutoWeightsLoader(self)
return loader.load_weights(weights)