"vscode:/vscode.git/clone" did not exist on "0dd5dee9b9bc88453f5f3eacfde751e6b9ba4871"
awq.py 8.86 KB
Newer Older
1
2
3
from typing import Any, Dict, List, Optional

import torch
zhuwenwen's avatar
zhuwenwen committed
4
import os
5
import torch.nn.functional as F
6

7
from vllm import _custom_ops as ops
8
9
from vllm.model_executor.layers.linear import (LinearBase, LinearMethodBase,
                                               UnquantizedLinearMethod)
10
11
from vllm.model_executor.layers.quantization.base_config import (
    QuantizationConfig)
12
13
from vllm.model_executor.parameter import (GroupQuantScaleParameter,
                                           PackedvLLMParameter)
14
15


16
17
18
19
20
21
22
23
24
25
class AWQShareWorkSpace:
    _instance = None
    
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super(AWQShareWorkSpace, cls).__new__(cls, *args, **kwargs)
            cls._instance._initialize()
        return cls._instance

    def _initialize(self):
zhuwenwen's avatar
zhuwenwen committed
26
27
        self.awqworkshapcesize = ops.GetAWQShareWorkspaceSize()
        self.awqworkshapce = ops.GetAWQShareWorkspace()
28
29
30
31
32
33
34
35
36
37
38
39
40


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,
41
        modules_to_not_convert: Optional[List[str]] = None,
42
43
44
45
    ) -> None:
        self.weight_bits = weight_bits
        self.group_size = group_size
        self.zero_point = zero_point
46
        self.modules_to_not_convert = modules_to_not_convert or []
47
48
49
50
51
52
53
54
55
56

        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}, "
57
58
                f"zero_point={self.zero_point}, "
                f"modules_to_not_convert={self.modules_to_not_convert})")
59
60
61
62
63
64
65

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

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

66
67
    @classmethod
    def get_min_capability(cls) -> int:
68
69
70
71
72
73
74
        # The AWQ kernel only supports Turing or newer GPUs.
        return 75

    @staticmethod
    def get_config_filenames() -> List[str]:
        return [
            "quant_config.json",  # E.g., casperhansen/vicuna-7b-v1.5-awq
75
76
            # E.g., abhinavkulkarni/mosaicml-mpt-7b-instruct-w4-g128-awq
            "quantize_config.json",
77
78
79
80
81
82
83
        ]

    @classmethod
    def from_config(cls, config: Dict[str, Any]) -> "AWQConfig":
        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"])
84
85
86
        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)
87

88
    def get_quant_method(self, layer: torch.nn.Module,
89
                         prefix: str) -> Optional["LinearMethodBase"]:
90
        if isinstance(layer, LinearBase):
91
92
            if is_layer_skipped_awq(prefix, self.modules_to_not_convert):
                return UnquantizedLinearMethod()
93
94
            return AWQLinearMethod(self)
        return None
95
96


97
98
def is_layer_skipped_awq(prefix: str, modules_to_not_convert: List[str]):
    return any(module_name in prefix for module_name in modules_to_not_convert)
99

100
101
102
103
104
105
106
107
108
109

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
110
        self.awqsingleton= AWQShareWorkSpace()
zhuwenwen's avatar
zhuwenwen committed
111
112
        self.use_awq_pad = os.environ.get('AWQ_PAD') == '1'
        self.AWQ_CK_GEMMBS =int(os.getenv('AWQ_CK_GEMMBS', '20000'))
113

114
115
    def create_weights(self, layer: torch.nn.Module,
                       input_size_per_partition: int,
James Fleming's avatar
James Fleming committed
116
                       output_partition_sizes: List[int], input_size: int,
117
118
                       output_size: int, params_dtype: torch.dtype,
                       **extra_weight_attrs):
CHU Tianxiang's avatar
CHU Tianxiang committed
119
        if input_size_per_partition % self.quant_config.group_size != 0:
120
121
122
123
            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
124
125

        output_size_per_partition = sum(output_partition_sizes)
CHU Tianxiang's avatar
CHU Tianxiang committed
126
        if output_size_per_partition % self.quant_config.pack_factor != 0:
127
128
129
130
131
            raise ValueError(
                "The output size is not aligned with the quantized "
                "weight shape. This can be caused by too large "
                "tensor parallel size.")

