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

CHU Tianxiang's avatar
CHU Tianxiang committed
4
5
import enum
from enum import Enum
6
from fractions import Fraction
7
from typing import TYPE_CHECKING, Any, Union
CHU Tianxiang's avatar
CHU Tianxiang committed
8
9

import torch
10
from safetensors.torch import _TYPES as _SAFETENSORS_TO_TORCH_DTYPE
CHU Tianxiang's avatar
CHU Tianxiang committed
11
12
from torch.nn.parameter import Parameter

13
from vllm import _custom_ops as ops
14
from vllm.logger import init_logger
15
from vllm.model_executor.layers.fused_moe.layer import FusedMoE
16
from vllm.model_executor.layers.linear import LinearMethodBase
CHU Tianxiang's avatar
CHU Tianxiang committed
17
from vllm.model_executor.layers.quantization.base_config import (
18
19
20
    QuantizationConfig,
    QuantizeMethodBase,
)
21
from vllm.model_executor.layers.quantization.utils.gptq_utils import (
22
23
24
25
26
27
28
29
30
    get_linear_quant_method,
)
from vllm.model_executor.parameter import (
    ChannelQuantScaleParameter,
    GroupQuantScaleParameter,
    PackedColumnParameter,
    PackedvLLMParameter,
    RowvLLMParameter,
)
31
from vllm.transformers_utils.config import get_safetensors_params_metadata
32
from vllm.utils.collection_utils import is_list_of
CHU Tianxiang's avatar
CHU Tianxiang committed
33

34
35
if TYPE_CHECKING:
    from vllm.model_executor.layers.quantization import QuantizationMethods
36
    from vllm.model_executor.models.utils import WeightsMapper
37
38
39
else:
    QuantizationMethods = str

40
41
logger = init_logger(__name__)

CHU Tianxiang's avatar
CHU Tianxiang committed
42
43
44
45
46
47
48
49
50
51
52
53

