bitsandbytes.py 20.7 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
from typing import Any, Union
5
6

import torch
7
from packaging import version
8

9
10
11
12
from vllm.model_executor.layers.fused_moe.config import (
    FusedMoEConfig,
    FusedMoEQuantConfig,
)
13
14
15
16
17
from vllm.model_executor.layers.fused_moe.fused_moe_router import FusedMoERouter
from vllm.model_executor.layers.fused_moe.layer import (
    FusedMoE,
    FusedMoEMethodBase,
)
18
19
20
21
22
23
24
25
26
27
from vllm.model_executor.layers.linear import (
    LinearBase,
    LinearMethodBase,
    UnquantizedLinearMethod,
    set_weight_attrs,
)
from vllm.model_executor.layers.quantization import (
    QuantizationConfig,
    QuantizationMethods,
)
28
from vllm.platforms import current_platform
29
from vllm.utils.torch_utils import direct_register_custom_op
30
31
32
33
34
35
36
37


class BitsAndBytesConfig(QuantizationConfig):
    """Config class for BitsAndBytes Quantization.

    Reference: https://arxiv.org/abs/2305.14314
    """

38
39
40
41
42
    def __init__(
        self,
        load_in_8bit: bool = False,
        load_in_4bit: bool = True,
        bnb_4bit_compute_dtype: str = "float32",
43
        bnb_4bit_quant_storage: str = "uint8",
44
45
46
47
        bnb_4bit_quant_type: str = "fp4",
        bnb_4bit_use_double_quant: bool = False,
        llm_int8_enable_fp32_cpu_offload: bool = False,
        llm_int8_has_fp16_weight: bool = False,
48
        llm_int8_skip_modules: list[str] | None = None,
49
        llm_int8_threshold: float = 6.0,
50
    ) -> None:
51
        super().__init__()
52
53
54
        self.load_in_8bit = load_in_8bit
        self.load_in_4bit = load_in_4bit
        self.bnb_4bit_compute_dtype = bnb_4bit_compute_dtype
55
        self.bnb_4bit_quant_storage = bnb_4bit_quant_storage
56
57
58
59
        self.bnb_4bit_quant_type = bnb_4bit_quant_type
        self.bnb_4bit_use_double_quant = bnb_4bit_use_double_quant
        self.llm_int8_enable_fp32_cpu_offload = llm_int8_enable_fp32_cpu_offload
        self.llm_int8_has_fp16_weight = llm_int8_has_fp16_weight
60
        self.llm_int8_skip_modules = llm_int8_skip_modules or []
61
        self.llm_int8_threshold = llm_int8_threshold
62

63
        if self.bnb_4bit_quant_storage not in ["uint8"]:
64
65
66
            raise ValueError(
                f"Unsupported bnb_4bit_quant_storage: {self.bnb_4bit_quant_storage}"
            )
67

68
    def __repr__(self) -> str:
69
70
71
72
73
74
75
76
        return (
            f"BitsAndBytesConfig(load_in_8bit={self.load_in_8bit}, "
            f"load_in_4bit={self.load_in_4bit}, "
            f"bnb_4bit_compute_dtype={self.bnb_4bit_compute_dtype}, "
            f"bnb_4bit_quant_storage={self.bnb_4bit_quant_storage}, "
            f"bnb_4bit_quant_type={self.bnb_4bit_quant_type}, "
            f"llm_int8_skip_modules={self.llm_int8_skip_modules})"
        )
77
78

    @classmethod
79
    def get_name(self) -> QuantizationMethods:
80
81
82
        return "bitsandbytes"

    @classmethod
83
    def get_supported_act_dtypes(self) -> list[torch.dtype]:
84
85
86
        return [torch.float32, torch.float16, torch.bfloat16]

    @classmethod
87
    def get_min_capability(cls) -> int:
88
89
90
        return 70

    @staticmethod
91
    def get_config_filenames() -> list[str]:
