| 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 itertools import islice |
| 6 | |
| 7 | import torch |
| 8 | from torch import nn |
| 9 | from transformers import CohereConfig |
| 10 | |
| 11 | from vllm.compilation.decorators import support_torch_compile |
| 12 | from vllm.config import CacheConfig, VllmConfig |
| 13 | from vllm.distributed import ( |
| 14 | get_pp_group, |
| 15 | get_tensor_model_parallel_world_size, |
| 16 | ) |
| 17 | from vllm.model_executor.layers.activation import SiluAndMul |
| 18 | from vllm.model_executor.layers.attention import Attention |
| 19 | from vllm.model_executor.layers.fused_moe import ( |
| 20 | FusedMoEFactory, |
| 21 | GateLinear, |
| 22 | ) |
| 23 | from vllm.model_executor.layers.linear import ( |
| 24 | MergedColumnParallelLinear, |
| 25 | QKVParallelLinear, |
| 26 | RowParallelLinear, |
| 27 | ) |
| 28 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 29 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 30 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 31 | from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding |
| 32 | from vllm.model_executor.model_loader.weight_utils import ( |
| 33 | row_parallel_weight_loader, |
| 34 | ) |
| 35 | from vllm.model_executor.utils import set_weight_attrs |
| 36 | from vllm.platforms import current_platform |
| 37 | from vllm.sequence import IntermediateTensors |
| 38 | |
| 39 | from .commandr import LayerNorm |
| 40 | from .interfaces import EagleModelMixin, SupportsEagle3, SupportsPP, SupportsQuant |
| 41 | from .utils import ( |
| 42 | AutoWeightsLoader, |
| 43 | WeightsMapper, |
| 44 | extract_layer_index, |
| 45 | make_empty_intermediate_tensors_factory, |
| 46 | make_layers, |
| 47 | maybe_prefix, |
| 48 | ) |
| 49 | |
| 50 | |
| 51 | def is_prefix_dense_layer(config: CohereConfig, layer_idx: int) -> bool: |
| 52 | """True when layer_idx lies in the contiguous dense MLP prefix.""" |
| 53 | if layer_idx >= len(config.mlp_layer_types): |
| 54 | return False |
| 55 | return all(t == "dense" for t in config.mlp_layer_types[: layer_idx + 1]) |
| 56 | |
| 57 | |
| 58 | @torch.compile(backend=current_platform.simple_compile_backend) |
| 59 | def token_choice_with_bias( |
| 60 | hidden_states: torch.Tensor, |
| 61 | gating_output: torch.Tensor, |
| 62 | topk: int, |
| 63 | renormalize: bool, |
| 64 | ): |
| 65 | """Sigmoid -> top-k (-> renormalize) custom routing for Cohere2Moe.""" |
| 66 | assert hidden_states.shape[0] == gating_output.shape[0], "Number of tokens mismatch" |
| 67 | |
| 68 | scores = gating_output.float().sigmoid() |
| 69 | topk_weights, topk_ids = torch.topk(scores, k=topk, dim=-1, sorted=False) |
| 70 | |
| 71 | if renormalize: |
| 72 | topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True) |
| 73 | |
| 74 | return topk_weights.to(torch.float32), topk_ids.to(torch.int32) |
| 75 | |
| 76 | |
| 77 | @torch.compile(backend=current_platform.simple_compile_backend) |
| 78 | def rms_norm_func(hidden_states, weight, variance_epsilon): |
| 79 | input_dtype = hidden_states.dtype |
| 80 | hidden_states = hidden_states.to(torch.float32) |
| 81 | variance = hidden_states.pow(2).mean(-1, keepdim=True) |
| 82 | hidden_states = hidden_states * torch.rsqrt(variance + variance_epsilon) |
| 83 | hidden_states = weight.to(torch.float32) * hidden_states |
| 84 | return hidden_states.to(input_dtype) |
| 85 | |
| 86 | |
| 87 | class RMSNorm(nn.Module): |
| 88 | def __init__(self, param_shape=None, eps=1e-6): |
| 89 | super().__init__() |
| 90 | self.weight = nn.Parameter(torch.ones(param_shape)) |
| 91 | self.variance_epsilon = eps |
| 92 | set_weight_attrs(self.weight, {"weight_loader": row_parallel_weight_loader}) |
| 93 | |
| 94 | def forward(self, hidden_states, residuals=None): |
| 95 | hidden_states = rms_norm_func(hidden_states, self.weight, self.variance_epsilon) |
| 96 | return hidden_states, residuals |
| 97 | |
| 98 | |
| 99 | def select_norm_impl(config: CohereConfig) -> tuple[type[nn.Module], float]: |
| 100 | """Returns (norm_class, eps). Uses RMSNorm when config.rms_norm_eps is set, |
| 101 | otherwise falls back to LayerNorm with config.layer_norm_eps.""" |
| 102 | rms_eps = getattr(config, "rms_norm_eps", None) |
| 103 | if rms_eps is not None: |
| 104 | return RMSNorm, rms_eps |
| 105 | return LayerNorm, config.layer_norm_eps |
| 106 | |
| 107 | |
| 108 | class Cohere2MoeMLP(nn.Module): |
| 109 | """Cohere MLP used as shared experts in the MoE block.""" |
| 110 | |
| 111 | def __init__( |
| 112 | self, |
| 113 | config: CohereConfig, |
| 114 | intermediate_size: int | None = None, |
| 115 | quant_config: QuantizationConfig | None = None, |
| 116 | reduce_results: bool = False, |
| 117 | prefix: str = "", |
| 118 | ): |
| 119 | super().__init__() |
| 120 | self.config = config |
| 121 | self.hidden_size = config.hidden_size |
| 122 | self.intermediate_size = ( |
| 123 | intermediate_size |
| 124 | if intermediate_size is not None |
| 125 | else config.intermediate_size |
| 126 | ) |
| 127 | self.gate_up_proj = MergedColumnParallelLinear( |
| 128 | self.hidden_size, |
| 129 | [self.intermediate_size] * 2, |
| 130 | bias=False, |
| 131 | quant_config=quant_config, |
| 132 | prefix=f"{prefix}.gate_up_proj", |
| 133 | ) |
| 134 | self.down_proj = RowParallelLinear( |
| 135 | self.intermediate_size, |
| 136 | self.hidden_size, |
| 137 | bias=False, |
| 138 | quant_config=quant_config, |
| 139 | reduce_results=reduce_results, |
| 140 | prefix=f"{prefix}.down_proj", |
| 141 | ) |
| 142 | self.act_fn = SiluAndMul() |
| 143 | |
| 144 | def forward(self, x): |
| 145 | gate_up, _ = self.gate_up_proj(x) |
| 146 | x = self.act_fn(gate_up) |
| 147 | x, _ = self.down_proj(x) |
| 148 | return x |
| 149 | |
| 150 | |
| 151 | class Cohere2MoeAttention(nn.Module): |
| 152 | """Cohere MoE attention with sliding-window interleave.""" |
| 153 | |
| 154 | def __init__( |
| 155 | self, |
| 156 | config: CohereConfig, |
| 157 | cache_config: CacheConfig | None = None, |
| 158 | quant_config: QuantizationConfig | None = None, |
| 159 | prefix: str = "", |
| 160 | ): |
| 161 | super().__init__() |
| 162 | tp_size = get_tensor_model_parallel_world_size() |
| 163 | self.config = config |
| 164 | self.layer_idx = extract_layer_index(prefix) |
| 165 | self.hidden_size = config.hidden_size |
| 166 | self.total_num_heads = config.num_attention_heads |
| 167 | self.num_heads = self.total_num_heads // tp_size |
| 168 | self.head_dim = getattr( |
| 169 | config, "head_dim", self.hidden_size // self.total_num_heads |
| 170 | ) |
| 171 | self.total_num_kv_heads = config.num_key_value_heads |
| 172 | if self.total_num_kv_heads >= tp_size: |
| 173 | assert self.total_num_kv_heads % tp_size == 0 |
| 174 | else: |
| 175 | assert tp_size % self.total_num_kv_heads == 0 |
| 176 | self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) |
| 177 | self.q_size = self.num_heads * self.head_dim |
| 178 | self.kv_size = self.num_kv_heads * self.head_dim |
| 179 | self.scaling = self.head_dim**-0.5 |
| 180 | self.max_position_embeddings = getattr( |
| 181 | config, "model_max_length", None |
| 182 | ) or getattr(config, "max_position_embeddings", 8192) |
| 183 | assert isinstance(self.max_position_embeddings, int) |
| 184 | self.qkv_proj = QKVParallelLinear( |
| 185 | self.hidden_size, |
| 186 | self.head_dim, |
| 187 | self.total_num_heads, |
| 188 | self.total_num_kv_heads, |
| 189 | bias=False, |
| 190 | quant_config=quant_config, |
| 191 | prefix=f"{prefix}.qkv_proj", |
| 192 | ) |
| 193 | self.o_proj = RowParallelLinear( |
| 194 | self.total_num_heads * self.head_dim, |
| 195 | self.hidden_size, |
| 196 | bias=False, |
| 197 | quant_config=quant_config, |
| 198 | prefix=f"{prefix}.o_proj", |
| 199 | ) |
| 200 | self.rotary_emb = get_rope( |
| 201 | self.head_dim, |
| 202 | max_position=self.max_position_embeddings, |
| 203 | rope_parameters=config.rope_parameters, |
| 204 | is_neox_style=False, |
| 205 | ) |
| 206 | |
| 207 | self.sliding_window = None |
| 208 | layer_types = getattr(config, "layer_types", None) |
| 209 | if ( |
| 210 | layer_types is not None |
| 211 | and layer_types[self.layer_idx] == "sliding_attention" |
| 212 | ): |
| 213 | self.sliding_window = config.sliding_window + 1 |
| 214 | |
| 215 | # Prefix-dense layers have full attention (no sliding window). When |
| 216 | # prefix_dense_sliding_window_pattern == 1, they keep RoPE even though |
| 217 | # they are not sliding-window layers. |
| 218 | prefix_dense_sliding_window_pattern = getattr( |
| 219 | config, "prefix_dense_sliding_window_pattern", 1 |
| 220 | ) |
| 221 | self.force_rope = bool( |
| 222 | is_prefix_dense_layer(config, self.layer_idx) |
| 223 | and prefix_dense_sliding_window_pattern == 1 |
| 224 | ) |
| 225 | |
| 226 | self.attn = Attention( |
| 227 | self.num_heads, |
| 228 | self.head_dim, |
| 229 | self.scaling, |
| 230 | num_kv_heads=self.num_kv_heads, |
| 231 | cache_config=cache_config, |
| 232 | quant_config=quant_config, |
| 233 | per_layer_sliding_window=self.sliding_window, |
| 234 | prefix=f"{prefix}.attn", |
| 235 | ) |
| 236 | |
| 237 | def forward( |
| 238 | self, |
| 239 | positions: torch.Tensor, |
| 240 | hidden_states: torch.Tensor, |
| 241 | ) -> torch.Tensor: |
| 242 | qkv, _ = self.qkv_proj(hidden_states) |
| 243 | q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) |
| 244 | if self.sliding_window or self.force_rope: |
| 245 | q, k = self.rotary_emb(positions, q, k) |
| 246 | attn_output = self.attn(q, k, v) |
| 247 | output, _ = self.o_proj(attn_output) |
| 248 | return output |
| 249 | |
| 250 | |
| 251 | class Cohere2Moe(nn.Module): |
| 252 | """Tensor-parallel MoE block for Cohere2Moe with shared experts.""" |
| 253 | |
| 254 | def __init__( |
| 255 | self, |
| 256 | config: CohereConfig, |
| 257 | params_dtype: torch.dtype | None = None, |
| 258 | quant_config: QuantizationConfig | None = None, |
| 259 | tp_size: int | None = None, |
| 260 | prefix: str = "", |
| 261 | ): |
| 262 | super().__init__() |
| 263 | self.hidden_size = config.hidden_size |
| 264 | self.tp_size = get_tensor_model_parallel_world_size() |
| 265 | |
| 266 | if self.tp_size > config.num_experts: |
| 267 | raise ValueError( |
| 268 | f"Tensor parallel size {self.tp_size} is greater than " |
| 269 | f"the number of experts {config.num_experts}." |
| 270 | ) |
| 271 | |
| 272 | if ( |
| 273 | hasattr(config, "expert_selection_fn") |
| 274 | and config.expert_selection_fn == "sigmoid" |
| 275 | ): |
| 276 | self.custom_routing_function = token_choice_with_bias |
| 277 | else: |
| 278 | self.custom_routing_function = None |
| 279 | |
| 280 | self.gate = GateLinear( |
| 281 | config.hidden_size, |
| 282 | config.num_experts, |
| 283 | params_dtype=params_dtype, |
| 284 | prefix=f"{prefix}.gate", |
| 285 | ) |
| 286 | |
| 287 | self.shared_experts: Cohere2MoeMLP | None |
| 288 | if hasattr(config, "num_shared_experts") and config.num_shared_experts > 0: |
| 289 | self.shared_experts = Cohere2MoeMLP( |
| 290 | config=config, |
| 291 | intermediate_size=config.intermediate_size * config.num_shared_experts, |
| 292 | quant_config=quant_config, |
| 293 | prefix=f"{prefix}.shared_experts", |
| 294 | ) |
| 295 | self.shared_expert_combination_strategy = getattr( |
| 296 | config, "shared_expert_combination_strategy", "sum" |
| 297 | ) |
| 298 | assert self.shared_expert_combination_strategy in ("average", "sum"), ( |
| 299 | "shared_expert_combination_strategy must be one of ['average', 'sum']" |
| 300 | ) |
| 301 | else: |
| 302 | self.shared_experts = None |
| 303 | self.shared_expert_combination_strategy = None |
| 304 | |
| 305 | self.experts = FusedMoEFactory( |
| 306 | num_experts=config.num_experts, |
| 307 | top_k=config.num_experts_per_tok, |
| 308 | hidden_size=config.hidden_size, |
| 309 | intermediate_size=config.intermediate_size, |
| 310 | params_dtype=params_dtype, |
| 311 | renormalize=getattr(config, "norm_topk_prob", True), |
| 312 | quant_config=quant_config, |
| 313 | tp_size=tp_size, |
| 314 | prefix=f"{prefix}.experts", |
| 315 | custom_routing_function=self.custom_routing_function, |
| 316 | shared_experts=self.shared_experts, |
| 317 | ) |
| 318 | |
| 319 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 320 | orig_shape = hidden_states.shape |
| 321 | hidden_states = hidden_states.view(-1, self.hidden_size) |
| 322 | router_logits, _ = self.gate(hidden_states) |
| 323 | # FusedMoEFactory handles shared expert overlap internally and returns |
| 324 | # shared_output + routed_output when shared_experts is set. |
| 325 | final_hidden_states = self.experts(hidden_states, router_logits) |
| 326 | if self.shared_expert_combination_strategy == "average": |
| 327 | final_hidden_states = final_hidden_states / 2 |
| 328 | return final_hidden_states.view(orig_shape) |
| 329 | |
| 330 | |
| 331 | class Cohere2MoeDecoderLayer(nn.Module): |
| 332 | def __init__( |
| 333 | self, |
| 334 | config: CohereConfig, |
| 335 | cache_config: CacheConfig | None = None, |
| 336 | quant_config: QuantizationConfig | None = None, |
| 337 | prefix: str = "", |
| 338 | ): |
| 339 | super().__init__() |
| 340 | self.config = config |
| 341 | self.hidden_size = config.hidden_size |
| 342 | self.layer_idx = extract_layer_index(prefix) |
| 343 | |
| 344 | self.self_attn = Cohere2MoeAttention( |
| 345 | config, |
| 346 | cache_config, |
| 347 | quant_config=quant_config, |
| 348 | prefix=f"{prefix}.self_attn", |
| 349 | ) |
| 350 | |
| 351 | if config.mlp_layer_types[self.layer_idx] == "dense": |
| 352 | self.mlp = Cohere2MoeMLP( |
| 353 | config=config, |
| 354 | intermediate_size=getattr( |
| 355 | config, "prefix_dense_intermediate_size", config.intermediate_size |
| 356 | ), |
| 357 | quant_config=quant_config, |
| 358 | reduce_results=True, |
| 359 | prefix=f"{prefix}.mlp", |
| 360 | ) |
| 361 | else: |
| 362 | self.mlp = Cohere2Moe( |
| 363 | config=config, quant_config=quant_config, prefix=f"{prefix}.mlp" |
| 364 | ) |
| 365 | |
| 366 | norm_cls, norm_eps = select_norm_impl(config) |
| 367 | self.input_layernorm = norm_cls(param_shape=(config.hidden_size,), eps=norm_eps) |
| 368 | |
| 369 | def forward( |
| 370 | self, |
| 371 | positions: torch.Tensor, |
| 372 | hidden_states: torch.Tensor, |
| 373 | residual: torch.Tensor | None, |
| 374 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 375 | residual = hidden_states |
| 376 | hidden_states, residual = self.input_layernorm(hidden_states, residual) |
| 377 | hidden_states_attention = self.self_attn( |
| 378 | positions=positions, |
| 379 | hidden_states=hidden_states, |
| 380 | ) |
| 381 | hidden_states_mlp = self.mlp(hidden_states) |
| 382 | |
| 383 | hidden_states = residual + hidden_states_attention + hidden_states_mlp |
| 384 | return hidden_states, residual |
| 385 | |
| 386 | |
| 387 | @support_torch_compile |
| 388 | class Cohere2MoeModel(nn.Module, EagleModelMixin): |
| 389 | """Transformer decoder for Cohere2Moe.""" |
| 390 | |
| 391 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 392 | super().__init__() |
| 393 | |
| 394 | config = vllm_config.model_config.hf_config |
| 395 | cache_config = vllm_config.cache_config |
| 396 | quant_config = vllm_config.quant_config |
| 397 | |
| 398 | self.config = config |
| 399 | self.quant_config = quant_config |
| 400 | self.vocab_size = config.vocab_size |
| 401 | self.org_vocab_size = config.vocab_size |
| 402 | self.embed_tokens = VocabParallelEmbedding( |
| 403 | config.vocab_size, config.hidden_size |
| 404 | ) |
| 405 | |
| 406 | # Decoder layers read per-layer MLP layout from config.mlp_layer_types |
| 407 | # (dense MLP vs MoE) and use it for weight loading. Transformers >=5.10 |
| 408 | # populates this field; older versions only expose first_k_dense_replace. |
| 409 | # Normalize here so layer construction below sees a consistent layout. |
| 410 | if getattr(config, "mlp_layer_types", None) is None: |
| 411 | first_k_dense_replace = getattr(config, "first_k_dense_replace", None) |
| 412 | n = config.num_hidden_layers |
| 413 | if first_k_dense_replace is not None: |
| 414 | config.mlp_layer_types = ["dense"] * first_k_dense_replace + [ |
| 415 | "sparse" |
| 416 | ] * (n - first_k_dense_replace) |
| 417 | else: |
| 418 | config.mlp_layer_types = ["sparse"] * n |
| 419 | |
| 420 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 421 | config.num_hidden_layers, |
| 422 | lambda prefix: Cohere2MoeDecoderLayer( |
| 423 | config, cache_config, quant_config, prefix=prefix |
| 424 | ), |
| 425 | prefix=f"{prefix}.layers", |
| 426 | ) |
| 427 | norm_cls, norm_eps = select_norm_impl(config) |
| 428 | self.norm = norm_cls(param_shape=(config.hidden_size,), eps=norm_eps) |
| 429 | self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( |
| 430 | ["hidden_states", "residual"], config.hidden_size |
| 431 | ) |
| 432 | |
| 433 | def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 434 | return self.embed_tokens(input_ids) |
| 435 | |
| 436 | def forward( |
| 437 | self, |
| 438 | input_ids: torch.Tensor, |
| 439 | positions: torch.Tensor, |
| 440 | intermediate_tensors: IntermediateTensors | None = None, |
| 441 | inputs_embeds: torch.Tensor | None = None, |
| 442 | ) -> torch.Tensor | IntermediateTensors | tuple[torch.Tensor, list[torch.Tensor]]: |
| 443 | if get_pp_group().is_first_rank: |
| 444 | if inputs_embeds is not None: |
| 445 | hidden_states = inputs_embeds |
| 446 | else: |
| 447 | hidden_states = self.get_input_embeddings(input_ids) |
| 448 | residual = None |
| 449 | else: |
| 450 | assert intermediate_tensors is not None |
| 451 | hidden_states = intermediate_tensors["hidden_states"] |
| 452 | residual = intermediate_tensors["residual"] |
| 453 | |
| 454 | aux_hidden_states = [] |
| 455 | if self.start_layer in self.aux_hidden_state_layers: |
| 456 | aux_hidden_states.append(hidden_states) |
| 457 | for layer_idx, layer in enumerate( |
| 458 | islice(self.layers, self.start_layer, self.end_layer), |
| 459 | start=self.start_layer, |
| 460 | ): |
| 461 | hidden_states, residual = layer(positions, hidden_states, residual) |
| 462 | if layer_idx + 1 in self.aux_hidden_state_layers: |
| 463 | aux_hidden_states.append(hidden_states) |
| 464 | if not get_pp_group().is_last_rank: |
| 465 | return IntermediateTensors( |
| 466 | {"hidden_states": hidden_states, "residual": residual} |
| 467 | ) |
| 468 | hidden_states, _ = self.norm(hidden_states, residual) |
| 469 | if aux_hidden_states: |
| 470 | return hidden_states, aux_hidden_states |
| 471 | return hidden_states |
| 472 | |
| 473 | |
| 474 | class Cohere2MoeForCausalLM(nn.Module, SupportsPP, SupportsQuant, SupportsEagle3): |
| 475 | is_text_generation_model = True |
| 476 | |
| 477 | hf_to_vllm_mapper = WeightsMapper( |
| 478 | orig_to_new_stacked={ |
| 479 | # weight_name: (param_name, shard_id) |
| 480 | ".q_proj": (".qkv_proj", "q"), |
| 481 | ".k_proj": (".qkv_proj", "k"), |
| 482 | ".v_proj": (".qkv_proj", "v"), |
| 483 | # .experts.gate_up_proj must be handled by MoERunner.load_weights for EP |
| 484 | ".mlp.gate_proj": (".mlp.gate_up_proj", 0), |
| 485 | ".mlp.up_proj": (".mlp.gate_up_proj", 1), |
| 486 | ".shared_experts.gate_proj": (".shared_experts.gate_up_proj", 0), |
| 487 | ".shared_experts.up_proj": (".shared_experts.gate_up_proj", 1), |
| 488 | }, |
| 489 | orig_to_new_prefix={"lm_head.": None}, |
| 490 | ) |
| 491 | packed_modules_mapping = { |
| 492 | "qkv_proj": [ |
| 493 | "q_proj", |
| 494 | "k_proj", |
| 495 | "v_proj", |
| 496 | ], |
| 497 | "gate_up_proj": [ |
| 498 | "gate_proj", |
| 499 | "up_proj", |
| 500 | ], |
| 501 | } |
| 502 | |
| 503 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 504 | super().__init__() |
| 505 | config = vllm_config.model_config.hf_config |
| 506 | quant_config = vllm_config.quant_config |
| 507 | self.config = config |
| 508 | self.unpadded_vocab_size = config.vocab_size |
| 509 | self.quant_config = quant_config |
| 510 | self.logits_scale = config.logit_scale |
| 511 | self.logits_processor = LogitsProcessor( |
| 512 | self.unpadded_vocab_size, config.vocab_size, scale=self.logits_scale |
| 513 | ) |
| 514 | self.model = Cohere2MoeModel( |
| 515 | vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") |
| 516 | ) |
| 517 | self.make_empty_intermediate_tensors = ( |
| 518 | self.model.make_empty_intermediate_tensors |
| 519 | ) |
| 520 | |
| 521 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 522 | return self.model.get_input_embeddings(input_ids) |
| 523 | |
| 524 | def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 525 | return self.model.get_input_embeddings(input_ids) |
| 526 | |
| 527 | @torch.no_grad() |
| 528 | def forward( |
| 529 | self, |
| 530 | input_ids: torch.Tensor, |
| 531 | positions: torch.Tensor, |
| 532 | intermediate_tensors: IntermediateTensors | None = None, |
| 533 | inputs_embeds: torch.Tensor | None = None, |
| 534 | ) -> torch.Tensor | IntermediateTensors | tuple[torch.Tensor, list[torch.Tensor]]: |
| 535 | return self.model(input_ids, positions, intermediate_tensors, inputs_embeds) |
| 536 | |
| 537 | def compute_logits( |
| 538 | self, |
| 539 | hidden_states: torch.Tensor, |
| 540 | ) -> torch.Tensor | None: |
| 541 | return self.logits_processor(self.model.embed_tokens, hidden_states) |
| 542 | |
| 543 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 544 | loader = AutoWeightsLoader(self) |
| 545 | return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper) |