punica_gpu.py 10.6 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6
7
8
9
"""
Based on:
Chen, L., Ye, Z., Wu, Y., Zhuo, D., Ceze, L., & Krishnamurthy, A. (2023). 
Punica: Multi-Tenant LoRA Serving. 
https://arxiv.org/abs/2310.18547
"""

10
from typing import TYPE_CHECKING, Optional, Union, final
11
12
13

import torch

14
import vllm.envs as envs
15
from vllm.lora.layers import LoRAMapping
16
17
18
from vllm.triton_utils import HAS_TRITON

if HAS_TRITON:
19
20
    from vllm.lora.ops.triton_ops import (LoRAKernelMeta, lora_expand,
                                          lora_shrink)
21
22
23

from .punica_base import PunicaWrapperBase

24
25
26
27
28
if TYPE_CHECKING:
    # avoid circuit import
    from vllm.lora.models import LongContextLoRAContext


29
@final
30
class PunicaWrapperGPU(PunicaWrapperBase):
31
32
33
34
35
36
37
38
39
40
41
    """
    PunicaWrapperGPU is designed to manage and provide metadata for the punica 
    kernel. The main function is to maintain the state information for 
    Multi-LoRA, and to provide the interface for the punica triton kernel.
    """

    def __init__(self, max_num_batched_tokens: int, max_batches: int,
                 device: Union[torch.device, str], **kwargs):
        PunicaWrapperBase.__init__(self, max_num_batched_tokens, max_batches,
                                   device)

42
43
        self.max_loras = kwargs['max_loras']

44
45
46
        self.token_mapping_meta = LoRAKernelMeta.make(self.max_loras,
                                                      max_num_batched_tokens,
                                                      device=device)
47
48
49
50
51
52
53

        # When cudagraph capture size is greater than max_num_seqs (max_batches,
        # here), V0 captures the graph as if max_num_seqs is set to
        # the capture size.
        # V1 doesn't have this problem and always respects max_num_seqs.
        max_num_prompts = (max_batches
                           if envs.VLLM_USE_V1 else max_num_batched_tokens)
54
        self.prompt_mapping_meta = LoRAKernelMeta.make(self.max_loras,
55
                                                       max_num_prompts,
56
                                                       device=device)
57
58
59
60

    def update_metadata(
            self,
            mapping: LoRAMapping,
61
            lora_index_to_id: list[Optional[int]],
62
63
64
65
66
67
            max_loras: int,
            vocab_size: int,
            extra_vocab_size: int,
            long_lora_context: Optional["LongContextLoRAContext"] = None,
            **kwargs):

68
69
70
71
        self.is_prefill = mapping.is_prefill
        self._update_base_metadata(mapping, lora_index_to_id, max_loras,
                                   vocab_size, extra_vocab_size,
                                   long_lora_context)
72

73
74
75
        # Prepare cuda kernel metadata tensors
        self.token_mapping_meta.prepare_tensors(self.token_lora_indices)
        self.prompt_mapping_meta.prepare_tensors(self.sampler_indices)
76

77
    def add_shrink(self, y: torch.Tensor, x: torch.Tensor,
78
                   lora_a_stacked: tuple[torch.Tensor,
79
                                         ...], scale: float, **kwargs):
80
81
82
83
84
85
86
87
        """
        Performs GEMM  for multiple slices of lora_a.
            
        Semantics:
        for i in range(len(lora_a_stacked)):
            y[i] += (x @ lora_a_stacked[i]) * scale
        
        Args:
88
            y (torch.Tensor): Output tensors
89
            x (torch.Tensor): Input tensor
90
            lora_a_stacked (tuple[torch.Tensor, ...]): lora_a's weights
91
92
93
94
            scale (float): Scaling factor for the operation
        """

        x = x.view(-1, x.shape[-1])
95
96
97
98
99
100
101
        lora_shrink(
            x,
            lora_a_stacked,
            y,
            *self.token_mapping_meta.meta_args(x.size(0)),
            scale,
        )
