Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Model format 0.17.0 (#863)

uuuvn2095266fa727
diff --git a/crates/uzu-engine/src/backends/common/gpu_types/matmul.rs b/crates/uzu-engine/src/backends/common/gpu_types/matmul.rs
index 900b06b1d..77ca8331d 100644
--- a/crates/uzu-engine/src/backends/common/gpu_types/matmul.rs
+++ b/crates/uzu-engine/src/backends/common/gpu_types/matmul.rs
@@ -1,3 +1,5 @@
+pub const QUANT_PARAMS_GROUP_OUTPUT_ALIGNMENT: u32 = 4;
+
#[repr(C)]
#[allow(non_snake_case)]
#[derive(Debug, Default, Copy, Clone)]
@@ -7,6 +9,10 @@ pub struct GemmParams {
pub K: u32,
pub leading_dimension_a: u32,
pub leading_dimension_b: u32,
+ pub scale_output_stride: u32,
+ pub scale_group_stride: u32,
+ pub zero_point_output_stride: u32,
+ pub zero_point_group_stride: u32,
pub leading_dimension_d: u32,
pub threadgroups_per_column: u32,
pub threadgroups_per_row: u32,
diff --git a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
index 17cb688c8..64afa3ba3 100644
--- a/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/activation_transform.rs
@@ -2,7 +2,7 @@ use crate::{
backends::common::{
Allocation, Backend, Encoder, Kernels,
gpu_types::{ActivationTransformOp, HADAMARD_TRANSFORM_BLOCK_SIZE},
- kernel::ActivationTransformKernel,
+ kernel::{ActivationTransformKernel, matmul::Int8CodeLayout},
},
data_type::DataType,
};
@@ -16,12 +16,47 @@ fn assert_row_width(element_count: u32) {
pub const ACTIVATION_SCALE_GROUP_SIZE: u32 = 128;
+#[derive(Clone, Copy)]
+pub struct ActivationQuantization {
+ scale_group_size: u32,
+ sum_group_size: Option<u32>,
+ code_layout: Int8CodeLayout,
+}
+
+impl ActivationQuantization {
+ pub fn new(
+ scale_group_size: u32,
+ weight_group_size: u32,
+ emit_group_sums: bool,
+ code_layout: Int8CodeLayout,
+ ) -> Option<Self> {
+ (matches!(scale_group_size, 32 | 64 | 128)
+ && matches!(weight_group_size, 32 | 64 | 128)
+ && scale_group_size >= weight_group_size)
+ .then_some(Self {
+ scale_group_size,
+ sum_group_size: emit_group_sums.then_some(weight_group_size),
+ code_layout,
+ })
+ }
+
+ pub const fn scale_group_size(self) -> u32 {
+ self.scale_group_size
+ }
+
+ pub const fn sum_group_size(self) -> Option<u32> {
+ self.sum_group_size
+ }
+
+ pub const fn code_layout(self) -> Int8CodeLayout {
+ self.code_layout
+ }
+}
+
pub struct ActivationTransform<B: Backend> {
kernel: <B::Kernels as Kernels>::ActivationTransformKernel,
- ops: ActivationTransformOp,
in_place: bool,
- activation_group_size: u32,
- sum_group_size: Option<u32>,
+ quantization: Option<ActivationQuantization>,
}
impl<B: Backend> ActivationTransform<B> {
@@ -30,23 +65,25 @@ impl<B: Backend> ActivationTransform<B> {
data_type: DataType,
ops: ActivationTransformOp,
in_place: bool,
- activation_group_size: u32,
- sum_group_size: Option<u32>,
+ quantization: Option<ActivationQuantization>,
) -> Result<Self, B::Error> {
+ let (codes_grouped_by_nibble, scale_group_size, sum_group_size) = match quantization {
+ Some(q) => (q.code_layout.is_grouped_by_nibble(), q.scale_group_size, q.sum_group_size),
+ None => (false, HADAMARD_TRANSFORM_BLOCK_SIZE, None),
+ };
let kernel = <B::Kernels as Kernels>::ActivationTransformKernel::new(
context,
data_type,
ops,
+ codes_grouped_by_nibble,
in_place,
- activation_group_size,
+ scale_group_size,
sum_group_size.unwrap_or(HADAMARD_TRANSFORM_BLOCK_SIZE),
)?;
Ok(Self {
kernel,
- ops,
in_place,
- activation_group_size,
- sum_group_size,
+ quantization,
})
}
@@ -55,7 +92,7 @@ impl<B: Backend> ActivationTransform<B> {
data_type: DataType,
in_place: bool,
) -> Result<Self, B::Error> {
- Self::new(context, data_type, ActivationTransformOp::InputRht, in_place, HADAMARD_TRANSFORM_BLOCK_SIZE, None)
+ Self::new(context, data_type, ActivationTransformOp::InputRht, in_place, None)
}
pub fn output_rht(
@@ -63,28 +100,30 @@ impl<B: Backend> ActivationTransform<B> {
data_type: DataType,
in_place: bool,
) -> Result<Self, B::Error> {
- Self::new(context, data_type, ActivationTransformOp::OutputRht, in_place, HADAMARD_TRANSFORM_BLOCK_SIZE, None)
+ Self::new(context, data_type, ActivationTransformOp::OutputRht, in_place, None)
}
pub fn quantize(
context: &B::Context,
data_type: DataType,
- activation_group_size: u32,
- sum_group_size: Option<u32>,
+ quantization: ActivationQuantization,
) -> Result<Self, B::Error> {
- let ops = if sum_group_size.is_some() {
- ActivationTransformOp::QuantizeWithGroupSums
- } else {
- ActivationTransformOp::Quantize
- };
- if let Some(group_size) = sum_group_size {
- assert!(matches!(group_size, 32 | 64 | 128), "unsupported correction group ({group_size})");
- }
- assert!(
- matches!(activation_group_size, 32 | 64 | 128),
- "unsupported activation group ({activation_group_size})"
- );
- Self::new(context, data_type, ops, false, activation_group_size, sum_group_size)
+ let op = quantization
+ .sum_group_size()
+ .map_or(ActivationTransformOp::Quantize, |_| ActivationTransformOp::QuantizeWithGroupSums);
+ Self::new(context, data_type, op, false, Some(quantization))
+ }
+
+ pub fn scale_group_size(&self) -> u32 {
+ self.quantization.expect("quantized activation transform required").scale_group_size()
+ }
+
+ pub fn sum_group_size(&self) -> Option<u32> {
+ self.quantization.expect("quantized activation transform required").sum_group_size()
+ }
+
+ pub fn code_layout(&self) -> Int8CodeLayout {
+ self.quantization.expect("quantized activation transform required").code_layout()
}
/// `input` and `output` must be distinct buffers.
@@ -97,7 +136,7 @@ impl<B: Backend> ActivationTransform<B> {
element_count: u32,
encoder: &mut Encoder<B>,
) {
- assert!(!self.quantizes() && !self.in_place);
+ assert!(self.quantization.is_none() && !self.in_place);
assert_row_width(element_count);
self.kernel.encode(
Some(input),
@@ -120,7 +159,7 @@ impl<B: Backend> ActivationTransform<B> {
element_count: u32,
encoder: &mut Encoder<B>,
) {
- assert!(!self.quantizes() && self.in_place);
+ assert!(self.quantization.is_none() && self.in_place);
assert_row_width(element_count);
self.kernel.encode(
None::<&Allocation<B>>,
@@ -146,14 +185,14 @@ impl<B: Backend> ActivationTransform<B> {
element_count: u32,
encoder: &mut Encoder<B>,
) {
- assert!(self.quantizes());
+ let quantization = self.quantization.expect("quantized activation transform required");
assert_row_width(element_count);
assert!(
- element_count.is_multiple_of(self.activation_group_size),
+ element_count.is_multiple_of(quantization.scale_group_size()),
"quantized activation row ({element_count}) must be a multiple of scale group ({})",
- self.activation_group_size
+ quantization.scale_group_size()
);
- if let Some(group_size) = self.sum_group_size {
+ if let Some(group_size) = quantization.sum_group_size() {
assert!(element_count.is_multiple_of(group_size));
}
self.kernel.encode(
@@ -168,20 +207,4 @@ impl<B: Backend> ActivationTransform<B> {
encoder,
);
}
-
- fn quantizes(&self) -> bool {
- matches!(self.ops, ActivationTransformOp::Quantize | ActivationTransformOp::QuantizeWithGroupSums)
- }
-
- pub fn emit_group_sums(&self) -> bool {
- self.sum_group_size.is_some()
- }
-
- pub fn activation_group_size(&self) -> u32 {
- self.activation_group_size
- }
-
- pub fn sum_group_size(&self) -> Option<u32> {
- self.sum_group_size
- }
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs b/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs
index 7bcc47cec..16f531686 100644
--- a/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/gated_act_mul.rs
@@ -4,31 +4,12 @@ use crate::{
backends::common::{
Allocation, Backend, Encoder, Kernels,
gpu_types::{ActivationType, GatedActMulOp, HADAMARD_TRANSFORM_BLOCK_SIZE},
- kernel::GatedActMulKernel,
+ kernel::{ActivationQuantization, GatedActMulKernel},
},
config::clipping::ClippingBounds,
data_type::DataType,
};
-#[repr(u32)]
-#[derive(Clone, Copy)]
-enum GatedActMulGroupSize {
- Size32 = 32,
- Size64 = 64,
- Size128 = 128,
-}
-
-impl GatedActMulGroupSize {
- fn from_u32(value: u32) -> Self {
- match value {
- 32 => Self::Size32,
- 64 => Self::Size64,
- 128 => Self::Size128,
- _ => panic!("unsupported activation group size: {value}"),
- }
- }
-}
-
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct GatedActMulOptions: u8 {
@@ -47,11 +28,9 @@ pub struct GatedActMulSettings {
pub struct GatedActMul<B: Backend> {
kernel: <B::Kernels as Kernels>::GatedActMulKernel,
- ops: GatedActMulOp,
options: GatedActMulOptions,
settings: GatedActMulSettings,
- activation_group_size: u32,
- sum_group_size: u32,
+ quantization: Option<ActivationQuantization>,
}
impl<B: Backend> GatedActMul<B> {
@@ -65,53 +44,47 @@ impl<B: Backend> GatedActMul<B> {
let mut options = GatedActMulOptions::empty();
options.set(GatedActMulOptions::INTERLEAVED, interleaved);
options.set(GatedActMulOptions::HADAMARD, use_hadamard);
- Self::new(
- context,
- data_type,
- GatedActMulOp::FullPrecision,
- options,
- HADAMARD_TRANSFORM_BLOCK_SIZE,
- HADAMARD_TRANSFORM_BLOCK_SIZE,
- settings,
- )
+ Self::new(context, data_type, options, settings, None)
}
pub fn quantized(
context: &B::Context,
data_type: DataType,
- activation_group_size: u32,
- sum_group_size: Option<u32>,
+ quantization: ActivationQuantization,
settings: GatedActMulSettings,
) -> Result<Self, B::Error> {
- let activation_group_size = GatedActMulGroupSize::from_u32(activation_group_size);
- let sum_group_size = sum_group_size.map(GatedActMulGroupSize::from_u32);
- Self::new(
- context,
- data_type,
- sum_group_size.map_or(GatedActMulOp::Quantize, |_| GatedActMulOp::QuantizeWithGroupSums),
- GatedActMulOptions::INTERLEAVED | GatedActMulOptions::HADAMARD,
- activation_group_size as u32,
- sum_group_size.unwrap_or(activation_group_size) as u32,
- settings,
- )
+ let options = GatedActMulOptions::INTERLEAVED | GatedActMulOptions::HADAMARD;
+ Self::new(context, data_type, options, settings, Some(quantization))
}
fn new(
context: &B::Context,
data_type: DataType,
- ops: GatedActMulOp,
options: GatedActMulOptions,
- activation_group_size: u32,
- sum_group_size: u32,
settings: GatedActMulSettings,
+ quantization: Option<ActivationQuantization>,
) -> Result<Self, B::Error> {
+ let (ops, codes_grouped_by_nibble, scale_group_size, sum_group_size) = match quantization {
+ Some(quantization) => (
+ if quantization.sum_group_size().is_some() {
+ GatedActMulOp::QuantizeWithGroupSums
+ } else {
+ GatedActMulOp::Quantize
+ },
+ quantization.code_layout().is_grouped_by_nibble(),
+ quantization.scale_group_size(),
+ quantization.sum_group_size().unwrap_or(quantization.scale_group_size()),
+ ),
+ None => (GatedActMulOp::FullPrecision, false, HADAMARD_TRANSFORM_BLOCK_SIZE, HADAMARD_TRANSFORM_BLOCK_SIZE),
+ };
let kernel = <B::Kernels as Kernels>::GatedActMulKernel::new(
context,
data_type,
ops,
+ codes_grouped_by_nibble,
options.contains(GatedActMulOptions::INTERLEAVED),
options.contains(GatedActMulOptions::HADAMARD),
- activation_group_size,
+ scale_group_size,
sum_group_size,
settings.activation_alpha.is_some(),
settings.gate_clipping.into_pair().is_some(),
@@ -119,11 +92,9 @@ impl<B: Backend> GatedActMul<B> {
)?;
Ok(Self {
kernel,
- ops,
options,
settings,
- activation_group_size,
- sum_group_size,
+ quantization,
})
}
@@ -140,7 +111,7 @@ impl<B: Backend> GatedActMul<B> {
act_type: ActivationType,
encoder: &mut Encoder<B>,
) {
- assert_eq!(self.ops, GatedActMulOp::FullPrecision);
+ assert!(self.quantization.is_none());
assert_eq!(self.options.contains(GatedActMulOptions::INTERLEAVED), value_operand.is_none());
assert_eq!(self.options.contains(GatedActMulOptions::HADAMARD), hadamard_factors.is_some());
assert!(
@@ -183,14 +154,14 @@ impl<B: Backend> GatedActMul<B> {
act_type: ActivationType,
encoder: &mut Encoder<B>,
) {
- assert!(matches!(self.ops, GatedActMulOp::Quantize | GatedActMulOp::QuantizeWithGroupSums));
+ let quantization = self.quantization.expect("quantized gated activation required");
assert!(self.options.contains(GatedActMulOptions::INTERLEAVED));
assert!(self.options.contains(GatedActMulOptions::HADAMARD));
assert!(gated_dim.is_multiple_of(HADAMARD_TRANSFORM_BLOCK_SIZE));
- assert!(gated_dim.is_multiple_of(self.activation_group_size));
- assert_eq!(self.ops == GatedActMulOp::QuantizeWithGroupSums, group_sums.is_some());
- if self.ops == GatedActMulOp::QuantizeWithGroupSums {
- assert!(gated_dim.is_multiple_of(self.sum_group_size));
+ assert!(gated_dim.is_multiple_of(quantization.scale_group_size()));
+ assert_eq!(quantization.sum_group_size().is_some(), group_sums.is_some());
+ if let Some(group_size) = quantization.sum_group_size() {
+ assert!(gated_dim.is_multiple_of(group_size));
}
let (gate_clip_min, gate_clip_max) = self.settings.gate_clipping.into_pair().unzip();
let (value_clip_min, value_clip_max) = self.settings.value_clipping.into_pair().unzip();
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs
index 6ff0365f0..8fe1982ac 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/kernel.rs
@@ -1,9 +1,12 @@
use crate::{
backends::common::{
Backend, BufferArg, Encoder, Kernels,
- kernel::matmul::{
- arguments::MatmulArguments,
- routing::{A8ActivationPlan, ActivationFormat, MatmulShape},
+ kernel::{
+ ActivationQuantization,
+ matmul::{
+ arguments::MatmulArguments,
+ routing::{ActivationFormat, MatmulShape},
+ },
},
},
data_type::DataType,
@@ -25,11 +28,11 @@ pub trait MatmulKernel: Sized + Send + Sync {
encoder: &mut Encoder<Self::Backend>,
) -> Result<(), <Self::Backend as Backend>::Error>;
- fn a8_activation_plan(
+ fn select_activation_quantization(
&self,
_candidate: &MatmulShape,
_context: &<Self::Backend as Backend>::Context,
- ) -> Option<A8ActivationPlan> {
+ ) -> Option<ActivationQuantization> {
None
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs
index 25539b183..d93c02b0e 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_a.rs
@@ -1,5 +1,51 @@
+use std::mem::size_of;
+
use crate::backends::common::{Allocation, Backend, gpu_types::gemm::GemmAPrologueKind};
+#[derive(Clone, Copy, PartialEq)]
+pub enum Int8CodeLayout {
+ Sequential,
+ GroupedByNibble,
+}
+
+impl Int8CodeLayout {
+ pub const fn from_grouped_by_nibble(grouped: bool) -> Self {
+ match grouped {
+ true => Self::GroupedByNibble,
+ false => Self::Sequential,
+ }
+ }
+
+ pub const fn for_right_bits(bits: u32) -> Option<Self> {
+ match bits {
+ 4 => Some(Self::GroupedByNibble),
+ 8 => Some(Self::Sequential),
+ _ => None,
+ }
+ }
+
+ pub const fn is_grouped_by_nibble(self) -> bool {
+ matches!(self, Self::GroupedByNibble)
+ }
+
+ pub const fn index(
+ self,
+ index: usize,
+ ) -> usize {
+ match self {
+ Self::Sequential => index,
+ Self::GroupedByNibble => {
+ // [0, 1, 2, 3, 4, 5, 6, 7] -> [0, 4, 1, 5, 2, 6, 3, 7]
+ const NIBBLES_PER_BYTE: usize = 2;
+ const CODES_PER_WORD: usize = size_of::<u32>() * NIBBLES_PER_BYTE;
+ const NIBBLE_GROUP_SIZE: usize = CODES_PER_WORD / NIBBLES_PER_BYTE;
+ let offset = index % CODES_PER_WORD;
+ index - offset + (offset % NIBBLES_PER_BYTE) * NIBBLE_GROUP_SIZE + offset / NIBBLES_PER_BYTE
+ },
+ }
+ }
+}
+
pub enum MatmulA<'a, B: Backend> {
FullPrecision {
values: &'a Allocation<B>,
@@ -9,7 +55,8 @@ pub enum MatmulA<'a, B: Backend> {
values: &'a Allocation<B>,
scales: &'a Allocation<B>,
group_sums: Option<&'a Allocation<B>>,
- group_size: u32,
+ scale_group_size: u32,
+ code_layout: Int8CodeLayout,
},
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs
index e472a5477..6d772b29a 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/matmul_b.rs
@@ -1,3 +1,4 @@
+use super::{QuantParams, QuantParamsLayout};
use crate::{
backends::common::{
Allocation, Backend, BufferArg,
@@ -10,106 +11,103 @@ pub enum MatmulB<'a, B: Backend, TB: BufferArg<'a, B> = &'a Allocation<B>> {
FullPrecision {
b: TB,
},
- ScaleBiasDequant {
- b: &'a Allocation<B>,
- scales: &'a Allocation<B>,
- biases: &'a Allocation<B>,
- mode: QuantizationMode,
- group_size: u32,
- signed_codes: bool,
- },
- ScaleZeroPointDequant {
- b: &'a Allocation<B>,
- scales: &'a Allocation<B>,
- zero_points: &'a Allocation<B>,
- mode: QuantizationMode,
- group_size: u32,
- signed_codes: bool,
- },
- ScaleSymmetricDequant {
- b: &'a Allocation<B>,
- scales: &'a Allocation<B>,
- mode: QuantizationMode,
- group_size: u32,
- signed_codes: bool,
- },
+ Quantized(QuantizedB<'a, B>),
}
-impl<'a, B: Backend, TB: BufferArg<'a, B>> MatmulB<'a, B, TB> {
- pub fn b_prologue(&self) -> GemmBPrologueKind {
+pub struct QuantizedB<'a, B: Backend> {
+ pub codes: &'a Allocation<B>,
+ pub scales: &'a Allocation<B>,
+ pub correction: QuantizedCorrection<&'a Allocation<B>>,
+ pub params: QuantParams,
+ pub mode: QuantizationMode,
+ pub group_size: u32,
+ pub signed_codes: bool,
+}
+
+#[derive(Clone, Copy)]
+pub enum QuantizedCorrection<T> {
+ Symmetric,
+ Biases(T),
+ ZeroPoints(T),
+}
+
+impl<T> QuantizedCorrection<T> {
+ pub fn as_ref(&self) -> QuantizedCorrection<&T> {
match self {
- Self::FullPrecision {
- ..
- } => GemmBPrologueKind::FullPrecision,
- Self::ScaleBiasDequant {
- ..
- } => GemmBPrologueKind::ScaleBiasDequant,
- Self::ScaleZeroPointDequant {
- ..
- } => GemmBPrologueKind::ScaleZeroPointDequant,
- Self::ScaleSymmetricDequant {
- ..
- } => GemmBPrologueKind::ScaleSymmetricDequant,
+ Self::Symmetric => QuantizedCorrection::Symmetric,
+ Self::Biases(biases) => QuantizedCorrection::Biases(biases),
+ Self::ZeroPoints(zero_points) => QuantizedCorrection::ZeroPoints(zero_points),
}
}
- pub fn bits_per_b(&self) -> Option<u32> {
+ pub fn biases(&self) -> Option<&T> {
match self {
- Self::FullPrecision {
- ..
- } => None,
- Self::ScaleBiasDequant {
- mode,
- ..
- }
- | Self::ScaleZeroPointDequant {
- mode,
- ..
- }
- | Self::ScaleSymmetricDequant {
- mode,
- ..
- } => Some(DataType::from(*mode).size_in_bits() as u32),
+ Self::Biases(biases) => Some(biases),
+ Self::Symmetric | Self::ZeroPoints(_) => None,
}
}
- pub fn group_size(&self) -> Option<u32> {
+ pub fn zero_points(&self) -> Option<&T> {
match self {
- Self::FullPrecision {
- ..
- } => None,
- Self::ScaleBiasDequant {
- group_size,
- ..
- }
- | Self::ScaleZeroPointDequant {
- group_size,
- ..
- }
- | Self::ScaleSymmetricDequant {
- group_size,
- ..
- } => Some(*group_size),
+ Self::ZeroPoints(zero_points) => Some(zero_points),
+ Self::Symmetric | Self::Biases(_) => None,
}
}
+}
- pub fn signed_codes(&self) -> bool {
+impl<'a, B: Backend> QuantizedB<'a, B> {
+ pub fn bits(&self) -> u32 {
+ DataType::from(self.mode).size_in_bits() as u32
+ }
+
+ pub fn prologue(&self) -> GemmBPrologueKind {
+ match self.correction {
+ QuantizedCorrection::Symmetric => GemmBPrologueKind::ScaleSymmetricDequant,
+ QuantizedCorrection::Biases(_) => GemmBPrologueKind::ScaleBiasDequant,
+ QuantizedCorrection::ZeroPoints(_) => GemmBPrologueKind::ScaleZeroPointDequant,
+ }
+ }
+
+ pub fn biases(&self) -> Option<&'a Allocation<B>> {
+ self.correction.biases().copied()
+ }
+
+ pub fn zero_points(&self) -> Option<&'a Allocation<B>> {
+ self.correction.zero_points().copied()
+ }
+
+ pub fn zero_point_strides(&self) -> super::QuantParamsStrides {
+ self.params.zero_point_strides(self.mode)
+ }
+}
+
+impl<'a, B: Backend, TB: BufferArg<'a, B>> MatmulB<'a, B, TB> {
+ pub fn quantized(&self) -> Option<&QuantizedB<'a, B>> {
match self {
Self::FullPrecision {
..
- } => false,
- Self::ScaleBiasDequant {
- signed_codes,
- ..
- }
- | Self::ScaleZeroPointDequant {
- signed_codes,
- ..
- }
- | Self::ScaleSymmetricDequant {
- signed_codes,
- ..
- } => *signed_codes,
+ } => None,
+ Self::Quantized(quantized) => Some(quantized),
}
}
+
+ pub fn b_prologue(&self) -> GemmBPrologueKind {
+ self.quantized().map_or(GemmBPrologueKind::FullPrecision, QuantizedB::prologue)
+ }
+
+ pub fn bits_per_b(&self) -> Option<u32> {
+ self.quantized().map(QuantizedB::bits)
+ }
+
+ pub fn group_size(&self) -> Option<u32> {
+ self.quantized().map(|quantized| quantized.group_size)
+ }
+
+ pub fn signed_codes(&self) -> bool {
+ self.quantized().is_some_and(|quantized| quantized.signed_codes)
+ }
+
+ pub fn quant_params_layout(&self) -> Option<QuantParamsLayout> {
+ self.quantized().map(|quantized| quantized.params.layout())
+ }
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
index 13089c3fd..aab560dee 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/mod.rs
@@ -10,6 +10,107 @@ 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;
-pub use routing::{A8ActivationPlan, ActivationFormat, MatmulShape};
+pub use matmul_a::{Int8CodeLayout, MatmulA};
+pub use matmul_b::{MatmulB, QuantizedB, QuantizedCorrection};
+pub use routing::{ActivationFormat, MatmulShape};
+
+use crate::backends::common::gpu_types::{QUANT_PARAMS_GROUP_OUTPUT_ALIGNMENT, QuantizationMode};
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum QuantParamsLayout {
+ /// `[N, G]`.
+ OutputGroup,
+ /// `[G, round_up_4(N)]`.
+ GroupOutput,
+}
+
+#[derive(Clone, Copy, Default)]
+pub struct QuantParamsStrides {
+ pub output_stride: u32,
+ pub group_stride: u32,
+}
+
+#[derive(Clone, Copy)]
+pub struct QuantParams {
+ layout: QuantParamsLayout,
+ row_count: u32,
+ group_count: u32,
+}
+
+impl QuantParams {
+ pub const fn new(
+ layout: QuantParamsLayout,
+ row_count: u32,
+ group_count: u32,
+ ) -> Self {
+ Self {
+ layout,
+ row_count,
+ group_count,
+ }
+ }
+
+ pub const fn layout(self) -> QuantParamsLayout {
+ self.layout
+ }
+
+ pub const fn scale_shape(self) -> [u32; 2] {
+ self.shape(1)
+ }
+
+ pub fn zero_point_shape(
+ self,
+ mode: QuantizationMode,
+ ) -> [u32; 2] {
+ self.shape(mode.packing_divisor())
+ }
+
+ pub const fn scale_strides(self) -> QuantParamsStrides {
+ self.strides(1)
+ }
+
+ pub fn zero_point_strides(
+ self,
+ mode: QuantizationMode,
+ ) -> QuantParamsStrides {
+ self.strides(mode.packing_divisor())
+ }
+
+ const fn shape(
+ self,
+ packing_divisor: u32,
+ ) -> [u32; 2] {
+ let row_values = self.padded_values_per_row(packing_divisor);
+ match self.layout {
+ QuantParamsLayout::OutputGroup => [self.row_count, row_values / packing_divisor],
+ QuantParamsLayout::GroupOutput => [self.group_count, row_values / packing_divisor],
+ }
+ }
+
+ const fn strides(
+ self,
+ packing_divisor: u32,
+ ) -> QuantParamsStrides {
+ let row_values = self.padded_values_per_row(packing_divisor);
+ match self.layout {
+ QuantParamsLayout::OutputGroup => QuantParamsStrides {
+ output_stride: row_values,
+ group_stride: 1,
+ },
+ QuantParamsLayout::GroupOutput => QuantParamsStrides {
+ output_stride: 1,
+ group_stride: row_values,
+ },
+ }
+ }
+
+ const fn padded_values_per_row(
+ self,
+ packing_divisor: u32,
+ ) -> u32 {
+ match self.layout {
+ QuantParamsLayout::OutputGroup => self.group_count.next_multiple_of(packing_divisor),
+ QuantParamsLayout::GroupOutput => self.row_count.next_multiple_of(QUANT_PARAMS_GROUP_OUTPUT_ALIGNMENT),
+ }
+ }
+}
diff --git a/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs b/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs
index e0f3e3c1f..640d77644 100644
--- a/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/matmul/routing.rs
@@ -1,4 +1,4 @@
-use super::{MatmulA, MatmulArguments};
+use super::{MatmulA, MatmulArguments, QuantParamsLayout};
use crate::backends::common::{
Backend, BufferArg,
gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},
@@ -10,12 +10,6 @@ pub enum ActivationFormat {
Int8,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct A8ActivationPlan {
- pub activation_group_size: u32,
- pub sum_group_size: Option<u32>,
-}
-
#[derive(Clone, Copy)]
pub struct MatmulShape {
pub m: u32,
@@ -29,6 +23,7 @@ pub struct MatmulShape {
pub signed_codes: bool,
pub a_full_precision: bool,
pub gathered: bool,
+ pub params_layout: Option<QuantParamsLayout>,
pub d_transform: GemmDTransform,
}
@@ -48,6 +43,7 @@ impl MatmulShape {
signed_codes: arguments.b.signed_codes(),
a_full_precision: matches!(arguments.a, MatmulA::FullPrecision { .. }),
gathered: arguments.gather_indices.is_some(),
+ params_layout: arguments.b.quant_params_layout(),
d_transform: arguments.d_transform.mask(),
}
}
diff --git a/crates/uzu-engine/src/backends/common/kernel/mod.rs b/crates/uzu-engine/src/backends/common/kernel/mod.rs
index 365a80af5..3b665c52a 100644
--- a/crates/uzu-engine/src/backends/common/kernel/mod.rs
+++ b/crates/uzu-engine/src/backends/common/kernel/mod.rs
@@ -10,7 +10,7 @@ pub mod gated_act_mul;
pub mod matmul;
pub mod radix_top_k_small;
-pub use activation_transform::ActivationTransform;
+pub use activation_transform::{ActivationQuantization, ActivationTransform};
pub use attention::{AttentionArguments, AttentionKernel, AttentionKernelConfig};
pub use gated_act_mul::{GatedActMul, GatedActMulSettings};
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rs b/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rs
index 67ae30e6d..259045989 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/activation_transform/activation_transform.rs
@@ -5,7 +5,10 @@ use uzu_engine_macros::kernel;
use super::{hadamard_transform, min_max_symmetric_divisor, quantize_symmetric_i8};
use crate::{
array::ArrayElement,
- backends::common::gpu_types::{ActivationTransformOp, HADAMARD_TRANSFORM_BLOCK_SIZE},
+ backends::common::{
+ gpu_types::{ActivationTransformOp, HADAMARD_TRANSFORM_BLOCK_SIZE},
+ kernel::matmul::Int8CodeLayout,
+ },
};
pub fn quantize_transformed_row(
@@ -15,6 +18,7 @@ pub fn quantize_transformed_row(
values: &mut [i8],
scales: &mut [f32],
mut group_sums: Option<&mut [i32]>,
+ code_layout: Int8CodeLayout,
) {
assert_eq!(transformed.len(), values.len());
assert_eq!(scales.len(), transformed.len() / activation_scale_group_size);
@@ -32,7 +36,8 @@ pub fn quantize_transformed_row(
for (index, &value) in source.iter().enumerate() {
let code = quantize_symmetric_i8(value, scale);
let absolute_index = scale_group_index * activation_scale_group_size + index;
- values[absolute_index] = code;
+ let output_index = code_layout.index(absolute_index);
+ values[output_index] = code;
if let Some(group_sums) = group_sums.as_deref_mut() {
group_sums[absolute_index / sum_group_size.expect("correction group")] += code as i32;
}
@@ -47,15 +52,18 @@ pub fn activation_transform<T: ArrayElement + Float>(
#[optional(ops == ActivationTransformOp::InputRht || ops == ActivationTransformOp::OutputRht)] fp_out: Option<
*mut T,
>,
- #[optional(ops == ActivationTransformOp::Quantize || ops == ActivationTransformOp::QuantizeWithGroupSums)]
+ #[optional(ops == ActivationTransformOp::Quantize
+ || ops == ActivationTransformOp::QuantizeWithGroupSums)]
q_out: Option<*mut i8>,
- #[optional(ops == ActivationTransformOp::Quantize || ops == ActivationTransformOp::QuantizeWithGroupSums)]
+ #[optional(ops == ActivationTransformOp::Quantize
+ || ops == ActivationTransformOp::QuantizeWithGroupSums)]
scales_out: Option<*mut f32>,
#[optional(ops == ActivationTransformOp::QuantizeWithGroupSums)] group_sums_out: Option<*mut i32>,
rht_factors: *const i32,
batch_size: u32,
element_count: u32,
#[specialize] ops: ActivationTransformOp,
+ #[specialize] grouped_by_weight_nibble: bool,
#[specialize] in_place: bool,
#[specialize] activation_scale_group_size: u32,
#[specialize] sum_group_size: u32,
@@ -123,6 +131,7 @@ pub fn activation_transform<T: ArrayElement + Float>(
values,
scales,
sums,
+ Int8CodeLayout::from_grouped_by_nibble(grouped_by_weight_nibble),
);
} else {
let fp_out = fp_out.expect("FP transform requires fp_out");
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rs b/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rs
index 74373cd83..a80a44e7d 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/gated_act_mul/gated_act_mul.rs
@@ -5,7 +5,10 @@ use uzu_engine_macros::kernel;
use crate::{
array::ArrayElement,
backends::{
- common::gpu_types::{ActivationType, GatedActMulOp, HADAMARD_TRANSFORM_BLOCK_SIZE, activation_silu_alpha},
+ common::{
+ gpu_types::{ActivationType, GatedActMulOp, HADAMARD_TRANSFORM_BLOCK_SIZE, activation_silu_alpha},
+ kernel::matmul::Int8CodeLayout,
+ },
cpu::kernel::activation_transform::{hadamard_transform, quantize_transformed_row},
},
};
@@ -16,10 +19,12 @@ pub fn gated_act_mul<T: ArrayElement + Float>(
act_operand: *const T,
#[optional(!interleaved)] value_operand: Option<*const T>,
#[optional(ops == GatedActMulOp::FullPrecision)] fp_out: Option<*mut T>,
- #[optional(ops == GatedActMulOp::Quantize || ops == GatedActMulOp::QuantizeWithGroupSums)] q_out: Option<*mut i8>,
- #[optional(ops == GatedActMulOp::Quantize || ops == GatedActMulOp::QuantizeWithGroupSums)] scales_out: Option<
- *mut f32,
- >,
+ #[optional(ops == GatedActMulOp::Quantize
+ || ops == GatedActMulOp::QuantizeWithGroupSums)]
+ q_out: Option<*mut i8>,
+ #[optional(ops == GatedActMulOp::Quantize
+ || ops == GatedActMulOp::QuantizeWithGroupSums)]
+ scales_out: Option<*mut f32>,
#[optional(ops == GatedActMulOp::QuantizeWithGroupSums)] group_sums_out: Option<*mut i32>,
#[optional(use_hadamard)] hadamard_factors: Option<*const i32>,
gated_dim: u32,
@@ -33,6 +38,7 @@ pub fn gated_act_mul<T: ArrayElement + Float>(
#[optional(clip_value)] value_clip_min: Option<f32>,
#[optional(clip_value)] value_clip_max: Option<f32>,
#[specialize] ops: GatedActMulOp,
+ #[specialize] grouped_by_weight_nibble: bool,
#[specialize] interleaved: bool,
#[specialize] use_hadamard: bool,
#[specialize] activation_scale_group_size: u32,
@@ -133,6 +139,7 @@ pub fn gated_act_mul<T: ArrayElement + Float>(
values,
scales,
group_sums,
+ Int8CodeLayout::from_grouped_by_nibble(grouped_by_weight_nibble),
);
} else {
let output = fp_out.expect("FP gate activation requires fp_out");
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
index c3db18e05..8a4612f41 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/matmul/kernel.rs
@@ -6,7 +6,7 @@ use crate::{
gpu_types::QuantizationMode,
kernel::{
ActivationTransform, TensorAddBiasKernel,
- matmul::{MatmulA, MatmulArguments, MatmulB, MatmulError, MatmulKernel},
+ matmul::{Int8CodeLayout, MatmulA, MatmulArguments, MatmulError, MatmulKernel},
},
},
cpu::{Cpu, context::CpuContext, error::CpuError},
@@ -91,6 +91,7 @@ impl MatmulKernel for MatmulCpuKernel {
values: SendPtr<u8>,
scales: SendPtr<u8>,
group_size: usize,
+ code_layout: Int8CodeLayout,
},
}
let a_data = match a {
@@ -106,24 +107,14 @@ impl MatmulKernel for MatmulCpuKernel {
values,
scales,
group_sums: _,
- group_size: a_group_size,
+ scale_group_size: a_group_size,
+ code_layout,
} => {
let compatible = matches!(a_group_size, 32 | 64 | 128)
&& k.is_multiple_of(a_group_size)
&& matches!(b.group_size(), Some(32 | 64 | 128))
- && matches!(
- b,
- MatmulB::ScaleSymmetricDequant {
- mode: QuantizationMode::U4 | QuantizationMode::U8,
- ..
- } | MatmulB::ScaleBiasDequant {
- mode: QuantizationMode::U4 | QuantizationMode::U8,
- ..
- } | MatmulB::ScaleZeroPointDequant {
- mode: QuantizationMode::U4 | QuantizationMode::U8,
- ..
- }
- );
+ && b.quantized()
+ .is_some_and(|quantized| matches!(quantized.mode, QuantizationMode::U4 | QuantizationMode::U8));
if !compatible {
return Err(MatmulError::IncompatibleA {
path: "CpuMatmul",
@@ -141,6 +132,7 @@ impl MatmulKernel for MatmulCpuKernel {
unsafe { &*scales_range.buffer().get() }.as_ptr().wrapping_byte_add(scales_range.range().start),
),
group_size: a_group_size as usize,
+ code_layout,
}
},
};
@@ -157,35 +149,11 @@ impl MatmulKernel for MatmulCpuKernel {
(&*d_buffer_range.buffer().get()).as_ptr().wrapping_byte_add(d_buffer_range.range().start) as *mut u8
});
- let weight_data = WeightData::from_b(b, b_leading_dimension, b_transpose, k_u, n_u);
+ 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 {
- WeightData::Quantized {
- bits,
- group_size,
- ..
- } => {
- let num_groups_k = k_u.div_ceil(*group_size);
- let zero_point_stride = if *bits == 4 {
- num_groups_k.div_ceil(2)
- } else {
- num_groups_k
- };
- let pack_factor = if *bits == 4 {
- 8
- } else {
- 4
- };
- Some((num_groups_k, zero_point_stride, pack_factor))
- },
- WeightData::FullPrecision {
- ..
- } => None,
- };
-
unsafe {
for row in 0..m_u {
for col in 0..n_u {
@@ -202,10 +170,12 @@ impl MatmulKernel for MatmulCpuKernel {
values,
scales,
group_size,
+ code_layout,
} => {
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 code_index = code_layout.index(inner);
+ let q = *(values.as_ptr() as *const i8).add(row * k_u + code_index) as f32;
let scale = *(scales.as_ptr() as *const f32).add(row * groups + group);
q * scale
},
@@ -228,14 +198,16 @@ impl MatmulKernel for MatmulCpuKernel {
scales,
zero_points,
biases,
+ scale_strides,
bits,
group_size,
signed_codes,
} => {
- let (num_groups_k, zero_point_stride, pack_factor) = quant_layout.unwrap();
+ let pack_factor = 32 / *bits;
let weight_linear_index = b_col * k_u + inner;
let word_index = weight_linear_index / pack_factor;
- let bit_offset = (weight_linear_index % pack_factor) * *bits;
+ let code_index_in_word = weight_linear_index % pack_factor;
+ let bit_offset = code_index_in_word * *bits;
let weights_words = weights.as_ptr() as *const u32;
let word = weights_words.add(word_index).read_unaligned();
let code_mask = (1u32 << bits) - 1;
@@ -245,29 +217,29 @@ impl MatmulKernel for MatmulCpuKernel {
}
let quantized_value = f32::from(weight_code);
let group_index = inner / group_size;
- let scale = read_f32(
- scales.as_ptr(),
- weights_data_type,
- b_col * num_groups_k + group_index,
- );
+ let metadata_index = b_col * scale_strides.output_stride as usize
+ + group_index * scale_strides.group_stride as usize;
+ let scale = read_f32(scales.as_ptr(), weights_data_type, metadata_index);
let midpoint = (1u32 << (bits - 1)) as f32;
- let zero_point = zero_points.map(|zp| {
+ let zero_point = zero_points.as_ref().map(|(zp, strides)| {
+ let zero_point_index = b_col * strides.output_stride as usize
+ + group_index * strides.group_stride as usize;
if *bits == 4 {
- let byte_index = b_col * zero_point_stride + (group_index >> 1);
+ let byte_index = zero_point_index / 2;
let byte_value = *zp.as_ptr().add(byte_index);
- if (group_index & 1) == 0 {
+ if zero_point_index.is_multiple_of(2) {
(byte_value & 0x0F) as f32
} else {
((byte_value >> 4) & 0x0F) as f32
}
} else {
- *zp.as_ptr().add(b_col * zero_point_stride + group_index) as f32
+ *zp.as_ptr().add(zero_point_index) as f32
}
});
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)
+ read_f32(b.as_ptr(), weights_data_type, metadata_index)
} else {
-scale * midpoint
};
diff --git a/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rs b/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rs
index 41c92a735..0ce2f5ac0 100644
--- a/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rs
+++ b/crates/uzu-engine/src/backends/cpu/kernel/matmul/reference.rs
@@ -2,7 +2,10 @@ use half::{bf16, f16};
use crate::{
backends::{
- common::{AsBufferRangeRef, BufferArg, gpu_types::QuantizationMode, kernel::matmul::MatmulB},
+ common::{
+ AsBufferRangeRef, BufferArg,
+ kernel::matmul::{MatmulB, MatmulError, QuantParamsStrides},
+ },
cpu::Cpu,
},
data_type::DataType,
@@ -18,8 +21,9 @@ pub(super) enum WeightData {
Quantized {
weights: SendPtr<u8>,
scales: SendPtr<u8>,
- zero_points: Option<SendPtr<u8>>,
+ zero_points: Option<(SendPtr<u8>, QuantParamsStrides)>,
biases: Option<SendPtr<u8>>,
+ scale_strides: QuantParamsStrides,
bits: usize,
group_size: usize,
signed_codes: bool,
@@ -33,15 +37,11 @@ impl WeightData {
b_transpose: bool,
k: usize,
n: usize,
- ) -> Self {
+ ) -> Result<Self, MatmulError<Cpu>> {
let alloc_ptr = |a: &crate::backends::common::Allocation<Cpu>| {
let r = a.as_buffer_range_ref();
SendPtr(unsafe { &*r.buffer().get() }.as_ptr().wrapping_byte_add(r.range().start))
};
- let bits_of = |mode| match mode {
- QuantizationMode::U4 => 4usize,
- _ => 8usize,
- };
match b {
MatmulB::FullPrecision {
b: weights,
@@ -52,59 +52,22 @@ impl WeightData {
n
});
let (buffer, byte_off, _) = weights.into_parts();
- WeightData::FullPrecision {
+ Ok(WeightData::FullPrecision {
ptr: SendPtr(unsafe { &*buffer.downcast().get() }.as_ptr().wrapping_byte_add(byte_off)),
leading_dimension,
transpose: b_transpose,
- }
- },
- MatmulB::ScaleBiasDequant {
- b: weights,
- scales,
- biases,
- mode,
- group_size,
- signed_codes,
- } => WeightData::Quantized {
- weights: alloc_ptr(weights),
- scales: alloc_ptr(scales),
- zero_points: None,
- biases: Some(alloc_ptr(biases)),
- bits: bits_of(mode),
- group_size: group_size as usize,
- signed_codes,
- },
- MatmulB::ScaleZeroPointDequant {
- b: weights,
- scales,
- zero_points,
- mode,
- group_size,
- signed_codes,
- } => WeightData::Quantized {
- weights: alloc_ptr(weights),
- scales: alloc_ptr(scales),
- zero_points: Some(alloc_ptr(zero_points)),
- biases: None,
- bits: bits_of(mode),
- group_size: group_size as usize,
- signed_codes,
- },
- MatmulB::ScaleSymmetricDequant {
- b: weights,
- scales,
- mode,
- group_size,
- signed_codes,
- } => WeightData::Quantized {
- weights: alloc_ptr(weights),
- scales: alloc_ptr(scales),
- zero_points: None,
- biases: None,
- bits: bits_of(mode),
- group_size: group_size as usize,
- signed_codes,
+ })
},
+ MatmulB::Quantized(quantized) => Ok(WeightData::Quantized {
+ weights: alloc_ptr(quantized.codes),
+ scales: alloc_ptr(quantized.scales),
+ zero_points: quantized.zero_points().map(|values| (alloc_ptr(values), quantized.zero_point_strides())),
+ biases: quantized.biases().map(alloc_ptr),
+ scale_strides: quantized.params.scale_strides(),
+ bits: quantized.bits() as usize,
+ group_size: quantized.group_size as usize,
+ signed_codes: quantized.signed_codes,
+ }),
}
}
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal
index d5bfe2713..65867c8af 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/activation_transform/activation_transform.metal
@@ -27,6 +27,7 @@ PUBLIC KERNEL(ActivationTransform)(
constant uint& batch_size,
constant uint& element_count,
const ActivationTransformOp ops SPECIALIZE,
+ const bool grouped_by_weight_nibble SPECIALIZE,
const bool in_place SPECIALIZE,
const uint activation_scale_group_size SPECIALIZE,
const uint sum_group_size SPECIALIZE,
@@ -78,7 +79,8 @@ PUBLIC KERNEL(ActivationTransform)(
const int8_t code =
static_cast<int8_t>(clamp(round(value / scale), -ACTIVATION_QUANT_INT8_MAX, ACTIVATION_QUANT_INT8_MAX));
if (in_bounds) {
- q_out[element_index] = code;
+ const uint output_factor_index = grouped_by_weight_nibble ? nibble_grouped_index(factor_index) : factor_index;
+ q_out[batch_index * element_count + output_factor_index] = code;
}
write_activation_quantization_group(
scales_out,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/common/activation_quantization.h b/crates/uzu-engine/src/backends/metal/kernel/common/activation_quantization.h
index a391f1388..00f181402 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/common/activation_quantization.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/common/activation_quantization.h
@@ -10,6 +10,15 @@ UZU_CONST uint ACTIVATION_QUANT_TILE_SIZE = 128;
UZU_CONST float ACTIVATION_QUANT_INT8_MAX = 127.0f;
#define ACTIVATION_QUANT_SIMDGROUPS 4
+static METAL_FUNC uint nibble_grouped_index(const uint index) {
+ constexpr uint NIBBLES_PER_BYTE = 2;
+ constexpr uint CODES_PER_WORD = sizeof(uint) * NIBBLES_PER_BYTE;
+ constexpr uint NIBBLE_GROUP_SIZE = CODES_PER_WORD / NIBBLES_PER_BYTE;
+ // [0, 1, 2, 3, 4, 5, 6, 7] -> [0, 4, 1, 5, 2, 6, 3, 7]
+ const uint offset = index % CODES_PER_WORD;
+ return index - offset + (offset % NIBBLES_PER_BYTE) * NIBBLE_GROUP_SIZE + offset / NIBBLES_PER_BYTE;
+}
+
template <typename T, typename SimdReduce, typename Combine>
METAL_FUNC T reduce_activation_quantization_group(
const T value,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metal b/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metal
index 9eeae5d80..b1a631046 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/gated_act_mul/gated_act_mul.metal
@@ -37,6 +37,7 @@ PUBLIC KERNEL(GatedActMul) (
const constant float& value_clip_min OPTIONAL(clip_value),
const constant float& value_clip_max OPTIONAL(clip_value),
const GatedActMulOp ops SPECIALIZE,
+ const bool grouped_by_weight_nibble SPECIALIZE,
const bool interleaved SPECIALIZE,
const bool use_hadamard SPECIALIZE,
const uint activation_scale_group_size SPECIALIZE,
@@ -128,7 +129,8 @@ PUBLIC KERNEL(GatedActMul) (
const int8_t code =
static_cast<int8_t>(clamp(round(result / scale), -ACTIVATION_QUANT_INT8_MAX, ACTIVATION_QUANT_INT8_MAX));
if (element_in_bounds) {
- q_out[batch_idx * gated_dim + gated_idx] = code;
+ const uint output_gated_index = grouped_by_weight_nibble ? nibble_grouped_index(gated_idx) : gated_idx;
+ q_out[batch_idx * gated_dim + output_gated_index] = code;
}
write_activation_quantization_group(
diff --git a/crates/uzu-engine/src/backends/metal/kernel/generated/matmul.h b/crates/uzu-engine/src/backends/metal/kernel/generated/matmul.h
index 072833b93..7b0cd7bbe 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/generated/matmul.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/generated/matmul.h
@@ -5,12 +5,18 @@
using namespace metal;
namespace uzu::matmul {
+static constant constexpr uint32_t QUANT_PARAMS_GROUP_OUTPUT_ALIGNMENT = 4;
+
typedef struct {
uint32_t M;
uint32_t N;
uint32_t K;
uint32_t leading_dimension_a;
uint32_t leading_dimension_b;
+ uint32_t scale_output_stride;
+ uint32_t scale_group_stride;
+ uint32_t zero_point_output_stride;
+ uint32_t zero_point_group_stride;
uint32_t leading_dimension_d;
uint32_t threadgroups_per_column;
uint32_t threadgroups_per_row;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h
index 372ff2608..71eaa9816 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/fragment.h
@@ -5,7 +5,6 @@
#include "../../common/integral_constant.h"
#include "../../common/thread_context.h"
#include "defines.h"
-#include "mxu_fragment/tensor_operand.h"
using namespace metal;
@@ -447,31 +446,5 @@ METAL_FUNC void fragment_mm(thread OutputFragment& output, thread LeftFragment&
);
}
-template <class OutputFragment, class LeftFragment, typename Format>
-METAL_FUNC void fragment_mma(
- thread OutputFragment& output,
- thread LeftFragment& left,
- const DeviceTensorOperand<Format> right
-) {
- static_assert(
- metal::is_same_v<typename OutputFragment::FragmentOpsType, typename LeftFragment::FragmentOpsType>,
- "fragment_mma requires output and left fragments to use the same FragmentOps"
- );
- OutputFragment::FragmentOpsType::template fragment_mma<LeftFragment::MMA_TRANSPOSE, true>(output, left, right);
-}
-
-template <class OutputFragment, class LeftFragment, typename Format>
-METAL_FUNC void fragment_mm(
- thread OutputFragment& output,
- thread LeftFragment& left,
- const DeviceTensorOperand<Format> right
-) {
- static_assert(
- metal::is_same_v<typename OutputFragment::FragmentOpsType, typename LeftFragment::FragmentOpsType>,
- "fragment_mm requires output and left fragments to use the same FragmentOps"
- );
- OutputFragment::FragmentOpsType::template fragment_mm<LeftFragment::MMA_TRANSPOSE, true>(output, left, right);
-}
-
} // namespace matmul
} // namespace uzu
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/integer_formats.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/integer_formats.h
deleted file mode 100644
index 53ea74127..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/integer_formats.h
+++ /dev/null
@@ -1,41 +0,0 @@
-#pragma once
-
-#include <metal_stdlib>
-
-#include "../../../common/defines.h"
-
-using namespace metal;
-
-namespace uzu {
-namespace matmul {
-
-enum class Signedness { Signed, Unsigned };
-
-template <ushort BITS, Signedness SIGNEDNESS>
-struct IntegerFormat;
-
-template <Signedness SIGNEDNESS>
-struct IntegerFormat<4, SIGNEDNESS> {
- using StorageElement = uchar;
- using UnpackedElement = metal::conditional_t<SIGNEDNESS == Signedness::Signed, int8_t, uint8_t>;
- using TensorElement =
- metal::conditional_t<SIGNEDNESS == Signedness::Signed, metal::int4b_format, metal::uint4b_format>;
- using DevicePointer = const device uchar*;
- using MutableDevicePointer = device uchar*;
- UZU_CONST ushort BITS = 4;
- UZU_CONST ushort ELEMENTS_PER_BYTE = 2;
-};
-
-template <Signedness SIGNEDNESS>
-struct IntegerFormat<8, SIGNEDNESS> {
- using StorageElement = metal::conditional_t<SIGNEDNESS == Signedness::Signed, int8_t, uint8_t>;
- using UnpackedElement = StorageElement;
- using TensorElement = StorageElement;
- using DevicePointer = const device StorageElement*;
- using MutableDevicePointer = device StorageElement*;
- UZU_CONST ushort BITS = 8;
- UZU_CONST ushort ELEMENTS_PER_BYTE = 1;
-};
-
-} // namespace matmul
-} // namespace uzu
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/ops.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/ops.h
index a4f2385f0..3b42179d4 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/ops.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/ops.h
@@ -7,7 +7,6 @@
#include "../defines.h"
#include "../loader.h"
-#include "tensor_operand.h"
#include <MetalPerformancePrimitives/MetalPerformancePrimitives.h>
@@ -27,7 +26,6 @@ struct MxuFragmentOps {
#include "layout.h"
#include "cooperative_vectors.h"
#include "fragment_matmul.h"
-#include "tensor_matmul.h"
};
using MxuStrictFragmentOps = MxuFragmentOps<false>;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/tensor_matmul.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/tensor_matmul.h
deleted file mode 100644
index 6fe704cfa..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/tensor_matmul.h
+++ /dev/null
@@ -1,95 +0,0 @@
-template <typename Format>
-METAL_FUNC static auto make_tensor_view(
- const typename Format::DevicePointer tile_base,
- const int right_row_stride_bytes
-) {
- constexpr int tile_k = int(2 * FRAGMENT_COLS);
- constexpr int tile_n = int(2 * FRAGMENT_COLS);
- using Element = typename Format::TensorElement;
- using RightTensor = tensor<device Element, extents<int, tile_k, tile_n>, tensor_inline>;
-
- const array<int, 2> right_strides = {1, right_row_stride_bytes * Format::ELEMENTS_PER_BYTE};
-
- return RightTensor(
- const_cast<typename Format::MutableDevicePointer>(tile_base),
- extents<int, tile_k, tile_n>{},
- right_strides
- );
-}
-
-template <
- MatmulMode OUTPUT_MODE,
- bool transpose_left,
- bool transpose_right,
- class OutputFragment,
- class LeftFragment,
- typename Format>
-METAL_FUNC static void fragment_matmul(
- thread OutputFragment& output,
- thread LeftFragment& left,
- const DeviceTensorOperand<Format> right
-) {
- static_assert(!transpose_left && transpose_right, "device-tensor leaf: only left x right^T is implemented");
- static_assert(
- metal::is_same_v<typename LeftFragment::ElementType, typename Format::UnpackedElement>,
- "device-tensor leaf: integer operand signedness must match"
- );
- static_assert(RELAXED, "device-tensor operands require the relaxed MXU layout");
- static_assert(LeftFragment::COL_FRAGMENTS == 2, "device-tensor operands expect K tiled as two fragments");
- static_assert(OutputFragment::COL_FRAGMENTS % 2 == 0, "device-tensor operands require even N fragments");
- static_assert(LeftFragment::ROW_FRAGMENTS == OutputFragment::ROW_FRAGMENTS, "M tiles must match");
-
- constexpr ushort rows = OutputFragment::ROW_FRAGMENTS;
- constexpr ushort cols = OutputFragment::COL_FRAGMENTS;
- constexpr int tile_k = int(2 * FRAGMENT_COLS);
- constexpr int tile_n = int(2 * FRAGMENT_COLS);
- constexpr auto descriptor =
- mpp::tensor_ops::matmul2d_descriptor(FRAGMENT_ROWS, tile_n, tile_k, false, true, RELAXED, OUTPUT_MODE);
- mpp::tensor_ops::matmul2d<descriptor, metal::execution_simdgroup> matmul_op;
-
- METAL_PRAGMA_UNROLL
- for (ushort row = 0; row < rows; ++row) {
- METAL_PRAGMA_UNROLL
- for (ushort col = 0; col < cols; col += 2) {
- auto cooperative_left = matmul_op.template get_left_input_cooperative_tensor<
- typename Format::UnpackedElement,
- typename Format::TensorElement,
- int>();
- load_paired_vectors(cooperative_left, left.fragment_at(row, 0), left.fragment_at(row, 1));
-
- auto right_tensor = make_tensor_view<Format>(
- right.base + int(col * FRAGMENT_COLS) * right.row_stride_bytes,
- right.row_stride_bytes
- );
-
- auto cooperative_output =
- matmul_op
- .template get_destination_cooperative_tensor<decltype(cooperative_left), decltype(right_tensor), int>();
-
- if constexpr (OUTPUT_MODE == MatmulMode::multiply_accumulate) {
- load_paired_vectors(cooperative_output, output.fragment_at(row, col), output.fragment_at(row, col + 1));
- }
- matmul_op.run(cooperative_left, right_tensor, cooperative_output);
-
- store_paired_vectors(cooperative_output, output.fragment_at(row, col), output.fragment_at(row, col + 1));
- }
- }
-}
-
-template <bool transpose_left, bool transpose_right, class OutputFragment, class LeftFragment, typename Format>
-METAL_FUNC static void fragment_mma(
- thread OutputFragment& output,
- thread LeftFragment& left,
- const DeviceTensorOperand<Format> right
-) {
- fragment_matmul<MatmulMode::multiply_accumulate, transpose_left, transpose_right>(output, left, right);
-}
-
-template <bool transpose_left, bool transpose_right, class OutputFragment, class LeftFragment, typename Format>
-METAL_FUNC static void fragment_mm(
- thread OutputFragment& output,
- thread LeftFragment& left,
- const DeviceTensorOperand<Format> right
-) {
- fragment_matmul<MatmulMode::multiply, transpose_left, transpose_right>(output, left, right);
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/tensor_operand.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/tensor_operand.h
deleted file mode 100644
index e1e34a955..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/mxu_fragment/tensor_operand.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#pragma once
-
-#include <metal_stdlib>
-
-#include "integer_formats.h"
-
-using namespace metal;
-
-namespace uzu {
-namespace matmul {
-
-template <typename Format>
-struct DeviceTensorOperand {
- using Element = typename Format::TensorElement;
- using Pointer = typename Format::DevicePointer;
-
- Pointer base;
- int row_stride_bytes;
-};
-
-} // namespace matmul
-} // namespace uzu
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h
index ec8a95f03..f160b3fb2 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/common/quant_unpack.h
@@ -55,11 +55,6 @@ 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(uint8_t packed, uint group_index) {
static_assert(BITS == 4 || BITS == 8, "Only int4 and int8 zero points supported");
@@ -76,12 +71,9 @@ METAL_FUNC uint decode_zero_point(const device uint8_t* zero_points_row, uint gr
return decode_zero_point<BITS>(zero_points_row[byte_index], group_index);
}
-METAL_FUNC char4 unpack_signed_nibbles_to_int8(uint packed) {
- uint spread = (packed | (packed << 8)) & 0x00FF00FFu;
- spread = (spread | (spread << 4)) & 0x0F0F0F0Fu;
- constexpr uint sign_bits = symmetric_zero_point<4>() * 0x01010101u;
- return as_type<char4>(spread ^ sign_bits) - char4(char(symmetric_zero_point<4>()));
-}
+UZU_CONST ushort W4_BITS = 4;
+UZU_CONST uint W4_SIGN_MASK = symmetric_zero_point<W4_BITS>() * 0x11111111u;
+UZU_CONST uint W4_NIBBLE_MASK = 0x0F0F0F0Fu;
template <typename U, int N, int bits>
inline void dequantize(const device uint8_t* w, U scale, U bias, threadgroup U* w_local, const bool signed_codes) {
@@ -90,8 +82,7 @@ inline void dequantize(const device uint8_t* w, U scale, U bias, threadgroup U*
if constexpr (bits == 4) {
U s0 = scale;
U s1 = scale / static_cast<U>(16.0f);
- // Keep the mask a literal in each arm; a value derived from the function
- // constant inside the loop defeats vectorization of the unpack.
+ // Keeping literal masks in each arm lets the compiler vectorize the unpack.
if (signed_codes) {
for (int i = 0; i < (N / 2); i++) {
const uint8_t word = w[i] ^ uint8_t(0x88u);
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h
index 9c3bee23a..50ddcce65 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/mxu_mma_core.h
@@ -77,8 +77,6 @@ struct MxuMmaCore {
const device RightElementType* output_bias,
const device int32_t* rht_factors,
threadgroup RightElementType* b_shared,
- const bool stage_weight_scales,
- const bool hoist_operand_addressing,
const thread ThreadContext& thread_context
) {
const uint partition = thread_context.threadgroup_position.z;
@@ -133,21 +131,16 @@ struct MxuMmaCore {
dispatch_bool(
alignment.contains(GemmAlignment::N) || (simdgroup_limit_n == SIMDGROUP_BLOCK_N),
[&](auto aligned_n) {
- AccumFragment accumulator_tile;
- dispatch_bool(stage_weight_scales, [&](auto stage) {
- dispatch_bool(hoist_operand_addressing, [&](auto hoist) {
- accumulator_tile = Schedule::
- template launch<MxuMmaCore, aligned_m.value, aligned_n.value, stage.value, hoist.value>(
- left,
- right,
- b_shared,
- params,
- tile_context,
- alignment,
- thread_context
- );
- });
- });
+ AccumFragment accumulator_tile =
+ Schedule::template launch<MxuMmaCore, aligned_m.value, aligned_n.value>(
+ left,
+ right,
+ b_shared,
+ params,
+ tile_context,
+ alignment,
+ thread_context
+ );
if (apply_scale) {
const AccumulatorType scale = AccumulatorType(params->ab_scale);
@@ -195,7 +188,12 @@ struct MxuMmaCore {
);
if (output_transform.contains(GemmDTransform::RHT)) {
- threadgroup_barrier(mem_flags::mem_device);
+ // Metal rejects a threadgroup barrier when the threadgroup contains one simdgroup.
+ if constexpr (SIMDGROUPS_PER_ROW * SIMDGROUPS_PER_COLUMN == 1) {
+ simdgroup_barrier(mem_flags::mem_device);
+ } else {
+ threadgroup_barrier(mem_flags::mem_device);
+ }
device OutputElementType* d_block = d + block_row * params->leading_dimension_d + block_col;
const ushort tile_block_rows = ushort(min(int(THREADGROUP_BLOCK_M), int(params->M) - int(block_row)));
const ushort tile_block_cols = ushort(min(int(THREADGROUP_BLOCK_N), int(params->N) - int(block_col)));
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/operands.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/operands.h
index c3e855402..0197e014d 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/operands.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/operands.h
@@ -3,7 +3,6 @@
#include <metal_stdlib>
#include "../../../generated/gemm.h"
-#include "../../common/mxu_fragment/integer_formats.h"
using namespace metal;
@@ -11,11 +10,12 @@ namespace uzu {
namespace gemm {
namespace operands {
-template <GemmAPrologueKind PROLOGUE, typename Element, ushort ACTIVATION_GROUP_SIZE>
+template <GemmAPrologueKind PROLOGUE, typename Element, ushort ACTIVATION_GROUP_SIZE, bool CODES_GROUPED_BY_NIBBLE>
struct LeftOperand {
UZU_CONST bool QUANTIZED = PROLOGUE == GemmAPrologueKind::Int8Symmetric;
UZU_CONST ushort BITS = QUANTIZED ? 8 : 0;
UZU_CONST ushort GROUP_SIZE = QUANTIZED ? ACTIVATION_GROUP_SIZE : 0;
+ UZU_CONST bool GROUPED_BY_NIBBLE = CODES_GROUPED_BY_NIBBLE;
static_assert(
QUANTIZED == (ACTIVATION_GROUP_SIZE != 0),
"activation group size must be present exactly for int8 activations"
@@ -25,8 +25,6 @@ struct LeftOperand {
using ScaleElement = float;
using DenseElement = Element;
using ElementType = metal::conditional_t<QUANTIZED, CodeElement, DenseElement>;
- using Format = uzu::matmul::IntegerFormat<8, uzu::matmul::Signedness::Signed>;
-
template <ushort BLOCK_K>
static constexpr ushort outer_block_k() {
if constexpr (QUANTIZED) {
@@ -46,6 +44,10 @@ struct RightOperand {
UZU_CONST GemmBPrologueKind SCHEME = PROLOGUE;
UZU_CONST bool NEEDS_CORRECTION = QUANTIZED && PROLOGUE != GemmBPrologueKind::ScaleSymmetricDequant;
+ UZU_CONST ushort CODE_ORIGIN = (!QUANTIZED || (BITS_ == 4 && PROLOGUE != GemmBPrologueKind::ScaleSymmetricDequant))
+ ? 0
+ : ushort(1u << (BITS - 1));
+
static_assert(!QUANTIZED || BITS_ == 4 || BITS_ == 8, "quantized integer weights must use 4 or 8 bits");
static_assert(!QUANTIZED || PROLOGUE != GemmBPrologueKind::FullPrecision, "quantized weights need a scheme");
@@ -53,11 +55,6 @@ struct RightOperand {
using ScaleElement = Element;
using DenseElement = Element;
using ElementType = DenseElement;
- using Format = metal::conditional_t<
- QUANTIZED,
- uzu::matmul::IntegerFormat<BITS_, uzu::matmul::Signedness::Signed>,
- uzu::matmul::IntegerFormat<8, uzu::matmul::Signedness::Signed>>;
-
template <ushort BLOCK_K>
static constexpr ushort outer_block_k() {
if constexpr (QUANTIZED) {
@@ -142,8 +139,8 @@ METAL_FUNC RightStorage<Right> pack_right(
}
}
-template <GemmAPrologueKind PROLOGUE, typename Element, ushort ACTIVATION_GROUP_SIZE>
-using LeftOperandFor = LeftOperand<PROLOGUE, Element, ACTIVATION_GROUP_SIZE>;
+template <GemmAPrologueKind PROLOGUE, typename Element, ushort ACTIVATION_GROUP_SIZE, bool CODES_GROUPED_BY_NIBBLE>
+using LeftOperandFor = LeftOperand<PROLOGUE, Element, ACTIVATION_GROUP_SIZE, CODES_GROUPED_BY_NIBBLE>;
template <GemmBPrologueKind PROLOGUE, ushort BITS, ushort GROUP_SIZE, typename Element>
using RightOperandFor = RightOperand<PROLOGUE, BITS, GROUP_SIZE, Element>;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.h
index 8d665e5d4..9fe71f078 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_bias.h
@@ -17,7 +17,6 @@ template <
short THREADGROUP_TILE_ROWS,
short THREADGROUP_TILE_COLS,
short DESTINATION_LEADING_DIMENSION,
- short REDUCTION_DIMENSION,
short THREADGROUP_SIZE,
short GROUP_SIZE,
short BITS>
@@ -56,23 +55,20 @@ struct QuantizedBlockLoaderScaleBias {
const device T* biases_,
const bool signed_codes_,
const int src_leading_dim_,
+ const int params_group_stride_,
+ const int params_output_stride_,
threadgroup T* dst_,
ushort simd_group_id [[simdgroup_index_in_threadgroup]],
ushort simd_lane_id [[thread_index_in_simdgroup]]
)
- : src_leading_dim(src_leading_dim_),
- tile_stride(
- REDUCTION_DIMENSION ? THREADGROUP_TILE_COLS_PACKED * BYTES_PER_PACK
- : THREADGROUP_TILE_ROWS * src_leading_dim_ * BYTES_PER_PACK / PACK_FACTOR
- ),
- group_step_counter(0), group_stride(THREADGROUP_TILE_ROWS * src_leading_dim_ / GROUP_SIZE),
- thread_index(simd_group_id * 32 + simd_lane_id),
+ : src_leading_dim(src_leading_dim_), tile_stride(THREADGROUP_TILE_COLS_PACKED * BYTES_PER_PACK),
+ group_step_counter(0), group_stride(params_group_stride_), thread_index(simd_group_id * 32 + simd_lane_id),
tile_row_index(READS_PER_THREAD * thread_index / THREADGROUP_TILE_COLS_PACKED),
tile_col_index((READS_PER_THREAD * thread_index) % THREADGROUP_TILE_COLS_PACKED),
dst(dst_ + tile_row_index * DESTINATION_LEADING_DIMENSION + tile_col_index * PACK_FACTOR),
src(src_ + tile_row_index * src_leading_dim_ * BYTES_PER_PACK / PACK_FACTOR + tile_col_index * BYTES_PER_PACK),
- scales(scales_ + tile_row_index * src_leading_dim_ / GROUP_SIZE),
- biases(biases_ + tile_row_index * src_leading_dim_ / GROUP_SIZE), signed_codes(signed_codes_) {}
+ scales(scales_ + tile_row_index * params_output_stride_),
+ biases(biases_ + tile_row_index * params_output_stride_), signed_codes(signed_codes_) {}
void load_unsafe() const {
if constexpr (TILE_HAS_IDLE_THREADS) {
@@ -126,22 +122,15 @@ struct QuantizedBlockLoaderScaleBias {
void next() {
src += tile_stride;
- if constexpr (REDUCTION_DIMENSION == 1) {
- if constexpr (GROUP_STEPS_PER_BLOCK > 1) {
- group_step_counter++;
- if (group_step_counter == GROUP_STEPS_PER_BLOCK) {
- group_step_counter = 0;
- scales++;
- biases++;
- }
- } else {
- scales++;
- biases++;
+ if constexpr (GROUP_STEPS_PER_BLOCK > 1) {
+ group_step_counter++;
+ if (group_step_counter != GROUP_STEPS_PER_BLOCK) {
+ return;
}
- } else {
- scales += group_stride;
- biases += group_stride;
+ group_step_counter = 0;
}
+ scales += group_stride;
+ biases += group_stride;
}
};
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.h
index defd0d85d..0cdd8d38e 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quant_scale_zero_point.h
@@ -17,7 +17,6 @@ template <
short THREADGROUP_TILE_ROWS,
short THREADGROUP_TILE_COLS,
short DESTINATION_LEADING_DIMENSION,
- short REDUCTION_DIMENSION,
short THREADGROUP_SIZE,
short GROUP_SIZE,
short BITS,
@@ -37,11 +36,10 @@ struct QuantizedBlockLoaderScaleZeroPoint {
UZU_CONST bool TILE_HAS_IDLE_THREADS = THREADGROUP_TILE_COLS_PACKED * THREADGROUP_TILE_ROWS < THREADGROUP_SIZE;
const int src_leading_dim;
- const int groups_per_row;
const int tile_stride;
short group_step_counter;
- int k_base;
const int group_stride;
+ const uint zero_point_group_stride;
const short thread_index;
const short tile_row_index;
@@ -50,8 +48,8 @@ struct QuantizedBlockLoaderScaleZeroPoint {
threadgroup T* dst;
const device uint8_t* src;
const device T* scales;
- const device T* scales_row_start;
const device uint8_t* zero_points_row_start;
+ uint zero_point_index;
const bool signed_codes;
QuantizedBlockLoaderScaleZeroPoint(
@@ -60,31 +58,25 @@ struct QuantizedBlockLoaderScaleZeroPoint {
const device uint8_t* zero_points_row_start_,
const bool signed_codes_,
const int src_leading_dim_,
- const int groups_per_row_,
+ const int params_group_stride_,
+ const int params_output_stride_,
+ const uint zero_point_output_stride_,
+ const uint zero_point_group_stride_,
+ const uint zero_point_index_,
threadgroup T* dst_,
ushort simd_group_id [[simdgroup_index_in_threadgroup]],
ushort simd_lane_id [[thread_index_in_simdgroup]]
)
- : src_leading_dim(src_leading_dim_), groups_per_row(groups_per_row_),
- tile_stride(
- REDUCTION_DIMENSION ? THREADGROUP_TILE_COLS_PACKED * BYTES_PER_PACK
- : THREADGROUP_TILE_ROWS * src_leading_dim_ * BYTES_PER_PACK / PACK_FACTOR
- ),
- group_step_counter(0), k_base(0), group_stride(THREADGROUP_TILE_ROWS * groups_per_row_),
+ : src_leading_dim(src_leading_dim_), tile_stride(THREADGROUP_TILE_COLS_PACKED * BYTES_PER_PACK),
+ group_step_counter(0), group_stride(params_group_stride_), zero_point_group_stride(zero_point_group_stride_),
thread_index(simd_group_id * 32 + simd_lane_id),
tile_row_index(READS_PER_THREAD * thread_index / THREADGROUP_TILE_COLS_PACKED),
tile_col_index((READS_PER_THREAD * thread_index) % THREADGROUP_TILE_COLS_PACKED),
dst(dst_ + tile_row_index * DESTINATION_LEADING_DIMENSION + tile_col_index * PACK_FACTOR),
src(src_ + tile_row_index * src_leading_dim_ * BYTES_PER_PACK / PACK_FACTOR + tile_col_index * BYTES_PER_PACK),
- 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 * zero_point_row_stride<ushort(BITS)>(groups_per_row_))
- : zero_points_row_start_)
- ),
+ scales(scales_ + tile_row_index * params_output_stride_),
+ zero_points_row_start(SCALE_SYMMETRIC ? nullptr : zero_points_row_start_),
+ zero_point_index(zero_point_index_ + uint(tile_row_index) * zero_point_output_stride_),
signed_codes(signed_codes_) {}
QuantizedBlockLoaderScaleZeroPoint(
@@ -92,7 +84,8 @@ struct QuantizedBlockLoaderScaleZeroPoint {
const device T* scales_,
const bool signed_codes_,
const int src_leading_dim_,
- const int groups_per_row_,
+ const int params_group_stride_,
+ const int params_output_stride_,
threadgroup T* dst_,
ushort simd_group_id [[simdgroup_index_in_threadgroup]],
ushort simd_lane_id [[thread_index_in_simdgroup]]
@@ -103,7 +96,11 @@ struct QuantizedBlockLoaderScaleZeroPoint {
static_cast<const device uint8_t*>(nullptr),
signed_codes_,
src_leading_dim_,
- groups_per_row_,
+ params_group_stride_,
+ params_output_stride_,
+ 0,
+ 0,
+ 0,
dst_,
simd_group_id,
simd_lane_id
@@ -114,18 +111,13 @@ struct QuantizedBlockLoaderScaleZeroPoint {
inline void current_scale_bias(thread T& out_scale, thread T& out_bias) const {
uint zero_point_value;
T scale_value;
- int group_index;
- if constexpr (REDUCTION_DIMENSION == 0) {
- group_index = k_base / GROUP_SIZE;
- scale_value = scales_row_start[group_index];
- } else {
- group_index = static_cast<int>(scales - scales_row_start);
- scale_value = *scales;
- }
+ scale_value = *scales;
if constexpr (SCALE_SYMMETRIC) {
zero_point_value = symmetric_zero_point<ushort(BITS)>();
} else {
- zero_point_value = decode_zero_point<ushort(BITS)>(zero_points_row_start, uint(group_index));
+ const uint byte_index = zero_point_index / uint(PACK_FACTOR);
+ const uint packed_index = zero_point_index % uint(PACK_FACTOR);
+ zero_point_value = decode_zero_point<ushort(BITS)>(zero_points_row_start[byte_index], packed_index);
}
out_scale = scale_value;
out_bias = static_cast<T>(-scale_value * static_cast<T>(zero_point_value));
@@ -185,18 +177,16 @@ struct QuantizedBlockLoaderScaleZeroPoint {
void next() {
src += tile_stride;
- if constexpr (REDUCTION_DIMENSION == 1) {
- if constexpr (GROUP_STEPS_PER_BLOCK > 1) {
- group_step_counter++;
- if (group_step_counter == GROUP_STEPS_PER_BLOCK) {
- group_step_counter = 0;
- scales++;
- }
- } else {
- scales++;
+ if constexpr (GROUP_STEPS_PER_BLOCK > 1) {
+ group_step_counter++;
+ if (group_step_counter != GROUP_STEPS_PER_BLOCK) {
+ return;
}
- } else {
- k_base += THREADGROUP_TILE_ROWS;
+ group_step_counter = 0;
+ }
+ scales += group_stride;
+ if constexpr (!SCALE_SYMMETRIC) {
+ zero_point_index += zero_point_group_stride;
}
}
};
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/cache.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/cache.h
deleted file mode 100644
index 49633347d..000000000
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/cache.h
+++ /dev/null
@@ -1,249 +0,0 @@
-#pragma once
-
-#include <metal_stdlib>
-
-#include "../../../../common/thread_context.h"
-#include "../../../../generated/gemm.h"
-#include "../../../common/fragment.h"
-#include "../../../common/quant_pack.h"
-#include "../../../common/quant_unpack.h"
-#include "../schedules/tile_context.h"
-#include "cursor.h"
-
-using namespace metal;
-
-namespace uzu {
-namespace gemm {
-namespace quantized {
-
-enum class Residency {
- Registers,
- Threadgroup,
-};
-
-struct NoStorage {};
-
-template <typename Operand, typename Storage>
-static METAL_FUNC float correction_value(
- const thread Storage& storage,
- const float scale,
- const uint scale_index,
- const uint column,
- const uint group,
- const uint groups_per_row
-) {
- if constexpr (Operand::SCHEME == GemmBPrologueKind::ScaleBiasDequant) {
- return scale * float(symmetric_zero_point<Operand::BITS>()) + float(storage.bias()[scale_index]);
- } else {
- static_assert(
- Operand::SCHEME == GemmBPrologueKind::ScaleZeroPointDequant,
- "correction is only defined for asymmetric quantized weights"
- );
- if constexpr (Operand::BITS == 8) {
- return scale * (float(symmetric_zero_point<Operand::BITS>()) - float(storage.zp()[scale_index]));
- } else {
- const device uint8_t* row = storage.zp() + column * zero_point_row_stride<Operand::BITS>(groups_per_row);
- return scale *
- (float(symmetric_zero_point<Operand::BITS>()) - float(decode_zero_point<Operand::BITS>(row, group)));
- }
- }
-}
-
-template <Residency RESIDENCY, typename Core, typename Storage, typename Operand, bool ALIGNED>
-struct Cache;
-
-template <typename Core, typename Storage, typename Operand, bool ALIGNED>
-struct Cache<Residency::Registers, Core, Storage, Operand, ALIGNED> {
- using Fragment = typename Core::AccumFragment;
- using Ops = typename Core::FragmentOps;
- using WeightOperand = typename Core::RightOperand;
- UZU_CONST bool ROWS = metal::is_same<Storage, typename Core::LeftStorage>::value;
- UZU_CONST bool NEEDS_CORRECTION = WeightOperand::NEEDS_CORRECTION;
-
- UZU_CONST ushort TILES = ROWS ? Fragment::ROW_FRAGMENTS : Fragment::COL_FRAGMENTS;
- UZU_CONST ushort SLOTS = ROWS ? Ops::THREAD_ELEMENT_ROWS : Ops::THREAD_ELEMENT_COLS;
- UZU_CONST ushort EXTENT = ROWS ? Fragment::FRAGMENT_ROWS : Fragment::FRAGMENT_COLS;
- UZU_CONST ushort STRIDE = ROWS ? Ops::THREAD_ELEMENT_ROW_STRIDE : 1;
-
- Storage source;
- short origin;
- short limit;
- uint absolute_base;
- uint scale_k_groups_per_row;
- metal::conditional_t<ROWS, uint, NoStorage> sum_k_groups_per_row;
- uint first_k_offset;
- float scales[TILES * SLOTS];
- metal::conditional_t<NEEDS_CORRECTION, float[TILES * SLOTS], NoStorage> corrections;
-
- METAL_FUNC Cache(
- const Storage source_,
- threadgroup typename Core::RightElementType*,
- const constant uzu::matmul::GemmParams* params,
- const schedules::TileContext tile,
- const thread ThreadContext& thread_context
- ) thread : source(source_) {
- const short2 position = Ops::get_position(thread_context.simd_lane_id);
- if constexpr (ROWS) {
- origin = position.y;
- limit = tile.simdgroup_limit_m;
- absolute_base = tile.abs_row_base;
- scale_k_groups_per_row = uint(params->K) / uint(Operand::GROUP_SIZE);
- const uint correction_group_size =
- Operand::GROUP_SIZE < WeightOperand::GROUP_SIZE ? uint(Operand::GROUP_SIZE) : uint(WeightOperand::GROUP_SIZE);
- sum_k_groups_per_row = uint(params->K) / correction_group_size;
- first_k_offset = tile.k_offset;
- } else {
- origin = position.x;
- limit = tile.simdgroup_limit_n;
- absolute_base = tile.absolute_column_base();
- scale_k_groups_per_row = (uint(params->K) + uint(Operand::GROUP_SIZE) - 1) / uint(Operand::GROUP_SIZE);
- first_k_offset = tile.k_offset;
- }
- }
-
- METAL_FUNC void fill(const int k_group_index) thread {
- fill_at_k_offset(uint(k_group_index) * uint(WeightOperand::GROUP_SIZE));
- }
-
- METAL_FUNC void fill_at_k_offset(const uint relative_k_offset) thread {
- const uint absolute_k_offset = first_k_offset + relative_k_offset;
- const uint absolute_k_group = absolute_k_offset / uint(ROWS ? WeightOperand::GROUP_SIZE : Operand::GROUP_SIZE);
- METAL_PRAGMA_UNROLL
- for (ushort tile_index = 0; tile_index < TILES; ++tile_index) {
- METAL_PRAGMA_UNROLL
- for (ushort slot_index = 0; slot_index < SLOTS; ++slot_index) {
- const short coordinate = origin + short(tile_index * EXTENT + slot_index * STRIDE);
- if (ALIGNED || coordinate < limit) {
- const uint line = absolute_base + uint(coordinate);
- uint scale_index;
- if constexpr (ROWS) {
- const uint scale_k_group = absolute_k_offset / uint(Operand::GROUP_SIZE);
- scale_index = line * scale_k_groups_per_row + scale_k_group;
- } else {
- scale_index = line * scale_k_groups_per_row + absolute_k_group;
- }
- const float group_scale = float(source.scales[scale_index]);
- scales[tile_index * SLOTS + slot_index] = group_scale;
- if constexpr (NEEDS_CORRECTION) {
- if constexpr (ROWS) {
- corrections[tile_index * SLOTS + slot_index] =
- group_scale *
- float(source.correction_sums()
- [line * sum_k_groups_per_row +
- absolute_k_offset / (uint(Operand::GROUP_SIZE) < uint(WeightOperand::GROUP_SIZE)
- ? uint(Operand::GROUP_SIZE)
- : uint(WeightOperand::GROUP_SIZE))]);
- } else {
- corrections[tile_index * SLOTS + slot_index] = correction_value<Operand>(
- source,
- group_scale,
- scale_index,
- line,
- absolute_k_group,
- scale_k_groups_per_row
- );
- }
- }
- }
- }
- }
- }
-
- METAL_FUNC float scale(const short coordinate) const thread { return scales[slot(coordinate)]; }
-
- METAL_FUNC float correction(const short coordinate) const thread { return corrections[slot(coordinate)]; }
-
-private:
- METAL_FUNC ushort slot(const short coordinate) const thread {
- const ushort offset = ushort(coordinate - origin);
- return (offset / EXTENT) * SLOTS + (offset % EXTENT) / STRIDE;
- }
-};
-
-template <typename Core, typename Storage, typename Operand, bool ALIGNED>
-struct Cache<Residency::Threadgroup, Core, Storage, Operand, ALIGNED> {
- using Element = typename Core::RightElementType;
- UZU_CONST bool NEEDS_CORRECTION = Operand::NEEDS_CORRECTION;
-
- Storage source;
- threadgroup Element* shared;
- const threadgroup Element* current_scales;
- metal::conditional_t<NEEDS_CORRECTION, const threadgroup float*, NoStorage> current_corrections;
- uint k_groups_per_row;
- uint first_k_group;
- uint block_column;
- short column_offset;
- short block_columns;
- ushort local_thread_index;
- ushort threads_per_threadgroup;
-
- METAL_FUNC Cache(
- const Storage source_,
- threadgroup Element* shared_,
- const constant uzu::matmul::GemmParams* params,
- const schedules::TileContext tile,
- const thread ThreadContext& thread_context
- ) thread
- : source(source_),
- shared(shared_),
- current_scales(nullptr),
- k_groups_per_row((uint(params->K) + uint(Operand::GROUP_SIZE) - 1) / uint(Operand::GROUP_SIZE)),
- first_k_group(tile.k_offset / uint(Operand::GROUP_SIZE)),
- block_column(uint(tile.block_col)),
- column_offset(short(tile.tile_col_offset)),
- block_columns(short(tile.tile_block_cols)),
- local_thread_index(thread_context.simdgroup_index* thread_context.simdgroup_size + thread_context.simd_lane_id),
- threads_per_threadgroup(thread_context.simdgroups_per_threadgroup* thread_context.simdgroup_size) {}
-
- METAL_FUNC void prefetch(const uint k_group) thread {
- const uint absolute_k_group = first_k_group + k_group;
- uint scale_index = (block_column + uint(local_thread_index)) * k_groups_per_row + absolute_k_group;
- threadgroup Element* group_scales = shared + group_slot_offset(k_group);
- if constexpr (NEEDS_CORRECTION) {
- threadgroup float* group_corrections = group_corrections_for(k_group);
- for (short column = short(local_thread_index); column < block_columns;
- column += short(threads_per_threadgroup), scale_index += uint(threads_per_threadgroup) * k_groups_per_row) {
- const uint weight_column = block_column + uint(column);
- const float group_scale = float(source.scales[scale_index]);
- group_scales[column] = Element(group_scale);
- group_corrections[column] = correction_value<Operand>(
- source,
- group_scale,
- scale_index,
- weight_column,
- absolute_k_group,
- k_groups_per_row
- );
- }
- } else {
- for (short column = short(local_thread_index); column < block_columns;
- column += short(threads_per_threadgroup), scale_index += uint(threads_per_threadgroup) * k_groups_per_row) {
- group_scales[column] = Element(source.scales[scale_index]);
- }
- }
- }
-
- METAL_FUNC void fill(const int k_group_index) thread {
- current_scales = shared + group_slot_offset(uint(k_group_index));
- if constexpr (NEEDS_CORRECTION) {
- current_corrections = group_corrections_for(uint(k_group_index));
- }
- }
-
- METAL_FUNC float scale(const short column) const thread { return float(current_scales[column_offset + column]); }
-
- METAL_FUNC float correction(const short column) const thread { return current_corrections[column_offset + column]; }
-
-private:
- static METAL_FUNC ushort group_slot_offset(const uint k_group) {
- return ushort(k_group & 1) * Core::THREADGROUP_BLOCK_N;
- }
-
- METAL_FUNC threadgroup float* group_corrections_for(const uint k_group) const thread {
- return reinterpret_cast<threadgroup float*>(shared + 2 * Core::THREADGROUP_BLOCK_N) + group_slot_offset(k_group);
- }
-};
-
-} // namespace quantized
-} // namespace gemm
-} // namespace uzu
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/cursor.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/cursor.h
index b6062a162..56e1140c1 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/cursor.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/quantized/cursor.h
@@ -5,7 +5,6 @@
#include "../../../../common/thread_context.h"
#include "../../../../generated/gemm.h"
#include "../../../common/fragment.h"
-#include "../../../common/mxu_fragment/integer_formats.h"
#include "../../../common/quant_pack.h"
#include "../../../common/quant_unpack.h"
#include "../schedules/tile_context.h"
@@ -16,212 +15,206 @@ namespace uzu {
namespace gemm {
namespace quantized {
-using uzu::matmul::DeviceTensorOperand;
-using uzu::matmul::IntegerFormat;
-using uzu::matmul::Signedness;
+namespace {
-using SignedInt4Format = IntegerFormat<4, Signedness::Signed>;
-using SignedInt8Format = IntegerFormat<8, Signedness::Signed>;
-
-enum class Axis {
- Rows,
- Columns,
-};
-
-template <typename Format, typename Fragment, bool ALIGNED, bool HOIST = true>
-struct Cursor;
-
-template <typename Fragment, bool ALIGNED>
-METAL_FUNC Fragment
-load_int8_tile(const device int8_t* src, const int row_stride, const short simdgroup_limit, const ushort simd_lane_id) {
- Fragment tile;
- auto source = uzu::matmul::fragment_source(src, row_stride);
- if constexpr (!ALIGNED) {
- source = source.bounded(simdgroup_limit, Fragment::COL_FRAGMENTS * Fragment::FragmentOpsType::FRAGMENT_ROWS);
+template <typename Fragment, typename Visitor>
+static METAL_FUNC void for_each_fragment_row(Visitor visitor) {
+ using Ops = typename Fragment::FragmentOpsType;
+ METAL_PRAGMA_UNROLL
+ for (ushort fragment_row = 0; fragment_row < Fragment::ROW_FRAGMENTS; ++fragment_row) {
+ METAL_PRAGMA_UNROLL
+ for (ushort row_slot = 0; row_slot < Ops::THREAD_ELEMENT_ROWS; ++row_slot) {
+ const short row_offset =
+ short(fragment_row * Ops::FRAGMENT_ROWS) + short(row_slot * Ops::THREAD_ELEMENT_ROW_STRIDE);
+ visitor(fragment_row, row_slot, row_offset);
+ }
}
- tile.load_from(simd_lane_id, source);
- return tile;
}
+} // namespace
-template <typename Fragment>
-METAL_FUNC Fragment load_int4_unaligned_tile(
- const device uint8_t* current,
- const int row_stride_bytes,
- const short simdgroup_limit,
- const short2 position
-) {
- using Ops = typename Fragment::FragmentOpsType;
+template <typename Fragment, bool ALIGNED, bool CODES_GROUPED_BY_NIBBLE>
+METAL_FUNC Fragment
+load_int8_tile(const device int8_t* src, const int row_stride, const short simdgroup_limit, const ushort simd_lane_id) {
Fragment tile;
- METAL_PRAGMA_UNROLL
- for (ushort tile_n = 0; tile_n < Fragment::ROW_FRAGMENTS; ++tile_n) {
- METAL_PRAGMA_UNROLL
- for (ushort tile_k = 0; tile_k < Fragment::COL_FRAGMENTS; ++tile_k) {
- thread auto& vector = tile.fragment_at(tile_n, tile_k);
+ if constexpr (CODES_GROUPED_BY_NIBBLE) {
+ using Ops = typename Fragment::FragmentOpsType;
+ const short2 position = Ops::get_position(simd_lane_id);
+ const device int8_t* base = src + int(position.y) * row_stride + int(get_pack_factor<W4_BITS>()) * int(position.x);
+ const short row_limit = simdgroup_limit - position.y;
+ for_each_fragment_row<Fragment>([&](ushort fragment_row, ushort row_slot, short row_offset) {
+ vec<uint, Fragment::COL_FRAGMENTS> packed_chunk(0u);
+ if (ALIGNED || row_offset < row_limit) {
+ packed_chunk =
+ *reinterpret_cast<const device vec<uint, Fragment::COL_FRAGMENTS>*>(base + int(row_offset) * row_stride);
+ }
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 (row < simdgroup_limit) {
- const int k_base = int(tile_k * Ops::FRAGMENT_COLS) + int(position.x);
- const ushort packed =
- *reinterpret_cast<const device ushort*>(current + int(row) * row_stride_bytes + (k_base >> 1));
- codes = unpack_signed_nibbles_to_int8(uint(packed));
- }
- vector[element_base + 0] = codes.x;
- vector[element_base + 1] = codes.y;
- vector[element_base + 2] = codes.z;
- vector[element_base + 3] = codes.w;
+ for (ushort fragment_column = 0; fragment_column < Fragment::COL_FRAGMENTS; ++fragment_column) {
+ reinterpret_cast<thread uint*>(&tile.fragment_at(fragment_row, fragment_column))[row_slot] =
+ packed_chunk[fragment_column];
}
+ });
+ } else {
+ auto source = uzu::matmul::fragment_source(src, row_stride);
+ if constexpr (!ALIGNED) {
+ source = source.bounded(simdgroup_limit, Fragment::COL_FRAGMENTS * Fragment::FragmentOpsType::FRAGMENT_ROWS);
}
+ tile.load_from(simd_lane_id, source);
}
return tile;
}
-template <typename Fragment, bool ALIGNED>
-struct Cursor<SignedInt8Format, Fragment, ALIGNED, true> {
- using Ops = typename Fragment::FragmentOpsType;
- UZU_CONST short BLOCK_K = short(Fragment::COL_FRAGMENTS * Ops::FRAGMENT_ROWS);
-
- const device int8_t* current;
- int row_stride;
- short simdgroup_limit;
- ushort simd_lane_id;
-
- METAL_FUNC Fragment load(const uint) const thread {
- return load_int8_tile<Fragment, ALIGNED>(current, row_stride, simdgroup_limit, simd_lane_id);
- }
-
- METAL_FUNC void advance() thread { current += BLOCK_K; }
-
- METAL_FUNC void begin_k_group(const uint) thread {}
-};
-
-template <typename Fragment, bool ALIGNED>
-struct Cursor<SignedInt8Format, Fragment, ALIGNED, false> {
+template <typename Fragment, bool ALIGNED, bool CODES_GROUPED_BY_NIBBLE, bool HOISTED>
+struct Int8Cursor {
using Ops = typename Fragment::FragmentOpsType;
UZU_CONST short BLOCK_K = short(Fragment::COL_FRAGMENTS * Ops::FRAGMENT_ROWS);
- const device int8_t* base;
- const device int8_t* group_base;
+ const device int8_t* origin;
+ const device int8_t* address;
int row_stride;
short simdgroup_limit;
ushort simd_lane_id;
METAL_FUNC Fragment load(const uint chunk_index) const thread {
- return load_int8_tile<Fragment, ALIGNED>(
- group_base + chunk_index * uint(BLOCK_K),
+ const device int8_t* source = address;
+ if constexpr (!HOISTED) {
+ source += chunk_index * uint(BLOCK_K);
+ }
+ return load_int8_tile<Fragment, ALIGNED, CODES_GROUPED_BY_NIBBLE>(
+ source,
row_stride,
simdgroup_limit,
simd_lane_id
);
}
- METAL_FUNC void advance() thread {}
+ METAL_FUNC void advance() thread {
+ if constexpr (HOISTED) {
+ address += BLOCK_K;
+ }
+ }
- METAL_FUNC void begin_k_group(const uint k_offset) thread { group_base = base + k_offset; }
+ METAL_FUNC void begin_k_group(const uint k_offset) thread {
+ if constexpr (!HOISTED) {
+ address = origin + k_offset;
+ }
+ }
};
-template <typename Fragment, bool HOIST>
-struct Cursor<SignedInt4Format, Fragment, false, HOIST> {
+template <typename Fragment, bool ALIGNED, ushort CODE_ORIGIN>
+struct W4Cursor {
using Ops = typename Fragment::FragmentOpsType;
UZU_CONST short BLOCK_K = short(Fragment::COL_FRAGMENTS * Ops::FRAGMENT_ROWS);
- const device uint8_t* current;
- int row_stride_bytes;
- short simdgroup_limit;
- short2 position;
-
- METAL_FUNC Fragment load(const uint) const thread {
- return load_int4_unaligned_tile<Fragment>(current, row_stride_bytes, simdgroup_limit, position);
- }
-
- METAL_FUNC void advance() thread { current += uint(BLOCK_K) * uint(SignedInt4Format::BITS) / 8; }
+ UZU_CONST uint CHUNK_BYTES = uint(BLOCK_K) * uint(get_bytes_per_pack<W4_BITS>()) / uint(get_pack_factor<W4_BITS>());
- METAL_FUNC void begin_k_group(const uint) thread {}
-};
+ struct PackedChunk {
+ UZU_CONST ushort WORD_COUNT = Fragment::ROW_FRAGMENTS * Ops::THREAD_ELEMENT_ROWS;
+ uint words[WORD_COUNT];
-template <typename Fragment, bool HOIST>
-struct Cursor<SignedInt4Format, Fragment, true, HOIST> {
- using Ops = typename Fragment::FragmentOpsType;
- UZU_CONST short BLOCK_K = short(Fragment::COL_FRAGMENTS * Ops::FRAGMENT_ROWS);
+ static constexpr ushort word_index(const ushort fragment_row, const ushort row_slot) {
+ return fragment_row * Ops::THREAD_ELEMENT_ROWS + row_slot;
+ }
+ };
const device uint8_t* current;
int row_stride_bytes;
+ short tile_row_limit;
+ short2 position;
+ bool signed_codes;
+
+ METAL_FUNC PackedChunk fetch(const uint chunk_index) const thread {
+ // Padding decodes to zero after the optional sign flip and code-origin adjustment.
+ const uint padding_word = (CODE_ORIGIN == 0) == signed_codes ? W4_SIGN_MASK : 0u;
+ const device uint8_t* base =
+ current + chunk_index * CHUNK_BYTES + int(position.y) * row_stride_bytes + int(position.x);
+ const short row_limit = tile_row_limit - position.y;
+ PackedChunk packed_chunk;
+ for_each_fragment_row<Fragment>([&](ushort fragment_row, ushort row_slot, short row_offset) {
+ uint word = padding_word;
+ if (ALIGNED || row_offset < row_limit) {
+ word = *reinterpret_cast<const device uint*>(base + int(row_offset) * row_stride_bytes);
+ }
+ packed_chunk.words[PackedChunk::word_index(fragment_row, row_slot)] = word;
+ });
+ return packed_chunk;
+ }
- METAL_FUNC DeviceTensorOperand<SignedInt4Format> load(const uint) const thread { return {current, row_stride_bytes}; }
+ METAL_FUNC Fragment decode(const thread PackedChunk& packed_chunk) const thread {
+ Fragment tile;
+ for_each_fragment_row<Fragment>([&](ushort fragment_row, ushort row_slot, short) {
+ const uint word =
+ packed_chunk.words[PackedChunk::word_index(fragment_row, row_slot)] ^ (signed_codes ? W4_SIGN_MASK : 0u);
+ uint low = word & W4_NIBBLE_MASK;
+ uint high = (word >> W4_BITS) & W4_NIBBLE_MASK;
+ if constexpr (CODE_ORIGIN != 0) {
+ low = as_type<uint>(as_type<char4>(low) - char4(char(CODE_ORIGIN)));
+ high = as_type<uint>(as_type<char4>(high) - char4(char(CODE_ORIGIN)));
+ }
+ reinterpret_cast<thread uint*>(&tile.fragment_at(fragment_row, 0))[row_slot] = low;
+ reinterpret_cast<thread uint*>(&tile.fragment_at(fragment_row, 1))[row_slot] = high;
+ });
+ return tile;
+ }
- METAL_FUNC void advance() thread { current += uint(BLOCK_K) * uint(SignedInt4Format::BITS) / 8; }
+ METAL_FUNC Fragment load(const uint) const thread { return decode(fetch(0)); }
+
+ METAL_FUNC void advance() thread { current += CHUNK_BYTES; }
METAL_FUNC void begin_k_group(const uint) thread {}
};
-template <Axis AXIS, bool HOIST_OPERAND_ADDRESSING, typename Core, typename Format, bool ALIGNED, typename Storage>
-static METAL_FUNC auto make_cursor(
- const Storage source,
+template <bool HOIST_OPERAND_ADDRESSING, typename Core, typename LeftOperand, bool ALIGNED>
+static METAL_FUNC auto make_left_cursor(
+ const typename Core::LeftStorage source,
const constant uzu::matmul::GemmParams* params,
const schedules::TileContext tile,
const thread ThreadContext& thread_context
) {
- if constexpr (AXIS == Axis::Rows) {
- using Fragment = uzu::matmul::Fragment<int8_t, Core::TILES_M, Core::TILES_K, typename Core::FragmentOps>;
- const device int8_t* current =
- source.codes + size_t(tile.abs_row_base) * params->leading_dimension_a + tile.k_offset;
- if constexpr (HOIST_OPERAND_ADDRESSING) {
- return Cursor<Format, Fragment, ALIGNED, true>{
- current,
- int(params->leading_dimension_a),
- tile.simdgroup_limit_m,
- ushort(thread_context.simd_lane_id)
- };
- } else {
- return Cursor<Format, Fragment, ALIGNED, false>{
- current,
- current,
- int(params->leading_dimension_a),
- tile.simdgroup_limit_m,
- ushort(thread_context.simd_lane_id)
- };
- }
+ using Fragment = uzu::matmul::Fragment<int8_t, Core::TILES_M, Core::TILES_K, typename Core::FragmentOps>;
+ const device int8_t* origin = source.codes + size_t(tile.abs_row_base) * params->leading_dimension_a + tile.k_offset;
+ return Int8Cursor<Fragment, ALIGNED, LeftOperand::GROUPED_BY_NIBBLE, HOIST_OPERAND_ADDRESSING>{
+ origin,
+ origin,
+ int(params->leading_dimension_a),
+ tile.simdgroup_limit_m,
+ ushort(thread_context.simd_lane_id)
+ };
+}
+
+template <bool HOIST_OPERAND_ADDRESSING, typename Core, typename Operand, bool ALIGNED>
+static METAL_FUNC auto make_right_cursor(
+ const typename Core::RightStorage source,
+ const constant uzu::matmul::GemmParams* params,
+ const schedules::TileContext tile,
+ const thread ThreadContext& thread_context
+) {
+ using Ops = uzu::matmul::MxuFragmentOps<>;
+ using Fragment = uzu::matmul::Fragment<int8_t, Core::TILES_N, Core::TILES_K, Ops, uzu::matmul::ReadDirect, true>;
+ const int row_stride_bytes =
+ int(uint(params->K) * uint(get_bytes_per_pack<Operand::BITS>()) / uint(get_pack_factor<Operand::BITS>()));
+ const device uint8_t* current =
+ source.codes + size_t(tile.block_col + tile.tile_col_offset) * size_t(row_stride_bytes) +
+ size_t(tile.k_offset) * size_t(get_bytes_per_pack<Operand::BITS>()) / size_t(get_pack_factor<Operand::BITS>());
+
+ if constexpr (Operand::BITS == 4) {
+ static_assert(Core::TILES_K == get_pack_factor<Operand::BITS>(), "W4 requires two K fragments");
+ return W4Cursor<Fragment, ALIGNED, Operand::CODE_ORIGIN>{
+ current,
+ row_stride_bytes,
+ tile.simdgroup_limit_n,
+ Ops::get_position(thread_context.simd_lane_id),
+ source.signed_codes
+ };
} else {
- using Ops = uzu::matmul::MxuFragmentOps<>;
- using Fragment = uzu::matmul::Fragment<int8_t, Core::TILES_N, Core::TILES_K, Ops, uzu::matmul::ReadDirect, true>;
- const int row_stride_bytes =
- int(uint(params->K) * uint(get_bytes_per_pack<Format::BITS>()) / uint(get_pack_factor<Format::BITS>()));
- const device uint8_t* current =
- source.codes + size_t(tile.block_col + tile.tile_col_offset) * size_t(row_stride_bytes) +
- size_t(tile.k_offset) * size_t(get_bytes_per_pack<Format::BITS>()) / size_t(get_pack_factor<Format::BITS>());
-
- if constexpr (Format::BITS == 4 && ALIGNED) {
- return Cursor<Format, Fragment, true, HOIST_OPERAND_ADDRESSING>{current, row_stride_bytes};
- } else if constexpr (Format::BITS == 4) {
- return Cursor<Format, Fragment, false, HOIST_OPERAND_ADDRESSING>{
- current,
- row_stride_bytes,
- tile.simdgroup_limit_n,
- Ops::get_position(thread_context.simd_lane_id)
- };
- } else {
- static_assert(Format::BITS == 8, "integer tile cursors support 4-bit and 8-bit codes");
- const device int8_t* current_int8 = reinterpret_cast<const device int8_t*>(current);
- if constexpr (HOIST_OPERAND_ADDRESSING) {
- return Cursor<Format, Fragment, ALIGNED, true>{
- current_int8,
- row_stride_bytes,
- tile.simdgroup_limit_n,
- ushort(thread_context.simd_lane_id)
- };
- } else {
- return Cursor<Format, Fragment, ALIGNED, false>{
- current_int8,
- current_int8,
- row_stride_bytes,
- tile.simdgroup_limit_n,
- ushort(thread_context.simd_lane_id)
- };
- }
- }
+ static_assert(Operand::BITS == 8, "integer tile cursors support 4-bit and 8-bit codes");
+ const device int8_t* origin_int8 = reinterpret_cast<const device int8_t*>(current);
+ return Int8Cursor<Fragment, ALIGNED, false, HOIST_OPERAND_ADDRESSING>{
+ origin_int8,
+ origin_int8,
+ row_stride_bytes,
+ tile.simdgroup_limit_n,
+ ushort(thread_context.simd_lane_id)
+ };
}
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/dense.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/dense.h
index 3bc5df857..27b2c319b 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/dense.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/dense.h
@@ -15,7 +15,7 @@ namespace gemm {
namespace schedules {
struct DenseSchedule {
- template <typename Core, bool ALIGNED_M, bool ALIGNED_N, bool, bool>
+ template <typename Core, bool ALIGNED_M, bool ALIGNED_N>
static METAL_FUNC typename Core::AccumFragment launch(
typename Core::LeftStorage left,
typename Core::RightStorage right,
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/integer.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/integer.h
index 1944abda0..271d99673 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/integer.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/integer.h
@@ -2,13 +2,15 @@
#include <metal_stdlib>
+#include "../../../../common/integral_constant.h"
#include "../../../../common/thread_context.h"
#include "../../../../generated/gemm.h"
+#include "../../../../generated/matmul.h"
#include "../../../common/fragment.h"
#include "../../../common/mxu_fragment/ops.h"
#include "../gemm_alignment.h"
+#include "../gemm_tiling.h"
#include "../operands.h"
-#include "../quantized/cache.h"
#include "../quantized/cursor.h"
#include "tile_context.h"
@@ -19,121 +21,316 @@ namespace gemm {
namespace schedules {
+namespace {
+
+static METAL_FUNC uint clamp_group_output_column(const uint column, const uint padded_output_count) {
+ return min(column, padded_output_count - uzu::matmul::QUANT_PARAMS_GROUP_OUTPUT_ALIGNMENT);
+}
+
+template <int COUNT, typename Visitor>
+static METAL_FUNC void for_each_static_index(Visitor visitor) {
+ const_for_loop<0, COUNT, 1>([&](auto slot) { visitor(ushort(decltype(slot)::value)); });
+}
+
+template <typename Accumulator, typename GroupProductFragment, typename Visitor>
+static METAL_FUNC void for_each_fragment(
+ thread Accumulator& accumulator,
+ thread GroupProductFragment& group_product,
+ Visitor visitor
+) {
+ for_each_static_index<int(GroupProductFragment::COL_FRAGMENTS)>([&](const ushort tile_n) {
+ for_each_static_index<int(GroupProductFragment::ROW_FRAGMENTS)>([&](const ushort tile_m) {
+ visitor(tile_m, tile_n, accumulator.fragment_at(tile_m, tile_n), group_product.fragment_at(tile_m, tile_n));
+ });
+ });
+}
+
+} // namespace
+
+struct MetadataContext {
+ uint left_row_base;
+ short left_row_limit;
+ uint right_column_base;
+ short right_column_limit;
+ uint left_group_count;
+ uint right_group_count;
+ uint right_scale_group_stride;
+ uint right_zero_point_group_stride;
+};
+
template <typename LeftOperand, typename RightOperand>
struct IntegerSchedule {
- UZU_CONST bool NEEDS_CORRECTION = RightOperand::NEEDS_CORRECTION;
+ UZU_CONST uint RIGHT_GROUP_SIZE = uint(RightOperand::GROUP_SIZE);
+ UZU_CONST bool HAS_ZERO_POINTS = RightOperand::SCHEME == GemmBPrologueKind::ScaleZeroPointDequant;
+ UZU_CONST bool HAS_BIAS = RightOperand::SCHEME == GemmBPrologueKind::ScaleBiasDequant;
+ UZU_CONST uchar RIGHT_CODE_OFFSET = uchar(RightOperand::CODE_ORIGIN);
+
+ template <typename Core, bool ALIGNED_M>
+ struct LeftMetadata {
+ using Ops = typename Core::FragmentOps;
+ UZU_CONST ushort THREAD_ROWS_PER_FRAGMENT = Ops::THREAD_ELEMENT_ROWS;
+ UZU_CONST ushort LEFT_VALUE_COUNT = Core::TILES_M * THREAD_ROWS_PER_FRAGMENT;
+
+ float scales[LEFT_VALUE_COUNT];
+ metal::conditional_t<HAS_ZERO_POINTS, int, float> group_corrections[LEFT_VALUE_COUNT];
+
+ struct LeftSlot {
+ uint row_index;
+ bool live;
+ };
+
+ static METAL_FUNC LeftSlot left_slot(const MetadataContext metadata_context, const ushort index) {
+ const short left_row_offset = short(
+ (index / THREAD_ROWS_PER_FRAGMENT) * Ops::FRAGMENT_ROWS +
+ (index % THREAD_ROWS_PER_FRAGMENT) * Ops::THREAD_ELEMENT_ROW_STRIDE
+ );
+ return {
+ metadata_context.left_row_base + uint(left_row_offset),
+ ALIGNED_M || (left_row_offset < metadata_context.left_row_limit)
+ };
+ }
+
+ METAL_FUNC void load(
+ const typename Core::LeftStorage left,
+ const MetadataContext metadata_context,
+ const uint k_offset
+ ) thread {
+ if (LeftOperand::GROUP_SIZE == RightOperand::GROUP_SIZE || (k_offset % uint(LeftOperand::GROUP_SIZE)) == 0u) {
+ const uint left_group_index = k_offset / uint(LeftOperand::GROUP_SIZE);
+ for_each_static_index<int(LEFT_VALUE_COUNT)>([&](const ushort index) {
+ const LeftSlot slot = left_slot(metadata_context, index);
+ scales[index] =
+ slot.live ? float(left.scales[slot.row_index * metadata_context.left_group_count + left_group_index])
+ : 0.0f;
+ });
+ }
+
+ if constexpr (HAS_ZERO_POINTS || HAS_BIAS) {
+ const uint right_group_index = k_offset / RIGHT_GROUP_SIZE;
+ for_each_static_index<int(LEFT_VALUE_COUNT)>([&](const ushort index) {
+ const LeftSlot slot = left_slot(metadata_context, index);
+ const int code_sum =
+ slot.live
+ ? left.correction_sums()[slot.row_index * metadata_context.right_group_count + right_group_index]
+ : 0;
+ if constexpr (HAS_ZERO_POINTS) {
+ group_corrections[index] = code_sum;
+ } else {
+ group_corrections[index] = slot.live ? (scales[index] * float(code_sum)) : 0.0f;
+ }
+ });
+ }
+ }
+ };
+
+ template <typename Core, bool ALIGNED_N>
+ struct RightMetadata {
+ using Ops = typename Core::FragmentOps;
+ using ScaleElement = typename RightOperand::ScaleElement;
+ using ScaleVector = vec<ScaleElement, Ops::THREAD_ELEMENT_COLS>;
+ using ZeroPointVector = uchar4;
+ static_assert(
+ Ops::THREAD_ELEMENT_COLS == uzu::matmul::QUANT_PARAMS_GROUP_OUTPUT_ALIGNMENT,
+ "group-major metadata must use the metadata load width"
+ );
+
+ ScaleVector scales[Core::TILES_N];
+ ScaleVector bias_offsets[Core::TILES_N];
+ ZeroPointVector zero_points[Core::TILES_N];
- template <typename Core, bool ALIGNED_M, bool ALIGNED_N, bool STAGE_WEIGHT_SCALES, bool HOIST_OPERAND_ADDRESSING>
+ METAL_FUNC void load(
+ const typename Core::RightStorage right,
+ const MetadataContext metadata_context,
+ const uint right_group_index
+ ) thread {
+ for_each_static_index<int(Core::TILES_N)>([&](const ushort tile_n) {
+ const ushort right_column_offset = tile_n * Ops::FRAGMENT_COLS;
+ uint right_scale_column_start = metadata_context.right_column_base + uint(right_column_offset);
+ if constexpr (!ALIGNED_N) {
+ right_scale_column_start =
+ clamp_group_output_column(right_scale_column_start, metadata_context.right_scale_group_stride);
+ }
+ scales[tile_n] = *reinterpret_cast<const device ScaleVector*>(
+ right.scales + right_group_index * metadata_context.right_scale_group_stride + right_scale_column_start
+ );
+ if constexpr (HAS_BIAS) {
+ bias_offsets[tile_n] = *reinterpret_cast<const device ScaleVector*>(
+ right.bias() + right_group_index * metadata_context.right_scale_group_stride + right_scale_column_start
+ );
+ bias_offsets[tile_n] += scales[tile_n] * ScaleElement(RIGHT_CODE_OFFSET);
+ }
+ if constexpr (HAS_ZERO_POINTS) {
+ constexpr uint ZERO_POINT_PACK_FACTOR = 8u / uint(RightOperand::BITS);
+ const device uint8_t* zero_point_row =
+ right.zp() +
+ right_group_index * (metadata_context.right_zero_point_group_stride / ZERO_POINT_PACK_FACTOR);
+ uint right_zero_point_column_start = metadata_context.right_column_base + uint(right_column_offset);
+ if constexpr (!ALIGNED_N) {
+ right_zero_point_column_start = clamp_group_output_column(
+ right_zero_point_column_start,
+ metadata_context.right_zero_point_group_stride
+ );
+ }
+ if constexpr (RightOperand::BITS == 4) {
+ const ushort packed =
+ *reinterpret_cast<const device ushort*>(zero_point_row + (right_zero_point_column_start >> 1));
+ uint spread = (uint(packed) | (uint(packed) << 8)) & 0x00FF00FFu;
+ spread = (spread | (spread << 4)) & 0x0F0F0F0Fu;
+ zero_points[tile_n] = as_type<ZeroPointVector>(spread);
+ } else {
+ zero_points[tile_n] =
+ *reinterpret_cast<const device ZeroPointVector*>(zero_point_row + right_zero_point_column_start);
+ }
+ }
+ if constexpr (!ALIGNED_N) {
+ const bool4 live =
+ (short4(right_column_offset) + short4(0, 1, 2, 3)) < short4(metadata_context.right_column_limit);
+ scales[tile_n] = select(ScaleVector(0), scales[tile_n], live);
+ if constexpr (HAS_BIAS) {
+ bias_offsets[tile_n] = select(ScaleVector(0), bias_offsets[tile_n], live);
+ }
+ if constexpr (HAS_ZERO_POINTS) {
+ zero_points[tile_n] = select(ZeroPointVector(RIGHT_CODE_OFFSET), zero_points[tile_n], live);
+ }
+ }
+ });
+ }
+ };
+
+ template <typename Core>
+ using GroupProducts = uzu::matmul::Fragment<int, Core::TILES_M, Core::TILES_N, typename Core::FragmentOps>;
+
+ template <typename Core, typename LeftCodes, typename RightCodes>
+ static METAL_FUNC GroupProducts<Core> multiply_group(thread LeftCodes& left_codes, thread RightCodes& right_codes) {
+ constexpr int chunks_per_group = int(RIGHT_GROUP_SIZE) / int(Core::SIMDGROUP_BLOCK_K);
+ constexpr bool PREFETCH_INT4_CHUNKS = Core::TILES_M == 1 && chunks_per_group > 1 && RightOperand::BITS == 4;
+ GroupProducts<Core> group_product;
+ group_product.clear();
+ if constexpr (PREFETCH_INT4_CHUNKS) {
+ typename RightCodes::PackedChunk packed_chunks[chunks_per_group];
+ for_each_static_index<chunks_per_group>([&](const ushort chunk) {
+ packed_chunks[chunk] = right_codes.fetch(uint(chunk));
+ });
+ for_each_static_index<chunks_per_group>([&](const ushort chunk) {
+ auto left_tile = left_codes.load(uint(chunk));
+ auto right_tile = right_codes.decode(packed_chunks[chunk]);
+ uzu::matmul::fragment_mma(group_product, left_tile, right_tile);
+ left_codes.advance();
+ right_codes.advance();
+ });
+ } else {
+ METAL_PRAGMA_NO_UNROLL
+ for (int chunk = 0; chunk < chunks_per_group; ++chunk) {
+ auto left_tile = left_codes.load(uint(chunk));
+ auto right_tile = right_codes.load(uint(chunk));
+ uzu::matmul::fragment_mma(group_product, left_tile, right_tile);
+ left_codes.advance();
+ right_codes.advance();
+ }
+ }
+ return group_product;
+ }
+
+ template <typename Core, bool ALIGNED_M, bool ALIGNED_N>
+ static METAL_FUNC void accumulate_group(
+ thread typename Core::AccumFragment& accumulator,
+ thread GroupProducts<Core>& group_product,
+ const thread LeftMetadata<Core, ALIGNED_M>& left_metadata,
+ const thread RightMetadata<Core, ALIGNED_N>& right_metadata
+ ) {
+ using Ops = typename Core::FragmentOps;
+
+ for_each_fragment(
+ accumulator,
+ group_product,
+ [&](const ushort tile_m, const ushort tile_n, thread auto& accumulated, thread auto& group_product_value) {
+ for_each_static_index<int(Ops::THREAD_ELEMENT_ROWS) * int(Ops::THREAD_ELEMENT_COLS)>(
+ [&](const ushort element) {
+ const ushort right_column = element % Ops::THREAD_ELEMENT_COLS;
+ const ushort left_row = tile_m * Ops::THREAD_ELEMENT_ROWS + element / Ops::THREAD_ELEMENT_COLS;
+ const float right_scale = float(right_metadata.scales[tile_n][right_column]);
+ int centered_product = group_product_value[element];
+ if constexpr (HAS_ZERO_POINTS) {
+ centered_product += (int(RIGHT_CODE_OFFSET) - int(right_metadata.zero_points[tile_n][right_column])) *
+ left_metadata.group_corrections[left_row];
+ }
+ accumulated[element] =
+ fma(left_metadata.scales[left_row] * right_scale, float(centered_product), accumulated[element]);
+ if constexpr (HAS_BIAS) {
+ accumulated[element] =
+ fma(right_metadata.bias_offsets[tile_n][right_column],
+ left_metadata.group_corrections[left_row],
+ accumulated[element]);
+ }
+ }
+ );
+ }
+ );
+ }
+
+ template <typename Core, bool ALIGNED_M, bool ALIGNED_N>
static METAL_FUNC typename Core::AccumFragment launch(
typename Core::LeftStorage left_storage,
typename Core::RightStorage right_storage,
- threadgroup typename Core::RightElementType* shared,
+ threadgroup typename Core::RightElementType*,
const constant uzu::matmul::GemmParams* params,
const TileContext tile,
const GemmAlignment,
const thread ThreadContext& thread_context
) {
static_assert(LeftOperand::QUANTIZED && RightOperand::QUANTIZED, "integer schedule requires quantized operands");
- static_assert(LeftOperand::GROUP_SIZE % Core::SIMDGROUP_BLOCK_K == 0, "left groups must contain MMA chunks");
static_assert(RightOperand::GROUP_SIZE % Core::SIMDGROUP_BLOCK_K == 0, "right groups must contain MMA chunks");
static_assert(
- LeftOperand::GROUP_SIZE % RightOperand::GROUP_SIZE == 0 ||
- RightOperand::GROUP_SIZE % LeftOperand::GROUP_SIZE == 0,
- "left and right quantization groups must divide one another"
+ LeftOperand::GROUP_SIZE % RightOperand::GROUP_SIZE == 0,
+ "the left group must hold a whole number of right groups"
);
- constexpr ushort SPAN =
- LeftOperand::GROUP_SIZE < RightOperand::GROUP_SIZE ? LeftOperand::GROUP_SIZE : RightOperand::GROUP_SIZE;
-
- auto left_codes = quantized::
- make_cursor<quantized::Axis::Rows, HOIST_OPERAND_ADDRESSING, Core, typename LeftOperand::Format, ALIGNED_M>(
- left_storage,
- params,
- tile,
- thread_context
- );
- auto right_codes = quantized::
- make_cursor<quantized::Axis::Columns, HOIST_OPERAND_ADDRESSING, Core, typename RightOperand::Format, ALIGNED_N>(
- right_storage,
- params,
- tile,
- thread_context
- );
- quantized::Cache<quantized::Residency::Registers, Core, typename Core::LeftStorage, LeftOperand, ALIGNED_M>
- left_scales(left_storage, shared, params, tile, thread_context);
- quantized::Cache<
- STAGE_WEIGHT_SCALES ? quantized::Residency::Threadgroup : quantized::Residency::Registers,
- Core,
- typename Core::RightStorage,
- RightOperand,
- ALIGNED_N>
- right_scales(right_storage, shared, params, tile, thread_context);
+ constexpr bool HOIST_OPERAND_ADDRESSING =
+ !(RightOperand::SCHEME == GemmBPrologueKind::ScaleSymmetricDequant &&
+ Core::TILING == GemmTiling::Tile128x128x256_Simdgroups4x4);
- typename Core::AccumFragment accumulator;
- accumulator.clear();
+ auto left_codes = quantized::make_left_cursor<HOIST_OPERAND_ADDRESSING, Core, LeftOperand, ALIGNED_M>(
+ left_storage,
+ params,
+ tile,
+ thread_context
+ );
+ auto right_codes = quantized::make_right_cursor<HOIST_OPERAND_ADDRESSING, Core, RightOperand, ALIGNED_N>(
+ right_storage,
+ params,
+ tile,
+ thread_context
+ );
- if constexpr (STAGE_WEIGHT_SCALES) {
- right_scales.prefetch(0);
- }
+ const short2 position = Core::FragmentOps::get_position(thread_context.simd_lane_id);
+ const MetadataContext metadata_context = {
+ tile.abs_row_base + uint(position.y),
+ short(tile.simdgroup_limit_m - position.y),
+ tile.absolute_column_base() + uint(position.x),
+ short(tile.simdgroup_limit_n - position.x),
+ uint(params->K) / uint(LeftOperand::GROUP_SIZE),
+ uint(params->K) / RIGHT_GROUP_SIZE,
+ params->scale_group_stride,
+ params->zero_point_group_stride,
+ };
+ const uint first_right_group = tile.k_offset / RIGHT_GROUP_SIZE;
- const int k_group_count = int(params->aligned_inner_iterations);
- constexpr int chunks_per_span = int(SPAN) / Core::SIMDGROUP_BLOCK_K;
- constexpr int spans_per_k_group = int(RightOperand::GROUP_SIZE) / int(SPAN);
+ LeftMetadata<Core, ALIGNED_M> left_metadata;
+ RightMetadata<Core, ALIGNED_N> right_metadata;
+ typename Core::AccumFragment accumulator;
+ accumulator.clear();
+ const int right_group_count = int(params->aligned_inner_iterations);
METAL_PRAGMA_NO_UNROLL
- for (int k_group_index = 0; k_group_index < k_group_count; ++k_group_index) {
- if constexpr (STAGE_WEIGHT_SCALES) {
- threadgroup_barrier(mem_flags::mem_threadgroup);
- if (k_group_index + 1 < k_group_count) {
- right_scales.prefetch(uint(k_group_index + 1));
- }
- }
- right_scales.fill(k_group_index);
-
- for (int span_index = 0; span_index < spans_per_k_group; ++span_index) {
- const uint span_offset = uint(k_group_index * int(RightOperand::GROUP_SIZE)) + uint(span_index * int(SPAN));
- left_codes.begin_k_group(span_offset);
- right_codes.begin_k_group(span_offset);
- left_scales.fill_at_k_offset(span_offset);
-
- uzu::matmul::Fragment<int, Core::TILES_M, Core::TILES_N, typename Core::FragmentOps> products;
- products.clear();
- METAL_PRAGMA_NO_UNROLL
- for (int chunk = 0; chunk < chunks_per_span; ++chunk) {
- auto left_tile = left_codes.load(uint(chunk));
- auto right_tile = right_codes.load(uint(chunk));
- uzu::matmul::fragment_mma(products, left_tile, right_tile);
- left_codes.advance();
- right_codes.advance();
- }
-
- Core::AccumFragment::zip_for_each_coord(
- thread_context.simd_lane_id,
- [&](short row, short column, thread float& accumulated, thread int& product) {
- if (!ALIGNED_M && row >= tile.simdgroup_limit_m) {
- return;
- }
- if (!ALIGNED_N && column >= tile.simdgroup_limit_n) {
- return;
- }
- accumulated += left_scales.scale(row) * right_scales.scale(column) * float(product);
- },
- accumulator,
- products
- );
-
- if constexpr (NEEDS_CORRECTION) {
- accumulator.map_coords(thread_context.simd_lane_id, [&](short row, short column, float value) {
- if (!ALIGNED_M && row >= tile.simdgroup_limit_m) {
- return value;
- }
- if (!ALIGNED_N && column >= tile.simdgroup_limit_n) {
- return value;
- }
- return value + right_scales.correction(column) * left_scales.correction(row);
- });
- }
- }
+ for (int right_group_index = 0; right_group_index < right_group_count; ++right_group_index) {
+ const uint absolute_right_group = first_right_group + uint(right_group_index);
+ const uint right_group_offset = uint(right_group_index * int(RIGHT_GROUP_SIZE));
+ left_codes.begin_k_group(right_group_offset);
+ right_codes.begin_k_group(right_group_offset);
+ auto group_product = multiply_group<Core>(left_codes, right_codes);
+ left_metadata.load(left_storage, metadata_context, tile.k_offset + right_group_offset);
+ right_metadata.load(right_storage, metadata_context, absolute_right_group);
+ accumulate_group<Core, ALIGNED_M, ALIGNED_N>(accumulator, group_product, left_metadata, right_metadata);
}
return accumulator;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/staged.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/staged.h
index c1d94022e..2ef2001b0 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/staged.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/common/schedules/staged.h
@@ -28,32 +28,33 @@ static METAL_FUNC auto make_staged_loader(
const thread ThreadContext& thread_context
) {
using Element = typename Core::RightElementType;
- using Format = typename RightOperand::Format;
const uint row_stride =
uint(params->K) * uint(get_bytes_per_pack<RightOperand::BITS>()) / uint(get_pack_factor<RightOperand::BITS>());
- const uint groups_per_row = (uint(params->K) + uint(RightOperand::GROUP_SIZE) - 1) / uint(RightOperand::GROUP_SIZE);
const uint first_group = k_offset / uint(RightOperand::GROUP_SIZE);
+ const int params_offset =
+ int(block_col) * int(params->scale_output_stride) + int(first_group) * int(params->scale_group_stride);
+ const device Element* scales = right.scales + params_offset;
const device uint8_t* values = right.codes + size_t(block_col) * row_stride +
size_t(k_offset) * size_t(get_bytes_per_pack<RightOperand::BITS>()) /
size_t(get_pack_factor<RightOperand::BITS>());
- const device Element* scales = right.scales + block_col * groups_per_row + first_group;
-
if constexpr (RightOperand::SCHEME == GemmBPrologueKind::ScaleBiasDequant) {
+ const device Element* biases = right.bias() + params_offset;
using Loader = QuantizedBlockLoaderScaleBias<
Element,
Core::THREADGROUP_BLOCK_N,
Core::THREADGROUP_BLOCK_K,
Core::SHARED_STRIDE_B,
- 1,
Core::THREADGROUP_THREADS,
RightOperand::GROUP_SIZE,
- Format::BITS>;
+ RightOperand::BITS>;
return Loader(
values,
scales,
- right.bias() + block_col * groups_per_row + first_group,
+ biases,
right.signed_codes,
int(params->K),
+ int(params->scale_group_stride),
+ int(params->scale_output_stride),
staging,
thread_context.simdgroup_index,
thread_context.simd_lane_id
@@ -64,19 +65,21 @@ static METAL_FUNC auto make_staged_loader(
Core::THREADGROUP_BLOCK_N,
Core::THREADGROUP_BLOCK_K,
Core::SHARED_STRIDE_B,
- 1,
Core::THREADGROUP_THREADS,
RightOperand::GROUP_SIZE,
- Format::BITS>;
- const device uint8_t* zero_points = right.zp() + block_col * zero_point_row_stride<Format::BITS>(groups_per_row) +
- ((Format::BITS == 4) ? first_group / 2 : first_group);
+ RightOperand::BITS,
+ false>;
return Loader(
values,
scales,
- zero_points,
+ right.zp(),
right.signed_codes,
int(params->K),
- int(groups_per_row),
+ int(params->scale_group_stride),
+ int(params->scale_output_stride),
+ params->zero_point_output_stride,
+ params->zero_point_group_stride,
+ uint(block_col) * params->zero_point_output_stride + first_group * params->zero_point_group_stride,
staging,
thread_context.simdgroup_index,
thread_context.simd_lane_id
@@ -91,17 +94,17 @@ static METAL_FUNC auto make_staged_loader(
Core::THREADGROUP_BLOCK_N,
Core::THREADGROUP_BLOCK_K,
Core::SHARED_STRIDE_B,
- 1,
Core::THREADGROUP_THREADS,
RightOperand::GROUP_SIZE,
- Format::BITS,
+ RightOperand::BITS,
true>;
return Loader(
values,
scales,
right.signed_codes,
int(params->K),
- int(groups_per_row),
+ int(params->scale_group_stride),
+ int(params->scale_output_stride),
staging,
thread_context.simdgroup_index,
thread_context.simd_lane_id
@@ -137,7 +140,7 @@ static METAL_FUNC auto make_full_precision_loader(
}
struct StagedSchedule {
- template <typename Core, bool ALIGNED_M, bool ALIGNED_N, bool, bool>
+ template <typename Core, bool ALIGNED_M, bool ALIGNED_N>
static METAL_FUNC typename Core::AccumFragment launch(
typename Core::LeftStorage left,
typename Core::RightStorage right,
@@ -148,6 +151,7 @@ struct StagedSchedule {
const thread ThreadContext& thread_context
) {
static_assert(!Core::Left::QUANTIZED && Core::Right::QUANTIZED, "staged schedule requires dense A and quantized W");
+ static_assert(Core::TRANSPOSE_RIGHT, "quantized staged GEMM requires transposed B");
using LeftTile =
uzu::matmul::Fragment<typename Core::LeftElementType, Core::TILES_M, Core::TILES_K, typename Core::FragmentOps>;
using RightTile = uzu::matmul::Fragment<
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal
index ce4dcce5b..91e9d5cd3 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/gemm.metal
@@ -15,13 +15,10 @@ using namespace uzu::gemm;
#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_INTEGER_TGB_ELEMENTS \
- ((B_PROLOGUE == GemmBPrologueKind::ScaleSymmetricDequant) \
- ? (2 * gemm_tiling_block_n(GEMM_TILING)) \
- : (2 * gemm_tiling_block_n(GEMM_TILING) * (1 + 4 / int(sizeof(BT)))))
+// The A8 MXU route reads its scales into registers, so it asks for no
+// threadgroup B memory.
#define GEMM_TGB_ELEMENTS \
- ((USE_MXU) ? (GEMM_MXU_QUANT ? (gemm_tiling_block_n(GEMM_TILING) * (int(GROUP_SIZE) + 16 / int(sizeof(BT)))) \
- : (A_IS_INT8 ? GEMM_INTEGER_TGB_ELEMENTS : 1)) \
+ ((USE_MXU) ? (GEMM_MXU_QUANT ? (gemm_tiling_block_n(GEMM_TILING) * (int(GROUP_SIZE) + 16 / int(sizeof(BT)))) : 1) \
: (gemm_tiling_block_n(GEMM_TILING) * (gemm_tiling_block_k(GEMM_TILING) + 16 / int(sizeof(BT)))))
template <
@@ -107,7 +104,9 @@ CONSTRAINT(
(TRANSPOSE_B && B_PROLOGUE != GemmBPrologueKind::FullPrecision))
CONSTRAINT(A_PROLOGUE == GemmAPrologueKind::FullPrecision || (AT == "bfloat" && DT == "bfloat"))
CONSTRAINT((A_PROLOGUE == GemmAPrologueKind::FullPrecision) == (A_GROUP_SIZE == 0))
-CONSTRAINT(A_PROLOGUE == GemmAPrologueKind::FullPrecision || A_GROUP_SIZE >= 32)
+// The integer schedule drains one weight group at a time, so an activation
+// group narrower than the weight group has no kernel.
+CONSTRAINT(A_PROLOGUE == GemmAPrologueKind::FullPrecision || A_GROUP_SIZE >= GROUP_SIZE)
KERNEL(Gemm)(
const device AT* a OPTIONAL(A_PROLOGUE == GemmAPrologueKind::FullPrecision),
const device BT* b,
@@ -132,8 +131,6 @@ KERNEL(Gemm)(
const GemmDTransform output_transform SPECIALIZE,
const GemmAlignment alignment SPECIALIZE,
const bool signed_codes SPECIALIZE,
- const bool stage_weight_scales SPECIALIZE,
- const bool hoist_operand_addressing SPECIALIZE,
threadgroup AT a_shared[GEMM_TGA_ELEMENTS],
threadgroup BT b_shared[GEMM_TGB_ELEMENTS],
const uint group_x GROUPS(group_count_x),
@@ -151,7 +148,8 @@ KERNEL(Gemm)(
(void)thread_y;
(void)thread_z;
- using LeftOperand = operands::LeftOperandFor<A_PROLOGUE, AT, ushort(A_GROUP_SIZE)>;
+ using LeftOperand = operands::
+ LeftOperandFor<A_PROLOGUE, AT, ushort(A_GROUP_SIZE), A_PROLOGUE == GemmAPrologueKind::Int8Symmetric && BITS == 4>;
using RightOperand = operands::RightOperandFor<B_PROLOGUE, ushort(BITS), ushort(GROUP_SIZE), BT>;
static_assert(
NEEDS_ASYMMETRIC_WEIGHT_CORRECTION == (A_IS_INT8 && RightOperand::NEEDS_CORRECTION),
@@ -160,11 +158,6 @@ KERNEL(Gemm)(
const auto left_storage = operands::pack_left<LeftOperand, AT>(a, a_int8, a_scales, a_group_sums);
const auto right_storage = operands::pack_right<RightOperand, BT>(b, scales, biases, zero_points, signed_codes);
- static_assert(
- !A_IS_INT8 || GEMM_TGB_ELEMENTS >= GEMM_INTEGER_TGB_ELEMENTS,
- "threadgroup scale-line cache is undersized"
- );
-
if constexpr (USE_MXU) {
using Core = MxuMmaCore<DT, GEMM_TILING, TRANSPOSE_B, LeftOperand, RightOperand>;
Core::run(
@@ -177,8 +170,6 @@ KERNEL(Gemm)(
output_bias,
rht_factors,
b_shared,
- stage_weight_scales,
- hoist_operand_addressing,
thread_context
);
} else {
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
index 3b27f7299..63108f7eb 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/kernel.rs
@@ -1,6 +1,7 @@
use std::collections::{HashMap, hash_map::Entry};
use super::{
+ super::supports_integer_right_operand,
GemmEngine, GemmPlan,
selection::{GemmProblem, outer_block_k},
specialization::GemmSpecialization,
@@ -15,7 +16,10 @@ use crate::{
},
kernel::{
ActivationTransform, TensorAddBiasKernel,
- matmul::{MatmulA, MatmulArguments, MatmulB, MatmulError, MatmulShape},
+ matmul::{
+ Int8CodeLayout, MatmulA, MatmulArguments, MatmulB, MatmulError, MatmulShape, QuantParamsLayout,
+ QuantParamsStrides,
+ },
},
},
metal::{
@@ -83,8 +87,6 @@ impl GemmKernel {
specialization.output_transform,
specialization.alignment,
specialization.signed_codes,
- specialization.stage_weight_scales,
- specialization.hoist_operand_addressing,
)?;
Ok(entry.insert(kernel))
},
@@ -171,11 +173,6 @@ impl GemmKernel {
let rht_factors = arguments.d_transform.rht_factors;
let output_transform = arguments.d_transform.mask();
- let b_prologue = arguments.b.b_prologue();
- let bits_per_b = arguments.b.bits_per_b();
- let group_size = arguments.b.group_size();
- let weights_signed_codes = arguments.b.signed_codes();
-
let MatmulArguments {
a,
b,
@@ -190,7 +187,7 @@ impl GemmKernel {
let use_mxu = plan.engine == GemmEngine::Mxu;
- match b {
+ let quantized = match b {
MatmulB::FullPrecision {
b: weights,
} => {
@@ -242,6 +239,8 @@ impl GemmKernel {
None,
&mut *d,
ab_scale,
+ None,
+ None,
shape,
plan,
output_transform,
@@ -268,6 +267,10 @@ impl GemmKernel {
aligned_inner_iterations: k / tiling.block_k(),
use_morton,
ab_scale,
+ scale_output_stride: 0,
+ scale_group_stride: 0,
+ zero_point_output_stride: 0,
+ zero_point_group_stride: 0,
};
let specialization = GemmSpecialization::from_plan(
@@ -298,135 +301,108 @@ impl GemmKernel {
1,
encoder,
);
+ return Ok(());
},
- quant_b @ (MatmulB::ScaleBiasDequant {
- ..
- }
- | MatmulB::ScaleZeroPointDequant {
- ..
- }
- | MatmulB::ScaleSymmetricDequant {
- ..
- }) => {
- let (weights, scales, biases, zero_points) = match quant_b {
- MatmulB::ScaleBiasDequant {
- b: w,
- scales,
- biases,
- ..
- } => (w, Some(scales), Some(biases), None),
- MatmulB::ScaleZeroPointDequant {
- b: w,
- scales,
- zero_points,
- ..
- } => (w, Some(scales), None, Some(zero_points)),
- MatmulB::ScaleSymmetricDequant {
- b: w,
- scales,
- ..
- } => (w, Some(scales), None, None),
- _ => unreachable!(),
- };
-
- let a_prologue = a.prologue_kind();
- let (a_full_precision, a_int8, a_scales, a_group_sums, a_group_size) = match &a {
- MatmulA::FullPrecision {
- values,
- offset,
- } => (Some((*values, *offset)), None, None, None, None),
- MatmulA::Int8Symmetric {
- values,
- scales: activation_scales,
- group_sums: activation_group_sums,
- group_size: a_group_size,
- } => {
- validate_int8_activation_arguments(
- use_mxu,
- weights_signed_codes,
- k,
- b_prologue,
- bits_per_b,
- group_size,
- *a_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), *activation_group_sums, Some(*a_group_size))
- },
- };
-
- 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)
- };
+ MatmulB::Quantized(quantized) => quantized,
+ };
+ let a_prologue = a.prologue_kind();
+ let (a_full_precision, a_int8, a_scales, a_group_sums, a_group_size) = match &a {
+ MatmulA::FullPrecision {
+ values,
+ offset,
+ } => (Some((*values, *offset)), None, None, None, None),
+ MatmulA::Int8Symmetric {
+ values,
+ scales: activation_scales,
+ group_sums: activation_group_sums,
+ scale_group_size,
+ code_layout,
+ } => {
+ validate_int8_left_operand(
+ use_mxu,
+ shape,
+ *scale_group_size,
+ *code_layout,
+ activation_group_sums.is_some(),
+ )?;
+ if output_transform.contains(GemmDTransform::SOFT_CAP) {
+ return Err(MatmulError::UnsupportedDOp {
+ bit: GemmDTransform::SOFT_CAP,
+ path: "Gemm int8 left operand",
+ }
+ .into());
+ }
+ (None, Some(*values), Some(*activation_scales), *activation_group_sums, Some(*scale_group_size))
+ },
+ };
- let tiling = plan.tiling;
- let alignment =
- GemmAlignment::new(m % tiling.block_m() == 0, n % tiling.block_n() == 0, k % tiling.block_k() == 0);
- let params = quant_params(shape, plan, ab_scale);
- let group_count_x = n.div_ceil(tiling.block_n());
- let group_count_y = m.div_ceil(tiling.block_m());
+ 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)
+ };
- if plan.split_k > 1 {
- self.encode_split_k(
- a,
- weights,
- scales,
- biases,
- zero_points,
- &mut *d,
- ab_scale,
- shape,
- plan,
- output_transform,
- output_bias,
- rht_factors,
- encoder,
- )?;
- } else {
- let specialization = GemmSpecialization::from_plan(
- plan,
- shape,
- self.weights_data_type,
- output_transform,
- alignment,
- a_prologue,
- a_group_size,
- )?;
- 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,
- a_group_sums,
- std::slice::from_ref(&params),
- group_count_x,
- group_count_y,
- 1,
- encoder,
- );
- }
+ let tiling = plan.tiling;
+ let alignment =
+ GemmAlignment::new(m % tiling.block_m() == 0, n % tiling.block_n() == 0, k % tiling.block_k() == 0);
+ let scale_strides = quantized.params.scale_strides();
+ let zero_point_strides = quantized.zero_point_strides();
+ let params = gemm_params(shape, plan, ab_scale, scale_strides, zero_point_strides);
+ let group_count_x = n.div_ceil(tiling.block_n());
+ let group_count_y = m.div_ceil(tiling.block_m());
+
+ if plan.split_k > 1 {
+ self.encode_split_k(
+ a,
+ quantized.codes,
+ Some(quantized.scales),
+ quantized.biases(),
+ quantized.zero_points(),
+ &mut *d,
+ ab_scale,
+ Some(scale_strides),
+ Some(zero_point_strides),
+ shape,
+ plan,
+ output_transform,
+ output_bias,
+ rht_factors,
+ encoder,
+ )?;
+ } else {
+ let specialization = GemmSpecialization::from_plan(
+ plan,
+ shape,
+ self.weights_data_type,
+ output_transform,
+ alignment,
+ a_prologue,
+ a_group_size,
+ )?;
+ let kernel = self.get_or_create(encoder.context(), specialization)?;
+ kernel.encode(
+ a_full_precision,
+ quantized.codes,
+ &mut *d,
+ Some(quantized.scales),
+ quantized.biases(),
+ quantized.zero_points(),
+ output_bias,
+ rht_factors,
+ a_int8,
+ a_scales,
+ a_group_sums,
+ std::slice::from_ref(&params),
+ 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, &mut *d, n, output_length, 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, &mut *d, n, output_length, encoder);
}
Ok(())
@@ -442,6 +418,8 @@ impl GemmKernel {
zero_points: Option<&Allocation<Metal>>,
d: &mut Allocation<Metal>,
ab_scale: f32,
+ scale_strides: Option<QuantParamsStrides>,
+ zero_point_strides: Option<QuantParamsStrides>,
shape: MatmulShape,
plan: GemmPlan,
output_transform: GemmDTransform,
@@ -464,8 +442,11 @@ impl GemmKernel {
values,
scales,
group_sums,
- group_size,
- } => (None, Some(values), Some(scales), group_sums, GemmAPrologueKind::Int8Symmetric, Some(group_size)),
+ scale_group_size,
+ code_layout: _,
+ } => {
+ (None, Some(values), Some(scales), group_sums, GemmAPrologueKind::Int8Symmetric, Some(scale_group_size))
+ },
};
let tiling = plan.tiling;
let split_k = plan.split_k;
@@ -488,6 +469,8 @@ impl GemmKernel {
let elem = (m as usize) * (n as usize);
let slice_bytes = elem * self.output_data_type.size_in_bytes();
let mut temp = encoder.allocate_scratch(split_k as usize * slice_bytes)?;
+ let scale_strides = scale_strides.unwrap_or_default();
+ let zero_point_strides = zero_point_strides.unwrap_or_default();
let params = GemmParams {
M: m,
@@ -501,6 +484,10 @@ impl GemmKernel {
aligned_inner_iterations: kp / k_step,
use_morton: false,
ab_scale: 1.0,
+ scale_output_stride: scale_strides.output_stride,
+ scale_group_stride: scale_strides.group_stride,
+ zero_point_output_stride: zero_point_strides.output_stride,
+ zero_point_group_stride: zero_point_strides.group_stride,
};
let part_kernel = self.get_or_create(encoder.context(), part_spec)?;
part_kernel.encode(
@@ -548,41 +535,59 @@ impl GemmKernel {
}
}
-fn validate_int8_activation_arguments(
+fn validate_int8_left_operand(
use_mxu: bool,
- weights_signed_codes: bool,
- k: u32,
- b_prologue: GemmBPrologueKind,
- bits_per_b: Option<u32>,
- weight_group_size: Option<u32>,
+ shape: MatmulShape,
a_group_size: u32,
+ code_layout: Int8CodeLayout,
+ has_group_sums: bool,
) -> Result<(), MetalError> {
+ if shape.b_bits.and_then(Int8CodeLayout::for_right_bits) != Some(code_layout) {
+ return Err(MatmulError::IncompatibleA {
+ path: "Gemm",
+ reason: "left code layout is incompatible with the right operand",
+ }
+ .into());
+ }
+ let needs_group_sums =
+ matches!(shape.b_prologue, GemmBPrologueKind::ScaleBiasDequant | GemmBPrologueKind::ScaleZeroPointDequant);
+ if needs_group_sums && !has_group_sums {
+ return Err(MatmulError::IncompatibleA {
+ path: "Gemm",
+ reason: "quantized correction requires left group sums",
+ }
+ .into());
+ }
let compatible = use_mxu
- && weights_signed_codes
+ && supports_integer_right_operand(&shape)
+ && shape.params_layout == Some(QuantParamsLayout::GroupOutput)
&& matches!(
- b_prologue,
+ shape.b_prologue,
GemmBPrologueKind::ScaleSymmetricDequant
| GemmBPrologueKind::ScaleBiasDequant
| GemmBPrologueKind::ScaleZeroPointDequant
)
- && matches!(bits_per_b, Some(4 | 8))
&& matches!(a_group_size, 32 | 64 | 128)
- && k.is_multiple_of(a_group_size)
- && weight_group_size.is_some_and(|gs| matches!(gs, 32 | 64 | 128) && k.is_multiple_of(gs));
+ && shape.k.is_multiple_of(a_group_size)
+ && shape
+ .b_group_size
+ .is_some_and(|gs| matches!(gs, 32 | 64 | 128) && shape.k.is_multiple_of(gs) && a_group_size >= gs);
if !compatible {
return Err(MatmulError::IncompatibleA {
path: "Gemm",
- reason: "symmetric int8 activations require a supported 32/64/128 activation and weight group",
+ reason: "symmetric int8 left operands require group-major metadata and supported 32/64/128 groups",
}
.into());
}
Ok(())
}
-fn quant_params(
+fn gemm_params(
shape: MatmulShape,
plan: GemmPlan,
ab_scale: f32,
+ scale_strides: QuantParamsStrides,
+ zero_point_strides: QuantParamsStrides,
) -> GemmParams {
let MatmulShape {
m,
@@ -603,5 +608,9 @@ fn quant_params(
aligned_inner_iterations: outer_block_k(shape, plan.engine, plan.tiling).map_or(0, |step| k / step),
use_morton: false,
ab_scale,
+ scale_output_stride: scale_strides.output_stride,
+ scale_group_stride: scale_strides.group_stride,
+ zero_point_output_stride: zero_point_strides.output_stride,
+ zero_point_group_stride: zero_point_strides.group_stride,
}
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rs
index ad6514ac5..edc7f9d90 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemm/specialization.rs
@@ -7,8 +7,6 @@ use crate::{
data_type::DataType,
};
-const STAGE_WEIGHT_SCALE_MIN_GROUPS: u32 = 6;
-
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(super) struct GemmSpecialization {
pub(super) weights_data_type: DataType,
@@ -23,8 +21,6 @@ pub(super) struct GemmSpecialization {
pub(super) b_group_size: Option<u32>,
pub(super) signed_codes: bool,
pub(super) a_group_size: Option<u32>,
- pub(super) stage_weight_scales: bool,
- pub(super) hoist_operand_addressing: bool,
}
impl GemmSpecialization {
@@ -37,7 +33,6 @@ impl GemmSpecialization {
a_prologue: GemmAPrologueKind,
a_group_size: Option<u32>,
) -> Result<Self, GemmSpecializationError> {
- let use_tuned_addressing = shape.is_quant() || plan.split_k > 1;
let specialization = Self {
weights_data_type,
tiling: plan.tiling,
@@ -51,12 +46,6 @@ impl GemmSpecialization {
b_group_size: shape.b_group_size,
signed_codes: shape.signed_codes,
a_group_size,
- stage_weight_scales: if use_tuned_addressing {
- plan.should_stage_weight_scales(shape)
- } else {
- true
- },
- hoist_operand_addressing: use_tuned_addressing && plan.should_hoist_operand_addressing(shape),
};
specialization.validate()?;
Ok(specialization)
@@ -105,30 +94,3 @@ impl GemmSpecialization {
Ok(())
}
}
-
-impl GemmPlan {
- pub(super) fn should_stage_weight_scales(
- self,
- shape: MatmulShape,
- ) -> bool {
- if shape.b_bits == Some(4) && shape.b_group_size == Some(32) && self.tiling.block_m() <= 32 {
- return false;
- }
- if self.tiling == GemmTiling::Tile32x64x256_Simdgroups2x2 {
- return shape
- .b_group_size
- .is_none_or(|group_size| shape.k / self.split_k / group_size >= STAGE_WEIGHT_SCALE_MIN_GROUPS);
- }
- true
- }
-
- pub(super) fn should_hoist_operand_addressing(
- self,
- shape: MatmulShape,
- ) -> bool {
- if matches!(shape.b_prologue, GemmBPrologueKind::ScaleBiasDequant | GemmBPrologueKind::ScaleZeroPointDequant) {
- return true;
- }
- self.tiling != GemmTiling::Tile128x128x256_Simdgroups4x4
- }
-}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/arguments.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/arguments.h
index 739a3697f..fef97899c 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/arguments.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/arguments.h
@@ -26,6 +26,10 @@ struct GemvOperands {
struct GemvParams {
uint in_vec_size;
uint out_vec_size;
+ uint scale_output_stride;
+ uint scale_group_stride;
+ uint zero_point_output_stride;
+ uint zero_point_group_stride;
uint batch_size;
float ab_scale;
float soft_cap;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_b_source.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_b_source.h
index 6df334cdb..220959e8e 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_b_source.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_b_source.h
@@ -48,7 +48,7 @@ struct QuantBSource {
QuantPosition position = {group, 0};
while (position.valid(groups)) {
Metadata metadata;
- metadata.load(position.group, groups, weight_row_indices, ops, params);
+ metadata.load(position.group, weight_row_indices, ops, params);
for (position.slice = 0; position.slice < Slice::SLICES_PER_LANE; position.slice++) {
current.load_weights(position, weights, weight_row_indices, row_stride, group_offset);
current.accumulate(result, position, ops, params, tile, group_offset, batch_remaining, metadata);
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h
index 75e58a995..abae2e1a5 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_chunk.h
@@ -69,10 +69,9 @@ private:
bool signed_codes
) {
constexpr uint CODES_PER_WORD = WORD_BITS / BITS;
- constexpr uint W4_SIGN_BITS = 0x88888888u;
constexpr uint W8_SIGN_BITS = 0x80808080u;
if constexpr (BITS == 4) {
- word0 ^= signed_codes ? W4_SIGN_BITS : 0u;
+ word0 ^= signed_codes ? W4_SIGN_MASK : 0u;
METAL_PRAGMA_UNROLL
for (uint i = 0; i < VALUES; i++) {
values[i] = as_type<float>(extract_bits(word0, BITS * i, BITS) | MANTISSA_BASE_BITS) - origin;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h
index 1ef1039c6..6ae4f69bd 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/common/quant_metadata.h
@@ -22,7 +22,6 @@ public:
METAL_FUNC void load(
uint group_index,
- uint group_count,
const thread uint (&weight_rows)[Tile::ROWS_PER_LANE],
const thread GemvOperands<AT, BT, DT>& ops,
const thread GemvParams& params
@@ -31,12 +30,16 @@ public:
Tile::for_each_output_row([&](auto output_index) UZU_ALWAYS_INLINE {
constexpr uint R = decltype(output_index)::value;
const uint row = weight_rows[R];
- scale[R] = float(ops.scales[row * group_count + group_index]);
+ const uint scale_index = row * params.scale_output_stride + group_index * params.scale_group_stride;
+ scale[R] = float(ops.scales[scale_index]);
if constexpr (B_PROLOGUE == GemmBPrologueKind::ScaleZeroPointDequant) {
constexpr uint ZERO_POINTS_PER_BYTE = QuantChunk<BITS>::BITS_PER_BYTE / BITS;
- const uint byte_index = group_index / ZERO_POINTS_PER_BYTE;
- const uint8_t packed = ops.zero_points[row * zero_point_row_stride<BITS>(group_count) + byte_index];
- origin[R] = QuantChunk<BITS>::MANTISSA_BASE + float(decode_zero_point<BITS>(packed, group_index));
+ const uint zero_point_index =
+ row * params.zero_point_output_stride + group_index * params.zero_point_group_stride;
+ const uint zero_point_row = zero_point_index / ZERO_POINTS_PER_BYTE;
+ const uint packed_index = zero_point_index % ZERO_POINTS_PER_BYTE;
+ origin[R] = QuantChunk<BITS>::MANTISSA_BASE +
+ float(decode_zero_point<BITS>(ops.zero_points + zero_point_row, packed_index));
bias[R] = 0.0f;
} else if constexpr (B_PROLOGUE == GemmBPrologueKind::ScaleSymmetricDequant) {
origin[R] = QuantChunk<BITS>::MANTISSA_BASE + float(symmetric_zero_point<BITS>());
@@ -44,7 +47,7 @@ public:
} else {
static_assert(B_PROLOGUE == GemmBPrologueKind::ScaleBiasDequant);
origin[R] = QuantChunk<BITS>::MANTISSA_BASE;
- bias[R] = float(ops.biases[row * group_count + group_index]);
+ bias[R] = float(ops.biases[scale_index]);
}
});
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metal b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metal
index 940dbd67c..597618e85 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metal
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/gemv.metal
@@ -129,6 +129,10 @@ KERNEL(Gemv)(
const constant uint& batch_size,
const constant float& ab_scale,
const constant uint& group_count_x,
+ const constant uint& scale_output_stride,
+ const constant uint& scale_group_stride,
+ const constant uint& zero_point_output_stride,
+ const constant uint& zero_point_group_stride,
const constant float& soft_cap
OPTIONAL(output_transform.contains(GemmDTransform::SOFT_CAP)),
const GemmDTransform output_transform SPECIALIZE,
@@ -143,8 +147,20 @@ KERNEL(Gemv)(
) {
using Ops = GemvOperands<AT, BT, DT>;
const Ops ops = {b, scales, zero_points, biases, a, d, output_bias, hadamard_factors, gather_indices};
- const GemvParams params =
- {in_vec_size, out_vec_size, batch_size, ab_scale, soft_cap, output_transform, gathered, signed_codes};
+ const GemvParams params = {
+ in_vec_size,
+ out_vec_size,
+ scale_output_stride,
+ scale_group_stride,
+ zero_point_output_stride,
+ zero_point_group_stride,
+ batch_size,
+ ab_scale,
+ soft_cap,
+ output_transform,
+ gathered,
+ signed_codes
+ };
dispatch_bool(full_tile, [&](auto full_tile_constant) {
constexpr bool FullTile = decltype(full_tile_constant)::value;
using Tile = GemvTile<INPUT_ROW_TILE, OUTPUT_ROW_TILE, REDUCTION_LANES, GROUP_LANES, NUM_SIMDGROUPS, K_SPLIT>;
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs
index a78ae14ed..126f0b975 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/gemv/kernel.rs
@@ -8,7 +8,7 @@ use crate::{
HADAMARD_TRANSFORM_BLOCK_SIZE,
gemm::{GemmBPrologueKind, GemmDTransform},
},
- kernel::matmul::MatmulShape,
+ kernel::matmul::{MatmulB, MatmulShape},
},
metal::{context::MetalContext, error::MetalError, kernel::GemvMetalKernel},
},
@@ -187,7 +187,7 @@ use std::collections::{HashMap, hash_map::Entry};
use crate::backends::{
common::{
BufferArg, Encoder,
- kernel::matmul::{MatmulA, MatmulArguments, MatmulB, MatmulError},
+ kernel::matmul::{MatmulA, MatmulArguments, MatmulError},
},
metal::Metal,
};
@@ -262,81 +262,51 @@ impl GemvKernel {
});
};
- // Preserve each weight buffer's residency range.
- let (scales, zero_points, biases) = match &b {
+ let (weights, scales, biases, zero_points, scale_strides, zero_point_strides) = match b {
MatmulB::FullPrecision {
- ..
- } => (None, None, None),
- MatmulB::ScaleBiasDequant {
- scales,
- biases,
- ..
- } => (Some(*scales), None, Some(*biases)),
- MatmulB::ScaleZeroPointDequant {
- scales,
- zero_points,
- ..
- } => (Some(*scales), Some(*zero_points), None),
- MatmulB::ScaleSymmetricDequant {
- scales,
- ..
- } => (Some(*scales), None, None),
+ b: weights,
+ } => {
+ let (buffer, offset, _) = weights.into_parts();
+ ((buffer, offset), None, None, None, Default::default(), Default::default())
+ },
+ MatmulB::Quantized(quantized) => {
+ let (buffer, offset, _) = quantized.codes.into_parts();
+ let zero_points = quantized.zero_points();
+ (
+ (buffer, offset),
+ Some(quantized.scales),
+ quantized.biases(),
+ zero_points,
+ quantized.params.scale_strides(),
+ quantized.zero_point_strides(),
+ )
+ },
};
-
let output_group_count = n.div_ceil(specialization.output_row_tile());
let context = encoder.context();
let pipeline = self.get_or_create(context, specialization)?;
- match b {
- MatmulB::FullPrecision {
- b: weights,
- } => pipeline.encode(
- weights,
- scales,
- zero_points,
- biases,
- (a, a_offset),
- &mut *d,
- output_bias,
- rht_factors,
- gather_indices,
- k,
- n,
- m,
- ab_scale,
- output_group_count,
- soft_cap,
- encoder,
- ),
- MatmulB::ScaleBiasDequant {
- b: weights,
- ..
- }
- | MatmulB::ScaleZeroPointDequant {
- b: weights,
- ..
- }
- | MatmulB::ScaleSymmetricDequant {
- b: weights,
- ..
- } => pipeline.encode(
- weights,
- scales,
- zero_points,
- biases,
- (a, a_offset),
- &mut *d,
- output_bias,
- rht_factors,
- gather_indices,
- k,
- n,
- m,
- ab_scale,
- output_group_count,
- soft_cap,
- encoder,
- ),
- }
+ pipeline.encode(
+ weights,
+ scales,
+ zero_points,
+ biases,
+ (a, a_offset),
+ &mut *d,
+ output_bias,
+ rht_factors,
+ gather_indices,
+ k,
+ n,
+ m,
+ ab_scale,
+ output_group_count,
+ scale_strides.output_stride,
+ scale_strides.group_stride,
+ zero_point_strides.output_stride,
+ zero_point_strides.group_stride,
+ soft_cap,
+ encoder,
+ );
Ok(())
}
diff --git a/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs b/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs
index 14fa5a4c1..ca226de60 100644
--- a/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs
+++ b/crates/uzu-engine/src/backends/metal/kernel/matmul/mod.rs
@@ -16,8 +16,12 @@ use crate::{
BufferArg, Encoder,
gpu_types::gemm::{GemmBPrologueKind, GemmTiling},
kernel::{
+ ActivationQuantization,
activation_transform::ACTIVATION_SCALE_GROUP_SIZE,
- matmul::{A8ActivationPlan, ActivationFormat, MatmulArguments, MatmulError, MatmulKernel, MatmulShape},
+ matmul::{
+ ActivationFormat, Int8CodeLayout, MatmulArguments, MatmulError, MatmulKernel, MatmulShape,
+ QuantParamsLayout,
+ },
},
},
metal::{Metal, context::MetalContext, error::MetalError},
@@ -38,6 +42,10 @@ enum MatmulDispatch {
Gemm(GemmPlan),
}
+fn supports_integer_right_operand(shape: &MatmulShape) -> bool {
+ matches!((shape.b_bits, shape.signed_codes), (Some(4), _) | (Some(8), true))
+}
+
impl MatmulMetalKernel {
fn prefer_gemm_over_gemv(
shape: MatmulShape,
@@ -156,41 +164,36 @@ impl MatmulKernel for MatmulMetalKernel {
})
}
- fn a8_activation_plan(
+ fn select_activation_quantization(
&self,
shape: &MatmulShape,
context: &MetalContext,
- ) -> Option<A8ActivationPlan> {
- let activation_group_size = ACTIVATION_SCALE_GROUP_SIZE;
- let Some(weight_group_size @ (32 | 64 | 128)) = shape.b_group_size else {
- return None;
+ ) -> Option<ActivationQuantization> {
+ let weight_group_size = shape.b_group_size?;
+ let emit_group_sums = match shape.b_prologue {
+ GemmBPrologueKind::ScaleSymmetricDequant => false,
+ GemmBPrologueKind::ScaleBiasDequant | GemmBPrologueKind::ScaleZeroPointDequant => true,
+ GemmBPrologueKind::FullPrecision => return None,
};
+ let code_layout = shape.b_bits.and_then(Int8CodeLayout::for_right_bits)?;
+ let quantization =
+ ActivationQuantization::new(ACTIVATION_SCALE_GROUP_SIZE, weight_group_size, emit_group_sums, code_layout)?;
if !context.supports_mxu
|| self.input_data_type != DataType::BF16
|| self.output_data_type != DataType::BF16
|| shape.a_full_precision
|| !shape.is_quant()
- || !shape.signed_codes
+ || shape.params_layout != Some(QuantParamsLayout::GroupOutput)
+ || !supports_integer_right_operand(shape)
|| !shape.b_transpose
|| shape.b_leading_dimension.is_some()
- || !matches!(shape.b_bits, Some(4 | 8))
- || !shape.k.is_multiple_of(activation_group_size)
+ || !shape.k.is_multiple_of(ACTIVATION_SCALE_GROUP_SIZE)
|| !shape.k.is_multiple_of(weight_group_size)
{
return None;
}
- let sum_group_size = match shape.b_prologue {
- GemmBPrologueKind::ScaleSymmetricDequant => None,
- GemmBPrologueKind::ScaleBiasDequant | GemmBPrologueKind::ScaleZeroPointDequant => {
- Some(weight_group_size.min(activation_group_size))
- },
- GemmBPrologueKind::FullPrecision => return None,
- };
- Some(A8ActivationPlan {
- activation_group_size,
- sum_group_size,
- })
+ Some(quantization)
}
fn select_activation_format(
@@ -198,7 +201,10 @@ impl MatmulKernel for MatmulMetalKernel {
bf16_shape: &MatmulShape,
context: &MetalContext,
) -> ActivationFormat {
- if matches!(self.select_dispatch(bf16_shape, context), MatmulDispatch::Gemv(_)) {
+ if bf16_shape.params_layout != Some(QuantParamsLayout::GroupOutput)
+ || !supports_integer_right_operand(bf16_shape)
+ || matches!(self.select_dispatch(bf16_shape, context), MatmulDispatch::Gemv(_))
+ {
return ActivationFormat::Bf16;
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
index 10d0111d0..c6ddb820a 100644
--- a/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/input_rht.rs
@@ -25,13 +25,11 @@ impl<B: Backend> InputRht<B> {
) -> Result<Self, B::Error> {
let LinearInputPreparation {
rht_signs,
- a8_plan,
+ activation_quantization,
} = preparation;
let rht = ActivationTransform::input_rht(context, data_type, in_place)?;
- let quantizer = a8_plan
- .map(|plan| {
- ActivationTransform::quantize(context, data_type, plan.activation_group_size, plan.sum_group_size)
- })
+ let quantizer = activation_quantization
+ .map(|quantization| ActivationTransform::quantize(context, data_type, quantization))
.transpose()?;
Ok(Self {
@@ -52,7 +50,7 @@ impl<B: Backend> InputRht<B> {
&& let Some(quantizer) = &self.quantizer
{
let input_dim = self.input_dim();
- let groups_per_row = input_dim.div_ceil(quantizer.activation_group_size());
+ let groups_per_row = input_dim.div_ceil(quantizer.scale_group_size());
let mut values = encoder.allocate_scratch(size_for_shape(&[batch_dim, input_dim], DataType::I8))?;
let mut scales = encoder.allocate_scratch(size_for_shape(&[batch_dim, groups_per_row], DataType::F32))?;
let mut group_sums = quantizer
@@ -77,7 +75,8 @@ impl<B: Backend> InputRht<B> {
values,
scales,
group_sums,
- group_size: quantizer.activation_group_size(),
+ scale_group_size: quantizer.scale_group_size(),
+ code_layout: quantizer.code_layout(),
});
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/matmul.rs b/crates/uzu-engine/src/encodable_block/linear/matmul.rs
index edf45acbc..59d1a8683 100644
--- a/crates/uzu-engine/src/encodable_block/linear/matmul.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/matmul.rs
@@ -6,11 +6,8 @@ use crate::{
backends::common::{
Allocation, Backend, Encoder,
kernel::{
- Kernels,
- matmul::{
- A8ActivationPlan, ActivationFormat, MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel,
- MatmulShape,
- },
+ ActivationQuantization, Kernels,
+ matmul::{ActivationFormat, MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, MatmulShape},
},
},
config::weight_matrix::{AnyWeightMatrixSpec, Layout},
@@ -111,12 +108,11 @@ impl<B: Backend> LinearMatmul<B> {
pub(super) fn prepare_a8(
&mut self,
context: &B::Context,
- ) -> Option<A8ActivationPlan> {
+ ) -> Option<ActivationQuantization> {
let mut candidate = self.matmul_shape(1, false);
- candidate.signed_codes = true;
- let plan = self.kernel.lock().a8_activation_plan(&candidate, context)?;
- self.matrix.make_codes_signed();
- Some(plan)
+ candidate.signed_codes = self.matrix.a8_signed_codes()?;
+ let quantization = self.kernel.lock().select_activation_quantization(&candidate, context)?;
+ self.matrix.try_prepare_a8_storage().then_some(quantization)
}
pub(super) fn encode_with_a(
@@ -166,6 +162,7 @@ impl<B: Backend> LinearMatmul<B> {
signed_codes: b.signed_codes(),
a_full_precision,
gathered: false,
+ params_layout: b.quant_params_layout(),
d_transform: self.d_ops().mask(),
}
}
@@ -221,9 +218,6 @@ impl<B: Backend> Linear<B> for LinearMatmul<B> {
batch_dim: u32,
context: &B::Context,
) -> ActivationFormat {
- if !self.matmul_b().signed_codes() {
- return ActivationFormat::Bf16;
- }
let bf16_shape = self.matmul_shape(batch_dim, true);
self.kernel.lock().select_activation_format(&bf16_shape, context)
}
diff --git a/crates/uzu-engine/src/encodable_block/linear/mod.rs b/crates/uzu-engine/src/encodable_block/linear/mod.rs
index dd156c573..ef0a8dcb7 100644
--- a/crates/uzu-engine/src/encodable_block/linear/mod.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/mod.rs
@@ -15,7 +15,10 @@ use crate::{
backends::common::{
Allocation, Backend, Encoder,
gpu_types::HADAMARD_TRANSFORM_BLOCK_SIZE,
- kernel::matmul::{A8ActivationPlan, ActivationFormat, MatmulA},
+ kernel::{
+ ActivationQuantization,
+ matmul::{ActivationFormat, Int8CodeLayout, MatmulA},
+ },
},
config::weight_matrix::{
AnyWeightMatrixSpec,
@@ -64,7 +67,8 @@ pub enum LinearInput<B: Backend> {
values: Allocation<B>,
scales: Allocation<B>,
group_sums: Option<Allocation<B>>,
- group_size: u32,
+ scale_group_size: u32,
+ code_layout: Int8CodeLayout,
},
}
@@ -84,12 +88,14 @@ impl<B: Backend> LinearInput<B> {
values,
scales,
group_sums,
- group_size,
+ scale_group_size,
+ code_layout,
} => MatmulA::Int8Symmetric {
values,
scales,
group_sums: group_sums.as_ref(),
- group_size: *group_size,
+ scale_group_size: *scale_group_size,
+ code_layout: *code_layout,
},
}
}
@@ -97,7 +103,7 @@ impl<B: Backend> LinearInput<B> {
pub struct LinearInputPreparation<B: Backend> {
pub rht_signs: Allocation<B>,
- pub a8_plan: Option<A8ActivationPlan>,
+ pub activation_quantization: Option<ActivationQuantization>,
}
#[derive(Debug, Error)]
diff --git a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
index df4ecb35d..54e9d6c2a 100644
--- a/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/rht_wrapper.rs
@@ -69,13 +69,13 @@ impl<B: Backend> RHTLinearWrapper<B> {
weights_data_type,
parameter_tree,
)?;
- let a8_plan = inner_linear.prepare_a8(context);
+ let activation_quantization = inner_linear.prepare_a8(context);
Self::build_self_contained(
context,
input_data_type,
LinearInputPreparation {
rht_signs,
- a8_plan,
+ activation_quantization,
},
inner_linear,
)
@@ -110,9 +110,9 @@ impl<B: Backend> RHTLinearWrapper<B> {
)?;
let input_preparation = LinearInputPreparation {
rht_signs,
- a8_plan: inner_linear.prepare_a8(context),
+ activation_quantization: inner_linear.prepare_a8(context),
};
- if input_preparation.a8_plan.is_some() && !allow_prequantized_activation {
+ if input_preparation.activation_quantization.is_some() && !allow_prequantized_activation {
let wrapper = Self::build_self_contained(context, input_data_type, input_preparation, inner_linear)?;
Ok(Some((Box::new(wrapper), None)))
} else {
diff --git a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
index 62e43b481..04400eeb2 100644
--- a/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
+++ b/crates/uzu-engine/src/encodable_block/linear/untied_readout.rs
@@ -64,7 +64,7 @@ impl<B: Backend> UntiedReadout<B> {
.read_allocation()?;
let preparation = LinearInputPreparation {
rht_signs,
- a8_plan: linear.prepare_a8(context),
+ activation_quantization: linear.prepare_a8(context),
};
let input_rht = InputRht::new(context, data_type, preparation, /* in_place */ false)
.map_err(LinearMatmulError::BackendError)?;
diff --git a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
index caee9d37c..a65853970 100644
--- a/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
+++ b/crates/uzu-engine/src/encodable_block/mlp/gate_act_mul.rs
@@ -3,10 +3,7 @@ use crate::{
backends::common::{
Allocation, Backend, Encoder,
gpu_types::ActivationType,
- kernel::{
- GatedActMul, GatedActMulSettings,
- matmul::{A8ActivationPlan, ActivationFormat},
- },
+ kernel::{ActivationQuantization, GatedActMul, GatedActMulSettings, matmul::ActivationFormat},
},
config::{activation::AnyActivation, clipping::ClippingBounds},
data_type::DataType,
@@ -19,7 +16,7 @@ pub struct MlpGateActMulEncodable<B: Backend> {
hidden_dim: u32,
data_type: DataType,
hadamard_factors: Option<Allocation<B>>,
- a8_plan: Option<A8ActivationPlan>,
+ activation_quantization: Option<ActivationQuantization>,
quantized_kernel: Option<GatedActMul<B>>,
}
@@ -33,18 +30,16 @@ impl<B: Backend> MlpGateActMulEncodable<B> {
hidden_dim: u32,
input_preparation: Option<LinearInputPreparation<B>>,
) -> Result<Self, B::Error> {
- let (hadamard_factors, a8_plan) =
- input_preparation.map_or((None, None), |preparation| (Some(preparation.rht_signs), preparation.a8_plan));
+ let (hadamard_factors, activation_quantization) = input_preparation
+ .map_or((None, None), |preparation| (Some(preparation.rht_signs), preparation.activation_quantization));
let settings = GatedActMulSettings {
activation_alpha: activation.custom_alpha(),
gate_clipping,
value_clipping,
};
let fp_kernel = GatedActMul::full_precision(context, data_type, true, hadamard_factors.is_some(), settings)?;
- let quantized_kernel = a8_plan
- .map(|plan| {
- GatedActMul::quantized(context, data_type, plan.activation_group_size, plan.sum_group_size, settings)
- })
+ let quantized_kernel = activation_quantization
+ .map(|quantization| GatedActMul::quantized(context, data_type, quantization, settings))
.transpose()?;
Ok(Self {
fp_kernel,
@@ -52,7 +47,7 @@ impl<B: Backend> MlpGateActMulEncodable<B> {
hidden_dim,
data_type,
hadamard_factors,
- a8_plan,
+ activation_quantization,
quantized_kernel,
})
}
@@ -70,16 +65,16 @@ impl<B: Backend> MlpGateActMulEncodable<B> {
panic!("Identity activation is not supported for kernel")
}
let input = if act_format == ActivationFormat::Int8
- && let Some(plan) = self.a8_plan
+ && let Some(quantization) = self.activation_quantization
{
let kernel = self.quantized_kernel.as_ref().expect("INT8 input requires a quantized gate kernel");
let mut values = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.hidden_dim], DataType::I8))?;
let mut scales = encoder.allocate_scratch(size_for_shape(
- &[batch_dim, self.hidden_dim.div_ceil(plan.activation_group_size)],
+ &[batch_dim, self.hidden_dim.div_ceil(quantization.scale_group_size())],
DataType::F32,
))?;
- let mut group_sums = plan
- .sum_group_size
+ let mut group_sums = quantization
+ .sum_group_size()
.map(|group_size| {
encoder.allocate_scratch(size_for_shape(
&[batch_dim, self.hidden_dim.div_ceil(group_size)],
@@ -102,7 +97,8 @@ impl<B: Backend> MlpGateActMulEncodable<B> {
values,
scales,
group_sums,
- group_size: plan.activation_group_size,
+ scale_group_size: quantization.scale_group_size(),
+ code_layout: quantization.code_layout(),
}
} else {
let mut hidden = encoder.allocate_scratch(size_for_shape(&[batch_dim, self.hidden_dim], self.data_type))?;
diff --git a/crates/uzu-engine/src/encodable_block/weight_matrix.rs b/crates/uzu-engine/src/encodable_block/weight_matrix.rs
index 06c435434..90b3e084c 100644
--- a/crates/uzu-engine/src/encodable_block/weight_matrix.rs
+++ b/crates/uzu-engine/src/encodable_block/weight_matrix.rs
@@ -4,7 +4,7 @@ use crate::{
backends::common::{
Allocation, Backend,
gpu_types::{QuantizationMethod, QuantizationMode},
- kernel::matmul::MatmulB,
+ kernel::matmul::{MatmulB, QuantParams, QuantParamsLayout, QuantizedB, QuantizedCorrection},
},
config::weight_matrix::{AnyWeightMatrixSpec, Layout},
data_type::DataType,
@@ -79,15 +79,10 @@ pub fn parse_spec<B: Backend>(spec: &AnyWeightMatrixSpec) -> Result<ParsedWeight
})
}
-enum QuantizedCorrection<B: Backend> {
- Symmetric,
- Biases(Allocation<B>),
- ZeroPoints(Allocation<B>),
-}
-
struct Quantized<B: Backend> {
scales: Allocation<B>,
- correction: QuantizedCorrection<B>,
+ correction: QuantizedCorrection<Allocation<B>>,
+ params: QuantParams,
info: QuantizationInfo,
signed_codes: bool,
}
@@ -108,22 +103,27 @@ impl<B: Backend> WeightMatrix<B> {
) -> Result<Self, WeightMatrixError<B>> {
let ParsedWeightSpec {
layout,
- quantization,
+ quantization: quantization_info,
} = parse_spec(&spec)?;
if layout != required_layout {
return Err(WeightMatrixError::UnsupportedConfiguration(format!(
- "expected {required_layout:?} layout, got {layout:?}"
+ "expected {required_layout:?} weight layout, got {layout:?}"
)));
}
let (rows, columns) = physical_shape(&layout, output_dim, input_dim);
- let Some(info) = quantization else {
+ let Some(info) = quantization_info else {
let values = tree.leaf("weights")?.validate(&[rows, columns], data_type)?.read_allocation()?;
return Ok(Self {
values,
quantized: None,
});
};
+ // Parameters swap the weight axes once K is grouped: output-input stores [G, N], input-output stores [N, G].
+ let params_layout = match layout {
+ Layout::OutputInput => QuantParamsLayout::GroupOutput,
+ Layout::InputOutput => QuantParamsLayout::OutputGroup,
+ };
let group_size = info.group_size;
let packing_divisor = info.mode.packing_divisor();
@@ -137,16 +137,21 @@ impl<B: Backend> WeightMatrix<B> {
let values =
tree.leaf("weights")?.validate(&[rows, columns / packing_divisor], storage_data_type)?.read_allocation()?;
- let scales = tree.leaf("scales")?.validate(&[rows, groups], data_type)?.read_allocation()?;
+ let params = QuantParams::new(params_layout, rows, groups);
+ let load_plane =
+ |name: &str, shape: [u32; 2], storage_type: DataType| -> Result<Allocation<B>, WeightMatrixError<B>> {
+ Ok(tree.leaf(name)?.validate(&shape, storage_type)?.read_allocation()?)
+ };
+ let scales = load_plane("scales", params.scale_shape(), data_type)?;
let correction = match info.method {
- QuantizationMethod::ScaleBias => QuantizedCorrection::Biases(
- tree.leaf("biases")?.validate(&[rows, groups], data_type)?.read_allocation()?,
- ),
- QuantizationMethod::ScaleZeroPoint => QuantizedCorrection::ZeroPoints(
- tree.leaf("zero_points")?
- .validate(&[rows, groups.div_ceil(packing_divisor)], storage_data_type)?
- .read_allocation()?,
- ),
+ QuantizationMethod::ScaleBias => {
+ QuantizedCorrection::Biases(load_plane("biases", params.scale_shape(), data_type)?)
+ },
+ QuantizationMethod::ScaleZeroPoint => QuantizedCorrection::ZeroPoints(load_plane(
+ "zero_points",
+ params.zero_point_shape(info.mode),
+ info.mode.storage_type(),
+ )?),
QuantizationMethod::ScaleSymmetric => QuantizedCorrection::Symmetric,
};
@@ -155,6 +160,7 @@ impl<B: Backend> WeightMatrix<B> {
quantized: Some(Quantized {
scales,
correction,
+ params,
info,
signed_codes: false,
}),
@@ -174,17 +180,11 @@ impl<B: Backend> WeightMatrix<B> {
}
pub fn zero_points(&self) -> Option<&Allocation<B>> {
- match &self.quantized.as_ref()?.correction {
- QuantizedCorrection::ZeroPoints(zero_points) => Some(zero_points),
- QuantizedCorrection::Biases(_) | QuantizedCorrection::Symmetric => None,
- }
+ self.quantized.as_ref()?.correction.zero_points()
}
pub fn biases(&self) -> Option<&Allocation<B>> {
- match &self.quantized.as_ref()?.correction {
- QuantizedCorrection::Biases(biases) => Some(biases),
- QuantizedCorrection::ZeroPoints(_) | QuantizedCorrection::Symmetric => None,
- }
+ self.quantized.as_ref()?.correction.biases()
}
pub fn matmul_b(&self) -> MatmulB<'_, B> {
@@ -196,48 +196,49 @@ impl<B: Backend> WeightMatrix<B> {
let mode = quantized.info.mode;
let group_size = quantized.info.group_size;
let signed_codes = quantized.signed_codes;
- match &quantized.correction {
- QuantizedCorrection::Biases(biases) => MatmulB::ScaleBiasDequant {
- b: &self.values,
- scales: &quantized.scales,
- biases,
- mode,
- group_size,
- signed_codes,
- },
- QuantizedCorrection::ZeroPoints(zero_points) => MatmulB::ScaleZeroPointDequant {
- b: &self.values,
- scales: &quantized.scales,
- zero_points,
- mode,
- group_size,
- signed_codes,
- },
- QuantizedCorrection::Symmetric => MatmulB::ScaleSymmetricDequant {
- b: &self.values,
- scales: &quantized.scales,
- mode,
- group_size,
- signed_codes,
- },
- }
+ MatmulB::Quantized(QuantizedB {
+ codes: &self.values,
+ scales: &quantized.scales,
+ correction: quantized.correction.as_ref(),
+ params: quantized.params,
+ mode,
+ group_size,
+ signed_codes,
+ })
}
- pub fn make_codes_signed(&mut self) {
+ pub fn try_prepare_a8_storage(&mut self) -> bool {
let Some(quantized) = self.quantized.as_mut() else {
- return;
+ return false;
};
- if quantized.signed_codes {
- return;
+ quantized.prepare_a8_storage(&mut self.values)
+ }
+
+ pub fn a8_signed_codes(&self) -> Option<bool> {
+ self.quantized.as_ref().map(|quantized| quantized.info.mode != QuantizationMode::U4)
+ }
+}
+
+impl<B: Backend> Quantized<B> {
+ fn prepare_a8_storage(
+ &mut self,
+ values: &mut Allocation<B>,
+ ) -> bool {
+ if self.params.layout() != QuantParamsLayout::GroupOutput {
+ return false;
}
- let Some(sign_flip_mask) = quantized.info.mode.weight_codes_sign_flip_mask() else {
- return;
- };
- let broadcast_mask = u64::from(sign_flip_mask) * 0x0101_0101_0101_0101;
- let (prefix, words, suffix) = bytemuck::pod_align_to_mut::<u8, u64>(self.values.as_slice_mut());
- words.iter_mut().for_each(|word| *word ^= broadcast_mask);
- prefix.iter_mut().chain(suffix.iter_mut()).for_each(|code| *code ^= sign_flip_mask);
- quantized.signed_codes = true;
+ if self.info.mode != QuantizationMode::U4 {
+ if !self.signed_codes
+ && let Some(sign_flip_mask) = self.info.mode.weight_codes_sign_flip_mask()
+ {
+ let broadcast_mask = u64::from(sign_flip_mask) * 0x0101_0101_0101_0101;
+ let (prefix, words, suffix) = bytemuck::pod_align_to_mut::<u8, u64>(values.as_slice_mut());
+ words.iter_mut().for_each(|word| *word ^= broadcast_mask);
+ prefix.iter_mut().chain(suffix.iter_mut()).for_each(|code| *code ^= sign_flip_mask);
+ }
+ self.signed_codes = true;
+ }
+ true
}
}
diff --git a/crates/uzu-engine/src/utils/version.rs b/crates/uzu-engine/src/utils/version.rs
index 695aeaea5..77aa47d6a 100644
--- a/crates/uzu-engine/src/utils/version.rs
+++ b/crates/uzu-engine/src/utils/version.rs
@@ -1,2 +1,2 @@
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
-pub const TOOLCHAIN_VERSION: &str = "0.16.1";
+pub const TOOLCHAIN_VERSION: &str = "0.17.0";
diff --git a/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs b/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs
index 1a98329ec..3ed476f2d 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/activation_transform_test.rs
@@ -113,7 +113,10 @@ mod quantize {
use super::BLOCK_SIZE;
use crate::{
backends::{
- common::{Backend, Context, Encoder, kernel::ActivationTransform},
+ common::{
+ Backend, Context, Encoder,
+ kernel::{ActivationQuantization, ActivationTransform, matmul::Int8CodeLayout},
+ },
cpu::Cpu,
},
data_type::DataType,
@@ -125,11 +128,12 @@ mod quantize {
factors_data: &[i32],
rows: u32,
columns: u32,
- activation_group_size: u32,
+ scale_group_size: u32,
emit_group_sums: bool,
sum_group_size: Option<u32>,
+ code_layout: Int8CodeLayout,
) -> (Vec<i8>, Vec<f32>, Option<Vec<i32>>) {
- let scale_groups = columns / activation_group_size;
+ let scale_groups = columns / scale_group_size;
let sum_groups = sum_group_size.map_or(0, |group_size| columns / group_size);
let context = B::Context::new().expect("context");
let input = alloc_allocation_with_data::<B, f32>(context.as_ref(), input_data);
@@ -138,9 +142,18 @@ mod quantize {
let mut scales = alloc_allocation::<B, f32>(context.as_ref(), (rows * scale_groups) as usize);
let mut group_sums =
emit_group_sums.then(|| alloc_allocation::<B, i32>(context.as_ref(), (rows * sum_groups) as usize));
- let kernel =
- ActivationTransform::quantize(context.as_ref(), DataType::F32, activation_group_size, sum_group_size)
- .expect("quantize transform");
+ let kernel = ActivationTransform::quantize(
+ context.as_ref(),
+ DataType::F32,
+ ActivationQuantization::new(
+ scale_group_size,
+ sum_group_size.unwrap_or(scale_group_size),
+ emit_group_sums,
+ code_layout,
+ )
+ .expect("supported activation quantization"),
+ )
+ .expect("quantize transform");
let mut encoder = Encoder::<B>::new(context.as_ref()).expect("encoder");
kernel.encode_quantize(
&input,
@@ -158,9 +171,10 @@ mod quantize {
}
fn check_quantize(
- activation_group_size: u32,
+ scale_group_size: u32,
emit_group_sums: bool,
sum_group_size: Option<u32>,
+ code_layout: Int8CodeLayout,
) {
let rows = 3;
let columns = 256;
@@ -180,9 +194,10 @@ mod quantize {
&factors_data,
rows,
columns,
- activation_group_size,
+ scale_group_size,
emit_group_sums,
sum_group_size,
+ code_layout,
);
for_each_backend!(|B| {
@@ -191,9 +206,10 @@ mod quantize {
&factors_data,
rows,
columns,
- activation_group_size,
+ scale_group_size,
emit_group_sums,
sum_group_size,
+ code_layout,
);
for (index, (&actual, &expected)) in actual_scales.iter().zip(&expected_scales).enumerate() {
@@ -227,22 +243,23 @@ mod quantize {
#[uzu_test]
fn quantize_with_group_sums_matches_cpu() {
- check_quantize(128, true, Some(BLOCK_SIZE));
+ check_quantize(128, true, Some(BLOCK_SIZE), Int8CodeLayout::Sequential);
}
#[uzu_test]
fn quantize_without_group_sums_matches_cpu() {
- check_quantize(128, false, None);
+ check_quantize(128, false, None, Int8CodeLayout::Sequential);
}
#[uzu_test]
fn quantize_compact_scale_g128_sum_g64_matches_cpu() {
- check_quantize(128, true, Some(64));
+ check_quantize(128, true, Some(64), Int8CodeLayout::Sequential);
}
#[uzu_test]
fn quantize_scale_g32_and_g64_match_cpu() {
- check_quantize(32, false, None);
- check_quantize(64, false, None);
+ check_quantize(32, false, None, Int8CodeLayout::Sequential);
+ check_quantize(64, false, None, Int8CodeLayout::Sequential);
+ check_quantize(128, false, None, Int8CodeLayout::GroupedByNibble);
}
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs b/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs
index 3f67aa1bf..51ba335e1 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/gated_act_mul_test.rs
@@ -10,7 +10,7 @@ use crate::{
common::{
Allocation, Backend, Context, Encoder,
gpu_types::ActivationType,
- kernel::{GatedActMul, GatedActMulSettings},
+ kernel::{ActivationQuantization, GatedActMul, GatedActMulSettings, matmul::Int8CodeLayout},
},
cpu::Cpu,
},
@@ -33,7 +33,7 @@ struct InterleavedInput<T: ArrayElement + Float> {
}
fn interleaved_input<T: ArrayElement + Float>(act_type: ActivationType) -> InterleavedInput<T> {
- let gated_dim = 64u32;
+ let gated_dim = 128u32;
let batch_dim = 4u32;
let fused_length = (batch_dim * 2 * gated_dim) as usize;
let mut fused_up: Vec<T> = vec![T::zero(); fused_length];
@@ -118,6 +118,45 @@ fn test_gated_act_mul_interleaved_silu_bf16() {
interleaved_test::<bf16>(ActivationType::SILU);
}
+fn run_nibble_grouped_quantized<B: Backend>(input: &InterleavedInput<bf16>) -> Vec<i8> {
+ let context = B::Context::new().expect("create context");
+ let act_operand = alloc_allocation_with_data::<B, bf16>(&context, &input.fused_up);
+ let factors = alloc_allocation_with_data::<B, i32>(&context, &input.hadamard_factors);
+ let mut values = alloc_allocation::<B, i8>(&context, (input.batch_dim * input.gated_dim) as usize);
+ let mut scales = alloc_allocation::<B, f32>(&context, (input.batch_dim * input.gated_dim / 128) as usize);
+ let kernel = GatedActMul::<B>::quantized(
+ &context,
+ DataType::BF16,
+ ActivationQuantization::new(128, 128, false, Int8CodeLayout::GroupedByNibble)
+ .expect("supported activation quantization"),
+ GatedActMulSettings::default(),
+ )
+ .expect("create quantized GatedActMul");
+ let mut encoder = Encoder::<B>::new(&context).expect("create encoder");
+ kernel.encode_quantized(
+ &act_operand,
+ &mut values,
+ &mut scales,
+ None,
+ &factors,
+ input.gated_dim,
+ input.batch_dim,
+ input.act_type,
+ &mut encoder,
+ );
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+ allocation_to_vec(&values)
+}
+
+#[uzu_test]
+fn test_gated_act_mul_nibble_grouped_quantization_matches_cpu() {
+ let input = interleaved_input::<bf16>(ActivationType::SILU);
+ let expected_values = run_nibble_grouped_quantized::<Cpu>(&input);
+ for_each_non_cpu_backend!(|B| {
+ assert_eq!(run_nibble_grouped_quantized::<B>(&input), expected_values, "gated activation bytes differ");
+ });
+}
+
#[uzu_test]
fn test_gated_act_mul_interleaved_gelu_f32() {
interleaved_test::<f32>(ActivationType::GELUApprox);
diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs
index 21131ac60..99caf1b13 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/a8w_bench.rs
@@ -12,9 +12,12 @@ use crate::{
Allocation, Backend, Encoder,
gpu_types::{HADAMARD_TRANSFORM_BLOCK_SIZE, QuantizationMethod, QuantizationMode},
kernel::{
- ActivationTransform, Kernels,
+ ActivationQuantization, ActivationTransform, Kernels,
activation_transform::ACTIVATION_SCALE_GROUP_SIZE,
- matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
+ matmul::{
+ Int8CodeLayout, MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, QuantParams,
+ QuantParamsLayout, QuantizedB, QuantizedCorrection,
+ },
},
},
metal::{GemmEngine, Metal, MetalContext},
@@ -22,7 +25,7 @@ use crate::{
data_type::DataType,
tests::{
helpers::{alloc_allocation, alloc_allocation_with_data},
- matmul::{QuantInput, iter_encode_loop_named, qwen3_layer_shapes},
+ matmul::{QuantInput, iter_encode_loop_named, qwen3_layer_shapes, transpose_metadata},
util::{shared_metal_context, type_short_name},
},
};
@@ -48,8 +51,10 @@ impl BenchPath {
struct BenchmarkData {
unsigned_weights: Allocation<Metal>,
- signed_weights: Allocation<Metal>,
+ a8_weights: Allocation<Metal>,
weight_scales: Allocation<Metal>,
+ /// The `[G, N]` scale plane the A8 MXU route reads.
+ group_major_weight_scales: Allocation<Metal>,
activations: Allocation<Metal>,
rht_factors: Allocation<Metal>,
a_working: Allocation<Metal>,
@@ -72,12 +77,15 @@ impl BenchmarkData {
group_size: u32,
seed: u64,
) -> Self {
- let input = QuantInput::<bf16>::new(m, k, n, group_size, bits, QuantizationMethod::ScaleSymmetric, seed)
- .with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE, None);
+ let input = QuantInput::<bf16>::new(m, k, n, group_size, bits, QuantizationMethod::ScaleSymmetric, seed);
+ let input = input.with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE, None);
let unsigned_weights = alloc_allocation_with_data::<Metal, u32>(context, &input.w_packed);
- let signed_weights = alloc_allocation_with_data::<Metal, u32>(context, &input.weights_for_upload());
+ let a8_weights = input.weights_for_upload();
+ let a8_weights = alloc_allocation_with_data::<Metal, u32>(context, &a8_weights);
let weight_scales = alloc_allocation_with_data::<Metal, bf16>(context, &input.scales);
+ let mut group_major_weight_scales = alloc_allocation_with_data::<Metal, bf16>(context, &input.scales);
+ transpose_metadata(group_major_weight_scales.as_slice_mut(), n, k.div_ceil(group_size), 16);
let activations = alloc_allocation_with_data::<Metal, bf16>(context, &input.x);
let rht: Vec<i32> = (0..k)
.map(|index| {
@@ -93,8 +101,9 @@ impl BenchmarkData {
let groups = k / group_size;
Self {
unsigned_weights,
- signed_weights,
+ a8_weights,
weight_scales,
+ group_major_weight_scales,
activations,
rht_factors,
a_working: alloc_allocation::<Metal, bf16>(context, (m * k) as usize),
@@ -121,13 +130,15 @@ impl BenchmarkData {
values: &self.a_working,
offset: 0,
},
- b: MatmulB::ScaleSymmetricDequant {
- b: &self.unsigned_weights,
+ b: MatmulB::Quantized(QuantizedB {
+ codes: &self.unsigned_weights,
scales: &self.weight_scales,
+ correction: QuantizedCorrection::Symmetric,
+ params: QuantParams::new(QuantParamsLayout::OutputGroup, self.n, self.k.div_ceil(self.group_size)),
mode: self.mode,
group_size: self.group_size,
signed_codes: false,
- },
+ }),
b_leading_dimension: None,
b_transpose: true,
d: output,
@@ -167,15 +178,19 @@ fn encode_step(
values: &data.a_int8,
scales: &data.a_scales,
group_sums: None,
- group_size: 128,
+ scale_group_size: 128,
+ code_layout: Int8CodeLayout::for_right_bits(DataType::from(data.mode).size_in_bits() as u32)
+ .expect("W4/W8 benchmark"),
},
- b: MatmulB::ScaleSymmetricDequant {
- b: &data.signed_weights,
- scales: &data.weight_scales,
+ b: MatmulB::Quantized(QuantizedB {
+ codes: &data.a8_weights,
+ scales: &data.group_major_weight_scales,
+ correction: QuantizedCorrection::Symmetric,
+ params: QuantParams::new(QuantParamsLayout::GroupOutput, data.n, data.k.div_ceil(data.group_size)),
mode: data.mode,
group_size: data.group_size,
- signed_codes: true,
- },
+ signed_codes: !matches!(data.mode, QuantizationMode::U4),
+ }),
b_leading_dimension: None,
b_transpose: true,
d: output,
@@ -252,10 +267,21 @@ fn bench_a8w(c: &mut Criterion) {
if !context.supports_mxu {
return;
}
- let prepare = ActivationTransform::<Metal>::quantize(&context, DataType::BF16, 128, None).expect("prepare kernel");
let hadamard = ActivationTransform::<Metal>::input_rht(&context, DataType::BF16, true).expect("hadamard kernel");
for bits in [8u32, 4u32] {
+ let prepare = ActivationTransform::<Metal>::quantize(
+ &context,
+ DataType::BF16,
+ ActivationQuantization::new(
+ 128,
+ 128,
+ false,
+ Int8CodeLayout::for_right_bits(bits).expect("W4/W8 benchmark"),
+ )
+ .expect("supported activation quantization"),
+ )
+ .expect("prepare kernel");
bench_bits(c, &context, &prepare, &hadamard, bits);
}
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs
index 82a918d9c..3f6154796 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/gemv_test.rs
@@ -21,9 +21,14 @@ use crate::{
tests::{
assert::assert_eq_float,
helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec, for_each_non_cpu_backend},
- matmul::{QuantBuffers, QuantInput, quant_b_variant},
+ matmul::{QuantBuffers, QuantInput},
},
};
+#[cfg(backend = "metal")]
+use crate::{
+ backends::metal::{Metal, MetalContext},
+ tests::matmul::run_quant_cpu,
+};
struct Input<T: ArrayElement + Float> {
a: Box<[T]>,
@@ -149,6 +154,34 @@ fn gemv_bf16(
test::<bf16>(m, k, n, 0.1);
}
+#[cfg(backend = "metal")]
+#[rstest]
+#[test_attr(uzu_test)]
+#[case::w4_zero_point(4, QuantizationMethod::ScaleZeroPoint)]
+#[case::w8_bias(8, QuantizationMethod::ScaleBias)]
+fn group_major_gemv_bf16(
+ #[case] bits: u32,
+ #[case] method: QuantizationMethod,
+) {
+ let context = MetalContext::new().expect("Metal context");
+ let input = QuantInput::<bf16>::new(1, 256, 72, 32, bits, method, 0).with_group_output();
+ let reference = run_quant_cpu::<bf16>(&input);
+
+ let buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);
+ let actual = run_gemv::<Metal, bf16>(
+ &context,
+ &buffers.x,
+ buffers.matmul_b(&input),
+ None,
+ 1,
+ input.n as usize,
+ input.k as usize,
+ None,
+ );
+
+ assert_eq_float(&reference, &actual, 0.05, &format!("GroupOutput GEMV W{bits} {method:?}"));
+}
+
#[rstest]
#[test_attr(uzu_test)]
#[case::m1(1, 128, 64)]
@@ -227,6 +260,25 @@ fn fp_gather_case<T: ArrayElement + Float + Debug + Display>(
});
}
+fn quant_gather_case(
+ input: QuantInput<bf16>,
+ eps: f32,
+) {
+ let (m, k, vocab, ids_per_row) = (input.m as usize, input.k as usize, input.n as usize, 8);
+ let ids: Vec<u32> = (0..m * ids_per_row).map(|i| ((i * 37 + 11) % vocab) as u32).collect();
+ // K_SPLIT == 1 keeps dense and gathered accumulation order identical.
+ check_gather!(m, vocab, ids, ids_per_row, eps, |B| {
+ let context = <B as Backend>::Context::new().expect("context");
+ let buffers = QuantBuffers::<B, bf16>::allocate(&context, &input);
+ let ids_alloc = alloc_allocation_with_data::<B, u32>(&context, &ids);
+ let b = || buffers.matmul_b(&input);
+ (
+ run_gemv::<B, bf16>(&context, &buffers.x, b(), None, m, vocab, k, None),
+ run_gemv::<B, bf16>(&context, &buffers.x, b(), Some(&ids_alloc), m, ids_per_row, k, None),
+ )
+ });
+}
+
#[uzu_test]
fn gemv_gather() {
// Full precision: one call per dtype (generic over T, so bf16/f32 can't be a runtime loop).
@@ -242,23 +294,14 @@ fn gemv_gather() {
(4, QuantizationMethod::ScaleSymmetric, false),
(8, QuantizationMethod::ScaleZeroPoint, false),
] {
- let (m, k, vocab, ids_per_row, group_size) = (8usize, 128usize, 64usize, 8usize, 32u32);
- let mut input = QuantInput::<bf16>::new(m as u32, k as u32, vocab as u32, group_size, bits, method, 0x5EED);
+ let mut input = QuantInput::new(8, 128, 64, 32, bits, method, 0x5EED);
if signed_codes {
input = input.with_signed_weight_codes();
}
- let ids: Vec<u32> = (0..m * ids_per_row).map(|i| ((i * 37 + 11) % vocab) as u32).collect();
- // K_SPLIT == 1 keeps k in one reduction, so gather and dense share the exact accumulation.
- check_gather!(m, vocab, ids, ids_per_row, 0.05, |B| {
- let context = <B as Backend>::Context::new().expect("context");
- let buffers = QuantBuffers::<B, bf16>::allocate(&context, &input);
- let ids_alloc = alloc_allocation_with_data::<B, u32>(&context, &ids);
- let variant =
- || quant_b_variant(&buffers.w, &buffers.scales, buffers.zp.as_ref(), buffers.bias.as_ref(), &input);
- (
- run_gemv::<B, bf16>(&context, &buffers.x, variant(), None, m, vocab, k, None),
- run_gemv::<B, bf16>(&context, &buffers.x, variant(), Some(&ids_alloc), m, ids_per_row, k, None),
- )
- });
+ quant_gather_case(input, 0.05);
}
+ quant_gather_case(
+ QuantInput::new(8, 96, 66, 32, 4, QuantizationMethod::ScaleZeroPoint, 0x5EED).with_group_output(),
+ 0.5,
+ );
}
diff --git a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
index 77d510c6b..62afbd834 100644
--- a/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
+++ b/crates/uzu-engine/unit/backends/common/kernel/matmul/quant_dispatch_test.rs
@@ -1,10 +1,12 @@
#![cfg(backend = "metal")]
use std::{
- error::Error as StdError,
+ error::Error,
fmt::{Debug, Display},
};
+use QuantParamsLayout::{GroupOutput, OutputGroup};
+use QuantizationMethod::{ScaleBias, ScaleZeroPoint};
use half::bf16;
use num_traits::Float;
use rstest::rstest;
@@ -15,11 +17,11 @@ use crate::{
backends::{
common::{
Backend, Context, Encoder,
- gpu_types::{QuantizationMethod, gemm::GemmDTransform},
+ gpu_types::{QuantizationMethod, QuantizationMode, gemm::GemmDTransform},
kernel::{
Kernels,
activation_transform::ACTIVATION_SCALE_GROUP_SIZE,
- matmul::{MatmulDOps, MatmulError, MatmulKernel},
+ matmul::{MatmulDOps, MatmulError, MatmulKernel, QuantParams, QuantParamsLayout, QuantParamsStrides},
},
},
cpu::Cpu,
@@ -31,7 +33,7 @@ use crate::{
QuantBuffers, QuantInput,
harness::TestDispatch,
quant::{run_quant_cpu, run_quant_metal},
- quant_arguments, quant_b_variant,
+ quant_arguments,
},
},
};
@@ -47,6 +49,25 @@ fn check_tolerance(
diff <= tol
}
+#[uzu_test]
+fn quant_params_layout_table() {
+ let cases = [
+ (QuantParamsLayout::OutputGroup, [5, 3], [3, 1], [5, 2], [4, 1]),
+ (QuantParamsLayout::GroupOutput, [3, 8], [1, 8], [3, 4], [1, 8]),
+ ];
+ for (layout, scale_shape, scale_strides, u4_shape, u4_strides) in cases {
+ let params = QuantParams::new(layout, 5, 3);
+ let strides = |strides: QuantParamsStrides| [strides.output_stride, strides.group_stride];
+
+ assert_eq!(params.scale_shape(), scale_shape);
+ assert_eq!(strides(params.scale_strides()), scale_strides);
+ assert_eq!(params.zero_point_shape(QuantizationMode::U8), scale_shape);
+ assert_eq!(strides(params.zero_point_strides(QuantizationMode::U8)), scale_strides);
+ assert_eq!(params.zero_point_shape(QuantizationMode::U4), u4_shape);
+ assert_eq!(strides(params.zero_point_strides(QuantizationMode::U4)), u4_strides);
+ }
+}
+
fn assert_parity<T: ArrayElement + Float + Debug + Display>(
label: &str,
reference: &[T],
@@ -411,6 +432,20 @@ fn parity_bf16_gemv_quant_rht() {
assert_parity::<bf16>("gemv_quant_rht", &reference, &actual, 0.05, 0.6);
}
+#[uzu_test]
+fn cpu_group_major_quantized_gemm_matches_row_major() {
+ for bits in [4, 8] {
+ for method in
+ [QuantizationMethod::ScaleBias, QuantizationMethod::ScaleZeroPoint, QuantizationMethod::ScaleSymmetric]
+ {
+ let input = QuantInput::<bf16>::new(4, 128, 12, 32, bits, method, 0);
+ let expected = run_quant_cpu(&input);
+ let actual = run_quant_cpu(&input.with_group_output());
+ assert_parity("CPU GroupOutput", &expected, &actual, 0.05, 0.5);
+ }
+ }
+}
+
#[uzu_test]
fn quant_gemm_accumulate_returns_unsupported_dop() {
let context = MetalContext::new().expect("Metal context");
@@ -433,10 +468,10 @@ fn quant_gemm_accumulate_returns_unsupported_dop() {
let result = matmul.encode(args, &mut encoder);
let err = result.expect_err("expected error");
- let matmul: &MatmulError<Metal> = (&err as &dyn StdError)
+ let matmul = err
.source()
- .and_then(|s| s.downcast_ref::<MatmulError<Metal>>())
- .expect("expected MatmulError source");
+ .and_then(|source| source.downcast_ref::<MatmulError<Metal>>())
+ .expect("expected a MatmulError source");
assert!(
matches!(
matmul,
@@ -449,6 +484,59 @@ fn quant_gemm_accumulate_returns_unsupported_dop() {
);
}
+#[rstest]
+#[test_attr(uzu_test)]
+#[case::output_group_single_group_gs64(OutputGroup, 64, 64, 64, 4, ScaleZeroPoint, 64)]
+#[case::output_group_single_group_gs128(OutputGroup, 128, 64, 128, 4, ScaleZeroPoint, 64)]
+#[case::output_group_odd_groups(OutputGroup, 192, 64, 64, 4, ScaleZeroPoint, 64)]
+#[case::group_output_padded_n(GroupOutput, 192, 66, 64, 4, ScaleZeroPoint, 66)]
+#[case::output_group_bias_prefix(OutputGroup, 128, 12, 32, 8, ScaleBias, 4)]
+#[case::group_output_bias_prefix(GroupOutput, 128, 12, 32, 8, ScaleBias, 4)]
+fn quant_gemm_parameter_layout_prefix_matches_cpu(
+ #[case] params_layout: QuantParamsLayout,
+ #[case] k: u32,
+ #[case] n: u32,
+ #[case] group_size: u32,
+ #[case] bits: u32,
+ #[case] method: QuantizationMethod,
+ #[case] logical_n: u32,
+) {
+ let context = MetalContext::new().expect("Metal context");
+ let mut matmul = <<Metal as Backend>::Kernels as Kernels>::MatmulKernel::new(
+ &context,
+ bf16::data_type(),
+ bf16::data_type(),
+ bf16::data_type(),
+ )
+ .expect("MatmulMetalKernel");
+
+ let input = QuantInput::<bf16>::new(64, k, n, group_size, bits, method, 0);
+ let input = if params_layout == GroupOutput {
+ input.with_group_output()
+ } else {
+ input
+ };
+ let reference = run_quant_cpu(&input);
+ for engine in [GemmEngine::Simdgroup, GemmEngine::Mxu] {
+ if engine == GemmEngine::Mxu && !context.supports_mxu {
+ continue;
+ }
+ let mut buffers = QuantBuffers::<Metal, bf16>::allocate(&context, &input);
+ let mut encoder = Encoder::<Metal>::new(&context).expect("encoder");
+ let mut args = quant_arguments(&mut buffers, &input);
+ args.n = logical_n;
+ matmul.gemm.encode_with_engine(args, engine, &mut encoder).unwrap();
+ encoder.end_encoding().submit().wait_until_completed().unwrap();
+ let actual = allocation_to_vec::<Metal, bf16>(&buffers.y);
+ let expected: Vec<_> = reference
+ .chunks_exact(input.n as usize)
+ .flat_map(|row| row[..logical_n as usize].iter().copied())
+ .collect();
+
+ assert_parity("quant params layout", &expected, &actual[..expected.len()], 0.05, 0.5);
+ }
+}
+
#[rstest]
#[test_attr(uzu_test)]
#[case::gs32_4bit_mlx(128, 256, 64, 32, 4, QuantizationMethod::ScaleBias)]
@@ -458,6 +546,8 @@ fn quant_gemm_accumulate_returns_unsupported_dop() {
#[case::gs32_4bit_zp(128, 256, 64, 32, 4, QuantizationMethod::ScaleZeroPoint)]
#[case::gs64_8bit_zp(128, 256, 64, 64, 8, QuantizationMethod::ScaleZeroPoint)]
#[case::gs128_8bit_zp(128, 256, 64, 128, 8, QuantizationMethod::ScaleZeroPoint)]
+#[case::gs64_4bit_zp_g1(128, 64, 64, 64, 4, QuantizationMethod::ScaleZeroPoint)]
+#[case::gs128_4bit_zp_g1(128, 128, 64, 128, 4, QuantizationMethod::ScaleZeroPoint)]
fn mxu_quant_parity_bf16(
#[case] m: u32,
#[case] k: u32,
@@ -507,12 +597,13 @@ fn a8w_mxu_parity_bf16(
return;
}
let (k, n) = (256u32, 128u32);
- let input = QuantInput::<bf16>::new(m, k, n, weight_gs, bits, method, 0).with_prepared_a(
- ACTIVATION_SCALE_GROUP_SIZE,
- (method != QuantizationMethod::ScaleSymmetric).then_some(weight_gs),
- );
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
- let reference = run_quant_cpu::<bf16>(&input);
+ let (input, reference_input) = QuantInput::<bf16>::new(m, k, n, weight_gs, bits, method, 0)
+ .with_prepared_a_and_reference(
+ ACTIVATION_SCALE_GROUP_SIZE,
+ (method != QuantizationMethod::ScaleSymmetric).then_some(weight_gs),
+ );
+ let actual = run_quant_metal(&context, &input.with_group_output(), Some(GemmEngine::Mxu));
+ let reference = run_quant_cpu::<bf16>(&reference_input);
assert_parity::<bf16>(
&format!("A8W{bits} MXU m={m} weight_gs={weight_gs} method={method:?}"),
&reference,
@@ -533,21 +624,21 @@ fn a8w_independent_activation_group_parity_bf16(#[case] m: u32) {
return;
}
- for (activation_group_size, weight_group_size) in
- [(32u32, 32u32), (32, 64), (64, 64), (64, 128), (128, 32), (128, 64), (128, 128)]
- {
+ for (activation_group_size, weight_group_size) in [(32u32, 32u32), (64, 64), (128, 32), (128, 64), (128, 128)] {
for (bits, method) in [
(4, QuantizationMethod::ScaleSymmetric),
(8, QuantizationMethod::ScaleSymmetric),
(8, QuantizationMethod::ScaleBias),
(4, QuantizationMethod::ScaleZeroPoint),
] {
- let input = QuantInput::<bf16>::new(m, 256, 72, weight_group_size, bits, method, 0).with_prepared_a(
- activation_group_size,
- (method != QuantizationMethod::ScaleSymmetric).then_some(activation_group_size.min(weight_group_size)),
- );
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
- let reference = run_quant_cpu::<bf16>(&input);
+ let (input, reference_input) = QuantInput::<bf16>::new(m, 256, 12, weight_group_size, bits, method, 0)
+ .with_prepared_a_and_reference(
+ activation_group_size,
+ (method != QuantizationMethod::ScaleSymmetric)
+ .then_some(activation_group_size.min(weight_group_size)),
+ );
+ let actual = run_quant_metal(&context, &input.with_group_output(), Some(GemmEngine::Mxu));
+ let reference = run_quant_cpu::<bf16>(&reference_input);
assert_parity::<bf16>(
&format!("A8W{bits} act{activation_group_size} weight{weight_group_size} m={m} method={method:?}"),
&reference,
@@ -564,30 +655,16 @@ fn a8w_independent_activation_group_parity_bf16(#[case] m: u32) {
#[case::m1(1)]
#[case::m16(16)]
#[case::m33(33)]
-fn a8w4_zero_point_tail_parity(#[case] m: u32) {
+fn a8w8_zero_point_tail_parity(#[case] m: u32) {
let context = MetalContext::new().expect("Metal context");
if !context.supports_mxu {
return;
}
- let input = QuantInput::<bf16>::new(m, 256, 72, 32, 4, QuantizationMethod::ScaleZeroPoint, 0)
+ let input = QuantInput::<bf16>::new(m, 256, 72, 32, 8, QuantizationMethod::ScaleZeroPoint, 0)
.with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE, Some(32));
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
let reference = run_quant_cpu::<bf16>(&input);
- assert_parity::<bf16>(&format!("A8W4 ZP N-tail m={m}"), &reference, &actual, 0.08, 0.8);
-}
-
-#[uzu_test]
-fn a8w4_zero_point_tail_signed_codes_parity() {
- let context = MetalContext::new().expect("Metal context");
- if !context.supports_mxu {
- return;
- }
- let input = QuantInput::<bf16>::new(33, 256, 72, 32, 4, QuantizationMethod::ScaleZeroPoint, 0)
- .with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE, Some(32))
- .with_signed_weight_codes();
- let actual = run_quant_metal::<bf16>(&context, &input, Some(GemmEngine::Mxu));
- let reference = run_quant_cpu::<bf16>(&input);
- assert_parity::<bf16>("A8W4 ZP signed-code N-tail", &reference, &actual, 0.08, 0.8);
+ let actual = run_quant_metal(&context, &input.with_group_output(), Some(GemmEngine::Mxu));
+ assert_parity::<bf16>(&format!("A8W8 ZP N-tail m={m}"), &reference, &actual, 0.08, 0.8);
}
#[rstest]
@@ -643,11 +720,12 @@ fn a8w_mxu_output_bias_parity_bf16(
if with_output_hadamard {
64u32
} else {
- 70u32
+ 72u32
},
);
- let input = QuantInput::<bf16>::new(m, k, n, 32, bits, QuantizationMethod::ScaleSymmetric, 0)
- .with_prepared_a(ACTIVATION_SCALE_GROUP_SIZE, None);
+ let (input, reference_input) = QuantInput::<bf16>::new(m, k, n, 32, bits, QuantizationMethod::ScaleSymmetric, 0)
+ .with_group_output()
+ .with_prepared_a_and_reference(ACTIVATION_SCALE_GROUP_SIZE, None);
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)
@@ -662,7 +740,7 @@ fn a8w_mxu_output_bias_parity_bf16(
});
let cpu_context = <Cpu as Backend>::Context::new().expect("CPU context");
- let mut cpu_buffers = QuantBuffers::<Cpu, bf16>::allocate(&cpu_context, &input);
+ let mut cpu_buffers = QuantBuffers::<Cpu, bf16>::allocate(&cpu_context, &reference_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));
@@ -674,7 +752,7 @@ fn a8w_mxu_output_bias_parity_bf16(
)
.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);
+ let mut cpu_arguments = quant_arguments(&mut cpu_buffers, &reference_input);
cpu_arguments.d_transform = MatmulDOps {
rht_factors: cpu_output_hadamard_factors.as_ref(),
..MatmulDOps::none()
@@ -733,7 +811,7 @@ fn run_widened_f32<B: Backend>(
let mut matmul =
<<B as Backend>::Kernels as Kernels>::MatmulKernel::new(context, DataType::BF16, DataType::BF16, DataType::F32)
.expect("MatmulKernel widened");
- let b = quant_b_variant(&buffers.w, &buffers.scales, buffers.zp.as_ref(), buffers.bias.as_ref(), input);
+ let b = buffers.matmul_b(input);
let mut encoder = Encoder::<B>::new(context).expect("encoder");
matmul
.encode(
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rs
index 6ab2041a4..759368e1f 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemm/selection_test.rs
@@ -1,9 +1,9 @@
use metal::MTLGPUFamily;
use uzu_engine_macros::uzu_test;
-use super::{super::specialization::GemmSpecialization, *};
+use super::*;
use crate::backends::{
- common::gpu_types::gemm::{GemmAPrologueKind, GemmAlignment, GemmDTransform},
+ common::{gpu_types::gemm::GemmDTransform, kernel::matmul::QuantParamsLayout},
metal::kernel::matmul::MatmulMetalKernel,
};
@@ -24,6 +24,7 @@ fn shape(
signed_codes: false,
a_full_precision: true,
gathered: false,
+ params_layout: Some(QuantParamsLayout::OutputGroup),
d_transform: GemmDTransform::empty(),
}
}
@@ -43,14 +44,6 @@ fn problem(
GemmProblem::new(shape, DataType::BF16, output_data_type, true, MTLGPUFamily::Apple7)
}
-fn plan(split_k: u32) -> GemmPlan {
- GemmPlan {
- engine: GemmEngine::Mxu,
- tiling: GemmTiling::Tile64x64x256_Simdgroups2x2,
- split_k,
- }
-}
-
#[uzu_test]
fn policy_boundaries_are_preserved() {
use GemmTiling::*;
@@ -167,30 +160,6 @@ fn forced_engine_errors_are_preserved() {
);
}
-#[uzu_test]
-fn specialization_flags_are_preserved() {
- let specialization = |shape, split_k| {
- GemmSpecialization::from_plan(
- plan(split_k),
- shape,
- DataType::BF16,
- GemmDTransform::empty(),
- GemmAlignment::new(true, true, true),
- GemmAPrologueKind::FullPrecision,
- None,
- )
- .unwrap()
- };
- for (split_k, hoist) in [(1, false), (2, true)] {
- let spec = specialization(shape(64, 4096, 4096), split_k);
- assert!(spec.stage_weight_scales);
- assert_eq!(spec.hoist_operand_addressing, hoist);
- }
- let spec = specialization(quant(shape(64, 4096, 4096)), 1);
- assert!(spec.stage_weight_scales);
- assert!(spec.hoist_operand_addressing);
-}
-
#[uzu_test]
fn gemv_gemm_route_boundaries_are_preserved() {
for (shape, data_type, prefer_gemm) in [
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs
index 48ac8e849..9eebb6761 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/gemv/policy_test.rs
@@ -5,7 +5,7 @@ use super::*;
use crate::{
backends::common::{
gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},
- kernel::matmul::MatmulShape,
+ kernel::matmul::{MatmulShape, QuantParamsLayout},
},
data_type::DataType,
};
@@ -180,6 +180,7 @@ fn quant_shape(
signed_codes: false,
a_full_precision: true,
gathered: false,
+ params_layout: Some(QuantParamsLayout::OutputGroup),
d_transform,
}
}
@@ -198,6 +199,7 @@ fn block_unaligned_quantized_k_stays_on_gemv() {
signed_codes: false,
a_full_precision: true,
gathered: false,
+ params_layout: Some(QuantParamsLayout::OutputGroup),
d_transform: GemmDTransform::empty(),
};
assert!(
@@ -229,3 +231,20 @@ fn specialization_preserves_quantized_route_and_accumulate_tail() {
assert!(clean.output_row_tile() > DEFAULT_RESULTS_PER_SIMDGROUP);
assert_eq!(select(8192 + clean.output_row_tile() / 2, GemmDTransform::ACCUMULATE), None);
}
+
+#[uzu_test]
+fn gathered_group_major_is_a_gemv_route() {
+ let mut shape = quant_shape(1, 8192, GemmDTransform::empty());
+ shape.params_layout = Some(QuantParamsLayout::GroupOutput);
+ shape.gathered = true;
+ assert!(
+ super::super::kernel::GemvSpecialization::select_tile(
+ &shape,
+ DataType::BF16,
+ DataType::BF16,
+ DataType::BF16,
+ qtile(8, 4),
+ )
+ .is_some()
+ );
+}
diff --git a/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rs b/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rs
index b4944350e..8d77a9801 100644
--- a/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rs
+++ b/crates/uzu-engine/unit/backends/metal/kernel/matmul/qmv/routes_test.rs
@@ -9,7 +9,7 @@ use crate::{
backends::{
common::{
gpu_types::gemm::{GemmBPrologueKind, GemmDTransform},
- kernel::matmul::MatmulShape,
+ kernel::matmul::{MatmulShape, QuantParamsLayout},
},
metal::kernel::matmul::{MatmulDispatch, MatmulMetalKernel, gemv::GemvSpecialization},
},
@@ -62,6 +62,7 @@ fn problem(
signed_codes: false,
a_full_precision: true,
gathered: false,
+ params_layout: Some(QuantParamsLayout::OutputGroup),
d_transform: GemmDTransform::empty(),
}
}
diff --git a/crates/uzu-engine/unit/common/matmul/mod.rs b/crates/uzu-engine/unit/common/matmul/mod.rs
index 34de4a92d..7d844fd12 100644
--- a/crates/uzu-engine/unit/common/matmul/mod.rs
+++ b/crates/uzu-engine/unit/common/matmul/mod.rs
@@ -5,7 +5,7 @@ pub mod shape;
pub use bench::{iter_encode_loop, iter_encode_loop_named};
pub use harness::{Case, cpu_reference, deterministic_input};
-pub use quant::{QuantBuffers, QuantInput, quant_arguments, quant_b_variant, run_quant_cpu};
+pub use quant::{QuantBuffers, QuantInput, quant_arguments, run_quant_cpu, transpose_metadata};
pub use shape::{
Shape, all_correctness_shapes, bench_fp_gemm_shapes, bench_quant_gemm_shapes, bench_quant_gemv_shapes,
qwen3_layer_shapes,
diff --git a/crates/uzu-engine/unit/common/matmul/quant.rs b/crates/uzu-engine/unit/common/matmul/quant.rs
index 97ee49263..0fbbe3774 100644
--- a/crates/uzu-engine/unit/common/matmul/quant.rs
+++ b/crates/uzu-engine/unit/common/matmul/quant.rs
@@ -1,4 +1,4 @@
-use std::mem::size_of_val;
+use std::mem::{size_of, size_of_val};
use num_traits::Float;
use rand::{RngExt, SeedableRng, rngs::SmallRng};
@@ -14,22 +14,28 @@ use crate::{
Allocation, Backend, Context, Encoder,
gpu_types::{QuantizationMethod, QuantizationMode},
kernel::{
- ActivationTransform, Kernels,
- matmul::{MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel},
+ ActivationQuantization, ActivationTransform, Kernels,
+ matmul::{
+ Int8CodeLayout, MatmulA, MatmulArguments, MatmulB, MatmulDOps, MatmulKernel, QuantParams,
+ QuantParamsLayout, QuantizedB, QuantizedCorrection,
+ },
},
},
cpu::Cpu,
},
+ data_type::DataType,
tests::helpers::{alloc_allocation, alloc_allocation_with_data, allocation_to_vec},
};
+#[derive(Clone)]
pub struct PreparedInt8A {
pub values: Vec<i8>,
pub scales: Vec<f32>,
pub group_sums: Vec<i32>,
- pub activation_scale_group_size: u32,
+ pub quantization: ActivationQuantization,
}
+#[derive(Clone)]
pub struct QuantInput<T: ArrayElement + Float> {
pub w_packed: Vec<u32>,
pub scales: Vec<T>,
@@ -42,6 +48,7 @@ pub struct QuantInput<T: ArrayElement + Float> {
pub group_size: u32,
pub quant_method: QuantizationMethod,
pub mode: QuantizationMode,
+ pub params_layout: QuantParamsLayout,
pub signed_codes: bool,
pub prepared_a: Option<PreparedInt8A>,
}
@@ -54,6 +61,69 @@ fn mode_for_bits(bits: u32) -> QuantizationMode {
}
}
+fn pad<T: ArrayElement>(
+ values: &[T],
+ minimum_len: usize,
+) -> Vec<T> {
+ let mut padded = values.to_vec();
+ padded.resize(values.len().max(minimum_len), T::zeroed());
+ padded
+}
+
+pub fn transpose_metadata(
+ plane: &mut [u8],
+ columns: u32,
+ groups: u32,
+ bits: u32,
+) {
+ let data_type = match bits {
+ 4 => DataType::U4,
+ 8 => DataType::U8,
+ 16 => DataType::BF16,
+ 32 => DataType::F32,
+ _ => unreachable!("unsupported metadata width: {bits}"),
+ };
+ let source_params = QuantParams::new(QuantParamsLayout::OutputGroup, columns, groups);
+ let destination_params = QuantParams::new(QuantParamsLayout::GroupOutput, columns, groups);
+ let plane_layout = |params: QuantParams| match data_type {
+ DataType::U4 => {
+ (params.zero_point_shape(QuantizationMode::U4), params.zero_point_strides(QuantizationMode::U4))
+ },
+ DataType::U8 => {
+ (params.zero_point_shape(QuantizationMode::U8), params.zero_point_strides(QuantizationMode::U8))
+ },
+ _ => (params.scale_shape(), params.scale_strides()),
+ };
+ let (source_shape, source_strides) = plane_layout(source_params);
+ let (_, destination_strides) = plane_layout(destination_params);
+ let source_len = source_shape.into_iter().product::<u32>() as usize
+ * if data_type == DataType::U4 {
+ DataType::U8
+ } else {
+ data_type
+ }
+ .size_in_bytes();
+ let source = plane[..source_len].to_vec();
+ plane.fill(0);
+ for output in 0..columns {
+ for group in 0..groups {
+ let source_index = (output * source_strides.output_stride + group * source_strides.group_stride) as usize;
+ let destination_index =
+ (output * destination_strides.output_stride + group * destination_strides.group_stride) as usize;
+ if bits == 4 {
+ let value = (source[source_index / 2] >> (source_index % 2 * 4)) & 0x0F;
+ plane[destination_index / 2] |= value << (destination_index % 2 * 4);
+ } else {
+ let width = bits as usize / u8::BITS as usize;
+ let source_offset = source_index * width;
+ let destination_offset = destination_index * width;
+ plane[destination_offset..destination_offset + width]
+ .copy_from_slice(&source[source_offset..source_offset + width]);
+ }
+ }
+ }
+}
+
impl<T: ArrayElement + Float> QuantInput<T> {
pub fn new(
m: u32,
@@ -105,6 +175,7 @@ impl<T: ArrayElement + Float> QuantInput<T> {
group_size,
quant_method,
mode: mode_for_bits(bits),
+ params_layout: QuantParamsLayout::OutputGroup,
signed_codes: false,
prepared_a: None,
}
@@ -115,15 +186,47 @@ impl<T: ArrayElement + Float> QuantInput<T> {
self
}
+ pub fn with_group_output(mut self) -> Self {
+ self.params_layout = QuantParamsLayout::GroupOutput;
+ self
+ }
+
pub fn with_prepared_a(
+ self,
+ activation_scale_group_size: u32,
+ sum_group_size: Option<u32>,
+ ) -> Self {
+ let code_layout = Int8CodeLayout::for_right_bits(DataType::from(self.mode).size_in_bits() as u32)
+ .expect("W4/W8 quantization");
+ self.with_prepared_a_layout(activation_scale_group_size, sum_group_size, code_layout)
+ }
+
+ pub fn with_prepared_a_and_reference(
+ self,
+ activation_scale_group_size: u32,
+ sum_group_size: Option<u32>,
+ ) -> (Self, Self) {
+ let code_layout = Int8CodeLayout::for_right_bits(DataType::from(self.mode).size_in_bits() as u32)
+ .expect("W4/W8 quantization");
+ let reference = self.clone().with_prepared_a_layout(
+ activation_scale_group_size,
+ sum_group_size,
+ Int8CodeLayout::Sequential,
+ );
+ let actual = self.with_prepared_a_layout(activation_scale_group_size, sum_group_size, code_layout);
+ (actual, reference)
+ }
+
+ fn with_prepared_a_layout(
mut self,
- activation_group_size: u32,
+ activation_scale_group_size: u32,
sum_group_size: Option<u32>,
+ code_layout: Int8CodeLayout,
) -> Self {
- self.signed_codes = true;
+ self.signed_codes = self.mode != QuantizationMode::U4;
let rows = self.m;
let columns = self.k;
- assert!(columns.is_multiple_of(activation_group_size));
+ assert!(columns.is_multiple_of(activation_scale_group_size));
if let Some(group_size) = sum_group_size {
assert!(columns.is_multiple_of(group_size));
}
@@ -132,12 +235,18 @@ impl<T: ArrayElement + Float> QuantInput<T> {
let factors = alloc_allocation_with_data::<Cpu, i32>(&context, &vec![1; columns as usize]);
let element_count = rows * columns;
let mut values = alloc_allocation::<Cpu, i8>(&context, element_count as usize);
- let mut scales = alloc_allocation::<Cpu, f32>(&context, (element_count / activation_group_size) as usize);
+ let mut scales = alloc_allocation::<Cpu, f32>(&context, (element_count / activation_scale_group_size) as usize);
let mut group_sums = sum_group_size
.map(|group_size| alloc_allocation::<Cpu, i32>(&context, (element_count / group_size) as usize));
- let transform =
- ActivationTransform::<Cpu>::quantize(&context, T::data_type(), activation_group_size, sum_group_size)
- .expect("CPU activation quantization transform");
+ let quantization = ActivationQuantization::new(
+ activation_scale_group_size,
+ sum_group_size.unwrap_or(activation_scale_group_size),
+ sum_group_size.is_some(),
+ code_layout,
+ )
+ .expect("supported activation quantization");
+ let transform = ActivationTransform::<Cpu>::quantize(&context, T::data_type(), quantization)
+ .expect("CPU activation quantization transform");
let mut encoder = Encoder::<Cpu>::new(&context).expect("CPU encoder");
transform.encode_quantize(
&input,
@@ -155,7 +264,7 @@ impl<T: ArrayElement + Float> QuantInput<T> {
values: allocation_to_vec(&values),
scales: allocation_to_vec(&scales),
group_sums: group_sums.map_or_else(Vec::new, |sums| allocation_to_vec(&sums)),
- activation_scale_group_size: activation_group_size,
+ quantization,
});
self
}
@@ -196,11 +305,22 @@ impl<B: Backend, T: ArrayElement + Float> QuantBuffers<B, T> {
context: &B::Context,
input: &QuantInput<T>,
) -> Self {
- Self {
+ let groups = input.k.div_ceil(input.group_size);
+ let params_layout = input.params_layout;
+ let params = QuantParams::new(params_layout, input.n, groups);
+ let metadata_elements = params.scale_shape().into_iter().product::<u32>() as usize;
+ let zero_point_bytes = params.zero_point_shape(input.mode).into_iter().product::<u32>() as usize;
+ let mut buffers = Self {
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)),
+ scales: alloc_allocation_with_data::<B, T>(context, &pad(&input.scales, metadata_elements)),
+ zp: input
+ .zero_points
+ .as_ref()
+ .map(|zero_points| alloc_allocation_with_data::<B, u8>(context, &pad(zero_points, zero_point_bytes))),
+ bias: input
+ .biases
+ .as_ref()
+ .map(|biases| alloc_allocation_with_data::<B, T>(context, &pad(biases, metadata_elements))),
x: alloc_allocation_with_data::<B, T>(context, &input.x),
prepared_a: input
.prepared_a
@@ -217,43 +337,74 @@ impl<B: Backend, T: ArrayElement + Float> QuantBuffers<B, T> {
.map(|prepared| alloc_allocation_with_data::<B, i32>(context, &prepared.group_sums)),
y: alloc_allocation::<B, T>(context, (input.m as usize) * (input.n as usize)),
_t: std::marker::PhantomData,
+ };
+ if params_layout == QuantParamsLayout::GroupOutput {
+ buffers.transpose_quant_params(input);
+ }
+ buffers
+ }
+
+ pub fn matmul_b<'a>(
+ &'a self,
+ input: &QuantInput<T>,
+ ) -> MatmulB<'a, B> {
+ quant_b_variant(&self.w, &self.scales, self.zp.as_ref(), self.bias.as_ref(), input.params_layout, input)
+ }
+
+ fn transpose_quant_params(
+ &mut self,
+ input: &QuantInput<T>,
+ ) {
+ let columns = input.n;
+ let groups = input.k.div_ceil(input.group_size);
+ let value_bits = size_of::<T>() as u32 * u8::BITS;
+ transpose_metadata(self.scales.as_slice_mut(), columns, groups, value_bits);
+ match input.quant_method {
+ QuantizationMethod::ScaleBias => {
+ transpose_metadata(
+ self.bias.as_mut().expect("bias buffer").as_slice_mut(),
+ columns,
+ groups,
+ value_bits,
+ );
+ },
+ QuantizationMethod::ScaleZeroPoint => {
+ let correction_bits = DataType::from(input.mode).size_in_bits() as u32;
+ transpose_metadata(
+ self.zp.as_mut().expect("zp buffer").as_slice_mut(),
+ columns,
+ groups,
+ correction_bits,
+ );
+ },
+ QuantizationMethod::ScaleSymmetric => {},
}
}
}
-pub fn quant_b_variant<'a, B: Backend, T: ArrayElement + Float>(
+fn quant_b_variant<'a, B: Backend, T: ArrayElement + Float>(
w: &'a Allocation<B>,
scales: &'a Allocation<B>,
zero_points: Option<&'a Allocation<B>>,
biases: Option<&'a Allocation<B>>,
+ params_layout: QuantParamsLayout,
input: &QuantInput<T>,
) -> MatmulB<'a, B> {
- let signed_codes = input.signed_codes;
- match input.quant_method {
- QuantizationMethod::ScaleBias => MatmulB::ScaleBiasDequant {
- b: w,
- scales,
- biases: biases.expect("bias buffer"),
- mode: input.mode,
- group_size: input.group_size,
- signed_codes,
- },
- QuantizationMethod::ScaleZeroPoint => MatmulB::ScaleZeroPointDequant {
- b: w,
- scales,
- zero_points: zero_points.expect("zp buffer"),
- mode: input.mode,
- group_size: input.group_size,
- signed_codes,
- },
- QuantizationMethod::ScaleSymmetric => MatmulB::ScaleSymmetricDequant {
- b: w,
- scales,
- mode: input.mode,
- group_size: input.group_size,
- signed_codes,
- },
- }
+ let params = QuantParams::new(params_layout, input.n, input.k.div_ceil(input.group_size));
+ let correction = match input.quant_method {
+ QuantizationMethod::ScaleBias => QuantizedCorrection::Biases(biases.expect("bias buffer")),
+ QuantizationMethod::ScaleZeroPoint => QuantizedCorrection::ZeroPoints(zero_points.expect("zp buffer")),
+ QuantizationMethod::ScaleSymmetric => QuantizedCorrection::Symmetric,
+ };
+ MatmulB::Quantized(QuantizedB {
+ codes: w,
+ scales,
+ correction,
+ params,
+ mode: input.mode,
+ group_size: input.group_size,
+ signed_codes: input.signed_codes,
+ })
}
pub fn quant_arguments<'a, B: Backend, T: ArrayElement + Float>(
@@ -272,15 +423,16 @@ pub fn quant_arguments<'a, B: Backend, T: ArrayElement + Float>(
y,
..
} = buffers;
- let b = quant_b_variant(w, scales, zp.as_ref(), bias.as_ref(), input);
+ let b = quant_b_variant(&*w, &*scales, zp.as_ref(), bias.as_ref(), input.params_layout, input);
let a = match &input.prepared_a {
- Some(_) => MatmulA::Int8Symmetric {
+ Some(prepared) => MatmulA::Int8Symmetric {
values: prepared_a.as_ref().expect("prepared activation buffer"),
scales: prepared_a_scales.as_ref().expect("prepared activation scales"),
// Symmetric weights carry no correction term, so the GEMM never reads these.
group_sums: (input.quant_method != QuantizationMethod::ScaleSymmetric)
.then(|| prepared_a_group_sums.as_ref().expect("prepared activation row sums")),
- group_size: input.prepared_a.as_ref().expect("prepared activation metadata").activation_scale_group_size,
+ scale_group_size: prepared.quantization.scale_group_size(),
+ code_layout: prepared.quantization.code_layout(),
},
None => MatmulA::FullPrecision {
values: x,