Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Speed up AWQ (#375)

CCYeh419082cb7000
diff --git a/crates/backend-uzu/src/backends/common/kernel/quant_matmul.rs b/crates/backend-uzu/src/backends/common/kernel/quant_matmul.rs
index ae6039cc0..0e4b3f12b 100644
--- a/crates/backend-uzu/src/backends/common/kernel/quant_matmul.rs
+++ b/crates/backend-uzu/src/backends/common/kernel/quant_matmul.rs
@@ -240,7 +240,7 @@ impl<B: Backend> QuantizedMatmulKernelEncodable<B> {
};
}
- if arguments.batch_dim >= 8 && self.output_dim > 1 {
+ if arguments.batch_dim >= 5 && self.output_dim > 1 {
if let Some(kernel) = self.matrix_matrix.pick(arguments.batch_dim) {
encode_kernel!(kernel, arguments.hadamard_factors);
return Ok(());
diff --git a/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/qmv_fast.metal b/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/qmv_fast.metal
index 4353e23ec..a4856d51c 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/qmv_fast.metal
+++ b/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/qmv_fast.metal
@@ -99,36 +99,47 @@ PUBLIC KERNEL(QuantizedMatmulQmvFast)(
result[3] +=
qdot<U, values_per_thread, BITS>(wl3, x_thread, s3, b3, sum);
} else {
- uint8_t zp_byte0 = zps[0];
- uint8_t zp_byte1 = zps[zp_stride];
- uint8_t zp_byte2 = zps[2 * zp_stride];
- uint8_t zp_byte3 = zps[3 * zp_stride];
- U zp0 = static_cast<U>(
- (BITS == 4 && high_nibble) ? (zp_byte0 >> 4) : (zp_byte0 & 0x0F)
+ uchar4 zp_bytes = uchar4(
+ zps[0],
+ zps[zp_stride],
+ zps[2 * zp_stride],
+ zps[3 * zp_stride]
);
- U zp1 = static_cast<U>(
- (BITS == 4 && high_nibble) ? (zp_byte1 >> 4) : (zp_byte1 & 0x0F)
+ uchar4 zp_nibbles;
+ if (BITS == 4) {
+ const uint8_t shift = high_nibble ? 4u : 0u;
+ zp_nibbles = (zp_bytes >> shift) & uchar4(0x0F);
+ } else {
+ zp_nibbles = zp_bytes;
+ }
+ result[0] += qdot<U, values_per_thread, BITS>(
+ wl0,
+ x_thread,
+ s0,
+ -s0 * static_cast<U>(zp_nibbles.x),
+ sum
);
- U zp2 = static_cast<U>(
- (BITS == 4 && high_nibble) ? (zp_byte2 >> 4) : (zp_byte2 & 0x0F)
+ result[1] += qdot<U, values_per_thread, BITS>(
+ wl1,
+ x_thread,
+ s1,
+ -s1 * static_cast<U>(zp_nibbles.y),
+ sum
);
- U zp3 = static_cast<U>(
- (BITS == 4 && high_nibble) ? (zp_byte3 >> 4) : (zp_byte3 & 0x0F)
+ result[2] += qdot<U, values_per_thread, BITS>(
+ wl2,
+ x_thread,
+ s2,
+ -s2 * static_cast<U>(zp_nibbles.z),
+ sum
+ );
+ result[3] += qdot<U, values_per_thread, BITS>(
+ wl3,
+ x_thread,
+ s3,
+ -s3 * static_cast<U>(zp_nibbles.w),
+ sum
);
- if (BITS == 8) {
- zp0 = static_cast<U>(zp_byte0);
- zp1 = static_cast<U>(zp_byte1);
- zp2 = static_cast<U>(zp_byte2);
- zp3 = static_cast<U>(zp_byte3);
- }
- result[0] +=
- qdot<U, values_per_thread, BITS>(wl0, x_thread, s0, -s0 * zp0, sum);
- result[1] +=
- qdot<U, values_per_thread, BITS>(wl1, x_thread, s1, -s1 * zp1, sum);
- result[2] +=
- qdot<U, values_per_thread, BITS>(wl2, x_thread, s2, -s2 * zp2, sum);
- result[3] +=
- qdot<U, values_per_thread, BITS>(wl3, x_thread, s3, -s3 * zp3, sum);
}
}
diff --git a/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.h b/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.h
index 6e8d0eda2..842d7d160 100644
--- a/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.h
+++ b/crates/backend-uzu/src/backends/metal/kernel/quant_matmul/quant_matmul.h
@@ -493,7 +493,7 @@ struct QuantizedBlockLoaderZp {
const int byte_index =
row_idx * zp_stride_total + (out_group_base >> 1);
uint8_t zp_b = zps_row_start[byte_index];
- zp_n = (out_group_base & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F);
+ zp_n = (uint(zp_b) >> (uint(out_group_base & 1) * 4u)) & 0x0Fu;
} else {
const int zp_index = row_idx * zp_stride_total + out_group_base;
zp_n = zps_row_start[zp_index];
@@ -505,7 +505,7 @@ struct QuantizedBlockLoaderZp {
if (bits == 4) {
const device uint8_t* zp_ptr = zps_row_start + (g >> 1);
uint8_t zp_b = *zp_ptr;
- zp_n = (g & 1) ? ((zp_b >> 4) & 0x0F) : (zp_b & 0x0F);
+ zp_n = (uint(zp_b) >> (uint(g & 1) * 4u)) & 0x0Fu;
} else {
zp_n = zps_row_start[g];
}
diff --git a/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmm_transposed_test.rs b/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmm_transposed_test.rs
index 67f93e151..909c00a02 100644
--- a/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmm_transposed_test.rs
+++ b/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmm_transposed_test.rs
@@ -7,11 +7,17 @@ use backend_uzu::{
cpu::Cpu,
},
};
+use criterion::{BenchmarkId, Criterion, Throughput};
use half::{bf16, f16};
+use itertools::iproduct;
use num_traits::Float;
+use rand::{RngExt, SeedableRng, rngs::SmallRng};
use super::{Input, check_tolerance, pack_weights_u32, pack_zero_points};
-use crate::{common::helpers::alloc_buffer_with_data, uzu_test};
+use crate::{
+ common::{helpers::alloc_buffer_with_data, type_short_name},
+ uzu_bench, uzu_test,
+};
fn make_input_basic<T: ArrayElement + Float>(
m: usize,
@@ -642,3 +648,115 @@ mod hadamard {
fn test_f16_gs128_4bit_mlx: f16, 128, 4, false, true;
);
}
+
+fn bench_qmm_transposed_typed<B: Backend, T: ArrayElement + Float>(
+ c: &mut Criterion,
+ context: &B::Context,
+ label: &str,
+ group_size: u32,
+ bits: u32,
+ use_zero_points: bool,
+ use_mlx_quant: bool,
+) {
+ // Use the dispatcher-selected tile configs: BM=8 small tile for M<48, big tile for M>=48.
+ // We always use the BM=8 small tile kernel for M in 4..=47 to match the dispatch threshold.
+ let block_size: usize = if bits == 4 { 512 } else { 256 };
+
+ for (m, n, k) in iproduct!([4usize, 5, 6, 7, 8, 16, 32, 48, 64], [2048usize, 4096, 14336], [2048usize, 4096, 14336]) {
+ if n % 32 != 0 || k % block_size != 0 {
+ continue;
+ }
+
+ // Pick tile based on M: small (BM=8) for M<48, big (BM=32) for M>=48
+ let (bm, bk, bn, wm, wn) = if m < 48 {
+ (8u32, 32u32, 32u32, 1u32, 1u32)
+ } else {
+ (32u32, 32u32, 32u32, 2u32, 2u32)
+ };
+
+ let num_groups = k.div_ceil(group_size as usize);
+ let mut rng = SmallRng::seed_from_u64(42);
+
+ let kernel = <<B as Backend>::Kernels as Kernels>::QuantizedMatmulQmmTransposedKernel::new(
+ context,
+ T::data_type(),
+ group_size,
+ bits,
+ bm,
+ bk,
+ bn,
+ wm,
+ wn,
+ use_zero_points,
+ use_mlx_quant,
+ false,
+ n % bn as usize == 0,
+ )
+ .unwrap();
+
+ let w_buf = alloc_buffer_with_data::<B, u32>(
+ context,
+ &(0..n * k * bits as usize / 32).map(|_| rng.random_range(0..u32::MAX)).collect::<Vec<_>>(),
+ );
+ let scales_buf = alloc_buffer_with_data::<B, T>(
+ context,
+ &(0..n * num_groups).map(|_| T::from(rng.random_range(0.01f32..1.0f32)).unwrap()).collect::<Vec<_>>(),
+ );
+ let x_buf = alloc_buffer_with_data::<B, T>(
+ context,
+ &(0..m * k).map(|_| T::from(rng.random_range(-1.0f32..1.0f32)).unwrap()).collect::<Vec<_>>(),
+ );
+ let mut y_buf = context.create_buffer(m * n * std::mem::size_of::<T>()).unwrap();
+
+ let zp_stride = if bits == 4 { (num_groups + 1) / 2 } else { num_groups };
+ let zp_buf = use_zero_points.then(|| {
+ alloc_buffer_with_data::<B, u8>(
+ context,
+ &(0..n * zp_stride).map(|_| rng.random_range(0u8..u8::MAX)).collect::<Vec<_>>(),
+ )
+ });
+ let bias_buf = use_mlx_quant.then(|| {
+ alloc_buffer_with_data::<B, T>(
+ context,
+ &(0..n * num_groups).map(|_| T::from(rng.random_range(-0.5f32..0.5f32)).unwrap()).collect::<Vec<_>>(),
+ )
+ });
+
+ let mut group = c.benchmark_group(format!("{}/Kernel/QmmTransposed/{}", type_short_name::<B>(), label));
+ group.throughput(Throughput::Elements((m * n * k) as u64));
+ group.bench_function(BenchmarkId::from_parameter(format!("M[{m}]N[{n}]K[{k}]")), |b| {
+ b.iter_custom(|n_iters| {
+ let mut encoder = Encoder::<B>::new(context).unwrap();
+ for _ in 0..n_iters {
+ kernel.encode(
+ &w_buf,
+ &scales_buf,
+ zp_buf.as_ref(),
+ bias_buf.as_ref(),
+ &x_buf,
+ &mut y_buf,
+ None::<&B::Buffer>,
+ k as u32,
+ n as u32,
+ m as u32,
+ &mut encoder,
+ );
+ }
+ encoder.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()
+ })
+ });
+ drop(group);
+ }
+}
+
+#[uzu_bench]
+fn bench_qmm_transposed(c: &mut Criterion) {
+ for_each_backend!(|B| {
+ let context = <B as Backend>::Context::new().unwrap();
+ bench_qmm_transposed_typed::<B, bf16>(c, &context, "Mlx_BF16_gs64", 64, 4, false, true);
+ bench_qmm_transposed_typed::<B, bf16>(c, &context, "ZP_BF16_gs64", 64, 4, true, false);
+ bench_qmm_transposed_typed::<B, bf16>(c, &context, "Mlx_BF16_gs128", 128, 4, false, true);
+ bench_qmm_transposed_typed::<B, bf16>(c, &context, "ZP_BF16_gs128", 128, 4, true, false);
+ bench_qmm_transposed_typed::<B, f16>(c, &context, "ZP_F16_gs64", 64, 4, true, false);
+ });
+}
diff --git a/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmv_fast_test.rs b/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmv_fast_test.rs
index ff5f2ebce..d378ea511 100644
--- a/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmv_fast_test.rs
+++ b/crates/backend-uzu/tests/unit/kernel/quant_matmul/qmv_fast_test.rs
@@ -12,7 +12,6 @@ use backend_uzu::{
};
use criterion::{BenchmarkId, Criterion, Throughput};
use half::{bf16, f16};
-use itertools::iproduct;
use num_traits::Float;
use rand::{RngExt, SeedableRng, rngs::SmallRng};
@@ -328,82 +327,87 @@ fn bench_qmv_fast_typed<B: Backend, T: ArrayElement + Float>(
256
};
- for (m, n, k) in iproduct!([1, 2, 3, 4], [1024, 2048, 4096, 14336, 65536], [1024, 2048, 4096, 8192, 14336]) {
+ let nk_pairs: &[(usize, usize)] = &[(4096, 4096), (4096, 14336), (14336, 4096), (14336, 14336)];
+ for &(n, k) in nk_pairs {
if n % 8 != 0 || k % block_size != 0 {
continue;
}
+ for m in [1usize, 2, 4, 8] {
+ let num_groups = k.div_ceil(group_size as usize);
+ let mut rng = SmallRng::seed_from_u64(42);
- let num_groups = k.div_ceil(group_size as usize);
- let mut rng = SmallRng::seed_from_u64(42);
-
- let kernel = <<B as Backend>::Kernels as Kernels>::QuantizedMatmulQmvFastKernel::new(
- context,
- T::data_type(),
- group_size,
- bits,
- use_zero_points,
- use_mlx_quant,
- false,
- )
- .unwrap();
-
- let w_buf = alloc_buffer_with_data::<B, u32>(
- context,
- &gen_random::<u32, _>(&mut rng, 0..u32::MAX, n * k * bits as usize / 32),
- );
- let scales_buf = alloc_buffer_with_data::<B, T>(
- context,
- &gen_random::<f32, _>(&mut rng, 0.01..1.0, n * num_groups)
- .iter()
- .map(|&v| T::from(v).unwrap())
- .collect::<Vec<_>>(),
- );
- let x_buf = alloc_buffer_with_data::<B, T>(
- context,
- &gen_random::<f32, _>(&mut rng, -1.0..1.0, m * k).iter().map(|&v| T::from(v).unwrap()).collect::<Vec<_>>(),
- );
- let mut y_buf = context.create_buffer(m * n * std::mem::size_of::<T>()).unwrap();
-
- let zp_buf = use_zero_points.then(|| {
- let zp_stride = if bits == 4 {
- (num_groups + 1) / 2
- } else {
- num_groups
- };
- alloc_buffer_with_data::<B, u8>(context, &gen_random::<u8, _>(&mut rng, 0..u8::MAX, n * zp_stride))
- });
- let bias_buf = use_mlx_quant.then(|| {
- alloc_buffer_with_data::<B, T>(
+ let kernel = <<B as Backend>::Kernels as Kernels>::QuantizedMatmulQmvFastKernel::new(
+ context,
+ T::data_type(),
+ group_size,
+ bits,
+ use_zero_points,
+ use_mlx_quant,
+ false,
+ )
+ .unwrap();
+
+ let w_buf = alloc_buffer_with_data::<B, u32>(
context,
- &gen_random::<f32, _>(&mut rng, -0.5..0.5, n * num_groups)
+ &gen_random::<u32, _>(&mut rng, 0..u32::MAX, n * k * bits as usize / 32),
+ );
+ let scales_buf = alloc_buffer_with_data::<B, T>(
+ context,
+ &gen_random::<f32, _>(&mut rng, 0.01..1.0, n * num_groups)
.iter()
.map(|&v| T::from(v).unwrap())
.collect::<Vec<_>>(),
- )
- });
-
- group.throughput(Throughput::Elements((m * n * k) as u64));
- group.bench_function(BenchmarkId::from_parameter(format!("M[{m}]N[{n}]K[{k}]")), |b| {
- b.iter_custom(|n_iters| {
- let mut encoder = Encoder::<B>::new(context).unwrap();
- for _ in 0..n_iters {
- kernel.encode(
- &w_buf,
- &scales_buf,
- zp_buf.as_ref(),
- bias_buf.as_ref(),
- &x_buf,
- &mut y_buf,
- None::<&B::Buffer>,
- k as u32,
- n as u32,
- m as u32,
- &mut encoder,
- );
- }
- encoder.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()
- })
- });
+ );
+ let x_buf = alloc_buffer_with_data::<B, T>(
+ context,
+ &gen_random::<f32, _>(&mut rng, -1.0..1.0, m * k)
+ .iter()
+ .map(|&v| T::from(v).unwrap())
+ .collect::<Vec<_>>(),
+ );
+ let mut y_buf = context.create_buffer(m * n * std::mem::size_of::<T>()).unwrap();
+
+ let zp_buf = use_zero_points.then(|| {
+ let zp_stride = if bits == 4 {
+ (num_groups + 1) / 2
+ } else {
+ num_groups
+ };
+ alloc_buffer_with_data::<B, u8>(context, &gen_random::<u8, _>(&mut rng, 0..u8::MAX, n * zp_stride))
+ });
+ let bias_buf = use_mlx_quant.then(|| {
+ alloc_buffer_with_data::<B, T>(
+ context,
+ &gen_random::<f32, _>(&mut rng, -0.5..0.5, n * num_groups)
+ .iter()
+ .map(|&v| T::from(v).unwrap())
+ .collect::<Vec<_>>(),
+ )
+ });
+
+ group.throughput(Throughput::Elements((m * n * k) as u64));
+ group.bench_function(BenchmarkId::from_parameter(format!("M[{m}]N[{n}]K[{k}]")), |b| {
+ b.iter_custom(|n_iters| {
+ let mut encoder = Encoder::<B>::new(context).unwrap();
+ for _ in 0..n_iters {
+ kernel.encode(
+ &w_buf,
+ &scales_buf,
+ zp_buf.as_ref(),
+ bias_buf.as_ref(),
+ &x_buf,
+ &mut y_buf,
+ None::<&B::Buffer>,
+ k as u32,
+ n as u32,
+ m as u32,
+ &mut encoder,
+ );
+ }
+ encoder.end_encoding().submit().wait_until_completed().unwrap().gpu_execution_time()
+ })
+ });
+ }
}
}
@@ -411,7 +415,12 @@ fn bench_qmv_fast_typed<B: Backend, T: ArrayElement + Float>(
fn bench_qmv_fast(c: &mut Criterion) {
for_each_backend!(|B| {
let context = <B as Backend>::Context::new().unwrap();
+ bench_qmv_fast_typed::<B, bf16>(c, &context, "Mlx_BF16_gs32", 32, 4, false, true);
+ bench_qmv_fast_typed::<B, bf16>(c, &context, "ZP_BF16_gs32", 32, 4, true, false);
+ bench_qmv_fast_typed::<B, bf16>(c, &context, "Mlx_BF16_gs64", 64, 4, false, true);
+ bench_qmv_fast_typed::<B, bf16>(c, &context, "ZP_BF16_gs64", 64, 4, true, false);
bench_qmv_fast_typed::<B, bf16>(c, &context, "Mlx_BF16_gs128", 128, 4, false, true);
+ bench_qmv_fast_typed::<B, bf16>(c, &context, "ZP_BF16_gs128", 128, 4, true, false);
bench_qmv_fast_typed::<B, f16>(c, &context, "ZP_F16_gs64", 64, 4, true, false);
bench_qmv_fast_typed::<B, bf16>(c, &context, "ZP_BF16_gs64_8b", 64, 8, true, false);
});