|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. |
| 3 | +# Copyright 2023 The vLLM team. |
| 4 | +# |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | +# Adapted from vllm/model_executor/layers/lmhead.py |
| 18 | +# This file is a part of the vllm-ascend project. |
| 19 | + |
| 20 | +from typing import Optional |
| 21 | + |
| 22 | +import torch |
| 23 | +from torch.nn.parameter import Parameter |
| 24 | +from vllm.distributed import divide |
| 25 | +from vllm.model_executor.layers.quantization.base_config import ( |
| 26 | + QuantizationConfig, QuantizeMethodBase, method_has_implemented_embedding) |
| 27 | +from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 28 | + UnquantizedEmbeddingMethod, VocabParallelEmbedding, pad_vocab_size) |
| 29 | +from vllm.model_executor.utils import set_weight_attrs |
| 30 | + |
| 31 | +from vllm_ascend.distributed.parallel_state import get_lmhead_group |
| 32 | + |
| 33 | +DEFAULT_VOCAB_PADDING_SIZE = 64 |
| 34 | + |
| 35 | + |
| 36 | +class CustomParallelLMHead(VocabParallelEmbedding): |
| 37 | + """Parallelized LM head. |
| 38 | +
|
| 39 | + Output logits weight matrices used in the Sampler. The weight and bias |
| 40 | + tensors are padded to make sure they are divisible by the number of |
| 41 | + model parallel GPUs. |
| 42 | +
|
| 43 | + Args: |
| 44 | + num_embeddings: vocabulary size. |
| 45 | + embedding_dim: size of hidden state. |
| 46 | + bias: whether to use bias. |
| 47 | + params_dtype: type of the parameters. |
| 48 | + org_num_embeddings: original vocabulary size (without LoRA). |
| 49 | + padding_size: padding size for the vocabulary. |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__(self, |
| 53 | + num_embeddings: int, |
| 54 | + embedding_dim: int, |
| 55 | + bias: bool = False, |
| 56 | + params_dtype: Optional[torch.dtype] = None, |
| 57 | + org_num_embeddings: Optional[int] = None, |
| 58 | + padding_size: int = DEFAULT_VOCAB_PADDING_SIZE, |
| 59 | + quant_config: Optional[QuantizationConfig] = None, |
| 60 | + prefix: str = ""): |
| 61 | + super().__init__(num_embeddings, embedding_dim, params_dtype, |
| 62 | + org_num_embeddings, padding_size, quant_config, |
| 63 | + prefix) |
| 64 | + # Keep the input dimensions. |
| 65 | + tp_rank = get_lmhead_group().rank_in_group |
| 66 | + self.tp_size = get_lmhead_group().world_size |
| 67 | + self.num_embeddings = num_embeddings |
| 68 | + self.padding_size = padding_size |
| 69 | + self.org_vocab_size = org_num_embeddings or num_embeddings |
| 70 | + num_added_embeddings = num_embeddings - self.org_vocab_size |
| 71 | + self.org_vocab_size_padded = pad_vocab_size(self.org_vocab_size, |
| 72 | + self.padding_size) |
| 73 | + self.num_embeddings_padded = pad_vocab_size( |
| 74 | + self.org_vocab_size_padded + num_added_embeddings, |
| 75 | + self.padding_size) |
| 76 | + assert self.org_vocab_size_padded <= self.num_embeddings_padded |
| 77 | + |
| 78 | + self.shard_indices = self._get_indices(self.num_embeddings_padded, |
| 79 | + self.org_vocab_size_padded, |
| 80 | + self.num_embeddings, |
| 81 | + self.org_vocab_size, tp_rank, |
| 82 | + self.tp_size) |
| 83 | + self.embedding_dim = embedding_dim |
| 84 | + |
| 85 | + quant_method = None |
| 86 | + if quant_config is not None: |
| 87 | + quant_method = quant_config.get_quant_method(self, prefix=prefix) |
| 88 | + if quant_method is None: |
| 89 | + quant_method = UnquantizedEmbeddingMethod() |
| 90 | + |
| 91 | + # If we are making an embedding layer, then our quantization linear |
| 92 | + # method must implement the embedding operation. If we are another |
| 93 | + # layer type like ParallelLMHead, this is not important. |
| 94 | + is_embedding_layer = type(self) is VocabParallelEmbedding |
| 95 | + quant_method_implements_embedding = method_has_implemented_embedding( |
| 96 | + type(quant_method)) |
| 97 | + if is_embedding_layer and not quant_method_implements_embedding: |
| 98 | + raise NotImplementedError( |
| 99 | + f"The class {type(quant_method).__name__} must implement " |
| 100 | + "the 'embedding' method, see UnquantizedEmbeddingMethod.") |
| 101 | + |
| 102 | + self.quant_method: QuantizeMethodBase = quant_method |
| 103 | + |
| 104 | + if params_dtype is None: |
| 105 | + params_dtype = torch.get_default_dtype() |
| 106 | + # Divide the weight matrix along the vocaburaly dimension. |
| 107 | + self.num_added_embeddings = self.num_embeddings - self.org_vocab_size |
| 108 | + self.num_embeddings_per_partition = divide(self.num_embeddings_padded, |
| 109 | + self.tp_size) |
| 110 | + assert (self.shard_indices.num_elements_padded == |
| 111 | + self.num_embeddings_per_partition) |
| 112 | + self.num_org_embeddings_per_partition = ( |
| 113 | + self.shard_indices.org_vocab_end_index - |
| 114 | + self.shard_indices.org_vocab_start_index) |
| 115 | + self.num_added_embeddings_per_partition = ( |
| 116 | + self.shard_indices.added_vocab_end_index - |
| 117 | + self.shard_indices.added_vocab_start_index) |
| 118 | + |
| 119 | + self.quant_method.create_weights(self, |
| 120 | + self.embedding_dim, |
| 121 | + [self.num_embeddings_per_partition], |
| 122 | + self.embedding_dim, |
| 123 | + self.num_embeddings_padded, |
| 124 | + params_dtype=params_dtype, |
| 125 | + weight_loader=self.weight_loader) |
| 126 | + |
| 127 | + self.quant_config = quant_config |
| 128 | + if bias: |
| 129 | + self.bias = Parameter( |
| 130 | + torch.empty(self.num_embeddings_per_partition, |
| 131 | + dtype=params_dtype)) |
| 132 | + set_weight_attrs(self.bias, { |
| 133 | + "output_dim": 0, |
| 134 | + "weight_loader": self.weight_loader, |
| 135 | + }) |
| 136 | + else: |
| 137 | + self.register_parameter("bias", None) |
| 138 | + |
| 139 | + def tie_weights(self, embed_tokens: VocabParallelEmbedding): |
| 140 | + """Tie the weights with word embeddings.""" |
| 141 | + # GGUF quantized embed_tokens. |
| 142 | + if self.quant_config and self.quant_config.get_name() == "gguf": |
| 143 | + return embed_tokens |
| 144 | + else: |
| 145 | + self.weight = embed_tokens.weight |
| 146 | + return self |
| 147 | + |
| 148 | + def forward(self, input_): |
| 149 | + del input_ |
| 150 | + raise RuntimeError("LMHead's weights should be used in the sampler.") |
0 commit comments