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

4
from typing import Any, Optional
5
6
7
8

import torch
from torch.nn.parameter import Parameter

9
from vllm import _custom_ops as ops
10
from vllm.logger import init_logger
11
from vllm.model_executor.layers.linear import LinearBase, LinearMethodBase
12
from vllm.model_executor.layers.quantization import QuantizationMethods
13
14
from vllm.model_executor.layers.quantization.base_config import (
    QuantizationConfig)
15
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
16
17
18
19
from vllm.model_executor.parameter import (BasevLLMParameter,
                                           ChannelQuantScaleParameter,
                                           GroupQuantScaleParameter,
                                           PackedvLLMParameter)
20

21
22
logger = init_logger(__name__)

23
24
25
26
27
28
29
30
31
32

class MarlinConfig(QuantizationConfig):
    """Config class for Marlin.

    Reference: https://github.com/IST-DASLab/marlin/tree/master
    """

    def __init__(
        self,
        group_size: int,
33
        lm_head_quantized: bool,
34
    ) -> None:
35
36
        super().__init__()

37
38
        # Group size for the quantization.
        self.group_size = group_size
39
        self.lm_head_quantized = lm_head_quantized
40
41
        if self.group_size != 128 and self.group_size != -1:
            raise ValueError(
42
43
44
                "Currently, only group size 128 and -1 (channelwise) "
                "is supported for Marlin, but got group_size of "
                f"{self.group_size}")
45
46
47
48
49
50
51
52
53
54
55
56
57

        # 4 Bits packed into 32 bit datatype.
        self.pack_factor = 32 // 4

        # Tile size used by marlin kernels.
        self.tile_size = 16

        # Min out_features dim
        self.min_n_threads = 64

        # Min in_features dim
        self.min_k_threads = 128

58
59
        # Max parallel problems to solve at once (improves large
        # batch performance)
60
61
62
63
64
65
        self.max_parallel = 16

        # Permutation length used by the marlin kernels.
        self.perm_len = 1024

    def __repr__(self) -> str:
66
67
        return (f"MarlinConfig(group_size={self.group_size}, "
                f"lm_head_quantized={self.lm_head_quantized})")
68
69

    @classmethod
70
    def get_name(cls) -> QuantizationMethods:
71
72
73
        return "marlin"

    @classmethod
74
    def get_supported_act_dtypes(cls) -> list[torch.dtype]:
75
76
77
78
79
80
81
82
        return [torch.half]

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

    @classmethod
83
    def get_config_filenames(cls) -> list[str]:
84
85
86
        return ["quantize_config.json"]

    @classmethod
87
    def from_config(cls, config: dict[str, Any]) -> "MarlinConfig":
88
        group_size = cls.get_from_keys(config, ["group_size"])
89
90
91
        lm_head_quantized = cls.get_from_keys_or(config, ["lm_head"],
                                                 default=False)
        return cls(group_size, lm_head_quantized)
92

93
    @classmethod
94
95
    def override_quantization_method(
            cls, hf_quant_cfg, user_quant) -> Optional[QuantizationMethods]:
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
        # compat: autogptq >=0.8.0 use checkpoint_format: str
        # compat: autogptq <=0.7.1 is_marlin_format: bool
        is_marlin_format = (hf_quant_cfg.get("checkpoint_format") == "marlin"
                            or hf_quant_cfg.get("is_marlin_format", False))

        is_valid_user_quant = (user_quant is None or user_quant == "gptq"
                               or user_quant == "marlin")

        if is_marlin_format and is_valid_user_quant:
            msg = ("The model is serialized in {} format. Using {} kernel.".
                   format(cls.get_name(), cls.get_name()))
            logger.info(msg)
            return cls.get_name()

        return None

112
113
    def get_quant_method(self, layer: torch.nn.Module,
                         prefix: str) -> Optional["MarlinLinearMethod"]:
114
115
        if (isinstance(layer, LinearBase) or
            (isinstance(layer, ParallelLMHead) and self.lm_head_quantized)):
116
117
            return MarlinLinearMethod(self)
        return None
118
119
120
121
122
123
124
125
126
127
128
129
130
131