class GPTQConfig(QuantizationConfig):
    """Config class for GPTQ.

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

    def __init__(
        self,
        weight_bits: int,
        group_size: int,
        desc_act: bool,
54
        lm_head_quantized: bool,
55
        dynamic: dict[str, dict[str, int | bool]],
56
        autoround_version: str = "",
57
        modules_in_block_to_quantize: list[str] | None = None,
58
        checkpoint_format: str = "",
CHU Tianxiang's avatar
CHU Tianxiang committed
59
    ) -> None:
60
61
        # GPTQModel use `dynamic` config property to allow per module
        # quantization config so each module can be individually optimized.
62
        # Format is dict[str, dict] where key is a regex string that can
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
        # perform both positive ("+:" prefixed) or negative ("-:" prefixed)
        # matching of a module.
        # Default to positive match, override base quant config mode, if no
        # prefix is used. Value is in dict format of field key and override
        # value.
        # Negative matching will skip quantization init for this module
        # entirely:
        # non-quantized inference. More details and quantization examples can be
        # found at: https://github.com/ModelCloud/GPTQModel
        # Example:
        #  # last 1/2 of the layers 10-21 has 8bit vs 4bit for 0-9
        #  # last 1/4 of the layers 16-21 has 8bit and group_size 64
        # dynamic = {
        #  #`.*\.` matches the layers_node prefix
        #  # positive match layer 10-15
        #  r"+:.*\.(?:1[0-5])\..*": {"bits": 8,},
        #  # positive match layer 16-21
        #  r"+:.*\.(?:1[6-9]|20|21)\..*": {"bits": 8, "group_size": 64,},
        #  r"-:.*\.moe\..*": {}, # negative match (skip) all `moe` layers
        # }
83
        super().__init__()
84
85
        self.dynamic = dynamic

CHU Tianxiang's avatar
CHU Tianxiang committed
86
87
88
        self.weight_bits = weight_bits
        self.group_size = group_size
        self.desc_act = desc_act
89
        self.lm_head_quantized = lm_head_quantized
90
91
        self.pack_factor = Fraction(32, self.weight_bits)
        if self.weight_bits not in [2, 3, 4, 8]:
CHU Tianxiang's avatar
CHU Tianxiang committed
92
            raise ValueError(
93
                "Currently, only 2/3/4/8-bit weight quantization is "
94
95
                f"supported for GPTQ, but got {self.weight_bits} bits."
            )
96
97
98
99
100
101
102
        # Somehow gptq_gemm 4-bit is buggy, maybe fix it in the future.
        # For now, show a warning, since gptq_marlin will be used by default.
        if self.weight_bits == 4:
            logger.warning_once(
                "Currently, the 4-bit gptq_gemm kernel for GPTQ is buggy. "
                "Please switch to gptq_marlin or gptq_bitblas."
            )
CHU Tianxiang's avatar
CHU Tianxiang committed
103

104
105
        self.modules_in_block_to_quantize = modules_in_block_to_quantize or []

106
107
108
        # used to identify GPTQ model quantized by autoround
        self.autoround_version = autoround_version

109
110
111
112
113
        # GPTQ v1 and v2 format deals with zero points differently.
        # Currently GPTQModel stores v1 format checkpoints by default,
        # but provides the option to set `format="gptq_v2"` in `QuantizeConfig`.
        self.checkpoint_format = checkpoint_format

CHU Tianxiang's avatar
CHU Tianxiang committed
114
    def __repr__(self) -> str:
115
116
117
118
119
120
        return (
            f"GPTQConfig(weight_bits={self.weight_bits}, "
            f"group_size={self.group_size}, "
            f"desc_act={self.desc_act}), "
            f"lm_head_quantized={self.lm_head_quantized}, "
            f"dynamic={self.dynamic}, "
121
122
            f"modules_in_block_to_quantize={self.modules_in_block_to_quantize}), "
            f"checkpoint_format={self.checkpoint_format})"
123
        )
CHU Tianxiang's avatar
CHU Tianxiang committed
124
125

    @classmethod
126
    def get_name(cls) -> QuantizationMethods:
CHU Tianxiang's avatar
CHU Tianxiang committed
127
128
129
        return "gptq"

    @classmethod
130
    def get_supported_act_dtypes(cls) -> list[torch.dtype]:
CHU Tianxiang's avatar
CHU Tianxiang committed
131
132
133
134
135
136
137
138
        return [torch.half]

    @classmethod
    # Need to figure it out
    def get_min_capability(cls) -> int:
        return 60

    @classmethod
139
    def get_config_filenames(cls) -> list[str]:
CHU Tianxiang's avatar
CHU Tianxiang committed
140
141
142
        return ["quantize_config.json"]

    @classmethod
143
    def from_config(cls, config: dict[str, Any]) -> "GPTQConfig":
144
145
146
        dynamic = cls.get_from_keys_or(config, ["dynamic"], default={})
        dynamic = {} if dynamic is None else dynamic

CHU Tianxiang's avatar
CHU Tianxiang committed
147
148
149
        weight_bits = cls.get_from_keys(config, ["bits"])
        group_size = cls.get_from_keys(config, ["group_size"])
        desc_act = cls.get_from_keys(config, ["desc_act"])
150
151
152
153
        lm_head_quantized = cls.get_from_keys_or(config, ["lm_head"], default=False)
        autoround_version = cls.get_from_keys_or(
            config, ["autoround_version"], default=""
        )
154
        modules_in_block_to_quantize = cls.get_from_keys_or(
155
156
            config, ["modules_in_block_to_quantize"], default=None
        )
157
158
159
        checkpoint_format = cls.get_from_keys_or(
            config, ["checkpoint_format"], default=""
        )
160
161
162
163
164
165
166
167
        return cls(
            weight_bits,
            group_size,
            desc_act,
            lm_head_quantized,
            dynamic,
            autoround_version,
            modules_in_block_to_quantize,
168
            checkpoint_format,
169
        )
CHU Tianxiang's avatar
CHU Tianxiang committed
170

171
172
    def get_quant_method(
        self, layer: torch.nn.Module, prefix: str
173
    ) -> Union["GPTQLinearMethod", "QuantizeMethodBase"] | None:
174
175
176
177
        if isinstance(layer, FusedMoE):
            # GPTQ MoE support: fall back to MoeWNA16 for broad compatibility
            from .moe_wna16 import MoeWNA16Config

178
            # TODO: maybe update this for GPTQv2 format checkpoints
179
180
181
182
183
184
185
            config = {
                "quant_method": "gptq",
                "bits": self.weight_bits,
                "group_size": self.group_size,
                "sym": True,  # GPTQ typically uses symmetric quantization
                "lm_head": False,
            }
186
            return MoeWNA16Config.from_config(config).get_quant_method(layer, prefix)
187

188
        return get_linear_quant_method(self, layer, prefix, GPTQLinearMethod)
CHU Tianxiang's avatar
CHU Tianxiang committed
189

190
    def apply_vllm_mapper(self, hf_to_vllm_mapper: "WeightsMapper"):
191
192
        if self.modules_in_block_to_quantize is not None:
            self.modules_in_block_to_quantize = hf_to_vllm_mapper.apply_list(
193
194
                self.modules_in_block_to_quantize
            )
195

196
    def maybe_update_config(self, model_name: str, revision: str | None = None):
197
198
199
200
201
        if self.modules_in_block_to_quantize:
            if is_list_of(self.modules_in_block_to_quantize, list):
                # original modules_in_block_to_quantize: list[list[str]]
                # flatten original modules_in_block_to_quantize
                self.modules_in_block_to_quantize = [
202
203
                    item
                    for sublist in self.modules_in_block_to_quantize
204
205
206
207
208
                    for item in sublist
                ]
            return

        unquant_dtypes = [torch.float16, torch.bfloat16, torch.float32]
209
        metadata = get_safetensors_params_metadata(model_name, revision=revision)
210
211
212
        quant_layers: set[str] = {
            param_name.rsplit(".", 1)[0]
            for param_name, info in metadata.items()
213
            if (dtype := info.get("dtype", None))
214
215
216
217
            and _SAFETENSORS_TO_TORCH_DTYPE[dtype] not in unquant_dtypes
        }
        self.modules_in_block_to_quantize = list(quant_layers)

CHU Tianxiang's avatar
CHU Tianxiang committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234

class ExllamaState(Enum):
    UNUSED = enum.auto()
    UNINITIALIZED = enum.auto()
    READY = enum.auto()


class GPTQLinearMethod(LinearMethodBase):
    """Linear method for GPTQ.

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

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