92
        return []
93
94

    @classmethod
95
    def from_config(cls, config: dict[str, Any]) -> "BitsAndBytesConfig":
96
97
98
99
100
101
102
        def get_safe_value(config, keys, default_value=None):
            try:
                value = cls.get_from_keys(config, keys)
                return value if value is not None else default_value
            except ValueError:
                return default_value

103
104
105
106
107
108
109
110
111
112
113
        load_in_8bit = get_safe_value(config, ["load_in_8bit"], default_value=False)
        load_in_4bit = get_safe_value(config, ["load_in_4bit"], default_value=True)
        bnb_4bit_compute_dtype = get_safe_value(
            config, ["bnb_4bit_compute_dtype"], default_value="float32"
        )
        bnb_4bit_quant_storage = get_safe_value(
            config, ["bnb_4bit_quant_storage"], default_value="uint8"
        )
        bnb_4bit_quant_type = get_safe_value(
            config, ["bnb_4bit_quant_type"], default_value="fp4"
        )
114
        bnb_4bit_use_double_quant = get_safe_value(
115
116
            config, ["bnb_4bit_use_double_quant"], default_value=False
        )
117
        llm_int8_enable_fp32_cpu_offload = get_safe_value(
118
119
120
121
122
123
124
125
126
127
128
            config, ["llm_int8_enable_fp32_cpu_offload"], default_value=False
        )
        llm_int8_has_fp16_weight = get_safe_value(
            config, ["llm_int8_has_fp16_weight"], default_value=False
        )
        llm_int8_skip_modules = get_safe_value(
            config, ["llm_int8_skip_modules"], default_value=[]
        )
        llm_int8_threshold = get_safe_value(
            config, ["llm_int8_threshold"], default_value=6.0
        )
129
130
131
132
133

        return cls(
            load_in_8bit=load_in_8bit,
            load_in_4bit=load_in_4bit,
            bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
134
            bnb_4bit_quant_storage=bnb_4bit_quant_storage,
135
136
137
138
139
            bnb_4bit_quant_type=bnb_4bit_quant_type,
            bnb_4bit_use_double_quant=bnb_4bit_use_double_quant,
            llm_int8_enable_fp32_cpu_offload=llm_int8_enable_fp32_cpu_offload,
            llm_int8_has_fp16_weight=llm_int8_has_fp16_weight,
            llm_int8_skip_modules=llm_int8_skip_modules,
140
141
            llm_int8_threshold=llm_int8_threshold,
        )
142

143
144
    def get_quant_method(
        self, layer: torch.nn.Module, prefix: str
145
    ) -> Union["LinearMethodBase", "BitsAndBytesMoEMethod"] | None:
146
        if isinstance(layer, LinearBase):
147
148
            if is_layer_skipped_bnb(prefix, self.llm_int8_skip_modules):
                return UnquantizedLinearMethod()
149
            return BitsAndBytesLinearMethod(self)
150
        elif isinstance(layer, FusedMoE):
151
            return BitsAndBytesMoEMethod(self, layer.moe_config)
152
153
154
        return None


155
def is_layer_skipped_bnb(prefix: str, llm_int8_skip_modules: list[str]):
156
    # Split the prefix into its dot-separated components
157
    components = prefix.split(".")
158
159

    # Check if any of the skip modules exactly matches any component
160
161
162
    substr_check = any(
        module_name in components for module_name in llm_int8_skip_modules
    )
163
164

    # Allow certain layers to not be quantized
165
    set_components = set(".".join(components[: i + 1]) for i in range(len(components)))
166
167
168
169
    set_llm_int8_skip_modules = set(llm_int8_skip_modules)
    prefix_check = len(set_llm_int8_skip_modules & set_components) != 0

    return substr_check or prefix_check
170
171


