"tests/vscode:/vscode.git/clone" did not exist on "f825c6bd22133a8b2242457069f59654a2ae401b"
lora.py 6.15 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
from collections.abc import Sequence as GenericSequence
from typing import Optional
6
7

import torch
8
import torch.types
9

10
from vllm.lora.peft_helper import PEFTHelper
11
from vllm.utils import is_pin_memory_available
12
13
14
15
16
17
18
19
20
21
22
23


class LoRALayerWeights:
    """LoRA weights for a layer composed of two low rank matrixes."""

    def __init__(
        self,
        module_name: str,
        rank: int,
        lora_alpha: int,
        lora_a: torch.Tensor,
        lora_b: torch.Tensor,
24
        bias: Optional[torch.Tensor] = None,
25
26
27
28
29
30
31
32
        embeddings_tensor: Optional[torch.Tensor] = None,
        scaling: Optional[float] = None,
    ) -> None:
        self.module_name = module_name
        self.rank = rank
        self.lora_alpha = lora_alpha
        self.lora_a = lora_a
        self.lora_b = lora_b
33
        self.bias = bias
34
35
36
37
38
39
40
41
42
43
        self.embeddings_tensor = embeddings_tensor

        if scaling is None:
            self.scaling = self.lora_alpha / self.rank
        else:
            self.scaling = scaling

    def optimize(self) -> "LoRALayerWeights":
        """Optimize the LoRA by merging the scaling into lora_b."""
        if self.scaling == 1:
44
            return self
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
        self.lora_b *= self.scaling
        self.scaling = 1
        return self

    @property
    def input_dim(self) -> int:
        return self.lora_a.shape[0]

    @property
    def output_dim(self) -> int:
        return self.lora_b.shape[1]

    @property
    def is_packed(self) -> bool:
        return False

    @property
    def extra_vocab_size(self) -> int:
        return self.embeddings_tensor.shape[
            0] if self.embeddings_tensor is not None else 0

66
67
68
69
70
71
72
    @classmethod
    def from_config(
        cls,
        module_name: str,
        peft_helper: PEFTHelper,
        embeddings_tensor: Optional[torch.Tensor] = None,
    ) -> "LoRALayerWeights":
73
74
75
        return cls(module_name, peft_helper.r, peft_helper.lora_alpha, None,
                   None, None, embeddings_tensor,
                   peft_helper.vllm_lora_scaling_factor)
76

77
78
79
80
81
82
83
84
    @classmethod
    def create_dummy_lora_weights(
            cls,
            module_name: str,
            input_dim: int,
            output_dim: int,
            rank: int,
            dtype: torch.dtype,
85
            device: torch.types.Device,
86
87
            embeddings_tensor_dim: Optional[int] = None,
            bias_enabled: Optional[bool] = False) -> "LoRALayerWeights":
88
        pin_memory = str(device) == "cpu" and is_pin_memory_available()
89
90
91
92
93
94
95
96
        lora_a = torch.zeros([input_dim, rank],
                             dtype=dtype,
                             device=device,
                             pin_memory=pin_memory)
        lora_b = torch.zeros([rank, output_dim],
                             dtype=dtype,
                             device=device,
                             pin_memory=pin_memory)
97
98
99
100
101
102
103
104
        if bias_enabled:
            bias = torch.zeros([output_dim],
                               dtype=dtype,
                               device=device,
                               pin_memory=pin_memory)
        else:
            bias = None

105
106
107
108
109
110
111
112
113
114
115
116
        embeddings_tensor = torch.rand(
            10,
            embeddings_tensor_dim,
            dtype=dtype,
            device=device,
            pin_memory=pin_memory) if embeddings_tensor_dim else None
        return cls(
            module_name,
            rank=rank,
            lora_alpha=1,
            lora_a=lora_a,
            lora_b=lora_b,
117
            bias=bias,
118
119
120
121
122
123
124
125
126
127
128
            embeddings_tensor=embeddings_tensor,
        )


class PackedLoRALayerWeights(LoRALayerWeights):
    """LoRA used for packed layers (eg. qkv_proj)."""

    def __init__(
        self,
        module_name: str,
        rank: int,
129
130
131
132
133
        lora_alphas: list[Optional[int]],
        lora_a: list[Optional[torch.Tensor]],
        lora_b: list[Optional[torch.Tensor]],
        bias: Optional[list[Optional[torch.Tensor]]] = None,
        scaling: Optional[list[float]] = None,
134
135
136
137
138
139
140
    ) -> None:
        super().__init__(
            module_name=module_name,
            rank=rank,
            lora_alpha=0,
            lora_a=lora_a,
            lora_b=lora_b,
141
            bias=bias,
142
            scaling=scaling,  # type: ignore
143
144
145
146
            embeddings_tensor=None,
        )
        self.lora_alphas = lora_alphas
        if scaling is None:
147
148
149
            self.scaling = [  # type: ignore
                lora_alpha / self.rank  # type: ignore # noqa
                for lora_alpha in self.lora_alphas
150
151
152
            ]

    @classmethod
153
    def pack(
154
        cls, loras: GenericSequence[Optional["LoRALayerWeights"]]
155
    ) -> "PackedLoRALayerWeights":
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        """Pack a list of LoRAs into a single LoRA.

        If LoRA is None, it signifies that the submodule does not have a LoRA.
        """
        first_lora = next(lora for lora in loras if lora is not None)
        for lora in loras:
            if lora is None:
                continue
            lora.optimize()
        rank = first_lora.rank
        module_name = first_lora.module_name
        obj = cls(
            module_name,
            rank,
            [lora.lora_alpha if lora is not None else None for lora in loras],
            [lora.lora_a if lora is not None else None for lora in loras],
            [lora.lora_b if lora is not None else None for lora in loras],
173
            [lora.bias if lora is not None else None for lora in loras],
174
175
176
177
            scaling=[
                1 if lora is not None else None  # type: ignore
                for lora in loras
            ])
178
179
180
181
182
        return obj

    def optimize(self) -> "PackedLoRALayerWeights":
        """Optimize the LoRA by merging the scaling into lora_b."""
        for i in range(len(self.lora_b)):
183
            if self.scaling[i] == 1 or self.lora_b[i] is None:  # type: ignore
184
                continue
185
186
            self.lora_b[i] *= self.scaling[i]  # type: ignore
            self.scaling[i] = 1  # type: ignore
187
188
189
190
191
192
193
194
195
196
197
198
199
        return self

    @property
    def input_dim(self) -> int:
        raise NotImplementedError()

    @property
    def output_dim(self) -> int:
        raise NotImplementedError()

    @property
    def is_packed(self) -> bool:
        return True