| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | # Adapted from |
| 5 | # https://github.com/inclusionAI/Ling/blob/master/models/modeling_bailing_moe.py |
| 6 | # Copyright 2023 The vLLM team. |
| 7 | # Copyright 2023 Antgroup 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 BailingMoE model compatible with HuggingFace weights.""" |
| 26 | |
| 27 | from collections.abc import Iterable |
| 28 | from itertools import islice |
| 29 | |
| 30 | import torch |
| 31 | import torch.nn.functional as F |
| 32 | from torch import nn |
| 33 | from transformers.configuration_utils import PreTrainedConfig |
| 34 | |
| 35 | from vllm.compilation.decorators import support_torch_compile |
| 36 | from vllm.config import CacheConfig, VllmConfig |
| 37 | from vllm.distributed import ( |
| 38 | get_pp_group, |
| 39 | get_tensor_model_parallel_rank, |
| 40 | get_tensor_model_parallel_world_size, |
| 41 | ) |
| 42 | from vllm.model_executor.layers.activation import SiluAndMul |
| 43 | from vllm.model_executor.layers.attention import Attention |
| 44 | from vllm.model_executor.layers.fused_moe import ( |
| 45 | FusedMoEFactory, |
| 46 | GateLinear, |
| 47 | ) |
| 48 | from vllm.model_executor.layers.layernorm import RMSNorm |
| 49 | from vllm.model_executor.layers.linear import ( |
| 50 | MergedColumnParallelLinear, |
| 51 | QKVParallelLinear, |
| 52 | RowParallelLinear, |
| 53 | ) |
| 54 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 55 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 56 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 57 | from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 58 | ParallelLMHead, |
| 59 | VocabParallelEmbedding, |
| 60 | ) |
| 61 | from vllm.sequence import IntermediateTensors |
| 62 | |
| 63 | from .interfaces import SupportsLoRA, SupportsPP |
| 64 | from .utils import ( |
| 65 | AutoWeightsLoader, |
| 66 | PPMissingLayer, |
| 67 | WeightsMapper, |
| 68 | make_empty_intermediate_tensors_factory, |
| 69 | make_layers, |
| 70 | maybe_prefix, |
| 71 | ) |
| 72 | |
| 73 | |
| 74 | class BailingAttention(nn.Module): |
| 75 | def __init__( |
| 76 | self, |
| 77 | config: PreTrainedConfig, |
| 78 | cache_config: CacheConfig | None = None, |
| 79 | quant_config: QuantizationConfig | None = None, |
| 80 | reduce_results: bool = True, |
| 81 | prefix: str = "", |
| 82 | ): |
| 83 | super().__init__() |
| 84 | self.hidden_size = config.hidden_size |
| 85 | self.total_num_heads = config.num_attention_heads |
| 86 | self.total_kv_heads = config.num_key_value_heads |
| 87 | tp_size = get_tensor_model_parallel_world_size() |
| 88 | |
| 89 | assert self.total_num_heads % tp_size == 0 |
| 90 | assert self.total_num_heads >= self.total_kv_heads |
| 91 | |
| 92 | self.num_heads = self.total_num_heads // tp_size |
| 93 | self.head_dim = config.head_dim or (self.hidden_size // self.total_num_heads) |
| 94 | self.q_size_per_rank = self.head_dim * self.num_heads |
| 95 | self.num_kv_heads = max(1, self.total_kv_heads // tp_size) |
| 96 | self.kv_size_per_rank = self.num_kv_heads * self.head_dim |
| 97 | self.scale = self.head_dim**-0.5 |
| 98 | self.use_qk_norm = getattr(config, "use_qk_norm", False) |
| 99 | self.use_rmsnorm = getattr(config, "use_rmsnorm", False) |
| 100 | |
| 101 | self.query_key_value = QKVParallelLinear( |
| 102 | self.hidden_size, |
| 103 | self.head_dim, |
| 104 | self.total_num_heads, |
| 105 | self.total_kv_heads, |
| 106 | bias=(config.use_bias or config.use_qkv_bias), |
| 107 | quant_config=quant_config, |
| 108 | prefix=f"{prefix}.query_key_value", |
| 109 | ) |
| 110 | |
| 111 | if self.use_qk_norm: |
| 112 | self.query_layernorm = ( |
| 113 | RMSNorm(self.head_dim, eps=config.rms_norm_eps) |
| 114 | if self.use_rmsnorm |
| 115 | else nn.LayerNorm(self.head_dim, eps=1e-6) |
| 116 | ) |
| 117 | self.key_layernorm = ( |
| 118 | RMSNorm(self.head_dim, eps=config.rms_norm_eps) |
| 119 | if self.use_rmsnorm |
| 120 | else nn.LayerNorm(self.head_dim, eps=1e-6) |
| 121 | ) |
| 122 | |
| 123 | self.dense = RowParallelLinear( |
| 124 | self.total_num_heads * self.head_dim, |
| 125 | self.hidden_size, |
| 126 | bias=config.use_bias, |
| 127 | quant_config=quant_config, |
| 128 | reduce_results=reduce_results, |
| 129 | prefix=f"{prefix}.dense", |
| 130 | ) |
| 131 | |
| 132 | rotary_dim = getattr(config, "rotary_dim", None) |
| 133 | if rotary_dim is None: |
| 134 | partial_rotary_factor = getattr(config, "partial_rotary_factor", 1.0) |
| 135 | rotary_dim = int(self.head_dim * partial_rotary_factor) |
| 136 | if rotary_dim is None: |
| 137 | rotary_dim = self.head_dim |
| 138 | config.rope_parameters["partial_rotary_factor"] = rotary_dim / self.head_dim |
| 139 | |
| 140 | self.rotary_emb = get_rope( |
| 141 | self.head_dim, |
| 142 | max_position=config.max_position_embeddings, |
| 143 | rope_parameters=config.rope_parameters, |
| 144 | is_neox_style=True, |
| 145 | ) |
| 146 | |
| 147 | self.attn = Attention( |
| 148 | self.num_heads, |
| 149 | self.head_dim, |
| 150 | self.scale, |
| 151 | num_kv_heads=self.num_kv_heads, |
| 152 | cache_config=cache_config, |
| 153 | prefix=f"{prefix}.attn", |
| 154 | ) |
| 155 | |
| 156 | def forward( |
| 157 | self, |
| 158 | hidden_states: torch.Tensor, |
| 159 | position_ids: torch.Tensor, |
| 160 | ) -> torch.Tensor: |
| 161 | qkv, _ = self.query_key_value(hidden_states) |
| 162 | q, k, v = qkv.split( |
| 163 | [self.q_size_per_rank, self.kv_size_per_rank, self.kv_size_per_rank], dim=-1 |
| 164 | ) |
| 165 | |
| 166 | if self.use_qk_norm: |
| 167 | q = q.view(-1, self.num_heads, self.head_dim) |
| 168 | k = k.view(-1, self.num_kv_heads, self.head_dim) |
| 169 | q = self.query_layernorm(q) |
| 170 | k = self.key_layernorm(k) |
| 171 | q = q.view(-1, self.q_size_per_rank) |
| 172 | k = k.view(-1, self.kv_size_per_rank) |
| 173 | |
| 174 | q, k = self.rotary_emb(position_ids, q, k) |
| 175 | |
| 176 | context_layer = self.attn(q, k, v) |
| 177 | |
| 178 | attn_output, _ = self.dense(context_layer) |
| 179 | return attn_output |
| 180 | |
| 181 | |
| 182 | class BailingMLP(nn.Module): |
| 183 | def __init__( |
| 184 | self, |
| 185 | intermediate_size: int, |
| 186 | config: PreTrainedConfig, |
| 187 | quant_config: QuantizationConfig | None = None, |
| 188 | reduce_results: bool = True, |
| 189 | prefix: str = "", |
| 190 | ) -> None: |
| 191 | super().__init__() |
| 192 | self.gate_up_proj = MergedColumnParallelLinear( |
| 193 | config.hidden_size, |
| 194 | [intermediate_size] * 2, |
| 195 | bias=config.use_bias, |
| 196 | quant_config=quant_config, |
| 197 | prefix=f"{prefix}.gate_up_proj", |
| 198 | ) |
| 199 | self.down_proj = RowParallelLinear( |
| 200 | intermediate_size, |
| 201 | config.hidden_size, |
| 202 | bias=config.use_bias, |
| 203 | quant_config=quant_config, |
| 204 | reduce_results=reduce_results, |
| 205 | prefix=f"{prefix}.down_proj", |
| 206 | ) |
| 207 | self.act_fn = SiluAndMul() |
| 208 | |
| 209 | def forward(self, x): |
| 210 | x, _ = self.gate_up_proj(x) |
| 211 | x = self.act_fn(x) |
| 212 | x, _ = self.down_proj(x) |
| 213 | return x |
| 214 | |
| 215 | |
| 216 | class BailingMoE(nn.Module): |
| 217 | def __init__( |
| 218 | self, |
| 219 | intermediate_size: int, |
| 220 | config: PreTrainedConfig, |
| 221 | quant_config: QuantizationConfig | None = None, |
| 222 | reduce_results: bool | None = True, |
| 223 | prefix: str = "", |
| 224 | ): |
| 225 | super().__init__() |
| 226 | |
| 227 | self.tp_size = get_tensor_model_parallel_world_size() |
| 228 | self.tp_rank = get_tensor_model_parallel_rank() |
| 229 | self.num_experts = config.num_experts |
| 230 | self.top_k = config.num_experts_per_tok |
| 231 | self.norm_expert_prob = config.norm_topk_prob |
| 232 | self.hidden_size = config.hidden_size |
| 233 | self.quant_config = quant_config |
| 234 | self.num_shared_experts = config.num_shared_experts |
| 235 | self.score_function = getattr(config, "score_function", None) |
| 236 | self.n_group = getattr(config, "n_group", None) |
| 237 | self.topk_group = getattr(config, "topk_group", None) |
| 238 | self.use_grouped_topk = self.n_group is not None and self.topk_group is not None |
| 239 | self.routed_scaling_factor = getattr(config, "routed_scaling_factor", 1.0) |
| 240 | |
| 241 | router_dtype = getattr(config, "router_dtype", None) |
| 242 | if router_dtype is None: |
| 243 | self.router_dtype = None |
| 244 | elif router_dtype == "fp32": |
| 245 | self.router_dtype = torch.float32 |
| 246 | else: |
| 247 | self.router_dtype = torch.bfloat16 |
| 248 | |
| 249 | self.gate = GateLinear( |
| 250 | self.hidden_size, |
| 251 | self.num_experts, |
| 252 | out_dtype=self.router_dtype, |
| 253 | params_dtype=self.router_dtype, |
| 254 | prefix=f"{prefix}.gate", |
| 255 | ) |
| 256 | |
| 257 | if getattr(config, "moe_router_enable_expert_bias", False): |
| 258 | self.gate.expert_bias = nn.Parameter( |
| 259 | torch.empty((config.num_experts,), dtype=torch.float32) |
| 260 | ) |
| 261 | else: |
| 262 | self.gate.expert_bias = None |
| 263 | |
| 264 | self.correction_bias = ( |
| 265 | self.gate.expert_bias.data if self.gate.expert_bias is not None else None |
| 266 | ) |
| 267 | |
| 268 | if self.score_function is not None: |
| 269 | assert ( |
| 270 | self.score_function == "softmax" and self.correction_bias is None |
| 271 | ) or ( |
| 272 | self.score_function == "sigmoid" and self.correction_bias is not None |
| 273 | ), ( |
| 274 | "score_function and correction_bias should be in 2 combination (softmax, None) or (sigmoid, not None)" # noqa: E501 |
| 275 | ) |
| 276 | else: |
| 277 | # default value for scoring_func |
| 278 | self.score_function = "softmax" |
| 279 | |
| 280 | if self.num_shared_experts > 0: |
| 281 | if hasattr(config, "moe_shared_expert_intermediate_size"): |
| 282 | intermediate_size = config.moe_shared_expert_intermediate_size |
| 283 | else: |
| 284 | intermediate_size = config.moe_intermediate_size |
| 285 | intermediate_size *= config.num_shared_experts |
| 286 | self.shared_experts: BailingMLP | None = BailingMLP( |
| 287 | intermediate_size=intermediate_size, |
| 288 | config=config, |
| 289 | quant_config=quant_config, |
| 290 | reduce_results=False, |
| 291 | prefix=f"{prefix}.shared_experts", |
| 292 | ) |
| 293 | else: |
| 294 | self.shared_experts = None |
| 295 | |
| 296 | self.experts = FusedMoEFactory( |
| 297 | shared_experts=self.shared_experts, |
| 298 | num_experts=self.num_experts, |
| 299 | top_k=self.top_k, |
| 300 | hidden_size=self.hidden_size, |
| 301 | intermediate_size=config.moe_intermediate_size, |
| 302 | renormalize=self.norm_expert_prob, |
| 303 | quant_config=quant_config, |
| 304 | prefix=f"{prefix}.experts", |
| 305 | scoring_func=self.score_function, |
| 306 | e_score_correction_bias=self.gate.expert_bias, |
| 307 | num_expert_group=self.n_group, |
| 308 | topk_group=self.topk_group, |
| 309 | use_grouped_topk=self.use_grouped_topk, |
| 310 | router_logits_dtype=self.router_dtype, |
| 311 | routed_scaling_factor=self.routed_scaling_factor, |
| 312 | ) |
| 313 | |
| 314 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 315 | num_tokens, hidden_size = hidden_states.shape |
| 316 | hidden_states = hidden_states.view(-1, hidden_size) |
| 317 | |
| 318 | # router_logits: (num_tokens, n_experts) |
| 319 | router_logits, _ = self.gate(hidden_states) |
| 320 | router_logits = router_logits.to(hidden_states.dtype) |
| 321 | |
| 322 | final_hidden_states = self.experts( |
| 323 | hidden_states=hidden_states, router_logits=router_logits |
| 324 | ) |
| 325 | return final_hidden_states.view(num_tokens, hidden_size) |
| 326 | |
| 327 | |
| 328 | class BailingMoeBlock(nn.Module): |
| 329 | def __init__( |
| 330 | self, |
| 331 | config: PreTrainedConfig, |
| 332 | cache_config: CacheConfig | None = None, |
| 333 | quant_config: QuantizationConfig | None = None, |
| 334 | prefix: str = "", |
| 335 | ): |
| 336 | super().__init__() |
| 337 | layer_idx = int(prefix.split(".")[-1]) |
| 338 | self.config = config |
| 339 | hidden_size = config.hidden_size |
| 340 | intermediate_size = config.intermediate_size |
| 341 | |
| 342 | self.input_layernorm = RMSNorm(hidden_size, eps=config.rms_norm_eps) |
| 343 | self.attention = BailingAttention( |
| 344 | config, cache_config, quant_config, prefix=f"{prefix}.attention" |
| 345 | ) |
| 346 | |
| 347 | self.post_attention_layernorm = RMSNorm(hidden_size, eps=config.rms_norm_eps) |
| 348 | |
| 349 | # Choose MLP class based on the number of experts and layer index |
| 350 | if layer_idx < config.first_k_dense_replace: |
| 351 | mlp_class = BailingMLP |
| 352 | else: |
| 353 | mlp_class = BailingMoE |
| 354 | self.mlp = mlp_class( |
| 355 | intermediate_size, config, quant_config, True, prefix=f"{prefix}.mlp" |
| 356 | ) |
| 357 | |
| 358 | def forward( |
| 359 | self, |
| 360 | hidden_states: torch.Tensor, |
| 361 | position_ids: torch.Tensor, |
| 362 | residual: torch.Tensor | None, |
| 363 | ) -> torch.Tensor: |
| 364 | if residual is None: |
| 365 | residual = hidden_states |
| 366 | hidden_states = self.input_layernorm(hidden_states) |
| 367 | else: |
| 368 | hidden_states, residual = self.input_layernorm(hidden_states, residual) |
| 369 | |
| 370 | hidden_states = self.attention( |
| 371 | hidden_states=hidden_states, |
| 372 | position_ids=position_ids, |
| 373 | ) |
| 374 | |
| 375 | hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) |
| 376 | hidden_states = self.mlp(hidden_states) |
| 377 | return hidden_states, residual |
| 378 | |
| 379 | |
| 380 | @support_torch_compile |
| 381 | class BailingMoeModel(nn.Module): |
| 382 | hf_to_vllm_mapper = WeightsMapper( |
| 383 | orig_to_new_stacked={ |
| 384 | # .experts.gate_up_proj must be handled by MoERunner.load_weights for EP |
| 385 | ".mlp.gate_proj": (".mlp.gate_up_proj", 0), |
| 386 | ".mlp.up_proj": (".mlp.gate_up_proj", 1), |
| 387 | ".shared_experts.gate_proj": (".shared_experts.gate_up_proj", 0), |
| 388 | ".shared_experts.up_proj": (".shared_experts.gate_up_proj", 1), |
| 389 | } |
| 390 | ) |
| 391 | |
| 392 | def __init__( |
| 393 | self, |
| 394 | *, |
| 395 | vllm_config: VllmConfig, |
| 396 | prefix: str = "", |
| 397 | ): |
| 398 | super().__init__() |
| 399 | config = vllm_config.model_config.hf_config |
| 400 | cache_config = vllm_config.cache_config |
| 401 | quant_config = vllm_config.quant_config |
| 402 | |
| 403 | self.config = config |
| 404 | self.vocab_size = config.vocab_size |
| 405 | self.embed_dim = config.hidden_size |
| 406 | self.tie_word_embeddings = getattr(config, "tie_word_embeddings", False) |
| 407 | |
| 408 | if get_pp_group().is_first_rank or ( |
| 409 | self.tie_word_embeddings and get_pp_group().is_last_rank |
| 410 | ): |
| 411 | self.word_embeddings = VocabParallelEmbedding( |
| 412 | self.vocab_size, |
| 413 | self.embed_dim, |
| 414 | quant_config=quant_config, |
| 415 | prefix=f"{prefix}.word_embeddings", |
| 416 | ) |
| 417 | else: |
| 418 | self.word_embeddings = PPMissingLayer() |
| 419 | |
| 420 | self.embedding_dropout = torch.nn.Dropout(config.embedding_dropout) |
| 421 | |
| 422 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 423 | config.num_hidden_layers, |
| 424 | lambda prefix: BailingMoeBlock( |
| 425 | config=config, |
| 426 | cache_config=cache_config, |
| 427 | quant_config=quant_config, |
| 428 | prefix=prefix, |
| 429 | ), |
| 430 | prefix=f"{prefix}.layers", |
| 431 | ) |
| 432 | |
| 433 | self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( |
| 434 | ["hidden_states", "residual"], config.hidden_size |
| 435 | ) |
| 436 | |
| 437 | if get_pp_group().is_last_rank: |
| 438 | self.norm = RMSNorm(self.embed_dim, eps=config.rms_norm_eps) |
| 439 | else: |
| 440 | self.norm = PPMissingLayer() |
| 441 | |
| 442 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 443 | return self.word_embeddings(input_ids) |
| 444 | |
| 445 | def forward( |
| 446 | self, |
| 447 | input_ids: torch.Tensor | None, |
| 448 | position_ids: torch.Tensor, |
| 449 | intermediate_tensors: IntermediateTensors | None, |
| 450 | inputs_embeds: torch.Tensor | None = None, |
| 451 | ) -> torch.Tensor | IntermediateTensors: |
| 452 | if get_pp_group().is_first_rank: |
| 453 | if inputs_embeds is not None: |
| 454 | hidden_states = inputs_embeds |
| 455 | else: |
| 456 | hidden_states = self.embed_input_ids(input_ids) |
| 457 | residual = None |
| 458 | else: |
| 459 | assert intermediate_tensors is not None |
| 460 | hidden_states = intermediate_tensors["hidden_states"] |
| 461 | residual = intermediate_tensors["residual"] |
| 462 | |
| 463 | for layer in islice(self.layers, self.start_layer, self.end_layer): |
| 464 | hidden_states, residual = layer( |
| 465 | hidden_states, |
| 466 | position_ids, |
| 467 | residual, |
| 468 | ) |
| 469 | |
| 470 | if not get_pp_group().is_last_rank: |
| 471 | return IntermediateTensors( |
| 472 | {"hidden_states": hidden_states, "residual": residual} |
| 473 | ) |
| 474 | else: |
| 475 | if residual is None: |
| 476 | hidden_states = self.norm(hidden_states) |
| 477 | else: |
| 478 | hidden_states, _ = self.norm(hidden_states, residual) |
| 479 | return hidden_states |
| 480 | |
| 481 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 482 | loader = AutoWeightsLoader(self) |
| 483 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |
| 484 | |
| 485 | |
| 486 | class BailingMoeForCausalLM(nn.Module, SupportsPP, SupportsLoRA): |
| 487 | packed_modules_mapping = { |
| 488 | "query_key_value": ["query_key_value"], |
| 489 | "gate_up_proj": [ |
| 490 | "gate_proj", |
| 491 | "up_proj", |
| 492 | ], |
| 493 | } |
| 494 | |
| 495 | def __init__( |
| 496 | self, |
| 497 | *, |
| 498 | vllm_config: VllmConfig, |
| 499 | prefix: str = "", |
| 500 | ) -> None: |
| 501 | super().__init__() |
| 502 | |
| 503 | config = vllm_config.model_config.hf_config.get_text_config() |
| 504 | vllm_config.model_config.hf_config = config |
| 505 | quant_config = vllm_config.quant_config |
| 506 | |
| 507 | self.config = config |
| 508 | self.quant_config = quant_config |
| 509 | self.max_position_embeddings = config.max_position_embeddings |
| 510 | self.model = BailingMoeModel( |
| 511 | vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") |
| 512 | ) |
| 513 | self.tie_word_embeddings = getattr(config, "tie_word_embeddings", False) |
| 514 | |
| 515 | if get_pp_group().is_last_rank: |
| 516 | self.lm_head = ParallelLMHead( |
| 517 | config.vocab_size, |
| 518 | config.hidden_size, |
| 519 | quant_config=quant_config, |
| 520 | prefix=maybe_prefix(prefix, "lm_head"), |
| 521 | ) |
| 522 | if self.tie_word_embeddings: |
| 523 | self.lm_head = self.lm_head.tie_weights(self.model.word_embeddings) |
| 524 | self.logits_processor = LogitsProcessor(config.vocab_size) |
| 525 | else: |
| 526 | self.lm_head = PPMissingLayer() |
| 527 | |
| 528 | self.make_empty_intermediate_tensors = ( |
| 529 | self.model.make_empty_intermediate_tensors |
| 530 | ) |
| 531 | |
| 532 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 533 | return self.model.embed_input_ids(input_ids) |
| 534 | |
| 535 | def forward( |
| 536 | self, |
| 537 | input_ids: torch.Tensor | None, |
| 538 | positions: torch.Tensor, |
| 539 | intermediate_tensors: IntermediateTensors | None = None, |
| 540 | inputs_embeds: torch.Tensor | None = None, |
| 541 | ) -> torch.Tensor | IntermediateTensors: |
| 542 | model_output = self.model( |
| 543 | input_ids, positions, intermediate_tensors, inputs_embeds |
| 544 | ) |
| 545 | return model_output |
| 546 | |
| 547 | def compute_logits( |
| 548 | self, |
| 549 | hidden_states: torch.Tensor, |
| 550 | ) -> torch.Tensor | None: |
| 551 | logits = self.logits_processor(self.lm_head, hidden_states) |
| 552 | return logits |
| 553 | |
| 554 | def _normalize_lm_head( |
| 555 | self, weights: Iterable[tuple[str, torch.Tensor]] |
| 556 | ) -> Iterable[tuple[str, torch.Tensor]]: |
| 557 | norm_head = getattr(self.config, "norm_head", False) |
| 558 | for name, loaded_weight in weights: |
| 559 | if norm_head and "lm_head.weight" in name: |
| 560 | loaded_weight = F.normalize(loaded_weight, dim=0, p=2, eps=1e-7) |
| 561 | yield name, loaded_weight |
| 562 | |
| 563 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 564 | loader = AutoWeightsLoader(self) |
| 565 | return loader.load_weights(self._normalize_lm_head(weights)) |
| 566 | |
| 567 | |
| 568 | class BailingMoeV2ForCausalLM(BailingMoeForCausalLM): |
| 569 | pass |