235
236
237
        # GPTQ v1 and v2 format deals with zero points differently
        self.use_v2_format = quant_config.checkpoint_format == "gptq_v2"

CHU Tianxiang's avatar
CHU Tianxiang committed
238
239
    def create_weights(
        self,
240
        layer: torch.nn.Module,
CHU Tianxiang's avatar
CHU Tianxiang committed
241
        input_size_per_partition: int,
242
        output_partition_sizes: list[int],
CHU Tianxiang's avatar
CHU Tianxiang committed
243
244
245
        input_size: int,
        output_size: int,
        params_dtype: torch.dtype,
246
247
        **extra_weight_attrs,
    ):
CHU Tianxiang's avatar
CHU Tianxiang committed
248
        del output_size  # Unused.
249
        weight_loader = extra_weight_attrs.get("weight_loader")
CHU Tianxiang's avatar
CHU Tianxiang committed
250
251
252
253
        if input_size_per_partition % self.quant_config.group_size != 0:
            raise ValueError(
                "The input size is not aligned with the quantized "
                "weight shape. This can be caused by too large "
254
255
                "tensor parallel size."
            )
James Fleming's avatar
James Fleming committed
256
        output_size_per_partition = sum(output_partition_sizes)
257
        if output_size_per_partition % self.quant_config.pack_factor.numerator != 0:
CHU Tianxiang's avatar
CHU Tianxiang committed
258
259
260
            raise ValueError(
                "The output size is not aligned with the quantized "
                "weight shape. This can be caused by too large "
261
262
                "tensor parallel size."
            )
CHU Tianxiang's avatar
CHU Tianxiang committed
263
264
265
266
267
268
269
270

        if self.quant_config.group_size != -1:
            group_size = self.quant_config.group_size
        else:
            group_size = input_size
        exllama_state = ExllamaState.UNINITIALIZED
        scale_and_zero_size = input_size // group_size
        scale_and_zero_input_dim = None
271
272
273
274
        if (
            input_size != input_size_per_partition
            and self.quant_config.group_size != -1
        ):
CHU Tianxiang's avatar
CHU Tianxiang committed
275
276
277
278
279
280
281
282
            # For act-order models, we cannot use Exllama for row parallel layer
            if self.quant_config.desc_act:
                exllama_state = ExllamaState.UNUSED
            else:
                # we need to partition qzeros and scales for exllama kernel
                scale_and_zero_size = input_size_per_partition // group_size
                scale_and_zero_input_dim = 0

283
284
        qweight = PackedvLLMParameter(
            data=torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
285
286
287
288
                input_size_per_partition // self.quant_config.pack_factor,
                output_size_per_partition,
                dtype=torch.int32,
            ),
