# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2024 Cohere and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This file is based on the LLama model definition file in transformers """PyTorch Cohere model.""" from collections.abc import Iterable from itertools import islice import torch from torch import nn from transformers import Cohere2Config, CohereConfig from vllm.compilation.decorators import support_torch_compile from vllm.config import CacheConfig, VllmConfig from vllm.distributed import ( get_pp_group, get_tensor_model_parallel_world_size, tensor_model_parallel_all_reduce, ) from vllm.model_executor.layers.activation import SiluAndMul from vllm.model_executor.layers.attention import Attention from vllm.model_executor.layers.linear import ( MergedColumnParallelLinear, QKVParallelLinear, RowParallelLinear, ) from vllm.model_executor.layers.logits_processor import LogitsProcessor from vllm.model_executor.layers.quantization import QuantizationConfig from vllm.model_executor.layers.rotary_embedding import get_rope from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding from vllm.model_executor.model_loader.weight_utils import row_parallel_weight_loader from vllm.model_executor.utils import set_weight_attrs from vllm.platforms import current_platform from vllm.sequence import IntermediateTensors from .interfaces import SupportsLoRA, SupportsPP, SupportsQuant from .utils import ( AutoWeightsLoader, WeightsMapper, extract_layer_index, make_empty_intermediate_tensors_factory, make_layers, maybe_prefix, ) @torch.compile(backend=current_platform.simple_compile_backend) def layer_norm_func(hidden_states, weight, variance_epsilon): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) mean = hidden_states.mean(-1, keepdim=True) variance = (hidden_states - mean).pow(2).mean(-1, keepdim=True) hidden_states = (hidden_states - mean) * torch.rsqrt(variance + variance_epsilon) hidden_states = weight.to(torch.float32) * hidden_states return hidden_states.to(input_dtype) class LayerNorm(nn.Module): def __init__(self, param_shape=None, eps=1e-5): super().__init__() self.weight = nn.Parameter(torch.ones(param_shape)) self.variance_epsilon = eps set_weight_attrs(self.weight, {"weight_loader": row_parallel_weight_loader}) def forward(self, hidden_states, residuals=None): hidden_states = layer_norm_func( hidden_states, self.weight, self.variance_epsilon ) return hidden_states, residuals @torch.compile(backend=current_platform.simple_compile_backend) def rms_norm_func(hidden_states, weight, variance_epsilon): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + variance_epsilon) hidden_states = weight.to(torch.float32) * hidden_states return hidden_states.to(input_dtype) class RMSNorm(nn.Module): def __init__(self, param_shape=None, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(param_shape)) self.variance_epsilon = eps set_weight_attrs(self.weight, {"weight_loader": row_parallel_weight_loader}) def forward(self, hidden_states, residuals=None): hidden_states = rms_norm_func(hidden_states, self.weight, self.variance_epsilon) return hidden_states, residuals def select_norm_impl(config: CohereConfig) -> tuple[type[nn.Module], float]: """Returns the normalization layer class and epsilon value to use. If `config.rms_norm_eps` is present, use RMSNorm. Otherwise default to LayerNorm with `config.layer_norm_eps`. """ rms_eps = getattr(config, "rms_norm_eps", None) if rms_eps is not None: return RMSNorm, rms_eps return LayerNorm, config.layer_norm_eps # Copied from transformers.models.llama.modeling_llama.LlamaMLP Llama->Cohere class CohereMLP(nn.Module): def __init__( self, config: CohereConfig, intermediate_size: int | None = None, quant_config: QuantizationConfig | None = None, # so we can reduce the attention and MLP outputs together reduce_results: bool = False, prefix: str = "", ): super().__init__() self.config = config self.hidden_size = config.hidden_size if intermediate_size is None: self.intermediate_size = config.intermediate_size else: self.intermediate_size = intermediate_size self.gate_up_proj = MergedColumnParallelLinear( self.hidden_size, [self.intermediate_size] * 2, bias=False, quant_config=quant_config, prefix=f"{prefix}.gate_up_proj", ) self.down_proj = RowParallelLinear( self.intermediate_size, self.hidden_size, bias=False, quant_config=quant_config, reduce_results=reduce_results, prefix=f"{prefix}.down_proj", ) self.act_fn = SiluAndMul() def forward(self, x): gate_up, _ = self.gate_up_proj(x) x = self.act_fn(gate_up) x, _ = self.down_proj(x) return x class CohereAttention(nn.Module): def __init__( self, config: CohereConfig | Cohere2Config, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ): super().__init__() tp_size = get_tensor_model_parallel_world_size() self.config = config self.layer_idx = extract_layer_index(prefix) self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size self.total_num_heads = config.num_attention_heads self.num_heads = self.total_num_heads // tp_size if hasattr(config, "head_dim"): self.head_dim = config.head_dim else: self.head_dim = self.hidden_size // self.total_num_heads self.total_num_kv_heads = config.num_key_value_heads if self.total_num_kv_heads >= tp_size: # Number of KV heads is greater than TP size, so we partition # the KV heads across multiple tensor parallel GPUs. assert self.total_num_kv_heads % tp_size == 0 else: # Number of KV heads is less than TP size, so we replicate # the KV heads across multiple tensor parallel GPUs. assert tp_size % self.total_num_kv_heads == 0 self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) self.q_size = self.num_heads * self.head_dim self.kv_size = self.num_kv_heads * self.head_dim self.scaling = self.head_dim**-0.5 self.max_position_embeddings = getattr( config, "model_max_length", None ) or getattr(config, "max_position_embeddings", 8192) assert isinstance(self.max_position_embeddings, int) self.use_qk_norm = getattr(config, "use_qk_norm", False) self.qkv_proj = QKVParallelLinear( self.hidden_size, self.head_dim, self.total_num_heads, self.total_num_kv_heads, bias=False, quant_config=quant_config, prefix=f"{prefix}.qkv_proj", ) self.o_proj = RowParallelLinear( self.total_num_heads * self.head_dim, self.hidden_size, bias=False, quant_config=quant_config, prefix=f"{prefix}.o_proj", # NOTE: reduction will happen in the decoder layer forward # so we can combine the attention and MLP outputs together reduce_results=False, ) self.rotary_emb = get_rope( self.head_dim, max_position=self.max_position_embeddings, rope_parameters=config.rope_parameters, is_neox_style=False, ) # Model v2 has interleaved sliding windows, v1 does not self.v1 = isinstance(config, CohereConfig) # cohere swa layer sees [pos - sliding_window, pos], i.e. sliding_window + 1 # tokens. vLLM's FlashAttention backend does (value - 1, 0), so we pass # sliding_window + 1 here to match the training convention. The same +1 # propagates into the KV-cache eviction formula # (single_type_kv_cache_manager.py), keeping both paths consistent. self.sliding_window = None if not self.v1 and config.layer_types[self.layer_idx] == "sliding_attention": self.sliding_window = config.sliding_window + 1 self.attn = Attention( self.num_heads, self.head_dim, self.scaling, num_kv_heads=self.num_kv_heads, cache_config=cache_config, quant_config=quant_config, per_layer_sliding_window=self.sliding_window, prefix=f"{prefix}.attn", ) norm_cls, norm_eps = select_norm_impl(config) if self.use_qk_norm: self.q_norm = norm_cls( param_shape=(self.num_heads, self.head_dim), eps=norm_eps ) self.k_norm = norm_cls( param_shape=(self.num_kv_heads, self.head_dim), eps=norm_eps ) def _apply_qk_norm(self, q, k): q = q.view(*q.shape[:-1], -1, self.head_dim) k = k.view(*k.shape[:-1], -1, self.head_dim) q, _ = self.q_norm(q) k, _ = self.k_norm(k) q = q.view(*q.shape[:-2], -1) k = k.view(*k.shape[:-2], -1) return q, k def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, ) -> torch.Tensor: qkv, _ = self.qkv_proj(hidden_states) q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) if self.use_qk_norm: q, k = self._apply_qk_norm(q, k) if self.v1 or self.sliding_window: q, k = self.rotary_emb(positions, q, k) attn_output = self.attn(q, k, v) output, _ = self.o_proj(attn_output) return output class CohereDecoderLayer(nn.Module): def __init__( self, config: CohereConfig | Cohere2Config, cache_config: CacheConfig | None = None, quant_config: QuantizationConfig | None = None, prefix: str = "", ): super().__init__() self.hidden_size = config.hidden_size self.tp_size = get_tensor_model_parallel_world_size() self.self_attn = CohereAttention( config, cache_config, quant_config=quant_config, prefix=f"{prefix}.self_attn", ) self.mlp = CohereMLP(config, quant_config=quant_config, prefix=f"{prefix}.mlp") norm_cls, norm_eps = select_norm_impl(config) self.input_layernorm = norm_cls(param_shape=(config.hidden_size), eps=norm_eps) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, residual: torch.Tensor | None, ) -> tuple[torch.Tensor, torch.Tensor]: # Self Attention residual = hidden_states hidden_states, residual = self.input_layernorm(hidden_states, residual) hidden_states_attention = self.self_attn( positions=positions, hidden_states=hidden_states, ) hidden_states_mlp = self.mlp(hidden_states) parallel_block_output = hidden_states_attention + hidden_states_mlp # Add everything together if self.tp_size > 1: # do the reduction in 1 shot instead of 2 separate all reduce parallel_block_output = tensor_model_parallel_all_reduce( parallel_block_output ) hidden_states = residual + parallel_block_output return hidden_states, residual @support_torch_compile class CohereModel(nn.Module): def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() config = vllm_config.model_config.hf_config cache_config = vllm_config.cache_config quant_config = vllm_config.quant_config self.quant_config = quant_config self.config = config self.vocab_size = config.vocab_size self.embed_tokens = VocabParallelEmbedding( config.vocab_size, config.hidden_size ) self.start_layer, self.end_layer, self.layers = make_layers( config.num_hidden_layers, lambda prefix: CohereDecoderLayer( config, cache_config, quant_config, prefix=prefix ), prefix=f"{prefix}.layers", ) norm_cls, norm_eps = select_norm_impl(config) self.norm = norm_cls(param_shape=(config.hidden_size), eps=norm_eps) self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( ["hidden_states", "residual"], config.hidden_size ) def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids) def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None, inputs_embeds: torch.Tensor | None = None, ) -> torch.Tensor | IntermediateTensors: if get_pp_group().is_first_rank: if inputs_embeds is not None: hidden_states = inputs_embeds else: hidden_states = self.embed_input_ids(input_ids) residual = None else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] residual = intermediate_tensors["residual"] for layer in islice(self.layers, self.start_layer, self.end_layer): hidden_states, residual = layer( positions, hidden_states, residual, ) if not get_pp_group().is_last_rank: return IntermediateTensors( {"hidden_states": hidden_states, "residual": residual} ) hidden_states, _ = self.norm(hidden_states, residual) return hidden_states class CohereForCausalLM(nn.Module, SupportsLoRA, SupportsPP, SupportsQuant): hf_to_vllm_mapper = WeightsMapper( orig_to_new_stacked={ # weight_name: (param_name, shard_id) ".q_proj": (".qkv_proj", "q"), ".k_proj": (".qkv_proj", "k"), ".v_proj": (".qkv_proj", "v"), ".gate_proj": (".gate_up_proj", 0), ".up_proj": (".gate_up_proj", 1), }, # ModelOpt NVFP4 checkpoints carry raw quantizer-module state # (e.g. "*.weight_quantizer._double_scale"); drop them before loading. # See #41925. orig_to_new_substr={"_quantizer.": None}, orig_to_new_prefix={"lm_head": None}, ) packed_modules_mapping: dict[str, list[str]] = { "qkv_proj": ["q_proj", "k_proj", "v_proj"], "gate_up_proj": ["gate_proj", "up_proj"], } # LoRA specific attributes embedding_modules = {"embed_tokens": "input_embeddings"} def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): super().__init__() config = vllm_config.model_config.hf_config quant_config = vllm_config.quant_config self.config = config self.quant_config = quant_config self.logits_processor = LogitsProcessor( config.vocab_size, scale=config.logit_scale ) self.model = CohereModel( vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") ) self.make_empty_intermediate_tensors = ( self.model.make_empty_intermediate_tensors ) def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: return self.model.embed_input_ids(input_ids) @torch.no_grad() def forward( self, input_ids: torch.Tensor | None, positions: torch.Tensor, intermediate_tensors: IntermediateTensors | None = None, inputs_embeds: torch.Tensor | None = None, ) -> torch.Tensor | IntermediateTensors: hidden_states = self.model( input_ids, positions, intermediate_tensors, inputs_embeds ) return hidden_states def compute_logits( self, hidden_states: torch.Tensor, ) -> torch.Tensor | None: is_not_lora = hasattr(self.model.embed_tokens, "weight") if is_not_lora: logits = self.logits_processor(self.model.embed_tokens, hidden_states) else: logits = self.logits_processor( self.model.embed_tokens.base_layer, hidden_states ) return logits def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: loader = AutoWeightsLoader(self) return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)