|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | + |
| 4 | +from collections.abc import Iterable |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +import torch |
| 8 | +import torch.nn as nn |
| 9 | + |
| 10 | +from vllm.compilation.decorators import support_torch_compile |
| 11 | +from vllm.config import VllmConfig |
| 12 | +from vllm.distributed import get_pp_group |
| 13 | +from vllm.logger import init_logger |
| 14 | +from vllm.model_executor.layers.layernorm import RMSNorm |
| 15 | +from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 16 | +from vllm.model_executor.layers.quantization.base_config import ( |
| 17 | + QuantizationConfig) |
| 18 | +from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 19 | + VocabParallelEmbedding) |
| 20 | +from vllm.model_executor.model_loader.weight_utils import default_weight_loader |
| 21 | +from vllm.model_executor.models.qwen2 import (Qwen2DecoderLayer, |
| 22 | + Qwen2ForCausalLM) |
| 23 | +from vllm.sequence import IntermediateTensors |
| 24 | + |
| 25 | +from .interfaces import MultiModalEmbeddings |
| 26 | +from .utils import (AutoWeightsLoader, PPMissingLayer, maybe_prefix, |
| 27 | + merge_multimodal_embeddings) |
| 28 | + |
| 29 | +logger = init_logger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +@support_torch_compile |
| 33 | +class Qwen2_5Model(nn.Module): |
| 34 | + |
| 35 | + def __init__( |
| 36 | + self, |
| 37 | + *, |
| 38 | + vllm_config: VllmConfig, |
| 39 | + prefix: str = "", |
| 40 | + start_layer_id: int = 0, |
| 41 | + quant_config: Optional[QuantizationConfig] = None, |
| 42 | + ) -> None: |
| 43 | + super().__init__() |
| 44 | + self.config = ( |
| 45 | + vllm_config.speculative_config.draft_model_config.hf_config) |
| 46 | + self.multimodal_config = (vllm_config.speculative_config. |
| 47 | + draft_model_config.multimodal_config) |
| 48 | + # embbeding |
| 49 | + if get_pp_group().is_first_rank or (self.config.tie_word_embeddings |
| 50 | + and get_pp_group().is_last_rank): |
| 51 | + self.embed_tokens = VocabParallelEmbedding( |
| 52 | + self.config.vocab_size, |
| 53 | + self.config.hidden_size, |
| 54 | + quant_config=quant_config, |
| 55 | + prefix=f"{prefix}.embed_tokens", |
| 56 | + ) |
| 57 | + else: |
| 58 | + self.embed_tokens = PPMissingLayer() |
| 59 | + |
| 60 | + # language model initial |
| 61 | + self.layers = nn.ModuleList([ |
| 62 | + Qwen2DecoderLayer( |
| 63 | + self.config, |
| 64 | + quant_config=quant_config, |
| 65 | + prefix=maybe_prefix(prefix, f"layers.{i + start_layer_id}"), |
| 66 | + ) for i in range(self.config.num_hidden_layers) |
| 67 | + ]) |
| 68 | + # Eagle feature fusion |
| 69 | + self.fc = torch.nn.Linear(self.config.hidden_size * 2, |
| 70 | + self.config.hidden_size, |
| 71 | + bias=False) |
| 72 | + self.norm = RMSNorm(self.config.hidden_size, |
| 73 | + eps=self.config.rms_norm_eps) |
| 74 | + |
| 75 | + def get_input_embeddings( |
| 76 | + self, |
| 77 | + input_ids: torch.Tensor, |
| 78 | + ) -> torch.Tensor: |
| 79 | + return self.embed_tokens(input_ids) |
| 80 | + |
| 81 | + def forward( |
| 82 | + self, |
| 83 | + input_ids: Optional[torch.Tensor], |
| 84 | + positions: torch.Tensor, |
| 85 | + hidden_states: torch.Tensor, |
| 86 | + inputs_embeds: Optional[torch.Tensor] = None, |
| 87 | + intermediate_tensors: Optional[IntermediateTensors] = None, |
| 88 | + ) -> tuple[torch.Tensor, torch.Tensor]: |
| 89 | + if inputs_embeds is None: |
| 90 | + inputs_embeds = self.get_input_embeddings(input_ids) |
| 91 | + # Eagle feature fusion |
| 92 | + hidden_states = self.fc( |
| 93 | + torch.cat((inputs_embeds, hidden_states), dim=-1)) |
| 94 | + residual = None |
| 95 | + for layer in self.layers: |
| 96 | + hidden_states, residual = layer( |
| 97 | + positions, |
| 98 | + hidden_states, |
| 99 | + residual, |
| 100 | + ) |
| 101 | + hidden_states, _ = self.norm(hidden_states, residual) |
| 102 | + return hidden_states, hidden_states |
| 103 | + |
| 104 | + def load_weights(self, weights: Iterable[tuple[str, |
| 105 | + torch.Tensor]]) -> set[str]: |
| 106 | + stacked_params_mapping = [ |
| 107 | + # (param_name, shard_name, shard_id) |
| 108 | + ("qkv_proj", "q_proj", "q"), |
| 109 | + ("qkv_proj", "k_proj", "k"), |
| 110 | + ("qkv_proj", "v_proj", "v"), |
| 111 | + ("gate_up_proj", "gate_proj", 0), |
| 112 | + ("gate_up_proj", "up_proj", 1), |
| 113 | + ] |
| 114 | + params_dict = dict(self.named_parameters()) |
| 115 | + loaded_params: set[str] = set() |
| 116 | + for name, loaded_weight in weights: |
| 117 | + # name = name.removeprefix("model.") |
| 118 | + # TODO :related to the trained model and may need to be modified |
| 119 | + if (name.find("t2d") or name.find("d2t") |
| 120 | + or name.find("hidden_norm")) and name not in params_dict: |
| 121 | + continue |
| 122 | + for param_name, weight_name, shard_id in stacked_params_mapping: |
| 123 | + if weight_name not in name: |
| 124 | + continue |
| 125 | + name = name.replace(weight_name, param_name) |
| 126 | + param = params_dict[name] |
| 127 | + weight_loader = param.weight_loader |
| 128 | + weight_loader(param, loaded_weight, shard_id) |
| 129 | + break |
| 130 | + else: |
| 131 | + # if PP disabled then draft will share embed with target |
| 132 | + if get_pp_group().world_size == 1 and \ |
| 133 | + "embed_tokens." in name: |
| 134 | + continue |
| 135 | + param = params_dict[name] |
| 136 | + weight_loader = getattr(param, "weight_loader", |
| 137 | + default_weight_loader) |
| 138 | + # TODO: train a suitable model |
| 139 | + if name.startswith("fc"): |
| 140 | + loaded_weight = loaded_weight[:, :self.config.hidden_size * |
| 141 | + 2] |
| 142 | + weight_loader(param, loaded_weight) |
| 143 | + loaded_params.add(name) |
| 144 | + return loaded_params |
| 145 | + |
| 146 | + |
| 147 | +class EagleQwen2_5_VLForCausalLM(Qwen2ForCausalLM): |
| 148 | + |
| 149 | + def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 150 | + nn.Module.__init__(self) |
| 151 | + self.config = vllm_config.speculative_config.\ |
| 152 | + draft_model_config.hf_config |
| 153 | + self.multimodal_config = vllm_config.model_config.multimodal_config |
| 154 | + |
| 155 | + # The number of layers in the target model |
| 156 | + # start_layer_id for the draft model |
| 157 | + target_layer_num = vllm_config.model_config.get_num_layers( |
| 158 | + vllm_config.parallel_config) |
| 159 | + # draft model quantization config may differ from target model |
| 160 | + quant_config = VllmConfig.get_quantization_config( |
| 161 | + vllm_config.speculative_config.draft_model_config, |
| 162 | + vllm_config.load_config) |
| 163 | + # Initialize the EAGLE model of QWEN2.5 |
| 164 | + self.model = Qwen2_5Model(vllm_config=vllm_config, |
| 165 | + prefix=maybe_prefix(prefix, "draft_model"), |
| 166 | + start_layer_id=target_layer_num, |
| 167 | + quant_config=quant_config) |
| 168 | + |
| 169 | + logit_scale = getattr(self.config, "logit_scale", 1.0) |
| 170 | + self.logits_processor = LogitsProcessor(self.config.vocab_size, |
| 171 | + scale=logit_scale) |
| 172 | + |
| 173 | + def load_weights(self, weights): |
| 174 | + loader = AutoWeightsLoader( |
| 175 | + self, |
| 176 | + skip_prefixes=(["lm_head."]), |
| 177 | + ) |
| 178 | + model_weights = {} |
| 179 | + |
| 180 | + for name, loaded_weight in weights: |
| 181 | + if "lm_head" not in name: |
| 182 | + name = "model." + name |
| 183 | + model_weights[name] = loaded_weight |
| 184 | + |
| 185 | + loader.load_weights(model_weights.items()) |
| 186 | + |
| 187 | + def forward( |
| 188 | + self, |
| 189 | + input_ids: torch.Tensor, |
| 190 | + positions: torch.Tensor, |
| 191 | + hidden_states: torch.Tensor, |
| 192 | + inputs_embeds: Optional[torch.Tensor] = None, |
| 193 | + **kwargs: object, |
| 194 | + ) -> tuple[torch.Tensor, torch.Tensor]: |
| 195 | + return self.model(input_ids, positions, hidden_states, inputs_embeds) |
| 196 | + |
| 197 | + def get_input_embeddings( |
| 198 | + self, |
| 199 | + input_ids: torch.Tensor, |
| 200 | + multimodal_embeddings: Optional[MultiModalEmbeddings] = None, |
| 201 | + ) -> torch.Tensor: |
| 202 | + inputs_embeds = self.model.get_input_embeddings(input_ids) |
| 203 | + if multimodal_embeddings is not None \ |
| 204 | + and len(multimodal_embeddings) != 0: |
| 205 | + inputs_embeds = merge_multimodal_embeddings( |
| 206 | + input_ids, inputs_embeds, multimodal_embeddings, |
| 207 | + self.config.image_token_index) |
| 208 | + return inputs_embeds |
0 commit comments