132
133
134
        weight_loader = extra_weight_attrs.get("weight_loader")
        qweight = PackedvLLMParameter(
            data=torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
135
136
                input_size_per_partition,
                output_size_per_partition // self.quant_config.pack_factor,
137
138
                dtype=torch.int32,
            ),
139
140
141
142
143
144
145
146
            input_dim=0,
            output_dim=1,
            packed_dim=1,
            packed_factor=self.quant_config.pack_factor,
            weight_loader=weight_loader)

        qzeros = PackedvLLMParameter(
            data=torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
147
148
                input_size_per_partition // self.quant_config.group_size,
                output_size_per_partition // self.quant_config.pack_factor,
149
150
                dtype=torch.int32,
            ),
151
152
153
154
155
156
157
158
159
160
161
162
163
164
            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(
            input_size_per_partition // self.quant_config.group_size,
            output_size_per_partition,
            dtype=params_dtype,
        ),
                                          input_dim=0,
                                          output_dim=1,
                                          weight_loader=weight_loader)
gaoqiong's avatar
gaoqiong committed
165
        
166
167
168
        zeros_and_scales = GroupQuantScaleParameter(data=torch.empty(
            input_size_per_partition // self.quant_config.group_size,
            output_size_per_partition,
zhuwenwen's avatar
zhuwenwen committed
169
            dtype=torch.int32,
170
171
172
173
        ),
                                          input_dim=0,
                                          output_dim=1,
                                          weight_loader=weight_loader)
174
175
176
177

        layer.register_parameter("qweight", qweight)
        layer.register_parameter("qzeros", qzeros)
        layer.register_parameter("scales", scales)
gaoqiong's avatar
gaoqiong committed
178
        layer.register_parameter("zeros_and_scales", zeros_and_scales)
179

180
181
182
183
184
185
186
187

    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)
188
189
        layer.zeros_and_scales = torch.nn.Parameter(layer.zeros_and_scales.data,
                                          requires_grad=False)
190

191
192
193
194
    def apply(self,
              layer: torch.nn.Module,
              x: torch.Tensor,
              bias: Optional[torch.Tensor] = None) -> torch.Tensor:
195
        qweight = layer.qweight
gaoqiong's avatar
gaoqiong committed
196
197
198
        zeros_and_scales = layer.zeros_and_scales
        
        out_shape = (x.shape[:-1] + (qweight.shape[0] * 1, ))
199
        reshaped_x = x.reshape(-1, x.shape[-1])
gaoqiong's avatar
gaoqiong committed
200
201
202
203
204
        
        m = reshaped_x.shape[0]
        k = reshaped_x.shape[-1]
        n = qweight.shape[0]
        
zhuwenwen's avatar
zhuwenwen committed
205
206
207
208
209
        if self.use_awq_pad:
            if k % 4096 == 0:
                padding_group=2
            else:
                padding_group=0
210
        else:
gaoqiong's avatar
gaoqiong committed
211
212
            padding_group=0
        
zhuwenwen's avatar
zhuwenwen committed
213
        if m <= self.AWQ_CK_GEMMBS: 
zhuwenwen's avatar
zhuwenwen committed
214
            out = ops.awq_gemm(reshaped_x,
gaoqiong's avatar
gaoqiong committed
215
216
217
218
219
220
221
                            qweight,
                            zeros_and_scales,
                            m,
                            n,
                            k,
                            self.quant_config.group_size,
                            padding_group,
222
223
                            self.awqsingleton.awqworkshapce,
                            self.awqsingleton.awqworkshapcesize)
zhuwenwen's avatar
zhuwenwen committed
224
225
        else: 
            #下面是采用rocblas的做法
zhuwenwen's avatar
zhuwenwen committed
226
            deqweight=ops.dequant_w4_gemm_colmajor(    # shape[n, k/8] ---> [n,k]
zhuwenwen's avatar
zhuwenwen committed
227
228
                            qweight, 
                            zeros_and_scales,
zhuwenwen's avatar
zhuwenwen committed
229
                            k+padding_group*self.quant_config.group_size,
zhuwenwen's avatar
zhuwenwen committed
230
231
232
                            n,
                            self.quant_config.group_size)
            out=F.linear(reshaped_x, deqweight[:,0:k])    
gaoqiong's avatar
gaoqiong committed
233
        
234
        if bias is not None:
235
            out.add_(bias)
zhuwenwen's avatar
zhuwenwen committed
236
        return out.reshape(out_shape)