awq.py 7.71 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, LinearMethodBase
8
9
from vllm.model_executor.layers.quantization.base_config import (
    QuantizationConfig)
10
from vllm.model_executor.utils import set_weight_attrs
gaoqiong's avatar
gaoqiong committed
11

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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):
        self.awqworkshapcesize = 2 << 29
        self.awqworkshapce = torch.zeros(self.awqworkshapcesize // 2 + 1, dtype=torch.float16).cuda()
        #print("AWQShareWorkSpace _initialize\n")
        #print("self.awqworkshapce.device:",self.awqworkshapce.device)
gaoqiong's avatar
gaoqiong committed
27

28
29
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


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,
    ) -> None:
        self.weight_bits = weight_bits
        self.group_size = group_size
        self.zero_point = zero_point

        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}, "
                f"zero_point={self.zero_point})")

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

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

    def get_min_capability(self) -> int:
        # 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
71
72
            # E.g., abhinavkulkarni/mosaicml-mpt-7b-instruct-w4-g128-awq
            "quantize_config.json",
73
74
75
76
77
78
79
80
81
        ]

    @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"])
        return cls(weight_bits, group_size, zero_point)

82
83
84
85
86
    def get_quant_method(
            self, layer: torch.nn.Module) -> Optional["AWQLinearMethod"]:
        if isinstance(layer, LinearBase):
            return AWQLinearMethod(self)
        return None
87

88
89
90
    def get_scaled_act_names(self) -> List[str]:
        return ["gelu", "gelu_fast", "gelu_new", "gelu_pytorch_tanh"]

91
92
93
94
95
96
97
98
99
100

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
101
        self.awqsingleton= AWQShareWorkSpace()
102

103
104
    def create_weights(self, layer: torch.nn.Module,
                       input_size_per_partition: int,
James Fleming's avatar
James Fleming committed
105
                       output_partition_sizes: List[int], input_size: int,
106
107
                       output_size: int, params_dtype: torch.dtype,
                       **extra_weight_attrs):
CHU Tianxiang's avatar
CHU Tianxiang committed
108
        if input_size_per_partition % self.quant_config.group_size != 0:
109
110
111
112
            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
113
114

        output_size_per_partition = sum(output_partition_sizes)
CHU Tianxiang's avatar
CHU Tianxiang committed
115
        if output_size_per_partition % self.quant_config.pack_factor != 0:
116
117
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.")

        qweight = Parameter(
            torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
123
124
                input_size_per_partition,
                output_size_per_partition // self.quant_config.pack_factor,
125
126
127
128
129
130
131
132
133
134
135
136
137
                dtype=torch.int32,
            ),
            requires_grad=False,
        )
        set_weight_attrs(
            qweight, {
                "input_dim": 0,
                "output_dim": 1,
                "packed_dim": 1,
                "pack_factor": self.quant_config.pack_factor,
            })
        qzeros = Parameter(
            torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
138
139
                input_size_per_partition // self.quant_config.group_size,
                output_size_per_partition // self.quant_config.pack_factor,
140
141
142
143
144
145
146
147
148
149
150
151
152
                dtype=torch.int32,
            ),
            requires_grad=False,
        )
        set_weight_attrs(
            qzeros, {
                "input_dim": 0,
                "output_dim": 1,
                "packed_dim": 1,
                "pack_factor": self.quant_config.pack_factor,
            })
        scales = Parameter(
            torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
153
154
                input_size_per_partition // self.quant_config.group_size,
                output_size_per_partition,
155
156
157
158
159
160
161
162
                dtype=params_dtype,
            ),
            requires_grad=False,
        )
        set_weight_attrs(scales, {
            "input_dim": 0,
            "output_dim": 1,
        })
gaoqiong's avatar
gaoqiong committed
163
164
165
166
167
168
169
170
171
172
173
174
175
        
        zeros_and_scales=Parameter(
            torch.empty(
                (input_size_per_partition // self.quant_config.group_size),
                output_size_per_partition,
                dtype=torch.int32,
            ),
            requires_grad=False,
        )    
        set_weight_attrs(zeros_and_scales, {
            "input_dim": 0,
            "output_dim": 1,
        })
176
177
178
179
180
181
182

        layer.register_parameter("qweight", qweight)
        set_weight_attrs(qweight, extra_weight_attrs)
        layer.register_parameter("qzeros", qzeros)
        set_weight_attrs(qzeros, extra_weight_attrs)
        layer.register_parameter("scales", scales)
        set_weight_attrs(scales, extra_weight_attrs)
gaoqiong's avatar
gaoqiong committed
183
184
        layer.register_parameter("zeros_and_scales", zeros_and_scales)
        set_weight_attrs(zeros_and_scales, extra_weight_attrs)
185

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