289
290
291
292
            input_dim=0,
            output_dim=1,
            packed_dim=0,
            packed_factor=self.quant_config.pack_factor,
293
294
295
296
297
298
299
300
301
302
303
304
305
306
            weight_loader=weight_loader,
        )

        g_idx = RowvLLMParameter(
            data=torch.tensor(
                [
                    i // self.quant_config.group_size
                    for i in range(input_size_per_partition)
                ],
                dtype=torch.int32,
            ),
            input_dim=0,
            weight_loader=weight_loader,
        )
307
        qzeros_args = {
308
            "data": torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
309
310
311
312
                scale_and_zero_size,
                output_size_per_partition // self.quant_config.pack_factor,
                dtype=torch.int32,
            ),
313
            "weight_loader": weight_loader,
314
315
        }
        weight_scale_args = {
316
            "data": torch.empty(
CHU Tianxiang's avatar
CHU Tianxiang committed
317
318
319
320
                scale_and_zero_size,
                output_size_per_partition,
                dtype=params_dtype,
            ),
321
            "weight_loader": weight_loader,
322
323
        }
        if scale_and_zero_input_dim is None:
324
            scales = ChannelQuantScaleParameter(output_dim=1, **weight_scale_args)
325
326
327
328
            qzeros = PackedColumnParameter(
                output_dim=1,
                packed_dim=1,
                packed_factor=self.quant_config.pack_factor,
329
330
                **qzeros_args,
            )
331
332

        else:
333
334
335
            scales = GroupQuantScaleParameter(
                output_dim=1, input_dim=0, **weight_scale_args
            )
336
337
338
339
340
            qzeros = PackedvLLMParameter(
                input_dim=0,
                output_dim=1,
                packed_dim=1,
                packed_factor=self.quant_config.pack_factor,
341
342
                **qzeros_args,
            )
343
344
345
346
347
348
349

        layer.register_parameter("qweight", qweight)
        layer.register_parameter("g_idx", g_idx)
        layer.register_parameter("qzeros", qzeros)
        layer.register_parameter("scales", scales)

        layer.exllama_state = exllama_state
CHU Tianxiang's avatar
CHU Tianxiang committed
350

351
    def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
352
353
354
355
        # for torch.compile
        layer.qzeros = Parameter(layer.qzeros.data, requires_grad=False)
        layer.qweight = Parameter(layer.qweight.data, requires_grad=False)
        layer.g_idx = Parameter(layer.g_idx.data, requires_grad=False)
356
        layer.scales = Parameter(layer.scales.data, requires_grad=False)
357

CHU Tianxiang's avatar
CHU Tianxiang committed
358
359
        # exllama needs to shuffle the weight after the weight is loaded
        # here we do the shuffle on first forward pass
360
        if layer.exllama_state == ExllamaState.UNINITIALIZED:
CHU Tianxiang's avatar
CHU Tianxiang committed
361
            if self.quant_config.desc_act:
362
                layer.g_idx.data = torch.argsort(layer.g_idx).to(torch.int)
CHU Tianxiang's avatar
CHU Tianxiang committed
363
            else:
364
365
366
                layer.g_idx.data = torch.empty(
                    (0,), dtype=torch.int, device=layer.g_idx.device
                )
367
            layer.exllama_state = ExllamaState.READY
368
369
370
371
372
373
            ops.gptq_shuffle(layer.qweight, layer.g_idx, self.quant_config.weight_bits)

    def apply(
        self,
        layer: torch.nn.Module,
        x: torch.Tensor,
374
        bias: torch.Tensor | None = None,
375
376
    ) -> torch.Tensor:
        out_shape = x.shape[:-1] + (layer.qweight.shape[-1],)
377
378
        reshaped_x = x.reshape(-1, x.shape[-1])

379
380
        # GPTQ v1 and v2 format checkpoints deals with zero points differently,
        # and require different gemm kernels.
381
382
383
384
385
386
387
        output = ops.gptq_gemm(
            reshaped_x,
            layer.qweight,
            layer.qzeros,
            layer.scales,
            layer.g_idx,
            layer.exllama_state == ExllamaState.READY,
388
            self.use_v2_format,
389
390
            self.quant_config.weight_bits,
        )
CHU Tianxiang's avatar
CHU Tianxiang committed
391
        if bias is not None:
392
            output.add_(bias)
CHU Tianxiang's avatar
CHU Tianxiang committed
393
        return output.reshape(out_shape)