| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | # Copyright 2024 The vLLM team. |
| 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 | """Transformers modeling backend mixins for pooling models.""" |
| 18 | |
| 19 | from typing import TYPE_CHECKING |
| 20 | |
| 21 | import torch |
| 22 | import torch.nn as nn |
| 23 | from transformers import AutoModelForSequenceClassification |
| 24 | |
| 25 | from vllm.config.utils import getattr_iter |
| 26 | from vllm.model_executor.layers.pooler import DispatchPooler |
| 27 | from vllm.model_executor.models.interfaces import SupportsCrossEncoding |
| 28 | from vllm.model_executor.models.interfaces_base import VllmModelForPooling |
| 29 | |
| 30 | from .base import Base |
| 31 | |
| 32 | if TYPE_CHECKING: |
| 33 | from vllm.config import VllmConfig |
| 34 | |
| 35 | |
| 36 | class ClassifierWithReshape(nn.Module): |
| 37 | """Token extraction has already been applied in `pooler.pooling`. |
| 38 | |
| 39 | Add dim to match expected input shape of `classifier.forward`. |
| 40 | """ |
| 41 | |
| 42 | def forward(self, *args, **kwargs): |
| 43 | if len(args) > 0: |
| 44 | args = (args[0].unsqueeze(1), *args[1:]) |
| 45 | return super().forward(*args, **kwargs) |
| 46 | |
| 47 | |
| 48 | class EmbeddingMixin(VllmModelForPooling, Base): |
| 49 | default_seq_pooling_type = "CLS" |
| 50 | |
| 51 | def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): |
| 52 | # Skip VllmModelForPooling.__init__ and call the next class in MRO |
| 53 | super(VllmModelForPooling, self).__init__( |
| 54 | vllm_config=vllm_config, prefix=prefix |
| 55 | ) |
| 56 | |
| 57 | pooler_config = vllm_config.model_config.pooler_config |
| 58 | assert pooler_config is not None |
| 59 | |
| 60 | self.pooler = DispatchPooler.for_embedding(pooler_config) |
| 61 | |
| 62 | |
| 63 | class SequenceClassificationMixin(SupportsCrossEncoding, VllmModelForPooling, Base): |
| 64 | default_seq_pooling_type = "CLS" |
| 65 | |
| 66 | def __init__(self, *, vllm_config: "VllmConfig", prefix: str = ""): |
| 67 | # Skip VllmModelForPooling.__init__ and call the next class in MRO |
| 68 | super(VllmModelForPooling, self).__init__( |
| 69 | vllm_config=vllm_config, prefix=prefix |
| 70 | ) |
| 71 | |
| 72 | pooler_config = vllm_config.model_config.pooler_config |
| 73 | assert pooler_config is not None |
| 74 | |
| 75 | # Certain information about the model and classifier can only be |
| 76 | # inferred from the `ForSequenceClassification` class. Therefore, we |
| 77 | # instantiate it on the "meta" device to avoid allocating GPU memory. |
| 78 | with torch.device("meta"): |
| 79 | seq_cls_model = AutoModelForSequenceClassification.from_config( |
| 80 | self.config, |
| 81 | dtype=self.model_config.dtype, |
| 82 | trust_remote_code=self.model_config.trust_remote_code, |
| 83 | ) |
| 84 | |
| 85 | # When used for sequence classification, some models have their |
| 86 | # pooling layers removed. Make sure this is reflected in vLLM. |
| 87 | for module in seq_cls_model.modules(): |
| 88 | if hasattr(module, "pooler") and module.pooler is None: |
| 89 | self.model.pooler = None |
| 90 | break |
| 91 | |
| 92 | # Unlike `lm_head`, `classifier` is not always `nn.Linear`. |
| 93 | self.classifier = getattr_iter(seq_cls_model, ["classifier", "score"], None) |
| 94 | if self.classifier is None: |
| 95 | raise ValueError( |
| 96 | "Could not find `classifier` or `score` layer in the " |
| 97 | "`AutoModelForSequenceClassification` instance." |
| 98 | ) |
| 99 | self.init_parameters(self.classifier, dtype=self.model_config.head_dtype) |
| 100 | |
| 101 | # Order `ClassifierWithReshape` ahead of the classifier's own class so that |
| 102 | # its `super().forward(...)` reaches the original implementation. |
| 103 | self.classifier.__class__ = type( |
| 104 | "ClassifierWithReshape", |
| 105 | (ClassifierWithReshape, type(self.classifier)), |
| 106 | {}, |
| 107 | ) |
| 108 | |
| 109 | self.pooler = DispatchPooler.for_seq_cls( |
| 110 | pooler_config, |
| 111 | classifier=self.classifier, |
| 112 | ) |