squeezellm.py 4.49 KB
Newer Older
1
2
3
4
5
from typing import Any, Dict, List, Optional

import torch
from torch.nn.parameter import Parameter

6
from vllm import _custom_ops as ops
7
from vllm.model_executor.layers.linear import LinearBase
8
from vllm.model_executor.layers.quantization.base_config import (
9
10
    QuantizationConfig, QuantizeMethodBase)
from vllm.model_executor.utils import set_weight_attrs
11
from vllm.utils import is_hip
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41


class SqueezeLLMConfig(QuantizationConfig):
    """Config class for SqueezeLLM.

    Reference: https://arxiv.org/pdf/2306.07629
    """

    def __init__(
        self,
        weight_bits: int,
    ) -> None:
        self.weight_bits = weight_bits

        if self.weight_bits != 4:
            raise ValueError(
                "Currently, only 4-bit weight quantization is supported for "
                f"SqueezeLLM, but got {self.weight_bits} bits.")

        self.pack_factor = 32 // self.weight_bits

    def __repr__(self) -> str:
        return f"SqueezeLLMConfig(weight_bits={self.weight_bits})"

    def get_name(self) -> str:
        return "squeezellm"

    def get_supported_act_dtypes(self) -> List[torch.dtype]:
        return [torch.half]

42
43
    @classmethod
    def get_min_capability(cls) -> int:
44
45
46
47
48
49
50
51
52
53
54
        return 70

    @staticmethod
    def get_config_filenames() -> List[str]:
        return ["quant_config.json"]

    @classmethod
    def from_config(cls, config: Dict[str, Any]) -> "SqueezeLLMConfig":
        weight_bits = cls.get_from_keys(config, ["wbits"])
        return cls(weight_bits)

55
56
    def get_quant_method(self, layer: torch.nn.Module,
                         prefix: str) -> Optional[QuantizeMethodBase]:
57
58
        if isinstance(layer, LinearBase):
            return SqueezeLLMLinearMethod(self)
59
        return None
60

61
62
63
    def get_scaled_act_names(self) -> List[str]:
        return []

64

65
class SqueezeLLMLinearMethod(QuantizeMethodBase):
66
67
68
69
70
71
72
73
74
    """Linear method for SqueezeLLM.

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

    def __init__(self, quant_config: SqueezeLLMConfig):
        self.quant_config = quant_config

75
76
    def create_weights(self, layer: torch.nn.Module,
                       input_size_per_partition: int,
James Fleming's avatar
James Fleming committed
77
                       output_partition_sizes: List[int], input_size: int,
78
79
                       output_size: int, params_dtype: torch.dtype,
                       **extra_weight_attrs):
CHU Tianxiang's avatar
CHU Tianxiang committed
80
        if input_size_per_partition % self.quant_config.pack_factor != 0:
81
82
83
84
            raise ValueError(
                "The input size is not aligned with the quantized "
                "weight shape. This can be caused by too large "
                "tensor parallel size.")
James Fleming's avatar
James Fleming committed
85
86

        output_size_per_partition = sum(output_partition_sizes)
87
88
        qweight = Parameter(
            torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
89
90
                input_size_per_partition // self.quant_config.pack_factor,
                output_size_per_partition,
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
                dtype=torch.int32,
            ),
            requires_grad=False,
        )
        set_weight_attrs(
            qweight, {
                "input_dim": 0,
                "output_dim": 1,
                "packed_dim": 0,
                "pack_factor": self.quant_config.pack_factor,
            })
        lookup_table = Parameter(
            torch.empty(
                output_size,
                self.quant_config.weight_bits**2,
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        set_weight_attrs(lookup_table, {
            "output_dim": 0,
        })
113
114
115
116
117

        layer.register_parameter("qweight", qweight)
        set_weight_attrs(qweight, extra_weight_attrs)
        layer.register_parameter("lookup_table", lookup_table)
        set_weight_attrs(lookup_table, extra_weight_attrs)
118

119
120
121
122
    def apply(self,
              layer: torch.nn.Module,
              x: torch.Tensor,
              bias: Optional[torch.Tensor] = None) -> torch.Tensor:
123
124
        qweight = layer.qweight
        lookup_table = layer.lookup_table
125
126
        out_shape = x.shape[:-1] + (qweight.shape[-1], )
        reshaped_x = x.reshape(-1, x.shape[-1])
127
        if is_hip():
128
            out_f = torch.zeros(out_shape, dtype=torch.float)
129
130
131
132
            ops.squeezellm_gemm(reshaped_x, qweight, out_f, lookup_table)
            out = out_f.to(dtype=torch.float16)
        else:
            # NOTE: The output tensor should be zero-initialized.
133
            out = torch.zeros(out_shape, dtype=torch.float16)
134
            ops.squeezellm_gemm(reshaped_x, qweight, out, lookup_table)
135
136

        if bias is not None:
137
            out.add_(bias)
138
        return out.reshape(out_shape)