| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | # Adapted from |
| 5 | # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py |
| 6 | # Copyright 2023 The vLLM team. |
| 7 | # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. |
| 8 | # |
| 9 | # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX |
| 10 | # and OPT implementations in this library. It has been modified from its |
| 11 | # original forms to accommodate minor architectural differences compared |
| 12 | # to GPT-NeoX and OPT used by the Meta AI team that trained the model. |
| 13 | # |
| 14 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 15 | # you may not use this file except in compliance with the License. |
| 16 | # You may obtain a copy of the License at |
| 17 | # |
| 18 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 19 | # |
| 20 | # Unless required by applicable law or agreed to in writing, software |
| 21 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 22 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 23 | # See the License for the specific language governing permissions and |
| 24 | # limitations under the License. |
| 25 | """Inference-only GraniteMoe model.""" |
| 26 | |
| 27 | from collections.abc import Iterable |
| 28 | from itertools import islice |
| 29 | |
| 30 | import torch |
| 31 | from torch import nn |
| 32 | from transformers.configuration_utils import PreTrainedConfig |
| 33 | |
| 34 | from vllm.compilation.decorators import support_torch_compile |
| 35 | from vllm.config import CacheConfig, VllmConfig |
| 36 | from vllm.distributed import ( |
| 37 | get_pp_group, |
| 38 | get_tensor_model_parallel_world_size, |
| 39 | tensor_model_parallel_all_gather, |
| 40 | ) |
| 41 | from vllm.model_executor.layers.attention import Attention |
| 42 | from vllm.model_executor.layers.fused_moe import ( |
| 43 | FusedMoEFactory, |
| 44 | GateLinear, |
| 45 | ) |
| 46 | from vllm.model_executor.layers.layernorm import RMSNorm |
| 47 | from vllm.model_executor.layers.linear import ( |
| 48 | QKVParallelLinear, |
| 49 | RowParallelLinear, |
| 50 | ) |
| 51 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 52 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 53 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 54 | from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 55 | ParallelLMHead, |
| 56 | VocabParallelEmbedding, |
| 57 | ) |
| 58 | from vllm.model_executor.model_loader.weight_utils import sharded_weight_loader |
| 59 | from vllm.model_executor.models.utils import sequence_parallel_chunk |
| 60 | from vllm.model_executor.utils import set_weight_attrs |
| 61 | from vllm.sequence import IntermediateTensors |
| 62 | |
| 63 | from .granite import granite_layer_attn_params |
| 64 | from .interfaces import SupportsLoRA, SupportsPP |
| 65 | from .utils import ( |
| 66 | AutoWeightsLoader, |
| 67 | WeightsMapper, |
| 68 | extract_layer_index, |
| 69 | make_layers, |
| 70 | maybe_prefix, |
| 71 | ) |
| 72 | |
| 73 | |
| 74 | class GraniteMoeMoE(nn.Module): |
| 75 | """A tensor-parallel MoE implementation for GraniteMoe that shards each |
| 76 | expert across all ranks. |
| 77 | Each expert's weights are sharded across all ranks and a fused MoE |
| 78 | kernel is used for the forward pass, and finally we reduce the outputs |
| 79 | across ranks. |
| 80 | """ |
| 81 | |
| 82 | def __init__( |
| 83 | self, |
| 84 | num_experts: int, |
| 85 | top_k: int, |
| 86 | hidden_size: int, |
| 87 | intermediate_size: int, |
| 88 | params_dtype: torch.dtype | None = None, |
| 89 | quant_config: QuantizationConfig | None = None, |
| 90 | tp_size: int | None = None, |
| 91 | is_sequence_parallel=False, |
| 92 | prefix: str = "", |
| 93 | ): |
| 94 | super().__init__() |
| 95 | self.hidden_size = hidden_size |
| 96 | self.is_sequence_parallel = is_sequence_parallel |
| 97 | |
| 98 | # Gate always runs at half / full precision for now. |
| 99 | self.gate = GateLinear( |
| 100 | hidden_size, |
| 101 | num_experts, |
| 102 | params_dtype=params_dtype, |
| 103 | prefix=f"{prefix}.gate", |
| 104 | ) |
| 105 | |
| 106 | self.experts = FusedMoEFactory( |
| 107 | num_experts=num_experts, |
| 108 | top_k=top_k, |
| 109 | hidden_size=hidden_size, |
| 110 | intermediate_size=intermediate_size, |
| 111 | params_dtype=params_dtype, |
| 112 | renormalize=True, |
| 113 | quant_config=quant_config, |
| 114 | tp_size=tp_size, |
| 115 | prefix=f"{prefix}.experts", |
| 116 | is_sequence_parallel=self.is_sequence_parallel, |
| 117 | ) |
| 118 | |
| 119 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 120 | # NOTE: hidden_states can have either 1D or 2D shape. |
| 121 | orig_shape = hidden_states.shape |
| 122 | hidden_states = hidden_states.view(-1, self.hidden_size) |
| 123 | |
| 124 | if self.is_sequence_parallel: |
| 125 | hidden_states = sequence_parallel_chunk(hidden_states) |
| 126 | |
| 127 | # router_logits: (num_tokens, n_experts) |
| 128 | router_logits, _ = self.gate(hidden_states) |
| 129 | final_hidden_states = self.experts(hidden_states, router_logits) |
| 130 | |
| 131 | if self.is_sequence_parallel: |
| 132 | final_hidden_states = tensor_model_parallel_all_gather( |
| 133 | final_hidden_states, 0 |
| 134 | ) |
| 135 | num_tokens = orig_shape[0] |
| 136 | final_hidden_states = final_hidden_states[:num_tokens] |
| 137 | |
| 138 | return final_hidden_states.view(orig_shape) |
| 139 | |
| 140 | |
| 141 | class GraniteMoeAttention(nn.Module): |
| 142 | def __init__( |
| 143 | self, |
| 144 | config: PreTrainedConfig, |
| 145 | hidden_size: int, |
| 146 | num_heads: int, |
| 147 | num_kv_heads: int, |
| 148 | max_position: int = 4096 * 32, |
| 149 | cache_config: CacheConfig | None = None, |
| 150 | quant_config: QuantizationConfig | None = None, |
| 151 | attention_multiplier: float | None = None, |
| 152 | prefix: str = "", |
| 153 | ) -> None: |
| 154 | super().__init__() |
| 155 | self.hidden_size = hidden_size |
| 156 | tp_size = get_tensor_model_parallel_world_size() |
| 157 | self.total_num_heads = num_heads |
| 158 | assert self.total_num_heads % tp_size == 0 |
| 159 | self.num_heads = self.total_num_heads // tp_size |
| 160 | self.total_num_kv_heads = num_kv_heads |
| 161 | if self.total_num_kv_heads >= tp_size: |
| 162 | # Number of KV heads is greater than TP size, so we partition |
| 163 | # the KV heads across multiple tensor parallel GPUs. |
| 164 | assert self.total_num_kv_heads % tp_size == 0 |
| 165 | else: |
| 166 | # Number of KV heads is less than TP size, so we replicate |
| 167 | # the KV heads across multiple tensor parallel GPUs. |
| 168 | assert tp_size % self.total_num_kv_heads == 0 |
| 169 | self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) |
| 170 | self.head_dim = hidden_size // self.total_num_heads |
| 171 | self.q_size = self.num_heads * self.head_dim |
| 172 | self.kv_size = self.num_kv_heads * self.head_dim |
| 173 | self.scaling = ( |
| 174 | attention_multiplier |
| 175 | if attention_multiplier is not None |
| 176 | else self.head_dim**-1 |
| 177 | ) |
| 178 | |
| 179 | self.qkv_proj = QKVParallelLinear( |
| 180 | hidden_size, |
| 181 | self.head_dim, |
| 182 | self.total_num_heads, |
| 183 | self.total_num_kv_heads, |
| 184 | bias=False, |
| 185 | quant_config=quant_config, |
| 186 | prefix=f"{prefix}.qkv_proj", |
| 187 | ) |
| 188 | self.o_proj = RowParallelLinear( |
| 189 | self.total_num_heads * self.head_dim, |
| 190 | hidden_size, |
| 191 | bias=False, |
| 192 | quant_config=quant_config, |
| 193 | prefix=f"{prefix}.o_proj", |
| 194 | ) |
| 195 | sliding_window, rope_theta, has_sink = granite_layer_attn_params( |
| 196 | config, extract_layer_index(prefix) |
| 197 | ) |
| 198 | |
| 199 | self.use_rope = rope_theta != 0 |
| 200 | if self.use_rope: |
| 201 | self.rotary_emb = get_rope( |
| 202 | self.head_dim, |
| 203 | max_position=max_position, |
| 204 | rope_parameters={**config.rope_parameters, "rope_theta": rope_theta}, |
| 205 | is_neox_style=True, |
| 206 | ) |
| 207 | |
| 208 | if has_sink: |
| 209 | self.sinks = nn.Parameter(torch.empty(self.num_heads), requires_grad=False) |
| 210 | set_weight_attrs(self.sinks, {"weight_loader": sharded_weight_loader(0)}) |
| 211 | else: |
| 212 | self.sinks = None |
| 213 | |
| 214 | self.attn = Attention( |
| 215 | self.num_heads, |
| 216 | self.head_dim, |
| 217 | self.scaling, |
| 218 | num_kv_heads=self.num_kv_heads, |
| 219 | cache_config=cache_config, |
| 220 | quant_config=quant_config, |
| 221 | per_layer_sliding_window=sliding_window, |
| 222 | prefix=f"{prefix}.attn", |
| 223 | sinks=self.sinks, |
| 224 | ) |
| 225 | |
| 226 | def forward( |
| 227 | self, |
| 228 | positions: torch.Tensor, |
| 229 | hidden_states: torch.Tensor, |
| 230 | ) -> torch.Tensor: |
| 231 | qkv, _ = self.qkv_proj(hidden_states) |
| 232 | q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) |
| 233 | if self.use_rope: |
| 234 | q, k = self.rotary_emb(positions, q, k) |
| 235 | attn_output = self.attn(q, k, v) |
| 236 | output, _ = self.o_proj(attn_output) |
| 237 | return output |
| 238 | |
| 239 | |
| 240 | class GraniteMoeDecoderLayer(nn.Module): |
| 241 | def __init__( |
| 242 | self, |
| 243 | vllm_config: VllmConfig, |
| 244 | prefix: str = "", |
| 245 | ) -> None: |
| 246 | super().__init__() |
| 247 | |
| 248 | config = vllm_config.model_config.hf_config |
| 249 | cache_config = vllm_config.cache_config |
| 250 | quant_config = vllm_config.quant_config |
| 251 | parallel_config = vllm_config.parallel_config |
| 252 | |
| 253 | self.hidden_size = config.hidden_size |
| 254 | self.self_attn = GraniteMoeAttention( |
| 255 | config=config, |
| 256 | hidden_size=self.hidden_size, |
| 257 | num_heads=config.num_attention_heads, |
| 258 | max_position=config.max_position_embeddings, |
| 259 | num_kv_heads=config.num_key_value_heads, |
| 260 | cache_config=cache_config, |
| 261 | quant_config=quant_config, |
| 262 | prefix=f"{prefix}.self_attn", |
| 263 | attention_multiplier=config.attention_multiplier, |
| 264 | ) |
| 265 | self.block_sparse_moe = GraniteMoeMoE( |
| 266 | num_experts=config.num_local_experts, |
| 267 | top_k=config.num_experts_per_tok, |
| 268 | hidden_size=config.hidden_size, |
| 269 | intermediate_size=config.intermediate_size, |
| 270 | quant_config=quant_config, |
| 271 | is_sequence_parallel=parallel_config.use_sequence_parallel_moe, |
| 272 | prefix=f"{prefix}.block_sparse_moe", |
| 273 | ) |
| 274 | |
| 275 | self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 276 | self.post_attention_layernorm = RMSNorm( |
| 277 | config.hidden_size, eps=config.rms_norm_eps |
| 278 | ) |
| 279 | |
| 280 | self.residual_multiplier = config.residual_multiplier |
| 281 | |
| 282 | def forward( |
| 283 | self, |
| 284 | positions: torch.Tensor, |
| 285 | hidden_states: torch.Tensor, |
| 286 | ) -> torch.Tensor: |
| 287 | # Self Attention |
| 288 | residual = hidden_states |
| 289 | hidden_states = self.input_layernorm(hidden_states) |
| 290 | hidden_states = self.self_attn( |
| 291 | positions=positions, |
| 292 | hidden_states=hidden_states, |
| 293 | ) |
| 294 | hidden_states = residual + hidden_states * self.residual_multiplier |
| 295 | residual = hidden_states |
| 296 | hidden_states = self.post_attention_layernorm(hidden_states) |
| 297 | hidden_states = self.block_sparse_moe(hidden_states) |
| 298 | hidden_states = residual + hidden_states * self.residual_multiplier |
| 299 | |
| 300 | return hidden_states |
| 301 | |
| 302 | |
| 303 | @support_torch_compile |
| 304 | class GraniteMoeModel(nn.Module): |
| 305 | hf_to_vllm_mapper: WeightsMapper = WeightsMapper( |
| 306 | orig_to_new_suffix={ |
| 307 | # Legacy names to new names |
| 308 | "moe.input_linear.weight": "moe.experts.gate_up_proj", |
| 309 | "moe.output_linear.weight": "moe.experts.down_proj", |
| 310 | ".router.layer.weight": ".gate.weight", |
| 311 | # Checkpoint name to vLLM name |
| 312 | ".router.weight": ".gate.weight", |
| 313 | }, |
| 314 | orig_to_new_stacked={ |
| 315 | # weight_name: (param_name, shard_id) |
| 316 | ".q_proj": (".qkv_proj", "q"), |
| 317 | ".k_proj": (".qkv_proj", "k"), |
| 318 | ".v_proj": (".qkv_proj", "v"), |
| 319 | }, |
| 320 | ) |
| 321 | |
| 322 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 323 | super().__init__() |
| 324 | |
| 325 | config = vllm_config.model_config.hf_config |
| 326 | quant_config = vllm_config.quant_config |
| 327 | |
| 328 | self.config = config |
| 329 | self.quant_config = quant_config # Required by MixtralModel |
| 330 | |
| 331 | self.vocab_size = config.vocab_size |
| 332 | |
| 333 | self.embed_tokens = VocabParallelEmbedding( |
| 334 | self.vocab_size, |
| 335 | config.hidden_size, |
| 336 | ) |
| 337 | self.embedding_multiplier = config.embedding_multiplier |
| 338 | |
| 339 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 340 | config.num_hidden_layers, |
| 341 | lambda prefix: GraniteMoeDecoderLayer(vllm_config, prefix=prefix), |
| 342 | prefix=f"{prefix}.layers", |
| 343 | ) |
| 344 | |
| 345 | self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 346 | |
| 347 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 348 | return self.embed_tokens(input_ids) |
| 349 | |
| 350 | def forward( |
| 351 | self, |
| 352 | input_ids: torch.Tensor | None, |
| 353 | positions: torch.Tensor, |
| 354 | intermediate_tensors: IntermediateTensors | None, |
| 355 | inputs_embeds: torch.Tensor | None = None, |
| 356 | ) -> torch.Tensor: |
| 357 | if get_pp_group().is_first_rank: |
| 358 | if inputs_embeds is not None: |
| 359 | hidden_states = inputs_embeds |
| 360 | else: |
| 361 | hidden_states = self.embed_input_ids(input_ids) |
| 362 | hidden_states *= self.embedding_multiplier |
| 363 | else: |
| 364 | assert intermediate_tensors is not None |
| 365 | hidden_states = intermediate_tensors["hidden_states"] |
| 366 | for layer in islice(self.layers, self.start_layer, self.end_layer): |
| 367 | hidden_states = layer(positions, hidden_states) |
| 368 | if not get_pp_group().is_last_rank: |
| 369 | return IntermediateTensors( |
| 370 | { |
| 371 | "hidden_states": hidden_states, |
| 372 | } |
| 373 | ) |
| 374 | hidden_states = self.norm(hidden_states) |
| 375 | return hidden_states |
| 376 | |
| 377 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 378 | loader = AutoWeightsLoader(self) |
| 379 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |
| 380 | |
| 381 | |
| 382 | class GraniteMoeForCausalLM(nn.Module, SupportsLoRA, SupportsPP): |
| 383 | fall_back_to_pt_during_load = False |
| 384 | |
| 385 | packed_modules_mapping = { |
| 386 | "qkv_proj": [ |
| 387 | "q_proj", |
| 388 | "k_proj", |
| 389 | "v_proj", |
| 390 | ], |
| 391 | } |
| 392 | |
| 393 | # LoRA specific attributes |
| 394 | embedding_modules = { |
| 395 | "embed_tokens": "input_embeddings", |
| 396 | "lm_head": "output_embeddings", |
| 397 | } |
| 398 | |
| 399 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 400 | super().__init__() |
| 401 | config = vllm_config.model_config.hf_config |
| 402 | quant_config = vllm_config.quant_config |
| 403 | |
| 404 | self.config = config |
| 405 | |
| 406 | self.model = GraniteMoeModel( |
| 407 | vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") |
| 408 | ) |
| 409 | |
| 410 | self.lm_head = ParallelLMHead( |
| 411 | config.vocab_size, |
| 412 | config.hidden_size, |
| 413 | quant_config=quant_config, |
| 414 | prefix=maybe_prefix(prefix, "lm_head"), |
| 415 | ) |
| 416 | if config.tie_word_embeddings: |
| 417 | self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens) |
| 418 | |
| 419 | self.logits_processor = LogitsProcessor( |
| 420 | config.vocab_size, |
| 421 | scale=1 / self.config.logits_scaling, |
| 422 | ) |
| 423 | |
| 424 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 425 | return self.model.embed_input_ids(input_ids) |
| 426 | |
| 427 | def forward( |
| 428 | self, |
| 429 | input_ids: torch.Tensor | None, |
| 430 | positions: torch.Tensor, |
| 431 | intermediate_tensors: IntermediateTensors | None = None, |
| 432 | inputs_embeds: torch.Tensor | None = None, |
| 433 | ) -> torch.Tensor: |
| 434 | hidden_states = self.model( |
| 435 | input_ids, positions, intermediate_tensors, inputs_embeds |
| 436 | ) |
| 437 | return hidden_states |
| 438 | |
| 439 | def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: |
| 440 | logits = self.logits_processor(self.lm_head, hidden_states) |
| 441 | return logits |
| 442 | |
| 443 | def make_empty_intermediate_tensors( |
| 444 | self, batch_size: int, dtype: torch.dtype, device: torch.device |
| 445 | ) -> IntermediateTensors: |
| 446 | return IntermediateTensors( |
| 447 | { |
| 448 | "hidden_states": torch.zeros( |
| 449 | (batch_size, self.config.hidden_size), dtype=dtype, device=device |
| 450 | ), |
| 451 | } |
| 452 | ) |
| 453 | |
| 454 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 455 | loader = AutoWeightsLoader(self) |
| 456 | return loader.load_weights(weights) |