"tests/vscode:/vscode.git/clone" did not exist on "c4dd1fd4a3ed37c1a6c67ecb9572b5123c2a1fec"
awq.py 7.12 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
from typing import Any, Optional
4
5
6

import torch

7
from vllm import _custom_ops as ops
8
9
from vllm.model_executor.layers.linear import (LinearBase, LinearMethodBase,
                                               UnquantizedLinearMethod)
10
from vllm.model_executor.layers.quantization import QuantizationMethods
11
12
from vllm.model_executor.layers.quantization.base_config import (
    QuantizationConfig)
13
14
from vllm.model_executor.parameter import (GroupQuantScaleParameter,
                                           PackedvLLMParameter)
15
16
17
18
19
20
21
22
23
24
25
26
27


class AWQConfig(QuantizationConfig):
    """Config class for AWQ.

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

    def __init__(
        self,
        weight_bits: int,
        group_size: int,
        zero_point: bool,
28
        modules_to_not_convert: Optional[list[str]] = None,
29
    ) -> None:
30
        super().__init__()
31
32
33
        self.weight_bits = weight_bits
        self.group_size = group_size
        self.zero_point = zero_point
34
        self.modules_to_not_convert = modules_to_not_convert or []
35
36
37
38
39
40
41
42
43
44

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

    def __repr__(self) -> str:
        return (f"AWQConfig(weight_bits={self.weight_bits}, "
                f"group_size={self.group_size}, "
45
46
                f"zero_point={self.zero_point}, "
                f"modules_to_not_convert={self.modules_to_not_convert})")
47

48
    def get_name(self) -> QuantizationMethods:
49
50
        return "awq"

51
    def get_supported_act_dtypes(self) -> list[torch.dtype]:
52
53
        return [torch.half]

54
55
    @classmethod
    def get_min_capability(cls) -> int:
56
57
58
59
        # The AWQ kernel only supports Turing or newer GPUs.
        return 75

    @staticmethod
60
    def get_config_filenames() -> list[str]:
61
62
        return [
            "quant_config.json",  # E.g., casperhansen/vicuna-7b-v1.5-awq
63
64
            # E.g., abhinavkulkarni/mosaicml-mpt-7b-instruct-w4-g128-awq
            "quantize_config.json",
65
66
67
        ]

    @classmethod
68
    def from_config(cls, config: dict[str, Any]) -> "AWQConfig":
69
70
71
        weight_bits = cls.get_from_keys(config, ["w_bit", "bits"])
        group_size = cls.get_from_keys(config, ["q_group_size", "group_size"])
        zero_point = cls.get_from_keys(config, ["zero_point"])
72
73
74
        modules_to_not_convert = cls.get_from_keys_or(
            config, ["modules_to_not_convert"], None)
        return cls(weight_bits, group_size, zero_point, modules_to_not_convert)
75

76
    def get_quant_method(self, layer: torch.nn.Module,
77
                         prefix: str) -> Optional["LinearMethodBase"]:
78
        if isinstance(layer, LinearBase):
79
80
            if is_layer_skipped_awq(prefix, self.modules_to_not_convert):
                return UnquantizedLinearMethod()
81
82
            return AWQLinearMethod(self)
        return None
83
84


85
def is_layer_skipped_awq(prefix: str, modules_to_not_convert: list[str]):
86
87
88
    return any(module_name in prefix for module_name in modules_to_not_convert)


89
90
91
92
93
94
95
96
97
98
class AWQLinearMethod(LinearMethodBase):
    """Linear method for AWQ.

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

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

99
100
    def create_weights(self, layer: torch.nn.Module,
                       input_size_per_partition: int,
101
                       output_partition_sizes: list[int], input_size: int,
102
103
                       output_size: int, params_dtype: torch.dtype,
                       **extra_weight_attrs):
104
105
106
107
108
109
110
        # Normalize group_size
        if self.quant_config.group_size != -1:
            group_size = self.quant_config.group_size
        else:
            group_size = input_size

        if input_size_per_partition % group_size != 0:
111
112
113
114
            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
115
116

        output_size_per_partition = sum(output_partition_sizes)
CHU Tianxiang's avatar
CHU Tianxiang committed
117
        if output_size_per_partition % self.quant_config.pack_factor != 0:
118
119
120
121
122
            raise ValueError(
                "The output size is not aligned with the quantized "
                "weight shape. This can be caused by too large "
                "tensor parallel size.")

123
124
125
        weight_loader = extra_weight_attrs.get("weight_loader")
        qweight = PackedvLLMParameter(
            data=torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
126
127
                input_size_per_partition,
                output_size_per_partition // self.quant_config.pack_factor,
128
129
                dtype=torch.int32,
            ),
130
131
132
133
134
135
            input_dim=0,
            output_dim=1,
            packed_dim=1,
            packed_factor=self.quant_config.pack_factor,
            weight_loader=weight_loader)

136
137
        num_groups = input_size_per_partition // group_size

138
139
        qzeros = PackedvLLMParameter(
            data=torch.empty(
140
                num_groups,
CHU Tianxiang's avatar
CHU Tianxiang committed
141
                output_size_per_partition // self.quant_config.pack_factor,
142
143
                dtype=torch.int32,
            ),
144
145
146
147
148
149
150
            input_dim=0,
            output_dim=1,
            packed_dim=1,
            packed_factor=self.quant_config.pack_factor,
            weight_loader=weight_loader)

        scales = GroupQuantScaleParameter(data=torch.empty(
151
            num_groups,
152
153
154
155
156
157
            output_size_per_partition,
            dtype=params_dtype,
        ),
                                          input_dim=0,
                                          output_dim=1,
                                          weight_loader=weight_loader)
158
159
160
161

        layer.register_parameter("qweight", qweight)
        layer.register_parameter("qzeros", qzeros)
        layer.register_parameter("scales", scales)
162
163
164
165
166
167
168
169

    def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
        layer.qweight = torch.nn.Parameter(layer.qweight.data,
                                           requires_grad=False)
        layer.qzeros = torch.nn.Parameter(layer.qzeros.data,
                                          requires_grad=False)
        layer.scales = torch.nn.Parameter(layer.scales.data,
                                          requires_grad=False)
170

171
172
173
174
    def apply(self,
              layer: torch.nn.Module,
              x: torch.Tensor,
              bias: Optional[torch.Tensor] = None) -> torch.Tensor:
175
176
177
        qweight = layer.qweight
        scales = layer.scales
        qzeros = layer.qzeros
178
179
180
        pack_factor = self.quant_config.pack_factor
        out_shape = (x.shape[:-1] + (qweight.shape[-1] * pack_factor, ))
        reshaped_x = x.reshape(-1, x.shape[-1])
181
182
183
184
185
186
187
188
189
190

        # num_tokens >= threshold
        FP16_MATMUL_HEURISTIC_CONDITION = x.shape[:-1].numel() >= 256

        if FP16_MATMUL_HEURISTIC_CONDITION:
            out = ops.awq_dequantize(qweight, scales, qzeros, 0, 0, 0)
            out = torch.matmul(reshaped_x, out)
        else:
            out = ops.awq_gemm(reshaped_x, qweight, scales, qzeros,
                               pack_factor)
191
        if bias is not None:
192
            out.add_(bias)
193
        return out.reshape(out_shape)