2023-05-14 21:54:32 -07:00
|
|
|
# coding=utf-8
|
2023-07-03 11:31:55 -07:00
|
|
|
# Adapted from
|
|
|
|
# https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
|
2023-06-17 03:07:40 -07:00
|
|
|
# Copyright 2023 The vLLM team.
|
2023-05-14 21:54:32 -07:00
|
|
|
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
|
|
|
|
#
|
|
|
|
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
|
|
|
# and OPT implementations in this library. It has been modified from its
|
|
|
|
# original forms to accommodate minor architectural differences compared
|
|
|
|
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2023-11-23 23:04:44 -08:00
|
|
|
"""Inference-only LLaMA model compatible with HuggingFace weights."""
|
2024-02-13 09:24:59 -08:00
|
|
|
from typing import Any, Dict, List, Optional, Tuple
|
2023-03-29 21:25:32 -07:00
|
|
|
|
|
|
|
import torch
|
|
|
|
from torch import nn
|
|
|
|
from transformers import LlamaConfig
|
|
|
|
|
2024-03-24 21:39:33 -07:00
|
|
|
from vllm.attention import Attention, AttentionMetadata
|
2024-02-28 13:03:28 -08:00
|
|
|
from vllm.config import LoRAConfig
|
2024-04-10 15:33:30 -07:00
|
|
|
from vllm.distributed import (get_tensor_model_parallel_rank,
|
|
|
|
get_tensor_model_parallel_world_size)
|
2023-06-17 03:07:40 -07:00
|
|
|
from vllm.model_executor.layers.activation import SiluAndMul
|
2023-11-15 22:50:41 -08:00
|
|
|
from vllm.model_executor.layers.layernorm import RMSNorm
|
|
|
|
from vllm.model_executor.layers.linear import (LinearMethodBase,
|
|
|
|
MergedColumnParallelLinear,
|
|
|
|
QKVParallelLinear,
|
|
|
|
RowParallelLinear)
|
2024-03-21 07:25:01 +08:00
|
|
|
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
2024-03-25 23:59:47 +09:00
|
|
|
from vllm.model_executor.layers.rotary_embedding import get_rope
|
2023-06-17 03:07:40 -07:00
|
|
|
from vllm.model_executor.layers.sampler import Sampler
|
2023-11-15 22:50:41 -08:00
|
|
|
from vllm.model_executor.layers.vocab_parallel_embedding import (
|
2024-03-25 23:59:47 +09:00
|
|
|
DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
|
2023-11-29 22:16:37 -08:00
|
|
|
from vllm.model_executor.sampling_metadata import SamplingMetadata
|
2023-11-15 22:50:41 -08:00
|
|
|
from vllm.model_executor.weight_utils import (default_weight_loader,
|
2024-04-03 16:15:55 -05:00
|
|
|
hf_model_weights_iterator,
|
|
|
|
kv_cache_scales_loader)
|
2023-09-04 17:29:42 -07:00
|
|
|
from vllm.sequence import SamplerOutput
|
2024-04-03 16:15:55 -05:00
|
|
|
from vllm.utils import is_hip
|
2023-03-29 21:25:32 -07:00
|
|
|
|
|
|
|
|
|
|
|
class LlamaMLP(nn.Module):
|
2023-03-30 11:04:21 -07:00
|
|
|
|
2023-03-29 21:25:32 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
2024-02-13 09:24:59 -08:00
|
|
|
hidden_size: int,
|
|
|
|
intermediate_size: int,
|
|
|
|
hidden_act: str,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method: Optional[LinearMethodBase] = None,
|
2023-09-16 00:03:37 -07:00
|
|
|
) -> None:
|
2023-03-29 21:25:32 -07:00
|
|
|
super().__init__()
|
2023-11-15 22:50:41 -08:00
|
|
|
self.gate_up_proj = MergedColumnParallelLinear(
|
2024-02-13 09:24:59 -08:00
|
|
|
hidden_size, [intermediate_size] * 2,
|
2023-11-15 22:50:41 -08:00
|
|
|
bias=False,
|
|
|
|
linear_method=linear_method)
|
2024-02-13 09:24:59 -08:00
|
|
|
self.down_proj = RowParallelLinear(intermediate_size,
|
|
|
|
hidden_size,
|
2023-11-15 22:50:41 -08:00
|
|
|
bias=False,
|
|
|
|
linear_method=linear_method)
|
2023-07-03 11:31:55 -07:00
|
|
|
if hidden_act != "silu":
|
|
|
|
raise ValueError(f"Unsupported activation: {hidden_act}. "
|
|
|
|
"Only silu is supported for now.")
|
2023-04-02 00:30:17 -07:00
|
|
|
self.act_fn = SiluAndMul()
|
2023-03-29 21:25:32 -07:00
|
|
|
|
|
|
|
def forward(self, x):
|
2023-04-02 15:23:29 +08:00
|
|
|
gate_up, _ = self.gate_up_proj(x)
|
2023-04-02 00:30:17 -07:00
|
|
|
x = self.act_fn(gate_up)
|
2023-03-29 21:25:32 -07:00
|
|
|
x, _ = self.down_proj(x)
|
|
|
|
return x
|
|
|
|
|
|
|
|
|
|
|
|
class LlamaAttention(nn.Module):
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
2024-02-13 09:24:59 -08:00
|
|
|
hidden_size: int,
|
|
|
|
num_heads: int,
|
|
|
|
num_kv_heads: int,
|
|
|
|
rope_theta: float = 10000,
|
|
|
|
rope_scaling: Optional[Dict[str, Any]] = None,
|
|
|
|
max_position_embeddings: int = 8192,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method: Optional[LinearMethodBase] = None,
|
2024-02-13 17:12:05 -08:00
|
|
|
bias: bool = False,
|
2024-02-22 10:25:05 +08:00
|
|
|
sliding_window: Optional[int] = None,
|
2023-09-16 00:03:37 -07:00
|
|
|
) -> None:
|
2023-03-29 21:25:32 -07:00
|
|
|
super().__init__()
|
2024-02-13 09:24:59 -08:00
|
|
|
self.hidden_size = hidden_size
|
2023-07-20 11:38:27 -07:00
|
|
|
tp_size = get_tensor_model_parallel_world_size()
|
2024-02-13 09:24:59 -08:00
|
|
|
self.total_num_heads = num_heads
|
2023-07-20 11:38:27 -07:00
|
|
|
assert self.total_num_heads % tp_size == 0
|
|
|
|
self.num_heads = self.total_num_heads // tp_size
|
2024-02-13 09:24:59 -08:00
|
|
|
self.total_num_kv_heads = num_kv_heads
|
2023-10-02 15:26:33 -07:00
|
|
|
if self.total_num_kv_heads >= tp_size:
|
|
|
|
# Number of KV heads is greater than TP size, so we partition
|
|
|
|
# the KV heads across multiple tensor parallel GPUs.
|
|
|
|
assert self.total_num_kv_heads % tp_size == 0
|
|
|
|
else:
|
|
|
|
# Number of KV heads is less than TP size, so we replicate
|
|
|
|
# the KV heads across multiple tensor parallel GPUs.
|
|
|
|
assert tp_size % self.total_num_kv_heads == 0
|
|
|
|
self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
|
2024-02-13 09:24:59 -08:00
|
|
|
self.head_dim = hidden_size // self.total_num_heads
|
2023-07-20 11:38:27 -07:00
|
|
|
self.q_size = self.num_heads * self.head_dim
|
|
|
|
self.kv_size = self.num_kv_heads * self.head_dim
|
2023-07-03 11:31:55 -07:00
|
|
|
self.scaling = self.head_dim**-0.5
|
2024-02-13 09:24:59 -08:00
|
|
|
self.rope_theta = rope_theta
|
|
|
|
self.max_position_embeddings = max_position_embeddings
|
2023-03-29 21:25:32 -07:00
|
|
|
|
2024-04-03 16:15:55 -05:00
|
|
|
# This will be overwritten by model initialization if we are using it.
|
|
|
|
# N.B. currently we only support per tensor scalar scaling factors
|
|
|
|
# & only applicable to ROCm (AMD GPU).
|
|
|
|
# The scaling factor convention we are assuming is
|
|
|
|
# quantized_value * scaling_factor ~= true_value
|
|
|
|
# which is consistent with the practice of setting
|
|
|
|
# scaling_factor = tensor_amax / FPtype_max
|
|
|
|
self.kv_scale = 1.0
|
|
|
|
|
2023-11-15 22:50:41 -08:00
|
|
|
self.qkv_proj = QKVParallelLinear(
|
2024-02-13 09:24:59 -08:00
|
|
|
hidden_size,
|
2023-07-20 11:38:27 -07:00
|
|
|
self.head_dim,
|
2023-11-15 22:50:41 -08:00
|
|
|
self.total_num_heads,
|
|
|
|
self.total_num_kv_heads,
|
2024-02-13 17:12:05 -08:00
|
|
|
bias=bias,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method=linear_method,
|
2023-03-29 21:25:32 -07:00
|
|
|
)
|
2023-11-15 22:50:41 -08:00
|
|
|
self.o_proj = RowParallelLinear(
|
2023-03-29 21:25:32 -07:00
|
|
|
self.total_num_heads * self.head_dim,
|
2024-02-13 09:24:59 -08:00
|
|
|
hidden_size,
|
2024-02-13 17:12:05 -08:00
|
|
|
bias=bias,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method=linear_method,
|
2023-03-29 21:25:32 -07:00
|
|
|
)
|
2023-11-29 15:37:31 -08:00
|
|
|
|
2024-02-13 09:24:59 -08:00
|
|
|
self.rotary_emb = get_rope(
|
|
|
|
self.head_dim,
|
|
|
|
rotary_dim=self.head_dim,
|
|
|
|
max_position=max_position_embeddings,
|
|
|
|
base=rope_theta,
|
|
|
|
rope_scaling=rope_scaling,
|
|
|
|
)
|
2024-03-07 01:45:50 -08:00
|
|
|
self.attn = Attention(self.num_heads,
|
|
|
|
self.head_dim,
|
|
|
|
self.scaling,
|
|
|
|
num_kv_heads=self.num_kv_heads,
|
|
|
|
sliding_window=sliding_window)
|
2023-03-29 21:25:32 -07:00
|
|
|
|
|
|
|
def forward(
|
|
|
|
self,
|
2023-05-23 17:58:51 -07:00
|
|
|
positions: torch.Tensor,
|
2023-03-29 21:25:32 -07:00
|
|
|
hidden_states: torch.Tensor,
|
2024-03-24 21:39:33 -07:00
|
|
|
kv_cache: torch.Tensor,
|
|
|
|
attn_metadata: AttentionMetadata,
|
2023-03-29 21:25:32 -07:00
|
|
|
) -> torch.Tensor:
|
2023-04-02 15:23:29 +08:00
|
|
|
qkv, _ = self.qkv_proj(hidden_states)
|
2023-07-20 11:38:27 -07:00
|
|
|
q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
|
2024-02-13 09:24:59 -08:00
|
|
|
q, k = self.rotary_emb(positions, q, k)
|
2024-04-03 16:15:55 -05:00
|
|
|
attn_output = self.attn(q, k, v, kv_cache, attn_metadata,
|
|
|
|
self.kv_scale)
|
2023-03-29 21:25:32 -07:00
|
|
|
output, _ = self.o_proj(attn_output)
|
|
|
|
return output
|
|
|
|
|
|
|
|
|
|
|
|
class LlamaDecoderLayer(nn.Module):
|
|
|
|
|
2023-09-16 00:03:37 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
config: LlamaConfig,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method: Optional[LinearMethodBase] = None,
|
2023-09-16 00:03:37 -07:00
|
|
|
) -> None:
|
2023-03-29 21:25:32 -07:00
|
|
|
super().__init__()
|
|
|
|
self.hidden_size = config.hidden_size
|
2024-02-13 09:24:59 -08:00
|
|
|
rope_theta = getattr(config, "rope_theta", 10000)
|
|
|
|
rope_scaling = getattr(config, "rope_scaling", None)
|
|
|
|
max_position_embeddings = getattr(config, "max_position_embeddings",
|
|
|
|
8192)
|
2024-02-22 10:25:05 +08:00
|
|
|
sliding_window = getattr(config, "sliding_window", None)
|
2024-04-09 01:12:35 +05:30
|
|
|
# Support abacusai/Smaug-72B-v0.1 with attention_bias
|
|
|
|
# Support internlm/internlm-7b with bias
|
|
|
|
attention_bias = getattr(config, "attention_bias", False) or getattr(
|
|
|
|
config, "bias", False)
|
2023-03-29 21:25:32 -07:00
|
|
|
self.self_attn = LlamaAttention(
|
2024-02-13 09:24:59 -08:00
|
|
|
hidden_size=self.hidden_size,
|
|
|
|
num_heads=config.num_attention_heads,
|
2024-02-13 18:01:15 -08:00
|
|
|
num_kv_heads=getattr(config, "num_key_value_heads",
|
|
|
|
config.num_attention_heads),
|
2024-02-13 09:24:59 -08:00
|
|
|
rope_theta=rope_theta,
|
|
|
|
rope_scaling=rope_scaling,
|
|
|
|
max_position_embeddings=max_position_embeddings,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method=linear_method,
|
2024-04-09 01:12:35 +05:30
|
|
|
bias=attention_bias,
|
2024-02-22 10:25:05 +08:00
|
|
|
sliding_window=sliding_window,
|
2023-03-29 21:25:32 -07:00
|
|
|
)
|
|
|
|
self.mlp = LlamaMLP(
|
2024-02-13 09:24:59 -08:00
|
|
|
hidden_size=self.hidden_size,
|
|
|
|
intermediate_size=config.intermediate_size,
|
|
|
|
hidden_act=config.hidden_act,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method=linear_method,
|
2023-03-29 21:25:32 -07:00
|
|
|
)
|
2024-02-13 09:24:59 -08:00
|
|
|
self.input_layernorm = RMSNorm(config.hidden_size,
|
|
|
|
eps=config.rms_norm_eps)
|
|
|
|
self.post_attention_layernorm = RMSNorm(config.hidden_size,
|
|
|
|
eps=config.rms_norm_eps)
|
2023-03-29 21:25:32 -07:00
|
|
|
|
|
|
|
def forward(
|
|
|
|
self,
|
2023-05-23 17:58:51 -07:00
|
|
|
positions: torch.Tensor,
|
2023-03-29 21:25:32 -07:00
|
|
|
hidden_states: torch.Tensor,
|
2024-03-24 21:39:33 -07:00
|
|
|
kv_cache: torch.Tensor,
|
|
|
|
attn_metadata: AttentionMetadata,
|
2023-11-19 10:18:02 +08:00
|
|
|
residual: Optional[torch.Tensor],
|
|
|
|
) -> Tuple[torch.Tensor, torch.Tensor]:
|
2023-03-29 21:25:32 -07:00
|
|
|
# Self Attention
|
2023-11-19 10:18:02 +08:00
|
|
|
if residual is None:
|
|
|
|
residual = hidden_states
|
|
|
|
hidden_states = self.input_layernorm(hidden_states)
|
|
|
|
else:
|
|
|
|
hidden_states, residual = self.input_layernorm(
|
|
|
|
hidden_states, residual)
|
2023-03-29 21:25:32 -07:00
|
|
|
hidden_states = self.self_attn(
|
|
|
|
positions=positions,
|
|
|
|
hidden_states=hidden_states,
|
|
|
|
kv_cache=kv_cache,
|
2024-03-24 21:39:33 -07:00
|
|
|
attn_metadata=attn_metadata,
|
2023-03-29 21:25:32 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
# Fully Connected
|
2023-11-19 10:18:02 +08:00
|
|
|
hidden_states, residual = self.post_attention_layernorm(
|
|
|
|
hidden_states, residual)
|
2023-03-29 21:25:32 -07:00
|
|
|
hidden_states = self.mlp(hidden_states)
|
2023-11-19 10:18:02 +08:00
|
|
|
return hidden_states, residual
|
2023-03-29 21:25:32 -07:00
|
|
|
|
|
|
|
|
|
|
|
class LlamaModel(nn.Module):
|
|
|
|
|
2023-09-16 00:03:37 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
config: LlamaConfig,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method: Optional[LinearMethodBase] = None,
|
2024-01-24 00:26:37 +01:00
|
|
|
lora_config: Optional[LoRAConfig] = None,
|
2023-09-16 00:03:37 -07:00
|
|
|
) -> None:
|
2023-03-29 21:25:32 -07:00
|
|
|
super().__init__()
|
|
|
|
self.config = config
|
|
|
|
self.padding_idx = config.pad_token_id
|
2024-01-24 00:26:37 +01:00
|
|
|
lora_vocab = (lora_config.lora_extra_vocab_size *
|
|
|
|
(lora_config.max_loras or 1)) if lora_config else 0
|
|
|
|
self.vocab_size = config.vocab_size + lora_vocab
|
|
|
|
self.org_vocab_size = config.vocab_size
|
2023-07-03 11:31:55 -07:00
|
|
|
self.embed_tokens = VocabParallelEmbedding(
|
2024-01-24 00:26:37 +01:00
|
|
|
self.vocab_size,
|
2023-10-02 15:36:09 -07:00
|
|
|
config.hidden_size,
|
2024-01-24 00:26:37 +01:00
|
|
|
org_num_embeddings=config.vocab_size,
|
2023-10-02 15:36:09 -07:00
|
|
|
)
|
2023-07-03 11:31:55 -07:00
|
|
|
self.layers = nn.ModuleList([
|
2024-02-13 09:24:59 -08:00
|
|
|
LlamaDecoderLayer(config, linear_method)
|
2023-09-16 00:03:37 -07:00
|
|
|
for _ in range(config.num_hidden_layers)
|
2023-07-03 11:31:55 -07:00
|
|
|
])
|
2024-02-13 09:24:59 -08:00
|
|
|
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
2023-03-29 21:25:32 -07:00
|
|
|
|
2024-03-25 14:16:30 -07:00
|
|
|
def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
|
|
|
|
return self.embed_tokens(input_ids)
|
|
|
|
|
2023-03-29 21:25:32 -07:00
|
|
|
def forward(
|
|
|
|
self,
|
2024-03-25 14:16:30 -07:00
|
|
|
input_ids: Optional[torch.Tensor],
|
2023-05-23 17:58:51 -07:00
|
|
|
positions: torch.Tensor,
|
2024-03-24 21:39:33 -07:00
|
|
|
kv_caches: List[torch.Tensor],
|
|
|
|
attn_metadata: AttentionMetadata,
|
2024-03-25 14:16:30 -07:00
|
|
|
inputs_embeds: Optional[torch.Tensor] = None,
|
2023-03-29 21:25:32 -07:00
|
|
|
) -> torch.Tensor:
|
2024-03-25 14:16:30 -07:00
|
|
|
if inputs_embeds is not None:
|
|
|
|
hidden_states = inputs_embeds
|
|
|
|
else:
|
|
|
|
hidden_states = self.get_input_embeddings(input_ids)
|
2023-11-19 10:18:02 +08:00
|
|
|
residual = None
|
2023-03-29 21:25:32 -07:00
|
|
|
for i in range(len(self.layers)):
|
|
|
|
layer = self.layers[i]
|
2023-11-19 10:18:02 +08:00
|
|
|
hidden_states, residual = layer(
|
2023-03-29 21:25:32 -07:00
|
|
|
positions,
|
|
|
|
hidden_states,
|
|
|
|
kv_caches[i],
|
2024-03-24 21:39:33 -07:00
|
|
|
attn_metadata,
|
2023-11-19 10:18:02 +08:00
|
|
|
residual,
|
2023-03-29 21:25:32 -07:00
|
|
|
)
|
2023-11-19 10:18:02 +08:00
|
|
|
hidden_states, _ = self.norm(hidden_states, residual)
|
2023-03-29 21:25:32 -07:00
|
|
|
return hidden_states
|
|
|
|
|
|
|
|
|
|
|
|
class LlamaForCausalLM(nn.Module):
|
2024-02-13 15:55:45 -08:00
|
|
|
packed_modules_mapping = {
|
|
|
|
"qkv_proj": [
|
|
|
|
"q_proj",
|
|
|
|
"k_proj",
|
|
|
|
"v_proj",
|
|
|
|
],
|
|
|
|
"gate_up_proj": [
|
|
|
|
"gate_proj",
|
|
|
|
"up_proj",
|
|
|
|
],
|
|
|
|
}
|
|
|
|
|
|
|
|
# LoRA specific attributes
|
|
|
|
supported_lora_modules = [
|
|
|
|
"qkv_proj",
|
|
|
|
"o_proj",
|
|
|
|
"gate_up_proj",
|
|
|
|
"down_proj",
|
|
|
|
"embed_tokens",
|
|
|
|
"lm_head",
|
|
|
|
]
|
|
|
|
embedding_modules = {
|
|
|
|
"embed_tokens": "input_embeddings",
|
|
|
|
"lm_head": "output_embeddings",
|
|
|
|
}
|
|
|
|
embedding_padding_modules = ["lm_head"]
|
2023-07-03 11:31:55 -07:00
|
|
|
|
2023-09-16 00:03:37 -07:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
config: LlamaConfig,
|
2023-11-15 22:50:41 -08:00
|
|
|
linear_method: Optional[LinearMethodBase] = None,
|
2024-01-24 00:26:37 +01:00
|
|
|
lora_config: Optional[LoRAConfig] = None,
|
2023-09-16 00:03:37 -07:00
|
|
|
) -> None:
|
2023-03-29 21:25:32 -07:00
|
|
|
super().__init__()
|
|
|
|
self.config = config
|
2023-11-15 22:50:41 -08:00
|
|
|
self.linear_method = linear_method
|
2024-02-13 09:24:59 -08:00
|
|
|
self.model = LlamaModel(config, linear_method, lora_config=lora_config)
|
2024-02-13 15:55:45 -08:00
|
|
|
self.unpadded_vocab_size = config.vocab_size
|
2024-01-24 00:26:37 +01:00
|
|
|
if lora_config:
|
2024-02-13 15:55:45 -08:00
|
|
|
self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
|
2024-01-24 00:26:37 +01:00
|
|
|
self.lm_head = ParallelLMHead(
|
2024-02-13 15:55:45 -08:00
|
|
|
self.unpadded_vocab_size,
|
2024-01-24 00:26:37 +01:00
|
|
|
config.hidden_size,
|
|
|
|
org_num_embeddings=config.vocab_size,
|
|
|
|
padding_size=DEFAULT_VOCAB_PADDING_SIZE
|
|
|
|
# We need bigger padding if using lora for kernel
|
|
|
|
# compatibility
|
|
|
|
if not lora_config else lora_config.lora_vocab_padding_size,
|
|
|
|
)
|
2024-03-21 07:25:01 +08:00
|
|
|
|
|
|
|
logit_scale = getattr(config, "logit_scale", 1.0)
|
|
|
|
self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
|
|
|
|
config.vocab_size, logit_scale)
|
|
|
|
self.sampler = Sampler()
|
2023-03-29 21:25:32 -07:00
|
|
|
|
|
|
|
def forward(
|
|
|
|
self,
|
2023-05-23 17:58:51 -07:00
|
|
|
input_ids: torch.Tensor,
|
|
|
|
positions: torch.Tensor,
|
2024-03-24 21:39:33 -07:00
|
|
|
kv_caches: List[torch.Tensor],
|
|
|
|
attn_metadata: AttentionMetadata,
|
2023-11-29 22:16:37 -08:00
|
|
|
) -> torch.Tensor:
|
2023-07-03 11:31:55 -07:00
|
|
|
hidden_states = self.model(input_ids, positions, kv_caches,
|
2024-03-24 21:39:33 -07:00
|
|
|
attn_metadata)
|
2023-11-29 22:16:37 -08:00
|
|
|
return hidden_states
|
|
|
|
|
2024-03-21 07:25:01 +08:00
|
|
|
def compute_logits(self, hidden_states: torch.Tensor,
|
|
|
|
sampling_metadata: SamplingMetadata) -> torch.Tensor:
|
|
|
|
logits = self.logits_processor(self.lm_head.weight, hidden_states,
|
|
|
|
sampling_metadata)
|
|
|
|
return logits
|
|
|
|
|
2023-11-29 22:16:37 -08:00
|
|
|
def sample(
|
|
|
|
self,
|
2024-03-21 07:25:01 +08:00
|
|
|
logits: torch.Tensor,
|
2023-11-29 22:16:37 -08:00
|
|
|
sampling_metadata: SamplingMetadata,
|
2024-01-04 03:30:22 +08:00
|
|
|
) -> Optional[SamplerOutput]:
|
2024-03-21 07:25:01 +08:00
|
|
|
next_tokens = self.sampler(logits, sampling_metadata)
|
2023-03-29 21:25:32 -07:00
|
|
|
return next_tokens
|
|
|
|
|
2023-07-03 11:31:55 -07:00
|
|
|
def load_weights(self,
|
|
|
|
model_name_or_path: str,
|
2023-05-03 15:32:04 +08:00
|
|
|
cache_dir: Optional[str] = None,
|
2023-09-14 06:20:02 +08:00
|
|
|
load_format: str = "auto",
|
|
|
|
revision: Optional[str] = None):
|
2023-11-15 22:50:41 -08:00
|
|
|
stacked_params_mapping = [
|
|
|
|
# (param_name, shard_name, shard_id)
|
|
|
|
("qkv_proj", "q_proj", "q"),
|
|
|
|
("qkv_proj", "k_proj", "k"),
|
|
|
|
("qkv_proj", "v_proj", "v"),
|
|
|
|
("gate_up_proj", "gate_proj", 0),
|
|
|
|
("gate_up_proj", "up_proj", 1),
|
2023-07-20 11:38:27 -07:00
|
|
|
]
|
2023-11-15 22:50:41 -08:00
|
|
|
params_dict = dict(self.named_parameters())
|
2023-05-03 15:32:04 +08:00
|
|
|
for name, loaded_weight in hf_model_weights_iterator(
|
2023-09-14 06:20:02 +08:00
|
|
|
model_name_or_path, cache_dir, load_format, revision):
|
2023-05-03 15:32:04 +08:00
|
|
|
if "rotary_emb.inv_freq" in name:
|
|
|
|
continue
|
2023-12-10 10:04:12 -08:00
|
|
|
if ("rotary_emb.cos_cached" in name
|
|
|
|
or "rotary_emb.sin_cached" in name):
|
|
|
|
# Models trained using ColossalAI may include these tensors in
|
|
|
|
# the checkpoint. Skip them.
|
2023-12-10 07:59:57 +08:00
|
|
|
continue
|
2023-11-15 22:50:41 -08:00
|
|
|
for (param_name, weight_name, shard_id) in stacked_params_mapping:
|
2023-07-20 11:38:27 -07:00
|
|
|
if weight_name not in name:
|
2023-05-03 15:32:04 +08:00
|
|
|
continue
|
2023-12-15 19:04:22 +08:00
|
|
|
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]
|
2023-11-15 22:50:41 -08:00
|
|
|
weight_loader = param.weight_loader
|
|
|
|
weight_loader(param, loaded_weight, shard_id)
|
2023-05-03 15:32:04 +08:00
|
|
|
break
|
2023-11-15 22:50:41 -08:00
|
|
|
else:
|
2023-12-15 19:04:22 +08:00
|
|
|
# Skip loading extra bias for GPTQ models.
|
|
|
|
if name.endswith(".bias") and name not in params_dict:
|
|
|
|
continue
|
2023-11-15 22:50:41 -08:00
|
|
|
param = params_dict[name]
|
|
|
|
weight_loader = getattr(param, "weight_loader",
|
|
|
|
default_weight_loader)
|
|
|
|
weight_loader(param, loaded_weight)
|
2024-04-03 16:15:55 -05:00
|
|
|
|
|
|
|
# If this function is called, it should always initialize KV cache scale
|
|
|
|
# factors (or else raise an exception). Thus, handled exceptions should
|
|
|
|
# make sure to leave KV cache scale factors in a known good (dummy) state
|
|
|
|
def load_kv_cache_scales(self, quantization_param_path: str) -> None:
|
|
|
|
tp_size = get_tensor_model_parallel_world_size()
|
|
|
|
tp_rank = get_tensor_model_parallel_rank()
|
|
|
|
for layer_idx, scaling_factor in kv_cache_scales_loader(
|
|
|
|
quantization_param_path, tp_rank, tp_size,
|
|
|
|
self.config.num_hidden_layers,
|
|
|
|
self.config.__class__.model_type):
|
|
|
|
layer_self_attn = self.model.layers[layer_idx].self_attn
|
|
|
|
|
|
|
|
if is_hip():
|
|
|
|
# The scaling factor convention we are assuming is
|
|
|
|
# quantized_value * scaling_factor ~= true_value
|
|
|
|
# which is consistent with the practice of setting
|
|
|
|
# scaling_factor = tensor_amax / FPtype_max
|
|
|
|
scaling_factor *= 2
|
|
|
|
if hasattr(layer_self_attn, "kv_scale"):
|
|
|
|
layer_self_attn.kv_scale = scaling_factor
|
|
|
|
else:
|
|
|
|
raise RuntimeError("Self attention has no KV cache scaling "
|
|
|
|
"factor attribute!")
|