102
103
104

    def add_expand(self,
                   y: torch.Tensor,
105
                   x: torch.Tensor,
106
107
108
                   lora_b_stacked: tuple[torch.Tensor, ...],
                   lora_bias_stacked: Optional[tuple[torch.Tensor, ...]],
                   output_slices: tuple[int, ...],
109
                   offset_start: int = 0,
110
                   add_inputs=True,
111
112
113
114
115
116
117
118
119
120
121
122
123
                   **kwargs) -> None:
        """
        Performs GEMM and bias addition for multiple slices of lora_b.
      
        Semantics:
            for i in range(len(lora_b_stacked)):
                slice = output_slices[i]
                y[:, offset:offset+slice] += x[i] @ lora_b_stacked[i] + 
                    lora_bias_stacked[i] 
                offset += slice
            
        Args:
            y (torch.Tensor): Output tensor.
124
            x (torch.Tensor): Input tensors
125
126
            lora_b_stacked (tuple[torch.Tensor, ...]): lora_b's weight
            lora_bias_stacked (Optional[tuple[torch.Tensor, ...]]): 
127
                bias's weight
128
            output_slices (tuple[int, ...]): Every slice's size
Jee Jee Li's avatar
Jee Jee Li committed
129
            add_inputs (bool): Defaults to True.
130
131
132
133
        """
        y_org = y
        y = y.view(-1, y.shape[-1])
        if lora_bias_stacked is not None:
134
135
136
            token_lora_indices = torch.narrow(self._token_lora_indices, 0, 0,
                                              y.size(0))
            self._apply_bias(token_lora_indices, y, output_slices,
137
                             lora_bias_stacked)
138

139
140
141
142
143
144
145
146
147
148
149
150
151
        assert x.ndim == 3
        assert x.size(0) == len(output_slices)
        num_tokens = x.size(1)  # first dimension is the num slices

        lora_expand(
            x,
            lora_b_stacked,
            y,
            *self.token_mapping_meta.meta_args(num_tokens),
            offset_start=offset_start,
            add_inputs=True,
        )

152
153
154
155
156
157
        y = y.view_as(y_org)

    def add_lora_embedding(self,
                           y: torch.Tensor,
                           x: torch.Tensor,
                           lora_b_stacked: torch.Tensor,
158
                           add_inputs: bool = True,
159
160
161
162
163
164
165
166
167
168
169
                           **kwargs) -> None:
        """
        Applies lora  specifically for VocabParallelEmbeddingWithLoRA.

        Semantics:
            y += x @ lora_b_stacked

        Args:
            y (torch.Tensor): Output tensor.
            x (torch.Tensor): Input tensor.
            lora_b_stacked (torch.Tensor): lora_b's weights.
170
            add_inputs (bool): Default to True.
171
172
        """

173
174
175
176
177
178
179
180
        lora_expand(
            x.unsqueeze(dim=0),
            (lora_b_stacked, ),
            y,
            *self.token_mapping_meta.meta_args(x.size(0)),
            offset_start=0,
            add_inputs=add_inputs,
        )
