Skip to content

vllm.lora.punica_wrapper.punica_xpu

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

PunicaWrapperXPU

Bases: PunicaWrapperBase

PunicaWrapperXPU 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 ipex kernel.

Source code in vllm/lora/punica_wrapper/punica_xpu.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
@final
class PunicaWrapperXPU(PunicaWrapperBase):
    """
    PunicaWrapperXPU 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 ipex kernel.
    """

    def __init__(
        self,
        max_num_batched_tokens: int,
        max_batches: int,
        device: torch.device | str,
        **kwargs,
    ):
        PunicaWrapperBase.__init__(self, max_num_batched_tokens, max_batches, device)
        torch._dynamo.mark_dynamic(self._token_lora_indices, 0)
        torch._dynamo.mark_dynamic(self._embeddings_indices, 1)
        torch._dynamo.mark_dynamic(self._sampler_indices_padded, 0)

        self.lora_config = kwargs["lora_config"]
        self.max_loras = self.lora_config.max_loras

        # Compute captured LoRA counts for cudagraph specialization.
        captured_lora_counts = get_captured_lora_counts(
            self.max_loras, self.lora_config.specialize_active_lora
        )

        self.token_mapping_meta = LoRAKernelMeta.make(
            self.max_loras,
            max_num_batched_tokens,
            device=device,
            captured_lora_counts=captured_lora_counts,
        )

        self.prompt_mapping_meta = LoRAKernelMeta.make(
            self.max_loras,
            max_num_batched_tokens,
            device=device,
            captured_lora_counts=captured_lora_counts,
        )

    def update_metadata(
        self,
        mapping: LoRAMapping,
        lora_index_to_id: list[int | None],
        max_loras: int,
        vocab_size: int,
        **kwargs,
    ):
        self.is_prefill = mapping.is_prefill
        self._update_base_metadata(mapping, lora_index_to_id, max_loras, vocab_size)

        # Prepare kernel metadata tensors
        self.token_mapping_meta.prepare_tensors(self.token_lora_indices)
        self.prompt_mapping_meta.prepare_tensors(self.sampler_indices)

    def _get_token_lora_indices(self, x: torch.Tensor) -> torch.IntTensor:
        return torch.narrow(self._token_lora_indices, 0, 0, x.size(0))

    def _apply_shrink(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        w_t_all: torch.Tensor,
        scale: float,
    ):
        bgmv_shrink(x, w_t_all, y, self._get_token_lora_indices(x), scale)

    def _apply_expand(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        w_t_all: torch.Tensor,
        y_offset: int,
        y_slice_size: int,
        add_inputs: bool,
    ):
        token_lora_indices = self._get_token_lora_indices(x)
        bgmv_expand_slice(
            x, w_t_all, y, token_lora_indices, y_offset, y_slice_size, add_inputs
        )

    def add_shrink(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_a_stacked: tuple[torch.Tensor, ...],
        scale: float,
        **kwargs,
    ):
        """
        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:
            y (torch.Tensor): Output tensors
            x (torch.Tensor): Input tensor
            lora_a_stacked (tuple[torch.Tensor, ...]): lora_a's weights
            scale (float): Scaling factor for the operation
        """

        x = x.view(-1, x.shape[-1])
        for slice_idx in range(len(lora_a_stacked)):
            self._apply_shrink(y[slice_idx], x, lora_a_stacked[slice_idx], scale)

    def add_expand(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_b_stacked: tuple[torch.Tensor, ...],
        output_slices: tuple[int, ...],
        offset_start: int = 0,
        add_inputs=True,
        **kwargs,
    ) -> None:
        """
        Performs GEMM 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]
                offset += slice

        Args:
            y (torch.Tensor): Output tensor.
            x (torch.Tensor): Input tensors
            lora_b_stacked (tuple[torch.Tensor, ...]): lora_b's weight
            output_slices (tuple[int, ...]): Every slice's size
            add_inputs (bool): Defaults to True.
        """
        y_org = y
        y = y.view(-1, y.shape[-1])

        assert x.ndim == 3
        assert x.size(0) == len(output_slices)

        # TODO fuse these kernels
        for slice_idx in range(len(lora_b_stacked)):
            self._apply_expand(
                y,
                x[slice_idx],
                lora_b_stacked[slice_idx],
                offset_start,
                output_slices[slice_idx],
                add_inputs=add_inputs,
            )
            offset_start += output_slices[slice_idx]
        y.view_as(y_org)

    def add_lora_embedding(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_b_stacked: torch.Tensor,
        add_inputs: bool = True,
        **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.
            add_inputs (bool): Default to True.
        """
        token_lora_indices = self._get_token_lora_indices(x)
        bgmv_expand(x, lora_b_stacked, y, token_lora_indices, add_inputs)

    def add_lora_linear(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_a_stacked: tuple[torch.Tensor, ...],
        lora_b_stacked: tuple[torch.Tensor, ...],
        scale: float,
        output_slices: tuple[int, ...],
        *,
        buffer: torch.Tensor | None = None,
        **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)

        Args:
            y (torch.Tensor): Output tensor. Will be changed in-place.
            x (torch.Tensor): Input tensor
            lora_a_stacked (tuple[torch.Tensor, ...]): lora_a's weight.
            lora_b_stacked (tuple[torch.Tensor, ...]): lora_b's weight.
            scale (float): Scaling factor.
            output_slices (tuple[int, ...]): Every slice's size.
            buffer (Optional[torch.Tensor]): Defaults to None.
        """

        assert len(lora_a_stacked) == len(lora_b_stacked) == len(output_slices)

        if buffer is None:
            r = lora_b_stacked[0].size(-1)
            buffer = torch.zeros(  # type: ignore
                (len(output_slices), x.size(0), r),
                dtype=x.dtype,
                device=x.device,
            )
        self.add_shrink(
            buffer,  # type: ignore
            x,
            lora_a_stacked,
            scale,
            **kwargs,
        )
        self.add_expand(
            y,
            buffer,  # type: ignore
            lora_b_stacked,
            output_slices,
            add_inputs=True,
            **kwargs,
        )

    @property
    def sampler_indices_padded(self) -> torch.Tensor:
        """
        This property provides access to padded sampler indices.
        """
        return self._sampler_indices_padded[:]

    def add_lora_logits(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_a_stacked: torch.Tensor,
        lora_b_stacked: torch.Tensor,
        scale,
        *,
        buffer: torch.Tensor | None = 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.
            lora_b_stacked (torch.Tensor): lora_b's weights.
            scale (float): Scaling factor.
            buffer (Optional[torch.Tensor]): Default to None.
        """
        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:
            buffer = torch.zeros((x.size(0), r), dtype=x.dtype, device=x.device)
        sampler_indices = torch.narrow(self._sampler_indices, 0, 0, x.size(0))
        bgmv_shrink(x, lora_a_stacked, buffer, sampler_indices, scale)
        bgmv_expand(buffer, lora_b_stacked, y, sampler_indices, add_inputs=True)
        return y.view_as(y_org)

    def moe_lora_align_block_size(
        self,
        topk_ids: torch.Tensor,
        num_tokens: int,
        block_size: int,
        num_experts: int,
        max_loras: int,
        adapter_enabled: torch.Tensor,
        expert_map: torch.Tensor | None = None,
        pad_sorted_ids: bool = False,
        naive_block_assignment: bool = False,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
        """
        Aligns tokens and experts into block-sized chunks for LoRA-based
        mixture-of-experts (MoE) execution.
        """
        (token_lora_mapping, _, _, _, lora_ids, _, _) = (
            self.token_mapping_meta.meta_args(
                num_tokens, self.lora_config.specialize_active_lora
            )
        )
        if naive_block_assignment:
            expert_ids = topk_ids.reshape(-1)
            sorted_ids = None
            num_tokens_post_pad = None
        else:
            max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1)
            if pad_sorted_ids:
                max_num_tokens_padded = round_up(max_num_tokens_padded, block_size)
            sorted_ids = torch.empty(
                (max_loras * max_num_tokens_padded,),
                dtype=torch.int32,
                device=topk_ids.device,
            )
            max_num_m_blocks = triton.cdiv(max_num_tokens_padded, block_size)
            # Expert ids must be set default to -1 to prevent a blank block
            expert_ids = torch.empty(
                (max_loras * max_num_m_blocks,),
                dtype=torch.int32,
                device=topk_ids.device,
            )
            num_tokens_post_pad = torch.empty(
                (max_loras), dtype=torch.int32, device=topk_ids.device
            )

            ops.moe_lora_align_block_size(
                topk_ids,
                token_lora_mapping,
                num_experts,
                block_size,
                max_loras,
                max_num_tokens_padded,
                max_num_m_blocks,
                sorted_ids,
                expert_ids,
                num_tokens_post_pad,
                adapter_enabled,
                lora_ids,
            )
            if expert_map is not None:
                expert_ids = expert_map[expert_ids]

        return None, sorted_ids, expert_ids, num_tokens_post_pad

    def add_lora_fused_moe(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_a_stacked: tuple[torch.Tensor, ...],
        lora_b_stacked: tuple[torch.Tensor, ...],
        topk_weights: torch.Tensor,
        sorted_token_ids: torch.Tensor | None,
        expert_ids: torch.Tensor,
        num_tokens_post_padded: torch.Tensor | None,
        max_lora_rank: int,
        top_k_num: int,
        shrink_config,
        expand_config,
        adapter_enabled: torch.Tensor,
        mul_routed_weight=False,
        fully_sharded: bool = False,
        offset: int = 0,
        token_lora_mapping: torch.Tensor | None = None,
    ):
        """
        Performs a fused forward computation for LoRA of Mixture-of-Experts (MoE) layer.
        """
        (
            token_lora_mapping_meta,
            _,
            _,
            _,
            lora_ids,
            _,
            num_active_loras,
        ) = self.token_mapping_meta.meta_args(
            x.size(0), self.lora_config.specialize_active_lora
        )
        if token_lora_mapping is None:
            token_lora_mapping = token_lora_mapping_meta
        fused_moe_lora(
            y,
            x,
            lora_a_stacked,
            lora_b_stacked,
            topk_weights,
            sorted_token_ids,
            expert_ids,
            num_tokens_post_padded,
            token_lora_mapping,
            max_lora_rank,
            top_k_num,
            lora_ids,
            num_active_loras,
            adapter_enabled,
            shrink_config.get("BLOCK_SIZE_M", 64),
            shrink_config.get("BLOCK_SIZE_N", 64),
            shrink_config.get("BLOCK_SIZE_K", 32),
            shrink_config.get("GROUP_SIZE_M", 8),
            shrink_config.get("NUM_WARPS", 4),
            shrink_config.get("NUM_STAGES", 3),
            shrink_config.get("SPLIT_K", 1),
            expand_config.get("BLOCK_SIZE_M", 64),
            expand_config.get("BLOCK_SIZE_N", 64),
            expand_config.get("BLOCK_SIZE_K", 32),
            expand_config.get("GROUP_SIZE_M", 8),
            expand_config.get("NUM_WARPS", 4),
            expand_config.get("NUM_STAGES", 3),
            expand_config.get("SPLIT_K", 1),
            mul_routed_weight,
            fully_sharded,
            offset,
        )

    def add_lora_w13(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_a_stacked: tuple[torch.Tensor, ...],
        lora_b_stacked: tuple[torch.Tensor, ...],
        topk_ids: torch.Tensor,
        topk_weights: torch.Tensor,
        expert_map: torch.Tensor | None,
        w1: torch.Tensor,
        w2: torch.Tensor,
        num_tokens: int,
        top_k_num: int,
        max_loras: int,
        adapter_enabled: torch.Tensor,
        local_num_experts: int,
        top_k: int,
        num_slices: int,
        fully_sharded: bool,
        use_tuned_config: bool,
    ) -> tuple[
        torch.Tensor | None,
        torch.Tensor | None,
        torch.Tensor | None,
        torch.Tensor | None,
    ]:
        import functools

        from vllm.lora.layers.utils import try_get_optimal_moe_lora_config
        from vllm.lora.ops.triton_ops.utils import (
            _normalize_lora_config_keys,
            get_lora_op_configs,
        )
        from vllm.model_executor.layers.fused_moe.config import _get_config_dtype_str

        config_dtype = _get_config_dtype_str(
            dtype=x.dtype,
            use_fp8_w8a8=False,
            use_int8_w8a16=False,
            use_int4_w4a16=False,
        )
        max_lora_rank = lora_a_stacked[0].shape[-2]

        if use_tuned_config:
            shrink_config = get_lora_op_configs(
                op_type="fused_moe_lora_w13_shrink",
                max_loras=max_loras,
                batch=num_tokens,
                hidden_size=x.shape[-1],
                rank=max_lora_rank,
                num_slices=num_slices,
                moe_intermediate_size=lora_b_stacked[0].shape[-2],
            )
            expand_config = get_lora_op_configs(
                op_type="fused_moe_lora_w13_expand",
                max_loras=max_loras,
                batch=num_tokens,
                hidden_size=x.shape[-1],
                rank=max_lora_rank,
                num_slices=num_slices,
                moe_intermediate_size=lora_b_stacked[0].shape[-2],
            )
        else:
            get_config = functools.partial(
                try_get_optimal_moe_lora_config,
                w1_shape=w1.shape,
                w2_shape=w2.shape,
                rank=max_lora_rank,
                top_k=top_k,
                dtype=config_dtype,
                M=num_tokens,
            )
            shrink_config = get_config(op_type="fused_moe_lora_w13_shrink")
            expand_config = get_config(op_type="fused_moe_lora_w13_expand")

        shrink_config = _normalize_lora_config_keys(shrink_config)
        expand_config = _normalize_lora_config_keys(expand_config)

        SPARSITY_FACTOR = 8
        naive_block_assignment = (
            expert_map is None
            and num_tokens * top_k * SPARSITY_FACTOR <= local_num_experts * max_loras
        )

        (
            token_lora_mapping,
            sorted_token_ids_lora,
            expert_ids_lora,
            num_tokens_post_padded_lora,
        ) = self.moe_lora_align_block_size(
            topk_ids,
            num_tokens,
            int(shrink_config.get("BLOCK_SIZE_M") or 64),
            local_num_experts,
            max_loras,
            adapter_enabled,
            expert_map,
            naive_block_assignment=naive_block_assignment,
        )

        _sorted = sorted_token_ids_lora
        _eids = expert_ids_lora
        if _sorted is not None:
            _eids = _eids.view(max_loras, -1)
            _sorted = _sorted.view(max_loras, -1)

        self.add_lora_fused_moe(
            y.view(-1, top_k_num, y.shape[-1]),
            x,
            lora_a_stacked,
            lora_b_stacked,
            topk_weights,
            _sorted,
            _eids,
            num_tokens_post_padded_lora,
            max_lora_rank,
            top_k,
            shrink_config,
            expand_config,
            adapter_enabled,
            fully_sharded=fully_sharded,
            token_lora_mapping=token_lora_mapping,
        )

        return (
            sorted_token_ids_lora,
            expert_ids_lora,
            num_tokens_post_padded_lora,
            token_lora_mapping,
        )

    def add_lora_w2(
        self,
        y: torch.Tensor,
        x: torch.Tensor,
        lora_a_stacked: tuple[torch.Tensor, ...],
        lora_b_stacked: tuple[torch.Tensor, ...],
        topk_weights: torch.Tensor,
        sorted_token_ids_lora: torch.Tensor | None,
        expert_ids_lora: torch.Tensor | None,
        num_tokens_post_padded_lora: torch.Tensor | None,
        token_lora_mapping: torch.Tensor | None,
        num_tokens: int,
        w1: torch.Tensor,
        w2: torch.Tensor,
        top_k_num: int,
        max_loras: int,
        adapter_enabled: torch.Tensor,
        top_k: int,
        fully_sharded: bool,
        tp_rank: int,
        use_tuned_config: bool,
    ) -> None:
        import functools

        from vllm.lora.layers.utils import try_get_optimal_moe_lora_config
        from vllm.lora.ops.triton_ops.utils import (
            _normalize_lora_config_keys,
            get_lora_op_configs,
        )
        from vllm.model_executor.layers.fused_moe.config import _get_config_dtype_str

        config_dtype = _get_config_dtype_str(
            dtype=x.dtype,
            use_fp8_w8a8=False,
            use_int8_w8a16=False,
            use_int4_w4a16=False,
        )
        max_lora_rank = lora_a_stacked[0].shape[-2]

        if use_tuned_config:
            shrink_config = get_lora_op_configs(
                op_type="fused_moe_lora_w2_shrink",
                max_loras=max_loras,
                batch=num_tokens,
                hidden_size=y.shape[-1],
                rank=max_lora_rank,
                num_slices=1,
                moe_intermediate_size=lora_a_stacked[0].shape[-1],
            )
            expand_config = get_lora_op_configs(
                op_type="fused_moe_lora_w2_expand",
                max_loras=max_loras,
                batch=num_tokens,
                hidden_size=y.shape[-1],
                rank=max_lora_rank,
                num_slices=1,
                moe_intermediate_size=lora_a_stacked[0].shape[-1],
            )
        else:
            get_config = functools.partial(
                try_get_optimal_moe_lora_config,
                w1_shape=w1.shape,
                w2_shape=w2.shape,
                rank=max_lora_rank,
                top_k=top_k,
                dtype=config_dtype,
                M=num_tokens,
            )
            shrink_config = get_config(op_type="fused_moe_lora_w2_shrink")
            expand_config = get_config(op_type="fused_moe_lora_w2_expand")

        shrink_config = _normalize_lora_config_keys(shrink_config)
        expand_config = _normalize_lora_config_keys(expand_config)

        _sorted = sorted_token_ids_lora
        _eids = expert_ids_lora
        if _sorted is not None:
            assert _eids is not None
            _eids = _eids.view(max_loras, -1)
            _sorted = _sorted.view(max_loras, -1)

        # w2_lora_b shape[-2] is hidden_size // tp_size when fully_sharded
        shard_size = lora_b_stacked[0].shape[-2]
        offset = shard_size * tp_rank if fully_sharded else 0

        self.add_lora_fused_moe(
            y,
            x,
            lora_a_stacked,
            lora_b_stacked,
            topk_weights,
            _sorted,
            _eids,
            num_tokens_post_padded_lora,
            max_lora_rank,
            top_k,
            shrink_config,
            expand_config,
            adapter_enabled,
            True,  # mul_routed_weight
            fully_sharded=fully_sharded,
            offset=offset,
            token_lora_mapping=token_lora_mapping,
        )

sampler_indices_padded property

sampler_indices_padded: Tensor

This property provides access to padded sampler indices.

add_expand

add_expand(
    y: Tensor,
    x: Tensor,
    lora_b_stacked: tuple[Tensor, ...],
    output_slices: tuple[int, ...],
    offset_start: int = 0,
    add_inputs=True,
    **kwargs,
) -> None

Performs GEMM 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] offset += slice

Parameters:

Name Type Description Default
y Tensor

Output tensor.

required
x Tensor

Input tensors

required
lora_b_stacked tuple[Tensor, ...]

lora_b's weight

required
output_slices tuple[int, ...]

Every slice's size

required
add_inputs bool

Defaults to True.

True
Source code in vllm/lora/punica_wrapper/punica_xpu.py
def add_expand(
    self,
    y: torch.Tensor,
    x: torch.Tensor,
    lora_b_stacked: tuple[torch.Tensor, ...],
    output_slices: tuple[int, ...],
    offset_start: int = 0,
    add_inputs=True,
    **kwargs,
) -> None:
    """
    Performs GEMM 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]
            offset += slice

    Args:
        y (torch.Tensor): Output tensor.
        x (torch.Tensor): Input tensors
        lora_b_stacked (tuple[torch.Tensor, ...]): lora_b's weight
        output_slices (tuple[int, ...]): Every slice's size
        add_inputs (bool): Defaults to True.
    """
    y_org = y
    y = y.view(-1, y.shape[-1])

    assert x.ndim == 3
    assert x.size(0) == len(output_slices)

    # TODO fuse these kernels
    for slice_idx in range(len(lora_b_stacked)):
        self._apply_expand(
            y,
            x[slice_idx],
            lora_b_stacked[slice_idx],
            offset_start,
            output_slices[slice_idx],
            add_inputs=add_inputs,
        )
        offset_start += output_slices[slice_idx]
    y.view_as(y_org)

add_lora_embedding

add_lora_embedding(
    y: Tensor,
    x: Tensor,
    lora_b_stacked: Tensor,
    add_inputs: bool = True,
    **kwargs,
) -> None

Applies lora specifically for VocabParallelEmbeddingWithLoRA.

Semantics

y += x @ lora_b_stacked

Parameters:

Name Type Description Default
y Tensor

Output tensor.

required
x Tensor

Input tensor.

required
lora_b_stacked Tensor

lora_b's weights.

required
add_inputs bool

Default to True.

True
Source code in vllm/lora/punica_wrapper/punica_xpu.py
def add_lora_embedding(
    self,
    y: torch.Tensor,
    x: torch.Tensor,
    lora_b_stacked: torch.Tensor,
    add_inputs: bool = True,
    **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.
        add_inputs (bool): Default to True.
    """
    token_lora_indices = self._get_token_lora_indices(x)
    bgmv_expand(x, lora_b_stacked, y, token_lora_indices, add_inputs)

add_lora_fused_moe

add_lora_fused_moe(
    y: Tensor,
    x: Tensor,
    lora_a_stacked: tuple[Tensor, ...],
    lora_b_stacked: tuple[Tensor, ...],
    topk_weights: Tensor,
    sorted_token_ids: Tensor | None,
    expert_ids: Tensor,
    num_tokens_post_padded: Tensor | None,
    max_lora_rank: int,
    top_k_num: int,
    shrink_config,
    expand_config,
    adapter_enabled: Tensor,
    mul_routed_weight=False,
    fully_sharded: bool = False,
    offset: int = 0,
    token_lora_mapping: Tensor | None = None,
)

Performs a fused forward computation for LoRA of Mixture-of-Experts (MoE) layer.

Source code in vllm/lora/punica_wrapper/punica_xpu.py
def add_lora_fused_moe(
    self,
    y: torch.Tensor,
    x: torch.Tensor,
    lora_a_stacked: tuple[torch.Tensor, ...],
    lora_b_stacked: tuple[torch.Tensor, ...],
    topk_weights: torch.Tensor,
    sorted_token_ids: torch.Tensor | None,
    expert_ids: torch.Tensor,
    num_tokens_post_padded: torch.Tensor | None,
    max_lora_rank: int,
    top_k_num: int,
    shrink_config,
    expand_config,
    adapter_enabled: torch.Tensor,
    mul_routed_weight=False,
    fully_sharded: bool = False,
    offset: int = 0,
    token_lora_mapping: torch.Tensor | None = None,
):
    """
    Performs a fused forward computation for LoRA of Mixture-of-Experts (MoE) layer.
    """
    (
        token_lora_mapping_meta,
        _,
        _,
        _,
        lora_ids,
        _,
        num_active_loras,
    ) = self.token_mapping_meta.meta_args(
        x.size(0), self.lora_config.specialize_active_lora
    )
    if token_lora_mapping is None:
        token_lora_mapping = token_lora_mapping_meta
    fused_moe_lora(
        y,
        x,
        lora_a_stacked,
        lora_b_stacked,
        topk_weights,
        sorted_token_ids,
        expert_ids,
        num_tokens_post_padded,
        token_lora_mapping,
        max_lora_rank,
        top_k_num,
        lora_ids,
        num_active_loras,
        adapter_enabled,
        shrink_config.get("BLOCK_SIZE_M", 64),
        shrink_config.get("BLOCK_SIZE_N", 64),
        shrink_config.get("BLOCK_SIZE_K", 32),
        shrink_config.get("GROUP_SIZE_M", 8),
        shrink_config.get("NUM_WARPS", 4),
        shrink_config.get("NUM_STAGES", 3),
        shrink_config.get("SPLIT_K", 1),
        expand_config.get("BLOCK_SIZE_M", 64),
        expand_config.get("BLOCK_SIZE_N", 64),
        expand_config.get("BLOCK_SIZE_K", 32),
        expand_config.get("GROUP_SIZE_M", 8),
        expand_config.get("NUM_WARPS", 4),
        expand_config.get("NUM_STAGES", 3),
        expand_config.get("SPLIT_K", 1),
        mul_routed_weight,
        fully_sharded,
        offset,
    )

add_lora_linear

add_lora_linear(
    y: Tensor,
    x: Tensor,
    lora_a_stacked: tuple[Tensor, ...],
    lora_b_stacked: tuple[Tensor, ...],
    scale: float,
    output_slices: tuple[int, ...],
    *,
    buffer: Tensor | None = None,
    **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)

Parameters:

Name Type Description Default
y Tensor

Output tensor. Will be changed in-place.

required
x Tensor

Input tensor

required
lora_a_stacked tuple[Tensor, ...]

lora_a's weight.

required
lora_b_stacked tuple[Tensor, ...]

lora_b's weight.

required
scale float

Scaling factor.

required
output_slices tuple[int, ...]

Every slice's size.

required
buffer Optional[Tensor]

Defaults to None.

None
Source code in vllm/lora/punica_wrapper/punica_xpu.py
def add_lora_linear(
    self,
    y: torch.Tensor,
    x: torch.Tensor,
    lora_a_stacked: tuple[torch.Tensor, ...],
    lora_b_stacked: tuple[torch.Tensor, ...],
    scale: float,
    output_slices: tuple[int, ...],
    *,
    buffer: torch.Tensor | None = None,
    **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)

    Args:
        y (torch.Tensor): Output tensor. Will be changed in-place.
        x (torch.Tensor): Input tensor
        lora_a_stacked (tuple[torch.Tensor, ...]): lora_a's weight.
        lora_b_stacked (tuple[torch.Tensor, ...]): lora_b's weight.
        scale (float): Scaling factor.
        output_slices (tuple[int, ...]): Every slice's size.
        buffer (Optional[torch.Tensor]): Defaults to None.
    """

    assert len(lora_a_stacked) == len(lora_b_stacked) == len(output_slices)

    if buffer is None:
        r = lora_b_stacked[0].size(-1)
        buffer = torch.zeros(  # type: ignore
            (len(output_slices), x.size(0), r),
            dtype=x.dtype,
            device=x.device,
        )
    self.add_shrink(
        buffer,  # type: ignore
        x,
        lora_a_stacked,
        scale,
        **kwargs,
    )
    self.add_expand(
        y,
        buffer,  # type: ignore
        lora_b_stacked,
        output_slices,
        add_inputs=True,
        **kwargs,
    )

add_lora_logits

add_lora_logits(
    y: Tensor,
    x: Tensor,
    lora_a_stacked: Tensor,
    lora_b_stacked: Tensor,
    scale,
    *,
    buffer: Tensor | None = None,
    **kwargs,
) -> None

Applies lora specifically for LogitsProcessorWithLoRA.

Semantics

buffer = (x @ lora_a_stacked) * scale y += buffer @ lora_b_stacked

Parameters:

Name Type Description Default
y Tensor

Output tensor.

required
x Tensor

Input tensor.

required
lora_a_stacked Tensor

lora_a's weights.

required
lora_b_stacked Tensor

lora_b's weights.

required
scale float

Scaling factor.

required
buffer Optional[Tensor]

Default to None.

None
Source code in vllm/lora/punica_wrapper/punica_xpu.py
def add_lora_logits(
    self,
    y: torch.Tensor,
    x: torch.Tensor,
    lora_a_stacked: torch.Tensor,
    lora_b_stacked: torch.Tensor,
    scale,
    *,
    buffer: torch.Tensor | None = 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.
        lora_b_stacked (torch.Tensor): lora_b's weights.
        scale (float): Scaling factor.
        buffer (Optional[torch.Tensor]): Default to None.
    """
    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:
        buffer = torch.zeros((x.size(0), r), dtype=x.dtype, device=x.device)
    sampler_indices = torch.narrow(self._sampler_indices, 0, 0, x.size(0))
    bgmv_shrink(x, lora_a_stacked, buffer, sampler_indices, scale)
    bgmv_expand(buffer, lora_b_stacked, y, sampler_indices, add_inputs=True)
    return y.view_as(y_org)

add_shrink

add_shrink(
    y: Tensor,
    x: Tensor,
    lora_a_stacked: tuple[Tensor, ...],
    scale: float,
    **kwargs,
)

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

Parameters:

Name Type Description Default
y Tensor

Output tensors

required
x Tensor

Input tensor

required
lora_a_stacked tuple[Tensor, ...]

lora_a's weights

required
scale float

Scaling factor for the operation

required
Source code in vllm/lora/punica_wrapper/punica_xpu.py
def add_shrink(
    self,
    y: torch.Tensor,
    x: torch.Tensor,
    lora_a_stacked: tuple[torch.Tensor, ...],
    scale: float,
    **kwargs,
):
    """
    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:
        y (torch.Tensor): Output tensors
        x (torch.Tensor): Input tensor
        lora_a_stacked (tuple[torch.Tensor, ...]): lora_a's weights
        scale (float): Scaling factor for the operation
    """

    x = x.view(-1, x.shape[-1])
    for slice_idx in range(len(lora_a_stacked)):
        self._apply_shrink(y[slice_idx], x, lora_a_stacked[slice_idx], scale)

moe_lora_align_block_size

moe_lora_align_block_size(
    topk_ids: Tensor,
    num_tokens: int,
    block_size: int,
    num_experts: int,
    max_loras: int,
    adapter_enabled: Tensor,
    expert_map: Tensor | None = None,
    pad_sorted_ids: bool = False,
    naive_block_assignment: bool = False,
) -> tuple[Tensor, Tensor, Tensor, Tensor]

Aligns tokens and experts into block-sized chunks for LoRA-based mixture-of-experts (MoE) execution.

Source code in vllm/lora/punica_wrapper/punica_xpu.py
def moe_lora_align_block_size(
    self,
    topk_ids: torch.Tensor,
    num_tokens: int,
    block_size: int,
    num_experts: int,
    max_loras: int,
    adapter_enabled: torch.Tensor,
    expert_map: torch.Tensor | None = None,
    pad_sorted_ids: bool = False,
    naive_block_assignment: bool = False,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """
    Aligns tokens and experts into block-sized chunks for LoRA-based
    mixture-of-experts (MoE) execution.
    """
    (token_lora_mapping, _, _, _, lora_ids, _, _) = (
        self.token_mapping_meta.meta_args(
            num_tokens, self.lora_config.specialize_active_lora
        )
    )
    if naive_block_assignment:
        expert_ids = topk_ids.reshape(-1)
        sorted_ids = None
        num_tokens_post_pad = None
    else:
        max_num_tokens_padded = topk_ids.numel() + num_experts * (block_size - 1)
        if pad_sorted_ids:
            max_num_tokens_padded = round_up(max_num_tokens_padded, block_size)
        sorted_ids = torch.empty(
            (max_loras * max_num_tokens_padded,),
            dtype=torch.int32,
            device=topk_ids.device,
        )
        max_num_m_blocks = triton.cdiv(max_num_tokens_padded, block_size)
        # Expert ids must be set default to -1 to prevent a blank block
        expert_ids = torch.empty(
            (max_loras * max_num_m_blocks,),
            dtype=torch.int32,
            device=topk_ids.device,
        )
        num_tokens_post_pad = torch.empty(
            (max_loras), dtype=torch.int32, device=topk_ids.device
        )

        ops.moe_lora_align_block_size(
            topk_ids,
            token_lora_mapping,
            num_experts,
            block_size,
            max_loras,
            max_num_tokens_padded,
            max_num_m_blocks,
            sorted_ids,
            expert_ids,
            num_tokens_post_pad,
            adapter_enabled,
            lora_ids,
        )
        if expert_map is not None:
            expert_ids = expert_map[expert_ids]

    return None, sorted_ids, expert_ids, num_tokens_post_pad