mlx/benchmarks/python/packed_qmv_bench.py

71 lines
1.7 KiB
Python
Raw Normal View History

2024-12-14 08:27:27 +08:00
import argparse
import math
from functools import partial
import mlx.core as mx
from time_utils import time_fn
2024-12-15 15:04:29 +08:00
D = 1024
M = 4 * D
2024-12-14 08:27:27 +08:00
group_size = 64
bits = 4
2024-12-14 08:27:27 +08:00
dtype = mx.float16
2024-12-14 10:36:36 +08:00
loops = 100
2024-12-14 08:27:27 +08:00
2024-12-15 15:04:29 +08:00
def qmv_(x, wq1, wq2, q_type):
2024-12-14 08:27:27 +08:00
for i in range(loops):
x = mx.quantized_matmul(
x,
2024-12-15 15:04:29 +08:00
*wq1,
group_size=group_size,
bits=bits,
type=q_type,
)
x = mx.quantized_matmul(
x,
*wq2,
2024-12-14 08:27:27 +08:00
group_size=group_size,
bits=bits,
type=q_type,
)
return x
2024-12-15 15:04:29 +08:00
def affine_qmv(x, wq1, wq2):
return qmv_(x, wq1, wq2, "affine")
2024-12-14 08:27:27 +08:00
2024-12-15 15:04:29 +08:00
def affine_packed_qmv(x, wq1, wq2):
return qmv_(x, wq1, wq2, "affine-packed")
2024-12-14 08:27:27 +08:00
def time_qmv():
mx.random.seed(3)
x = mx.random.normal(shape=(1, D)).astype(dtype)
2024-12-15 15:04:29 +08:00
w1 = mx.random.normal(shape=(M, D)).astype(dtype)
wq1 = mx.quantize(w1, group_size=group_size, bits=bits, type="affine")
w2 = mx.random.normal(shape=(D, M)).astype(dtype)
wq2 = mx.quantize(w2, group_size=group_size, bits=bits, type="affine")
mx.eval(x, wq1, wq2)
time_fn(affine_qmv, x, wq1, wq2)
2024-12-14 08:27:27 +08:00
def time_packed_qmv():
mx.random.seed(3)
x = mx.random.normal(shape=(1, D)).astype(dtype)
2024-12-15 15:04:29 +08:00
w1 = mx.random.normal(shape=(M, D)).astype(dtype)
wq1 = mx.quantize(w1, group_size=group_size, bits=bits, type="affine-packed")
w2 = mx.random.normal(shape=(D, M)).astype(dtype)
wq2 = mx.quantize(w2, group_size=group_size, bits=bits, type="affine-packed")
mx.eval(x, wq1, wq2)
time_fn(affine_packed_qmv, x, wq1, wq2)
2024-12-14 08:27:27 +08:00
if __name__ == "__main__":
2024-12-15 15:04:29 +08:00
for b in [2, 3, 4, 6, 8]:
bits = b
print(f"Bits {bits}:")
time_qmv()
time_packed_qmv()