172
173
174
175
176
177
178
def calculate_quant_ratio(dtype):
    if dtype.is_floating_point:
        return torch.finfo(dtype).bits // torch.iinfo(torch.uint8).bits
    else:
        return torch.iinfo(dtype).bits // torch.iinfo(torch.uint8).bits


179
180
181
182
183
184
185
186
187
188
class BitsAndBytesLinearMethod(LinearMethodBase):
    """Linear method for BitsAndBytes.

    Args:
       quant_config: The BitsAndBytes quantization config.
    """

    def __init__(self, quant_config: BitsAndBytesConfig):
        try:
            import bitsandbytes
189
190
191
192
193
194

            if version.parse(bitsandbytes.__version__) < version.parse("0.46.1"):
                raise ImportError(
                    "bitsandbytes version is wrong. Please "
                    "install bitsandbytes>=0.46.1."
                )
195
        except ImportError as err:
196
197
198
199
200
            raise ImportError(
                "Please install bitsandbytes>=0.46.1 via "
                "`pip install bitsandbytes>=0.46.1` to use "
                "bitsandbytes quantizer."
            ) from err
201
202
203

        self.quant_config = quant_config

204
205
206
207
208
209
210
211
212
213
    def create_weights(
        self,
        layer: torch.nn.Module,
        input_size_per_partition: int,
        output_partition_sizes: list[int],
        input_size: int,
        output_size: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
214
215
216
217
        from bitsandbytes.nn import Int8Params

        def create_qweight_for_8bit():
            qweight = Int8Params(
218
219
220
221
222
                data=torch.empty(
                    sum(output_partition_sizes),
                    input_size_per_partition,
                    dtype=torch.int8,
                ),
223
                has_fp16_weights=self.quant_config.llm_int8_has_fp16_weight,
224
225
                requires_grad=False,
            )
226
            set_weight_attrs(
227
228
                qweight,
                {
229
230
231
232
                    "input_dim": 0,
                    "output_dim": 0,
                    "pack_factor": 1,
                    "use_bitsandbytes_8bit": True,
233
234
235
                    "generation": 0,
                },
            )
236
237
238
239
240
241
242
243
            return qweight

        def create_qweight_for_4bit():
            quant_ratio = calculate_quant_ratio(params_dtype)

            total_size = input_size_per_partition * sum(output_partition_sizes)
            if total_size % quant_ratio != 0:
                raise ValueError(
244
245
                    "The input size is not aligned with the quantized weight shape."
                )
246

247
248
249
250
            qweight = torch.nn.Parameter(
                torch.empty(total_size // quant_ratio, 1, dtype=torch.uint8),
                requires_grad=False,
            )
251
            set_weight_attrs(
252
253
                qweight,
                {
254
255
256
                    "input_dim": 0,
                    "output_dim": 0,
                    "pack_factor": quant_ratio,
257
258
259
                    "use_bitsandbytes_4bit": True,
                },
            )
260
261
262
263
            return qweight

        if self.quant_config.load_in_8bit:
            qweight = create_qweight_for_8bit()
264
        else:
265
            qweight = create_qweight_for_4bit()
266
267
268
        # Enable parameters to have the same name as in the BNB
        # checkpoint format.
        layer.register_parameter("weight", qweight)
269
270
        set_weight_attrs(qweight, extra_weight_attrs)

271
272
273
274
    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
275
        bias: torch.Tensor | None = None,
276
    ) -> torch.Tensor:
277
278
279
280
281
282
        if self.quant_config.load_in_8bit:
            return self._apply_8bit_weight(layer, x, bias)
        else:
            return self._apply_4bit_weight(layer, x, bias)

    def _apply_8bit_weight(
283
284
285
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
286
        bias: torch.Tensor | None = None,
287
    ) -> torch.Tensor:
288
289
290
291
        # only load the bitsandbytes module when needed
        from bitsandbytes import MatmulLtState, matmul

        original_type = x.dtype
292
293
294
295
296
        original_shape = x.shape
        reshape_after_matmul = False
        if x.ndim > 2:
            x = x.reshape(-1, x.size(-1))
            reshape_after_matmul = True
297
298
        bf_x = x.to(torch.bfloat16)

299
        qweight = layer.weight
300
301
302
303
304
305
306
        offsets = qweight.bnb_shard_offsets
        quant_states = qweight.bnb_quant_state
        matmul_states = qweight.matmul_state
        generation = qweight.generation

        out_dim_0 = x.shape[0]
        out_dim_1 = sum(
307
308
309
            [quant_state[1].shape[0] for quant_state in quant_states.items()]
        )
        out = torch.empty(out_dim_0, out_dim_1, dtype=torch.float16, device=x.device)
310
311
312
313
314
315
316
317
318

        current_index = 0
        for i in range(len(quant_states)):
            output_size = quant_states[i].shape[0]

            # in profile_run or the first generation of inference,
            # create new matmul_states
            if generation == 0 or generation == 1:
                matmul_states[i] = MatmulLtState()
319
                matmul_states[i].CB = qweight[offsets[i] : offsets[i + 1]]
320
                matmul_states[i].SCB = quant_states[i].to(x.device)
321
322
323
324
                matmul_states[i].threshold = self.quant_config.llm_int8_threshold
                matmul_states[
                    i
                ].has_fp16_weights = self.quant_config.llm_int8_has_fp16_weight
325
                matmul_states[i].is_training = False
326
327
328
329
                if (
                    matmul_states[i].threshold > 0.0
                    and not matmul_states[i].has_fp16_weights
                ):
330
331
332
333
                    matmul_states[i].use_pool = True

            new_x = bf_x.unsqueeze(0)

334
335
336
            out[:, current_index : current_index + output_size] = matmul(
                new_x, qweight[offsets[i] : offsets[i + 1]], state=matmul_states[i]
            )
337
338
339
340

            current_index += output_size

            # only update the matmul_states if it is not profile_run
341
342
343
344
345
346
            if (
                generation > 0
                and not self.quant_config.llm_int8_has_fp16_weight
                and matmul_states[i].CB is not None
                and matmul_states[i].CxB is not None
            ):
347
                del matmul_states[i].CB
348
                qweight[offsets[i] : offsets[i + 1]] = matmul_states[i].CxB
349
350
351

        out = out.to(original_type)

352
353
354
        if reshape_after_matmul:
            out = out.view(*original_shape[:-1], out.size(-1))

355
356
357
358
359
360
361
362
        if bias is not None:
            out += bias

        qweight.generation += 1

        return out

    def _apply_4bit_weight(
363
364
365
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
366
        bias: torch.Tensor | None = None,
367
    ) -> torch.Tensor:
368
        original_type = x.dtype
369
370
371
372
373
        original_shape = x.shape
        reshape_after_matmul = False
        if x.ndim > 2:
            x = x.reshape(-1, x.size(-1))
            reshape_after_matmul = True
374
375
        bf_x = x.to(torch.bfloat16)

376
        qweight = layer.weight
377
378
379
380
381
        quant_states = qweight.bnb_quant_state
        offsets = qweight.bnb_shard_offsets

        out_dim_0 = x.shape[0]
        out_dim_1 = sum(
382
383
384
            [quant_state[1].shape[0] for quant_state in quant_states.items()]
        )
        out = torch.empty(out_dim_0, out_dim_1, dtype=torch.bfloat16, device=x.device)
385
        apply_bnb_4bit(bf_x, qweight, offsets, out)
386
387
        out = out.to(original_type)

388
389
390
        if reshape_after_matmul:
            out = out.view(*original_shape[:-1], out.size(-1))

391
392
393
394
        if bias is not None:
            out += bias

        return out
395
396
397
398
399
400
401
402
403
404


def _apply_bnb_4bit(
    x: torch.Tensor,
    weight: torch.Tensor,
    offsets: torch.Tensor,
    out: torch.Tensor,
) -> None:
    # only load the bitsandbytes module when needed
    from bitsandbytes import matmul_4bit
405

406
407
408
409
410
411
412
413
    quant_states = weight.bnb_quant_state
    current_index = 0
    for i in range(len(quant_states)):
        output_size = quant_states[i].shape[0]
        # It is more efficient to use out kwarg like
        # matmul_4bit(..., out = ...).  Infeasible now due to the bug
        # https://github.com/TimDettmers/bitsandbytes/issues/1235.
        # Need to change  after the bug is fixed.
414
415
416
        out[:, current_index : current_index + output_size] = matmul_4bit(
            x, weight[offsets[i] : offsets[i + 1]].t(), quant_states[i]
        )
417
418
419
420
421
422
423
424
425
426
427
428
429
        current_index += output_size


def _apply_bnb_4bit_fake(
    x: torch.Tensor,
    weight: torch.Tensor,
    offsets: torch.Tensor,
    out: torch.Tensor,
) -> None:
    return


try:
430
431
432
433
434
435
436
    direct_register_custom_op(
        op_name="apply_bnb_4bit",
        op_func=_apply_bnb_4bit,
        mutates_args=["out"],
        fake_impl=_apply_bnb_4bit_fake,
        dispatch_key=current_platform.dispatch_key,
    )
437
438
439
440
    apply_bnb_4bit = torch.ops.vllm.apply_bnb_4bit

except AttributeError as error:
    raise error
441
442
443
444
445
446
447
448
449


class BitsAndBytesMoEMethod(FusedMoEMethodBase):
    """MoE method for BitsAndBytes.

    Args:
       quant_config: The BitsAndBytes quantization config.
    """

450
451
452
453
454
455
    def __init__(
        self,
        quant_config: BitsAndBytesConfig,
        moe: FusedMoEConfig,
    ):
        super().__init__(moe)
456
457
        try:
            import bitsandbytes
458
459
460
461
462
463

            if version.parse(bitsandbytes.__version__) < version.parse("0.46.1"):
                raise ImportError(
                    "bitsandbytes version is wrong. Please "
                    "install bitsandbytes>=0.46.1."
                )
464
        except ImportError as err:
465
466
467
468
469
            raise ImportError(
                "Please install bitsandbytes>=0.46.1 via "
                "`pip install bitsandbytes>=0.46.1` to use "
                "bitsandbytes quantizer."
            ) from err
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
        self.quant_config = quant_config

    def create_weights(
        self,
        layer: torch.nn.Module,
        num_experts: int,
        hidden_size: int,
        intermediate_size_per_partition: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
        if self.quant_config.load_in_8bit:
            call_fun = self._create_weights_8bit
        else:
            call_fun = self._create_weights_4bit
        call_fun(
            layer,
            num_experts,
            hidden_size,
            intermediate_size_per_partition,
            params_dtype,
            **extra_weight_attrs,
        )

494
    def get_fused_moe_quant_config(
495
        self, layer: torch.nn.Module
496
    ) -> FusedMoEQuantConfig | None:
497
498
        return None

499
500
    def apply(
        self,
501
        layer: FusedMoE,
502
        router: FusedMoERouter,
503
504
        x: torch.Tensor,
        router_logits: torch.Tensor,
505
    ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
506
        from vllm.model_executor.layers.fused_moe import fused_experts
507

508
        topk_weights, topk_ids = router.select_experts(
509
510
            hidden_states=x,
            router_logits=router_logits,
511
        )
512
        # TODO(bnell): Do these need to be called on the hot path?
513
514
515
516
517
518
519
520
521
522
523
        if self.quant_config.load_in_8bit:
            w13, w2 = self._apply_8bit_dequant(layer)
        else:
            w13, w2 = self._apply_4bit_dequnt(layer)
        return fused_experts(
            hidden_states=x,
            w1=w13,
            w2=w2,
            topk_weights=topk_weights,
            topk_ids=topk_ids,
            inplace=True,
524
525
526
527
            activation=layer.activation,
            apply_router_weight_on_input=layer.apply_router_weight_on_input,
            global_num_experts=layer.global_num_experts,
            expert_map=layer.expert_map,
528
            quant_config=self.moe_quant_config,
529
530
531
532
533
534
535
536
537
538
539
540
541
        )

    def _create_weights_4bit(
        self,
        layer: torch.nn.Module,
        num_experts: int,
        hidden_size: int,
        intermediate_size_per_partition: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
        quant_ratio = calculate_quant_ratio(params_dtype)
        # Fused gate_up_proj (column parallel)
542
543
544
        w13_total_size = (
            hidden_size * 2 * intermediate_size_per_partition
        ) // quant_ratio
545
546
547
548
549
550
551
552
553
554
555
556
557
558
        w13_qweight = torch.nn.Parameter(
            torch.empty(
                num_experts,
                w13_total_size,
                1,
                dtype=torch.uint8,
            ),
            requires_grad=False,
        )
        layer.register_parameter("w13_weight", w13_qweight)
        set_weight_attrs(w13_qweight, extra_weight_attrs)
        set_weight_attrs(
            w13_qweight,
            {
559
560
561
                "num_experts": num_experts,
                "input_dim": hidden_size,
                "output_dim": 2 * intermediate_size_per_partition,
562
563
564
565
566
                "experts_shape": (
                    num_experts,
                    intermediate_size_per_partition * 2,
                    hidden_size,
                ),
567
568
                "pack_factor": quant_ratio,
                "use_bitsandbytes_4bit": True,
569
570
571
            },
        )
        # down_proj (row parallel)
572
        w2_total_size = (hidden_size * intermediate_size_per_partition) // quant_ratio
573
574
575
576
577
578
579
580
581
582
583
584
        w2_qweight = torch.nn.Parameter(
            torch.empty(
                num_experts,
                w2_total_size,
                1,
                dtype=torch.uint8,
            ),
            requires_grad=False,
        )
        set_weight_attrs(
            w2_qweight,
            {
585
586
587
                "num_experts": num_experts,
                "input_dim": intermediate_size_per_partition,
                "output_dim": hidden_size,
588
589
590
591
592
                "experts_shape": (
                    num_experts,
                    hidden_size,
                    intermediate_size_per_partition,
                ),
593
594
                "pack_factor": quant_ratio,
                "use_bitsandbytes_4bit": True,
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
            },
        )
        layer.register_parameter("w2_weight", w2_qweight)
        set_weight_attrs(w2_qweight, extra_weight_attrs)

    def _create_weights_8bit(
        self,
        layer: torch.nn.Module,
        num_experts: int,
        hidden_size: int,
        intermediate_size_per_partition: int,
        params_dtype: torch.dtype,
        **extra_weight_attrs,
    ):
        raise NotImplementedError

    def _apply_4bit_dequnt(
612
613
        self, layer: torch.nn.Module
    ) -> tuple[torch.Tensor, torch.Tensor]:
614
        from bitsandbytes.functional import dequantize_4bit
615

616
617
618
619
620
621
622
623
624
625
626
627
628
        w13 = dequantize_4bit(
            layer.w13_weight.reshape(-1, 1),
            layer.w13_weight.bnb_quant_state,
        )
        w2 = dequantize_4bit(
            layer.w2_weight.reshape(-1, 1),
            layer.w2_weight.bnb_quant_state,
        )
        w13 = w13.reshape(layer.w13_weight.experts_shape)
        w2 = w2.reshape(layer.w2_weight.experts_shape)
        return w13, w2

    def _apply_8bit_dequant(
629
630
        self, layer: torch.nn.Module
    ) -> tuple[torch.Tensor, torch.Tensor]:
631
        raise NotImplementedError