181
182
183
184

    def add_lora_linear(self,
                        y: torch.Tensor,
                        x: torch.Tensor,
185
186
187
                        lora_a_stacked: tuple[torch.Tensor, ...],
                        lora_b_stacked: tuple[torch.Tensor, ...],
                        lora_bias_stacked: Optional[tuple[torch.Tensor, ...]],
188
                        scale: float,
189
                        output_slices: tuple[int, ...],
190
                        *,
191
                        buffer: Optional[torch.Tensor] = None,
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
                        **kwargs) -> None:
        """
        Applicable to linear-related lora. 

        Semantics:
            for i in range(len(lora_a_stacked)):
                y[i] += (
                    x[i].unsqueeze(0)
                    @ lora_a_stacked[indices[i], layer_idx, :, :]
                    @ lora_b_stacked[indices[i], layer_idx, :, :]
                    * scale
                    ).squeeze(0)+lora_bias_stacked[i]

        Args:
            y (torch.Tensor): Output tensor. Will be changed in-place.
            x (torch.Tensor): Input tensor
208
209
210
            lora_a_stacked (tuple[torch.Tensor, ...]): lora_a's weight.
            lora_b_stacked (tuple[torch.Tensor, ...]): lora_b's weight.
            lora_bias_stacked (Optional[tuple[torch.Tensor, ...]]): lora's bias.
211
            scale (float): Scaling factor.
212
            output_slices (tuple[int, ...]): Every slice's size.
213
            buffer (Optional[torch.Tensor]): Defaults to None.
214
215
216
217
218
        """

        assert len(lora_a_stacked) == len(lora_b_stacked) == len(output_slices)
        if lora_bias_stacked is not None:
            assert len(lora_bias_stacked) == len(output_slices)
219
220
221
            token_lora_indices = torch.narrow(self._token_lora_indices, 0, 0,
                                              y.size(0))
            y = self._apply_bias(token_lora_indices, y, output_slices,
222
223
224
225
                                 lora_bias_stacked)

        if buffer is None:
            r = lora_b_stacked[0].size(-1)
Jee Jee Li's avatar
Jee Jee Li committed
226
            # We set the buffer to be float32 by default, refer to:
227
            # https://github.com/triton-lang/triton/issues/1387
228
            buffer = torch.zeros(  # type: ignore
229
230
231
232
                (len(output_slices), x.size(0), r),
                dtype=torch.float32,
                device=x.device,
            )
233
234
235
236
237
238
239
240
241
242
243
244
245
246
        self.add_shrink(
            buffer,  # type: ignore
            x,
            lora_a_stacked,
            scale,
            **kwargs)
        self.add_expand(
            y,
            buffer,  # type: ignore
            lora_b_stacked,
            None,
            output_slices,
            add_inputs=True,
            **kwargs)
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267

    def add_lora_logits(self,
                        y: torch.Tensor,
                        x: torch.Tensor,
                        lora_a_stacked: torch.Tensor,
                        lora_b_stacked: torch.Tensor,
                        scale,
                        *,
                        buffer: Optional[torch.Tensor] = None,
                        **kwargs) -> None:
        """
        Applies lora  specifically for LogitsProcessorWithLoRA.
        
        Semantics:
            buffer = (x @ lora_a_stacked) * scale
            y += buffer @ lora_b_stacked

        Args:
            y (torch.Tensor): Output tensor.
            x (torch.Tensor): Input tensor.
            lora_a_stacked (torch.Tensor): lora_a's weights.
Jee Jee Li's avatar
Jee Jee Li committed
268
            lora_b_stacked (torch.Tensor): lora_b's weights.
269
            scale (float): Scaling factor.
Jee Jee Li's avatar
Jee Jee Li committed
270
            buffer (Optional[torch.Tensor]): Default to None.
271
272
273
274
275
276
        """
        y_org = y
        y = y.view(-1, y.shape[-1])
        x = x.view(-1, x.shape[-1])
        r = lora_b_stacked.size(-1)
        if buffer is None:
Jee Jee Li's avatar
Jee Jee Li committed
277
            # We set the buffer to be float32 by default, refer to:
278
279
280
281
            # https://github.com/triton-lang/triton/issues/1387
            buffer = torch.zeros((x.size(0), r),
                                 dtype=torch.float32,
                                 device=x.device)
282

283
284
285
286
287
288
289
        lora_shrink(x, [lora_a_stacked], buffer.unsqueeze(dim=0),
                    *self.prompt_mapping_meta.meta_args(x.size(0)), scale)

        lora_expand(buffer.unsqueeze(dim=0), [lora_b_stacked],
                    y,
                    *self.prompt_mapping_meta.meta_args(buffer.size(0)),
                    add_inputs=True)
290
        y = y.view_as(y_org)