| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Inference-only GraniteMoeShared model. |
| 4 | |
| 5 | The architecture is the same as granitemoe but with the addition of shared |
| 6 | experts. |
| 7 | |
| 8 | Also serves the `granitemoe_swa` checkpoints (`GraniteMoeSWAForCausalLM`), which |
| 9 | add the same per-layer sliding window, attention sink and per-layer RoPE support |
| 10 | as `granite_swa` (see `granite.py`). |
| 11 | """ |
| 12 | |
| 13 | from collections.abc import Iterable |
| 14 | from itertools import islice |
| 15 | |
| 16 | import torch |
| 17 | from torch import nn |
| 18 | from transformers.models.granitemoeshared import GraniteMoeSharedConfig |
| 19 | |
| 20 | from vllm.compilation.decorators import support_torch_compile |
| 21 | from vllm.config import CacheConfig, VllmConfig |
| 22 | from vllm.distributed import get_pp_group |
| 23 | from vllm.model_executor.layers.activation import SiluAndMul |
| 24 | from vllm.model_executor.layers.layernorm import RMSNorm |
| 25 | from vllm.model_executor.layers.linear import ( |
| 26 | MergedColumnParallelLinear, |
| 27 | RowParallelLinear, |
| 28 | ) |
| 29 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 30 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 31 | from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 32 | ParallelLMHead, |
| 33 | VocabParallelEmbedding, |
| 34 | ) |
| 35 | from vllm.sequence import IntermediateTensors |
| 36 | |
| 37 | from .granitemoe import GraniteMoeAttention, GraniteMoeModel, GraniteMoeMoE |
| 38 | from .interfaces import SupportsLoRA, SupportsPP |
| 39 | from .utils import AutoWeightsLoader, make_layers, maybe_prefix |
| 40 | |
| 41 | |
| 42 | class GraniteMoeSharedMLP(nn.Module): |
| 43 | def __init__( |
| 44 | self, |
| 45 | config: GraniteMoeSharedConfig, |
| 46 | quant_config: QuantizationConfig | None = None, |
| 47 | prefix: str = "", |
| 48 | ): |
| 49 | super().__init__() |
| 50 | |
| 51 | self.input_size = config.hidden_size |
| 52 | self.hidden_size = config.shared_intermediate_size |
| 53 | self.input_linear = MergedColumnParallelLinear( |
| 54 | input_size=self.input_size, |
| 55 | output_sizes=[self.hidden_size] * 2, |
| 56 | bias=False, |
| 57 | quant_config=quant_config, |
| 58 | prefix=f"{prefix}.input_linear", |
| 59 | ) |
| 60 | self.output_linear = RowParallelLinear( |
| 61 | self.hidden_size, |
| 62 | self.input_size, |
| 63 | bias=False, |
| 64 | quant_config=quant_config, |
| 65 | prefix=f"{prefix}.output_linear", |
| 66 | ) |
| 67 | if config.hidden_act != "silu": |
| 68 | raise ValueError( |
| 69 | f"Unsupported activation: {config.hidden_act}. " |
| 70 | "Only silu is supported for now." |
| 71 | ) |
| 72 | self.act_fn = SiluAndMul() |
| 73 | |
| 74 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 75 | hidden_states, _ = self.input_linear(hidden_states) |
| 76 | hidden_states = self.act_fn(hidden_states) |
| 77 | hidden_states, _ = self.output_linear(hidden_states) |
| 78 | return hidden_states |
| 79 | |
| 80 | |
| 81 | class GraniteMoeSharedDecoderLayer(nn.Module): |
| 82 | def __init__( |
| 83 | self, |
| 84 | config: GraniteMoeSharedConfig, |
| 85 | cache_config: CacheConfig | None = None, |
| 86 | quant_config: QuantizationConfig | None = None, |
| 87 | prefix: str = "", |
| 88 | ) -> None: |
| 89 | super().__init__() |
| 90 | self.hidden_size = config.hidden_size |
| 91 | self.self_attn = GraniteMoeAttention( |
| 92 | config=config, |
| 93 | hidden_size=self.hidden_size, |
| 94 | num_heads=config.num_attention_heads, |
| 95 | max_position=config.max_position_embeddings, |
| 96 | num_kv_heads=config.num_key_value_heads, |
| 97 | cache_config=cache_config, |
| 98 | quant_config=quant_config, |
| 99 | prefix=f"{prefix}.self_attn", |
| 100 | attention_multiplier=config.attention_multiplier, |
| 101 | ) |
| 102 | self.block_sparse_moe = GraniteMoeMoE( |
| 103 | num_experts=config.num_local_experts, |
| 104 | top_k=config.num_experts_per_tok, |
| 105 | hidden_size=config.hidden_size, |
| 106 | intermediate_size=config.intermediate_size, |
| 107 | quant_config=quant_config, |
| 108 | prefix=f"{prefix}.block_sparse_moe", |
| 109 | ) |
| 110 | self.shared_mlp = ( |
| 111 | None |
| 112 | if getattr(config, "shared_intermediate_size", 0) == 0 |
| 113 | else GraniteMoeSharedMLP( |
| 114 | config, quant_config=quant_config, prefix=f"{prefix}.shared_mlp" |
| 115 | ) |
| 116 | ) |
| 117 | |
| 118 | self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 119 | self.post_attention_layernorm = RMSNorm( |
| 120 | config.hidden_size, eps=config.rms_norm_eps |
| 121 | ) |
| 122 | |
| 123 | self.residual_multiplier = config.residual_multiplier |
| 124 | |
| 125 | def forward( |
| 126 | self, |
| 127 | positions: torch.Tensor, |
| 128 | hidden_states: torch.Tensor, |
| 129 | ) -> torch.Tensor: |
| 130 | # Self Attention |
| 131 | residual = hidden_states |
| 132 | hidden_states = self.input_layernorm(hidden_states) |
| 133 | hidden_states = self.self_attn( |
| 134 | positions=positions, |
| 135 | hidden_states=hidden_states, |
| 136 | ) |
| 137 | hidden_states = residual + hidden_states * self.residual_multiplier |
| 138 | residual = hidden_states |
| 139 | hidden_states = self.post_attention_layernorm(hidden_states) |
| 140 | if self.shared_mlp is None: |
| 141 | hidden_states = self.block_sparse_moe(hidden_states) |
| 142 | else: |
| 143 | # create a copy since block_sparse_moe modifies in-place |
| 144 | moe_hidden_states = hidden_states.clone() |
| 145 | moe_hidden_states = self.block_sparse_moe(moe_hidden_states) |
| 146 | hidden_states = moe_hidden_states + self.shared_mlp(hidden_states) |
| 147 | del moe_hidden_states |
| 148 | hidden_states = residual + hidden_states * self.residual_multiplier |
| 149 | |
| 150 | return hidden_states |
| 151 | |
| 152 | |
| 153 | @support_torch_compile |
| 154 | class GraniteMoeSharedModel(nn.Module): |
| 155 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 156 | super().__init__() |
| 157 | |
| 158 | config = vllm_config.model_config.hf_config |
| 159 | cache_config = vllm_config.cache_config |
| 160 | quant_config = vllm_config.quant_config |
| 161 | |
| 162 | self.config = config |
| 163 | self.quant_config = quant_config # Required by MixtralModel |
| 164 | |
| 165 | self.vocab_size = config.vocab_size |
| 166 | |
| 167 | self.embed_tokens = VocabParallelEmbedding( |
| 168 | self.vocab_size, |
| 169 | config.hidden_size, |
| 170 | quant_config=quant_config, |
| 171 | ) |
| 172 | self.embedding_multiplier = config.embedding_multiplier |
| 173 | |
| 174 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 175 | config.num_hidden_layers, |
| 176 | lambda prefix: GraniteMoeSharedDecoderLayer( |
| 177 | config, cache_config, quant_config=quant_config, prefix=prefix |
| 178 | ), |
| 179 | prefix=f"{prefix}.layers", |
| 180 | ) |
| 181 | |
| 182 | self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 183 | |
| 184 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 185 | return self.embed_tokens(input_ids) |
| 186 | |
| 187 | def forward( |
| 188 | self, |
| 189 | input_ids: torch.Tensor | None, |
| 190 | positions: torch.Tensor, |
| 191 | intermediate_tensors: IntermediateTensors | None, |
| 192 | inputs_embeds: torch.Tensor | None = None, |
| 193 | ) -> torch.Tensor: |
| 194 | if get_pp_group().is_first_rank: |
| 195 | if inputs_embeds is not None: |
| 196 | hidden_states = inputs_embeds |
| 197 | else: |
| 198 | hidden_states = self.embed_input_ids(input_ids) |
| 199 | hidden_states *= self.embedding_multiplier |
| 200 | else: |
| 201 | assert intermediate_tensors is not None |
| 202 | hidden_states = intermediate_tensors["hidden_states"] |
| 203 | for layer in islice(self.layers, self.start_layer, self.end_layer): |
| 204 | hidden_states = layer(positions, hidden_states) |
| 205 | if not get_pp_group().is_last_rank: |
| 206 | return IntermediateTensors( |
| 207 | { |
| 208 | "hidden_states": hidden_states, |
| 209 | } |
| 210 | ) |
| 211 | hidden_states = self.norm(hidden_states) |
| 212 | return hidden_states |
| 213 | |
| 214 | hf_to_vllm_mapper = GraniteMoeModel.hf_to_vllm_mapper |
| 215 | load_weights = GraniteMoeModel.load_weights |
| 216 | |
| 217 | |
| 218 | class GraniteMoeSharedForCausalLM(nn.Module, SupportsLoRA, SupportsPP): |
| 219 | fall_back_to_pt_during_load = False |
| 220 | |
| 221 | packed_modules_mapping = { |
| 222 | "qkv_proj": [ |
| 223 | "q_proj", |
| 224 | "k_proj", |
| 225 | "v_proj", |
| 226 | ], |
| 227 | } |
| 228 | |
| 229 | # LoRA specific attributes |
| 230 | embedding_modules = { |
| 231 | "embed_tokens": "input_embeddings", |
| 232 | "lm_head": "output_embeddings", |
| 233 | } |
| 234 | |
| 235 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 236 | super().__init__() |
| 237 | config = vllm_config.model_config.hf_config |
| 238 | quant_config = vllm_config.quant_config |
| 239 | |
| 240 | self.config = config |
| 241 | |
| 242 | self.model = GraniteMoeSharedModel( |
| 243 | vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") |
| 244 | ) |
| 245 | |
| 246 | self.lm_head = ParallelLMHead( |
| 247 | config.vocab_size, |
| 248 | config.hidden_size, |
| 249 | quant_config=quant_config, |
| 250 | prefix=maybe_prefix(prefix, "lm_head"), |
| 251 | ) |
| 252 | if config.tie_word_embeddings: |
| 253 | self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens) |
| 254 | |
| 255 | self.logits_processor = LogitsProcessor( |
| 256 | config.vocab_size, |
| 257 | config.vocab_size, |
| 258 | scale=1 / self.config.logits_scaling, |
| 259 | ) |
| 260 | |
| 261 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 262 | return self.model.embed_input_ids(input_ids) |
| 263 | |
| 264 | def forward( |
| 265 | self, |
| 266 | input_ids: torch.Tensor | None, |
| 267 | positions: torch.Tensor, |
| 268 | intermediate_tensors: IntermediateTensors | None = None, |
| 269 | inputs_embeds: torch.Tensor | None = None, |
| 270 | ) -> torch.Tensor: |
| 271 | hidden_states = self.model( |
| 272 | input_ids, positions, intermediate_tensors, inputs_embeds |
| 273 | ) |
| 274 | return hidden_states |
| 275 | |
| 276 | def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: |
| 277 | logits = self.logits_processor(self.lm_head, hidden_states) |
| 278 | return logits |
| 279 | |
| 280 | def make_empty_intermediate_tensors( |
| 281 | self, batch_size: int, dtype: torch.dtype, device: torch.device |
| 282 | ) -> IntermediateTensors: |
| 283 | return IntermediateTensors( |
| 284 | { |
| 285 | "hidden_states": torch.zeros( |
| 286 | (batch_size, self.config.hidden_size), dtype=dtype, device=device |
| 287 | ), |
| 288 | } |
| 289 | ) |
| 290 | |
| 291 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 292 | loader = AutoWeightsLoader(self) |
| 293 | return loader.load_weights(weights) |