benchmark_aqlm.py 8.98 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

James Fleming's avatar
James Fleming committed
3
4
5
6
7
8
9
import os
import sys
from typing import Optional

import torch
import torch.nn.functional as F

10
from vllm import _custom_ops as ops
James Fleming's avatar
James Fleming committed
11
from vllm.model_executor.layers.quantization.aqlm import (
12
13
14
15
16
    dequantize_weight,
    generic_dequantize_gemm,
    get_int_dtype,
    optimized_dequantize_gemm,
)
17
from vllm.utils import FlexibleArgumentParser
James Fleming's avatar
James Fleming committed
18

19
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
James Fleming's avatar
James Fleming committed
20
21
22


def torch_mult(
23
24
25
26
27
    # [..., in_features]
    input: torch.Tensor,
    weights: torch.Tensor,
    # [num_out_groups, 1, 1, 1]
    scales: torch.Tensor,
James Fleming's avatar
James Fleming committed
28
29
30
31
32
33
) -> torch.Tensor:
    output = F.linear(input, weights)
    return output


def dequant_out_scale(
34
35
36
37
38
39
40
41
    # [..., in_features]
    input: torch.Tensor,
    # [num_out_groups, num_in_groups, num_codebooks]
    codes: torch.IntTensor,
    # [num_codebooks, codebook_size, out_group_size, in_group_size]
    codebooks: torch.Tensor,
    # [num_out_groups, 1, 1, 1]
    scales: torch.Tensor,
James Fleming's avatar
James Fleming committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    output_partition_sizes: torch.IntTensor,
    bias: Optional[torch.Tensor],
) -> torch.Tensor:
    weights = ops.aqlm_dequant(codes, codebooks, output_partition_sizes)

    if bias is None:
        output = F.linear(input, weights, bias)
        orig_shape = output.shape
        flattened_output = output.view(-1, output.size(-1))
        f_scales = scales.view(-1, scales.shape[0])
        b_scales = f_scales.expand(flattened_output.shape[0], -1)
        flattened_output *= b_scales
        return flattened_output.view(orig_shape)
    else:
56
        b_scales = scales.view(scales.shape[:-3] + (-1,)).expand(-1, weights.shape[1])
James Fleming's avatar
James Fleming committed
57
58
59
60
61
        weights *= b_scales
        return F.linear(input, weights, bias)


def dequant_weight_scale(
62
63
64
65
66
67
68
69
    # [..., in_features]
    input: torch.Tensor,
    # [num_out_groups, num_in_groups, num_codebooks]
    codes: torch.IntTensor,
    # [num_codebooks, codebook_size, out_group_size, in_group_size]
    codebooks: torch.Tensor,
    # [num_out_groups, 1, 1, 1]
    scales: torch.Tensor,
James Fleming's avatar
James Fleming committed
70
71
72
73
74
    output_partition_sizes: torch.IntTensor,
    bias: Optional[torch.Tensor],
) -> torch.Tensor:
    weights = ops.aqlm_dequant(codes, codebooks, output_partition_sizes)

75
    b_scales = scales.view(scales.shape[:-3] + (-1,)).expand(-1, weights.shape[1])
James Fleming's avatar
James Fleming committed
76
77
78
79
80
    weights *= b_scales
    return F.linear(input, weights, bias)


def dequant_no_scale(
81
82
83
84
85
86
87
88
    # [..., in_features]
    input: torch.Tensor,
    # [num_out_groups, num_in_groups, num_codebooks]
    codes: torch.IntTensor,
    # [num_codebooks, codebook_size, out_group_size, in_group_size]
    codebooks: torch.Tensor,
    # [num_out_groups, 1, 1, 1]
    scales: torch.Tensor,
James Fleming's avatar
James Fleming committed
89
90
91
92
93
94
95
96
97
98
99
    output_partition_sizes: torch.IntTensor,
    bias: Optional[torch.Tensor],
) -> torch.Tensor:
    weights = ops.aqlm_dequant(codes, codebooks, output_partition_sizes)

    return F.linear(input, weights, bias)