class MarlinLinearMethod(LinearMethodBase):
    """Linear method for Marlin.

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

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

    def create_weights(
        self,
132
        layer: torch.nn.Module,
133
        input_size_per_partition: int,
134
        output_partition_sizes: list[int],
135
136
137
        input_size: int,
        output_size: int,
        params_dtype: torch.dtype,
138
139
        **extra_weight_attrs,
    ):
140
        del output_size  # Unused.
141
        weight_loader = extra_weight_attrs["weight_loader"]
142
143
144
145
146
147

        if params_dtype != torch.float16:
            raise ValueError(
                f"The params dtype must be float16, but got {params_dtype}")

        # Validate output_size_per_partition
James Fleming's avatar
James Fleming committed
148
        output_size_per_partition = sum(output_partition_sizes)
149
150
        if output_size_per_partition % self.quant_config.min_n_threads != 0:
            raise ValueError(
151
152
153
                f"Weight output_size_per_partition = "
                f"{output_size_per_partition} is not divisible by "
                f"min_n_threads = {self.quant_config.min_n_threads}.")
154
155
        if output_size_per_partition % self.quant_config.pack_factor != 0:
            raise ValueError(
156
157
158
                f"Weight output_size_per_partition = "
                f"{output_size_per_partition} is not divisible by "
                f"pack_factor = {self.quant_config.pack_factor}.")
159
160
161
162

        # Validate input_size_per_partition
        if input_size_per_partition % self.quant_config.min_k_threads != 0:
            raise ValueError(
163
164
165
166
167
168
169
170
                f"Weight input_size_per_partition = "
                f"{input_size_per_partition} is not divisible by "
                f"min_k_threads = {self.quant_config.min_k_threads}.")
        if (self.quant_config.group_size != -1 and
                input_size_per_partition % self.quant_config.group_size != 0):
            raise ValueError(f"Weight input_size_per_partition = "
                             f"{input_size_per_partition} is not divisible by "
                             f"group_size = {self.quant_config.group_size}.")
171
172
173
174
175
176
177
178
179

        # Check that we have at least 4 tiles horizontally in the shard
        num_tiles_per_perm = self.quant_config.perm_len // (
            self.quant_config.tile_size**2)
        if output_size_per_partition % num_tiles_per_perm != 0:
            raise ValueError(
                "Each permutation group must reside on the same gpu")

        # Quantized 4Bit weights packed into Int32.
180
181
        qweight = PackedvLLMParameter(
            data=torch.empty(
182
183
184
185
186
187
                input_size_per_partition // self.quant_config.tile_size,
                output_size_per_partition * self.quant_config.tile_size //
                self.quant_config.pack_factor,
                device="cuda",
                dtype=torch.int32,
            ),
188
189
190
191
192
193
            input_dim=0,
            output_dim=1,
            packed_dim=1,
            packed_factor=self.quant_config.pack_factor,
            marlin_tile_size=self.quant_config.tile_size,
            weight_loader=weight_loader)
194
195

        # Determine if channelwise or not
196
197
198
        input_groups = (1 if self.quant_config.group_size == -1 else
                        input_size_per_partition //
                        self.quant_config.group_size)
199

200
201
        weight_scale_args = {
            "data":
202
203
204
205
206
207
            torch.empty(
                input_groups,
                output_size_per_partition,
                device="cuda",
                dtype=params_dtype,
            ),
208
209
210
211
212
213
214
215
216
217
            "weight_loader":
            weight_loader
        }
        if input_groups == 1:
            scales = ChannelQuantScaleParameter(output_dim=1,
                                                **weight_scale_args)
        else:
            scales = GroupQuantScaleParameter(output_dim=1,
                                              input_dim=0,
                                              **weight_scale_args)
218
219
220
221
222

        # Allocate workspace (Used for internal locking mechanism)
        max_workspace_size = (
            output_size_per_partition //
            self.quant_config.min_n_threads) * self.quant_config.max_parallel
223
224
225
226
227

        workspace = BasevLLMParameter(data=torch.zeros(max_workspace_size,
                                                       device="cuda",
                                                       dtype=torch.int),
                                      weight_loader=weight_loader)
228

229
230
231
        layer.register_parameter("B", qweight)
        layer.register_parameter("s", scales)
        layer.register_parameter("workspace", workspace)
232
233
234
235
236
237

    def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
        # required by torch.compile
        layer.B = Parameter(layer.B.data, requires_grad=False)
        layer.s = Parameter(layer.s.data, requires_grad=False)
        layer.workspace = Parameter(layer.workspace.data, requires_grad=False)
238

239
    def apply(
240
        self,
241
        layer: torch.nn.Module,
242
243
244
        x: torch.Tensor,
        bias: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
245
246
247
        qweight = layer.B
        scales = layer.s
        workspace = layer.workspace
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263

        x_2d = x.view(-1, x.shape[-1])

        size_m = x_2d.shape[0]
        size_k = x_2d.shape[1]
        size_n = scales.shape[1]

        output_2d = ops.marlin_gemm(x_2d, qweight, scales, workspace, size_m,
                                    size_n, size_k)

        output = output_2d.view(x.shape[:-1] + (output_2d.shape[1], ))

        if bias is not None:
            output.add_(bias)  # In-place add

        return output