row_parallel_linear.py 6.12 KB
Newer Older
Jee Jee Li's avatar
Jee Jee Li committed
1
2
3
4
5
6
7
8
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project


import torch
import torch.nn as nn
from transformers import PretrainedConfig

9
from vllm.config.lora import LoRAConfig
10
11
12
13
from vllm.distributed import (
    split_tensor_along_last_dim,
    tensor_model_parallel_all_reduce,
)
14
from vllm.model_executor.custom_op import maybe_get_oot_by_class
Jee Jee Li's avatar
Jee Jee Li committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from vllm.model_executor.layers.linear import RowParallelLinear
from vllm.platforms import current_platform

from .base_linear import BaseLinearLayerWithLoRA
from .utils import _fully_sharded_can_replace, _not_fully_sharded_can_replace


class RowParallelLinearWithLoRA(BaseLinearLayerWithLoRA):
    def __init__(self, base_layer: RowParallelLinear) -> None:
        super().__init__(base_layer)

        # reset input_size
        self.input_size = self.base_layer.input_size_per_partition
        self.output_size = self.base_layer.output_size
        # There is only one LoRA layer.
        self.n_slices = 1

    def slice_lora_a(self, lora_a: torch.Tensor) -> torch.Tensor:
        shard_size = self.input_size
        start_idx = self.tp_rank * shard_size
        end_idx = (self.tp_rank + 1) * shard_size
36
        lora_a = lora_a[:, start_idx:end_idx]
Jee Jee Li's avatar
Jee Jee Li committed
37
38
39
40
41
42
43
        return lora_a

    def slice_lora_b(self, lora_b: torch.Tensor) -> torch.Tensor:
        return lora_b

    def forward(
        self, input_: torch.Tensor
44
    ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor | None]:
Jee Jee Li's avatar
Jee Jee Li committed
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
        """Forward of RowParallelLinear

        Args:
            input_: tensor whose last dimension is `input_size`. If
                    `input_is_parallel` is set, then the last dimension
                    is `input_size // tp_size`.

        Returns:
            - output
            - bias
        """
        # set up backprop all-reduce.
        if self.base_layer.input_is_parallel:
            input_parallel = input_
        else:
            # TODO: simplify code below
Jiayi Yan's avatar
Jiayi Yan committed
61
            split_input = split_tensor_along_last_dim(
62
63
                input_, num_partitions=self.tp_size
            )
Jiayi Yan's avatar
Jiayi Yan committed
64
            input_parallel = split_input[self.tp_rank].contiguous()
Jee Jee Li's avatar
Jee Jee Li committed
65
66

        # Matrix multiply.
67
68
69
70
71
72
        bias_ = (
            None
            if (self.tp_rank > 0 or self.base_layer.skip_bias_add)
            else self.base_layer.bias
        )
        output_parallel = self.apply(input_parallel, bias_)
73
        if self.base_layer.reduce_results and self.tp_size > 1:
74
            output = tensor_model_parallel_all_reduce(output_parallel)
Jee Jee Li's avatar
Jee Jee Li committed
75
        else:
76
            output = output_parallel
Jee Jee Li's avatar
Jee Jee Li committed
77

78
        output_bias = self.base_layer.bias if self.base_layer.skip_bias_add else None
Jee Jee Li's avatar
Jee Jee Li committed
79
80
81
82
83
84
85
86
87
88
89
90
        if not self.base_layer.return_bias:
            return output

        return output, output_bias

    @classmethod
    @_not_fully_sharded_can_replace
    def can_replace_layer(
        cls,
        source_layer: nn.Module,
        lora_config: LoRAConfig,
        packed_modules_list: list,
91
        model_config: PretrainedConfig | None = None,
Jee Jee Li's avatar
Jee Jee Li committed
92
    ) -> bool:
93
        return type(source_layer) is maybe_get_oot_by_class(RowParallelLinear)
Jee Jee Li's avatar
Jee Jee Li committed
94
95
96
97
98
99


# The following layer is based on the tensor parallelism strategy given in
# Y. Sheng et al., S-LoRA: Serving Thousands of Concurrent LoRA Adapters. 2023,
# https://arxiv.org/abs/2311.03285.

100

Jee Jee Li's avatar
Jee Jee Li committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class RowParallelLinearWithShardedLoRA(RowParallelLinearWithLoRA):
    """
    Differs from RowParallelLinearWithLoRA by slicing the
    LoRA B's also.

    Based on S-LoRA, slicing happens along the output dim.
    This yields a combined partial sum from the row parallel base
    layer and column partitioned output from the LoRA.
    """

    def slice_lora_b(self, lora_b: torch.Tensor) -> torch.Tensor:
        shard_size = self.lora_b_stacked[0].shape[2]
        start_idx = self.tp_rank * shard_size
        end_idx = (self.tp_rank + 1) * shard_size
115
        lora_b = lora_b[start_idx:end_idx, :]
Jee Jee Li's avatar
Jee Jee Li committed
116
117
        return lora_b

118
    def apply(self, x: torch.Tensor, bias: torch.Tensor | None = None) -> torch.Tensor:
119
        output = self.base_layer.quant_method.apply(self.base_layer, x, bias)
Jee Jee Li's avatar
Jee Jee Li committed
120
121

        x = x.view(-1, x.shape[-1])
122
        output, out_orig_shape = output.view(-1, output.shape[-1]), output.shape
Jee Jee Li's avatar
Jee Jee Li committed
123
124
125
126
127
128
        buffer = torch.zeros(
            (self.n_slices, x.shape[0], self.lora_a_stacked[0].shape[2]),
            dtype=torch.float32,
            device=x.device,
        )

129
        shrunk_buffer: torch.Tensor | None = self.punica_wrapper.add_shrink(
130
131
            buffer, x, self.lora_a_stacked, 1.0
        )
Jee Jee Li's avatar
Jee Jee Li committed
132
133
        if not current_platform.can_update_inplace():
            buffer = shrunk_buffer
134
        if self.tp_size > 1:
135
            buffer = tensor_model_parallel_all_reduce(buffer)
Jee Jee Li's avatar
Jee Jee Li committed
136
137
138
139
140
141
142
143
144
145

        # following S-LoRA, allows the fusing of all_gather and all_reduce
        # by adding the column partitioned lora output to a slice of output
        # tensor, which is a partial sum due to row parallel. All that
        # remains is a standard all_reduce. User should be aware though that
        # the output is not the same as a normal row_parallel, it should be
        # reduced before being used
        # NOTE offset are based on the rank.
        shard_size = self.lora_b_stacked[0].shape[2]
        offset_start = self.tp_rank * shard_size
146
        lora_output: torch.Tensor | None = self.punica_wrapper.add_expand(
Jee Jee Li's avatar
Jee Jee Li committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
            output,
            buffer,
            self.lora_b_stacked,
            self.output_slices,
            offset_start=offset_start,
            add_input=True,
        )

        if not current_platform.can_update_inplace():
            output = lora_output

        output = output.view(*out_orig_shape)
        return output

    @classmethod
    @_fully_sharded_can_replace
    def can_replace_layer(
        cls,
        source_layer: nn.Module,
        lora_config: LoRAConfig,
        packed_modules_list: list,
168
        model_config: PretrainedConfig | None = None,
Jee Jee Li's avatar
Jee Jee Li committed
169
170
171
172
173
174
175
176
177
    ) -> bool:
        # specifying kwargs so they can be easily accessed in decorator
        return super().can_replace_layer(
            source_layer=source_layer,
            lora_config=lora_config,
            packed_modules_list=packed_modules_list,
            model_config=model_config,
            decorate=False,
        )