# Compare the optimized 1x16 and 2x8 cuda decompression/dequant kernels against
# the generic pytorch version.
# Just visual comparison.
100
101
def dequant_test(k: int, parts: torch.Tensor, nbooks: int, bits: int) -> None:
    n = int(parts.sum().item())
James Fleming's avatar
James Fleming committed
102

103
    device = torch.device("cuda:0")
James Fleming's avatar
James Fleming committed
104
105
106
107

    code_range = (1 << bits) // 2
    ingroups = 8

108
109
110
111
112
113
114
    codes = torch.randint(
        -code_range,
        code_range,
        size=(n, k // ingroups, nbooks),
        dtype=get_int_dtype(bits),
        device=device,
    )
James Fleming's avatar
James Fleming committed
115

116
117
118
119
120
    codebooks = torch.randn(
        size=(parts.shape[0] * nbooks, 1 << bits, 1, 8),
        dtype=torch.float16,
        device=device,
    )
James Fleming's avatar
James Fleming committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    count = 0
    for index in range(16):
        for i in range(8):
            for book in range(nbooks):
                codebooks[book, index, 0, i] = count * (10**book)
            count += 1

    print("codes shape", codes.shape)

    for i in range(16):
        for book in range(nbooks):
            codes[0, i, book] = i
            codes[0, -i, book] = i

    weights = dequantize_weight(codes, codebooks, None)
    weights2 = ops.aqlm_dequant(codes, codebooks, parts)

    print("weights shape:", weights.shape)
    print("weights2 shape:", weights2.shape)

    print("weights are:", weights)
    print("weights2 are:", weights2)

    print("first 128 weights are", weights[0, 0:128].to(torch.int32))
    print("first 128 weights2 are:", weights2[0, 0:128].to(torch.int32))

    print("last 128 weights are", weights[0, -128:])
    print("last 128 weights2 are:", weights2[0, -128:])


def main():
153
    parser = FlexibleArgumentParser(description="Benchmark aqlm performance.")
James Fleming's avatar
James Fleming committed
154
155

    # Add arguments
156
157
158
159
160
161
162
163
164
    parser.add_argument(
        "--nbooks", type=int, default=1, help="Number of codebooks (default: 1)"
    )
    parser.add_argument(
        "--bits",
        type=int,
        default=16,
        help="Number of bits per code element (default: 16)",
    )
James Fleming's avatar
James Fleming committed
165
166
167
168
169
    parser.add_argument(
        "--test",
        type=bool,
        default=False,
        help="Run the decompression/dequant tester rather than benchmarking "
170
171
        "(default: False)",
    )
James Fleming's avatar
James Fleming committed
172
173
174
175
176
177
178
179
180

    # Parse the arguments
    args = parser.parse_args()

    # Extract values
    nbooks = args.nbooks
    bits = args.bits

    if args.test:
181
        dequant_test(4096, torch.tensor((4096,)), nbooks, bits)
James Fleming's avatar
James Fleming committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
        return

    # Otherwise, benchmark.
    methods = [
        ops.aqlm_gemm,
        dequant_out_scale,
        generic_dequantize_gemm,
        optimized_dequantize_gemm,
        dequant_weight_scale,
        torch_mult,
        dequant_no_scale,
    ]

    filename = f"./aqlm_benchmark_{nbooks}x{bits}.csv"
    print(f"writing benchmarks to file {filename}")
    with open(filename, "w") as f:
        sys.stdout = f

200
        print("m | k | n | n parts", end="")
James Fleming's avatar
James Fleming committed
201
        for method in methods:
202
203
            print(f" | {method.__name__.replace('_', ' ')} (µs)", end="")
        print("")
James Fleming's avatar
James Fleming committed
204
205

        # These are reasonable prefill sizes.
206
207
208
209
210
211
        ksandpartions = (
            (4096, (4096, 4096, 4096)),
            (4096, (4096,)),
            (4096, (11008, 11008)),
            (11008, (4096,)),
        )
James Fleming's avatar
James Fleming committed
212
213
214

        # reasonable ranges for m.
        for m in [
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
            1,
            2,
            4,
            8,
            10,
            12,
            14,
            16,
            24,
            32,
            48,
            52,
            56,
            64,
            96,
            112,
            128,
            256,
            512,
            1024,
            1536,
            2048,
            3072,
            4096,
James Fleming's avatar
James Fleming committed
239
        ]:
240
            print(f"{m}", file=sys.__stdout__)
James Fleming's avatar
James Fleming committed
241
            for ksp in ksandpartions:
242
                run_grid(m, ksp[0], torch.tensor(ksp[1]), nbooks, bits, methods)
James Fleming's avatar
James Fleming committed
243
244
245
246

        sys.stdout = sys.__stdout__


247
def run_grid(m: int, k: int, parts: torch.Tensor, nbooks: int, bits: int, methods):
James Fleming's avatar
James Fleming committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    # I didn't see visible improvements from increasing these, but feel free :)
    num_warmup_trials = 1
    num_trials = 1

    num_calls = 100

    # warmup.
    for method in methods:
        for _ in range(num_warmup_trials):
            run_timing(
                num_calls=num_calls,
                m=m,
                k=k,
                parts=parts,
                nbooks=nbooks,
                bits=bits,
                method=method,
            )

    n = parts.sum().item()
268
    print(f"{m} | {k} | {n} | {parts.tolist()}", end="")
James Fleming's avatar
James Fleming committed
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287

    for method in methods:
        best_time_us = 1e20
        for _ in range(num_trials):
            kernel_dur_ms = run_timing(
                num_calls=num_calls,
                m=m,
                k=k,
                parts=parts,
                nbooks=nbooks,
                bits=bits,
                method=method,
            )

            kernel_dur_us = 1000 * kernel_dur_ms

            if kernel_dur_us < best_time_us:
                best_time_us = kernel_dur_us

288
        print(f" | {kernel_dur_us:.0f}", end="")
James Fleming's avatar
James Fleming committed
289

290
    print("")
James Fleming's avatar
James Fleming committed
291
292


293
294
295
def run_timing(
    num_calls: int, m: int, k: int, parts: torch.Tensor, nbooks: int, bits: int, method
) -> float:
296
    n = int(parts.sum().item())
James Fleming's avatar
James Fleming committed
297

298
    device = torch.device("cuda:0")
James Fleming's avatar
James Fleming committed
299
300
301
302
303
304

    input = torch.randn((1, m, k), dtype=torch.float16, device=device)

    code_range = (1 << bits) // 2
    ingroups = 8

305
306
307
308
309
310
311
312
313
314
315
316
317
    codes = torch.randint(
        -code_range,
        code_range,
        size=(n, k // ingroups, nbooks),
        dtype=get_int_dtype(bits),
        device=device,
    )

    codebooks = torch.randn(
        size=(parts.shape[0] * nbooks, 1 << bits, 1, 8),
        dtype=torch.float16,
        device=device,
    )
James Fleming's avatar
James Fleming committed
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

    scales = torch.randn(size=(n, 1, 1, 1), dtype=torch.float16, device=device)

    # for comparison to just a pytorch mult.
    weights = torch.randn((n, k), dtype=torch.float16, device=device)

    start_event = torch.cuda.Event(enable_timing=True)
    end_event = torch.cuda.Event(enable_timing=True)

    start_event.record()

    if method is torch_mult:
        for i in range(num_calls):
            torch_mult(input, weights, scales)
    else:
        for i in range(num_calls):
            method(input, codes, codebooks, scales, parts, None)

    end_event.record()
    end_event.synchronize()

    dur_ms = start_event.elapsed_time(end_event) / num_calls
    return dur_ms


if __name__ == "__main__":
    sys.exit(main())