A high-performance inference engine for AI models
activation quantization
eugenebe76599ed8c2
diff --git a/crates/backend-uzu/src/backends/common/context.rs b/crates/backend-uzu/src/backends/common/context.rsindex 9dadfcf0b..640ab6b99 100644--- a/crates/backend-uzu/src/backends/common/context.rs+++ b/crates/backend-uzu/src/backends/common/context.rs@@ -1,6 +1,6 @@use std::{path::Path, sync::Arc};-use crate::backends::common::{Allocation, AllocationPool, AllocationType, Backend, CommandBuffer};+use crate::backends::common::{Allocation, AllocationPool, AllocationType, Backend, CommandBuffer, DeviceCapabilities};pub trait Context: Sized + Send + Sync {type Backend: Backend<Context = Self>;@@ -43,5 +43,5 @@ pub trait Context: Sized + Send + Sync {fn stop_capture(&self) -> Result<(), <Self::Backend as Backend>::Error>;- fn sparse_buffers_supported(&self) -> bool;+ fn device_capabilities(&self) -> DeviceCapabilities;}diff --git a/crates/backend-uzu/src/backends/common/device_capabilities.rs b/crates/backend-uzu/src/backends/common/device_capabilities.rsnew file mode 100644index 000000000..8125a319a--- /dev/null+++ b/crates/backend-uzu/src/backends/common/device_capabilities.rs@@ -0,0 +1,10 @@+use bitflags::bitflags;++bitflags! {+ #[repr(transparent)]+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+ pub struct DeviceCapabilities: u32 {+ const SPARSE_BUFFERS = 1 << 0;+ const NATIVE_INT8_MATMUL = 1 << 1;+ }+}diff --git a/crates/backend-uzu/src/backends/common/gpu_types/gemm.rs b/crates/backend-uzu/src/backends/common/gpu_types/gemm.rsindex 5d1ebf676..92e1b7877 100644--- a/crates/backend-uzu/src/backends/common/gpu_types/gemm.rs+++ b/crates/backend-uzu/src/backends/common/gpu_types/gemm.rs@@ -1,6 +1,13 @@use bitflags::bitflags;use derive_more::Display;+#[repr(C)]+#[derive(Debug, Display, Clone, Copy, PartialEq, Eq, Hash)]+pub enum GemmAPrologueKind {+ FullPrecision,+ Int8Symmetric,+}+#[repr(C)]#[derive(Debug, Display, Clone, Copy, PartialEq, Eq, Hash)]pub enum GemmBPrologueKind {diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rsindex 925812443..1de408fa2 100644--- a/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rs+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/arguments.rs@@ -1,9 +1,8 @@-use super::{d_ops::MatmulDOps, matmul_b::MatmulB};+use super::{d_ops::MatmulDOps, matmul_a::MatmulA, matmul_b::MatmulB};use crate::backends::common::{Allocation, Backend, BufferArg};pub struct MatmulArguments<'a, 'b, 'd, B: Backend, TB: BufferArg<'b, B> = &'b Allocation<B>> {- pub a: &'a Allocation<B>,- pub a_offset: usize,+ pub a: MatmulA<'a, B>,pub b: MatmulB<'b, B, TB>,pub b_leading_dimension: Option<u32>,pub b_transpose: bool,diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/error.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/error.rsindex 791ef5b61..c98795a5a 100644--- a/crates/backend-uzu/src/backends/common/kernel/matmul/error.rs+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/error.rs@@ -20,6 +20,11 @@ pub enum MatmulError<B: Backend> {UnsupportedLayout {path: &'static str,},+ #[error("Incompatible A operand for {path}: {reason}")]+ IncompatibleA {+ path: &'static str,+ reason: &'static str,+ },#[error("Backend error: {0}")]BackendError(#[source] B::Error),}diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/matmul_a.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/matmul_a.rsnew file mode 100644index 000000000..49565bf8c--- /dev/null+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/matmul_a.rs@@ -0,0 +1,25 @@+use crate::backends::common::{Allocation, Backend, gpu_types::gemm::GemmAPrologueKind};++pub enum MatmulA<'a, B: Backend> {+ FullPrecision {+ values: &'a Allocation<B>,+ offset: usize,+ },+ Int8Symmetric {+ values: &'a Allocation<B>,+ scales: &'a Allocation<B>,+ },+}++impl<'a, B: Backend> MatmulA<'a, B> {+ pub fn prologue_kind(&self) -> GemmAPrologueKind {+ match self {+ Self::FullPrecision {+ ..+ } => GemmAPrologueKind::FullPrecision,+ Self::Int8Symmetric {+ ..+ } => GemmAPrologueKind::Int8Symmetric,+ }+ }+}diff --git a/crates/backend-uzu/src/backends/common/kernel/matmul/mod.rs b/crates/backend-uzu/src/backends/common/kernel/matmul/mod.rsindex fbe1265af..7e8d91981 100644--- a/crates/backend-uzu/src/backends/common/kernel/matmul/mod.rs+++ b/crates/backend-uzu/src/backends/common/kernel/matmul/mod.rs@@ -2,10 +2,12 @@ mod arguments;mod d_ops;mod error;mod kernel;+mod matmul_a;mod matmul_b;pub use arguments::MatmulArguments;pub use d_ops::MatmulDOps;pub use error::MatmulError;pub use kernel::MatmulKernel;+pub use matmul_a::MatmulA;pub use matmul_b::MatmulB;diff --git a/crates/backend-uzu/src/backends/common/mod.rs b/crates/backend-uzu/src/backends/common/mod.rsindex 541870438..d3b57f26d 100644--- a/crates/backend-uzu/src/backends/common/mod.rs+++ b/crates/backend-uzu/src/backends/common/mod.rs@@ -3,6 +3,7 @@ mod backend;mod buffer;mod command_buffer;mod context;+mod device_capabilities;mod encoder;pub mod gpu_types;mod hazard_tracker;@@ -22,6 +23,7 @@ pub use command_buffer::{CommandBufferInitial, CommandBufferPending,};pub use context::Context;+pub use device_capabilities::DeviceCapabilities;pub use encoder::{Completed, Encoder, Executable, Pending};pub use hazard_tracker::Access;pub use kernel::Kernels;diff --git a/crates/backend-uzu/src/backends/cpu/context.rs b/crates/backend-uzu/src/backends/cpu/context.rsindex 31203ae91..cbb9cf074 100644--- a/crates/backend-uzu/src/backends/cpu/context.rs+++ b/crates/backend-uzu/src/backends/cpu/context.rs@@ -5,7 +5,7 @@ use std::{};use crate::backends::{- common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context},+ common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context, DeviceCapabilities},cpu::{Cpu, command_buffer::CpuCommandBufferInitial, dense_buffer::CpuBuffer, error::CpuError},};@@ -82,7 +82,7 @@ impl Context for CpuContext {Err(CpuError::NotSupported)}- fn sparse_buffers_supported(&self) -> bool {- false+ fn device_capabilities(&self) -> DeviceCapabilities {+ DeviceCapabilities::empty()}}diff --git a/crates/backend-uzu/src/backends/cpu/kernel/hadamard_transform/hadamard_transform.rs b/crates/backend-uzu/src/backends/cpu/kernel/hadamard_transform/hadamard_transform.rsindex 820eec4b0..d43c3cdba 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/hadamard_transform/hadamard_transform.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/hadamard_transform/hadamard_transform.rs@@ -7,7 +7,7 @@ use crate::{backends::common::gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, HadamardTransformOrder},};-fn hadamard_transform(values: &mut [f32; HADAMARD_TRANSFORM_BLOCK_SIZE]) {+pub(crate) fn hadamard_transform(values: &mut [f32; HADAMARD_TRANSFORM_BLOCK_SIZE]) {let mut stride = 1;while stride < HADAMARD_TRANSFORM_BLOCK_SIZE {for lane in 0..HADAMARD_TRANSFORM_BLOCK_SIZE {diff --git a/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs b/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rsindex c0341077c..0d46008b1 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/matmul/kernel.rs@@ -2,11 +2,11 @@ use super::reference::{WeightData, read_f32, write_f32};use crate::{backends::{common::{- AsBufferRangeMut, AsBufferRangeRef, Backend, BufferArg, Encoder, Kernels,- gpu_types::HadamardTransformOrder,+ Allocation, AsBufferRangeMut, AsBufferRangeRef, Backend, BufferArg, Encoder, Kernels,+ gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, HadamardTransformOrder, QuantizationMode},kernel::{- HadamardTransformKernel,- matmul::{MatmulArguments, MatmulError, MatmulKernel},+ HadamardTransformKernel, TensorAddBiasKernel,+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulError, MatmulKernel},},},cpu::{Cpu, context::CpuContext, error::CpuError},@@ -20,6 +20,7 @@ pub struct MatmulCpuKernel {input_data_type: DataType,output_data_type: DataType,hadamard: <<Cpu as Backend>::Kernels as Kernels>::HadamardTransformKernel,+ bias_add: <<Cpu as Backend>::Kernels as Kernels>::TensorAddBiasKernel,}impl MatmulKernel for MatmulCpuKernel {@@ -41,11 +42,19 @@ impl MatmulKernel for MatmulCpuKernel {output_data_type,HadamardTransformOrder::Output,)?;+ let bias_add = <<Cpu as Backend>::Kernels as Kernels>::TensorAddBiasKernel::new(+ context,+ output_data_type,+ weights_data_type,+ true,+ false,+ )?;Ok(Self {weights_data_type,input_data_type,output_data_type,hadamard,+ bias_add,})}@@ -62,7 +71,6 @@ impl MatmulKernel for MatmulCpuKernel {let MatmulArguments {a,- a_offset,b,b_leading_dimension,b_transpose,@@ -81,9 +89,62 @@ impl MatmulKernel for MatmulCpuKernel {let input_data_type = self.input_data_type;let output_data_type = self.output_data_type;- let a_buffer_range = a.as_buffer_range_ref();- let a_byte_off = a_buffer_range.range().start + a_offset * input_data_type.size_in_bytes();- let a_ptr = SendPtr(unsafe { &*a_buffer_range.buffer().get() }.as_ptr().wrapping_byte_add(a_byte_off));+ #[derive(Clone, Copy)]+ enum AData {+ FullPrecision(SendPtr<u8>),+ Int8 {+ values: SendPtr<u8>,+ scales: SendPtr<u8>,+ group_size: usize,+ },+ }+ let a_data = match a {+ MatmulA::FullPrecision {+ values,+ offset,+ } => {+ let range = values.as_buffer_range_ref();+ let byte_offset = range.range().start + offset * input_data_type.size_in_bytes();+ AData::FullPrecision(SendPtr(unsafe { &*range.buffer().get() }.as_ptr().wrapping_byte_add(byte_offset)))+ },+ MatmulA::Int8Symmetric {+ values,+ scales,+ } => {+ let weight_gs_ok = matches!(b.group_size(), Some(32 | 64 | 128));+ let weights_ok = matches!(+ b,+ MatmulB::ScaleSymmetricDequant {+ mode: QuantizationMode::U4 | QuantizationMode::U8,+ ..+ } | MatmulB::ScaleBiasDequant {+ mode: QuantizationMode::U4 | QuantizationMode::U8,+ ..+ } | MatmulB::ScaleZeroPointDequant {+ mode: QuantizationMode::U4 | QuantizationMode::U8,+ ..+ }+ );+ if !weight_gs_ok || !weights_ok {+ return Err(MatmulError::IncompatibleA {+ path: "CpuMatmul",+ reason: "symmetric int8 activations require unsigned 4/8-bit quantized weights with group size 32/64/128",+ }+ .into());+ }+ let values_range = values.as_buffer_range_ref();+ let scales_range = scales.as_buffer_range_ref();+ AData::Int8 {+ values: SendPtr(+ unsafe { &*values_range.buffer().get() }.as_ptr().wrapping_byte_add(values_range.range().start),+ ),+ scales: SendPtr(+ unsafe { &*scales_range.buffer().get() }.as_ptr().wrapping_byte_add(scales_range.range().start),+ ),+ group_size: HADAMARD_TRANSFORM_BLOCK_SIZE,+ }+ },+ };let bias_ptr = bias_alloc.map(|bias| {let r = bias.as_buffer_range_ref();SendPtr(unsafe { &*r.buffer().get() }.as_ptr().wrapping_byte_add(r.range().start))@@ -99,6 +160,7 @@ impl MatmulKernel for MatmulCpuKernel {let weight_data = WeightData::from_b(b, b_leading_dimension, b_transpose, k_u, n_u);+ let bias_after_rht = post_rht.is_some();let command_buffer = encoder.as_command_buffer_mut();command_buffer.push_command(move || {let quant_layout = match &weight_data {@@ -135,7 +197,20 @@ impl MatmulKernel for MatmulCpuKernel {};let mut accumulator = 0.0f32;for inner in 0..k_u {- let a_value = read_f32(a_ptr.as_ptr(), input_data_type, row * k_u + inner);+ let a_value = match a_data {+ AData::FullPrecision(ptr) => read_f32(ptr.as_ptr(), input_data_type, row * k_u + inner),+ AData::Int8 {+ values,+ scales,+ group_size,+ } => {+ let groups = k_u.div_ceil(group_size);+ let group = inner / group_size;+ let q = *(values.as_ptr() as *const i8).add(row * k_u + inner) as f32;+ let scale = *(scales.as_ptr() as *const f32).add(row * groups + group);+ q * scale+ },+ };let b_value = match &weight_data {WeightData::FullPrecision {ptr,@@ -163,7 +238,8 @@ impl MatmulKernel for MatmulCpuKernel {let word_index = weight_linear_index / pack_factor;let bit_offset = (weight_linear_index % pack_factor) * 4;let w = weights.as_ptr() as *const u32;- ((w.add(word_index).read_unaligned() >> bit_offset) & 0xF) as f32+ let nibble = ((w.add(word_index).read_unaligned() >> bit_offset) & 0xF) as u8;+ f32::from(nibble)} else {let word_index = weight_linear_index / pack_factor;let bit_offset = (weight_linear_index % pack_factor) * 8;@@ -176,8 +252,9 @@ impl MatmulKernel for MatmulCpuKernel {weights_data_type,b_col * num_groups_k + group_index,);- let bias_term = if let Some(zp) = zero_points {- let zero_point = if *bits == 4 {+ let midpoint = (1u32 << (bits - 1)) as f32;+ let zero_point = zero_points.map(|zp| {+ if *bits == 4 {let byte_index = b_col * zero_point_stride + (group_index >> 1);let byte_value = *zp.as_ptr().add(byte_index);if (group_index & 1) == 0 {@@ -187,12 +264,13 @@ impl MatmulKernel for MatmulCpuKernel {}} else {*zp.as_ptr().add(b_col * zero_point_stride + group_index) as f32- };- -scale * zero_point+ }+ });+ let bias_term = if let Some(zp) = zero_point {+ -scale * zp} else if let Some(b) = biases {read_f32(b.as_ptr(), weights_data_type, b_col * num_groups_k + group_index)} else {- let midpoint = (1u32 << (bits - 1)) as f32;-scale * midpoint};scale * quantized_value + bias_term@@ -206,7 +284,7 @@ impl MatmulKernel for MatmulCpuKernel {if accumulate {value += read_f32(d_ptr.as_ptr(), output_data_type, output_index);}- if let Some(bias) = bias_ptr {+ if !bias_after_rht && let Some(bias) = bias_ptr {value += read_f32(bias.as_ptr(), weights_data_type, col);}if let Some(cap) = soft_cap {@@ -219,7 +297,19 @@ impl MatmulKernel for MatmulCpuKernel {});if let Some(factors) = post_rht {- self.hadamard.encode(d, factors, n, m, encoder);+ self.hadamard.encode(&mut *d, factors, n, m, encoder);+ if let Some(bias) = bias_alloc {+ let output_length = m.checked_mul(n).expect("matmul output length must fit in u32");+ self.bias_add.encode(+ None::<&Allocation<Cpu>>,+ bias,+ None::<&Allocation<Cpu>>,+ &mut *d,+ n,+ output_length,+ encoder,+ );+ }}Ok(())diff --git a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/mod.rsindex 046f70af0..2867bd11e 100644--- a/crates/backend-uzu/src/backends/cpu/kernel/mod.rs+++ b/crates/backend-uzu/src/backends/cpu/kernel/mod.rs@@ -14,6 +14,7 @@ mod moe;mod normalization;mod pooling;mod radix_top_k_small;+pub(crate) mod rht_quantize_activations;mod sampling;mod short_conv;mod softmax;diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rht_quantize_activations/mod.rs b/crates/backend-uzu/src/backends/cpu/kernel/rht_quantize_activations/mod.rsnew file mode 100644index 000000000..d463aeba0--- /dev/null+++ b/crates/backend-uzu/src/backends/cpu/kernel/rht_quantize_activations/mod.rs@@ -0,0 +1,21 @@+pub mod rht_quantize_activations;++pub const INT8_SYMMETRIC_QUANTIZATION_MAXIMUM: f32 = 127.0;++pub fn min_max_symmetric_divisor(values: &[f32]) -> f32 {+ let (min, max) =+ values.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(min, max), &value| (min.min(value), max.max(value)));+ let magnitude = min.abs().max(max.abs());+ if magnitude.is_finite() && magnitude > 0.0 {+ magnitude / INT8_SYMMETRIC_QUANTIZATION_MAXIMUM+ } else {+ 1.0+ }+}++pub fn quantize_symmetric_i8(+ value: f32,+ divisor: f32,+) -> i8 {+ (value / divisor).round().clamp(-INT8_SYMMETRIC_QUANTIZATION_MAXIMUM, INT8_SYMMETRIC_QUANTIZATION_MAXIMUM) as i8+}diff --git a/crates/backend-uzu/src/backends/cpu/kernel/rht_quantize_activations/rht_quantize_activations.rs b/crates/backend-uzu/src/backends/cpu/kernel/rht_quantize_activations/rht_quantize_activations.rsnew file mode 100644index 000000000..87e6e4fca--- /dev/null+++ b/crates/backend-uzu/src/backends/cpu/kernel/rht_quantize_activations/rht_quantize_activations.rs@@ -0,0 +1,54 @@+use half::bf16;+use num_traits::{Float, NumCast};+use proc_macros::kernel;++use super::{+ super::hadamard_transform::hadamard_transform::hadamard_transform, min_max_symmetric_divisor, quantize_symmetric_i8,+};+use crate::{array::ArrayElement, backends::common::gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE};++#[kernel(RHTQuantizeActivations)]+#[variants(InputT, f32, bf16)]+pub fn activations_prepare<InputT: ArrayElement + Float>(+ input: *const InputT,+ q_out: *mut i8,+ scales_out: *mut f32,+ rht_factors: *const i32,+ batch_size: u32,+ element_count: u32,+ group_size: u32,+) {+ let rows = batch_size as usize;+ let columns = element_count as usize;+ let group_size = group_size as usize;+ assert!(columns.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE));+ assert!(group_size > 0 && columns.is_multiple_of(group_size));++ let groups = columns.div_ceil(group_size);+ let mut prepared = vec![0.0f32; columns];+ for row in 0..rows {+ for block_start in (0..columns).step_by(HADAMARD_TRANSFORM_BLOCK_SIZE) {+ let mut block = [0.0f32; HADAMARD_TRANSFORM_BLOCK_SIZE];+ for lane in 0..HADAMARD_TRANSFORM_BLOCK_SIZE {+ let index = block_start + lane;+ let value: f32 = NumCast::from(unsafe { *input.add(row * columns + index) }).unwrap();+ let factor = unsafe { *rht_factors.add(index) } as f32;+ block[lane] = value * factor;+ }+ hadamard_transform(&mut block);+ prepared[block_start..block_start + HADAMARD_TRANSFORM_BLOCK_SIZE].copy_from_slice(&block);+ }++ for group in 0..groups {+ let start = group * group_size;+ let end = (start + group_size).min(columns);+ let slice = &prepared[start..end];+ let divisor = min_max_symmetric_divisor(slice);+ unsafe { *scales_out.add(row * groups + group) = divisor };+ for index in start..end {+ let q = quantize_symmetric_i8(prepared[index], divisor);+ unsafe { *q_out.add(row * columns + index) = q };+ }+ }+ }+}diff --git a/crates/backend-uzu/src/backends/cpu/mod.rs b/crates/backend-uzu/src/backends/cpu/mod.rsindex b98cb0309..5628b5d28 100644--- a/crates/backend-uzu/src/backends/cpu/mod.rs+++ b/crates/backend-uzu/src/backends/cpu/mod.rs@@ -4,7 +4,7 @@ mod command_buffer;mod context;mod dense_buffer;mod error;-mod kernel;+pub(crate) mod kernel;mod sparse;pub use backend::Cpu;diff --git a/crates/backend-uzu/src/backends/metal/context.rs b/crates/backend-uzu/src/backends/metal/context.rsindex 8d0dc33b4..81bf19bc6 100644--- a/crates/backend-uzu/src/backends/metal/context.rs+++ b/crates/backend-uzu/src/backends/metal/context.rs@@ -25,7 +25,7 @@ use super::{metal_extensions::{DeviceExt, LibraryPipelineExtensions},};use crate::backends::{- common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context},+ common::{Allocation, AllocationPool, AllocationType, Allocator, Backend, Context, DeviceCapabilities},metal::{command_buffer::MetalCommandBufferInitial,sparse::{MetalSparseBuffer, MetalSparseHeapPool, MetalSparseMappingOpsBatch},@@ -234,7 +234,14 @@ impl Context for MetalContext {Ok(())}- fn sparse_buffers_supported(&self) -> bool {- self.device.supports_placement_sparse_resources()+ fn device_capabilities(&self) -> DeviceCapabilities {+ let mut capabilities = DeviceCapabilities::empty();+ if self.device.supports_placement_sparse_resources() {+ capabilities |= DeviceCapabilities::SPARSE_BUFFERS;+ }+ if self.device.supports_mxu() {+ capabilities |= DeviceCapabilities::NATIVE_INT8_MATMUL;+ }+ capabilities}}diff --git a/crates/backend-uzu/src/backends/metal/kernel/generated/gemm.h b/crates/backend-uzu/src/backends/metal/kernel/generated/gemm.hindex 80daae838..c47ed59de 100644--- a/crates/backend-uzu/src/backends/metal/kernel/generated/gemm.h+++ b/crates/backend-uzu/src/backends/metal/kernel/generated/gemm.h@@ -5,6 +5,11 @@using namespace metal;namespace uzu::gemm {+enum class GemmAPrologueKind : uint32_t {+ FullPrecision = 0,+ Int8Symmetric = 1,+};+enum class GemmBPrologueKind : uint32_t {FullPrecision = 0,ScaleBiasDequant = 1,diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.hindex 5945254fe..71eaa9816 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.h+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/fragment.h@@ -143,7 +143,12 @@ struct Fragment {template <class Fn, class... Fragments>METAL_FUNC static void zip_for_each_coord(const ushort simd_lane_id, Fn fn, thread Fragments&... fragments) {static_assert(sizeof...(Fragments) > 0, "zip_for_each_coord needs at least one fragment");- static_assert((metal::is_same_v<Fragment, Fragments> && ...), "zipped fragments must have the same type");+ static_assert(+ ((Fragments::ROW_FRAGMENTS == ROW_FRAGMENTS && Fragments::COL_FRAGMENTS == COL_FRAGMENTS &&+ metal::is_same_v<typename Fragments::FragmentOpsType, Ops>) &&+ ...),+ "zipped fragments must share this fragment's layout"+ );const short2 position = get_position(simd_lane_id);for_each_fragment([&](auto fragment_row, auto fragment_col) {diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/mxu_fragment_ops.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/mxu_fragment_ops.hindex 6f571fe6e..d4e77f502 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/common/mxu_fragment_ops.h+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/common/mxu_fragment_ops.h@@ -70,6 +70,52 @@ struct MxuFragmentOps {}}+ template <typename CooperativeTensor, typename U>+ METAL_FUNC static void load_paired_vectors(+ thread CooperativeTensor& cooperative,+ const thread ThreadVector<U>& vector_0,+ const thread ThreadVector<U>& vector_1+ ) {+ if constexpr (RELAXED) {+ METAL_PRAGMA_UNROLL+ for (ushort i = 0; i < ELEMENTS_PER_THREAD; i++) {+ cooperative[i] = vector_0[i];+ cooperative[ELEMENTS_PER_THREAD + i] = vector_1[i];+ }+ } else {+ METAL_PRAGMA_UNROLL+ for (ushort i = 0; i < 4; i++) {+ cooperative[i] = vector_0[i];+ cooperative[4 + i] = vector_1[i];+ cooperative[8 + i] = vector_0[4 + i];+ cooperative[12 + i] = vector_1[4 + i];+ }+ }+ }++ template <typename CooperativeTensor, typename U>+ METAL_FUNC static void store_paired_vectors(+ thread CooperativeTensor& cooperative,+ thread ThreadVector<U>& vector_0,+ thread ThreadVector<U>& vector_1+ ) {+ if constexpr (RELAXED) {+ METAL_PRAGMA_UNROLL+ for (ushort i = 0; i < ELEMENTS_PER_THREAD; i++) {+ vector_0[i] = cooperative[i];+ vector_1[i] = cooperative[ELEMENTS_PER_THREAD + i];+ }+ } else {+ METAL_PRAGMA_UNROLL+ for (ushort i = 0; i < 4; i++) {+ vector_0[i] = cooperative[i];+ vector_1[i] = cooperative[4 + i];+ vector_0[4 + i] = cooperative[8 + i];+ vector_1[4 + i] = cooperative[12 + i];+ }+ }+ }+// MPP has no valid 16x16x16 op; fragment_mma pairs fragments into 16x32.template <bool ACCUMULATE,@@ -107,40 +153,12 @@ struct MxuFragmentOps {marshal_inputs(cooperative_left, cooperative_right);if constexpr (ACCUMULATE) {- if constexpr (RELAXED) {- METAL_PRAGMA_UNROLL- for (ushort i = 0; i < ELEMENTS_PER_THREAD; i++) {- cooperative_output[i] = output_0[i];- cooperative_output[ELEMENTS_PER_THREAD + i] = output_1[i];- }- } else {- METAL_PRAGMA_UNROLL- for (ushort i = 0; i < 4; i++) {- cooperative_output[i] = output_0[i];- cooperative_output[4 + i] = output_1[i];- cooperative_output[8 + i] = output_0[4 + i];- cooperative_output[12 + i] = output_1[4 + i];- }- }+ load_paired_vectors(cooperative_output, output_0, output_1);}matmul_op.run(cooperative_left, cooperative_right, cooperative_output);- if constexpr (RELAXED) {- METAL_PRAGMA_UNROLL- for (ushort i = 0; i < ELEMENTS_PER_THREAD; i++) {- output_0[i] = cooperative_output[i];- output_1[i] = cooperative_output[ELEMENTS_PER_THREAD + i];- }- } else {- METAL_PRAGMA_UNROLL- for (ushort i = 0; i < 4; i++) {- output_0[i] = cooperative_output[i];- output_1[i] = cooperative_output[4 + i];- output_0[4 + i] = cooperative_output[8 + i];- output_1[4 + i] = cooperative_output[12 + i];- }- }+ store_paired_vectors(cooperative_output, output_0, output_1);}template <@@ -167,21 +185,7 @@ struct MxuFragmentOps {for (ushort i = 0; i < ELEMENTS_PER_THREAD; i++) {cooperative_left[i] = left[i];}- if constexpr (RELAXED) {- METAL_PRAGMA_UNROLL- for (ushort i = 0; i < ELEMENTS_PER_THREAD; i++) {- cooperative_right[i] = right_col_0[i];- cooperative_right[ELEMENTS_PER_THREAD + i] = right_col_1[i];- }- } else {- METAL_PRAGMA_UNROLL- for (ushort i = 0; i < 4; i++) {- cooperative_right[i] = right_col_0[i];- cooperative_right[4 + i] = right_col_1[i];- cooperative_right[8 + i] = right_col_0[4 + i];- cooperative_right[12 + i] = right_col_1[4 + i];- }- }+ load_paired_vectors(cooperative_right, right_col_0, right_col_1);});}@@ -207,10 +211,9 @@ struct MxuFragmentOps {output_row_0,output_row_1,[&](thread auto& cooperative_left, thread auto& cooperative_right) {+ load_paired_vectors(cooperative_left, left_row_0, left_row_1);METAL_PRAGMA_UNROLLfor (ushort i = 0; i < ELEMENTS_PER_THREAD; i++) {- cooperative_left[i] = left_row_0[i];- cooperative_left[ELEMENTS_PER_THREAD + i] = left_row_1[i];cooperative_right[i] = right[i];}}diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.hindex c0fb0fb24..5cd74dc90 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h@@ -14,6 +14,7 @@#include "quant_pack.h"#include "quant_scale_bias.h"#include "quant_scale_zero_point.h"+#include "quant_unpack.h"using namespace metal;@@ -28,7 +29,8 @@ template <bool TRANSPOSE_B,GemmBPrologueKind B_PROLOGUE = GemmBPrologueKind::FullPrecision,int BITS = 0,- int GROUP_SIZE = 0>+ int GROUP_SIZE = 0,+ GemmAPrologueKind A_PROLOGUE = GemmAPrologueKind::FullPrecision>struct MxuMmaCore {UZU_CONST ushort THREADGROUP_BLOCK_M = gemm_tiling_block_m(GEMM_TILING);UZU_CONST ushort THREADGROUP_BLOCK_N = gemm_tiling_block_n(GEMM_TILING);@@ -92,6 +94,27 @@ struct MxuMmaCore {using AccumFragment = uzu::matmul::Fragment<AccumulatorType, TILES_M, TILES_N, uzu::matmul::MxuFragmentOps<>>;+ struct QuantizedWeightAddressing {+ int row_stride_bytes;+ int groups_per_row;+ int k_offset_groups;+ const device uint8_t* block;+ };++ static METAL_FUNC QuantizedWeightAddressing+ quantized_weight_addressing(const device BT* b, const size_t block_col, const uint k_offset, const int k_elements) {+ constexpr int pack_factor = get_pack_factor<(BITS > 0) ? BITS : 4, 8>();+ constexpr int bytes_per_pack = get_bytes_per_pack<(BITS > 0) ? BITS : 4>();+ const int row_stride_bytes = k_elements * bytes_per_pack / pack_factor;+ return QuantizedWeightAddressing{+ row_stride_bytes,+ (k_elements + int(GROUP_SIZE) - 1) / int(GROUP_SIZE),+ int(k_offset) / int(GROUP_SIZE),+ reinterpret_cast<const device uint8_t*>(b) + block_col * row_stride_bytes ++ int(k_offset) * bytes_per_pack / pack_factor,+ };+ }+template <bool ALIGNED_M, bool ALIGNED_N, typename Loader>static METAL_FUNC AccumFragment quant_k_loop(const device AT* a_simdgroup,@@ -148,6 +171,286 @@ struct MxuMmaCore {return accumulator;}+ template <bool ALIGNED_M>+ static METAL_FUNC uzu::matmul::Fragment<int8_t, TILES_M, TILES_K, uzu::matmul::MxuFragmentOps<>> load_int8_left_tile(+ const device int8_t* a_int8_simdgroup,+ const int leading_dimension_a,+ const short simdgroup_limit_m,+ const ushort simd_lane_id+ ) {+ uzu::matmul::Fragment<int8_t, TILES_M, TILES_K, uzu::matmul::MxuFragmentOps<>> left_tile;+ auto left_src = uzu::matmul::fragment_source(a_int8_simdgroup, leading_dimension_a);+ if constexpr (!ALIGNED_M) {+ left_src = left_src.bounded(simdgroup_limit_m, SIMDGROUP_BLOCK_K);+ }+ left_tile.load_from(simd_lane_id, left_src);+ return left_tile;+ }++ template <bool ALIGNED_N>+ static METAL_FUNC uzu::matmul::Fragment<int8_t, TILES_N, TILES_K, uzu::matmul::MxuFragmentOps<>> load_int8_weight_tile(+ const device uint8_t* b_packed_simdgroup,+ const int k_element_offset,+ const int b_row_stride_bytes,+ const short simdgroup_limit_n,+ const short2 position,+ const ushort simd_lane_id+ ) {+ using Ops = uzu::matmul::MxuFragmentOps<>;+ uzu::matmul::Fragment<int8_t, TILES_N, TILES_K, Ops> right_tile;+ if constexpr (BITS == 4) {+ METAL_PRAGMA_UNROLL+ for (ushort tile_n = 0; tile_n < TILES_N; ++tile_n) {+ METAL_PRAGMA_UNROLL+ for (ushort tile_k = 0; tile_k < TILES_K; ++tile_k) {+ thread auto& weight_vector = right_tile.fragment_at(tile_n, tile_k);+ METAL_PRAGMA_UNROLL+ for (ushort thread_row = 0; thread_row < Ops::THREAD_ELEMENT_ROWS; ++thread_row) {+ const short row =+ short(tile_n * Ops::FRAGMENT_ROWS) + position.y + short(thread_row * Ops::THREAD_ELEMENT_ROW_STRIDE);+ const ushort element_base = thread_row * Ops::THREAD_ELEMENT_COLS;+ char4 codes = char4(0);+ if (ALIGNED_N || row < simdgroup_limit_n) {+ const int k_base = k_element_offset + int(tile_k * Ops::FRAGMENT_COLS) + int(position.x);+ const ushort packed = *reinterpret_cast<const device ushort*>(+ b_packed_simdgroup + int(row) * b_row_stride_bytes + (k_base >> 1)+ );+ codes = unpack_nibbles_to_int8(uint(packed));+ }+ weight_vector[element_base + 0] = codes.x;+ weight_vector[element_base + 1] = codes.y;+ weight_vector[element_base + 2] = codes.z;+ weight_vector[element_base + 3] = codes.w;+ }+ }+ }+ } else {+ static_assert(BITS == 8, "symmetric int8 activations only support 4-bit or 8-bit weights");+ auto right_src = uzu::matmul::fragment_source(+ reinterpret_cast<const device int8_t*>(b_packed_simdgroup) + k_element_offset,+ b_row_stride_bytes+ );+ if constexpr (!ALIGNED_N) {+ right_src = right_src.bounded(simdgroup_limit_n, SIMDGROUP_BLOCK_K);+ }+ right_tile.load_from(simd_lane_id, right_src);+ thread int8_t* right_codes = right_tile.elements();+ METAL_PRAGMA_UNROLL+ for (ushort i = 0; i < right_tile.ELEMENTS_PER_FRAGMENT; ++i) {+ right_codes[i] = unbias_uint8_to_int8(as_type<uchar>(right_codes[i]));+ }+ }+ return right_tile;+ }++ // Per-thread cache holding one value per distinct fragment row (or column) line+ // a thread owns, addressable either by slot or by offset from the thread origin.+ template <ushort TILES, ushort SLOTS_PER_TILE, ushort FRAGMENT_EXTENT, ushort SLOT_STRIDE>+ struct FragmentLineCache {+ float values[TILES * SLOTS_PER_TILE];++ METAL_FUNC thread float& slot(const ushort tile, const ushort index) thread {+ return values[tile * SLOTS_PER_TILE + index];+ }++ METAL_FUNC float at(const short offset) const thread {+ const ushort tile = ushort(offset) / FRAGMENT_EXTENT;+ const ushort index = (ushort(offset) % FRAGMENT_EXTENT) / SLOT_STRIDE;+ return values[tile * SLOTS_PER_TILE + index];+ }++ template <bool ALIGNED, typename Sink>+ static METAL_FUNC void for_each_line(+ const short origin,+ const short limit,+ const uint abs_base,+ const uint groups_per_row,+ const uint group_index,+ Sink sink+ ) {+ METAL_PRAGMA_UNROLL+ for (ushort tile = 0; tile < TILES; ++tile) {+ METAL_PRAGMA_UNROLL+ for (ushort index = 0; index < SLOTS_PER_TILE; ++index) {+ const short coord = origin + tile * FRAGMENT_EXTENT + index * SLOT_STRIDE;+ if (ALIGNED || coord < limit) {+ sink(tile, index, (abs_base + uint(coord)) * groups_per_row + group_index);+ }+ }+ }+ }+ };++ using FragmentOps = uzu::matmul::MxuFragmentOps<>;+ using ActivationLineCache = FragmentLineCache<+ TILES_M,+ FragmentOps::THREAD_ELEMENT_ROWS,+ FragmentOps::FRAGMENT_ROWS,+ FragmentOps::THREAD_ELEMENT_ROW_STRIDE>;+ using WeightLineCache = FragmentLineCache<TILES_N, FragmentOps::THREAD_ELEMENT_COLS, FragmentOps::FRAGMENT_COLS, 1>;++ static_assert(+ A_PROLOGUE != GemmAPrologueKind::Int8Symmetric || GROUP_SIZE % int(SIMDGROUP_BLOCK_K) == 0,+ "A8 weight group size must be a multiple of the 32-wide activation chunk"+ );+ UZU_CONST bool int8_activation_needs_weight_correction =+ A_PROLOGUE == GemmAPrologueKind::Int8Symmetric && B_PROLOGUE != GemmBPrologueKind::ScaleSymmetricDequant;+ UZU_CONST float int8_weight_midpoint = float(symmetric_zero_point<ushort((BITS > 0) ? BITS : 4)>());++ static METAL_FUNC float int8_weight_dequant_bias(+ const float scale,+ const uint scale_index,+ const uint col,+ const uint weight_group,+ const uint weight_groups_per_row,+ const device BT* biases,+ const device uint8_t* zero_points+ ) {+ if constexpr (B_PROLOGUE == GemmBPrologueKind::ScaleBiasDequant) {+ return static_cast<float>(biases[scale_index]);+ } else if constexpr (B_PROLOGUE == GemmBPrologueKind::ScaleZeroPointDequant) {+ const device uint8_t* zero_points_row =+ zero_points + col * zero_point_row_stride<ushort(BITS)>(weight_groups_per_row);+ return -scale * float(decode_zero_point<ushort(BITS)>(zero_points_row, weight_group));+ } else {+ return 0.0f;+ }+ }++ template <bool ALIGNED_M, bool ALIGNED_N>+ static METAL_FUNC AccumFragment symmetric_int8_activation_k_loop(+ const device int8_t* a_int8_simdgroup,+ const device uint8_t* b_packed_simdgroup,+ const device float* a_scales,+ const device BT* b_scales,+ const device BT* biases,+ const device uint8_t* zero_points,+ const int leading_dimension_a,+ const int b_row_stride_bytes,+ const int weight_group_iterations,+ const short simdgroup_limit_m,+ const short simdgroup_limit_n,+ const uint abs_row_base,+ const uint abs_col_base,+ const uint k_offset_weight_groups,+ const uint k_offset_act_groups,+ const uint weight_groups_per_row,+ const uint act_groups_per_row,+ const thread ThreadContext& thread_context+ ) {+ using Ops = uzu::matmul::MxuFragmentOps<>;+ AccumFragment accumulator;+ accumulator.clear();++ const short2 position = Ops::get_position(thread_context.simd_lane_id);+ constexpr int k_bytes_per_weight_group = (BITS == 4) ? (int(GROUP_SIZE) / 2) : int(GROUP_SIZE);+ constexpr int act_chunks_per_weight_group = int(GROUP_SIZE) / int(SIMDGROUP_BLOCK_K);++ uzu::matmul::Fragment<int8_t, TILES_N, TILES_K, Ops> ones_tile;+ if constexpr (int8_activation_needs_weight_correction) {+ thread int8_t* ones = ones_tile.elements();+ METAL_PRAGMA_UNROLL+ for (ushort i = 0; i < ones_tile.ELEMENTS_PER_FRAGMENT; ++i) {+ ones[i] = int8_t(1);+ }+ }++ METAL_PRAGMA_NO_UNROLL+ for (int weight_group = 0; weight_group < weight_group_iterations; ++weight_group) {+ const uint weight_group_index = k_offset_weight_groups + uint(weight_group);++ WeightLineCache weight_scales;+ WeightLineCache weight_corrections;+ WeightLineCache::template for_each_line<ALIGNED_N>(+ position.x,+ simdgroup_limit_n,+ abs_col_base,+ weight_groups_per_row,+ weight_group_index,+ [&](ushort tile_col, ushort thread_col, uint scale_index) {+ const float scale = static_cast<float>(b_scales[scale_index]);+ weight_scales.slot(tile_col, thread_col) = scale;+ if constexpr (int8_activation_needs_weight_correction) {+ const uint col = scale_index / weight_groups_per_row;+ weight_corrections.slot(tile_col, thread_col) = scale * int8_weight_midpoint + int8_weight_dequant_bias(+ scale,+ scale_index,+ col,+ weight_group_index,+ weight_groups_per_row,+ biases,+ zero_points+ );+ }+ }+ );++ METAL_PRAGMA_NO_UNROLL+ for (int act_chunk = 0; act_chunk < act_chunks_per_weight_group; ++act_chunk) {+ const int k_element_offset = act_chunk * int(SIMDGROUP_BLOCK_K);+ auto activation_tile = load_int8_left_tile<ALIGNED_M>(+ a_int8_simdgroup + k_element_offset,+ leading_dimension_a,+ simdgroup_limit_m,+ thread_context.simd_lane_id+ );++ uzu::matmul::Fragment<int, TILES_M, TILES_N, Ops> chunk_products;+ auto right_tile = load_int8_weight_tile<ALIGNED_N>(+ b_packed_simdgroup,+ k_element_offset,+ b_row_stride_bytes,+ simdgroup_limit_n,+ position,+ thread_context.simd_lane_id+ );+ Ops::template fragment_mm<false, true>(chunk_products, activation_tile, right_tile);++ const uint act_group_index = k_offset_act_groups + uint(weight_group * act_chunks_per_weight_group + act_chunk);+ ActivationLineCache activation_scales;+ ActivationLineCache::template for_each_line<ALIGNED_M>(+ position.y,+ simdgroup_limit_m,+ abs_row_base,+ act_groups_per_row,+ act_group_index,+ [&](ushort tile_row, ushort thread_row, uint scale_index) {+ activation_scales.slot(tile_row, thread_row) = a_scales[scale_index];+ }+ );++ uzu::matmul::Fragment<int, TILES_M, TILES_N, Ops> activation_row_sums;+ if constexpr (int8_activation_needs_weight_correction) {+ Ops::template fragment_mm<false, true>(activation_row_sums, activation_tile, ones_tile);+ }+ AccumFragment::zip_for_each_coord(+ thread_context.simd_lane_id,+ [&](short row, short col, thread float& accumulated, thread int& products, thread int& row_sums) {+ if (!ALIGNED_M && row >= simdgroup_limit_m) {+ return;+ }+ if (!ALIGNED_N && col >= simdgroup_limit_n) {+ return;+ }+ float scaled_products = weight_scales.at(col - position.x) * float(products);+ if constexpr (int8_activation_needs_weight_correction) {+ scaled_products += weight_corrections.at(col - position.x) * float(row_sums);+ }+ accumulated += activation_scales.at(row - position.y) * scaled_products;+ },+ accumulator,+ chunk_products,+ activation_row_sums+ );+ }++ a_int8_simdgroup += GROUP_SIZE;+ b_packed_simdgroup += k_bytes_per_weight_group;+ }++ return accumulator;+ }+static METAL_FUNC void run(const device AT* a,const device BT* b,@@ -160,6 +463,8 @@ struct MxuMmaCore {const device uint8_t* zero_points,const device BT* output_bias,const device int32_t* rht_factors,+ const device int8_t* a_int8,+ const device float* a_scales,threadgroup BT* b_shared,const thread ThreadContext& thread_context) {@@ -179,7 +484,6 @@ struct MxuMmaCore {(B_PROLOGUE == GemmBPrologueKind::FullPrecision) ? uint(THREADGROUP_BLOCK_K_FP) : uint(QUANT_BK);const uint k_offset = partition * params->aligned_inner_iterations * k_offset_per_block;- const device AT* a_block = a + block_row * params->leading_dimension_a + k_offset;const device BT* b_block_fp = b + (TRANSPOSE_B ? block_col * params->leading_dimension_b : block_col) +(TRANSPOSE_B ? k_offset : k_offset * uint(params->leading_dimension_b));@@ -199,7 +503,11 @@ struct MxuMmaCore {? SIMDGROUP_BLOCK_N: short(min(int(SIMDGROUP_BLOCK_N), int(params->N) - int(geometry.block_col_start + tile_col_offset)));- const device AT* a_simdgroup = a_block + size_t(tile_row_offset) * params->leading_dimension_a;+ const device AT* a_simdgroup = a;+ if constexpr (A_PROLOGUE == GemmAPrologueKind::FullPrecision) {+ a_simdgroup +=+ block_row * params->leading_dimension_a + k_offset + size_t(tile_row_offset) * params->leading_dimension_a;+ }const device BT* b_simdgroup_fp =b_block_fp +(TRANSPOSE_B ? size_t(tile_col_offset) * int(params->leading_dimension_b) : size_t(tile_col_offset));@@ -228,7 +536,35 @@ struct MxuMmaCore {alignment.contains(GemmAlignment::N) || (simdgroup_limit_n == SIMDGROUP_BLOCK_N),[&](auto aligned_n) {auto accumulator_tile = [&]() {- if constexpr (B_PROLOGUE == GemmBPrologueKind::FullPrecision) {+ if constexpr (A_PROLOGUE == GemmAPrologueKind::Int8Symmetric) {+ const auto quantized_weights =+ quantized_weight_addressing(b, block_col, k_offset, int(params->K));+ const device int8_t* a_int8_simdgroup = a_int8 + block_row * params->leading_dimension_a ++ k_offset ++ size_t(tile_row_offset) * params->leading_dimension_a;+ const device uint8_t* b_packed_simdgroup =+ quantized_weights.block + size_t(tile_col_offset) * quantized_weights.row_stride_bytes;+ return symmetric_int8_activation_k_loop<aligned_m.value, aligned_n.value>(+ a_int8_simdgroup,+ b_packed_simdgroup,+ a_scales,+ scales,+ biases,+ zero_points,+ int(params->leading_dimension_a),+ quantized_weights.row_stride_bytes,+ int(params->aligned_inner_iterations),+ simdgroup_limit_m,+ simdgroup_limit_n,+ uint(geometry.block_row_start) + tile_row_offset,+ uint(geometry.block_col_start) + tile_col_offset,+ uint(quantized_weights.k_offset_groups),+ k_offset / uint(SIMDGROUP_BLOCK_K),+ uint(quantized_weights.groups_per_row),+ uint(params->K) / uint(SIMDGROUP_BLOCK_K),+ thread_context+ );+ } else if constexpr (B_PROLOGUE == GemmBPrologueKind::FullPrecision) {const int aligned_k_iterations_fp = int(params->aligned_inner_iterations);return uzu::matmul::gemm_loop<AT,@@ -255,15 +591,11 @@ struct MxuMmaCore {);} else {const int aligned_k_iterations_q = int(params->aligned_inner_iterations);- constexpr int pack_factor = get_pack_factor<BITS, 8>();- constexpr int bytes_per_pack = get_bytes_per_pack<BITS>();const int k_elements = int(params->K);- const int weights_row_stride_bytes = k_elements * bytes_per_pack / pack_factor;- const int groups_per_row = (k_elements + GROUP_SIZE - 1) / GROUP_SIZE;- const int k_offset_groups = int(k_offset) / GROUP_SIZE;- const device uint8_t* weights_block = reinterpret_cast<const device uint8_t*>(b) +- block_col * weights_row_stride_bytes +- int(k_offset) * bytes_per_pack / pack_factor;+ const auto quantized_weights = quantized_weight_addressing(b, block_col, k_offset, k_elements);+ const int groups_per_row = quantized_weights.groups_per_row;+ const int k_offset_groups = quantized_weights.k_offset_groups;+ const device uint8_t* weights_block = quantized_weights.block;const device BT* scales_offset = scales + block_col * groups_per_row + k_offset_groups;auto loader_b = [&]() {@@ -279,8 +611,7 @@ struct MxuMmaCore {thread_context.simd_lane_id);} else if constexpr (B_PROLOGUE == GemmBPrologueKind::ScaleZeroPointDequant) {- const int zero_point_stride_per_row =- (BITS == 4) ? ((groups_per_row + 1) / 2) : groups_per_row;+ const int zero_point_stride_per_row = zero_point_row_stride<ushort(BITS)>(groups_per_row);const device uint8_t* zero_points_row_start =zero_points + block_col * zero_point_stride_per_row +((BITS == 4) ? (k_offset_groups / 2) : k_offset_groups);diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.hindex 330b30330..42e1abd4b 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.h+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.h@@ -77,11 +77,11 @@ struct QuantizedBlockLoaderScaleZeroPoint {scales(REDUCTION_DIMENSION == 1 ? (scales_ + tile_row_index * groups_per_row_) : scales_),scales_row_start(REDUCTION_DIMENSION == 1 ? (scales_ + tile_row_index * groups_per_row_) : scales_),zero_points_row_start(- SCALE_SYMMETRIC ? nullptr- : (REDUCTION_DIMENSION == 1- ? (zero_points_row_start_ +- tile_row_index * (BITS == 4 ? ((groups_per_row_ + 1) / 2) : groups_per_row_))- : zero_points_row_start_)+ SCALE_SYMMETRIC+ ? nullptr+ : (REDUCTION_DIMENSION == 1 ? (zero_points_row_start_ ++ tile_row_index * zero_point_row_stride<ushort(BITS)>(groups_per_row_))+ : zero_points_row_start_)) {}inline void current_scale_bias(thread T& out_scale, thread T& out_bias) const {@@ -96,13 +96,9 @@ struct QuantizedBlockLoaderScaleZeroPoint {scale_value = *scales;}if constexpr (SCALE_SYMMETRIC) {- zero_point_value = 1u << (BITS - 1);- } else if constexpr (BITS == 4) {- const device uint8_t* zero_point_ptr = zero_points_row_start + (group_index >> 1);- uint8_t zero_point_byte = *zero_point_ptr;- zero_point_value = (uint(zero_point_byte) >> (uint(group_index & 1) * 4u)) & 0x0Fu;+ zero_point_value = symmetric_zero_point<ushort(BITS)>();} else {- zero_point_value = zero_points_row_start[group_index];+ zero_point_value = decode_zero_point<ushort(BITS)>(zero_points_row_start, uint(group_index));}out_scale = scale_value;out_bias = static_cast<T>(-scale_value * static_cast<T>(zero_point_value));diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_unpack.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_unpack.hindex 654c72165..559c95d9e 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_unpack.h+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/common/quant_unpack.h@@ -50,6 +50,37 @@ METAL_FUNC bfloat4 uint4_to_fp4<bfloat, 8>(uint4 n) {return bfloat4(_uint4_to_fp4_float<8>(n));}+template <ushort BITS>+METAL_FUNC constexpr uint symmetric_zero_point() {+ return 1u << (BITS - 1);+}++template <ushort BITS, typename Int>+METAL_FUNC constexpr Int zero_point_row_stride(Int groups_per_row) {+ return (BITS == 4) ? (groups_per_row + Int(1)) / Int(2) : groups_per_row;+}++template <ushort BITS>+METAL_FUNC uint decode_zero_point(const device uint8_t* zero_points_row, uint group_index) {+ static_assert(BITS == 4 || BITS == 8, "Only int4 and int8 zero points supported");+ if constexpr (BITS == 4) {+ const uint packed = uint(zero_points_row[group_index >> 1]);+ return (packed >> ((group_index & 1u) * 4u)) & 0x0Fu;+ } else {+ return uint(zero_points_row[group_index]);+ }+}++METAL_FUNC char4 unpack_nibbles_to_int8(uint packed) {+ uint spread = (packed | (packed << 8)) & 0x00FF00FFu;+ spread = (spread | (spread << 4)) & 0x0F0F0F0Fu;+ return as_type<char4>(spread) - char4(char(symmetric_zero_point<4>()));+}++METAL_FUNC int8_t unbias_uint8_to_int8(uchar code) {+ return as_type<int8_t>(uchar(code ^ uchar(symmetric_zero_point<8>())));+}+template <typename U, int N, int bits>inline void dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local) {static_assert(bits == 4 || bits == 8, "Only int4 and int8 supported");diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/gemm.metal b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/gemm.metalindex 4e7d979cd..56b43101d 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/gemm.metal+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/gemm.metal@@ -10,7 +10,8 @@using namespace metal;using namespace uzu::gemm;-#define GEMM_MXU_QUANT (USE_MXU && B_PROLOGUE != GemmBPrologueKind::FullPrecision)+#define A_IS_INT8 (A_PROLOGUE == GemmAPrologueKind::Int8Symmetric)+#define GEMM_MXU_QUANT (USE_MXU && B_PROLOGUE != GemmBPrologueKind::FullPrecision && !A_IS_INT8)#define GEMM_TGA_ELEMENTS \((USE_MXU) ? 1 : (gemm_tiling_block_m(GEMM_TILING) * (gemm_tiling_block_k(GEMM_TILING) + 16 / int(sizeof(AT)))))#define GEMM_TGB_ELEMENTS \@@ -26,7 +27,8 @@ template <bool USE_MXU,GemmBPrologueKind B_PROLOGUE,uint BITS,- uint GROUP_SIZE>+ uint GROUP_SIZE,+ GemmAPrologueKind A_PROLOGUE>VARIANTS(AT, bfloat, float)VARIANTS(BT, bfloat, float)VARIANTS(DT, bfloat, float)@@ -54,6 +56,10 @@ VARIANTS(GemmBPrologueKind::ScaleSymmetricDequant)VARIANTS(BITS, 0, 4, 8)VARIANTS(GROUP_SIZE, 0, 16, 32, 64, 128)+VARIANTS(+ A_PROLOGUE,+ GemmAPrologueKind::FullPrecision,+ GemmAPrologueKind::Int8Symmetric)CONSTRAINT(USE_MXU ==(GEMM_TILING == GemmTiling::Tile16x32x256_Simdgroups1x1 ||@@ -80,9 +86,20 @@ CONSTRAINT(CONSTRAINT(!(GEMM_TILING == GemmTiling::Tile16x32x256_Simdgroups1x1 ||GEMM_TILING == GemmTiling::Tile16x128x256_Simdgroups1x4) ||- (TRANSPOSE_B && B_PROLOGUE == GemmBPrologueKind::FullPrecision))+ (TRANSPOSE_B &&+ (B_PROLOGUE == GemmBPrologueKind::FullPrecision ||+ A_PROLOGUE == GemmAPrologueKind::Int8Symmetric)))+CONSTRAINT(A_PROLOGUE == GemmAPrologueKind::FullPrecision || USE_MXU)+CONSTRAINT(A_PROLOGUE == GemmAPrologueKind::FullPrecision || BITS == 4 || BITS == 8)+CONSTRAINT(+ A_PROLOGUE == GemmAPrologueKind::FullPrecision ||+ (GROUP_SIZE % METAL_SIMD_SIZE == 0 && GROUP_SIZE != 0))+CONSTRAINT(+ A_PROLOGUE == GemmAPrologueKind::FullPrecision ||+ (TRANSPOSE_B && B_PROLOGUE != GemmBPrologueKind::FullPrecision))+CONSTRAINT(A_PROLOGUE == GemmAPrologueKind::FullPrecision || (AT == "bfloat" && DT == "bfloat"))KERNEL(Gemm)(- const device AT* a,+ const device AT* a OPTIONAL(A_PROLOGUE == GemmAPrologueKind::FullPrecision),const device BT* b,device DT* d,const device BT* scales@@ -95,6 +112,8 @@ KERNEL(Gemm)(OPTIONAL(output_transform.contains(GemmDTransform::BIAS)),const device int32_t* rht_factorsOPTIONAL(output_transform.contains(GemmDTransform::RHT)),+ const device int8_t* a_int8 OPTIONAL(A_IS_INT8),+ const device float* a_scales OPTIONAL(A_IS_INT8),const constant uzu::matmul::GemmParams* params,const constant uint& group_count_x,const constant uint& group_count_y,@@ -119,7 +138,7 @@ KERNEL(Gemm)((void)thread_z;if constexpr (USE_MXU) {- MxuMmaCore<AT, BT, DT, GEMM_TILING, TRANSPOSE_B, B_PROLOGUE, BITS, GROUP_SIZE>::run(+ MxuMmaCore<AT, BT, DT, GEMM_TILING, TRANSPOSE_B, B_PROLOGUE, BITS, GROUP_SIZE, A_PROLOGUE>::run(a,b,d,@@ -131,6 +150,8 @@ KERNEL(Gemm)(zero_points,output_bias,rht_factors,+ a_int8,+ a_scales,b_shared,thread_context);diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rsindex ab58a3be9..19b38102f 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/kernel.rs@@ -6,12 +6,12 @@ use crate::{common::{Allocation, Backend, BufferArg, Encoder,gpu_types::{- GemmParams, HadamardTransformOrder,- gemm::{GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling},+ GemmParams, HADAMARD_TRANSFORM_BLOCK_SIZE, HadamardTransformOrder,+ gemm::{GemmAPrologueKind, GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling},},kernel::{HadamardTransformKernel, Kernels, TensorAddBiasKernel,- matmul::{MatmulArguments, MatmulB, MatmulError},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulError},},},metal::{@@ -25,6 +25,9 @@ use crate::{data_type::DataType,};+const SPLIT_K_TARGET_TILES_INT8_ACTIVATIONS: u32 = 128;+const SPLIT_K_TARGET_TILES: u32 = 512;+#[derive(Debug, Clone, Copy)]pub enum GemmDispatchPath {Simdgroup,@@ -85,6 +88,7 @@ impl GemmKernel {specialization.b_prologue,specialization.bits_per_b.unwrap_or(0),specialization.group_size.unwrap_or(0),+ specialization.a_prologue,specialization.output_transform,specialization.alignment,)?;@@ -173,7 +177,13 @@ impl GemmKernel {if !arguments.b_transpose || arguments.b_leading_dimension.is_some() {return None;}- let tiling = select_mxu_quant_tiling(arguments.m, arguments.n, arguments.b.group_size().unwrap_or(0));+ let group_size = arguments.b.group_size().unwrap_or(0);+ let int8_activations = arguments.a.prologue_kind() == GemmAPrologueKind::Int8Symmetric;+ let tiling =+ select_mxu_quant_tiling(arguments.m, arguments.n, arguments.k, group_size, int8_activations);+ if int8_activations {+ return (group_size != 0 && arguments.k.is_multiple_of(group_size)).then_some(tiling);+ }arguments.k.is_multiple_of(tiling.block_k()).then_some(tiling)},}@@ -184,7 +194,10 @@ impl GemmKernel {arguments: MatmulArguments<'a, 'b, 'd, Metal, TB>,encoder: &mut Encoder<Metal>,) -> Result<(), MetalError> {- let path = if encoder.context().device.supports_mxu() && self.select_mxu_tiling(&arguments).is_some() {+ let path = if encoder.context().device.supports_mxu()+ && (arguments.a.prologue_kind() == GemmAPrologueKind::Int8Symmetric+ || self.select_mxu_tiling(&arguments).is_some())+ {GemmDispatchPath::Mxu} else {GemmDispatchPath::Simdgroup@@ -224,10 +237,6 @@ impl GemmKernel {}.into());}- assert!(- !d_mask.contains(GemmDTransform::BIAS | GemmDTransform::RHT),- "QuantGemm with both output bias and output RHT is not supported: bias must be applied after RHT",- );if !arguments.b_transpose || arguments.b_leading_dimension.is_some() {return Err(MatmulError::UnsupportedLayout {path: "QuantGemm",@@ -247,7 +256,6 @@ impl GemmKernel {let MatmulArguments {a,- a_offset,b,b_leading_dimension,b_transpose,@@ -264,6 +272,18 @@ impl GemmKernel {MatmulB::FullPrecision {b: weights,} => {+ let MatmulA::FullPrecision {+ values: a,+ offset: a_offset,+ } = a+ else {+ return Err(MatmulError::IncompatibleA {+ path: "Gemm",+ reason: "int8 activations require quantized weights",+ }+ .into());+ };+let tiling = if use_mxu {if b_transpose {select_mxu_tiling(m, n, k)@@ -297,13 +317,15 @@ impl GemmKernel {GemmAlignment::new(m % tiling.block_m() == 0, n % tiling.block_n() == 0, k % tiling.block_k() == 0);if b_transpose && b_leading_dimension.is_none() {- let split_k = select_split_k(m, n, k, tiling, use_mxu, 0, true, false);+ let split_k = select_split_k(m, n, k, tiling, use_mxu, 0, true, false, SPLIT_K_TARGET_TILES);if split_k > 1&& split_k_output_supported(output_transform, n, self.weights_data_type, self.output_data_type){return self.encode_split_k(- a,- a_offset,+ Some((a, a_offset)),+ None,+ None,+ GemmAPrologueKind::FullPrecision,weights,None,None,@@ -356,11 +378,12 @@ impl GemmKernel {b_prologue,bits_per_b,group_size,+ a_prologue: GemmAPrologueKind::FullPrecision,};specialization.validate()?;let kernel = self.get_or_create(encoder.context(), specialization)?;kernel.encode(- (a, a_offset),+ Some((a, a_offset)),weights,&mut *d,None::<&Allocation<Metal>>,@@ -368,6 +391,8 @@ impl GemmKernel {None::<&Allocation<Metal>>,output_bias,rht_factors,+ None::<&Allocation<Metal>>,+ None::<&Allocation<Metal>>,std::slice::from_ref(¶ms),group_count_x,group_count_y,@@ -405,8 +430,38 @@ impl GemmKernel {_ => unreachable!(),};+ let a_prologue = a.prologue_kind();+ let a_is_int8 = a_prologue == GemmAPrologueKind::Int8Symmetric;+ let (a_full_precision, a_int8, a_scales) = match a {+ MatmulA::FullPrecision {+ values,+ offset,+ } => (Some((values, offset)), None, None),+ MatmulA::Int8Symmetric {+ values,+ scales: activation_scales,+ } => {+ validate_int8_activation_arguments(use_mxu, k, b_prologue, bits_per_b, group_size)?;+ if output_transform.contains(GemmDTransform::SOFT_CAP) {+ return Err(MatmulError::UnsupportedDOp {+ bit: GemmDTransform::SOFT_CAP,+ path: "Gemm int8 activations",+ }+ .into());+ }+ (None, Some(values), Some(activation_scales))+ },+ };++ let (output_bias, bias_after_rht, output_transform) = if rht_factors.is_some() && output_bias.is_some()+ {+ (None, output_bias, output_transform.difference(GemmDTransform::BIAS))+ } else {+ (output_bias, None, output_transform)+ };+let tiling = if use_mxu {- select_mxu_quant_tiling(m, n, group_size.unwrap_or(0))+ select_mxu_quant_tiling(m, n, k, group_size.unwrap_or(0), a_is_int8)} else {select_quant_tiling(m, n, group_size.unwrap_or(0))};@@ -417,13 +472,30 @@ impl GemmKernel {let group_count_y = m.div_ceil(tiling.block_m());let zero_point_4bit = zero_points.is_some() && bits_per_b == Some(4);- let split_k = select_split_k(m, n, k, tiling, use_mxu, group_size.unwrap_or(0), false, zero_point_4bit);+ let split_k_target = if a_is_int8 {+ SPLIT_K_TARGET_TILES_INT8_ACTIVATIONS+ } else {+ SPLIT_K_TARGET_TILES+ };+ let split_k = select_split_k(+ m,+ n,+ k,+ tiling,+ use_mxu,+ group_size.unwrap_or(0),+ false,+ zero_point_4bit,+ split_k_target,+ );if split_k > 1&& split_k_output_supported(output_transform, n, self.weights_data_type, self.output_data_type){- return self.encode_split_k(- a,- a_offset,+ self.encode_split_k(+ a_full_precision,+ a_int8,+ a_scales,+ a_prologue,weights,scales,biases,@@ -443,37 +515,53 @@ impl GemmKernel {output_bias,rht_factors,encoder,+ )?;+ } else {+ let specialization = GemmSpecialization {+ weights_data_type: self.weights_data_type,+ tiling,+ use_mxu,+ output_transform,+ alignment,+ transpose_b: true,+ b_prologue,+ bits_per_b,+ group_size,+ a_prologue,+ };+ specialization.validate()?;+ let kernel = self.get_or_create(encoder.context(), specialization)?;+ kernel.encode(+ a_full_precision,+ weights,+ &mut *d,+ scales,+ biases,+ zero_points,+ output_bias,+ rht_factors,+ a_int8,+ a_scales,+ std::slice::from_ref(¶ms),+ group_count_x,+ group_count_y,+ 1,+ encoder,);}- let specialization = GemmSpecialization {- weights_data_type: self.weights_data_type,- tiling,- use_mxu,- output_transform,- alignment,- transpose_b: true,- b_prologue,- bits_per_b,- group_size,- };- specialization.validate()?;- let kernel = self.get_or_create(encoder.context(), specialization)?;- kernel.encode(- (a, a_offset),- weights,- &mut *d,- scales,- biases,- zero_points,- output_bias,- rht_factors,- std::slice::from_ref(¶ms),- group_count_x,- group_count_y,- 1,- encoder,- );+ if let Some(bias) = bias_after_rht {+ let output_length = m.checked_mul(n).expect("GEMM output length must fit in u32");+ self.bias_add.encode(+ None::<&Allocation<Metal>>,+ bias,+ None::<&Allocation<Metal>>,+ &mut *d,+ n,+ output_length,+ encoder,+ );+ }},}@@ -481,10 +569,12 @@ impl GemmKernel {}#[allow(clippy::too_many_arguments)]- fn encode_split_k<'a, WB: BufferArg<'a, Metal>>(+ fn encode_split_k<'a, 'b, WB: BufferArg<'b, Metal>>(&mut self,- a: &Allocation<Metal>,- a_offset: usize,+ a_full_precision: Option<(&Allocation<Metal>, usize)>,+ a_int8: Option<&Allocation<Metal>>,+ a_scales: Option<&Allocation<Metal>>,+ a_prologue: GemmAPrologueKind,weights: WB,scales: Option<&Allocation<Metal>>,biases: Option<&Allocation<Metal>>,@@ -522,6 +612,7 @@ impl GemmKernel {b_prologue,bits_per_b,group_size,+ a_prologue,};part_spec.validate()?;@@ -544,7 +635,7 @@ impl GemmKernel {};let part_kernel = self.get_or_create(encoder.context(), part_spec)?;part_kernel.encode(- (a, a_offset),+ a_full_precision,weights,&mut temp,scales,@@ -552,6 +643,8 @@ impl GemmKernel {zero_points,None::<&Allocation<Metal>>,None::<&Allocation<Metal>>,+ a_int8,+ a_scales,std::slice::from_ref(¶ms),base_gx,base_gy,@@ -585,6 +678,35 @@ impl GemmKernel {}}+fn validate_int8_activation_arguments(+ use_mxu: bool,+ k: u32,+ b_prologue: GemmBPrologueKind,+ bits_per_b: Option<u32>,+ weight_group_size: Option<u32>,+) -> Result<(), MetalError> {+ let weight_gs_ok = matches!(weight_group_size, Some(32 | 64 | 128));+ let compatible = use_mxu+ && matches!(+ b_prologue,+ GemmBPrologueKind::ScaleSymmetricDequant+ | GemmBPrologueKind::ScaleBiasDequant+ | GemmBPrologueKind::ScaleZeroPointDequant+ )+ && matches!(bits_per_b, Some(4 | 8))+ && weight_gs_ok+ && (k as usize).is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE)+ && weight_group_size.is_some_and(|gs| k.is_multiple_of(gs));+ if !compatible {+ return Err(MatmulError::IncompatibleA {+ path: "Gemm",+ reason: "symmetric int8 activations require MXU and unsigned 4/8-bit quantized weights with group size 32/64/128",+ }+ .into());+ }+ Ok(())+}+fn quant_params(m: u32,n: u32,@@ -644,6 +766,7 @@ fn select_split_k(group_size: u32,full_precision: bool,zero_point_4bit: bool,+ target_tiles: u32,) -> u32 {let base_tiles = n.div_ceil(tiling.block_n()) * m.div_ceil(tiling.block_m());if base_tiles == 0 {@@ -652,7 +775,7 @@ fn select_split_k(if !((m as u64) * (n as u64)).is_multiple_of(4) {return 1;}- let mut split_k = (512 / base_tiles).max(1);+ let mut split_k = (target_tiles / base_tiles).max(1);let step = match split_k_step(tiling, use_mxu, group_size, full_precision) {Some(s) => s,None => return 1,@@ -740,9 +863,15 @@ fn select_small_m_mxu_tiling(pub(crate) fn select_mxu_quant_tiling(m: u32,n: u32,+ k: u32,group_size: u32,+ int8_activations: bool,) -> GemmTiling {- let tiling = select_base_mxu_tiling(m, n);+ let tiling = if int8_activations {+ select_mxu_tiling(m, n, k)+ } else {+ select_base_mxu_tiling(m, n)+ };if tiling.fits_quant_group_size(group_size) {tiling} else {diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rsindex ee6471c6a..0a311a97b 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemm/specialization.rs@@ -1,24 +1,27 @@use super::error::GemmSpecializationError;use crate::{- backends::common::gpu_types::gemm::{GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling},+ backends::common::gpu_types::gemm::{+ GemmAPrologueKind, GemmAlignment, GemmBPrologueKind, GemmDTransform, GemmTiling,+ },data_type::DataType,};#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-pub(crate) struct GemmSpecialization {- pub(crate) weights_data_type: DataType,- pub(crate) tiling: GemmTiling,- pub(crate) use_mxu: bool,- pub(crate) output_transform: GemmDTransform,- pub(crate) alignment: GemmAlignment,- pub(crate) transpose_b: bool,- pub(crate) b_prologue: GemmBPrologueKind,- pub(crate) bits_per_b: Option<u32>,- pub(crate) group_size: Option<u32>,+pub(super) struct GemmSpecialization {+ pub(super) weights_data_type: DataType,+ pub(super) tiling: GemmTiling,+ pub(super) use_mxu: bool,+ pub(super) output_transform: GemmDTransform,+ pub(super) alignment: GemmAlignment,+ pub(super) transpose_b: bool,+ pub(super) a_prologue: GemmAPrologueKind,+ pub(super) b_prologue: GemmBPrologueKind,+ pub(super) bits_per_b: Option<u32>,+ pub(super) group_size: Option<u32>,}impl GemmSpecialization {- pub(crate) fn validate(&self) -> Result<(), GemmSpecializationError> {+ pub(super) fn validate(&self) -> Result<(), GemmSpecializationError> {if self.use_mxu != self.tiling.is_mxu_variant() {return Err(GemmSpecializationError::TilingUseMxuMismatch {tiling: self.tiling,diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/common/epilogue.h b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/common/epilogue.hindex b51a3f82e..f28e52208 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/common/epilogue.h+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/common/epilogue.h@@ -41,7 +41,7 @@ struct Epilogue {if (is_accumulate && global_row < out_vec_size) {value += static_cast<U>(d[row]);}- if (is_bias && global_row < out_vec_size) {+ if (is_bias && !use_hadamard && global_row < out_vec_size) {value += static_cast<U>(output_bias[global_row]);}if (is_soft_cap) {@@ -64,11 +64,15 @@ struct Epilogue {if (simd_group == 0) {uint global_out_idx = out_block_idx * 32 + simd_lane;if (global_out_idx < out_vec_size) {- d[simd_lane] = simdgroup_output_random_hadamard_transform(+ DT transformed = simdgroup_output_random_hadamard_transform(static_cast<ushort>(simd_lane),static_cast<DT>(shared_results[simd_lane]),hadamard_factors[global_out_idx]);+ if (is_bias) {+ transformed += static_cast<DT>(output_bias[global_out_idx]);+ }+ d[simd_lane] = transformed;}}} else {diff --git a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rsindex 611e438a1..40f0d26d1 100644--- a/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/matmul/gemv/kernel.rs@@ -12,7 +12,7 @@ use crate::{HADAMARD_TRANSFORM_BLOCK_SIZE,gemm::{GemmBPrologueKind, GemmDTransform},},- kernel::matmul::{MatmulArguments, MatmulB, MatmulError},+ kernel::matmul::{MatmulA, MatmulArguments, MatmulB, MatmulError},},metal::{Metal, context::MetalContext, device_tier::DeviceTier, kernel::GemvMetalKernel},},@@ -49,7 +49,7 @@ impl GemvSpecialization {output_data_type: DataType,device_tier: DeviceTier,) -> Option<GemvSpecialization> {- if !args.b_transpose {+ if !args.b_transpose || !matches!(args.a, MatmulA::FullPrecision { .. }) {return None;}let is_quant = !matches!(args.b, MatmulB::FullPrecision { .. });@@ -185,7 +185,6 @@ impl GemvDispatch {let MatmulArguments {a,- a_offset,b,d,m,@@ -194,6 +193,16 @@ impl GemvDispatch {gather_indices,..} = arguments;+ let MatmulA::FullPrecision {+ values: a,+ offset: a_offset,+ } = a+ else {+ return Err(MatmulError::IncompatibleA {+ path: "Gemv",+ reason: "prepared int8 activations require GEMM",+ });+ };let group_count_x = n.div_ceil(rows_per_threadgroup(specialization.k_split,diff --git a/crates/backend-uzu/src/backends/metal/kernel/mod.rs b/crates/backend-uzu/src/backends/metal/kernel/mod.rsindex 429e646c8..29d21e422 100644--- a/crates/backend-uzu/src/backends/metal/kernel/mod.rs+++ b/crates/backend-uzu/src/backends/metal/kernel/mod.rs@@ -30,3 +30,7 @@ impl Kernels for MetalKernels {type MatmulKernel = matmul::MatmulMetalKernel;type RadixTopKSmall = radix_top_k_small::MetalRadixTopKSmall;}++#[cfg(test)]+#[path = "../../../../tests/unit/backends/metal/kernel/rht_quantize_activations_test.rs"]+mod rht_quantize_activations_test;diff --git a/crates/backend-uzu/src/backends/metal/kernel/rht_quantize_activations/rht_quantize_activations.metal b/crates/backend-uzu/src/backends/metal/kernel/rht_quantize_activations/rht_quantize_activations.metalnew file mode 100644index 000000000..54db55b69--- /dev/null+++ b/crates/backend-uzu/src/backends/metal/kernel/rht_quantize_activations/rht_quantize_activations.metal@@ -0,0 +1,37 @@+#include <metal_stdlib>+#include "../common/defines.h"+#include "../common/dsl.h"+#include "../hadamard_transform/hadamard_transform.h"++using namespace metal;++UZU_CONST float SYM_QMAX = 127.0;++template <typename InputT>+VARIANTS(InputT, float, bfloat)+PUBLIC KERNEL(RHTQuantizeActivations)(+ const device InputT* input,+ device int8_t* q_out,+ device float* scales_out,+ const device int32_t* rht_factors,+ constant uint& batch_size,+ constant uint& element_count,+ constant uint& group_size,+ uint block_index GROUPS(element_count.div_ceil(METAL_SIMD_SIZE)),+ uint batch_index GROUPS(batch_size),+ uint lane_index THREADS(METAL_SIMD_SIZE)+) {+ const uint factor_index = block_index * METAL_SIMD_SIZE + lane_index;+ const uint element_index = batch_index * element_count + factor_index;++ float value = static_cast<float>(input[element_index]);+ value = simdgroup_input_random_hadamard_transform(lane_index, value, rht_factors[factor_index]);++ const float magnitude = max(fabs(simd_min(value)), fabs(simd_max(value)));+ const float scale = isfinite(magnitude) && magnitude > 0.0f ? magnitude / SYM_QMAX : 1.0f;+ if (lane_index == 0) {+ scales_out[batch_index * (element_count / group_size) + block_index] = scale;+ }++ q_out[element_index] = static_cast<int8_t>(clamp(round(value / scale), -SYM_QMAX, SYM_QMAX));+}diff --git a/crates/backend-uzu/src/backends/metal/mod.rs b/crates/backend-uzu/src/backends/metal/mod.rsindex 22edc84b3..045b68c00 100644--- a/crates/backend-uzu/src/backends/metal/mod.rs+++ b/crates/backend-uzu/src/backends/metal/mod.rs@@ -19,4 +19,8 @@ const _: () = {pub use backend::Metal;pub use context::MetalContext;+#[cfg(test)]+pub(crate) use device_tier::DeviceTier;pub use kernel::matmul::GemmDispatchPath;+#[cfg(test)]+pub(crate) use kernel::matmul::gemv::{GemvDispatch, GemvSpecialization};diff --git a/crates/backend-uzu/src/encodable_block/embedding.rs b/crates/backend-uzu/src/encodable_block/embedding.rsindex 6ae003af2..081716246 100644--- a/crates/backend-uzu/src/encodable_block/embedding.rs+++ b/crates/backend-uzu/src/encodable_block/embedding.rs@@ -8,7 +8,7 @@ use crate::{gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod, QuantizationMode},kernel::{FullPrecisionEmbeddingLookupKernel, LogitSoftCapKernel, QuantizedEmbeddingLookupKernel,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},config::{@@ -547,8 +547,10 @@ impl<B: Backend> Embedding<B> {},} => {let arguments = MatmulArguments {- a: input_allocation,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: input_allocation,+ offset: 0,+ },b: MatmulB::FullPrecision {b: weights,},@@ -631,8 +633,10 @@ impl<B: Backend> Embedding<B> {.lock().encode(MatmulArguments {- a: input_allocation,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: input_allocation,+ offset: 0,+ },b,b_leading_dimension: None,b_transpose: true,@@ -707,8 +711,10 @@ impl<B: Backend> Embedding<B> {.lock().encode(MatmulArguments {- a: input,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: input,+ offset: 0,+ },b: MatmulB::FullPrecision {b: weights,},diff --git a/crates/backend-uzu/src/encodable_block/linear/matmul.rs b/crates/backend-uzu/src/encodable_block/linear/matmul.rsindex beafbb42a..f2f97d943 100644--- a/crates/backend-uzu/src/encodable_block/linear/matmul.rs+++ b/crates/backend-uzu/src/encodable_block/linear/matmul.rs@@ -8,7 +8,7 @@ use crate::{gpu_types::{QuantizationMethod, QuantizationMode},kernel::{Kernels,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},config::weight_matrix::{AnyWeightMatrixSpec, Layout, int_spec::IntSpec, mlx_spec::MLXSpec},@@ -208,10 +208,10 @@ fn load_biases<B: Backend>(.transpose()?)}-impl<B: Backend> Linear<B> for LinearMatmul<B> {- fn encode(+impl<B: Backend> LinearMatmul<B> {+ pub(super) fn encode_with_a(&self,- input: Allocation<B>,+ a: MatmulA<'_, B>,batch_dim: usize,encoder: &mut Encoder<B>,) -> Result<Allocation<B>, B::Error> {@@ -270,8 +270,7 @@ impl<B: Backend> Linear<B> for LinearMatmul<B> {self.kernel.lock().encode(MatmulArguments {- a: &input,- a_offset: 0,+ a,b,b_leading_dimension: None,b_transpose: true,@@ -288,3 +287,21 @@ impl<B: Backend> Linear<B> for LinearMatmul<B> {Ok(output)}}++impl<B: Backend> Linear<B> for LinearMatmul<B> {+ fn encode(+ &self,+ input: Allocation<B>,+ batch_dim: usize,+ encoder: &mut Encoder<B>,+ ) -> Result<Allocation<B>, B::Error> {+ self.encode_with_a(+ MatmulA::FullPrecision {+ values: &input,+ offset: 0,+ },+ batch_dim,+ encoder,+ )+ }+}diff --git a/crates/backend-uzu/src/encodable_block/linear/mod.rs b/crates/backend-uzu/src/encodable_block/linear/mod.rsindex dec2968d4..a9c1c8b39 100644--- a/crates/backend-uzu/src/encodable_block/linear/mod.rs+++ b/crates/backend-uzu/src/encodable_block/linear/mod.rs@@ -4,6 +4,7 @@ mod rht_wrapper;pub use matmul::{LinearMatmul, LinearMatmulError};pub use qlora_wrapper::{QLoRALinearWrapper, QLoRALinearWrapperError};+use rht_wrapper::int8_activations_eligible;pub use rht_wrapper::{RHTLinearWrapper, RHTLinearWrapperError};use thiserror::Error;@@ -216,8 +217,29 @@ impl<B: Backend> dyn Linear<B> {incoherence_block_size: Some(HADAMARD_TRANSFORM_BLOCK_SIZE),incoherence_processing_mode: IncoherenceProcessingMode::InputOutput,..- }) = spec+ }) = &spec{+ let quantization_spec = weights_tree.subtree("quantized")?.metadata::<AnyWeightMatrixSpec>("spec")?;+ if int8_activations_eligible::<B>(+ context,+ &quantization_spec,+ input_dimension,+ input_data_type,+ output_data_type,+ ) {+ let linear = RHTLinearWrapper::new(+ context,+ input_dimension,+ output_dimension_sum,+ has_biases,+ weights_data_type,+ input_data_type,+ output_data_type,+ parameter_tree,+ )?;+ return Ok((Box::new(linear), None));+ }+let input_factors = weights_tree.leaf("incoherence_signs.input_signs")?.validate(&[input_dimension], DataType::I32)?diff --git a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rsindex 7a1b67f95..48508a8bc 100644--- a/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs+++ b/crates/backend-uzu/src/encodable_block/linear/qlora_wrapper.rs@@ -8,7 +8,7 @@ use crate::{gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, HadamardTransformOrder},kernel::{HadamardTransformKernel, Kernels,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},config::weight_matrix::{AnyWeightMatrixSpec, hybrid_spec::IncoherenceProcessingMode, low_rank_spec::LowRankSpec},@@ -175,8 +175,10 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {let mut adapter_kernel = self.adapter_down_kernel.lock();adapter_kernel.encode(MatmulArguments {- a: &input,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: &input,+ offset: 0,+ },b: MatmulB::FullPrecision {b: &self.adapter_down,},@@ -215,8 +217,10 @@ impl<B: Backend> Linear<B> for QLoRALinearWrapper<B> {let mut adapter_kernel = self.adapter_up_kernel.lock();adapter_kernel.encode(MatmulArguments {- a: &intermediate,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: &intermediate,+ offset: 0,+ },b: MatmulB::FullPrecision {b: &self.adapter_up,},diff --git a/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs b/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rsindex 1e18afaef..4ccf94fb4 100644--- a/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs+++ b/crates/backend-uzu/src/encodable_block/linear/rht_wrapper.rs@@ -1,24 +1,68 @@use thiserror::Error;use crate::{+ array::size_for_shape,backends::common::{- Allocation, Backend, Encoder,+ Allocation, Backend, Context, DeviceCapabilities, Encoder,gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, HadamardTransformOrder},- kernel::{HadamardTransformKernel, Kernels},+ kernel::{HadamardTransformKernel, Kernels, RHTQuantizeActivationsKernel, matmul::MatmulA},},config::weight_matrix::{- AnyWeightMatrixSpec,+ AnyWeightMatrixSpec, Layout,hybrid_spec::{HybridSpec, IncoherenceProcessingMode},+ int_spec::IntSpec,+ mlx_spec::MLXSpec,},data_type::DataType,- encodable_block::linear::{Linear, OutputHadamardLinearError},+ encodable_block::linear::{Linear, LinearMatmul, LinearMatmulError},parameters::{ParameterLoaderError, ParameterTree},};+// Temporary, for testing only: flip to false to run linear layers on the bf16+// activation path without touching model configs.+const INT8_ACTIVATIONS_ENABLED: bool = true;++pub(super) fn int8_activations_eligible<B: Backend>(+ context: &B::Context,+ quantization_spec: &AnyWeightMatrixSpec,+ input_dimension: usize,+ input_data_type: DataType,+ output_data_type: DataType,+) -> bool {+ if !INT8_ACTIVATIONS_ENABLED {+ return false;+ }+ if !context.device_capabilities().contains(DeviceCapabilities::NATIVE_INT8_MATMUL) {+ return false;+ }+ if input_data_type != DataType::BF16 || output_data_type != DataType::BF16 {+ return false;+ }+ let (bits, group_size) = match quantization_spec {+ AnyWeightMatrixSpec::IntSpec(IntSpec {+ bits,+ group_size,+ layout: Layout::OutputInput,+ ..+ })+ | AnyWeightMatrixSpec::MLXSpec(MLXSpec {+ bits,+ group_size,+ layout: Layout::OutputInput,+ ..+ }) => (*bits, *group_size),+ _ => return false,+ };+ matches!(bits, 4 | 8)+ && matches!(group_size, 32 | 64 | 128)+ && input_dimension.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE)+ && input_dimension.is_multiple_of(group_size)+}+#[derive(Debug, Error)]pub enum RHTLinearWrapperError<B: Backend> {#[error("Inner linear error: {0}")]- InnerLinearError(#[from] OutputHadamardLinearError<B>),+ InnerLinearError(#[from] LinearMatmulError<B>),#[error("Parameter loading error: {0}")]ParameterError(#[from] ParameterLoaderError<B>),#[error("Backend error: {0}")]@@ -27,10 +71,15 @@ pub enum RHTLinearWrapperError<B: Backend> {UnsupportedConfiguration(String),}+struct SymmetricInt8Preparation<B: Backend> {+ kernel: <B::Kernels as Kernels>::RHTQuantizeActivationsKernel,+}+pub struct RHTLinearWrapper<B: Backend> {input_hadamard_kernel: <B::Kernels as Kernels>::HadamardTransformKernel,+ symmetric_int8_preparation: Option<SymmetricInt8Preparation<B>>,input_factors: Allocation<B>,- inner_linear: Box<dyn Linear<B>>,+ inner_linear: LinearMatmul<B>,input_dimension: usize,}@@ -65,26 +114,50 @@ impl<B: Backend> RHTLinearWrapper<B> {.leaf("incoherence_signs.output_signs")?.validate(&[output_dimension], DataType::I32)?.read_allocation()?;+ let quantized_weights_tree = weights_tree.subtree("quantized")?;+ let quantization_spec = quantized_weights_tree.metadata::<AnyWeightMatrixSpec>("spec")?;+let input_hadamard_kernel = <B::Kernels as Kernels>::HadamardTransformKernel::new(context,input_data_type,HadamardTransformOrder::Input,).map_err(RHTLinearWrapperError::BackendError)?;- let inner_linear = <dyn Linear<B>>::new_with_output_hadamard_mixed_precision(++ let symmetric_int8_preparation = if int8_activations_eligible::<B>(context,- parameter_tree,- output_factors,+ &quantization_spec,+ input_dimension,+ input_data_type,+ output_data_type,+ ) {+ Some(+ <B::Kernels as Kernels>::RHTQuantizeActivationsKernel::new(context, input_data_type)+ .map(|kernel| SymmetricInt8Preparation {+ kernel,+ })+ .map_err(RHTLinearWrapperError::BackendError)?,+ )+ } else {+ None+ };++ let inner_linear = LinearMatmul::quantized(+ context,+ quantization_spec,input_dimension,output_dimension,- has_biases,weights_data_type,input_data_type,output_data_type,+ &quantized_weights_tree,+ has_biases.then_some(parameter_tree),+ Some(output_factors),)?;Ok(Self {input_hadamard_kernel,+ symmetric_int8_preparation,input_factors,inner_linear,input_dimension,@@ -95,10 +168,37 @@ impl<B: Backend> RHTLinearWrapper<B> {impl<B: Backend> Linear<B> for RHTLinearWrapper<B> {fn encode(&self,- mut input: Allocation<B>,+ input: Allocation<B>,batch_dim: usize,encoder: &mut Encoder<B>,) -> Result<Allocation<B>, B::Error> {+ if let Some(preparation) = &self.symmetric_int8_preparation {+ let groups_per_row = self.input_dimension.div_ceil(HADAMARD_TRANSFORM_BLOCK_SIZE);+ let mut values =+ encoder.allocate_scratch(size_for_shape(&[batch_dim, self.input_dimension], DataType::I8))?;+ let mut scales = encoder.allocate_scratch(size_for_shape(&[batch_dim, groups_per_row], DataType::F32))?;++ preparation.kernel.encode(+ &input,+ &mut values,+ &mut scales,+ &self.input_factors,+ batch_dim as u32,+ self.input_dimension as u32,+ HADAMARD_TRANSFORM_BLOCK_SIZE as u32,+ encoder,+ );+ return self.inner_linear.encode_with_a(+ MatmulA::Int8Symmetric {+ values: &values,+ scales: &scales,+ },+ batch_dim,+ encoder,+ );+ }++ let mut input = input;self.input_hadamard_kernel.encode(&mut input,&self.input_factors,diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rsindex be55a128e..c5d5e421b 100644--- a/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/core/fallback.rs@@ -6,7 +6,7 @@ use crate::{Allocation, Backend, BufferArg, Encoder, Kernels,kernel::{AttentionFallbackScatterScoresKernel, AttentionFallbackScatterValuesKernel, SoftmaxKernel,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},data_type::DataType,@@ -91,8 +91,10 @@ impl<B: Backend> AttentionFallbackCore<B> {for group_index in 0..self.num_groups {self.matmul.lock().encode(MatmulArguments {- a: arguments.queries,- a_offset: group_index * gqa_factor * arguments.suffix_length * self.head_dim * dt_bytes,+ a: MatmulA::FullPrecision {+ values: arguments.queries,+ offset: group_index * gqa_factor * arguments.suffix_length * self.head_dim * dt_bytes,+ },b: MatmulB::FullPrecision {b: (arguments.keys, group_index * self.head_dim * dt_bytes),},@@ -140,8 +142,10 @@ impl<B: Backend> AttentionFallbackCore<B> {for group_index in 0..self.num_groups {self.matmul.lock().encode(MatmulArguments {- a: &scores,- a_offset: group_index * gqa_factor * arguments.suffix_length * sequence_length * dt_bytes,+ a: MatmulA::FullPrecision {+ values: &scores,+ offset: group_index * gqa_factor * arguments.suffix_length * sequence_length * dt_bytes,+ },b: MatmulB::FullPrecision {b: (arguments.values, group_index * self.head_dim * dt_bytes),},diff --git a/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs b/crates/backend-uzu/src/encodable_block/mixer/attention/state.rsindex 2ba828942..3150c43a7 100644--- a/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs+++ b/crates/backend-uzu/src/encodable_block/mixer/attention/state.rs@@ -2,7 +2,7 @@ use std::any::Any;use crate::{backends::common::{- Backend, Buffer, Context, Encoder, Kernels, SparseBuffer,+ Backend, Buffer, Context, DeviceCapabilities, Encoder, Kernels, SparseBuffer,gpu_types::{Copy, ring::RingParams},kernel::KVCacheUpdateKernel,},@@ -109,7 +109,7 @@ impl<B: Backend> AttentionState<B> {let kv_buffer_bytes = max_elements * element_size * data_type.size_in_bytes();let is_ring = matches!(state_type, AttentionStateType::Ring { .. });- let is_sparse = !is_ring && context.sparse_buffers_supported();+ let is_sparse = !is_ring && context.device_capabilities().contains(DeviceCapabilities::SPARSE_BUFFERS);let (keys, values): (Box<dyn Buffer<Backend = B>>, Box<dyn Buffer<Backend = B>>) = if is_sparse {(diff --git a/crates/backend-uzu/src/engine/language_model/mod.rs b/crates/backend-uzu/src/engine/language_model/mod.rsindex 243c8d976..97aeb8666 100644--- a/crates/backend-uzu/src/engine/language_model/mod.rs+++ b/crates/backend-uzu/src/engine/language_model/mod.rs@@ -3,7 +3,7 @@ use std::{fs::File, io, io::BufReader, path::Path, sync::Arc};use thiserror::Error;use crate::{- backends::common::{Backend, Context, Kernels, kernel::ContextRingUpdateKernel},+ backends::common::{Backend, Context, DeviceCapabilities, Kernels, kernel::ContextRingUpdateKernel},config::model::{generation::GenerationConfig, language_model::LanguageModelConfig},data_type::DataType,encodable_block::{@@ -122,7 +122,7 @@ impl<B: Backend> LanguageModel<B> {let max_context_length = self.max_context_length();// TODO: This is not the correct way to do it, there should be a real memory model- if self.context.sparse_buffers_supported() {+ if self.context.device_capabilities().contains(DeviceCapabilities::SPARSE_BUFFERS) {// We just assume that all mixers use sparse if it's available to make max context free until it's actually used// Currenlty true for all mixers in uzu:// - full attention uses sparse if it's available to make max context free until it's actually useddiff --git a/crates/backend-uzu/src/tests/matmul/harness.rs b/crates/backend-uzu/src/tests/matmul/harness.rsindex afa46974d..bfa214161 100644--- a/crates/backend-uzu/src/tests/matmul/harness.rs+++ b/crates/backend-uzu/src/tests/matmul/harness.rs@@ -10,7 +10,7 @@ use crate::{AllocationType, Backend, Context, Encoder,kernel::{Kernels,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},cpu::Cpu,@@ -157,8 +157,10 @@ fn run<B: Backend, T: ArrayElement + Float>(encode(kernel,MatmulArguments {- a: &a_allocation,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: &a_allocation,+ offset: 0,+ },b: MatmulB::FullPrecision {b: &b_allocation,},diff --git a/crates/backend-uzu/src/tests/matmul/quant.rs b/crates/backend-uzu/src/tests/matmul/quant.rsindex af49f65b5..46015ddeb 100644--- a/crates/backend-uzu/src/tests/matmul/quant.rs+++ b/crates/backend-uzu/src/tests/matmul/quant.rs@@ -10,17 +10,25 @@ use crate::{backends::{common::{Allocation, Backend, Context, Encoder,- gpu_types::{QuantizationMethod, QuantizationMode},+ gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod, QuantizationMode},kernel::{Kernels,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},- cpu::Cpu,+ cpu::{+ Cpu,+ kernel::rht_quantize_activations::{min_max_symmetric_divisor, quantize_symmetric_i8},+ },},tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},};+pub struct PreparedInt8A {+ pub values: Vec<i8>,+ pub scales: Vec<f32>,+}+pub struct QuantInput<T: ArrayElement + Float> {pub w_packed: Vec<u32>,pub scales: Vec<T>,@@ -33,12 +41,13 @@ pub struct QuantInput<T: ArrayElement + Float> {pub group_size: u32,pub quant_method: QuantizationMethod,pub mode: QuantizationMode,+ pub prepared_a: Option<PreparedInt8A>,}fn mode_for_bits(bits: u32) -> QuantizationMode {match bits {4 => QuantizationMode::U4,- 8 => QuantizationMode::I8,+ 8 => QuantizationMode::U8,_ => unreachable!("unsupported bits: {bits}"),}}@@ -89,7 +98,41 @@ impl<T: ArrayElement + Float> QuantInput<T> {group_size,quant_method,mode: mode_for_bits(bits),+ prepared_a: None,+ }+ }++ pub fn with_prepared_a(mut self) -> Self {+ let group_size = HADAMARD_TRANSFORM_BLOCK_SIZE;+ let rows = self.m as usize;+ let columns = self.k as usize;+ let groups = columns.div_ceil(group_size);+ let mut values = vec![0i8; rows * columns];+ let mut scales = vec![0.0f32; rows * groups];++ for row in 0..rows {+ for group in 0..groups {+ let start = group * group_size;+ let end = (start + group_size).min(columns);+ let prepared =+ (start..end).map(|column| self.x[row * columns + column].to_f32().unwrap()).collect::<Vec<_>>();+ let divisor = min_max_symmetric_divisor(&prepared);+ scales[row * groups + group] = divisor;+ for (column, value) in (start..end).zip(prepared) {+ values[row * columns + column] = quantize_symmetric_i8(value, divisor);+ }+ }}++ self.prepared_a = Some(PreparedInt8A {+ values,+ scales,+ });+ self+ }++ fn weights_for_upload(&self) -> Vec<u32> {+ self.w_packed.clone()}pub(crate) fn weight_buffer_bytes(&self) -> usize {@@ -106,6 +149,8 @@ pub struct QuantBuffers<B: Backend, T: ArrayElement + Float> {pub zp: Option<Allocation<B>>,pub bias: Option<Allocation<B>>,pub x: Allocation<B>,+ pub prepared_a: Option<Allocation<B>>,+ pub prepared_a_scales: Option<Allocation<B>>,pub y: Allocation<B>,_t: std::marker::PhantomData<T>,}@@ -116,11 +161,19 @@ impl<B: Backend, T: ArrayElement + Float> QuantBuffers<B, T> {input: &QuantInput<T>,) -> Self {Self {- w: alloc_allocation_with_data::<B, u32>(context, &input.w_packed),+ w: alloc_allocation_with_data::<B, u32>(context, &input.weights_for_upload()),scales: alloc_allocation_with_data::<B, T>(context, &input.scales),zp: input.zero_points.as_ref().map(|zp| alloc_allocation_with_data::<B, u8>(context, zp)),bias: input.biases.as_ref().map(|b| alloc_allocation_with_data::<B, T>(context, b)),x: alloc_allocation_with_data::<B, T>(context, &input.x),+ prepared_a: input+ .prepared_a+ .as_ref()+ .map(|prepared| alloc_allocation_with_data::<B, i8>(context, &prepared.values)),+ prepared_a_scales: input+ .prepared_a+ .as_ref()+ .map(|prepared| alloc_allocation_with_data::<B, f32>(context, &prepared.scales)),y: alloc_allocation::<B, T>(context, (input.m as usize) * (input.n as usize)),_t: std::marker::PhantomData,}@@ -153,9 +206,18 @@ pub fn quant_arguments<'a, B: Backend, T: ArrayElement + Float>(group_size: input.group_size,},};+ let a = match &input.prepared_a {+ Some(_) => MatmulA::Int8Symmetric {+ values: buffers.prepared_a.as_ref().expect("prepared activation buffer"),+ scales: buffers.prepared_a_scales.as_ref().expect("prepared activation scales"),+ },+ None => MatmulA::FullPrecision {+ values: &buffers.x,+ offset: 0,+ },+ };MatmulArguments {- a: &buffers.x,- a_offset: 0,+ a,b: b_variant,b_leading_dimension: None,b_transpose: true,diff --git a/crates/backend-uzu/src/tests/matmul/shape.rs b/crates/backend-uzu/src/tests/matmul/shape.rsindex d0760c519..29402382d 100644--- a/crates/backend-uzu/src/tests/matmul/shape.rs+++ b/crates/backend-uzu/src/tests/matmul/shape.rs@@ -79,22 +79,23 @@ pub fn bench_quant_gemv_shapes(bits: u32) -> impl Iterator<Item = Shape> {}const QWEN3_LAYERS: &[(&str, usize, usize)] = &[- ("0.6b_qkv", 1024, 4096),- ("0.6b_o", 2048, 1024),- ("0.6b_gateup", 1024, 6144),- ("0.6b_down", 3072, 1024),- ("1.7b_qkv", 2048, 4096),- ("1.7b_o", 2048, 2048),- ("1.7b_gateup", 2048, 12288),- ("1.7b_down", 6144, 2048),+ ("0.8b_qkv", 1024, 3072),+ ("0.8b_o", 2048, 1024),+ ("0.8b_gate", 1024, 2048),+ ("0.8b_up", 1024, 7168),+ ("0.8b_down", 3584, 1024),+ ("0.8b_in", 1024, 8224),+ ("2b_qkv", 2048, 3072),+ ("2b_o", 2048, 2048),+ ("2b_up", 2048, 12288),+ ("2b_down", 6144, 2048),+ ("2b_in", 2048, 8224),("4b_qkv", 2560, 6144),("4b_o", 4096, 2560),- ("4b_gateup", 2560, 19456),- ("4b_down", 9728, 2560),- ("8b_qkv", 4096, 6144),- ("8b_o", 4096, 4096),- ("8b_gateup", 4096, 24576),- ("8b_down", 12288, 4096),+ ("4b_gate", 2560, 4096),+ ("4b_up", 2560, 18432),+ ("4b_down", 9216, 2560),+ ("4b_in", 2560, 12352),];pub fn qwen3_layer_shapes(bits: u32) -> impl Iterator<Item = (&'static str, Shape)> {@@ -103,13 +104,9 @@ pub fn qwen3_layer_shapes(bits: u32) -> impl Iterator<Item = (&'static str, Shap} else {256};- let decode_ms = &[1usize, 4, 8];- let prefill_ms = &[32usize, 64];- QWEN3_LAYERS.iter().flat_map(move |&(label, k, n)| {- decode_ms- .iter()- .chain(prefill_ms.iter())- .filter(move |_| k % block_size == 0)- .map(move |&m| (label, Shape::new(m, k, n)))- })+ let ms = &[1usize, 2, 4, 8, 16, 32, 64];+ QWEN3_LAYERS+ .iter()+ .filter(move |&&(_, k, _)| k.is_multiple_of(block_size))+ .flat_map(move |&(label, k, n)| ms.iter().map(move |&m| (label, Shape::new(m, k, n))))}diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_fallback_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_fallback_test.rsindex 4e64548b9..78efa57a7 100644--- a/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_fallback_test.rs+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/attention/attention_fallback_test.rs@@ -9,7 +9,7 @@ use crate::{kernel::{AttentionFallbackScatterScoresKernel, AttentionFallbackScatterValuesKernel, AttentionSinglePassKernel,SoftmaxKernel,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},cpu::Cpu,@@ -132,8 +132,10 @@ fn pipeline_output<B: Backend>(matmul.encode(MatmulArguments {- a: &qa,- a_offset: g as usize * GQA as usize * SUFFIX as usize * q_row,+ a: MatmulA::FullPrecision {+ values: &qa,+ offset: g as usize * GQA as usize * SUFFIX as usize * q_row,+ },b: MatmulB::FullPrecision {b: (&ka, g as usize * head_stride * dt),},@@ -171,8 +173,10 @@ fn pipeline_output<B: Backend>(matmul.encode(MatmulArguments {- a: &scores,- a_offset: g as usize * GQA as usize * SUFFIX as usize * s_row,+ a: MatmulA::FullPrecision {+ values: &scores,+ offset: g as usize * GQA as usize * SUFFIX as usize * s_row,+ },b: MatmulB::FullPrecision {b: (&va, g as usize * head_stride * dt),},diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/a8w_bench.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/a8w_bench.rsnew file mode 100644index 000000000..d671a605e--- /dev/null+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/a8w_bench.rs@@ -0,0 +1,280 @@+#![cfg(metal_backend)]++use std::time::Duration;++use criterion::{BenchmarkId, Criterion, Throughput};+use half::bf16;+use proc_macros::uzu_bench;++use crate::{+ backends::{+ common::{+ Allocation, Backend, Encoder,+ gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, HadamardTransformOrder, QuantizationMethod, QuantizationMode},+ kernel::{+ HadamardTransformKernel, Kernels, RHTQuantizeActivationsKernel,+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ },+ },+ metal::{DeviceTier, GemmDispatchPath, GemvDispatch, GemvSpecialization, Metal, MetalContext},+ },+ data_type::DataType,+ tests::{+ helpers::{alloc_allocation, alloc_allocation_with_data},+ matmul::{QuantInput, iter_encode_loop_named, qwen3_layer_shapes},+ util::{shared_metal_context, type_short_name},+ },+};++type MetalMatmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel;+type MetalPrepare = <<Metal as Backend>::Kernels as Kernels>::RHTQuantizeActivationsKernel;+type MetalHadamard = <<Metal as Backend>::Kernels as Kernels>::HadamardTransformKernel;++#[derive(Clone, Copy)]+enum BenchPath {+ A8GemmMxu,+ Bf16GemmMxu,+ Bf16Gemv,+}++impl BenchPath {+ fn label(self) -> &'static str {+ match self {+ BenchPath::A8GemmMxu => "a8_gemm_mxu",+ BenchPath::Bf16GemmMxu => "abf16_gemm_mxu",+ BenchPath::Bf16Gemv => "abf16_gemv",+ }+ }+}++struct BenchmarkData {+ weights_u8: Allocation<Metal>,+ weight_scales: Allocation<Metal>,+ activations: Allocation<Metal>,+ rht_factors: Allocation<Metal>,+ a_working: Allocation<Metal>,+ a_int8: Allocation<Metal>,+ a_scales: Allocation<Metal>,+ m: u32,+ k: u32,+ n: u32,+ group_size: u32,+ mode: QuantizationMode,+}++impl BenchmarkData {+ fn new(+ context: &MetalContext,+ m: usize,+ k: usize,+ n: usize,+ bits: u32,+ seed: u64,+ ) -> Self {+ let group_size = HADAMARD_TRANSFORM_BLOCK_SIZE as u32;+ let input = QuantInput::<bf16>::new(m, k, n, group_size, bits, QuantizationMethod::ScaleSymmetric, seed);++ let weights_u8 = alloc_allocation_with_data::<Metal, u32>(context, &input.w_packed);+ let weight_scales = alloc_allocation_with_data::<Metal, bf16>(context, &input.scales);+ let activations = alloc_allocation_with_data::<Metal, bf16>(context, &input.x);+ let rht: Vec<i32> = (0..k)+ .map(|index| {+ if index % 3 == 0 {+ -1+ } else {+ 1+ }+ })+ .collect();+ let rht_factors = alloc_allocation_with_data::<Metal, i32>(context, &rht);++ let groups = k / group_size as usize;+ Self {+ weights_u8,+ weight_scales,+ activations,+ rht_factors,+ a_working: alloc_allocation::<Metal, bf16>(context, m * k),+ a_int8: alloc_allocation::<Metal, i8>(context, m * k),+ a_scales: alloc_allocation::<Metal, f32>(context, m * groups),+ m: m as u32,+ k: k as u32,+ n: n as u32,+ group_size,+ mode: if bits == 4 {+ QuantizationMode::U4+ } else {+ QuantizationMode::U8+ },+ }+ }++ fn bf16_arguments<'a>(+ &'a self,+ output: &'a mut Allocation<Metal>,+ ) -> MatmulArguments<'a, 'a, 'a, Metal, &'a Allocation<Metal>> {+ MatmulArguments {+ a: MatmulA::FullPrecision {+ values: &self.a_working,+ offset: 0,+ },+ b: MatmulB::ScaleSymmetricDequant {+ b: &self.weights_u8,+ scales: &self.weight_scales,+ mode: self.mode,+ group_size: self.group_size,+ },+ b_leading_dimension: None,+ b_transpose: true,+ d: output,+ d_transform: MatmulDOps::none(),+ gather_indices: None,+ m: self.m,+ n: self.n,+ k: self.k,+ }+ }+}++#[allow(clippy::too_many_arguments)]+fn encode_step(+ path: BenchPath,+ data: &mut BenchmarkData,+ output: &mut Allocation<Metal>,+ prepare: &MetalPrepare,+ hadamard: &MetalHadamard,+ matmul: &mut MetalMatmul,+ gemv: &mut GemvDispatch,+ device_tier: DeviceTier,+ encoder: &mut Encoder<Metal>,+) {+ match path {+ BenchPath::A8GemmMxu => {+ prepare.encode(+ &data.activations,+ &mut data.a_int8,+ &mut data.a_scales,+ &data.rht_factors,+ data.m,+ data.k,+ HADAMARD_TRANSFORM_BLOCK_SIZE as u32,+ encoder,+ );+ let args: MatmulArguments<'_, '_, '_, Metal, &Allocation<Metal>> = MatmulArguments {+ a: MatmulA::Int8Symmetric {+ values: &data.a_int8,+ scales: &data.a_scales,+ },+ b: MatmulB::ScaleSymmetricDequant {+ b: &data.weights_u8,+ scales: &data.weight_scales,+ mode: data.mode,+ group_size: data.group_size,+ },+ b_leading_dimension: None,+ b_transpose: true,+ d: output,+ d_transform: MatmulDOps::none(),+ gather_indices: None,+ m: data.m,+ n: data.n,+ k: data.k,+ };+ matmul.gemm.encode_dispatch_path(args, GemmDispatchPath::Mxu, encoder).expect("a8 gemm mxu encode");+ },+ BenchPath::Bf16GemmMxu => {+ encoder.encode_copy(&data.activations, .., &mut data.a_working, ..);+ hadamard.encode(&mut data.a_working, &data.rht_factors, data.k, data.m, encoder);+ let args = data.bf16_arguments(output);+ matmul.gemm.encode_dispatch_path(args, GemmDispatchPath::Mxu, encoder).expect("bf16 gemm mxu encode");+ },+ BenchPath::Bf16Gemv => {+ encoder.encode_copy(&data.activations, .., &mut data.a_working, ..);+ hadamard.encode(&mut data.a_working, &data.rht_factors, data.k, data.m, encoder);+ let args = data.bf16_arguments(output);+ let spec = GemvSpecialization::select(&args, DataType::BF16, DataType::BF16, DataType::BF16, device_tier)+ .expect("bf16 gemv specialization");+ gemv.encode(args, spec, encoder).expect("bf16 gemv encode");+ },+ }+}++fn bench_bits(+ c: &mut Criterion,+ context: &MetalContext,+ device_tier: DeviceTier,+ prepare: &MetalPrepare,+ hadamard: &MetalHadamard,+ bits: u32,+) {+ let mut matmul = <MetalMatmul as MatmulKernel>::new(context, DataType::BF16, DataType::BF16, DataType::BF16)+ .expect("matmul kernel");+ let mut gemv = GemvDispatch::new(DataType::BF16, DataType::BF16, DataType::BF16);++ let mut group = c.benchmark_group(format!("{}/Kernel/A8W/w{bits}", type_short_name::<Metal>()));+ group.sample_size(10);+ group.warm_up_time(Duration::from_millis(100));+ group.measurement_time(Duration::from_millis(800));++ for (layer, shape) in qwen3_layer_shapes(bits) {+ let (m, k, n) = (shape.m, shape.k, shape.n);+ let mut data = BenchmarkData::new(context, m, k, n, bits, 0xA8_00 ^ u64::from(bits) ^ k as u64 ^ n as u64);+ let mut output = alloc_allocation::<Metal, bf16>(context, m * n);+ let shape_label = format!("{layer}_m{m}_k{k}_n{n}");++ let gemv_eligible = GemvSpecialization::select(+ &data.bf16_arguments(&mut output),+ DataType::BF16,+ DataType::BF16,+ DataType::BF16,+ device_tier,+ )+ .is_some();++ let mut paths = vec![BenchPath::A8GemmMxu, BenchPath::Bf16GemmMxu];+ if gemv_eligible {+ paths.push(BenchPath::Bf16Gemv);+ }++ group.throughput(Throughput::Elements((m * k * n) as u64));+ for path in paths {+ group.bench_function(BenchmarkId::new(path.label(), &shape_label), |bench| {+ let benchmark_path =+ format!("{}/Kernel/A8W/w{bits}/{}/{shape_label}", type_short_name::<Metal>(), path.label());+ iter_encode_loop_named::<Metal, _>(context, bench, &benchmark_path, |encoder| {+ encode_step(+ path,+ &mut data,+ &mut output,+ prepare,+ hadamard,+ &mut matmul,+ &mut gemv,+ device_tier,+ encoder,+ );+ });+ });+ }+ }+ group.finish();+}++#[uzu_bench]+fn bench_a8w(c: &mut Criterion) {+ let context = shared_metal_context();+ if !context.supports_mxu() {+ return;+ }+ let device_tier = context.device_tier();++ let prepare =+ <MetalPrepare as RHTQuantizeActivationsKernel>::new(&context, DataType::BF16).expect("prepare kernel");+ let hadamard =+ <MetalHadamard as HadamardTransformKernel>::new(&context, DataType::BF16, HadamardTransformOrder::Input)+ .expect("hadamard kernel");++ for bits in [8u32, 4u32] {+ bench_bits(c, &context, device_tier, &prepare, &hadamard, bits);+ }+}diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rsindex d5d430814..2a5bd330c 100644--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rs+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemm_bench.rs@@ -11,7 +11,7 @@ use crate::{Backend,kernel::{Kernels,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},metal::{GemmDispatchPath, Metal},@@ -56,8 +56,10 @@ fn bench_gemm(c: &mut Criterion) {.gemm.encode_dispatch_path(MatmulArguments {- a: &a,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: &a,+ offset: 0,+ },b: MatmulB::FullPrecision {b: &b_weights,},diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rsindex 932448051..8ee40cccf 100644--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rs+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/gemv_test.rs@@ -14,7 +14,7 @@ use crate::{gpu_types::QuantizationMethod,kernel::{Kernels,- matmul::{MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},+ matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},},},cpu::Cpu,@@ -77,8 +77,10 @@ fn run_gemv<'a, B: Backend, T: ArrayElement + Float>(kernel.encode(MatmulArguments {- a,- a_offset: 0,+ a: MatmulA::FullPrecision {+ values: a,+ offset: 0,+ },b,b_leading_dimension: None,b_transpose: true,diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/mod.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/mod.rsindex 66ee3725e..ab1716ec5 100644--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/mod.rs+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/mod.rs@@ -1,3 +1,4 @@+mod a8w_bench;mod dispatch_paths_test;mod gemm_bench;mod gemv_test;diff --git a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rsindex d9422a7f1..368ba2d11 100644--- a/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs+++ b/crates/backend-uzu/tests/unit/backends/common/kernel/matmul/quant_dispatch_test.rs@@ -311,8 +311,6 @@ fn parity_bf16_gemv_quant_rht_with_bias() {let bias_f32: Vec<f32> = (0..input.n as usize).map(|j| 0.3 + 0.05 * (j % 4) as f32).collect();let bias_t: Vec<bf16> = bias_f32.iter().map(|&v| bf16::from_f32(v)).collect();- // CPU reference applies bias before RHT (matmul loop adds bias, then the- // Hadamard pass transforms the result) — the same order GEMV uses.let cpu_context = <Cpu as Backend>::Context::new().expect("Cpu context");let mut cpu_buffers = QuantBuffers::<Cpu, bf16>::allocate(&cpu_context, &input);let cpu_rht = crate::tests::helpers::alloc_allocation_with_data::<Cpu, i32>(&cpu_context, &rht);@@ -488,3 +486,140 @@ fn mxu_quant_parity_bf16(0.5,);}++#[rstest]+#[test_attr(uzu_test)]+#[case::sym_w4_gs32(16usize, 32u32, 4u32, QuantizationMethod::ScaleSymmetric)]+#[case::sym_w8_gs64(16usize, 64u32, 8u32, QuantizationMethod::ScaleSymmetric)]+#[case::sym_w4_gs128(32usize, 128u32, 4u32, QuantizationMethod::ScaleSymmetric)]+#[case::bias_w4_gs32(16usize, 32u32, 4u32, QuantizationMethod::ScaleBias)]+#[case::bias_w8_gs64(16usize, 64u32, 8u32, QuantizationMethod::ScaleBias)]+#[case::bias_w4_gs128(32usize, 128u32, 4u32, QuantizationMethod::ScaleBias)]+#[case::zp_w4_gs32(16usize, 32u32, 4u32, QuantizationMethod::ScaleZeroPoint)]+#[case::zp_w8_gs64(16usize, 64u32, 8u32, QuantizationMethod::ScaleZeroPoint)]+#[case::zp_w4_gs128(32usize, 128u32, 4u32, QuantizationMethod::ScaleZeroPoint)]+#[case::m1_bias_w4_gs64(1usize, 64u32, 4u32, QuantizationMethod::ScaleBias)]+#[case::m1_zp_w8_gs32(1usize, 32u32, 8u32, QuantizationMethod::ScaleZeroPoint)]+#[case::m1_sym_w4_gs128(1usize, 128u32, 4u32, QuantizationMethod::ScaleSymmetric)]+fn a8w_mxu_parity_bf16(+ #[case] m: usize,+ #[case] weight_gs: u32,+ #[case] bits: u32,+ #[case] method: QuantizationMethod,+) {+ let context = MetalContext::new().expect("Metal context");+ if !context.supports_mxu() {+ return;+ }+ let (k, n) = (256usize, 128usize);+ let input = QuantInput::<bf16>::new(m, k, n, weight_gs, bits, method, 0).with_prepared_a();+ let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmDispatchPath::Mxu));+ let reference = run_quant_cpu::<bf16>(&input);+ assert_parity::<bf16>(+ &format!("A8W{bits} MXU m={m} weight_gs={weight_gs} method={method:?}"),+ &reference,+ &actual,+ 0.08,+ 0.8,+ );+}++#[rstest]+#[test_attr(uzu_test)]+#[case::w4_bias(4u32, false)]+#[case::w8_bias(8u32, false)]+#[case::w4_rht_bias(4u32, true)]+#[case::w8_rht_bias(8u32, true)]+fn a8w_mxu_output_bias_parity_bf16(+ #[case] bits: u32,+ #[case] with_output_hadamard: bool,+) {+ let context = MetalContext::new().expect("Metal context");+ if !context.supports_mxu() {+ return;+ }++ let (m, k, n) = (+ 16usize,+ 256usize,+ if with_output_hadamard {+ 64usize+ } else {+ 70usize+ },+ );+ let input = QuantInput::<bf16>::new(m, k, n, 32, bits, QuantizationMethod::ScaleSymmetric, 0).with_prepared_a();+ let output_bias: Vec<bf16> = (0..n).map(|column| bf16::from_f32(0.25 + 0.05 * (column % 7) as f32)).collect();+ let output_hadamard_factors: Option<Vec<i32>> = with_output_hadamard.then(|| {+ (0..n)+ .map(|column| {+ if column.is_multiple_of(2) {+ 1+ } else {+ -1+ }+ })+ .collect()+ });++ let cpu_context = <Cpu as Backend>::Context::new().expect("CPU context");+ let mut cpu_buffers = QuantBuffers::<Cpu, bf16>::allocate(&cpu_context, &input);+ let cpu_output_hadamard_factors = output_hadamard_factors+ .as_ref()+ .map(|factors| crate::tests::helpers::alloc_allocation_with_data::<Cpu, i32>(&cpu_context, factors));+ let mut cpu_matmul = <<Cpu as Backend>::Kernels as Kernels>::MatmulKernel::new(+ &cpu_context,+ bf16::data_type(),+ bf16::data_type(),+ bf16::data_type(),+ )+ .expect("CPU matmul kernel");+ let mut cpu_encoder = Encoder::<Cpu>::new(&cpu_context).expect("CPU encoder");+ let mut cpu_arguments = quant_arguments(&mut cpu_buffers, &input);+ cpu_arguments.d_transform = MatmulDOps {+ rht_factors: cpu_output_hadamard_factors.as_ref(),+ ..MatmulDOps::none()+ };+ cpu_matmul.encode(cpu_arguments, &mut cpu_encoder).expect("CPU A8W matmul");+ cpu_encoder.end_encoding().submit().wait_until_completed().unwrap();+ let mut reference = allocation_to_vec::<Cpu, bf16>(&cpu_buffers.y);+ for row in reference.chunks_exact_mut(n) {+ for (value, bias) in row.iter_mut().zip(&output_bias) {+ *value = bf16::from_f32(value.to_f32() + bias.to_f32());+ }+ }++ let mut metal_buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);+ let metal_output_bias = crate::tests::helpers::alloc_allocation_with_data::<Metal, bf16>(&context, &output_bias);+ let metal_output_hadamard_factors = output_hadamard_factors+ .as_ref()+ .map(|factors| crate::tests::helpers::alloc_allocation_with_data::<Metal, i32>(&context, factors));+ let mut metal_matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(+ &context,+ bf16::data_type(),+ bf16::data_type(),+ bf16::data_type(),+ )+ .expect("Metal matmul kernel");+ let mut metal_encoder = Encoder::<Metal>::new(&context).expect("Metal encoder");+ let mut metal_arguments = quant_arguments(&mut metal_buffers, &input);+ metal_arguments.d_transform = MatmulDOps {+ bias: Some(&metal_output_bias),+ rht_factors: metal_output_hadamard_factors.as_ref(),+ ..MatmulDOps::none()+ };+ metal_matmul+ .gemm+ .encode_dispatch_path(metal_arguments, GemmDispatchPath::Mxu, &mut metal_encoder)+ .expect("Metal A8W MXU matmul with output bias");+ metal_encoder.end_encoding().submit().wait_until_completed().unwrap();+ let actual = allocation_to_vec::<Metal, bf16>(&metal_buffers.y);++ assert_parity::<bf16>(+ &format!("A8W{bits} MXU output bias, output Hadamard={with_output_hadamard}"),+ &reference,+ &actual,+ 0.08,+ 0.8,+ );+}diff --git a/crates/backend-uzu/tests/unit/backends/metal/kernel/rht_quantize_activations_test.rs b/crates/backend-uzu/tests/unit/backends/metal/kernel/rht_quantize_activations_test.rsnew file mode 100644index 000000000..d5e3ab5f5--- /dev/null+++ b/crates/backend-uzu/tests/unit/backends/metal/kernel/rht_quantize_activations_test.rs@@ -0,0 +1,88 @@+#![cfg(metal_backend)]++use proc_macros::uzu_test;+use rand::{RngExt, SeedableRng, rngs::SmallRng};++use super::RHTQuantizeActivationsMetalKernel;+use crate::{+ backends::{+ common::{+ Backend, Context, Encoder,+ kernel::{Kernels, RHTQuantizeActivationsKernel},+ },+ cpu::Cpu,+ metal::{Metal, MetalContext},+ },+ data_type::DataType,+ tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},+};++#[uzu_test]+fn rht_quantize_matches_cpu() {+ let rows = 5usize;+ let columns = 96usize;+ let group_size = 32u32;+ let groups = columns.div_ceil(group_size as usize);++ let mut rng = SmallRng::seed_from_u64(0x5EED_0001);+ let input_data: Vec<f32> = (0..rows * columns).map(|_| rng.random_range(-1.0f32..1.0f32)).collect();+ let factors_data: Vec<i32> = (0..columns)+ .map(|i| {+ if i % 3 == 0 {+ -1+ } else {+ 1+ }+ })+ .collect();++ let metal = MetalContext::new().expect("metal");+ let cpu = <Cpu as Backend>::Context::new().expect("cpu");+ let mut metal_values = alloc_allocation::<Metal, i8>(&metal, rows * columns);+ let mut metal_scales = alloc_allocation::<Metal, f32>(&metal, rows * groups);+ let mut cpu_values = alloc_allocation::<Cpu, i8>(&cpu, rows * columns);+ let mut cpu_scales = alloc_allocation::<Cpu, f32>(&cpu, rows * groups);++ let metal_input = alloc_allocation_with_data::<Metal, f32>(&metal, &input_data);+ let metal_factors = alloc_allocation_with_data::<Metal, i32>(&metal, &factors_data);+ let cpu_input = alloc_allocation_with_data::<Cpu, f32>(&cpu, &input_data);+ let cpu_factors = alloc_allocation_with_data::<Cpu, i32>(&cpu, &factors_data);++ let metal_kernel = RHTQuantizeActivationsMetalKernel::new(&metal, DataType::F32).expect("metal prepare");+ let cpu_kernel = <<Cpu as Backend>::Kernels as Kernels>::RHTQuantizeActivationsKernel::new(&cpu, DataType::F32)+ .expect("cpu prepare");++ let mut metal_enc = Encoder::<Metal>::new(&metal).expect("metal encoder");+ metal_kernel.encode(+ &metal_input,+ &mut metal_values,+ &mut metal_scales,+ &metal_factors,+ rows as u32,+ columns as u32,+ group_size,+ &mut metal_enc,+ );+ metal_enc.end_encoding().submit().wait_until_completed().unwrap();++ let mut cpu_enc = Encoder::<Cpu>::new(&cpu).expect("cpu encoder");+ cpu_kernel.encode(+ &cpu_input,+ &mut cpu_values,+ &mut cpu_scales,+ &cpu_factors,+ rows as u32,+ columns as u32,+ group_size,+ &mut cpu_enc,+ );+ cpu_enc.end_encoding().submit().wait_until_completed().unwrap();++ let (mv, ms) = (allocation_to_vec::<Metal, i8>(&metal_values), allocation_to_vec::<Metal, f32>(&metal_scales));+ let (cv, cs) = (allocation_to_vec::<Cpu, i8>(&cpu_values), allocation_to_vec::<Cpu, f32>(&cpu_scales));+ for (i, (a, e)) in ms.iter().zip(&cs).enumerate() {+ let rel = (a - e).abs() / e.abs().max(1e-6);+ assert!(rel < 1e-3, "scale {i}: {a} != {e}");+ }+ assert!(mv.iter().zip(cv).all(|(a, e)| (*a as i32 - e as i32).abs() <= 1));+}diff --git a/crates/test-runner/Cargo.toml b/crates/test-runner/Cargo.tomlindex a904c388e..dffbb8641 100644--- a/crates/test-runner/Cargo.toml+++ b/crates/test-runner/Cargo.toml@@ -18,10 +18,14 @@ nightly-harness = [][dependencies]criterion.workspace = true+# Non-optional: the iOS `path.rs` (Documents dir via NSSearchPath) uses+# objc2-foundation unconditionally, so it must be linked for on-device builds.[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]-objc2 = { workspace = true, optional = true }-objc2-foundation = { workspace = true, optional = true }+objc2 = { workspace = true }+objc2-foundation = { workspace = true }-# GPU temperature for bench cooldown; keisoku is Apple-only.-[target.'cfg(target_vendor = "apple")'.dependencies]+# GPU temperature for bench cooldown. keisoku is macOS-only — its power /+# IOReport subsystem does not build for iOS — and cooldown is a dev-machine+# concern, so on-device (iOS) builds skip it (see metrics.rs stub).+[target.'cfg(target_os = "macos")'.dependencies]keisoku.workspace = truediff --git a/crates/test-runner/src/metrics.rs b/crates/test-runner/src/metrics.rsindex 2b78c4512..c8ba0fd67 100644--- a/crates/test-runner/src/metrics.rs+++ b/crates/test-runner/src/metrics.rs@@ -2,7 +2,7 @@ use std::{thread::sleep, time::Duration};const COOL_GPU_TEMP: f32 = 60.0;-#[cfg(target_vendor = "apple")]+#[cfg(target_os = "macos")]fn get_gpu_temp() -> f32 {let (sum, count) = keisoku::thermal_sensors().iter()@@ -15,7 +15,7 @@ fn get_gpu_temp() -> f32 {}}-#[cfg(not(target_vendor = "apple"))]+#[cfg(not(target_os = "macos"))]fn get_gpu_temp() -> f32 {0.0}